@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,96 @@
|
|
|
1
|
+
// The reader: rebuild a passport's history from an index and verify it
|
|
2
|
+
// yourself. The index only finds the bytes; every signature, every link and
|
|
3
|
+
// every block proof is checked here, and the report says pass, fail, unknown
|
|
4
|
+
// or not-applicable for each check with a reason. Missing evidence stays
|
|
5
|
+
// unknown and is never treated as verified.
|
|
6
|
+
import { WhatsOnChain, type ChainTracker, type Transaction } from '@bsv/sdk'
|
|
7
|
+
import { EVIDENCE_CHECK_LABELS, findDppOutputs, verifyPassportEvidence, type EvidenceReport, type ManagedAcceptanceRecord } from '@bsv/dpp-protocol'
|
|
8
|
+
import type { Network } from './config.js'
|
|
9
|
+
import type { IndexClient } from './index-client.js'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Ask the header source one question at a time, a little apart, and keep
|
|
13
|
+
* each answer for the run: WhatsOnChain answers only a few requests a second.
|
|
14
|
+
*/
|
|
15
|
+
export function pacedTracker(inner: ChainTracker, gapMs = 400): ChainTracker {
|
|
16
|
+
const answers = new Map<string, Promise<unknown>>()
|
|
17
|
+
let queue: Promise<unknown> = Promise.resolve()
|
|
18
|
+
const ask = <T>(key: string, question: () => Promise<T>): Promise<T> => {
|
|
19
|
+
if (!answers.has(key)) {
|
|
20
|
+
const answer = queue.then(() => new Promise((wait) => setTimeout(wait, gapMs))).then(question)
|
|
21
|
+
queue = answer.catch(() => {})
|
|
22
|
+
answers.set(
|
|
23
|
+
key,
|
|
24
|
+
answer.catch((error: unknown) => {
|
|
25
|
+
answers.delete(key)
|
|
26
|
+
throw error
|
|
27
|
+
})
|
|
28
|
+
)
|
|
29
|
+
}
|
|
30
|
+
return answers.get(key) as Promise<T>
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
isValidRootForHeight: (root, height) => ask(`${height}:${root}`, () => inner.isValidRootForHeight(root, height)),
|
|
34
|
+
currentHeight: () => ask('height', () => inner.currentHeight()),
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function headerSource(network: Network, wocApiKey?: string): ChainTracker {
|
|
39
|
+
return pacedTracker(new WhatsOnChain(network, wocApiKey == null ? {} : { apiKey: wocApiKey }))
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface ReaderOptions {
|
|
43
|
+
index: IndexClient
|
|
44
|
+
/** 'scripts only' checks no inclusion; development and tests use it because nothing there is mined. */
|
|
45
|
+
chainTracker: ChainTracker | 'scripts only'
|
|
46
|
+
/** The custodians whose acceptance records this reader accepts: this platform's own key, and any it trusts. */
|
|
47
|
+
acceptanceCustodians?: string[]
|
|
48
|
+
/** The issuers whose genesis this reader accepts; empty accepts any. */
|
|
49
|
+
genesisIssuers?: string[]
|
|
50
|
+
policyId?: string
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface PassportReading {
|
|
54
|
+
passportId: string
|
|
55
|
+
lineage: Array<{ op: string; txid: string; timestamp: string; controllerKey: string; actorIdentityKey: string; payloadPublic: unknown }>
|
|
56
|
+
report: EvidenceReport
|
|
57
|
+
checks: Array<{ name: string; label: string; status: string; reasonCode?: string }>
|
|
58
|
+
publisherKeys: string[]
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function readPassport(passportId: string, options: ReaderOptions, evidence: { acceptanceRecords?: ManagedAcceptanceRecord[] } = {}): Promise<PassportReading> {
|
|
62
|
+
const publisherKeys = await options.index.publisherKeys()
|
|
63
|
+
const lineage: Transaction[] = await options.index.lineage(passportId)
|
|
64
|
+
if (lineage.length === 0) throw new Error(`the index holds nothing for ${passportId}`)
|
|
65
|
+
const report = await verifyPassportEvidence(
|
|
66
|
+
{ tokenHistory: lineage, acceptanceRecords: evidence.acceptanceRecords ?? [] },
|
|
67
|
+
{ passportId, source: 'request-context' },
|
|
68
|
+
{
|
|
69
|
+
policyId: options.policyId ?? 'managed-custody@1/application',
|
|
70
|
+
publisherKeys,
|
|
71
|
+
managedAcceptance: { required: true },
|
|
72
|
+
chainTracker: options.chainTracker,
|
|
73
|
+
authority: {
|
|
74
|
+
required: true,
|
|
75
|
+
...(options.genesisIssuers != null && options.genesisIssuers.length > 0 ? { genesisIssuers: options.genesisIssuers } : {}),
|
|
76
|
+
...(options.acceptanceCustodians != null ? { acceptanceCustodians: options.acceptanceCustodians } : {}),
|
|
77
|
+
},
|
|
78
|
+
}
|
|
79
|
+
)
|
|
80
|
+
return {
|
|
81
|
+
passportId,
|
|
82
|
+
lineage: lineage.map((tx) => {
|
|
83
|
+
const { state } = findDppOutputs(tx)[0]
|
|
84
|
+
let payloadPublic: unknown = state.payloadPublic
|
|
85
|
+
try {
|
|
86
|
+
payloadPublic = JSON.parse(state.payloadPublic)
|
|
87
|
+
} catch {
|
|
88
|
+
// Left as the string it is.
|
|
89
|
+
}
|
|
90
|
+
return { op: state.op, txid: tx.id('hex'), timestamp: state.timestamp, controllerKey: state.ownerIdentityKey, actorIdentityKey: state.actorIdentityKey, payloadPublic }
|
|
91
|
+
}),
|
|
92
|
+
report,
|
|
93
|
+
checks: report.checks.map((c) => ({ name: c.name, label: EVIDENCE_CHECK_LABELS[c.name], status: c.status, reasonCode: c.reasonCode })),
|
|
94
|
+
publisherKeys,
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
// The HTTP surface. JSON under /api; the built web app and the passport
|
|
2
|
+
// pages under everything else. Reads are open: anyone may verify a passport.
|
|
3
|
+
// Writes need a signed-in member of the brand that holds the passport, or,
|
|
4
|
+
// for a recipient under managed custody, the claim code they accepted with.
|
|
5
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import { Hash, Utils } from '@bsv/sdk'
|
|
8
|
+
import { verifyLifecycleClaim } from '@bsv/dpp-protocol'
|
|
9
|
+
import { readPublicPayloadSchema, readRestrictedPayloadSchema } from '@bsv/dpp-profiles'
|
|
10
|
+
import express, { type NextFunction, type Request, type Response } from 'express'
|
|
11
|
+
import { fromNodeHeaders, toNodeHandler } from 'better-auth/node'
|
|
12
|
+
import { sessionFrom, type Auth, type Session } from './auth.js'
|
|
13
|
+
import { EVENT_TYPES } from './claims.js'
|
|
14
|
+
import { isDemonstrationPolicy, mintPassportId } from './identifiers.js'
|
|
15
|
+
import type { Party } from './parties.js'
|
|
16
|
+
import type { Platform } from './platform.js'
|
|
17
|
+
import { currentProfiles, isProfileId, manifestFor, sampleWithProblems } from './profiles.js'
|
|
18
|
+
import type { PassportRecord, StateEntry } from './store.js'
|
|
19
|
+
import { pendingDuties, runDuties, summariseJournal } from './worker.js'
|
|
20
|
+
import { WriteRefused } from './writer.js'
|
|
21
|
+
|
|
22
|
+
export interface ServerOptions {
|
|
23
|
+
platform: Platform
|
|
24
|
+
auth?: Auth
|
|
25
|
+
/**
|
|
26
|
+
* Without sign-in (no MongoDB), every request is this developer, a member of
|
|
27
|
+
* one development brand. Never set in production: it is what makes
|
|
28
|
+
* `npm run dev` work with no services, and nothing else.
|
|
29
|
+
*/
|
|
30
|
+
devSession?: Session
|
|
31
|
+
/** The built web app to serve, when it exists. */
|
|
32
|
+
webDist?: string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
class HttpError extends Error {
|
|
36
|
+
constructor(
|
|
37
|
+
readonly status: number,
|
|
38
|
+
readonly code: string,
|
|
39
|
+
detail: string
|
|
40
|
+
) {
|
|
41
|
+
super(detail)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const sha256hex = (text: string): string => Utils.toHex(Hash.sha256(Utils.toArray(text, 'utf8')))
|
|
46
|
+
/** A URL-safe slug from a name: lower-case letters and digits with single hyphens, at most 64 characters, built without backtracking. */
|
|
47
|
+
function slugOf(name: string): string {
|
|
48
|
+
let slug = ''
|
|
49
|
+
let hyphen = false
|
|
50
|
+
for (const char of name.toLowerCase().slice(0, 128)) {
|
|
51
|
+
if (/[a-z0-9]/.test(char)) {
|
|
52
|
+
slug += char
|
|
53
|
+
hyphen = false
|
|
54
|
+
} else if (slug.length > 0 && !hyphen) {
|
|
55
|
+
slug += '-'
|
|
56
|
+
hyphen = true
|
|
57
|
+
}
|
|
58
|
+
if (slug.length >= 64) break
|
|
59
|
+
}
|
|
60
|
+
return slug.endsWith('-') ? slug.slice(0, -1) : slug
|
|
61
|
+
}
|
|
62
|
+
/** A route parameter as one string; Express 5 types it as possibly several. */
|
|
63
|
+
const param = (req: Request, name: string): string => {
|
|
64
|
+
const value = req.params[name]
|
|
65
|
+
return Array.isArray(value) ? value[0] : value
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** What a passport looks like over the API: the journal without the owner-tier ciphertext. */
|
|
69
|
+
function publicView(record: PassportRecord, policyIsDemo: boolean) {
|
|
70
|
+
const tip = record.states.at(-1)
|
|
71
|
+
let payload: unknown = tip?.payloadPublic
|
|
72
|
+
try {
|
|
73
|
+
payload = tip == null ? undefined : JSON.parse(tip.payloadPublic)
|
|
74
|
+
} catch {
|
|
75
|
+
// Left as the string it is.
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
passportId: record.passportId,
|
|
79
|
+
brandId: record.brandId,
|
|
80
|
+
profile: record.profile,
|
|
81
|
+
status: record.status,
|
|
82
|
+
demonstration: policyIsDemo,
|
|
83
|
+
holder: record.holder,
|
|
84
|
+
createdAt: record.createdAt,
|
|
85
|
+
payload,
|
|
86
|
+
journal: summariseJournal(record),
|
|
87
|
+
states: record.states.map((s: StateEntry) => ({
|
|
88
|
+
op: s.op,
|
|
89
|
+
txid: s.txid,
|
|
90
|
+
timestamp: s.timestamp,
|
|
91
|
+
actor: s.actor,
|
|
92
|
+
index: s.index,
|
|
93
|
+
refusal: s.refusal,
|
|
94
|
+
network: s.network,
|
|
95
|
+
proven: s.proof != null,
|
|
96
|
+
proofPushed: s.proofPushed === true,
|
|
97
|
+
blockHeight: s.proof?.blockHeight,
|
|
98
|
+
})),
|
|
99
|
+
acceptanceRecords: record.acceptanceRecords,
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function createServer(options: ServerOptions): express.Express {
|
|
104
|
+
const { platform, auth } = options
|
|
105
|
+
const { store, parties, writer, custody, claims, config } = platform
|
|
106
|
+
const policy = { host: config.passportHost, prefix: config.gs1Prefix }
|
|
107
|
+
const demo = isDemonstrationPolicy(policy)
|
|
108
|
+
const app = express()
|
|
109
|
+
app.disable('x-powered-by')
|
|
110
|
+
|
|
111
|
+
// Better Auth owns /api/auth; it must see the raw body, so it is mounted before the JSON parser.
|
|
112
|
+
if (auth != null) app.all('/api/auth/{*splat}', toNodeHandler(auth))
|
|
113
|
+
app.use(express.json({ limit: '1mb' }))
|
|
114
|
+
|
|
115
|
+
const wrap = (handler: (req: Request, res: Response) => Promise<unknown>) => (req: Request, res: Response, next: NextFunction) => {
|
|
116
|
+
handler(req, res).then((body) => {
|
|
117
|
+
if (!res.headersSent) res.json(body)
|
|
118
|
+
}, next)
|
|
119
|
+
}
|
|
120
|
+
const session = async (req: Request): Promise<Session | undefined> => (auth == null ? options.devSession : await sessionFrom(auth, req.headers))
|
|
121
|
+
const requireSession = async (req: Request): Promise<Session> => {
|
|
122
|
+
const s = await session(req)
|
|
123
|
+
if (s == null) throw new HttpError(401, 'sign-in-required', 'sign in first')
|
|
124
|
+
return s
|
|
125
|
+
}
|
|
126
|
+
const requireMember = async (req: Request, brandId: string): Promise<Session> => {
|
|
127
|
+
const s = await requireSession(req)
|
|
128
|
+
if (!s.brandIds.includes(brandId)) throw new HttpError(403, 'not-a-member', `you are not a member of brand ${brandId}`)
|
|
129
|
+
return s
|
|
130
|
+
}
|
|
131
|
+
const passportFrom = async (ref: string): Promise<PassportRecord> => {
|
|
132
|
+
const passportId = decodeURIComponent(ref)
|
|
133
|
+
const record = await store.getPassport(passportId)
|
|
134
|
+
if (record == null) throw new HttpError(404, 'passport-unknown', `no passport ${passportId} in this platform's journal`)
|
|
135
|
+
return record
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Who may act on a held passport: a member of the brand while the brand
|
|
139
|
+
* holds it; the recipient, with the claim code they accepted with, once a
|
|
140
|
+
* hand-on moved control to them.
|
|
141
|
+
*/
|
|
142
|
+
const actorFor = async (req: Request, record: PassportRecord): Promise<Party> => {
|
|
143
|
+
const [scope, id] = record.holder.party.split(':', 2)
|
|
144
|
+
if (scope === 'brand') {
|
|
145
|
+
await requireMember(req, record.brandId)
|
|
146
|
+
return parties.brand(id)
|
|
147
|
+
}
|
|
148
|
+
if (scope === 'recipient') {
|
|
149
|
+
const claimCode = typeof req.body?.claimCode === 'string' ? req.body.claimCode : undefined
|
|
150
|
+
const offer = await store.getOffer(id)
|
|
151
|
+
if (claimCode == null || offer?.claimCodeHash == null || sha256hex(claimCode) !== offer.claimCodeHash) throw new HttpError(403, 'claim-code-required', 'the holder acts with the claim code they accepted with')
|
|
152
|
+
return parties.recipient(id)
|
|
153
|
+
}
|
|
154
|
+
throw new HttpError(409, 'holder-unknown', `the holder ${record.holder.party} is not one this platform acts for`)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ------------------------------------------------------------------ open reads
|
|
158
|
+
|
|
159
|
+
app.get(
|
|
160
|
+
'/api/health',
|
|
161
|
+
wrap(async () => ({
|
|
162
|
+
ok: true,
|
|
163
|
+
network: config.network,
|
|
164
|
+
index: platform.index.url,
|
|
165
|
+
publisherKey: platform.wallet.identityKey,
|
|
166
|
+
wallet: platform.wallet.kind,
|
|
167
|
+
livePublishing: config.livePublishing,
|
|
168
|
+
identifiers: { host: policy.host, prefix: policy.prefix, demonstration: demo },
|
|
169
|
+
signIn: auth != null,
|
|
170
|
+
devSession: auth == null && options.devSession != null ? { name: options.devSession.name, brandIds: options.devSession.brandIds } : undefined,
|
|
171
|
+
}))
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
app.get('/api/profiles', wrap(async () => currentProfiles()))
|
|
175
|
+
app.get(
|
|
176
|
+
'/api/profiles/:id',
|
|
177
|
+
wrap(async (req) => {
|
|
178
|
+
const id = param(req, 'id')
|
|
179
|
+
if (!isProfileId(id)) throw new HttpError(404, 'profile-unknown', `${id} is not a profile this platform knows`)
|
|
180
|
+
const manifest = manifestFor(id)
|
|
181
|
+
return {
|
|
182
|
+
id,
|
|
183
|
+
title: manifest.title,
|
|
184
|
+
description: manifest.description,
|
|
185
|
+
fields: manifest.fields.map((f) => ({ key: f.key, label: f.label, valueType: f.valueType, unit: f.unit, accessTier: f.accessTier, obligation: f.obligation, cardinality: f.cardinality, codeList: f.codeList, constraints: f.constraints, note: f.note, group: f.group })),
|
|
186
|
+
publicSchema: readPublicPayloadSchema(id),
|
|
187
|
+
restrictedSchema: readRestrictedPayloadSchema(id),
|
|
188
|
+
...(() => {
|
|
189
|
+
const { payload, problems } = sampleWithProblems(id, demo)
|
|
190
|
+
return { sample: payload, sampleProblems: problems }
|
|
191
|
+
})(),
|
|
192
|
+
}
|
|
193
|
+
})
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
app.get(
|
|
197
|
+
'/api/verify',
|
|
198
|
+
wrap(async (req) => {
|
|
199
|
+
const passportId = typeof req.query.passportId === 'string' ? req.query.passportId : undefined
|
|
200
|
+
if (passportId == null) throw new HttpError(400, 'passport-id-required', 'give passportId')
|
|
201
|
+
try {
|
|
202
|
+
return await platform.read(passportId)
|
|
203
|
+
} catch (cause) {
|
|
204
|
+
throw new HttpError(404, 'not-found', cause instanceof Error ? cause.message : String(cause))
|
|
205
|
+
}
|
|
206
|
+
})
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
app.get('/api/passports/:ref', wrap(async (req) => publicView(await passportFrom(param(req, 'ref')), demo)))
|
|
210
|
+
app.get('/api/passports/:ref/claims', wrap(async (req) => (await store.listClaims({ passportId: (await passportFrom(param(req, 'ref'))).passportId })).map((c) => ({ ...c, verified: verifyLifecycleClaim(c.claim).signature }))))
|
|
211
|
+
|
|
212
|
+
app.get('/api/offers/:requestId', wrap(async (req) => await custody.preview(param(req, 'requestId'))))
|
|
213
|
+
app.post('/api/offers/:requestId/accept', wrap(async (req) => await custody.accept({ requestId: param(req, 'requestId'), claimCode: req.body?.claimCode })))
|
|
214
|
+
app.post('/api/offers/:requestId/decline', wrap(async (req) => await custody.decline(param(req, 'requestId'), req.body?.claimCode)))
|
|
215
|
+
|
|
216
|
+
// ------------------------------------------------------------------ signed in
|
|
217
|
+
|
|
218
|
+
app.get(
|
|
219
|
+
'/api/me',
|
|
220
|
+
wrap(async (req) => {
|
|
221
|
+
const s = await requireSession(req)
|
|
222
|
+
return { ...s, brands: await store.listBrands(s.brandIds) }
|
|
223
|
+
})
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
app.get('/api/brands', wrap(async (req) => await store.listBrands((await requireSession(req)).brandIds)))
|
|
227
|
+
app.post(
|
|
228
|
+
'/api/brands',
|
|
229
|
+
wrap(async (req) => {
|
|
230
|
+
const s = await requireSession(req)
|
|
231
|
+
const name = typeof req.body?.name === 'string' ? req.body.name.trim().slice(0, 128) : ''
|
|
232
|
+
if (name === '') throw new HttpError(400, 'name-required', 'a brand needs a name')
|
|
233
|
+
let id: string
|
|
234
|
+
if (auth == null) {
|
|
235
|
+
// Development without sign-in: one brand per name, owned by the development session.
|
|
236
|
+
id = `dev-${slugOf(name)}`
|
|
237
|
+
if (!s.brandIds.includes(id)) s.brandIds.push(id)
|
|
238
|
+
} else {
|
|
239
|
+
const slug = `${slugOf(name)}-${Date.now().toString(36)}`
|
|
240
|
+
const organisation = await auth.api.createOrganization({ body: { name, slug }, headers: fromNodeHeaders(req.headers) })
|
|
241
|
+
if (organisation == null) throw new HttpError(500, 'brand-not-created', 'the organisation was not created')
|
|
242
|
+
id = organisation.id
|
|
243
|
+
}
|
|
244
|
+
const party = parties.brand(id)
|
|
245
|
+
const brand = { id, name, identityKey: party.identityKey, did: party.did, createdAt: new Date().toISOString() }
|
|
246
|
+
await store.saveBrand(brand)
|
|
247
|
+
return brand
|
|
248
|
+
})
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
app.get(
|
|
252
|
+
'/api/brands/:brandId/passports',
|
|
253
|
+
wrap(async (req) => {
|
|
254
|
+
await requireMember(req, param(req, 'brandId'))
|
|
255
|
+
return (await store.listPassports({ brandId: param(req, 'brandId') })).map((p) => publicView(p, demo))
|
|
256
|
+
})
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
app.post(
|
|
260
|
+
'/api/brands/:brandId/passports',
|
|
261
|
+
wrap(async (req) => {
|
|
262
|
+
const brandId = param(req, 'brandId')
|
|
263
|
+
await requireMember(req, brandId)
|
|
264
|
+
const brandRecord = await store.getBrand(brandId)
|
|
265
|
+
if (brandRecord == null) throw new HttpError(404, 'brand-unknown', `no brand ${brandId}`)
|
|
266
|
+
const { profile, itemReference, serial, payload, ownerFields } = req.body ?? {}
|
|
267
|
+
if (!isProfileId(profile)) throw new HttpError(400, 'profile-unknown', `${profile} is not a profile this platform knows`)
|
|
268
|
+
if (typeof itemReference !== 'string' || typeof serial !== 'string') throw new HttpError(400, 'identifier-required', 'give itemReference (digits) and serial')
|
|
269
|
+
const passportId = mintPassportId(policy, itemReference, serial)
|
|
270
|
+
const outcome = await writer.issue({ brandId, brand: parties.brand(brandId), passportId, profile, payload: payload ?? {}, ownerFields: ownerFields ?? {} })
|
|
271
|
+
return publicView(outcome.record, demo)
|
|
272
|
+
})
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
app.post(
|
|
276
|
+
'/api/passports/:ref/update',
|
|
277
|
+
wrap(async (req) => {
|
|
278
|
+
const record = await passportFrom(param(req, 'ref'))
|
|
279
|
+
const actor = await actorFor(req, record)
|
|
280
|
+
// ownerFields absent carries the current owner tier unchanged; {} seals an empty one.
|
|
281
|
+
const ownerFields = typeof req.body?.ownerFields === 'object' && req.body.ownerFields != null ? req.body.ownerFields : undefined
|
|
282
|
+
const outcome = await writer.update({ record, actor, payload: req.body?.payload ?? {}, ownerFields, eventData: req.body?.eventData })
|
|
283
|
+
return publicView(outcome.record, demo)
|
|
284
|
+
})
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
app.post(
|
|
288
|
+
'/api/passports/:ref/offer',
|
|
289
|
+
wrap(async (req) => {
|
|
290
|
+
const record = await passportFrom(param(req, 'ref'))
|
|
291
|
+
const holder = await actorFor(req, record)
|
|
292
|
+
const terms = typeof req.body?.terms === 'object' && req.body.terms != null ? req.body.terms : { word: 'Handed on' }
|
|
293
|
+
return await custody.offer({ record, holder, terms, mechanism: req.body?.mechanism, recipientIdentityKey: req.body?.recipientIdentityKey })
|
|
294
|
+
})
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
app.post(
|
|
298
|
+
'/api/offers/:requestId/withdraw',
|
|
299
|
+
wrap(async (req) => {
|
|
300
|
+
const offer = await store.getOffer(param(req, 'requestId'))
|
|
301
|
+
if (offer == null) throw new HttpError(404, 'offer-unknown', `no offer ${param(req, 'requestId')}`)
|
|
302
|
+
const record = await passportFrom(encodeURIComponent(offer.passportId))
|
|
303
|
+
const holder = await actorFor(req, record)
|
|
304
|
+
return await custody.withdraw(param(req, 'requestId'), holder)
|
|
305
|
+
})
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
app.get(
|
|
309
|
+
'/api/passports/:ref/offers',
|
|
310
|
+
wrap(async (req) => {
|
|
311
|
+
const record = await passportFrom(param(req, 'ref'))
|
|
312
|
+
await requireMember(req, record.brandId)
|
|
313
|
+
return (await store.listOffers({ passportId: record.passportId })).map(({ claimCodeHash: _hidden, ...offer }) => offer)
|
|
314
|
+
})
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
app.post(
|
|
318
|
+
'/api/passports/:ref/retire',
|
|
319
|
+
wrap(async (req) => {
|
|
320
|
+
const record = await passportFrom(param(req, 'ref'))
|
|
321
|
+
const actor = await actorFor(req, record)
|
|
322
|
+
const reason = typeof req.body?.reason === 'string' ? req.body.reason : 'retired'
|
|
323
|
+
const outcome = await writer.retire({ record, actor, reason })
|
|
324
|
+
return publicView(outcome.record, demo)
|
|
325
|
+
})
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
app.post(
|
|
329
|
+
'/api/passports/:ref/states/:txid/resolve',
|
|
330
|
+
wrap(async (req) => {
|
|
331
|
+
const record = await passportFrom(param(req, 'ref'))
|
|
332
|
+
await requireMember(req, record.brandId)
|
|
333
|
+
const outcome = req.body?.outcome
|
|
334
|
+
if (outcome !== 'sent' && outcome !== 'abandoned') throw new HttpError(400, 'outcome-required', "outcome must be 'sent' or 'abandoned'")
|
|
335
|
+
return publicView(await writer.resolveInterrupted(record, param(req, 'txid'), outcome), demo)
|
|
336
|
+
})
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
app.post(
|
|
340
|
+
'/api/passports/:ref/claims',
|
|
341
|
+
wrap(async (req) => {
|
|
342
|
+
const s = await requireSession(req)
|
|
343
|
+
const record = await passportFrom(param(req, 'ref'))
|
|
344
|
+
const eventType = req.body?.eventType
|
|
345
|
+
if (!EVENT_TYPES.includes(eventType)) throw new HttpError(400, 'event-type-unknown', `eventType must be one of ${EVENT_TYPES.join(', ')}`)
|
|
346
|
+
const issuer = parties.member(s.userId)
|
|
347
|
+
let claim = await claims.sign({ passport: record, issuer, eventType, keyId: s.email })
|
|
348
|
+
if (req.body?.submit === true) claim = await claims.submit(claim)
|
|
349
|
+
return { ...claim, verified: verifyLifecycleClaim(claim.claim).signature }
|
|
350
|
+
})
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
app.get(
|
|
354
|
+
'/api/operations',
|
|
355
|
+
wrap(async (req) => {
|
|
356
|
+
await requireSession(req)
|
|
357
|
+
return { duties: await pendingDuties(store), passports: (await store.listPassports()).map((p) => ({ passportId: p.passportId, brandId: p.brandId, status: p.status, journal: summariseJournal(p) })) }
|
|
358
|
+
})
|
|
359
|
+
)
|
|
360
|
+
app.post(
|
|
361
|
+
'/api/operations/run',
|
|
362
|
+
wrap(async (req) => {
|
|
363
|
+
await requireSession(req)
|
|
364
|
+
return { done: await runDuties({ store, index: platform.index, writer }) }
|
|
365
|
+
})
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
app.get(
|
|
369
|
+
'/api/wallet',
|
|
370
|
+
wrap(async (req) => {
|
|
371
|
+
await requireSession(req)
|
|
372
|
+
return { kind: platform.wallet.kind, network: config.network, identityKey: platform.wallet.identityKey, balance: await platform.wallet.balance(), livePublishing: config.livePublishing }
|
|
373
|
+
})
|
|
374
|
+
)
|
|
375
|
+
app.post(
|
|
376
|
+
'/api/wallet/funding-address',
|
|
377
|
+
wrap(async (req) => {
|
|
378
|
+
await requireSession(req)
|
|
379
|
+
return await platform.wallet.fundingAddress()
|
|
380
|
+
})
|
|
381
|
+
)
|
|
382
|
+
app.post(
|
|
383
|
+
'/api/wallet/internalize',
|
|
384
|
+
wrap(async (req) => {
|
|
385
|
+
await requireSession(req)
|
|
386
|
+
const { txid, funding } = req.body ?? {}
|
|
387
|
+
if (typeof txid !== 'string' || typeof funding !== 'object') throw new HttpError(400, 'funding-required', 'give the txid and the funding address record it paid')
|
|
388
|
+
return await platform.wallet.internalize(funding, txid)
|
|
389
|
+
})
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
// ------------------------------------------------------------------ the web app
|
|
393
|
+
|
|
394
|
+
const webDist = options.webDist
|
|
395
|
+
if (webDist != null && existsSync(join(webDist, 'index.html'))) {
|
|
396
|
+
app.use(express.static(webDist, { index: false }))
|
|
397
|
+
// The passport page lives at the identifier's own path, and every other path is the single-page app's. Its shell is read once, not per request.
|
|
398
|
+
const shell = readFileSync(join(webDist, 'index.html'), 'utf8')
|
|
399
|
+
app.get('/{*splat}', (req, res, next) => {
|
|
400
|
+
if (req.path.startsWith('/api/')) return next()
|
|
401
|
+
res.type('html').send(shell)
|
|
402
|
+
})
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
app.use((error: unknown, _req: Request, res: Response, _next: NextFunction) => {
|
|
406
|
+
if (error instanceof HttpError) {
|
|
407
|
+
res.status(error.status).json({ error: error.code, description: error.message })
|
|
408
|
+
return
|
|
409
|
+
}
|
|
410
|
+
if (error instanceof WriteRefused) {
|
|
411
|
+
res.status(error.code.endsWith('-unknown') ? 404 : 409).json({ error: error.code, description: error.message })
|
|
412
|
+
return
|
|
413
|
+
}
|
|
414
|
+
const description = error instanceof Error ? error.message : String(error)
|
|
415
|
+
console.error('request failed:', error)
|
|
416
|
+
res.status(500).json({ error: 'internal', description })
|
|
417
|
+
})
|
|
418
|
+
|
|
419
|
+
return app
|
|
420
|
+
}
|