@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,71 @@
|
|
|
1
|
+
// An index in this process for development and tests: the real topic
|
|
2
|
+
// manager, lookup service and HTTP host the reference deployment runs, over
|
|
3
|
+
// in-memory storage, on a loopback port, with a publisher policy naming the
|
|
4
|
+
// platform wallet and the managed-custody profile selected. Its header
|
|
5
|
+
// checks are off, so it takes the made-up proofs a dry run pushes and claims
|
|
6
|
+
// no inclusion. Production runs the reference index as its own service
|
|
7
|
+
// (a separate operator project or an existing provider) and never this.
|
|
8
|
+
//
|
|
9
|
+
// The HTTP host is the package's ./server export. Imported, it is a library
|
|
10
|
+
// and starts nothing by itself.
|
|
11
|
+
import { PrivateKey } from '@bsv/sdk'
|
|
12
|
+
import { policySigningPreimage, type PublisherPolicy } from '@bsv/dpp-protocol'
|
|
13
|
+
|
|
14
|
+
export interface DevIndex {
|
|
15
|
+
url: string
|
|
16
|
+
submitToken: string
|
|
17
|
+
callbackToken: string
|
|
18
|
+
close: () => Promise<void>
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function startDevIndex(publisherKey: string): Promise<DevIndex> {
|
|
22
|
+
const overlay = await import('@bsv/overlay')
|
|
23
|
+
const topics = await import('@bsv/dpp-overlay')
|
|
24
|
+
const host = await import('@bsv/dpp-overlay/server')
|
|
25
|
+
|
|
26
|
+
// The policy chain of spec/services.md section 1: one operator signs a genesis naming the platform wallet as a state publisher.
|
|
27
|
+
const operatorKey = PrivateKey.fromHex('44'.repeat(32))
|
|
28
|
+
const operator = 'Development operator'
|
|
29
|
+
const genesis: PublisherPolicy = {
|
|
30
|
+
policyFormat: 'dpp-publisher-policy@1',
|
|
31
|
+
policyVersion: 1,
|
|
32
|
+
scope: { operatorProfile: 'single-operator@1', operators: [operator], topics: ['tm_dpp'] },
|
|
33
|
+
issuedAt: '2026-01-01T00:00:00Z',
|
|
34
|
+
publishers: [{ key: publisherKey, role: 'state-publisher', activeFrom: '2026-01-01T00:00:00Z' }],
|
|
35
|
+
authorisation: { kind: 'genesis', signer: operatorKey.toPublicKey().toString(), suite: 'bsv-ecdsa-der', value: '' },
|
|
36
|
+
}
|
|
37
|
+
genesis.authorisation.value = operatorKey.sign(policySigningPreimage(genesis)).toDER('hex') as string
|
|
38
|
+
const policy = topics.loadPublisherPolicyJson(JSON.stringify([genesis]), { [operator]: operatorKey.toPublicKey().toString() })
|
|
39
|
+
|
|
40
|
+
const records = new topics.InMemoryDppStorage()
|
|
41
|
+
const storage = new topics.InMemoryOverlayStorage()
|
|
42
|
+
const lookupServices = { ls_dpp: new topics.DppLookupService(records) }
|
|
43
|
+
const silent = { ...console, log() {}, info() {}, warn() {}, error() {} }
|
|
44
|
+
const engine = new overlay.Engine(
|
|
45
|
+
{ tm_dpp: new topics.DppTopicManager('', { publisherPolicy: policy.chain, managedAcceptance: true, admittedOutputs: storage }) },
|
|
46
|
+
lookupServices,
|
|
47
|
+
storage,
|
|
48
|
+
'scripts only',
|
|
49
|
+
undefined,
|
|
50
|
+
undefined,
|
|
51
|
+
undefined,
|
|
52
|
+
undefined,
|
|
53
|
+
undefined,
|
|
54
|
+
{ tm_dpp: false },
|
|
55
|
+
false,
|
|
56
|
+
'[index] ',
|
|
57
|
+
false,
|
|
58
|
+
undefined,
|
|
59
|
+
silent
|
|
60
|
+
)
|
|
61
|
+
const submitToken = 'dev-submit-token'
|
|
62
|
+
const callbackToken = 'dev-callback-token'
|
|
63
|
+
const service = await host.startOverlayService(engine, {
|
|
64
|
+
port: 0,
|
|
65
|
+
host: '127.0.0.1',
|
|
66
|
+
submitToken,
|
|
67
|
+
proofToken: callbackToken,
|
|
68
|
+
components: { records, engineStorage: storage, lookupServices, publisherPolicy: policy, managedAcceptance: true },
|
|
69
|
+
})
|
|
70
|
+
return { url: `http://127.0.0.1:${service.port}`, submitToken, callbackToken, close: service.close }
|
|
71
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Read the project's .env before anything reads the environment, so the npm
|
|
2
|
+
// scripts (dev, start, wallet, operations) see the same settings Docker passes
|
|
3
|
+
// with --env-file. Settings already in the environment win. Tests pass their
|
|
4
|
+
// own settings to loadConfig and never read the file.
|
|
5
|
+
import { existsSync } from 'node:fs'
|
|
6
|
+
import { dirname, resolve } from 'node:path'
|
|
7
|
+
import { fileURLToPath } from 'node:url'
|
|
8
|
+
|
|
9
|
+
const file = resolve(dirname(fileURLToPath(import.meta.url)), '../../../.env')
|
|
10
|
+
if (existsSync(file)) {
|
|
11
|
+
const before = { ...process.env }
|
|
12
|
+
process.loadEnvFile(file)
|
|
13
|
+
for (const [key, value] of Object.entries(before)) if (value !== undefined) process.env[key] = value
|
|
14
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Passport identifiers: GS1 Digital Links of the form
|
|
2
|
+
// https://<host>/01/<GTIN-14>/21/<serial>, minted under one GS1 company
|
|
3
|
+
// prefix. The default prefix, 952, is GS1's demonstration prefix, never
|
|
4
|
+
// licensed to anyone, so nothing real stands behind it. A state written under
|
|
5
|
+
// a GTIN you did not allocate is permanent and cannot be withdrawn, which is
|
|
6
|
+
// why every identifier is checked against the configured prefix before a
|
|
7
|
+
// write, and why the demonstration notice is carried while the prefix is 952.
|
|
8
|
+
import { GS1_DEMONSTRATION_PREFIX, buildGs1DigitalLink, gs1CheckDigit, gtin14, parseGs1DigitalLink } from '@bsv/dpp-profiles'
|
|
9
|
+
|
|
10
|
+
export interface IdentifierPolicy {
|
|
11
|
+
host: string
|
|
12
|
+
prefix: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const isDemonstrationPolicy = (policy: IdentifierPolicy): boolean => policy.prefix === GS1_DEMONSTRATION_PREFIX
|
|
16
|
+
|
|
17
|
+
/** The item reference digits that, with the prefix and the check digit, make a GTIN-13 for the host's prefix. */
|
|
18
|
+
export function mintGtin(prefix: string, itemReference: string): string {
|
|
19
|
+
if (!/^\d+$/.test(prefix) || !/^\d+$/.test(itemReference)) throw new Error('a GTIN is digits only')
|
|
20
|
+
const body = `${prefix}${itemReference}`
|
|
21
|
+
if (body.length !== 12) throw new Error(`prefix and item reference must total 12 digits, not ${body.length}`)
|
|
22
|
+
const data = `0${body}`
|
|
23
|
+
return data + gs1CheckDigit(data)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A fresh identifier for a serialised item under the policy's host and prefix. */
|
|
27
|
+
export function mintPassportId(policy: IdentifierPolicy, itemReference: string, serial: string): string {
|
|
28
|
+
if (!/^[A-Za-z0-9!"%&'()*+,\-./:;<=>?_]{1,20}$/.test(serial)) throw new Error('a serial is 1 to 20 characters of the GS1 encodable set')
|
|
29
|
+
return buildGs1DigitalLink(policy.host, mintGtin(policy.prefix, itemReference), serial)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Why a write under this identifier is refused; empty when it may be written. */
|
|
33
|
+
export function identifierProblems(passportId: string, policy: IdentifierPolicy): string[] {
|
|
34
|
+
let url: URL
|
|
35
|
+
let link: ReturnType<typeof parseGs1DigitalLink>
|
|
36
|
+
try {
|
|
37
|
+
url = new URL(passportId)
|
|
38
|
+
link = parseGs1DigitalLink(passportId)
|
|
39
|
+
} catch (cause) {
|
|
40
|
+
return [`it is not a GS1 Digital Link (${cause instanceof Error ? cause.message : String(cause)})`]
|
|
41
|
+
}
|
|
42
|
+
const problems: string[] = []
|
|
43
|
+
if (url.search !== '' || url.hash !== '') problems.push('it carries a query or a fragment')
|
|
44
|
+
if (!link.checkDigitValid) problems.push('its GTIN check digit does not hold')
|
|
45
|
+
if (link.serial == null) problems.push('it has no serial under application identifier 21')
|
|
46
|
+
if (link.host === 'id.gs1.org') problems.push("its host is GS1's own resolver, not a host you control")
|
|
47
|
+
if (link.host !== policy.host) problems.push(`its host is ${link.host}, not this platform's ${policy.host}`)
|
|
48
|
+
const digits = gtin14(link.gtin)
|
|
49
|
+
if (!digits.slice(1).startsWith(policy.prefix)) {
|
|
50
|
+
problems.push(
|
|
51
|
+
isDemonstrationPolicy(policy)
|
|
52
|
+
? `its GTIN is not under the GS1 demonstration prefix ${GS1_DEMONSTRATION_PREFIX}, so it would name a product someone else may own`
|
|
53
|
+
: `its GTIN is not under this platform's licensed prefix ${policy.prefix}`
|
|
54
|
+
)
|
|
55
|
+
}
|
|
56
|
+
return problems
|
|
57
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// The index (overlay) over its HTTP contract: capabilities, lookup, submit,
|
|
2
|
+
// retract and proof delivery. Only an answer refuses: an index that cannot
|
|
3
|
+
// be reached refuses nothing, and the writer sends anyway and announces the
|
|
4
|
+
// same bytes again later. A 401 or 403 is this platform's own configuration
|
|
5
|
+
// and stops a write while the state is still a draft.
|
|
6
|
+
import { Beef, type MerklePath, type Transaction } from '@bsv/sdk'
|
|
7
|
+
import { chainFromBeef } from '@bsv/dpp-protocol'
|
|
8
|
+
|
|
9
|
+
export type Announcement = 'admitted' | 'duplicate' | 'refused' | 'unauthorised' | 'unreachable'
|
|
10
|
+
|
|
11
|
+
export interface CapabilityDocument {
|
|
12
|
+
implementation?: { name: string; version: string }
|
|
13
|
+
publisherPolicy?: { publisherKeys: string[]; anchoringServices?: string[] }
|
|
14
|
+
profiles?: Array<{ id: string; version: string; kind: string; options?: Record<string, unknown> }>
|
|
15
|
+
[key: string]: unknown
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface IndexClientOptions {
|
|
19
|
+
url: string
|
|
20
|
+
submitToken?: string
|
|
21
|
+
callbackToken?: string
|
|
22
|
+
/** Silence the in-process index's logging during a call; tests use it. */
|
|
23
|
+
quiet?: boolean
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class IndexClient {
|
|
27
|
+
readonly url: string
|
|
28
|
+
private submitToken?: string
|
|
29
|
+
private callbackToken?: string
|
|
30
|
+
/** The last refusal reason the index gave in X-Admission-Refusal, for the journal. */
|
|
31
|
+
lastRefusal: string | undefined
|
|
32
|
+
|
|
33
|
+
constructor(options: IndexClientOptions) {
|
|
34
|
+
this.url = options.url.replace(/\/+$/, '')
|
|
35
|
+
this.submitToken = options.submitToken
|
|
36
|
+
this.callbackToken = options.callbackToken
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
private async request(path: string, init?: RequestInit): Promise<Response> {
|
|
40
|
+
return await fetch(`${this.url}${path}`, init)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async capabilities(): Promise<CapabilityDocument> {
|
|
44
|
+
const response = await this.request('/capabilities')
|
|
45
|
+
if (!response.ok) throw new Error(`the index answered HTTP ${response.status} to GET /capabilities`)
|
|
46
|
+
return (await response.json()) as CapabilityDocument
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The publisher keys the index admits, from its own capability document. */
|
|
50
|
+
async publisherKeys(): Promise<string[]> {
|
|
51
|
+
const document = await this.capabilities()
|
|
52
|
+
return document.publisherPolicy?.publisherKeys ?? []
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The lineage the index holds for the passport, genesis first, or an empty list. */
|
|
56
|
+
async lineage(passportId: string): Promise<Transaction[]> {
|
|
57
|
+
const response = await this.request('/lookup', {
|
|
58
|
+
method: 'POST',
|
|
59
|
+
headers: { 'Content-Type': 'application/json' },
|
|
60
|
+
body: JSON.stringify({ service: 'ls_dpp', query: { passportId } }),
|
|
61
|
+
})
|
|
62
|
+
if (!response.ok) throw new Error(`the index answered HTTP ${response.status} to the lookup`)
|
|
63
|
+
const { outputs } = (await response.json()) as { outputs: Array<{ beef: number[] }> }
|
|
64
|
+
if (outputs.length === 0) return []
|
|
65
|
+
const merged = Beef.fromBinary(outputs[0].beef)
|
|
66
|
+
for (const output of outputs.slice(1)) merged.mergeBeef(output.beef)
|
|
67
|
+
return chainFromBeef(merged, passportId)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Announce an unsent transaction (spec/writing.md section 3). */
|
|
71
|
+
async announce(beef: number[]): Promise<Announcement> {
|
|
72
|
+
this.lastRefusal = undefined
|
|
73
|
+
let response: Response
|
|
74
|
+
try {
|
|
75
|
+
response = await this.request('/submit', {
|
|
76
|
+
method: 'POST',
|
|
77
|
+
headers: {
|
|
78
|
+
'Content-Type': 'application/octet-stream',
|
|
79
|
+
'X-Topics': JSON.stringify(['tm_dpp']),
|
|
80
|
+
...(this.submitToken != null ? { Authorization: `Bearer ${this.submitToken}` } : {}),
|
|
81
|
+
},
|
|
82
|
+
body: new Uint8Array(beef),
|
|
83
|
+
})
|
|
84
|
+
} catch {
|
|
85
|
+
return 'unreachable'
|
|
86
|
+
}
|
|
87
|
+
if (response.status === 401 || response.status === 403) return 'unauthorised'
|
|
88
|
+
if (response.status === 400) {
|
|
89
|
+
const body = (await response.json().catch(() => ({}))) as { description?: string }
|
|
90
|
+
this.lastRefusal = body.description ?? 'no reason given'
|
|
91
|
+
return 'refused'
|
|
92
|
+
}
|
|
93
|
+
if (!response.ok) return 'unreachable'
|
|
94
|
+
const admission = response.headers.get('x-admission') ?? ''
|
|
95
|
+
if (admission.includes('tm_dpp=none')) {
|
|
96
|
+
this.lastRefusal = response.headers.get('x-admission-refusal') ?? 'no reason given'
|
|
97
|
+
return 'refused'
|
|
98
|
+
}
|
|
99
|
+
if (admission.includes('duplicate')) return 'duplicate'
|
|
100
|
+
return 'admitted'
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Withdraw a state the network refused after the index admitted it. */
|
|
104
|
+
async retract(txid: string, reason: string): Promise<{ ok: boolean; detail: string }> {
|
|
105
|
+
let response: Response
|
|
106
|
+
try {
|
|
107
|
+
response = await this.request('/retract', {
|
|
108
|
+
method: 'POST',
|
|
109
|
+
headers: { 'Content-Type': 'application/json', ...(this.submitToken != null ? { Authorization: `Bearer ${this.submitToken}` } : {}) },
|
|
110
|
+
body: JSON.stringify({ txid, outputIndex: 0, reason }),
|
|
111
|
+
})
|
|
112
|
+
} catch (cause) {
|
|
113
|
+
return { ok: false, detail: `the index could not be reached (${cause instanceof Error ? cause.message : String(cause)})` }
|
|
114
|
+
}
|
|
115
|
+
const body = (await response.json().catch(() => ({}))) as { status?: string; error?: string; description?: string }
|
|
116
|
+
const ok = response.ok && body.status === 'retracted'
|
|
117
|
+
return { ok, detail: ok ? 'retracted' : `HTTP ${response.status}${body.error != null ? ` ${body.error}` : ''}${body.description != null ? `, ${body.description}` : ''}` }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Offer a merkle path to the index, in the shape a broadcaster's callback carries (section 7). */
|
|
121
|
+
async pushProof(txid: string, path: MerklePath): Promise<{ ok: boolean; detail: string }> {
|
|
122
|
+
let response: Response
|
|
123
|
+
try {
|
|
124
|
+
response = await this.request('/arc-ingest', {
|
|
125
|
+
method: 'POST',
|
|
126
|
+
headers: { 'Content-Type': 'application/json', ...(this.callbackToken != null ? { 'X-Callback-Token': this.callbackToken } : {}) },
|
|
127
|
+
body: JSON.stringify({ txid, merklePath: path.toHex(), blockHeight: path.blockHeight }),
|
|
128
|
+
})
|
|
129
|
+
} catch (cause) {
|
|
130
|
+
return { ok: false, detail: `the index could not be reached (${cause instanceof Error ? cause.message : String(cause)})` }
|
|
131
|
+
}
|
|
132
|
+
const body = (await response.json().catch(() => ({}))) as { status?: string; description?: string }
|
|
133
|
+
const ok = response.ok && body.status === 'applied'
|
|
134
|
+
return { ok, detail: body.status ?? `HTTP ${response.status}${body.description != null ? `, ${body.description}` : ''}` }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Boot: configuration, the platform, sign-in, the HTTP server and the worker
|
|
2
|
+
// loop, in one process. Scale by running more API processes and exactly one
|
|
3
|
+
// worker (WORKER=only runs the loop alone; WORKER=off runs the API alone).
|
|
4
|
+
import './env.js'
|
|
5
|
+
import { existsSync } from 'node:fs'
|
|
6
|
+
import { dirname, join } from 'node:path'
|
|
7
|
+
import { fileURLToPath } from 'node:url'
|
|
8
|
+
import { createAuth } from './auth.js'
|
|
9
|
+
import { loadConfig } from './config.js'
|
|
10
|
+
import { openPlatform } from './platform.js'
|
|
11
|
+
import { createServer } from './server.js'
|
|
12
|
+
import { startWorker } from './worker.js'
|
|
13
|
+
|
|
14
|
+
const config = loadConfig()
|
|
15
|
+
const role = process.env.WORKER ?? 'with-api'
|
|
16
|
+
const platform = await openPlatform({ config, mode: 'live' })
|
|
17
|
+
|
|
18
|
+
const auth = platform.db == null ? undefined : createAuth({ db: platform.db, secret: config.authSecret, baseURL: config.publicUrl, trustedOrigins: ['http://localhost:5173'] })
|
|
19
|
+
// No MongoDB means no sign-in: a development session stands in, with one development brand, so the pages work with no services.
|
|
20
|
+
const devSession = auth != null || process.env.NODE_ENV === 'production' ? undefined : { userId: 'developer', email: 'developer@localhost', name: 'Developer', brandIds: ['dev-brand'] }
|
|
21
|
+
if (devSession != null) {
|
|
22
|
+
const party = platform.parties.brand('dev-brand')
|
|
23
|
+
await platform.store.saveBrand({ id: 'dev-brand', name: 'Development brand', identityKey: party.identityKey, did: party.did, createdAt: new Date().toISOString() })
|
|
24
|
+
console.log('Sign-in is off: every request is the developer, a member of "Development brand". Configure MongoDB for sign-in and persistence.')
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
let server: ReturnType<ReturnType<typeof createServer>['listen']> | undefined
|
|
28
|
+
if (role !== 'only') {
|
|
29
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
30
|
+
const candidates = [join(here, '..', '..', 'web', 'dist'), join(process.cwd(), 'apps', 'web', 'dist')]
|
|
31
|
+
const webDist = candidates.find((path) => existsSync(join(path, 'index.html')))
|
|
32
|
+
const app = createServer({ platform, auth, devSession, webDist })
|
|
33
|
+
server = app.listen(config.port, () => {
|
|
34
|
+
console.log(`API on http://localhost:${config.port}${webDist == null ? ' (no built web app; run the Vite dev server for the pages)' : ', serving the web app'}`)
|
|
35
|
+
})
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const worker = role === 'off' ? undefined : startWorker({ store: platform.store, index: platform.index, writer: platform.writer, intervalMs: 60_000, log: (line) => console.log(`[worker] ${line}`) })
|
|
39
|
+
|
|
40
|
+
let stopping = false
|
|
41
|
+
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
|
42
|
+
process.on(signal, () => {
|
|
43
|
+
if (stopping) return
|
|
44
|
+
stopping = true
|
|
45
|
+
console.log(`${signal} received, stopping`)
|
|
46
|
+
worker?.stop()
|
|
47
|
+
server?.close()
|
|
48
|
+
void platform.close().finally(() => process.exit(0))
|
|
49
|
+
})
|
|
50
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Who signs. Under managed custody the platform holds every key: the
|
|
2
|
+
// custodian (the platform wallet) publishes every state, holds the lock and
|
|
3
|
+
// signs acceptance records; brands, recipients and members are managed
|
|
4
|
+
// identities the platform derives from a secret. The `Party` interface is
|
|
5
|
+
// the seam: a later implementation can be a person's own BRC-100 wallet,
|
|
6
|
+
// which the standard allows for every role, without changing the writer.
|
|
7
|
+
import { CachedKeyDeriver, Hash, PrivateKey, ProtoWallet, Utils } from '@bsv/sdk'
|
|
8
|
+
import { didKeyFromIdentityKey, ownerKeyFromDeriver, ownerLinkageFromDeriver } from '@bsv/dpp-protocol'
|
|
9
|
+
|
|
10
|
+
/** The slice of a BRC-100 wallet the @bsv/dpp packages call on an actor or controller. */
|
|
11
|
+
export interface PartyWallet {
|
|
12
|
+
getPublicKey: ProtoWallet['getPublicKey']
|
|
13
|
+
createSignature: ProtoWallet['createSignature']
|
|
14
|
+
encrypt: ProtoWallet['encrypt']
|
|
15
|
+
decrypt: ProtoWallet['decrypt']
|
|
16
|
+
revealSpecificKeyLinkage: ProtoWallet['revealSpecificKeyLinkage']
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface Party {
|
|
20
|
+
/** A label for the journal, never shown as proof of anything. */
|
|
21
|
+
name: string
|
|
22
|
+
/** Compressed public key, hex. */
|
|
23
|
+
identityKey: string
|
|
24
|
+
/** did:key form of the identity key, the issuer of claims. */
|
|
25
|
+
did: string
|
|
26
|
+
wallet: PartyWallet
|
|
27
|
+
/** Field 6 when this party controls the passport: one derivation below the identity key, per passport. */
|
|
28
|
+
controllerKey(passportId: string): Promise<string>
|
|
29
|
+
/** The BRC-69 scalar proving this party derived that controller key: the control proof a later state carries. */
|
|
30
|
+
controlLinkage(passportId: string): Promise<string>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A party whose root key the platform holds. */
|
|
34
|
+
export function managedParty(name: string, key: PrivateKey): Party {
|
|
35
|
+
const deriver = new CachedKeyDeriver(key)
|
|
36
|
+
return {
|
|
37
|
+
name,
|
|
38
|
+
identityKey: key.toPublicKey().toString(),
|
|
39
|
+
did: didKeyFromIdentityKey(key.toPublicKey().toString()),
|
|
40
|
+
wallet: new ProtoWallet(key),
|
|
41
|
+
controllerKey: async (passportId) => ownerKeyFromDeriver(passportId, deriver),
|
|
42
|
+
controlLinkage: async (passportId) => ownerLinkageFromDeriver(passportId, deriver),
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A deterministic private key from a secret and a scope, so nothing per party is stored. */
|
|
47
|
+
export function deriveManagedKey(secret: string, scope: string, id: string): PrivateKey {
|
|
48
|
+
if (secret.length < 16) throw new Error('a managed identity secret must be at least 16 characters')
|
|
49
|
+
const seed = Hash.sha256(Utils.toArray(`${secret}\u0000${scope}\u0000${id}`, 'utf8'))
|
|
50
|
+
return PrivateKey.fromHex(Utils.toHex(seed))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface Parties {
|
|
54
|
+
/** The brand's identity: actor on issue, update and retire, and the controller until a hand-on. */
|
|
55
|
+
brand(brandId: string): Party
|
|
56
|
+
/** A recipient's managed identity for one offer; the hand-on moves control to its controller key. */
|
|
57
|
+
recipient(requestId: string): Party
|
|
58
|
+
/** A signed-in member's identity, the issuer of the lifecycle claims they sign. */
|
|
59
|
+
member(userId: string): Party
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function managedParties(options: { brandRootSecret: string; managedIdentitySecret: string }): Parties {
|
|
63
|
+
return {
|
|
64
|
+
brand: (brandId) => managedParty(`brand:${brandId}`, deriveManagedKey(options.brandRootSecret, 'brand', brandId)),
|
|
65
|
+
recipient: (requestId) => managedParty(`recipient:${requestId}`, deriveManagedKey(options.managedIdentitySecret, 'recipient', requestId)),
|
|
66
|
+
member: (userId) => managedParty(`member:${userId}`, deriveManagedKey(options.managedIdentitySecret, 'member', userId)),
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Everything the API, the worker, the CLI and the tests share, assembled
|
|
2
|
+
// once from the configuration: the store, the platform wallet, the managed
|
|
3
|
+
// parties, the index client, the writer, the reader's settings, custody and
|
|
4
|
+
// claims. In development with no INDEX_URL an index runs in this process.
|
|
5
|
+
import { MongoClient, type Db } from 'mongodb'
|
|
6
|
+
import type { ChainTracker } from '@bsv/sdk'
|
|
7
|
+
import { Claims } from './claims.js'
|
|
8
|
+
import type { Config } from './config.js'
|
|
9
|
+
import { Custody } from './custody.js'
|
|
10
|
+
import { startDevIndex, type DevIndex } from './dev-index.js'
|
|
11
|
+
import { IndexClient } from './index-client.js'
|
|
12
|
+
import { managedParties, type Parties } from './parties.js'
|
|
13
|
+
import { headerSource, readPassport, type PassportReading } from './reader.js'
|
|
14
|
+
import { MemoryStore, MongoStore, type Store } from './store.js'
|
|
15
|
+
import { openTestWallet, openToolboxWallet, type PlatformWallet } from './wallet.js'
|
|
16
|
+
import { Writer } from './writer.js'
|
|
17
|
+
|
|
18
|
+
export interface Platform {
|
|
19
|
+
config: Config
|
|
20
|
+
store: Store
|
|
21
|
+
db?: Db
|
|
22
|
+
wallet: PlatformWallet
|
|
23
|
+
parties: Parties
|
|
24
|
+
index: IndexClient
|
|
25
|
+
writer: Writer
|
|
26
|
+
custody: Custody
|
|
27
|
+
claims: Claims
|
|
28
|
+
chainTracker: ChainTracker | 'scripts only'
|
|
29
|
+
read(passportId: string): Promise<PassportReading>
|
|
30
|
+
close(): Promise<void>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface PlatformOptions {
|
|
34
|
+
config: Config
|
|
35
|
+
/** 'test' wires a memory store, a test wallet and an in-process index with nothing live. */
|
|
36
|
+
mode: 'live' | 'test'
|
|
37
|
+
log?: (line: string) => void
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function openPlatform(options: PlatformOptions): Promise<Platform> {
|
|
41
|
+
const { config, mode } = options
|
|
42
|
+
const log = options.log ?? ((line: string) => console.log(line))
|
|
43
|
+
|
|
44
|
+
let client: MongoClient | undefined
|
|
45
|
+
let db: Db | undefined
|
|
46
|
+
let store: Store
|
|
47
|
+
if (mode === 'test') {
|
|
48
|
+
store = new MemoryStore()
|
|
49
|
+
} else {
|
|
50
|
+
// MongoDB holds the records, the journal and sign-in. Without one, development
|
|
51
|
+
// runs on memory: everything is forgotten on restart and sign-in is unavailable.
|
|
52
|
+
try {
|
|
53
|
+
client = new MongoClient(config.mongoUrl, { serverSelectionTimeoutMS: 2_000 })
|
|
54
|
+
await client.connect()
|
|
55
|
+
db = client.db(config.mongoDb)
|
|
56
|
+
const mongo = new MongoStore(db)
|
|
57
|
+
await mongo.init()
|
|
58
|
+
store = mongo
|
|
59
|
+
} catch (cause) {
|
|
60
|
+
await client?.close().catch(() => undefined)
|
|
61
|
+
client = undefined
|
|
62
|
+
log(`MongoDB at ${config.mongoUrl} is not reachable (${cause instanceof Error ? cause.message : String(cause)}): records live in memory for this run, and sign-in is off.`)
|
|
63
|
+
store = new MemoryStore()
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const wallet =
|
|
68
|
+
mode === 'test' || config.wallet.rootKeyHex == null
|
|
69
|
+
? openTestWallet(undefined, config.network)
|
|
70
|
+
: await openToolboxWallet({ network: config.network, rootKeyHex: config.wallet.rootKeyHex, filePath: config.wallet.filePath, wocApiKey: config.wallet.wocApiKey, arcUrl: config.wallet.arcUrl })
|
|
71
|
+
if (mode === 'live' && wallet.kind === 'test') log('WALLET_ROOT_KEY is not set: a test wallet with fixed keys stands in, and nothing can be written to the chain.')
|
|
72
|
+
|
|
73
|
+
let devIndex: DevIndex | undefined
|
|
74
|
+
let index: IndexClient
|
|
75
|
+
if (config.index.url != null) {
|
|
76
|
+
index = new IndexClient({ url: config.index.url, submitToken: config.index.submitToken, callbackToken: config.index.callbackToken })
|
|
77
|
+
} else {
|
|
78
|
+
devIndex = await startDevIndex(wallet.identityKey)
|
|
79
|
+
index = new IndexClient({ url: devIndex.url, submitToken: devIndex.submitToken, callbackToken: devIndex.callbackToken })
|
|
80
|
+
if (mode === 'live') log(`INDEX_URL is not set: an index runs in this process at ${devIndex.url} with in-memory storage; it forgets everything on restart and claims no inclusion.`)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const parties = managedParties({ brandRootSecret: config.brandRootSecret, managedIdentitySecret: config.managedIdentitySecret })
|
|
84
|
+
const writer = new Writer({
|
|
85
|
+
store,
|
|
86
|
+
wallet,
|
|
87
|
+
index,
|
|
88
|
+
identifiers: { host: config.passportHost, prefix: config.gs1Prefix },
|
|
89
|
+
livePublishing: config.livePublishing,
|
|
90
|
+
spendCapSatoshis: config.spendCapSatoshis,
|
|
91
|
+
log,
|
|
92
|
+
})
|
|
93
|
+
const custody = new Custody({ store, wallet, parties, writer })
|
|
94
|
+
const claims = new Claims({ store, registry: config.registry.url == null ? undefined : { url: config.registry.url, token: config.registry.token } })
|
|
95
|
+
// Inclusion can only be checked against a header source; the in-process index and the test wallet mine nothing.
|
|
96
|
+
const chainTracker: ChainTracker | 'scripts only' = wallet.kind === 'toolbox' && config.index.url != null ? headerSource(config.network, config.wallet.wocApiKey) : 'scripts only'
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
config,
|
|
100
|
+
store,
|
|
101
|
+
db,
|
|
102
|
+
wallet,
|
|
103
|
+
parties,
|
|
104
|
+
index,
|
|
105
|
+
writer,
|
|
106
|
+
custody,
|
|
107
|
+
claims,
|
|
108
|
+
chainTracker,
|
|
109
|
+
async read(passportId) {
|
|
110
|
+
// A passport this platform wrote: its brand is the genesis issuer the policy names, and its acceptance records are supplied. Another platform's passport is read with what the index holds, and authority stays unknown.
|
|
111
|
+
const own = await store.getPassport(passportId)
|
|
112
|
+
const genesisIssuers = own == null ? [] : [parties.brand(own.brandId).identityKey]
|
|
113
|
+
return await readPassport(passportId, { index, chainTracker, acceptanceCustodians: [wallet.identityKey], genesisIssuers }, { acceptanceRecords: own?.acceptanceRecords ?? [] })
|
|
114
|
+
},
|
|
115
|
+
async close() {
|
|
116
|
+
await wallet.close()
|
|
117
|
+
await devIndex?.close()
|
|
118
|
+
await client?.close()
|
|
119
|
+
},
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// Industry profiles: which product data a passport carries, checked against
|
|
2
|
+
// the profile's published JSON schema before anything is written. The
|
|
3
|
+
// schemas and manifests come from @bsv/dpp-profiles; this module only
|
|
4
|
+
// chooses the current ones and runs the validator.
|
|
5
|
+
import { Ajv2020 } from 'ajv/dist/2020.js'
|
|
6
|
+
import addFormats from 'ajv-formats'
|
|
7
|
+
import {
|
|
8
|
+
PROFILE_IDS,
|
|
9
|
+
readManifest,
|
|
10
|
+
readPublicPayloadSchema,
|
|
11
|
+
readRestrictedPayloadSchema,
|
|
12
|
+
type ProfileId,
|
|
13
|
+
type ProfileManifest,
|
|
14
|
+
} from '@bsv/dpp-profiles'
|
|
15
|
+
|
|
16
|
+
const ajv = new Ajv2020({ allErrors: true, strict: false })
|
|
17
|
+
;(addFormats as unknown as (instance: Ajv2020) => void)(ajv)
|
|
18
|
+
|
|
19
|
+
/** The profiles a brand may choose: every published version whose manifest says it is current. */
|
|
20
|
+
export function currentProfiles(): Array<{ id: ProfileId; title: string; description?: string }> {
|
|
21
|
+
return PROFILE_IDS.filter((id) => readManifest(id).status === 'current').map((id) => {
|
|
22
|
+
const manifest = readManifest(id)
|
|
23
|
+
return { id, title: manifest.title, description: manifest.description }
|
|
24
|
+
})
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function isProfileId(value: string): value is ProfileId {
|
|
28
|
+
return (PROFILE_IDS as readonly string[]).includes(value)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function manifestFor(profile: ProfileId): ProfileManifest {
|
|
32
|
+
return readManifest(profile)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export type Tier = 'public' | 'restricted'
|
|
36
|
+
|
|
37
|
+
export interface Validation {
|
|
38
|
+
valid: boolean
|
|
39
|
+
problems: string[]
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Check a payload against the profile's public or restricted schema. The problems name the field and what is wrong. */
|
|
43
|
+
export function validatePayload(profile: ProfileId, tier: Tier, payload: unknown): Validation {
|
|
44
|
+
const schema = (tier === 'public' ? readPublicPayloadSchema(profile) : readRestrictedPayloadSchema(profile)) as { $id?: string }
|
|
45
|
+
const validate = (schema.$id != null ? ajv.getSchema(schema.$id) : undefined) ?? ajv.compile(schema)
|
|
46
|
+
const valid = validate(payload) as boolean
|
|
47
|
+
const problems = valid ? [] : (validate.errors ?? []).map((e) => `${e.instancePath || 'the payload'} ${e.message ?? 'is invalid'}`)
|
|
48
|
+
return { valid, problems }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** A placeholder of the right shape for one schema node, so a form can start from something valid. */
|
|
52
|
+
function placeholder(node: Record<string, unknown>, name: string): unknown {
|
|
53
|
+
if (node.const !== undefined) return node.const
|
|
54
|
+
if (Array.isArray(node.enum)) return node.enum[0]
|
|
55
|
+
if (Array.isArray(node.oneOf)) return placeholder(node.oneOf[0] as Record<string, unknown>, name)
|
|
56
|
+
if (Array.isArray(node.anyOf)) return placeholder(node.anyOf[0] as Record<string, unknown>, name)
|
|
57
|
+
const type = Array.isArray(node.type) ? node.type[0] : node.type
|
|
58
|
+
if (type === 'object' || node.properties != null) {
|
|
59
|
+
const out: Record<string, unknown> = {}
|
|
60
|
+
const properties = (node.properties ?? {}) as Record<string, Record<string, unknown>>
|
|
61
|
+
for (const key of (node.required ?? []) as string[]) out[key] = placeholder(properties[key] ?? {}, key)
|
|
62
|
+
return out
|
|
63
|
+
}
|
|
64
|
+
if (type === 'array') return Array.from({ length: Math.max(1, Number(node.minItems ?? 1)) }, () => placeholder((node.items ?? {}) as Record<string, unknown>, name))
|
|
65
|
+
if (type === 'integer') return Number(node.minimum ?? 0)
|
|
66
|
+
if (type === 'number') return Number(node.minimum ?? 0)
|
|
67
|
+
if (type === 'boolean') return false
|
|
68
|
+
if (node.format === 'date') return '2026-01-01'
|
|
69
|
+
if (node.format === 'date-time') return '2026-01-01T00:00:00Z'
|
|
70
|
+
if (node.format === 'uri') return 'https://example.com/'
|
|
71
|
+
if (typeof node.pattern === 'string') {
|
|
72
|
+
// The shapes the profiles' patterns ask for: a country code, a month, a CAS number, a GTIN.
|
|
73
|
+
const candidates = ['AU', '2026-01', '7440-50-8', '09521000000025', '12345678', 'A', '0']
|
|
74
|
+
const regex = new RegExp(node.pattern)
|
|
75
|
+
const match = candidates.find((candidate) => regex.test(candidate))
|
|
76
|
+
if (match != null) return match
|
|
77
|
+
}
|
|
78
|
+
const text = `${name} placeholder`
|
|
79
|
+
return typeof node.maxLength === 'number' ? text.slice(0, node.maxLength) : text
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* A minimal valid public payload for the profile: every required field with a
|
|
84
|
+
* placeholder value. With `demonstration`, it starts with the notice a record
|
|
85
|
+
* that describes no real product carries. Replace every value with the
|
|
86
|
+
* product's own data; a placeholder is never a statement about a product.
|
|
87
|
+
*/
|
|
88
|
+
export function samplePayload(profile: ProfileId, demonstration: boolean): Record<string, unknown> {
|
|
89
|
+
const { payload, problems } = sampleWithProblems(profile, demonstration)
|
|
90
|
+
if (problems.length > 0) throw new Error(`the generated ${profile} sample is refused by its own schema: ${problems.join('; ')}`)
|
|
91
|
+
return payload
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The same sample, with whatever its own schema still refuses, so a form can start from it and show what to fix. */
|
|
95
|
+
export function sampleWithProblems(profile: ProfileId, demonstration: boolean): { payload: Record<string, unknown>; problems: string[] } {
|
|
96
|
+
const schema = readPublicPayloadSchema(profile) as Record<string, unknown>
|
|
97
|
+
const required = placeholder(schema, 'payload') as Record<string, unknown>
|
|
98
|
+
const payload = demonstration ? { notice: 'Demonstration record. Nothing here describes a real product.', ...required } : required
|
|
99
|
+
return { payload, problems: validatePayload(profile, 'public', payload).problems }
|
|
100
|
+
}
|