Forked from
ima-jin/imajin-app-template. ReadAGENTS.mdfirst — it defines the boundary this app must not cross.
Platform: Imajin (sovereign-tech kernel) · Reference app: ima-jin/imajin-scorecard
This repository is the app — a real, arms-length third-party application that composes the Imajin platform
only through its public app surface (requireAppAuth + the documented kernel API). It holds no workspace:*
deps, no monorepo internals, no DB access, no in-process bus — it talks to Imajin as an external client. Published
@ima-jin/* SDK packages (from npmjs.org, no auth needed) are fine to depend on; they're the same versioned
artifact every app — first-party or third-party — consumes.
This app holds nothing authoritative. The signed records are the user's own, on their per-DID path. The kernel is
the authoritative index/projection of those records — not their owner. The user can walk with their records and
everything still verifies. (See AGENTS.md §3.)
| Header | Meaning |
|---|---|
X-App-DID |
this app's DID (from registration) |
X-App-Authorization |
the attestation ID from the user's consent flow |
The kernel verifies both and returns { appDid, userDid, scopes } — that triple is the app's entire authority.
- Create your app repo WITH template history — clone + rename, not GitHub's "Use this template" button (see Creating a new app below).
- Register this app with the kernel — see
docs/REGISTRATION.md. You'll get back this app'sappDidand registryid. - Set env:
cp .env.example .env.local, then fill inIMAJIN_APP_DID,NEXT_PUBLIC_IMAJIN_APP_ID,APP_DB_SCHEMA, andIMAJIN_KERNEL_URL. This app refuses to start withoutIMAJIN_APP_DIDset, or if a rawIMAJIN_APP_PRIVATE_KEYis present (seeinstrumentation.ts) — it fetches its own signing key at boot via@ima-jin/auth-client'sloadAppSigningKey()instead. The only claim path is approve on/jin→ open<this app>/claim→ paste the code → done — seedocs/REGISTRATION.md. - Prepare vault credentials through the operator's
/jinApp surface: syncimajin.app.json, then App secrets set/rotate forDATABASE_URLwith owner countersign. The value is operator-supplied, never put in env or a shell. Session signing remains kernel-generated.createVaultBootfetches both credentials through the bootstrap keystore-authenticated encrypted channel before dynamically importing the server initializer; only then is the database client created. Missing required credentials fail closed with no env fallback. Build and unclaimed mode never create a DB client. - Migrate this app's own Postgres schema through the vault (see
docs/MIGRATIONS.md; on a database that already holds themarketschema, i.e. prod/dev,scripts/deploy.shruns the migration baseline first — seedocs/DEPLOY.md):pnpm install node --env-file=.env.local scripts/migrate-baseline.mjs pnpm db:migrate
- Run it:
pnpm dev
/api/healthand/api/specshould respond immediately;/api/mereturns your DID once you sign in through the header's "Sign in with Imajin" link.
The app's identity is minted by the kernel, never by hand: no keys are generated, copied, or logged in this repo. Dev and prod are separate registered apps — each has its own DID, claim code and keystore.
- Operator mints a claim code on the kernel's
/jin(https://dev-jin.imajin.ai/jinfor dev,https://jin.imajin.ai/jinfor prod): approve the app'sapps.provisioncard. The kernel returns the app'sdid:imajin:…and a one-time claim code. - Redeem it only in the browser: configure
IMAJIN_APP_DIDand start the app unclaimed. Until it is claimed, every route serves a "not claimed yet" page except/claim,/api/claimand/api/health. Open<this app>/claim(/market/claimbehind the kernel host's Caddy), paste the code, and submit. The app is live immediately — no env edit or restart. The exchange persists a0600bootstrap keystore atIMAJIN_APP_KEYSTORE;/claimand/api/claimthen return 404. - The kernel issues and seals the session signing recipe declared in
imajin.app.jsonduring provision/claim. Boot loads it withcreateVaultBootinto memory before importing the server or enabling sessions. For an existing app, select Sync manifest secrets on/jinand countersign. Rotate there, then restart through the operator tool to pick up the new generation (existing sessions are invalidated); no secret env or file edit. - Later boots use the keystore alone. A lost keystore needs a re-approval with
reissueClaim: true.
The claim code and keystore contents are never logged or placed in env.
Full detail: docs/REGISTRATION.md and docs/DEPLOY.md.
Rollout is not authorized by #27. Runtime, baseline and migration scripts load credentials from the vault into memory; the same non-secret env file passes preflight and configures every step. No deploy or environment change is part of this adoption. Keep imajin-ai#2260 separate.
Command per environment (~/prod/market, ~/dev/market), after browser claim and vault approvals:
scripts/deploy.sh dev # or: scripts/deploy.sh prod
scripts/deploy.sh prod --ref <tag> # a specific ref; also the rollback
scripts/deploy.sh prod --dry-run # print the plan, execute nothingIt validates the env file, installs, builds, runs the idempotent migration baseline (adopts the existing
market schema, refuses on mismatch, never drops anything) then the vault-backed programmatic
scripts/migrate.mjs, restarts the pm2 entry
(prod-market on 7104 / dev-market on 3104) and health-checks /market/api/health. The app is served under the
/market base path behind the kernel host's Caddy. See docs/DEPLOY.md (runbook, Caddy route,
pm2, baseline, cutover checklist) and docs/ENVIRONMENTS.md (every env var; .env.example,
.env.dev.example, .env.prod.example).
Ported from the kernel's apps/market (ima-jin/imajin-ai#1989, step 2 of 5):
- API (
app/api/**, documented inapi-spec/openapi.yaml, served at/api/spec): listings (browse, create, update, soft-delete), checkout via the pay service, the seller's own listings, seller settings and public profile widgets, handle/DID resolution, and the pay-service payment webhook. - Pages (
app/**/page.tsx): browse, listing detail, create/edit, seller page, settings, checkout success. - Auth: every authenticated route goes through
authenticate()(src/lib/auth/authenticate.ts): a scopedAuthorization: Bearer <app-token>for the registry slugmarket, or the shared session cookie as a fallback. Seedocs/REGISTRATION.md§6. - Kernel callbacks: the kernel signs;
verifyKernelWebhookverifies raw bytes, the app DID, freshness and nonce before processing. No shared callback credential is needed. Seedocs/DEPLOY.md. - Domain events:
listing.created,listing.updated, andlisting.purchasedare published through the kernel'sPOST /api/eventsusing market's own app-service token. See Domain events. - Known kernel gaps (filed as
gap(kernel)issues, all refs ima-jin/imajin-ai#1989):@ima-jin/media(#2637), acting-as-scope (#2639), identity tier (#2640),@ima-jin/onboard(#2645).
src/lib/kernel/events.ts publishes to {IMAJIN_KERNEL_URL}/api/events. The existing
IMAJIN_KERNEL_URL must be the kernel base URL, without an /auth, /pay, or /market suffix.
No new environment variable or shared service secret is needed. IMAJIN_APP_DID and the app's claimed
signing identity must be available (see Identity).
The published @ima-jin/auth-client helper proves possession of that in-memory key at
POST /auth/api/apps/token/service. Its default imajin:apps audience is accepted by the events endpoint;
the cached token is refreshed at 80% of its TTL.
The body is { type, subject, payload, correlationId? }. The kernel sets the issuer/origin and scope itself.
Creation and updates emit one canonical event each; listing.purchased is emitted after a verified successful
payment callback, not merely after checkout creation. App-origin events can notify and audit only — never
move money or issue attestations. Market's existing checkout/settlement flow remains independent.
Publishing is best-effort and does not change the listing, checkout, or webhook response. Missing configuration
is logged at error level naming the setting; unclaimed identity and network failures are also error-logged.
Mint and publish requests each have a five-second timeout. Refusals (including 401, 403 for unapproved types,
and 429 with Retry-After) are logged without token, key, payload, or response-body contents. There is no automatic
replay/retry or delivery guarantee; after 401 the next event mints a fresh token.
Paid fulfillment refusals are warning-logged with session, payment, listing and reason identifiers only, never secrets.
Operator step after deployment (prod and dev separately): review the emittableEvents declarations from
imajin.app.json in the /jin provision/declarations preview and approve listing.created, listing.updated,
and listing.purchased for that environment's market app. Declaration alone grants nothing. Until approval,
the kernel returns 403. Then trigger a listing action and confirm market's app DID/event in the kernel audit
log and the applicable notify reactor. This code change does not deploy or approve anything.
Do not use GitHub's "Use this template" button. It creates a repo with a brand-new, unrelated root commit. Such an app can never merge template changes cleanly — its first sync is an
--allow-unrelated-historiesmerge with add/add conflicts on nearly every file (that's why/claimhad to be hand-ported intolinksanddykil). Instead, keep the template's history as the app's ancestry:
# 1. Clone the template under your app's name; the template becomes the `template` remote.
git clone https://github.com/ima-jin/imajin-app-template.git <app-name>
cd <app-name>
git remote rename origin template
# 2. Create the (empty) app repo on GitHub and make it `origin`. No README/license/.gitignore — it must be empty.
gh repo create ima-jin/<app-name> --private --source=. --remote=origin --push
# 3. Rename the template identity (one commit), then push.
# package.json "name", api-spec/openapi.yaml (title + example), app/api/health/route.ts (+ its test),
# app/layout.tsx description, sonar-project.properties (projectKey), the README title, and AGENTS.md §8.
git checkout -b chore/rename-app
# ...edit the files above...
git commit -am "chore: rename template → <app-name>" && git push -u origin chore/rename-appBecause the app was cloned from the template, git merge-base HEAD template/main finds a common ancestor from
the very first commit — there is nothing to "join".
scripts/sync-from-template.sh --check # list pending template commits; no merge, no branch
scripts/sync-from-template.sh # merge template/main onto chore/sync-from-template → open a PRThe script adds the template remote if missing, fetches template/main, and checks for a common ancestor:
- Histories joined → prints
histories already joined; incremental mergeand runs a normalgit merge template/main --no-editon achore/sync-from-templatebranch (never straight tomain). - Not joined (app created with "Use this template") → exits with status 2 and prints the one-time join. The
join is history-only — it changes no files:
Use the template commit the app was generated from (the template's state when the app repo was created), not
git checkout -b chore/join-template-history git merge -s ours --allow-unrelated-histories <template-sha> -m "chore: join template history (one-time)"
template/main:-s oursmarks everything up to that commit as already merged, so joining at the tip would silently skip every template change since the app was created. After the join PR merges, the script reportshistories already joinedand pulls later template changes as an ordinary merge.
On a conflict (almost always AGENTS.md §8, or the renamed identity files from step 3), keep your version of what is yours and take the template's side of the shared contract.
Published @ima-jin/* packages (e.g. @ima-jin/auth-client, @ima-jin/config, @ima-jin/ui) are served from
npmjs.org, the default registry — no .npmrc scoping and no auth token needed to install them:
pnpm add @ima-jin/auth-clientAGENTS.md ← boundary + scope for coding agents (read first)
README.md ← this file
docs/
ARCHITECTURE.md ← design notes
REGISTRATION.md ← how to register this app with the kernel
MIGRATIONS.md ← this app's schema-ownership rule
DEPLOY.md ← prod + dev deploy runbook, identity, migration baseline, Caddy, pm2
ENVIRONMENTS.md ← every env var (generated from scripts/lib/env-manifest.mjs)
app/ ← Next.js App Router: pages + API routes
src/
components/ ← client components
lib/ ← auth config, signing-identity (loadAppSigningKey boot path), base-path, other helpers
db/ ← this app's own drizzle schema (never a kernel schema)
migrations/ ← generated by `pnpm db:generate`, applied by `pnpm db:migrate`
api-spec/ ← this app's own OpenAPI document, served at /api/spec
scripts/ ← deploy.sh, migrate-baseline.mjs, check-env.mjs (+ tests)
ecosystem.config.cjs ← pm2 entries prod-market (7104) / dev-market (3104)
instrumentation.ts ← boot-env guards + loadAppSigningKey() bootstrap (see docs/REGISTRATION.md)
middleware.ts ← gates every route on claim state — unclaimed page, /claim 404 once claimed (#2427)
app/claim/page.tsx + app/api/claim/route.ts are the operator-facing claim page and its server
route (#2427) — see "This app's own signing key" below.
This app never reads a raw private key from env. instrumentation.ts fails loud at boot if
IMAJIN_APP_PRIVATE_KEY is set, and instead calls @ima-jin/auth-client's loadAppSigningKey().
Without a keystore yet, this app boots in unclaimed mode (#2427): every route
except /claim, /api/claim, and /api/health serves a minimal "not claimed yet" page. The
operator path: approve provisioning on the kernel's /jin → open <this app>/claim → paste the
one-time claim code → done — no ssh, no env edit, no restart. Only this browser path bootstraps
a local 0600 keystore (IMAJIN_APP_KEYSTORE); every later boot re-authenticates with that
keystore, no operator action needed. See
docs/REGISTRATION.md.
Set NEXT_PUBLIC_BASE_PATH (e.g. /coffee) when this fork is served behind a reverse-proxy path
prefix instead of at /. next.config.js reads it for Next's own basePath (covers <Link> and
router.push automatically); route any raw fetch(), <a href>, or redirect() through
src/lib/base-path.ts's withBasePath() helper, since Next.js doesn't rewrite those.
Every Imajin app before the external integrators was first-party (same repo, same server, privileged access). Apps built from this template are the external-integrator test: if this app can do everything it needs through app-auth and the public API alone, the federated-app boundary is real.