@bsv/create-dpp-app 0.0.0-stage → 0.1.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +203 -0
- package/README.md +73 -2
- package/dist/index.js +97 -0
- package/package.json +53 -4
- package/template/Dockerfile +35 -0
- package/template/README.md +134 -0
- package/template/_dockerignore +6 -0
- package/template/_env.example +53 -0
- package/template/_github/workflows/ci.yml +23 -0
- package/template/_gitignore +8 -0
- package/template/_prettierrc +6 -0
- package/template/apps/api/API.md +49 -0
- package/template/apps/api/package.json +34 -0
- package/template/apps/api/src/auth.ts +55 -0
- package/template/apps/api/src/claims.ts +85 -0
- package/template/apps/api/src/cli.ts +42 -0
- package/template/apps/api/src/config.ts +66 -0
- package/template/apps/api/src/custody.ts +186 -0
- package/template/apps/api/src/dev-index.ts +71 -0
- package/template/apps/api/src/env.ts +14 -0
- package/template/apps/api/src/identifiers.ts +57 -0
- package/template/apps/api/src/index-client.ts +136 -0
- package/template/apps/api/src/main.ts +50 -0
- package/template/apps/api/src/parties.ts +68 -0
- package/template/apps/api/src/platform.ts +121 -0
- package/template/apps/api/src/profiles.ts +100 -0
- package/template/apps/api/src/reader.ts +96 -0
- package/template/apps/api/src/server.ts +420 -0
- package/template/apps/api/src/store.ts +249 -0
- package/template/apps/api/src/wallet.ts +346 -0
- package/template/apps/api/src/worker.ts +106 -0
- package/template/apps/api/src/writer.ts +351 -0
- package/template/apps/api/test/config.test.ts +15 -0
- package/template/apps/api/test/external-index.test.ts +31 -0
- package/template/apps/api/test/lifecycle.test.ts +136 -0
- package/template/apps/api/tsconfig.json +9 -0
- package/template/apps/api/vitest.config.ts +9 -0
- package/template/apps/web/components.json +21 -0
- package/template/apps/web/index.html +12 -0
- package/template/apps/web/package.json +33 -0
- package/template/apps/web/src/app.tsx +51 -0
- package/template/apps/web/src/components/bits.tsx +188 -0
- package/template/apps/web/src/components/layout.tsx +118 -0
- package/template/apps/web/src/components/passport-form.tsx +244 -0
- package/template/apps/web/src/components/read-passport.tsx +48 -0
- package/template/apps/web/src/components/reading.tsx +157 -0
- package/template/apps/web/src/components/ui/alert.tsx +65 -0
- package/template/apps/web/src/components/ui/badge.tsx +47 -0
- package/template/apps/web/src/components/ui/button.tsx +63 -0
- package/template/apps/web/src/components/ui/card.tsx +91 -0
- package/template/apps/web/src/components/ui/dialog.tsx +156 -0
- package/template/apps/web/src/components/ui/input.tsx +20 -0
- package/template/apps/web/src/components/ui/label.tsx +21 -0
- package/template/apps/web/src/components/ui/select.tsx +189 -0
- package/template/apps/web/src/components/ui/separator.tsx +25 -0
- package/template/apps/web/src/components/ui/table.tsx +115 -0
- package/template/apps/web/src/components/ui/tabs.tsx +90 -0
- package/template/apps/web/src/components/ui/textarea.tsx +17 -0
- package/template/apps/web/src/index.css +81 -0
- package/template/apps/web/src/lib/api.ts +286 -0
- package/template/apps/web/src/lib/auth.ts +10 -0
- package/template/apps/web/src/lib/format.ts +64 -0
- package/template/apps/web/src/lib/session.tsx +92 -0
- package/template/apps/web/src/lib/use-load.ts +46 -0
- package/template/apps/web/src/main.tsx +18 -0
- package/template/apps/web/src/pages/accept.tsx +108 -0
- package/template/apps/web/src/pages/brand.tsx +94 -0
- package/template/apps/web/src/pages/brands.tsx +104 -0
- package/template/apps/web/src/pages/home.tsx +51 -0
- package/template/apps/web/src/pages/new-passport.tsx +114 -0
- package/template/apps/web/src/pages/operations.tsx +150 -0
- package/template/apps/web/src/pages/passport.tsx +568 -0
- package/template/apps/web/src/pages/public-passport.tsx +24 -0
- package/template/apps/web/src/pages/sign-in.tsx +93 -0
- package/template/apps/web/src/pages/verify.tsx +30 -0
- package/template/apps/web/src/pages/wallet.tsx +141 -0
- package/template/apps/web/tsconfig.json +29 -0
- package/template/apps/web/vite.config.ts +15 -0
- package/template/deploy/compose.yml +26 -0
- package/template/package.json +42 -0
- package/template/tsconfig.base.json +13 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# Copy to .env and fill in. The npm scripts (dev, start, wallet, operations) read .env at start,
|
|
2
|
+
# as does Docker with --env-file. A value already set in the environment wins over the file.
|
|
3
|
+
# Values marked (live) are needed only to write real passports on BSV mainnet;
|
|
4
|
+
# `npm test` and `npm run dev` work without them.
|
|
5
|
+
|
|
6
|
+
# The chain your wallet and index are on: main or test
|
|
7
|
+
NETWORK=main
|
|
8
|
+
PORT=3000
|
|
9
|
+
# Where the web app is served from in production (the API serves it); in dev Vite proxies to the API
|
|
10
|
+
PUBLIC_URL=http://localhost:3000
|
|
11
|
+
|
|
12
|
+
# MongoDB for the application's records, journal and sign-in
|
|
13
|
+
MONGO_URL=mongodb://127.0.0.1:27017
|
|
14
|
+
MONGO_DB=dpp_app
|
|
15
|
+
|
|
16
|
+
# Sign-in (Better Auth). Generate a secret with: openssl rand -hex 32
|
|
17
|
+
AUTH_SECRET=change-me-to-32-random-bytes-hex
|
|
18
|
+
|
|
19
|
+
# The platform wallet: a BRC-100 wallet the API owns (wallet-toolbox on SQLite).
|
|
20
|
+
# Generate a root key with: openssl rand -hex 32. Keep it secret and backed up.
|
|
21
|
+
WALLET_ROOT_KEY=
|
|
22
|
+
WALLET_FILE=local/wallet.sqlite
|
|
23
|
+
# WhatsOnChain API key: the header source for the wallet and the reader (live)
|
|
24
|
+
WOC_API_KEY=
|
|
25
|
+
# An ARC-compatible broadcaster URL; empty uses the toolbox's defaults for the network (live)
|
|
26
|
+
ARC_URL=
|
|
27
|
+
|
|
28
|
+
# Secrets the platform derives managed identities from: one per brand, one per recipient. openssl rand -hex 32 each.
|
|
29
|
+
BRAND_ROOT_SECRET=
|
|
30
|
+
MANAGED_IDENTITY_SECRET=
|
|
31
|
+
|
|
32
|
+
# The index (overlay) this platform writes to. Empty in dev: the API runs one in-process.
|
|
33
|
+
# Required once LIVE_PUBLISHING=true; the API refuses to start without it.
|
|
34
|
+
# Use an existing provider or a separate @bsv/create-dpp-index project.
|
|
35
|
+
# Copy its .app.env connection values here. App Compose starts only the app database.
|
|
36
|
+
INDEX_URL=
|
|
37
|
+
INDEX_SUBMIT_TOKEN=
|
|
38
|
+
INDEX_CALLBACK_TOKEN=
|
|
39
|
+
|
|
40
|
+
# The host passports are minted under: https://<PASSPORT_HOST>/01/<gtin>/21/<serial>
|
|
41
|
+
PASSPORT_HOST=localhost:3000
|
|
42
|
+
# The GS1 company prefix passports may be written under. 952 is GS1's demonstration prefix, never licensed to anyone.
|
|
43
|
+
# Replace with your licensed prefix for real products; the demo notice switches off with it.
|
|
44
|
+
GS1_PREFIX=952
|
|
45
|
+
|
|
46
|
+
# A registry that validates and stores lifecycle claims (POST /validate is open on the hosted reference)
|
|
47
|
+
REGISTRY_URL=https://dpp-resolver.bsvb.net
|
|
48
|
+
REGISTRY_TOKEN=
|
|
49
|
+
|
|
50
|
+
# Writing to the chain spends real satoshis. Keep false until the live prerequisites in README.md are met.
|
|
51
|
+
LIVE_PUBLISHING=false
|
|
52
|
+
# How many satoshis the platform may spend per day before it refuses to write more
|
|
53
|
+
SPEND_CAP_SATOSHIS=20000
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Install, typecheck, build and run the offline lifecycle test on every change.
|
|
2
|
+
name: CI
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
test:
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: actions/setup-node@v4
|
|
17
|
+
with:
|
|
18
|
+
node-version: 22
|
|
19
|
+
cache: npm
|
|
20
|
+
- run: npm ci
|
|
21
|
+
- run: npm run typecheck
|
|
22
|
+
- run: npm run build
|
|
23
|
+
- run: npm test
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# The application API
|
|
2
|
+
|
|
3
|
+
JSON under `/api`. Reads are open. Writes need a signed-in member of the brand that holds the passport, or, for a recipient who accepted a hand-on, the claim code they accepted with. Sign-in is Better Auth under `/api/auth/*` (email and password, organisations as brands); without MongoDB the API runs a development session instead and every request is "Developer", a member of brand `dev-brand`.
|
|
4
|
+
|
|
5
|
+
Errors are `{ error: <code>, description: <sentence> }`. A refused write is HTTP 409 with the writer's own code (`identifier-refused`, `payload-invalid`, `index-refused`, `not-the-controller`, `retired`, `live-publishing-off`, `spend-cap`, and so on); 401 means sign in; 403 means not a member or no claim code; 404 means not in this platform's journal, or an unknown offer or state.
|
|
6
|
+
|
|
7
|
+
A passport reference `:ref` is the URL-encoded passport identifier, for example `https%3A%2F%2Flocalhost%3A3000%2F01%2F09521000000011%2F21%2FA1`.
|
|
8
|
+
|
|
9
|
+
## Open
|
|
10
|
+
|
|
11
|
+
| Route | Returns |
|
|
12
|
+
|---|---|
|
|
13
|
+
| `GET /api/health` | `{ ok, network, index, publisherKey, wallet: 'toolbox'\|'test', livePublishing, identifiers: { host, prefix, demonstration }, signIn, devSession? }` |
|
|
14
|
+
| `GET /api/profiles` | `[{ id, title, description }]`, the current industry profiles |
|
|
15
|
+
| `GET /api/profiles/:id` | `{ id, title, description, fields: [{ key, label, valueType, unit, accessTier, obligation, cardinality, codeList, constraints, note, group }], publicSchema, restrictedSchema, sample, sampleProblems }`. `sample` is a minimal public payload of placeholders and `sampleProblems` lists anything its own schema still refuses (empty for the current profiles); fields whose `accessTier` is `public` go in `payload`; every other tier goes in `ownerFields`, the restricted tier that is encrypted off chain |
|
|
16
|
+
| `GET /api/verify?passportId=` | The reader's result: `{ passportId, lineage: [{ op, txid, timestamp, controllerKey, actorIdentityKey, payloadPublic }], checks: [{ name, label, status, reasonCode }], report, publisherKeys }`. `status` is `pass`, `fail`, `unknown` or `not-applicable`; `unknown` is missing evidence, never a pass |
|
|
17
|
+
| `GET /api/passports/:ref` | The journal view: `{ passportId, brandId, profile, status, demonstration, holder: { party, controllerKey }, createdAt, payload, journal: { states, proven, pending, status }, states: [{ op, txid, timestamp, actor, index, refusal, network, proven, proofPushed, blockHeight }], acceptanceRecords }` |
|
|
18
|
+
| `GET /api/passports/:ref/claims` | `[{ id, passportId, issuer, issuedBy, claim, registry?, createdAt, verified }]` |
|
|
19
|
+
| `GET /api/offers/:requestId` | `{ requestId, passportId, terms, expiresAt, status }`, what a recipient sees before deciding |
|
|
20
|
+
| `POST /api/offers/:requestId/accept` `{ claimCode }` | `{ offer, record, transferTxid }`: the custodian-signed acceptance record and the TRANSFER it committed to |
|
|
21
|
+
| `POST /api/offers/:requestId/decline` `{ claimCode }` | The offer, declined; nothing is written |
|
|
22
|
+
|
|
23
|
+
## Signed in
|
|
24
|
+
|
|
25
|
+
| Route | Body | Returns |
|
|
26
|
+
|---|---|---|
|
|
27
|
+
| `GET /api/me` | | `{ userId, email, name, brandIds, brands: [{ id, name, identityKey, did, createdAt }] }` |
|
|
28
|
+
| `GET /api/brands` | | The user's brands |
|
|
29
|
+
| `POST /api/brands` | `{ name }` | The new brand; its identity key is derived by the platform |
|
|
30
|
+
| `GET /api/brands/:brandId/passports` | | Journal views of the brand's passports |
|
|
31
|
+
| `POST /api/brands/:brandId/passports` | `{ profile, itemReference, serial, payload, ownerFields }` | The issued passport's journal view. `itemReference` is the digits after the GS1 prefix (nine for prefix 952), `serial` the item's serial |
|
|
32
|
+
| `POST /api/passports/:ref/update` | `{ payload, ownerFields?, eventData?, claimCode? }` | The journal view after the UPDATE. Omit `ownerFields` to carry the current owner tier unchanged; send `{}` to seal an empty one. The API never returns the owner tier |
|
|
33
|
+
| `POST /api/passports/:ref/offer` | `{ terms: { word, note? }, mechanism?, recipientIdentityKey?, claimCode? }` | `{ offer, claimCode }`. The claim code is shown once; give it to the recipient out of band |
|
|
34
|
+
| `GET /api/passports/:ref/offers` | | The passport's offers, without claim-code hashes; the brand's view, so it needs brand membership even after a hand-on |
|
|
35
|
+
| `POST /api/offers/:requestId/withdraw` | `{ claimCode? }` | The offer, withdrawn |
|
|
36
|
+
| `POST /api/passports/:ref/retire` | `{ reason, claimCode? }` | The journal view after the RETIRE |
|
|
37
|
+
| `POST /api/passports/:ref/states/:txid/resolve` | `{ outcome: 'sent'\|'abandoned' }` | A write interrupted between announcement and the network's answer (network `pending`, listed as a `resolve-interrupted` duty) is kept as sent, or withdrawn from the index, aborted in the wallet and removed. Only the operator knows which; never rebuild a state that was sent |
|
|
38
|
+
| `POST /api/passports/:ref/claims` | `{ eventType: 'Origin'\|'Transfer'\|'Transformation'\|'Disposition', submit?: boolean }` | The signed claim record with `verified`; with `submit`, the registry's answer under `registry` |
|
|
39
|
+
| `GET /api/operations` | | `{ duties: [{ passportId, txid, op, duty: 'announce'\|'prove'\|'push-proof'\|'resolve-interrupted', since }], passports: [{ passportId, brandId, status, journal }] }` |
|
|
40
|
+
| `POST /api/operations/run` | | `{ done: [sentence] }`, one pass over the duties |
|
|
41
|
+
| `GET /api/wallet` | | `{ kind, network, identityKey, balance, livePublishing }` |
|
|
42
|
+
| `POST /api/wallet/funding-address` | | `{ address, derivationPrefix, derivationSuffix, senderIdentityKey }`, a fresh address to pay |
|
|
43
|
+
| `POST /api/wallet/internalize` | `{ txid, funding }` | `{ satoshis }` taken in from a payment to that funding address |
|
|
44
|
+
|
|
45
|
+
`claimCode` on update, offer, withdraw and retire is for a recipient who holds the passport after a hand-on; a brand member omits it.
|
|
46
|
+
|
|
47
|
+
## The passport page
|
|
48
|
+
|
|
49
|
+
The API serves the built web app for every path outside `/api`, including a passport's own identifier path `/01/<gtin>/21/<serial>`, so a label's QR code opens the passport page. The page reconstructs the identifier from the current origin and that path, then calls `GET /api/verify` and `GET /api/passports/:ref`.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "api",
|
|
3
|
+
"private": true,
|
|
4
|
+
"description": "The application API: owns the platform wallet, writes and reads passports with the @bsv/dpp packages, keeps the journal and runs the unattended duties",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"dev": "tsx watch src/main.ts",
|
|
9
|
+
"build": "tsc -p tsconfig.json",
|
|
10
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
11
|
+
"test": "vitest run",
|
|
12
|
+
"start": "node dist/main.js"
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@bsv/dpp-overlay": "0.4.0-beta.12",
|
|
16
|
+
"@bsv/dpp-profiles": "0.3.0-beta.9",
|
|
17
|
+
"@bsv/dpp-protocol": "0.3.0-beta.9",
|
|
18
|
+
"@bsv/overlay": "2.3.1",
|
|
19
|
+
"@bsv/sdk": "2.8.10",
|
|
20
|
+
"@bsv/wallet-toolbox": "2.14.6",
|
|
21
|
+
"ajv": "8.20.0",
|
|
22
|
+
"ajv-formats": "3.0.1",
|
|
23
|
+
"better-auth": "1.7.7",
|
|
24
|
+
"express": "5.3.0",
|
|
25
|
+
"mongodb": "7.7.0"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/express": "^5.0.6",
|
|
29
|
+
"@types/node": "^22.20.3",
|
|
30
|
+
"tsx": "^4.23.15",
|
|
31
|
+
"typescript": "^7.0.2",
|
|
32
|
+
"vitest": "^5.0.3"
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Sign-in is the guard rail on every write: the write routes spend real
|
|
2
|
+
// satoshis and write permanent states, so who may act for which brand must
|
|
3
|
+
// be decided before a key is used. Better Auth, self-hosted on the same
|
|
4
|
+
// MongoDB, with email and password and organisations: an organisation is a
|
|
5
|
+
// brand, and its members act for it. The signature itself is always made
|
|
6
|
+
// with a key the platform holds; sign-in only decides who may ask for it.
|
|
7
|
+
// At Ring 0 this platform is the only party vouching for who a member is.
|
|
8
|
+
import { betterAuth } from 'better-auth'
|
|
9
|
+
import { mongodbAdapter } from 'better-auth/adapters/mongodb'
|
|
10
|
+
import { fromNodeHeaders } from 'better-auth/node'
|
|
11
|
+
import { organization } from 'better-auth/plugins'
|
|
12
|
+
import type { Db } from 'mongodb'
|
|
13
|
+
import type { IncomingHttpHeaders } from 'node:http'
|
|
14
|
+
|
|
15
|
+
export interface AuthOptions {
|
|
16
|
+
db: Db
|
|
17
|
+
secret: string
|
|
18
|
+
baseURL: string
|
|
19
|
+
trustedOrigins?: string[]
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createAuth(options: AuthOptions) {
|
|
23
|
+
return betterAuth({
|
|
24
|
+
database: mongodbAdapter(options.db),
|
|
25
|
+
secret: options.secret,
|
|
26
|
+
baseURL: options.baseURL,
|
|
27
|
+
basePath: '/api/auth',
|
|
28
|
+
trustedOrigins: options.trustedOrigins ?? [],
|
|
29
|
+
emailAndPassword: { enabled: true },
|
|
30
|
+
plugins: [organization()],
|
|
31
|
+
})
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type Auth = ReturnType<typeof createAuth>
|
|
35
|
+
|
|
36
|
+
export interface Session {
|
|
37
|
+
userId: string
|
|
38
|
+
email: string
|
|
39
|
+
name: string
|
|
40
|
+
/** The brands (organisations) this user is a member of. */
|
|
41
|
+
brandIds: string[]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The signed-in user behind a request, or undefined. */
|
|
45
|
+
export async function sessionFrom(auth: Auth, headers: IncomingHttpHeaders): Promise<Session | undefined> {
|
|
46
|
+
const session = await auth.api.getSession({ headers: fromNodeHeaders(headers) })
|
|
47
|
+
if (session == null) return undefined
|
|
48
|
+
const organisations = await auth.api.listOrganizations({ headers: fromNodeHeaders(headers) })
|
|
49
|
+
return {
|
|
50
|
+
userId: session.user.id,
|
|
51
|
+
email: session.user.email,
|
|
52
|
+
name: session.user.name,
|
|
53
|
+
brandIds: organisations.map((o) => o.id),
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// Lifecycle claims: a signed statement about a passport, such as a repair or
|
|
2
|
+
// a recycling, on its own rail. It never spends the passport. The issuer
|
|
3
|
+
// signs it with their own key, a registry validates and stores it and
|
|
4
|
+
// publishes a separate anchor, and a reader checks the signature and the
|
|
5
|
+
// anchor itself. This platform signs for a signed-in member with the
|
|
6
|
+
// managed identity it derives for them, and sends the claim to the
|
|
7
|
+
// configured registry over HTTP.
|
|
8
|
+
import { PrivateKey, Utils } from '@bsv/sdk'
|
|
9
|
+
import { lifecycleClaimDigest, signLifecycleClaim, verifyLifecycleClaim, type LifecycleClaim, type LifecycleEventType, type SignedLifecycleClaim } from '@bsv/dpp-protocol'
|
|
10
|
+
import type { Party } from './parties.js'
|
|
11
|
+
import type { ClaimRecord, PassportRecord, Store } from './store.js'
|
|
12
|
+
import { WriteRefused } from './writer.js'
|
|
13
|
+
|
|
14
|
+
export interface ClaimsOptions {
|
|
15
|
+
store: Store
|
|
16
|
+
registry?: { url: string; token?: string }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const EVENT_TYPES: LifecycleEventType[] = ['Origin', 'Transfer', 'Transformation', 'Disposition']
|
|
20
|
+
|
|
21
|
+
export class Claims {
|
|
22
|
+
constructor(private readonly options: ClaimsOptions) {}
|
|
23
|
+
|
|
24
|
+
/** Sign a claim about the passport's current state as the issuer, and keep it. */
|
|
25
|
+
async sign(args: { passport: PassportRecord; issuer: Party; eventType: LifecycleEventType; keyId?: string }): Promise<ClaimRecord> {
|
|
26
|
+
const tip = args.passport.states.at(-1)
|
|
27
|
+
if (tip == null) throw new WriteRefused('not-issued', `${args.passport.passportId} has no state to claim about`)
|
|
28
|
+
const [profile, version] = args.passport.profile.split('@')
|
|
29
|
+
const claim: LifecycleClaim = {
|
|
30
|
+
claimFormat: 'dpp-lifecycle-v1',
|
|
31
|
+
passportId: args.passport.passportId,
|
|
32
|
+
recordId: tip.txid,
|
|
33
|
+
eventType: args.eventType,
|
|
34
|
+
timestamp: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
|
|
35
|
+
issuer: args.issuer.did,
|
|
36
|
+
issuerKeyId: args.keyId ?? args.issuer.name,
|
|
37
|
+
profile,
|
|
38
|
+
profile_version: Number(version),
|
|
39
|
+
}
|
|
40
|
+
const signed = await signLifecycleClaim(claim, args.issuer.wallet)
|
|
41
|
+
if (verifyLifecycleClaim(signed).signature !== 'verified') throw new WriteRefused('claim-unsigned', 'the signed claim does not verify under its own issuer key')
|
|
42
|
+
const record: ClaimRecord = {
|
|
43
|
+
id: `claim-${lifecycleClaimDigest(signed).slice(0, 16)}-${Utils.toHex(PrivateKey.fromRandom().toArray().slice(0, 4))}`,
|
|
44
|
+
passportId: args.passport.passportId,
|
|
45
|
+
issuer: signed.issuer,
|
|
46
|
+
issuedBy: args.issuer.name,
|
|
47
|
+
claim: signed,
|
|
48
|
+
createdAt: claim.timestamp,
|
|
49
|
+
}
|
|
50
|
+
await this.options.store.saveClaim(record)
|
|
51
|
+
return record
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Send a signed claim to the registry to verify, store and anchor (POST /attestations). Storing needs the registry's permission. */
|
|
55
|
+
async submit(record: ClaimRecord): Promise<ClaimRecord> {
|
|
56
|
+
const registry = this.options.registry
|
|
57
|
+
if (registry == null) throw new WriteRefused('registry-unset', 'REGISTRY_URL is not set')
|
|
58
|
+
const response = await fetch(`${registry.url}/attestations`, {
|
|
59
|
+
method: 'POST',
|
|
60
|
+
headers: { 'Content-Type': 'application/json', ...(registry.token != null ? { Authorization: `Bearer ${registry.token}` } : {}) },
|
|
61
|
+
body: JSON.stringify(record.claim),
|
|
62
|
+
})
|
|
63
|
+
const body = (await response.json().catch(() => ({}))) as { accepted?: boolean; attestationId?: string; description?: string; error?: string }
|
|
64
|
+
record.registry = {
|
|
65
|
+
url: registry.url,
|
|
66
|
+
status: response.status,
|
|
67
|
+
accepted: response.status === 202 && body.accepted === true,
|
|
68
|
+
attestationId: body.attestationId,
|
|
69
|
+
detail: body.description ?? body.error,
|
|
70
|
+
}
|
|
71
|
+
await this.options.store.saveClaim(record)
|
|
72
|
+
return record
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Ask the registry to check a claim without storing it (POST /validate is open on the hosted reference). */
|
|
76
|
+
async validate(claim: SignedLifecycleClaim): Promise<unknown> {
|
|
77
|
+
const registry = this.options.registry
|
|
78
|
+
if (registry == null) throw new WriteRefused('registry-unset', 'REGISTRY_URL is not set')
|
|
79
|
+
const url = new URL('/validate', registry.url)
|
|
80
|
+
url.searchParams.set('subject', claim.passportId)
|
|
81
|
+
const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(claim) })
|
|
82
|
+
if (!response.ok) throw new WriteRefused('registry-refused', `the registry answered HTTP ${response.status} to /validate`)
|
|
83
|
+
return await response.json()
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Operator commands against the running configuration, with no HTTP:
|
|
3
|
+
//
|
|
4
|
+
// node apps/api/dist/cli.js wallet publisher key, a funding address, balance
|
|
5
|
+
// node apps/api/dist/cli.js wallet fund <txid> <address> <prefix> <suffix>
|
|
6
|
+
// take in a payment made to a funding address
|
|
7
|
+
// node apps/api/dist/cli.js operations what is still owed, and run the duties once
|
|
8
|
+
import './env.js'
|
|
9
|
+
import { loadConfig } from './config.js'
|
|
10
|
+
import { openPlatform } from './platform.js'
|
|
11
|
+
import { pendingDuties, runDuties } from './worker.js'
|
|
12
|
+
import { ANYONE_IDENTITY_KEY } from './wallet.js'
|
|
13
|
+
|
|
14
|
+
const [command, ...rest] = process.argv.slice(2)
|
|
15
|
+
const config = loadConfig()
|
|
16
|
+
const platform = await openPlatform({ config, mode: 'live', log: () => {} })
|
|
17
|
+
|
|
18
|
+
try {
|
|
19
|
+
if (command === 'wallet' && rest[0] === 'fund') {
|
|
20
|
+
const [txid, address, derivationPrefix, derivationSuffix] = rest.slice(1)
|
|
21
|
+
if (txid == null || address == null || derivationPrefix == null || derivationSuffix == null) throw new Error('usage: wallet fund <txid> <address> <prefix> <suffix>')
|
|
22
|
+
const taken = await platform.wallet.internalize({ address, derivationPrefix, derivationSuffix, senderIdentityKey: ANYONE_IDENTITY_KEY }, txid)
|
|
23
|
+
console.log(`Took in ${taken.satoshis} satoshis from ${txid}. Balance: ${await platform.wallet.balance()} satoshis.`)
|
|
24
|
+
} else if (command === 'wallet') {
|
|
25
|
+
const funding = await platform.wallet.fundingAddress()
|
|
26
|
+
console.log(`Publisher key (give this to your index; it is public): ${platform.wallet.identityKey}`)
|
|
27
|
+
console.log(`Wallet: ${platform.wallet.kind} on ${platform.wallet.network}`)
|
|
28
|
+
console.log(`Balance: ${await platform.wallet.balance()} satoshis`)
|
|
29
|
+
console.log(`Funding address: ${funding.address}`)
|
|
30
|
+
console.log(`After paying it, take the payment in with: wallet fund <txid> ${funding.address} ${funding.derivationPrefix} ${funding.derivationSuffix}`)
|
|
31
|
+
} else if (command === 'operations') {
|
|
32
|
+
const duties = await pendingDuties(platform.store)
|
|
33
|
+
console.log(duties.length === 0 ? 'Nothing is owed.' : `${duties.length} dut${duties.length === 1 ? 'y' : 'ies'} pending:`)
|
|
34
|
+
for (const d of duties) console.log(` ${d.op} ${d.txid.slice(0, 12)}... ${d.duty} (${d.passportId})`)
|
|
35
|
+
for (const line of await runDuties({ store: platform.store, index: platform.index, writer: platform.writer })) console.log(` ${line}`)
|
|
36
|
+
} else {
|
|
37
|
+
console.error('usage: cli.js wallet | wallet fund <txid> <address> <prefix> <suffix> | operations')
|
|
38
|
+
process.exitCode = 2
|
|
39
|
+
}
|
|
40
|
+
} finally {
|
|
41
|
+
await platform.close()
|
|
42
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Configuration is environment only. Secrets are read here once and never
|
|
2
|
+
// printed. `npm test` and `npm run dev` work with the defaults; the values
|
|
3
|
+
// marked live in .env.example are needed only to write real passports.
|
|
4
|
+
|
|
5
|
+
export type Network = 'main' | 'test'
|
|
6
|
+
|
|
7
|
+
export interface Config {
|
|
8
|
+
network: Network
|
|
9
|
+
port: number
|
|
10
|
+
publicUrl: string
|
|
11
|
+
mongoUrl: string
|
|
12
|
+
mongoDb: string
|
|
13
|
+
authSecret: string
|
|
14
|
+
wallet: { rootKeyHex?: string; filePath: string; wocApiKey?: string; arcUrl?: string }
|
|
15
|
+
brandRootSecret: string
|
|
16
|
+
managedIdentitySecret: string
|
|
17
|
+
index: { url?: string; submitToken?: string; callbackToken?: string }
|
|
18
|
+
passportHost: string
|
|
19
|
+
gs1Prefix: string
|
|
20
|
+
registry: { url?: string; token?: string }
|
|
21
|
+
livePublishing: boolean
|
|
22
|
+
spendCapSatoshis: number
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const text = (env: NodeJS.ProcessEnv, name: string): string | undefined => {
|
|
26
|
+
const value = env[name]?.trim()
|
|
27
|
+
return value == null || value === '' ? undefined : value
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Read the configuration from an environment. Missing secrets get development defaults that the README says to replace. */
|
|
31
|
+
export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
|
|
32
|
+
const network = (text(env, 'NETWORK') ?? 'main') as Network
|
|
33
|
+
if (network !== 'main' && network !== 'test') throw new Error(`NETWORK must be main or test, not ${network}`)
|
|
34
|
+
const livePublishing = text(env, 'LIVE_PUBLISHING') === 'true'
|
|
35
|
+
const rootKeyHex = text(env, 'WALLET_ROOT_KEY')
|
|
36
|
+
if (rootKeyHex != null && !/^[0-9a-fA-F]{64}$/.test(rootKeyHex)) throw new Error('WALLET_ROOT_KEY must be 64 hexadecimal characters')
|
|
37
|
+
if (livePublishing && rootKeyHex == null) throw new Error('LIVE_PUBLISHING=true needs WALLET_ROOT_KEY')
|
|
38
|
+
// A real passport announced only to the in-process index would be on the chain and findable by nobody after a restart.
|
|
39
|
+
if (livePublishing && text(env, 'INDEX_URL') == null) throw new Error('LIVE_PUBLISHING=true needs INDEX_URL: connect an index that persists before writing to the chain (README, Connect an index)')
|
|
40
|
+
return {
|
|
41
|
+
network,
|
|
42
|
+
port: Number(text(env, 'PORT') ?? 3000),
|
|
43
|
+
publicUrl: (text(env, 'PUBLIC_URL') ?? 'http://localhost:3000').replace(/\/+$/, ''),
|
|
44
|
+
mongoUrl: text(env, 'MONGO_URL') ?? 'mongodb://127.0.0.1:27017',
|
|
45
|
+
mongoDb: text(env, 'MONGO_DB') ?? 'dpp_app',
|
|
46
|
+
authSecret: text(env, 'AUTH_SECRET') ?? 'development-only-secret-replace-me-before-deploying',
|
|
47
|
+
wallet: {
|
|
48
|
+
rootKeyHex,
|
|
49
|
+
filePath: text(env, 'WALLET_FILE') ?? 'local/wallet.sqlite',
|
|
50
|
+
wocApiKey: text(env, 'WOC_API_KEY'),
|
|
51
|
+
arcUrl: text(env, 'ARC_URL'),
|
|
52
|
+
},
|
|
53
|
+
brandRootSecret: text(env, 'BRAND_ROOT_SECRET') ?? 'development-only-brand-secret-replace-me',
|
|
54
|
+
managedIdentitySecret: text(env, 'MANAGED_IDENTITY_SECRET') ?? 'development-only-managed-identity-secret-replace-me',
|
|
55
|
+
index: {
|
|
56
|
+
url: text(env, 'INDEX_URL')?.replace(/\/+$/, ''),
|
|
57
|
+
submitToken: text(env, 'INDEX_SUBMIT_TOKEN'),
|
|
58
|
+
callbackToken: text(env, 'INDEX_CALLBACK_TOKEN'),
|
|
59
|
+
},
|
|
60
|
+
passportHost: text(env, 'PASSPORT_HOST') ?? 'localhost:3000',
|
|
61
|
+
gs1Prefix: text(env, 'GS1_PREFIX') ?? '952',
|
|
62
|
+
registry: { url: text(env, 'REGISTRY_URL')?.replace(/\/+$/, ''), token: text(env, 'REGISTRY_TOKEN') },
|
|
63
|
+
livePublishing,
|
|
64
|
+
spendCapSatoshis: Number(text(env, 'SPEND_CAP_SATOSHIS') ?? 20_000),
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// Hand-ons under managed-custody@1 (spec/managed-custody.md): offer,
|
|
2
|
+
// acceptance, transfer. The custodian, this platform, fixes the current tip,
|
|
3
|
+
// a digest of the exact terms shown to the recipient and an expiry; the
|
|
4
|
+
// recipient accepts with a claim code or as a named identity; the custodian
|
|
5
|
+
// signs and keeps the acceptance record; the TRANSFER commits to it in
|
|
6
|
+
// field 15 and moves control to the recipient's managed key. Only the third
|
|
7
|
+
// step touches the chain. A declined or expired offer writes nothing.
|
|
8
|
+
import { Hash, PrivateKey, Utils } from '@bsv/sdk'
|
|
9
|
+
import { bindAcceptanceToState, canonicalJson, inspectManagedAcceptance, signManagedAcceptance, type ManagedAcceptanceClaim, type ManagedAcceptanceRecord } from '@bsv/dpp-protocol'
|
|
10
|
+
import type { Parties, Party } from './parties.js'
|
|
11
|
+
import type { OfferRecord, PassportRecord, Store } from './store.js'
|
|
12
|
+
import type { PlatformWallet } from './wallet.js'
|
|
13
|
+
import { WriteRefused, type Writer } from './writer.js'
|
|
14
|
+
|
|
15
|
+
const instant = (offsetSeconds = 0): string => new Date(Date.now() + offsetSeconds * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z')
|
|
16
|
+
const sha256hex = (text: string): string => Utils.toHex(Hash.sha256(Utils.toArray(text, 'utf8')))
|
|
17
|
+
|
|
18
|
+
export interface CustodyOptions {
|
|
19
|
+
store: Store
|
|
20
|
+
wallet: PlatformWallet
|
|
21
|
+
parties: Parties
|
|
22
|
+
writer: Writer
|
|
23
|
+
/** How long an offer stays open. */
|
|
24
|
+
offerLifetimeSeconds?: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class Custody {
|
|
28
|
+
private readonly lifetime: number
|
|
29
|
+
|
|
30
|
+
constructor(private readonly options: CustodyOptions) {
|
|
31
|
+
this.lifetime = options.offerLifetimeSeconds ?? 7 * 24 * 3600
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The holder asks the custodian to offer the passport, by claim code (the
|
|
36
|
+
* code is returned once and only its hash is kept) or to a named identity.
|
|
37
|
+
*/
|
|
38
|
+
async offer(args: { record: PassportRecord; holder: Party; terms: Record<string, unknown>; mechanism?: 'claim-code' | 'named-recipient'; recipientIdentityKey?: string }): Promise<{ offer: OfferRecord; claimCode?: string }> {
|
|
39
|
+
const { record, holder } = args
|
|
40
|
+
if (record.status === 'retired') throw new WriteRefused('retired', `${record.passportId} is retired`)
|
|
41
|
+
if (record.holder.party !== holder.name) throw new WriteRefused('not-the-holder', `${holder.name} does not hold ${record.passportId}`)
|
|
42
|
+
const tip = record.states.at(-1)
|
|
43
|
+
if (tip == null) throw new WriteRefused('not-issued', `${record.passportId} has no state`)
|
|
44
|
+
const open = await this.options.store.listOffers({ passportId: record.passportId, status: 'open' })
|
|
45
|
+
if (open.length > 0) throw new WriteRefused('offer-open', `${record.passportId} already has an open offer ${open[0].requestId}; withdraw it first`)
|
|
46
|
+
const mechanism = args.mechanism ?? 'claim-code'
|
|
47
|
+
if (mechanism === 'named-recipient' && args.recipientIdentityKey == null) throw new WriteRefused('recipient-missing', 'a named-recipient offer needs the recipient identity key')
|
|
48
|
+
const claimCode = mechanism === 'claim-code' ? Utils.toHex(PrivateKey.fromRandom().toArray().slice(0, 8)) : undefined
|
|
49
|
+
const offer: OfferRecord = {
|
|
50
|
+
requestId: `offer-${Date.now().toString(36)}-${Utils.toHex(PrivateKey.fromRandom().toArray().slice(0, 4))}`,
|
|
51
|
+
passportId: record.passportId,
|
|
52
|
+
brandId: record.brandId,
|
|
53
|
+
mechanism,
|
|
54
|
+
claimCodeHash: claimCode == null ? undefined : sha256hex(claimCode),
|
|
55
|
+
recipientIdentityKey: args.recipientIdentityKey,
|
|
56
|
+
terms: args.terms,
|
|
57
|
+
termsDigest: sha256hex(canonicalJson(args.terms)),
|
|
58
|
+
holderIdentityKey: holder.identityKey,
|
|
59
|
+
expectedPredecessor: { txid: tip.txid, outputIndex: tip.outputIndex },
|
|
60
|
+
createdAt: instant(),
|
|
61
|
+
expiresAt: instant(this.lifetime),
|
|
62
|
+
status: 'open',
|
|
63
|
+
}
|
|
64
|
+
await this.options.store.saveOffer(offer)
|
|
65
|
+
return { offer, claimCode }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async withdraw(requestId: string, holder: Party): Promise<OfferRecord> {
|
|
69
|
+
const offer = await this.options.store.getOffer(requestId)
|
|
70
|
+
if (offer == null) throw new WriteRefused('offer-unknown', `no offer ${requestId}`)
|
|
71
|
+
if (offer.holderIdentityKey !== holder.identityKey) throw new WriteRefused('not-the-holder', 'only the holder withdraws an offer')
|
|
72
|
+
if (offer.status !== 'open') throw new WriteRefused('offer-closed', `offer ${requestId} is ${offer.status}`)
|
|
73
|
+
offer.status = 'withdrawn'
|
|
74
|
+
await this.options.store.saveOffer(offer)
|
|
75
|
+
return offer
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** What a recipient sees before deciding: the terms the digest covers, and when the offer closes. */
|
|
79
|
+
async preview(requestId: string): Promise<{ requestId: string; passportId: string; terms: Record<string, unknown>; expiresAt: string; status: OfferRecord['status'] }> {
|
|
80
|
+
const offer = await this.options.store.getOffer(requestId)
|
|
81
|
+
if (offer == null) throw new WriteRefused('offer-unknown', `no offer ${requestId}`)
|
|
82
|
+
return { requestId, passportId: offer.passportId, terms: offer.terms, expiresAt: offer.expiresAt, status: offer.status }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async decline(requestId: string, claimCode?: string): Promise<OfferRecord> {
|
|
86
|
+
const offer = await this.openOffer(requestId, claimCode)
|
|
87
|
+
offer.status = 'declined'
|
|
88
|
+
await this.options.store.saveOffer(offer)
|
|
89
|
+
return offer
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
private async openOffer(requestId: string, claimCode?: string, recipientIdentityKey?: string): Promise<OfferRecord> {
|
|
93
|
+
const offer = await this.options.store.getOffer(requestId)
|
|
94
|
+
if (offer == null) throw new WriteRefused('offer-unknown', `no offer ${requestId}`)
|
|
95
|
+
if (offer.status !== 'open') throw new WriteRefused('offer-closed', `offer ${requestId} is ${offer.status}`)
|
|
96
|
+
if (offer.expiresAt <= instant()) {
|
|
97
|
+
offer.status = 'expired'
|
|
98
|
+
await this.options.store.saveOffer(offer)
|
|
99
|
+
throw new WriteRefused('offer-expired', `offer ${requestId} expired at ${offer.expiresAt}`)
|
|
100
|
+
}
|
|
101
|
+
if (offer.mechanism === 'claim-code' && (claimCode == null || sha256hex(claimCode) !== offer.claimCodeHash)) throw new WriteRefused('claim-code-wrong', 'the claim code does not match this offer')
|
|
102
|
+
if (offer.mechanism === 'named-recipient' && recipientIdentityKey !== offer.recipientIdentityKey) throw new WriteRefused('recipient-wrong', 'this offer is addressed to another identity')
|
|
103
|
+
return offer
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The recipient accepts: the custodian derives the recipient's managed
|
|
108
|
+
* identity, records and signs the acceptance, keeps it, then writes the
|
|
109
|
+
* TRANSFER that commits to it. The tip must still be the one the offer named.
|
|
110
|
+
*/
|
|
111
|
+
async accept(args: { requestId: string; claimCode?: string; recipientIdentityKey?: string }): Promise<{ offer: OfferRecord; record: ManagedAcceptanceRecord; transferTxid: string }> {
|
|
112
|
+
const { store, wallet, parties, writer } = this.options
|
|
113
|
+
// An acceptance whose TRANSFER did not get written is retried with the same record, never signed twice.
|
|
114
|
+
const earlier = await store.getOffer(args.requestId)
|
|
115
|
+
const retrying = earlier?.status === 'accepted' && earlier.record != null && earlier.transferTxid == null
|
|
116
|
+
const offer = retrying ? earlier : await this.openOffer(args.requestId, args.claimCode, args.recipientIdentityKey)
|
|
117
|
+
if (retrying && offer.mechanism === 'claim-code' && (args.claimCode == null || sha256hex(args.claimCode) !== offer.claimCodeHash)) throw new WriteRefused('claim-code-wrong', 'the claim code does not match this offer')
|
|
118
|
+
const passport = await store.getPassport(offer.passportId)
|
|
119
|
+
if (passport == null) throw new WriteRefused('passport-unknown', `no passport ${offer.passportId}`)
|
|
120
|
+
const tip = passport.states.at(-1)
|
|
121
|
+
if (tip == null || tip.txid !== offer.expectedPredecessor.txid) throw new WriteRefused('tip-moved', 'the passport moved since the offer was made; ask for a new offer')
|
|
122
|
+
const holder = this.holderOf(passport)
|
|
123
|
+
const recipient = parties.recipient(offer.requestId)
|
|
124
|
+
if (retrying) {
|
|
125
|
+
const record = offer.record!
|
|
126
|
+
const outcome = await writer.transfer({ record: passport, holder, recipient, acceptance: record, eventData: { word: typeof offer.terms.word === 'string' ? offer.terms.word : 'Handed on' } })
|
|
127
|
+
offer.status = 'transferred'
|
|
128
|
+
offer.transferTxid = outcome.entry.txid
|
|
129
|
+
await store.saveOffer(offer)
|
|
130
|
+
return { offer, record, transferTxid: outcome.entry.txid }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const claim: ManagedAcceptanceClaim = {
|
|
134
|
+
acceptanceFormat: 'dpp-managed-acceptance@1',
|
|
135
|
+
requestId: offer.requestId,
|
|
136
|
+
passportId: offer.passportId,
|
|
137
|
+
lineageGenesis: { txid: passport.states[0].txid, outputIndex: passport.states[0].outputIndex },
|
|
138
|
+
expectedPredecessor: offer.expectedPredecessor,
|
|
139
|
+
termsDigest: offer.termsDigest,
|
|
140
|
+
offer: {
|
|
141
|
+
holderIdentityKey: offer.holderIdentityKey,
|
|
142
|
+
createdAt: offer.createdAt,
|
|
143
|
+
expiresAt: offer.expiresAt,
|
|
144
|
+
mechanism: offer.mechanism,
|
|
145
|
+
recipientRef: offer.mechanism === 'claim-code' ? offer.claimCodeHash : offer.recipientIdentityKey,
|
|
146
|
+
},
|
|
147
|
+
acceptance: {
|
|
148
|
+
recipientIdentityKey: recipient.identityKey,
|
|
149
|
+
destinationKey: await recipient.controllerKey(offer.passportId),
|
|
150
|
+
acceptedAt: instant(),
|
|
151
|
+
evidenceKind: 'custodian-attested',
|
|
152
|
+
},
|
|
153
|
+
custodian: wallet.identityKey,
|
|
154
|
+
}
|
|
155
|
+
const record = await signManagedAcceptance(claim, wallet.acceptanceSigner)
|
|
156
|
+
const inspection = inspectManagedAcceptance(record, { custodians: [wallet.identityKey] })
|
|
157
|
+
if (!inspection.structureValid || !inspection.signatureValid || inspection.failures.length > 0) throw new WriteRefused('acceptance-invalid', `the acceptance record does not inspect clean: ${inspection.failures.map((f) => f.detail).join('; ')}`)
|
|
158
|
+
offer.status = 'accepted'
|
|
159
|
+
offer.record = record
|
|
160
|
+
await store.saveOffer(offer)
|
|
161
|
+
|
|
162
|
+
const outcome = await writer.transfer({
|
|
163
|
+
record: passport,
|
|
164
|
+
holder,
|
|
165
|
+
recipient,
|
|
166
|
+
acceptance: record,
|
|
167
|
+
eventData: { word: typeof offer.terms.word === 'string' ? offer.terms.word : 'Handed on' },
|
|
168
|
+
})
|
|
169
|
+
const mismatches = bindAcceptanceToState(record, outcome.state)
|
|
170
|
+
if (mismatches.length > 0) throw new WriteRefused('acceptance-mismatch', `the record does not bind to the TRANSFER: ${mismatches.map((m) => m.detail).join('; ')}`)
|
|
171
|
+
offer.status = 'transferred'
|
|
172
|
+
offer.transferTxid = outcome.entry.txid
|
|
173
|
+
await store.saveOffer(offer)
|
|
174
|
+
return { offer, record, transferTxid: outcome.entry.txid }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The party that controls the passport now, resolved from the journal's holder name. */
|
|
178
|
+
holderOf(passport: PassportRecord): Party {
|
|
179
|
+
const { parties } = this.options
|
|
180
|
+
const [scope, id] = passport.holder.party.split(':', 2)
|
|
181
|
+
if (scope === 'brand') return parties.brand(id)
|
|
182
|
+
if (scope === 'recipient') return parties.recipient(id)
|
|
183
|
+
if (scope === 'member') return parties.member(id)
|
|
184
|
+
throw new WriteRefused('holder-unknown', `the holder ${passport.holder.party} is not a managed identity this platform derives`)
|
|
185
|
+
}
|
|
186
|
+
}
|