@bsv/create-dpp-app 0.0.0-stage → 0.1.0-beta.2
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/NOTICE +2 -0
- package/PATENTS +12 -0
- package/README.md +93 -2
- package/dist/index.js +125 -0
- package/package.json +57 -4
- package/template/Dockerfile +37 -0
- package/template/README.md +389 -0
- package/template/_dockerignore +6 -0
- package/template/_env.example +122 -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 +119 -0
- package/template/apps/api/package.json +39 -0
- package/template/apps/api/src/auth.ts +55 -0
- package/template/apps/api/src/bound-profiles.ts +590 -0
- package/template/apps/api/src/claims.ts +204 -0
- package/template/apps/api/src/cli.ts +99 -0
- package/template/apps/api/src/config.ts +180 -0
- package/template/apps/api/src/custody.ts +358 -0
- package/template/apps/api/src/dev-index.ts +120 -0
- package/template/apps/api/src/env-file.ts +55 -0
- package/template/apps/api/src/env.ts +14 -0
- package/template/apps/api/src/epcis/exchange.ts +434 -0
- package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
- package/template/apps/api/src/epcis/routes.ts +364 -0
- package/template/apps/api/src/epcis/sources.ts +142 -0
- package/template/apps/api/src/go-live.ts +226 -0
- package/template/apps/api/src/http-error.ts +15 -0
- package/template/apps/api/src/identifiers.ts +57 -0
- package/template/apps/api/src/index-client.ts +261 -0
- package/template/apps/api/src/index-projects.ts +53 -0
- package/template/apps/api/src/lifecycle-authority.ts +49 -0
- package/template/apps/api/src/lifecycle.ts +485 -0
- package/template/apps/api/src/main.ts +58 -0
- package/template/apps/api/src/parties.ts +68 -0
- package/template/apps/api/src/platform.ts +176 -0
- package/template/apps/api/src/portability/commands.ts +224 -0
- package/template/apps/api/src/portability/export.ts +708 -0
- package/template/apps/api/src/portability/package.ts +270 -0
- package/template/apps/api/src/portability/restore.ts +863 -0
- package/template/apps/api/src/profiles.ts +125 -0
- package/template/apps/api/src/reader.ts +265 -0
- package/template/apps/api/src/resolver.ts +159 -0
- package/template/apps/api/src/sector-examples.ts +390 -0
- package/template/apps/api/src/server.ts +613 -0
- package/template/apps/api/src/store.ts +426 -0
- package/template/apps/api/src/validation-engine.ts +172 -0
- package/template/apps/api/src/wallet.ts +359 -0
- package/template/apps/api/src/worker.ts +113 -0
- package/template/apps/api/src/writer.ts +603 -0
- package/template/apps/api/test/bound-http.test.ts +496 -0
- package/template/apps/api/test/bound-profiles.test.ts +547 -0
- package/template/apps/api/test/config.test.ts +160 -0
- package/template/apps/api/test/custody-journal.test.ts +415 -0
- package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
- package/template/apps/api/test/custom-profile.test.ts +167 -0
- package/template/apps/api/test/env-file.test.ts +53 -0
- package/template/apps/api/test/epcis-fixtures.ts +270 -0
- package/template/apps/api/test/epcis-http.test.ts +1179 -0
- package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
- package/template/apps/api/test/epcis-separation.test.ts +253 -0
- package/template/apps/api/test/epcis-web.test.ts +230 -0
- package/template/apps/api/test/exit-exercise.test.ts +1038 -0
- package/template/apps/api/test/external-index.test.ts +32 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
- package/template/apps/api/test/go-live.test.ts +179 -0
- package/template/apps/api/test/gs1-global-setup.ts +33 -0
- package/template/apps/api/test/gs1-test-env.ts +5 -0
- package/template/apps/api/test/identifier-host.test.ts +256 -0
- package/template/apps/api/test/index-projects.test.ts +81 -0
- package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
- package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
- package/template/apps/api/test/lifecycle.test.ts +147 -0
- package/template/apps/api/test/manifest-notice.test.ts +36 -0
- package/template/apps/api/test/network-guard.ts +113 -0
- package/template/apps/api/test/portability.test.ts +655 -0
- package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
- package/template/apps/api/test/retired-profiles.test.ts +216 -0
- package/template/apps/api/test/sector-cutover.test.ts +95 -0
- package/template/apps/api/test/sector-forms.test.ts +420 -0
- package/template/apps/api/test/unjoined-index.test.ts +62 -0
- package/template/apps/api/test/validation-engine.test.ts +328 -0
- package/template/apps/api/test/wallet-monitor.test.ts +38 -0
- package/template/apps/api/test/writer-journal.test.ts +327 -0
- package/template/apps/api/tsconfig.json +9 -0
- package/template/apps/api/vitest.config.ts +12 -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 +55 -0
- package/template/apps/web/src/components/bits.tsx +188 -0
- package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
- package/template/apps/web/src/components/bound/field-view.tsx +237 -0
- package/template/apps/web/src/components/bound/pieces.tsx +169 -0
- package/template/apps/web/src/components/bound/readings.tsx +152 -0
- package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
- package/template/apps/web/src/components/claim-dialog.tsx +344 -0
- package/template/apps/web/src/components/epcis-events.tsx +119 -0
- package/template/apps/web/src/components/layout.tsx +135 -0
- package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
- package/template/apps/web/src/components/passport-form.tsx +244 -0
- package/template/apps/web/src/components/read-passport.tsx +49 -0
- package/template/apps/web/src/components/reading.tsx +150 -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 +396 -0
- package/template/apps/web/src/lib/auth.ts +10 -0
- package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
- package/template/apps/web/src/lib/bound/display.ts +122 -0
- package/template/apps/web/src/lib/bound/fields.ts +128 -0
- package/template/apps/web/src/lib/bound/form-model.ts +521 -0
- package/template/apps/web/src/lib/bound/forms.ts +15 -0
- package/template/apps/web/src/lib/bound/identity.ts +48 -0
- package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
- package/template/apps/web/src/lib/bound/units.ts +37 -0
- package/template/apps/web/src/lib/epcis.ts +345 -0
- package/template/apps/web/src/lib/format.ts +87 -0
- package/template/apps/web/src/lib/lifecycle.ts +350 -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 +113 -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/events.tsx +388 -0
- package/template/apps/web/src/pages/home.tsx +51 -0
- package/template/apps/web/src/pages/new-passport.tsx +137 -0
- package/template/apps/web/src/pages/operations.tsx +169 -0
- package/template/apps/web/src/pages/passport.tsx +632 -0
- package/template/apps/web/src/pages/public-passport.tsx +64 -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 +23 -0
- package/template/deploy/compose.yml +38 -0
- package/template/package.json +48 -0
- package/template/tsconfig.base.json +13 -0
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// npm run go-live: everything a real write needs, checked in order, each
|
|
2
|
+
// failure printed with its fix, and nothing on the chain until all pass.
|
|
3
|
+
// Registration is the one step that changes the index: the wallet signs a
|
|
4
|
+
// dpp-index-registration@1 request, POST /register appends the publisher
|
|
5
|
+
// key to the index's policy and answers with this app's two write tokens,
|
|
6
|
+
// which go into .env beside the root key the first run generated. A passing
|
|
7
|
+
// run writes LIVE_PUBLISHING=true; a failing run leaves it as it was.
|
|
8
|
+
import { INDEX_REGISTRATION_FORMAT, signRegistration } from '@bsv/dpp-protocol'
|
|
9
|
+
import { KNOWN_INDEX_HOSTS, loadConfig, type Config } from './config.js'
|
|
10
|
+
import { generateRootKey, ROOT_KEY_GENERATED, updateEnvFile } from './env-file.js'
|
|
11
|
+
import { IndexClient } from './index-client.js'
|
|
12
|
+
import { openPlatform as openDefaultPlatform, type Platform, type PlatformOptions } from './platform.js'
|
|
13
|
+
|
|
14
|
+
export const CUSTODY_PROFILE = 'managed-custody@2'
|
|
15
|
+
/** A few states' worth: one costs a little over a hundred satoshis. */
|
|
16
|
+
export const MINIMUM_SATOSHIS = 500
|
|
17
|
+
const LABEL_BYTES = 128
|
|
18
|
+
|
|
19
|
+
export interface GoLiveFailure {
|
|
20
|
+
check: string
|
|
21
|
+
problem: string
|
|
22
|
+
fix: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface GoLiveOptions {
|
|
26
|
+
env: NodeJS.ProcessEnv
|
|
27
|
+
/** The project's .env, which gains the root key, the tokens and LIVE_PUBLISHING. */
|
|
28
|
+
envFile: string
|
|
29
|
+
/** The label the index's operator sees for this app. */
|
|
30
|
+
projectName: string
|
|
31
|
+
out: (line: string) => void
|
|
32
|
+
openPlatform?: (options: PlatformOptions) => Promise<Platform>
|
|
33
|
+
now?: () => Date
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface GoLiveResult {
|
|
37
|
+
ok: boolean
|
|
38
|
+
passed: string[]
|
|
39
|
+
failures: GoLiveFailure[]
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
type RegisterAnswer = { status: number; body: { status?: string; error?: string; description?: string; hint?: string; policyVersion?: number; tokens?: { submit: string; callback: string } } }
|
|
43
|
+
|
|
44
|
+
async function postRegister(url: string, request: unknown): Promise<RegisterAnswer> {
|
|
45
|
+
const response = await fetch(`${url}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(request) })
|
|
46
|
+
const body = (await response.json().catch(() => ({}))) as RegisterAnswer['body']
|
|
47
|
+
return { status: response.status, body }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** An error's message with the reason fetch hides under `cause` (ENOTFOUND, ECONNREFUSED), so a newcomer can tell DNS from a service that is down. */
|
|
51
|
+
const describe = (cause: unknown): string => {
|
|
52
|
+
if (!(cause instanceof Error)) return String(cause)
|
|
53
|
+
const inner = (cause as Error & { cause?: unknown }).cause
|
|
54
|
+
return inner instanceof Error && inner.message !== '' && inner.message !== cause.message ? `${cause.message} (${inner.message})` : cause.message
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** go-live decides LIVE_PUBLISHING itself, so the file's current value never stops the run: a true left behind without tokens would otherwise send the user round in a loop. */
|
|
58
|
+
const configuration = (env: NodeJS.ProcessEnv): Config => loadConfig({ ...env, LIVE_PUBLISHING: 'false' })
|
|
59
|
+
|
|
60
|
+
export async function goLive(options: GoLiveOptions): Promise<GoLiveResult> {
|
|
61
|
+
const env = { ...options.env }
|
|
62
|
+
const out = options.out
|
|
63
|
+
const open = options.openPlatform ?? openDefaultPlatform
|
|
64
|
+
const now = options.now ?? (() => new Date())
|
|
65
|
+
const passed: string[] = []
|
|
66
|
+
const failures: GoLiveFailure[] = []
|
|
67
|
+
const pass = (check: string, detail?: string): void => {
|
|
68
|
+
passed.push(check)
|
|
69
|
+
out(`ok ${check}${detail == null ? '' : `: ${detail}`}`)
|
|
70
|
+
}
|
|
71
|
+
const fail = (check: string, problem: string, fix: string): void => {
|
|
72
|
+
failures.push({ check, problem, fix })
|
|
73
|
+
out(`no ${check}: ${problem}. Fix: ${fix}`)
|
|
74
|
+
}
|
|
75
|
+
const result = (): GoLiveResult => ({ ok: failures.length === 0, passed, failures })
|
|
76
|
+
|
|
77
|
+
// 1. Configuration.
|
|
78
|
+
let config: Config
|
|
79
|
+
if ((env.LIVE_PUBLISHING ?? '').trim() === 'true') out('note configuration: LIVE_PUBLISHING is already true in .env; this run decides it again')
|
|
80
|
+
try {
|
|
81
|
+
config = configuration(env)
|
|
82
|
+
} catch (cause) {
|
|
83
|
+
fail('configuration', describe(cause), 'edit .env as the message says, then run npm run go-live again')
|
|
84
|
+
return result()
|
|
85
|
+
}
|
|
86
|
+
const indexUrl = config.index.url
|
|
87
|
+
if (indexUrl == null) {
|
|
88
|
+
fail('configuration', 'INDEX_URL is empty', 'set INDEX_URL to the index this app publishes to (the default testnet index is https://dpp-overlay-testnet.bsvb.net), or run npm run connect-index -- --url <index>')
|
|
89
|
+
} else {
|
|
90
|
+
let host: string | undefined
|
|
91
|
+
try {
|
|
92
|
+
host = new URL(indexUrl).hostname
|
|
93
|
+
} catch {
|
|
94
|
+
fail('configuration', `INDEX_URL ${indexUrl} is not a URL`, 'set INDEX_URL to the index address, https://host or http://host:port')
|
|
95
|
+
}
|
|
96
|
+
const known = host == null ? undefined : KNOWN_INDEX_HOSTS[host]
|
|
97
|
+
if (known != null && known !== config.network) {
|
|
98
|
+
fail('configuration', `${host} serves ${known} and NETWORK is ${config.network}`, `set NETWORK=${known} for that index, or INDEX_URL to the ${config.network} index (${config.network === 'test' ? 'https://dpp-overlay-testnet.bsvb.net' : 'https://dpp-overlay-mainnet.bsvb.net'})`)
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (config.network === 'main') {
|
|
102
|
+
if (config.gs1Prefix === '952') fail('configuration', 'GS1_PREFIX is 952, the demonstration prefix, and NETWORK is main', 'set GS1_PREFIX to a prefix licensed to you before writing real passports on mainnet')
|
|
103
|
+
if (/^localhost(:\d+)?$/.test(config.passportHost)) fail('configuration', `PASSPORT_HOST is ${config.passportHost} and NETWORK is main`, 'set PASSPORT_HOST to a host you serve this app from, so a label opens the passport page')
|
|
104
|
+
} else {
|
|
105
|
+
if (config.gs1Prefix === '952') out('note configuration: GS1_PREFIX is 952, the demonstration prefix; fine on testnet, replace it before mainnet')
|
|
106
|
+
if (/^localhost(:\d+)?$/.test(config.passportHost)) out(`note configuration: PASSPORT_HOST is ${config.passportHost}; fine on testnet, set a host you serve before mainnet`)
|
|
107
|
+
}
|
|
108
|
+
if (failures.length > 0) return result()
|
|
109
|
+
pass('configuration', `${config.network}, index ${indexUrl}`)
|
|
110
|
+
|
|
111
|
+
// 2. Wallet.
|
|
112
|
+
if (config.wallet.rootKeyHex == null && (await generateRootKey(options.envFile, env))) {
|
|
113
|
+
config = configuration(env)
|
|
114
|
+
out(ROOT_KEY_GENERATED)
|
|
115
|
+
}
|
|
116
|
+
let platform: Platform
|
|
117
|
+
try {
|
|
118
|
+
platform = await open({ config, mode: 'live', log: () => {} })
|
|
119
|
+
} catch (cause) {
|
|
120
|
+
fail('wallet', `the wallet could not be opened: ${describe(cause)}`, 'check WALLET_ROOT_KEY and WALLET_FILE in .env, then run npm run go-live again')
|
|
121
|
+
return result()
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
const publisherKey = platform.wallet.identityKey
|
|
125
|
+
if (config.testWallet && platform.wallet.kind === 'test') out('DPP_TEST_WALLET=1: the test wallet stands in on the configured root key, with made-up funds; nothing can be written to the chain. Unset it unless this is the scaffold check.')
|
|
126
|
+
pass('wallet', `${platform.wallet.kind} wallet on ${platform.wallet.network}, publisher key ${publisherKey}`)
|
|
127
|
+
|
|
128
|
+
// 3. The index.
|
|
129
|
+
const index = new IndexClient({ url: indexUrl! })
|
|
130
|
+
let custodyProfile: string | undefined
|
|
131
|
+
let registrationMode: string | undefined
|
|
132
|
+
let publisherKeys: string[] = []
|
|
133
|
+
try {
|
|
134
|
+
const health = await index.health()
|
|
135
|
+
if (health.network !== config.network) {
|
|
136
|
+
fail('index', `${indexUrl} serves ${health.network} and NETWORK is ${config.network}`, `set NETWORK=${health.network}, or point INDEX_URL at a ${config.network} index`)
|
|
137
|
+
}
|
|
138
|
+
const document = await index.capabilities()
|
|
139
|
+
const custody = document.profiles?.find((p) => p.kind === 'custody')
|
|
140
|
+
custodyProfile = custody == null ? undefined : `${custody.id}@${custody.version}`
|
|
141
|
+
registrationMode = (document.profiles?.find((p) => p.kind === 'operator')?.options?.registration as string | undefined) ?? 'off'
|
|
142
|
+
publisherKeys = document.publisherPolicy?.publisherKeys ?? []
|
|
143
|
+
if (custodyProfile !== CUSTODY_PROFILE) {
|
|
144
|
+
fail('index', `${indexUrl} admits under custody profile ${custodyProfile ?? 'none'} and this app writes under ${CUSTODY_PROFILE}`, `use an index on ${config.network} that advertises ${CUSTODY_PROFILE}, then run npm run connect-index`)
|
|
145
|
+
}
|
|
146
|
+
} catch (cause) {
|
|
147
|
+
fail('index', `${indexUrl} could not be reached: ${describe(cause)}`, 'check the address and that the index is running; to use another index, run npm run connect-index -- --url <index>')
|
|
148
|
+
}
|
|
149
|
+
if (failures.length > 0) return result()
|
|
150
|
+
pass('index', `${indexUrl} on ${config.network}, ${custodyProfile}, registration ${registrationMode}`)
|
|
151
|
+
|
|
152
|
+
// 4. Registration.
|
|
153
|
+
// Named and holding tokens: done. Named without tokens is still a request:
|
|
154
|
+
// an approved key collects its tokens this way, and a key the operator
|
|
155
|
+
// added by hand is told 409 and where to get them.
|
|
156
|
+
const named = publisherKeys.includes(publisherKey)
|
|
157
|
+
if (named && config.index.joined) {
|
|
158
|
+
pass('registration', 'this publisher key is registered and the tokens are held')
|
|
159
|
+
} else {
|
|
160
|
+
let answer: RegisterAnswer
|
|
161
|
+
try {
|
|
162
|
+
const request = await signRegistration(
|
|
163
|
+
{
|
|
164
|
+
registrationFormat: INDEX_REGISTRATION_FORMAT,
|
|
165
|
+
indexUrl: indexUrl!,
|
|
166
|
+
publisherKey,
|
|
167
|
+
network: config.network,
|
|
168
|
+
custodyProfile: CUSTODY_PROFILE,
|
|
169
|
+
label: Buffer.from(options.projectName, 'utf8').subarray(0, LABEL_BYTES).toString('utf8').replace(/�+$/, '') || 'dpp-app',
|
|
170
|
+
requestedAt: now().toISOString(),
|
|
171
|
+
},
|
|
172
|
+
platform.wallet.publisher
|
|
173
|
+
)
|
|
174
|
+
answer = await postRegister(indexUrl!, request)
|
|
175
|
+
} catch (cause) {
|
|
176
|
+
const message = describe(cause)
|
|
177
|
+
if (/label/.test(message)) {
|
|
178
|
+
fail('registration', `the request could not be signed: ${message}`, 'set a plain name in package.json (letters, digits and hyphens), then run npm run go-live again')
|
|
179
|
+
return result()
|
|
180
|
+
}
|
|
181
|
+
fail('registration', `POST /register failed: ${describe(cause)}`, 'run npm run go-live again; if it keeps failing, ask the operator')
|
|
182
|
+
return result()
|
|
183
|
+
}
|
|
184
|
+
const { status, body } = answer
|
|
185
|
+
if (status === 201 && body.tokens != null) {
|
|
186
|
+
await updateEnvFile(options.envFile, { INDEX_SUBMIT_TOKEN: body.tokens.submit, INDEX_CALLBACK_TOKEN: body.tokens.callback })
|
|
187
|
+
env.INDEX_SUBMIT_TOKEN = body.tokens.submit
|
|
188
|
+
env.INDEX_CALLBACK_TOKEN = body.tokens.callback
|
|
189
|
+
config = configuration(env)
|
|
190
|
+
pass('registration', `registered in policy version ${body.policyVersion}; the tokens are in .env`)
|
|
191
|
+
} else if (status === 202) {
|
|
192
|
+
fail('registration', `${indexUrl} holds the request for its operator's approval`, 'run npm run go-live again once the operator has approved; the tokens are handed over then')
|
|
193
|
+
} else if (status === 404) {
|
|
194
|
+
fail('registration', `${indexUrl} does not register publishers itself`, 'ask its operator for admission and a connection file (dpp-index connection), then run npm run connect-index -- --from <file>; or run your own index from the DPP operator preset')
|
|
195
|
+
} else if (status === 409 && body.error === 'already-registered') {
|
|
196
|
+
fail('registration', `${indexUrl} names this publisher key and holds no tokens for it to hand over`, 'ask the operator for this key\'s connection file (dpp-index connection), then run npm run connect-index -- --from <file>')
|
|
197
|
+
} else {
|
|
198
|
+
fail('registration', `${indexUrl} answered ${status}${body.error == null ? '' : ` ${body.error}`}${body.description == null ? '' : `: ${body.description}`}`, body.hint ?? 'read the message, change .env accordingly and run npm run go-live again')
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if (failures.length > 0) return result()
|
|
202
|
+
|
|
203
|
+
// 5. Funds.
|
|
204
|
+
const balance = await platform.wallet.balance()
|
|
205
|
+
if (balance < MINIMUM_SATOSHIS) {
|
|
206
|
+
const funding = await platform.wallet.fundingAddress()
|
|
207
|
+
fail('funds', `the wallet holds ${balance} satoshis`, `pay a few thousand satoshis to ${funding.address}, then take the payment in with: npm run wallet fund <txid> ${funding.address} ${funding.derivationPrefix} ${funding.derivationSuffix}; then run npm run go-live again`)
|
|
208
|
+
return result()
|
|
209
|
+
}
|
|
210
|
+
pass('funds', `${balance} satoshis`)
|
|
211
|
+
|
|
212
|
+
// 6. Admission: the index names the key now.
|
|
213
|
+
const keys = await index.publisherKeys().catch(() => [] as string[])
|
|
214
|
+
if (!keys.includes(publisherKey)) {
|
|
215
|
+
fail('admission', `${indexUrl} does not yet name this publisher key`, 'run npm run go-live again in a moment; if it keeps failing, ask the operator')
|
|
216
|
+
return result()
|
|
217
|
+
}
|
|
218
|
+
pass('admission', 'the index admits states this key countersigns')
|
|
219
|
+
|
|
220
|
+
await updateEnvFile(options.envFile, { LIVE_PUBLISHING: 'true' })
|
|
221
|
+
out(`LIVE_PUBLISHING=true is written: the next passport write spends real satoshis on ${config.network === 'main' ? 'mainnet' : 'testnet'} and is permanent.`)
|
|
222
|
+
return result()
|
|
223
|
+
} finally {
|
|
224
|
+
await platform.close()
|
|
225
|
+
}
|
|
226
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// An error a route answers with a status and a code. It lives in a module of
|
|
2
|
+
// its own so that a group of routes can use it without importing the server,
|
|
3
|
+
// and through the server everything the server imports.
|
|
4
|
+
|
|
5
|
+
export class HttpError extends Error {
|
|
6
|
+
constructor(
|
|
7
|
+
readonly status: number,
|
|
8
|
+
readonly code: string,
|
|
9
|
+
detail: string,
|
|
10
|
+
/** Further members of the answer, beside `error` and `description`. */
|
|
11
|
+
readonly data: Record<string, unknown> = {}
|
|
12
|
+
) {
|
|
13
|
+
super(detail)
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -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.startsWith(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,261 @@
|
|
|
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 { createHash } from 'node:crypto'
|
|
7
|
+
import { Beef, Transaction, type MerklePath } from '@bsv/sdk'
|
|
8
|
+
import { chainFromBeef, decodeAttestationAnchor } from '@bsv/dpp-protocol'
|
|
9
|
+
|
|
10
|
+
export type Announcement = 'admitted' | 'duplicate' | 'refused' | 'unauthorised' | 'unreachable'
|
|
11
|
+
|
|
12
|
+
export interface CapabilityDocument {
|
|
13
|
+
implementation?: { name: string; version: string }
|
|
14
|
+
publisherPolicy?: { publisherKeys: string[]; anchoringServices?: string[] }
|
|
15
|
+
profiles?: Array<{ id: string; version: string; kind: string; options?: Record<string, unknown> }>
|
|
16
|
+
[key: string]: unknown
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface IndexClientOptions {
|
|
20
|
+
url: string
|
|
21
|
+
submitToken?: string
|
|
22
|
+
callbackToken?: string
|
|
23
|
+
/** This index can withdraw drafts admitted before the network answers. */
|
|
24
|
+
supportsRetraction?: boolean
|
|
25
|
+
/** Silence the in-process index's logging during a call; tests use it. */
|
|
26
|
+
quiet?: boolean
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Read a discovery response up to its wire limit, including responses without Content-Length. */
|
|
30
|
+
export async function boundedJson(response: Response, limit: number): Promise<unknown> {
|
|
31
|
+
const reader = response.body?.getReader()
|
|
32
|
+
if (reader == null) throw new Error('the response has no body')
|
|
33
|
+
const chunks: Uint8Array[] = []
|
|
34
|
+
let length = 0
|
|
35
|
+
try {
|
|
36
|
+
for (;;) {
|
|
37
|
+
const chunk = await reader.read()
|
|
38
|
+
if (chunk.done) break
|
|
39
|
+
length += chunk.value.length
|
|
40
|
+
if (length > limit) throw new Error(`the response exceeds the reader limit of ${limit} bytes`)
|
|
41
|
+
chunks.push(chunk.value)
|
|
42
|
+
}
|
|
43
|
+
} finally {
|
|
44
|
+
if (length > limit) await reader.cancel()
|
|
45
|
+
reader.releaseLock()
|
|
46
|
+
}
|
|
47
|
+
return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)))
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export class IndexClient {
|
|
51
|
+
readonly url: string
|
|
52
|
+
readonly supportsRetraction: boolean
|
|
53
|
+
readonly destinationId: string
|
|
54
|
+
private submitToken?: string
|
|
55
|
+
private callbackToken?: string
|
|
56
|
+
/** The last refusal reason the index gave in X-Admission-Refusal, for the journal. */
|
|
57
|
+
lastRefusal: string | undefined
|
|
58
|
+
|
|
59
|
+
constructor(options: IndexClientOptions) {
|
|
60
|
+
this.url = options.url.replace(/\/+$/, '')
|
|
61
|
+
this.destinationId = createHash('sha256').update(this.url).digest('hex')
|
|
62
|
+
this.supportsRetraction = options.supportsRetraction ?? false
|
|
63
|
+
this.submitToken = options.submitToken
|
|
64
|
+
this.callbackToken = options.callbackToken
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
private async request(path: string, init?: RequestInit): Promise<Response> {
|
|
68
|
+
return await fetch(`${this.url}${path}`, init)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The index's own health answer, which names the network it serves. */
|
|
72
|
+
async health(): Promise<{ status: string; network: string }> {
|
|
73
|
+
const response = await this.request('/health')
|
|
74
|
+
if (!response.ok) throw new Error(`the index answered HTTP ${response.status} to GET /health`)
|
|
75
|
+
return (await response.json()) as { status: string; network: string }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async capabilities(): Promise<CapabilityDocument> {
|
|
79
|
+
const response = await this.request('/capabilities')
|
|
80
|
+
if (!response.ok) throw new Error(`the index answered HTTP ${response.status} to GET /capabilities`)
|
|
81
|
+
return (await response.json()) as CapabilityDocument
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The publisher keys the index admits, from its own capability document. */
|
|
85
|
+
async publisherKeys(): Promise<string[]> {
|
|
86
|
+
const document = await this.capabilities()
|
|
87
|
+
return document.publisherPolicy?.publisherKeys ?? []
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The lineage the index holds for the passport, genesis first, or an empty list. */
|
|
91
|
+
async lineage(passportId: string): Promise<Transaction[]> {
|
|
92
|
+
const response = await this.request('/lookup', {
|
|
93
|
+
method: 'POST',
|
|
94
|
+
headers: { 'Content-Type': 'application/json' },
|
|
95
|
+
body: JSON.stringify({ service: 'ls_dpp', query: { passportId } }),
|
|
96
|
+
})
|
|
97
|
+
if (!response.ok) throw new Error(`the index answered HTTP ${response.status} to the lookup`)
|
|
98
|
+
const { outputs } = (await response.json()) as { outputs: Array<{ beef: number[] }> }
|
|
99
|
+
if (outputs.length === 0) return []
|
|
100
|
+
const merged = Beef.fromBinary(outputs[0].beef)
|
|
101
|
+
for (const output of outputs.slice(1)) merged.mergeBeef(output.beef)
|
|
102
|
+
return chainFromBeef(merged, passportId)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The attestation anchors the index holds under one selector (`ls_attestation`), each as its transaction and output.
|
|
107
|
+
* An anchor's metadata is unsigned by the claim's issuer: it says where to look, and the claim's own verification
|
|
108
|
+
* decides what the claim is about. Throws when the index cannot be reached or refuses the question.
|
|
109
|
+
*/
|
|
110
|
+
async *scanAnchors(query: { subject: string } | { attestationId: string }, representation?: string, signal = AbortSignal.timeout(30_000)): AsyncGenerator<{ transaction: Transaction; outputIndex: number; attestationId: string }> {
|
|
111
|
+
let after: { txid: string; outputIndex: number } | undefined
|
|
112
|
+
let count = 0
|
|
113
|
+
// The lookup contract ends on an empty page. Preserve results already read if a later page fails.
|
|
114
|
+
const maxAnchors = 500
|
|
115
|
+
for (;;) {
|
|
116
|
+
const limit = Math.min(100, maxAnchors - count + 1)
|
|
117
|
+
const response = await this.request('/lookup', {
|
|
118
|
+
method: 'POST',
|
|
119
|
+
headers: { 'Content-Type': 'application/json' },
|
|
120
|
+
signal,
|
|
121
|
+
body: JSON.stringify({ service: 'ls_attestation', query: { ...query, ...(representation == null ? {} : { representation }), limit, after } }),
|
|
122
|
+
})
|
|
123
|
+
if (!response.ok) throw new Error(`the index answered HTTP ${response.status} to the anchor lookup`)
|
|
124
|
+
const { outputs } = (await boundedJson(response, 32 * 1024 * 1024)) as { outputs?: Array<{ beef: number[]; outputIndex: number }> }
|
|
125
|
+
if (!Array.isArray(outputs) || outputs.length > limit) throw new Error('the index returned an invalid anchor page')
|
|
126
|
+
if (outputs.length === 0) return
|
|
127
|
+
for (const output of outputs) {
|
|
128
|
+
if (count === maxAnchors) throw new Error(`the anchor lookup exceeded the reader limit of ${maxAnchors} outputs`)
|
|
129
|
+
const transaction = Transaction.fromBEEF(output.beef)
|
|
130
|
+
const txid = transaction.id('hex')
|
|
131
|
+
const outputIndex = output.outputIndex
|
|
132
|
+
if (!Number.isSafeInteger(outputIndex) || transaction.outputs[outputIndex] == null) throw new Error('the index returned an invalid anchor outpoint')
|
|
133
|
+
if (after != null && (txid < after.txid || (txid === after.txid && outputIndex <= after.outputIndex))) throw new Error('the anchor page did not advance in outpoint order')
|
|
134
|
+
const metadata = decodeAttestationAnchor(transaction.outputs[outputIndex]!.lockingScript)
|
|
135
|
+
if (metadata == null || ('subject' in query && metadata.subject !== query.subject) || ('attestationId' in query && metadata.attestationId !== query.attestationId) || (representation != null && metadata.representation !== representation)) {
|
|
136
|
+
throw new Error('the returned anchor does not match the lookup selector')
|
|
137
|
+
}
|
|
138
|
+
after = { txid, outputIndex }
|
|
139
|
+
count += 1
|
|
140
|
+
yield { transaction, outputIndex, attestationId: metadata.attestationId }
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async anchorsFor(query: { subject: string } | { attestationId: string }, representation?: string): Promise<Array<{ transaction: Transaction; outputIndex: number }>> {
|
|
146
|
+
const anchors = []
|
|
147
|
+
for await (const { transaction, outputIndex } of this.scanAnchors(query, representation)) anchors.push({ transaction, outputIndex })
|
|
148
|
+
return anchors
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The identity key the index signs its evidence packages under, as its capability document names it, or nothing when it signs none. */
|
|
152
|
+
async exporterIdentityKey(): Promise<string | undefined> {
|
|
153
|
+
const key = (await this.capabilities()).exporterIdentityKey
|
|
154
|
+
return typeof key === 'string' && /^0[23][0-9a-f]{64}$/.test(key) ? key : undefined
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* The index's bounded evidence package for one passport (GET /evidence-package), exactly as it answered: the signed
|
|
159
|
+
* manifest and every file by path, base64. `absent` says why there is none: the index holds no state of the
|
|
160
|
+
* passport, signs no package, or could not be reached. Nothing here checks the package; the caller inspects it.
|
|
161
|
+
*/
|
|
162
|
+
async evidencePackage(passportId: string): Promise<{ envelope: { manifest: unknown; files: Record<string, string> } } | { absent: 'not-held' | 'export-unavailable' | 'unreachable'; detail: string }> {
|
|
163
|
+
let response: Response
|
|
164
|
+
try {
|
|
165
|
+
response = await this.request(`/evidence-package?${new URLSearchParams({ passportId }).toString()}`)
|
|
166
|
+
} catch (cause) {
|
|
167
|
+
return { absent: 'unreachable', detail: `the index could not be reached (${cause instanceof Error ? cause.message : String(cause)})` }
|
|
168
|
+
}
|
|
169
|
+
if (response.status === 404) return { absent: 'not-held', detail: 'the index holds no state of the passport' }
|
|
170
|
+
if (response.status === 503) return { absent: 'export-unavailable', detail: 'the index signs no evidence package: its operator has not set an exporter key' }
|
|
171
|
+
if (!response.ok) return { absent: 'unreachable', detail: `the index answered HTTP ${response.status} to GET /evidence-package` }
|
|
172
|
+
return { envelope: (await response.json()) as { manifest: unknown; files: Record<string, string> } }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* One part of the index's complete export for one passport (GET /evidence-export), exactly as it answered. The
|
|
177
|
+
* bearer is the index's EXPORT_TOKEN, where its operator set one. `absent` says why there is no part.
|
|
178
|
+
*/
|
|
179
|
+
async evidenceExportPart(passportId: string, cursor: string | null, token?: string): Promise<{ part: Record<string, unknown> } | { absent: 'not-held' | 'export-unavailable' | 'unauthorised' | 'unreachable'; detail: string }> {
|
|
180
|
+
const query = new URLSearchParams({ passportId })
|
|
181
|
+
if (cursor != null) query.set('cursor', cursor)
|
|
182
|
+
let response: Response
|
|
183
|
+
try {
|
|
184
|
+
response = await this.request(`/evidence-export?${query.toString()}`, token == null ? undefined : { headers: { Authorization: `Bearer ${token}` } })
|
|
185
|
+
} catch (cause) {
|
|
186
|
+
return { absent: 'unreachable', detail: `the index could not be reached (${cause instanceof Error ? cause.message : String(cause)})` }
|
|
187
|
+
}
|
|
188
|
+
if (response.status === 401 || response.status === 403) return { absent: 'unauthorised', detail: 'the index wants its export token for the complete export: set INDEX_EXPORT_TOKEN to the one its operator gave you' }
|
|
189
|
+
if (response.status === 404) return { absent: 'not-held', detail: 'the index holds no state of the passport' }
|
|
190
|
+
if (response.status === 503) return { absent: 'export-unavailable', detail: 'the index signs no evidence package: its operator has not set an exporter key' }
|
|
191
|
+
if (!response.ok) return { absent: 'unreachable', detail: `the index answered HTTP ${response.status} to GET /evidence-export` }
|
|
192
|
+
return { part: (await response.json()) as Record<string, unknown> }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Submit a signed transaction for index admission. */
|
|
196
|
+
async announce(beef: number[]): Promise<Announcement> {
|
|
197
|
+
this.lastRefusal = undefined
|
|
198
|
+
let response: Response
|
|
199
|
+
try {
|
|
200
|
+
response = await this.request('/submit', {
|
|
201
|
+
method: 'POST',
|
|
202
|
+
headers: {
|
|
203
|
+
'Content-Type': 'application/octet-stream',
|
|
204
|
+
'X-Topics': JSON.stringify(['tm_dpp']),
|
|
205
|
+
...(this.submitToken != null ? { Authorization: `Bearer ${this.submitToken}` } : {}),
|
|
206
|
+
},
|
|
207
|
+
body: new Uint8Array(beef),
|
|
208
|
+
})
|
|
209
|
+
} catch {
|
|
210
|
+
return 'unreachable'
|
|
211
|
+
}
|
|
212
|
+
if (response.status === 401 || response.status === 403) return 'unauthorised'
|
|
213
|
+
if (response.status === 400) {
|
|
214
|
+
const body = (await response.json().catch(() => ({}))) as { description?: string }
|
|
215
|
+
this.lastRefusal = body.description ?? 'no reason given'
|
|
216
|
+
return 'refused'
|
|
217
|
+
}
|
|
218
|
+
if (!response.ok) return 'unreachable'
|
|
219
|
+
const admission = response.headers.get('x-admission') ?? ''
|
|
220
|
+
if (admission.includes('tm_dpp=none')) {
|
|
221
|
+
this.lastRefusal = response.headers.get('x-admission-refusal') ?? 'no reason given'
|
|
222
|
+
return 'refused'
|
|
223
|
+
}
|
|
224
|
+
if (admission.includes('duplicate')) return 'duplicate'
|
|
225
|
+
return 'admitted'
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Withdraw a state the network refused after the index admitted it. */
|
|
229
|
+
async retract(txid: string, reason: string, outputIndex = 0): Promise<{ ok: boolean; detail: string; absent?: boolean }> {
|
|
230
|
+
let response: Response
|
|
231
|
+
try {
|
|
232
|
+
response = await this.request('/retract', {
|
|
233
|
+
method: 'POST',
|
|
234
|
+
headers: { 'Content-Type': 'application/json', ...(this.submitToken != null ? { Authorization: `Bearer ${this.submitToken}` } : {}) },
|
|
235
|
+
body: JSON.stringify({ txid, outputIndex, reason }),
|
|
236
|
+
})
|
|
237
|
+
} catch (cause) {
|
|
238
|
+
return { ok: false, detail: `the index could not be reached (${cause instanceof Error ? cause.message : String(cause)})` }
|
|
239
|
+
}
|
|
240
|
+
const body = (await response.json().catch(() => ({}))) as { status?: string; error?: string; description?: string }
|
|
241
|
+
const ok = response.ok && body.status === 'retracted'
|
|
242
|
+
return { ok, absent: response.status === 404 && body.error === 'output-unknown', detail: ok ? 'retracted' : `HTTP ${response.status}${body.error != null ? ` ${body.error}` : ''}${body.description != null ? `, ${body.description}` : ''}` }
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Offer a merkle path to the index, in the shape a broadcaster's callback carries (section 7). */
|
|
246
|
+
async pushProof(txid: string, path: MerklePath): Promise<{ ok: boolean; detail: string }> {
|
|
247
|
+
let response: Response
|
|
248
|
+
try {
|
|
249
|
+
response = await this.request('/arc-ingest', {
|
|
250
|
+
method: 'POST',
|
|
251
|
+
headers: { 'Content-Type': 'application/json', ...(this.callbackToken != null ? { 'X-Callback-Token': this.callbackToken } : {}) },
|
|
252
|
+
body: JSON.stringify({ txid, merklePath: path.toHex(), blockHeight: path.blockHeight }),
|
|
253
|
+
})
|
|
254
|
+
} catch (cause) {
|
|
255
|
+
return { ok: false, detail: `the index could not be reached (${cause instanceof Error ? cause.message : String(cause)})` }
|
|
256
|
+
}
|
|
257
|
+
const body = (await response.json().catch(() => ({}))) as { status?: string; description?: string }
|
|
258
|
+
const ok = response.ok && body.status === 'applied'
|
|
259
|
+
return { ok, detail: body.status ?? `HTTP ${response.status}${body.description != null ? `, ${body.description}` : ''}` }
|
|
260
|
+
}
|
|
261
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// npm run connect-index: the way to an index besides the default one. It
|
|
2
|
+
// takes a provider's address and, when the provider handed them out, its
|
|
3
|
+
// tokens; without tokens, go-live registers. --from reads the same settings
|
|
4
|
+
// from a connection file, the one an index operator writes with
|
|
5
|
+
// `dpp-index connection` (the DPP repository's operator preset), so the
|
|
6
|
+
// tokens never pass through the command line. Either way the connection is
|
|
7
|
+
// written to .env and the go-live checks run.
|
|
8
|
+
import { existsSync } from 'node:fs'
|
|
9
|
+
import { loadConfig } from './config.js'
|
|
10
|
+
import { readEnvFile, updateEnvFile } from './env-file.js'
|
|
11
|
+
import { goLive, type GoLiveOptions, type GoLiveResult } from './go-live.js'
|
|
12
|
+
|
|
13
|
+
export interface ConnectIndexOptions extends GoLiveOptions {
|
|
14
|
+
url?: string
|
|
15
|
+
submitToken?: string
|
|
16
|
+
callbackToken?: string
|
|
17
|
+
/** A connection file holding NETWORK, INDEX_URL, INDEX_SUBMIT_TOKEN and INDEX_CALLBACK_TOKEN; a flag given beside it wins. */
|
|
18
|
+
from?: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const USAGE = 'run npm run connect-index -- --from <connection file>, or npm run connect-index -- --url <index> [--submit-token <t> --callback-token <t>]'
|
|
22
|
+
|
|
23
|
+
export async function connectIndex(options: ConnectIndexOptions): Promise<GoLiveResult> {
|
|
24
|
+
const failure = (problem: string, fix: string): GoLiveResult => {
|
|
25
|
+
options.out(`no connect-index: ${problem}. Fix: ${fix}`)
|
|
26
|
+
return { ok: false, passed: [], failures: [{ check: 'connect-index', problem, fix }] }
|
|
27
|
+
}
|
|
28
|
+
let file: Record<string, string> = {}
|
|
29
|
+
if (options.from != null && options.from !== '') {
|
|
30
|
+
if (!existsSync(options.from)) return failure(`${options.from} does not exist`, 'give the path of the connection file the index operator wrote with dpp-index connection')
|
|
31
|
+
file = readEnvFile(options.from)
|
|
32
|
+
let network: string
|
|
33
|
+
try {
|
|
34
|
+
network = loadConfig(options.env).network
|
|
35
|
+
} catch (cause) {
|
|
36
|
+
return failure(cause instanceof Error ? cause.message : String(cause), 'edit .env as the message says, then run npm run connect-index again')
|
|
37
|
+
}
|
|
38
|
+
const theirs = (file.NETWORK ?? '').trim()
|
|
39
|
+
if (theirs !== '' && theirs !== network) {
|
|
40
|
+
return failure(`${options.from} connects to a ${theirs} index and this app's NETWORK is ${network}`, `ask the operator for a ${network} index, or set NETWORK=${theirs} in .env if this app belongs on ${theirs}`)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const url = (options.url ?? file.INDEX_URL ?? '').trim().replace(/\/+$/, '')
|
|
44
|
+
if (url === '') return failure(options.from == null ? 'no address given' : `${options.from} holds no INDEX_URL`, USAGE)
|
|
45
|
+
const values: Record<string, string> = { INDEX_URL: url }
|
|
46
|
+
const submitToken = options.submitToken ?? file.INDEX_SUBMIT_TOKEN
|
|
47
|
+
const callbackToken = options.callbackToken ?? file.INDEX_CALLBACK_TOKEN
|
|
48
|
+
if (submitToken != null && submitToken !== '') values.INDEX_SUBMIT_TOKEN = submitToken
|
|
49
|
+
if (callbackToken != null && callbackToken !== '') values.INDEX_CALLBACK_TOKEN = callbackToken
|
|
50
|
+
await updateEnvFile(options.envFile, values)
|
|
51
|
+
options.out(`Wrote the connection to .env: ${url}${values.INDEX_SUBMIT_TOKEN == null ? ', no tokens yet (go-live registers for them)' : ' with its tokens'}.`)
|
|
52
|
+
return await goLive({ ...options, env: { ...options.env, ...values } })
|
|
53
|
+
}
|