@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,358 @@
|
|
|
1
|
+
// Hand-ons under managed-custody@2 (spec/managed-custody.md): offer,
|
|
2
|
+
// acceptance, transfer. The custodian, this platform, fixes the current tip,
|
|
3
|
+
// a digest of the exact terms shown to the recipient and an expiry; the
|
|
4
|
+
// recipient accepts with a claim code or as a named identity; the custodian
|
|
5
|
+
// signs and keeps the acceptance record; the TRANSFER commits to it in
|
|
6
|
+
// field 15 and moves control to the recipient's managed key. Only the third
|
|
7
|
+
// step touches the chain. A declined or expired offer writes nothing.
|
|
8
|
+
import { Hash, PrivateKey, Transaction, Utils } from '@bsv/sdk'
|
|
9
|
+
import { bindAcceptanceToState, canonicalJson, findDppOutputs, inspectManagedAcceptance, signManagedAcceptance, type ManagedAcceptanceClaim, type ManagedAcceptanceRecord } from '@bsv/dpp-protocol'
|
|
10
|
+
import type { Parties, Party } from './parties.js'
|
|
11
|
+
import { isInterrupted, type OfferRecord, type PassportRecord, type Store } from './store.js'
|
|
12
|
+
import type { PlatformWallet } from './wallet.js'
|
|
13
|
+
import { WriteRefused, refuseRetiredProfile, type Writer } from './writer.js'
|
|
14
|
+
|
|
15
|
+
const instant = (offsetSeconds = 0): string => new Date(Date.now() + offsetSeconds * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z')
|
|
16
|
+
const sha256hex = (text: string): string => Utils.toHex(Hash.sha256(Utils.toArray(text, 'utf8')))
|
|
17
|
+
|
|
18
|
+
export interface CustodyOptions {
|
|
19
|
+
store: Store
|
|
20
|
+
wallet: PlatformWallet
|
|
21
|
+
parties: Parties
|
|
22
|
+
writer: Writer
|
|
23
|
+
/** How long an offer stays open. */
|
|
24
|
+
offerLifetimeSeconds?: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface CreateOfferInput {
|
|
28
|
+
record: PassportRecord
|
|
29
|
+
/** Direct callers already hold the party. HTTP authenticates the holder of the original offer on a retry. */
|
|
30
|
+
holder: Party | ((partyName: string) => Promise<Party>)
|
|
31
|
+
requestId?: string
|
|
32
|
+
terms: Record<string, unknown>
|
|
33
|
+
mechanism?: 'claim-code' | 'named-recipient'
|
|
34
|
+
recipientIdentityKey?: string
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type Outpoint = OfferRecord['expectedPredecessor']
|
|
38
|
+
const sameOutpoint = (left: Outpoint, right: Outpoint): boolean =>
|
|
39
|
+
left.txid === right.txid && left.outputIndex === right.outputIndex
|
|
40
|
+
|
|
41
|
+
/** Check a retained offer against the custodian's signed record using only public keys and the carried journal. */
|
|
42
|
+
export function acceptanceMatchesOffer(offer: OfferRecord, record: ManagedAcceptanceRecord, passport: PassportRecord, custodian: string): boolean {
|
|
43
|
+
const inspection = inspectManagedAcceptance(record, { custodians: [custodian] })
|
|
44
|
+
if (!inspection.signatureValid || inspection.failures.length > 0) return false
|
|
45
|
+
try {
|
|
46
|
+
return record.requestId === offer.requestId && record.passportId === offer.passportId &&
|
|
47
|
+
record.termsDigest === offer.termsDigest && sha256hex(canonicalJson(offer.terms)) === offer.termsDigest &&
|
|
48
|
+
record.lineageGenesis.txid === passport.states[0]?.txid && record.lineageGenesis.outputIndex === passport.states[0]?.outputIndex &&
|
|
49
|
+
canonicalJson(record.expectedPredecessor) === canonicalJson(offer.expectedPredecessor) &&
|
|
50
|
+
record.offer.mechanism === offer.mechanism && record.offer.recipientRef === (offer.mechanism === 'claim-code' ? offer.claimCodeHash : offer.recipientIdentityKey) &&
|
|
51
|
+
record.offer.holderIdentityKey === offer.holderIdentityKey && record.offer.createdAt === offer.createdAt && record.offer.expiresAt === offer.expiresAt
|
|
52
|
+
} catch {
|
|
53
|
+
return false
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A later state's actor held the preceding outpoint. Only the original holder may repeat or withdraw that offer. */
|
|
58
|
+
export function offerHolderName(record: PassportRecord, offer?: OfferRecord): string {
|
|
59
|
+
if (offer?.passportId === record.passportId) {
|
|
60
|
+
const predecessor = record.states.findIndex(state => sameOutpoint(state, offer.expectedPredecessor))
|
|
61
|
+
if (predecessor >= 0) return record.states[predecessor + 1]?.actor ?? record.holder.party
|
|
62
|
+
}
|
|
63
|
+
return record.holder.party
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function requireOfferTip(saved: PassportRecord | undefined, predecessor: Outpoint): asserts saved is PassportRecord {
|
|
67
|
+
const tip = saved?.states.at(-1)
|
|
68
|
+
if (tip && isInterrupted(tip)) throw new WriteRefused('operation-interrupted', 'resolve the unsettled passport state before making an offer')
|
|
69
|
+
if (!tip || !sameOutpoint(tip, predecessor)) throw new WriteRefused('tip-moved', 'the passport moved before the offer was saved')
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface AcceptOfferInput {
|
|
73
|
+
requestId: string
|
|
74
|
+
claimCode?: string
|
|
75
|
+
recipientIdentityKey?: string
|
|
76
|
+
/** The authenticated member accepting a named offer. */
|
|
77
|
+
recipient?: Party
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface AcceptedTransfer {
|
|
81
|
+
offer: OfferRecord
|
|
82
|
+
record: ManagedAcceptanceRecord
|
|
83
|
+
transferTxid: string
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export class Custody {
|
|
87
|
+
private readonly lifetime: number
|
|
88
|
+
private readonly accepting = new Map<string, Promise<AcceptedTransfer>>()
|
|
89
|
+
|
|
90
|
+
constructor(private readonly options: CustodyOptions) {
|
|
91
|
+
this.lifetime = options.offerLifetimeSeconds ?? 7 * 24 * 3600
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The holder asks the custodian to offer the passport, by claim code (the
|
|
96
|
+
* code is returned once and only its hash is kept) or to a named identity.
|
|
97
|
+
*/
|
|
98
|
+
async offer(args: CreateOfferInput): Promise<{ offer: OfferRecord; claimCode?: string }> {
|
|
99
|
+
const { record, requestId } = args
|
|
100
|
+
// Offer identifiers are also URL path segments. Dot segments would be normalised away by clients.
|
|
101
|
+
if (requestId !== undefined && (typeof requestId !== 'string' || !requestId.length || Buffer.byteLength(requestId) > 128 ||
|
|
102
|
+
/[\u0000-\u001f\u007f-\u009f]/u.test(requestId) || Buffer.from(requestId).toString() !== requestId || requestId === '.' || requestId === '..')) {
|
|
103
|
+
throw new WriteRefused('offer-request-id-invalid', 'an offer request ID must be printable text of 1 to 128 UTF-8 bytes and cannot be a dot segment')
|
|
104
|
+
}
|
|
105
|
+
const retained = requestId === undefined ? undefined : await this.options.store.getOffer(requestId)
|
|
106
|
+
const holder = typeof args.holder === 'function' ? await args.holder(offerHolderName(record, retained)) : args.holder
|
|
107
|
+
const mechanism = args.mechanism ?? 'claim-code'
|
|
108
|
+
const recipientIdentityKey = args.recipientIdentityKey ?? undefined
|
|
109
|
+
const termsDigest = sha256hex(canonicalJson(args.terms))
|
|
110
|
+
const replay = (existing: OfferRecord) => {
|
|
111
|
+
if (existing.passportId !== record.passportId || existing.brandId !== record.brandId || existing.holderIdentityKey !== holder.identityKey ||
|
|
112
|
+
existing.mechanism !== mechanism || (existing.recipientIdentityKey ?? undefined) !== recipientIdentityKey || existing.termsDigest !== termsDigest) {
|
|
113
|
+
throw new WriteRefused('offer-request-conflict', 'this request ID is already used for a different offer')
|
|
114
|
+
}
|
|
115
|
+
// Replay the creation response with its current status, omitting fields added by acceptance.
|
|
116
|
+
const { record: _acceptance, transferTxid: _transfer, ...offer } = existing
|
|
117
|
+
return { offer }
|
|
118
|
+
}
|
|
119
|
+
if (retained) return replay(retained)
|
|
120
|
+
// A hand-on ends in a TRANSFER, which the writer refuses under a retired profile. Refused here, no offer is left open that can never complete.
|
|
121
|
+
refuseRetiredProfile(record.profile)
|
|
122
|
+
if (record.status === 'retired') throw new WriteRefused('retired', `${record.passportId} is retired`)
|
|
123
|
+
if (record.holder.party !== holder.name) throw new WriteRefused('not-the-holder', `${holder.name} does not hold ${record.passportId}`)
|
|
124
|
+
const tip = record.states.at(-1)
|
|
125
|
+
if (tip == null) throw new WriteRefused('not-issued', `${record.passportId} has no state`)
|
|
126
|
+
if (mechanism !== 'named-recipient' && mechanism !== 'claim-code') throw new WriteRefused('offer-mechanism-invalid', 'use claim-code or named-recipient')
|
|
127
|
+
if (mechanism === 'named-recipient' && recipientIdentityKey === undefined) throw new WriteRefused('recipient-missing', 'a named-recipient offer needs the recipient identity key')
|
|
128
|
+
if (recipientIdentityKey !== undefined && (typeof recipientIdentityKey !== 'string' || !/^0[23][0-9a-f]{64}$/.test(recipientIdentityKey))) {
|
|
129
|
+
throw new WriteRefused('recipient-invalid', 'the recipient identity key must be a compressed public key in lower-case hex')
|
|
130
|
+
}
|
|
131
|
+
const claimCode = mechanism === 'claim-code' ? Utils.toHex(PrivateKey.fromRandom().toArray().slice(0, 8)) : undefined
|
|
132
|
+
const offer: OfferRecord = {
|
|
133
|
+
requestId: requestId ?? `offer-${Date.now().toString(36)}-${Utils.toHex(PrivateKey.fromRandom().toArray().slice(0, 4))}`,
|
|
134
|
+
passportId: record.passportId,
|
|
135
|
+
brandId: record.brandId,
|
|
136
|
+
mechanism,
|
|
137
|
+
...(claimCode == null ? {} : { claimCodeHash: sha256hex(claimCode) }),
|
|
138
|
+
...(recipientIdentityKey === undefined ? {} : { recipientIdentityKey }),
|
|
139
|
+
terms: args.terms,
|
|
140
|
+
termsDigest,
|
|
141
|
+
holderIdentityKey: holder.identityKey,
|
|
142
|
+
expectedPredecessor: { txid: tip.txid, outputIndex: tip.outputIndex },
|
|
143
|
+
createdAt: instant(),
|
|
144
|
+
expiresAt: instant(this.lifetime),
|
|
145
|
+
status: 'open',
|
|
146
|
+
}
|
|
147
|
+
if (await this.reserveOffer(offer)) return { offer, claimCode }
|
|
148
|
+
// Unique insertion also covers callers racing on the same request from different processes.
|
|
149
|
+
const winner = requestId === undefined ? undefined : await this.options.store.getOffer(requestId)
|
|
150
|
+
if (winner) return replay(winner)
|
|
151
|
+
throw new WriteRefused('offer-open', `${record.passportId} already has an open offer or an acceptance awaiting transfer.`)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
private async reserveOffer(offer: OfferRecord): Promise<boolean> {
|
|
155
|
+
const { store } = this.options
|
|
156
|
+
const saved = await store.getPassport(offer.passportId)
|
|
157
|
+
try {
|
|
158
|
+
requireOfferTip(saved, offer.expectedPredecessor)
|
|
159
|
+
} catch (cause) {
|
|
160
|
+
// Another creator may have inserted and transferred this request since the caller's initial lookup.
|
|
161
|
+
if (await store.getOffer(offer.requestId)) return false
|
|
162
|
+
throw cause
|
|
163
|
+
}
|
|
164
|
+
if (!await store.createOpenOffer(offer)) {
|
|
165
|
+
// An old or interrupted writer can leave an open offer at a spent outpoint. A matching
|
|
166
|
+
// request must replay it. A new request may replace it once its successor is settled.
|
|
167
|
+
const [open] = await store.listOffers({ passportId: offer.passportId, status: 'open' })
|
|
168
|
+
if (!open || open.requestId === offer.requestId || !saved.states.slice(0, -1).some(state => sameOutpoint(state, open.expectedPredecessor))) return false
|
|
169
|
+
await store.changeOfferStatus({ ...open, status: 'withdrawn' }, 'open')
|
|
170
|
+
if (!await store.createOpenOffer(offer)) return false
|
|
171
|
+
}
|
|
172
|
+
// The journal and offers are separate durable records. A delayed insert can overlap a spend.
|
|
173
|
+
const latest = await store.getPassport(offer.passportId)
|
|
174
|
+
try {
|
|
175
|
+
requireOfferTip(latest, offer.expectedPredecessor)
|
|
176
|
+
} catch (cause) {
|
|
177
|
+
// Acceptance or closure already won the race. Return the retained response without the creation secret.
|
|
178
|
+
if (!await store.changeOfferStatus({ ...offer, status: 'withdrawn' }, 'open')) return false
|
|
179
|
+
throw cause
|
|
180
|
+
}
|
|
181
|
+
return true
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async withdraw(requestId: string, holder: Party): Promise<OfferRecord> {
|
|
185
|
+
const offer = await this.options.store.getOffer(requestId)
|
|
186
|
+
if (offer == null) throw new WriteRefused('offer-unknown', `no offer ${requestId}`)
|
|
187
|
+
if (offer.holderIdentityKey !== holder.identityKey) throw new WriteRefused('not-the-holder', 'only the holder withdraws an offer')
|
|
188
|
+
if (offer.status !== 'open') throw new WriteRefused('offer-closed', `offer ${requestId} is ${offer.status}`)
|
|
189
|
+
return await this.closeOpenOffer(offer, 'withdrawn')
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** What a recipient sees before deciding: the terms the digest covers, and when the offer closes. */
|
|
193
|
+
async preview(requestId: string): Promise<{ requestId: string; passportId: string; terms: Record<string, unknown>; expiresAt: string; status: OfferRecord['status'] }> {
|
|
194
|
+
const offer = await this.options.store.getOffer(requestId)
|
|
195
|
+
if (offer == null) throw new WriteRefused('offer-unknown', `no offer ${requestId}`)
|
|
196
|
+
return { requestId, passportId: offer.passportId, terms: offer.terms, expiresAt: offer.expiresAt, status: offer.status }
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async decline(requestId: string, claimCode?: string, recipientIdentityKey?: string): Promise<OfferRecord> {
|
|
200
|
+
const offer = await this.openOffer(requestId, claimCode, recipientIdentityKey)
|
|
201
|
+
return await this.closeOpenOffer(offer, 'declined')
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
private async closeOpenOffer(offer: OfferRecord, status: 'withdrawn' | 'declined' | 'expired'): Promise<OfferRecord> {
|
|
205
|
+
const closed = { ...offer, status }
|
|
206
|
+
if (!await this.options.store.changeOfferStatus(closed, 'open')) throw new WriteRefused('offer-closed', `offer ${offer.requestId} is no longer open`)
|
|
207
|
+
return closed
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
private checkRecipient(offer: OfferRecord, claimCode?: string, recipientIdentityKey?: string): void {
|
|
211
|
+
if (offer.mechanism === 'claim-code' && (typeof claimCode !== 'string' || sha256hex(claimCode) !== offer.claimCodeHash)) throw new WriteRefused('claim-code-wrong', 'the claim code does not match this offer')
|
|
212
|
+
if (offer.mechanism === 'named-recipient' && (recipientIdentityKey == null || recipientIdentityKey !== offer.recipientIdentityKey)) throw new WriteRefused('recipient-wrong', 'this offer is addressed to another identity')
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private recipientFor(offer: OfferRecord, args: AcceptOfferInput): Party {
|
|
216
|
+
const managed = this.options.parties.recipient(offer.requestId)
|
|
217
|
+
this.checkRecipient(offer, args.claimCode, args.recipient?.identityKey ?? args.recipientIdentityKey)
|
|
218
|
+
if (offer.mechanism === 'claim-code') return managed
|
|
219
|
+
const recipient = args.recipient ?? managed
|
|
220
|
+
if (recipient.identityKey !== offer.recipientIdentityKey) throw new WriteRefused('recipient-wrong', 'the accepting party must control the named identity')
|
|
221
|
+
return recipient
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
private async openOffer(requestId: string, claimCode?: string, recipientIdentityKey?: string): Promise<OfferRecord> {
|
|
225
|
+
const offer = await this.options.store.getOffer(requestId)
|
|
226
|
+
if (offer == null) throw new WriteRefused('offer-unknown', `no offer ${requestId}`)
|
|
227
|
+
if (offer.status !== 'open') throw new WriteRefused('offer-closed', `offer ${requestId} is ${offer.status}`)
|
|
228
|
+
if (offer.expiresAt <= instant()) {
|
|
229
|
+
await this.closeOpenOffer(offer, 'expired')
|
|
230
|
+
throw new WriteRefused('offer-expired', `offer ${requestId} expired at ${offer.expiresAt}`)
|
|
231
|
+
}
|
|
232
|
+
this.checkRecipient(offer, claimCode, recipientIdentityKey)
|
|
233
|
+
return offer
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* The recipient accepts: the custodian derives the recipient's managed
|
|
238
|
+
* identity, records and signs the acceptance, keeps it, then writes the
|
|
239
|
+
* TRANSFER that commits to it. The tip must still be the one the offer named.
|
|
240
|
+
*/
|
|
241
|
+
async accept(args: AcceptOfferInput): Promise<AcceptedTransfer> {
|
|
242
|
+
const offer = await this.options.store.getOffer(args.requestId)
|
|
243
|
+
if (offer == null) throw new WriteRefused('offer-unknown', `no offer ${args.requestId}`)
|
|
244
|
+
const recipient = this.recipientFor(offer, args)
|
|
245
|
+
const underway = this.accepting.get(offer.requestId)
|
|
246
|
+
if (underway != null) return await underway
|
|
247
|
+
const pending = this.acceptOffer(offer, args, recipient)
|
|
248
|
+
this.accepting.set(offer.requestId, pending)
|
|
249
|
+
try {
|
|
250
|
+
return await pending
|
|
251
|
+
} finally {
|
|
252
|
+
this.accepting.delete(offer.requestId)
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
private async acceptOffer(offer: OfferRecord, args: AcceptOfferInput, recipient: Party): Promise<AcceptedTransfer> {
|
|
257
|
+
const { store, wallet } = this.options
|
|
258
|
+
if (offer.status !== 'open' && offer.status !== 'accepted' && offer.status !== 'transferred') throw new WriteRefused('offer-closed', `offer ${offer.requestId} is ${offer.status}`)
|
|
259
|
+
const passport = await store.getPassport(offer.passportId)
|
|
260
|
+
if (passport == null) throw new WriteRefused('passport-unknown', `no passport ${offer.passportId}`)
|
|
261
|
+
if (offer.status !== 'open') {
|
|
262
|
+
if (offer.record == null) throw new WriteRefused('acceptance-invalid', 'the accepted offer has no signed record')
|
|
263
|
+
await this.checkAcceptance(offer, offer.record, passport, recipient)
|
|
264
|
+
return await this.completeTransfer(offer, offer.record, passport, recipient)
|
|
265
|
+
}
|
|
266
|
+
if (offer.expiresAt <= instant()) {
|
|
267
|
+
await this.closeOpenOffer(offer, 'expired')
|
|
268
|
+
throw new WriteRefused('offer-expired', `offer ${offer.requestId} expired at ${offer.expiresAt}`)
|
|
269
|
+
}
|
|
270
|
+
refuseRetiredProfile(passport.profile)
|
|
271
|
+
const tip = passport.states.at(-1)
|
|
272
|
+
if (tip?.txid !== offer.expectedPredecessor.txid || tip.outputIndex !== offer.expectedPredecessor.outputIndex) throw new WriteRefused('tip-moved', 'the passport moved since the offer was made; ask for a new offer')
|
|
273
|
+
|
|
274
|
+
const claim: ManagedAcceptanceClaim = {
|
|
275
|
+
acceptanceFormat: 'dpp-managed-acceptance@2',
|
|
276
|
+
requestId: offer.requestId,
|
|
277
|
+
passportId: offer.passportId,
|
|
278
|
+
lineageGenesis: { txid: passport.states[0].txid, outputIndex: passport.states[0].outputIndex },
|
|
279
|
+
expectedPredecessor: offer.expectedPredecessor,
|
|
280
|
+
termsDigest: offer.termsDigest,
|
|
281
|
+
offer: {
|
|
282
|
+
holderIdentityKey: offer.holderIdentityKey,
|
|
283
|
+
createdAt: offer.createdAt,
|
|
284
|
+
expiresAt: offer.expiresAt,
|
|
285
|
+
mechanism: offer.mechanism,
|
|
286
|
+
recipientRef: offer.mechanism === 'claim-code' ? offer.claimCodeHash : offer.recipientIdentityKey,
|
|
287
|
+
},
|
|
288
|
+
acceptance: {
|
|
289
|
+
recipientIdentityKey: recipient.identityKey,
|
|
290
|
+
destinationKey: await recipient.controllerKey(offer.passportId),
|
|
291
|
+
acceptedAt: instant(),
|
|
292
|
+
evidenceKind: 'custodian-attested',
|
|
293
|
+
},
|
|
294
|
+
custodian: wallet.identityKey,
|
|
295
|
+
}
|
|
296
|
+
const record = await signManagedAcceptance(claim, wallet.custodian)
|
|
297
|
+
await this.checkAcceptance(offer, record, passport, recipient)
|
|
298
|
+
const accepted: OfferRecord = { ...offer, status: 'accepted', record }
|
|
299
|
+
if (!await store.changeOfferStatus(accepted, 'open')) {
|
|
300
|
+
const held = await store.getOffer(offer.requestId)
|
|
301
|
+
if (held == null || held.status === 'open') throw new WriteRefused('offer-changed', 'the offer changed while its acceptance was being recorded')
|
|
302
|
+
return await this.acceptOffer(held, args, this.recipientFor(held, args))
|
|
303
|
+
}
|
|
304
|
+
return await this.completeTransfer(accepted, record, passport, recipient)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
private async checkAcceptance(offer: OfferRecord, record: ManagedAcceptanceRecord, passport: PassportRecord, recipient: Party): Promise<void> {
|
|
308
|
+
if (!acceptanceMatchesOffer(offer, record, passport, this.options.wallet.identityKey)
|
|
309
|
+
|| record.acceptance.recipientIdentityKey !== recipient.identityKey || record.acceptance.destinationKey !== await recipient.controllerKey(offer.passportId)) {
|
|
310
|
+
throw new WriteRefused('acceptance-invalid', 'the signed acceptance must identify this offer, recipient and destination')
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
private async completeTransfer(offer: OfferRecord, record: ManagedAcceptanceRecord, passport: PassportRecord, recipient: Party): Promise<AcceptedTransfer> {
|
|
315
|
+
const { store, writer } = this.options
|
|
316
|
+
const predecessor = passport.states.findIndex(entry => entry.txid === offer.expectedPredecessor.txid && entry.outputIndex === offer.expectedPredecessor.outputIndex)
|
|
317
|
+
if (predecessor < 0) throw new WriteRefused('tip-moved', 'the passport no longer holds the predecessor of this offer')
|
|
318
|
+
let entry = passport.states[predecessor + 1]
|
|
319
|
+
if (entry == null) {
|
|
320
|
+
if (offer.status === 'transferred') throw new WriteRefused('acceptance-mismatch', 'the completed offer has no retained transfer')
|
|
321
|
+
refuseRetiredProfile(passport.profile)
|
|
322
|
+
try {
|
|
323
|
+
const outcome = await writer.transfer({ record: passport, holder: this.holderOf(passport), recipient, acceptance: record, eventData: { word: typeof offer.terms.word === 'string' ? offer.terms.word : 'Handed on' } })
|
|
324
|
+
entry = outcome.entry
|
|
325
|
+
} catch (cause) {
|
|
326
|
+
// Another process may have completed the transfer, or a successful journal write may have lost its response.
|
|
327
|
+
const retained = (await store.getPassport(offer.passportId))?.states[predecessor + 1]
|
|
328
|
+
if (retained == null || (retained.network !== 'accepted' && retained.network !== 'dry-run')) throw cause
|
|
329
|
+
entry = retained
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
if (entry.op !== 'TRANSFER') throw new WriteRefused('tip-moved', 'another operation followed the predecessor of this offer')
|
|
333
|
+
const tx = Transaction.fromHex(entry.rawTx)
|
|
334
|
+
const outputs = findDppOutputs(tx)
|
|
335
|
+
const output = outputs[0]
|
|
336
|
+
if (entry.txid !== tx.id('hex') || outputs.length !== 1 || output?.outputIndex !== entry.outputIndex || output.state.version !== '2'
|
|
337
|
+
|| !tx.inputs.some(input => input.sourceTXID === offer.expectedPredecessor.txid && input.sourceOutputIndex === offer.expectedPredecessor.outputIndex)
|
|
338
|
+
|| bindAcceptanceToState(record, output.state).length > 0) throw new WriteRefused('acceptance-mismatch', 'the retained transfer does not bind this signed acceptance')
|
|
339
|
+
if (entry.network !== 'accepted' && entry.network !== 'dry-run') throw new WriteRefused('operation-interrupted', `the send of transfer ${entry.txid} has no successful answer`)
|
|
340
|
+
const completed: OfferRecord = { ...offer, status: 'transferred', transferTxid: entry.txid }
|
|
341
|
+
if (offer.status !== 'transferred' && await store.changeOfferStatus(completed, 'accepted')) return { offer: completed, record, transferTxid: entry.txid }
|
|
342
|
+
const held = await store.getOffer(offer.requestId)
|
|
343
|
+
if (held?.status !== 'transferred' || held.transferTxid !== entry.txid || held.record == null || canonicalJson(held.record) !== canonicalJson(record)) throw new WriteRefused('acceptance-mismatch', 'the offer does not record this completed transfer')
|
|
344
|
+
return { offer: held, record, transferTxid: entry.txid }
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** The party that controls the passport now, resolved from the journal's holder name. */
|
|
348
|
+
holderOf(passport: PassportRecord): Party {
|
|
349
|
+
const { parties } = this.options
|
|
350
|
+
const split = passport.holder.party.indexOf(':')
|
|
351
|
+
const scope = passport.holder.party.slice(0, split)
|
|
352
|
+
const id = passport.holder.party.slice(split + 1)
|
|
353
|
+
if (scope === 'brand') return parties.brand(id)
|
|
354
|
+
if (scope === 'recipient') return parties.recipient(id)
|
|
355
|
+
if (scope === 'member') return parties.member(id)
|
|
356
|
+
throw new WriteRefused('holder-unknown', `the holder ${passport.holder.party} is not a managed identity this platform derives`)
|
|
357
|
+
}
|
|
358
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// An index in this process for development and tests: the real topic
|
|
2
|
+
// managers, lookup services 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. Beside the passport topic it admits generic attestation
|
|
7
|
+
// anchors on tm_attestation, from any anchoring service, as the reference
|
|
8
|
+
// index does when its operator names none; a lifecycle claim's anchors are
|
|
9
|
+
// found there by passport. Production runs the reference index as its own service
|
|
10
|
+
// (a separate operator project or an existing provider) and never this.
|
|
11
|
+
//
|
|
12
|
+
// The HTTP host is the package's ./server export. Imported, it is a library
|
|
13
|
+
// and starts nothing by itself.
|
|
14
|
+
import { PrivateKey } from '@bsv/sdk'
|
|
15
|
+
import { policySigningPreimage, type PublisherPolicy } from '@bsv/dpp-protocol'
|
|
16
|
+
import type { RegistrationSettings } from '@bsv/dpp-overlay'
|
|
17
|
+
import type { Network } from './config.js'
|
|
18
|
+
|
|
19
|
+
export interface DevIndex {
|
|
20
|
+
url: string
|
|
21
|
+
submitToken: string
|
|
22
|
+
callbackToken: string
|
|
23
|
+
/** The development operator's identity key, which signs the policy and, with registration on, each appended version. */
|
|
24
|
+
operatorKey: string
|
|
25
|
+
/** The identity key this index signs its evidence packages under: a fixed development key, set apart from the operator's and the publisher's. */
|
|
26
|
+
exporterIdentityKey: string
|
|
27
|
+
/** Under approval, what the operator's command line would do: append the version and mark the key approved. */
|
|
28
|
+
approve?: (publisherKey: string) => Promise<void>
|
|
29
|
+
close: () => Promise<void>
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface DevIndexOptions {
|
|
33
|
+
/** The key the genesis names as the state publisher. */
|
|
34
|
+
publisherKey: string
|
|
35
|
+
/** What the index reports on GET /health, so it agrees with the app's NETWORK. */
|
|
36
|
+
network: Network
|
|
37
|
+
/** Run POST /register in this mode, for the go-live test; off by default. */
|
|
38
|
+
registration?: 'open' | 'approval'
|
|
39
|
+
/** The custody profile the index declares; managed custody unless the test says otherwise. */
|
|
40
|
+
custody?: 'managed-custody@2' | 'record-model-baseline@2'
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function startDevIndex(options: DevIndexOptions): Promise<DevIndex> {
|
|
44
|
+
const { publisherKey, network } = options
|
|
45
|
+
const overlay = await import('@bsv/overlay')
|
|
46
|
+
const topics = await import('@bsv/dpp-overlay')
|
|
47
|
+
const host = await import('@bsv/dpp-overlay/server')
|
|
48
|
+
|
|
49
|
+
// The publisher key policy of the @bsv/dpp-overlay README: one operator signs a genesis naming the platform wallet as a state publisher.
|
|
50
|
+
const operatorKey = PrivateKey.fromHex('44'.repeat(32))
|
|
51
|
+
const operator = 'Development operator'
|
|
52
|
+
const genesis: PublisherPolicy = {
|
|
53
|
+
policyFormat: 'dpp-publisher-policy@1',
|
|
54
|
+
policyVersion: 1,
|
|
55
|
+
scope: { operatorProfile: 'single-operator@1', operators: [operator], topics: ['tm_dpp'] },
|
|
56
|
+
issuedAt: '2026-01-01T00:00:00Z',
|
|
57
|
+
publishers: [{ key: publisherKey, role: 'state-publisher', activeFrom: '2026-01-01T00:00:00Z' }],
|
|
58
|
+
authorisation: { kind: 'genesis', signer: operatorKey.toPublicKey().toString(), suite: 'bsv-ecdsa-der', value: '' },
|
|
59
|
+
}
|
|
60
|
+
genesis.authorisation.value = operatorKey.sign(policySigningPreimage(genesis)).toDER('hex') as string
|
|
61
|
+
const policy = topics.loadPublisherPolicyJson(JSON.stringify([genesis]), { [operator]: operatorKey.toPublicKey().toString() })
|
|
62
|
+
|
|
63
|
+
const managedAcceptance = (options.custody ?? 'managed-custody@2') === 'managed-custody@2'
|
|
64
|
+
const records = new topics.InMemoryDppStorage()
|
|
65
|
+
const storage = new topics.InMemoryOverlayStorage()
|
|
66
|
+
const attestations = new topics.InMemoryAttestationStorage()
|
|
67
|
+
const lookupServices = { ls_dpp: new topics.DppLookupService(records), ls_attestation: new topics.AttestationLookupService(attestations) }
|
|
68
|
+
const silent = { ...console, log() {}, info() {}, warn() {}, error() {} }
|
|
69
|
+
const engine = new overlay.Engine(
|
|
70
|
+
{ tm_dpp: new topics.DppTopicManager('', { publisherPolicy: policy.chain, managedAcceptance, admittedOutputs: storage }), tm_attestation: new topics.AttestationTopicManager() },
|
|
71
|
+
lookupServices,
|
|
72
|
+
storage,
|
|
73
|
+
'scripts only',
|
|
74
|
+
undefined,
|
|
75
|
+
undefined,
|
|
76
|
+
undefined,
|
|
77
|
+
undefined,
|
|
78
|
+
undefined,
|
|
79
|
+
{ tm_dpp: false, tm_attestation: false },
|
|
80
|
+
false,
|
|
81
|
+
'[index] ',
|
|
82
|
+
false,
|
|
83
|
+
undefined,
|
|
84
|
+
silent
|
|
85
|
+
)
|
|
86
|
+
const submitToken = 'dev-submit-token'
|
|
87
|
+
const callbackToken = 'dev-callback-token'
|
|
88
|
+
// With registration on, a registering key's tokens come from this store and
|
|
89
|
+
// its policy version from the registration store; the address the request
|
|
90
|
+
// must name is this index's own, known only once the socket is bound, so the
|
|
91
|
+
// settings are completed after the start.
|
|
92
|
+
const publisherTokens = options.registration == null ? undefined : new topics.InMemoryPublisherTokenStore()
|
|
93
|
+
const registration: RegistrationSettings | undefined =
|
|
94
|
+
options.registration == null
|
|
95
|
+
? undefined
|
|
96
|
+
: { mode: options.registration, signingKey: operatorKey, indexUrl: 'http://127.0.0.1', custodyProfile: topics.declaredCustodyProfile(managedAcceptance), store: new topics.InMemoryRegistrationStore(), rateLimitPerHour: 1_000, trustProxy: false }
|
|
97
|
+
// The index signs evidence packages, as an operator's does once EXPORTER_PRIVATE_KEY is set, so an export of this application
|
|
98
|
+
// can be made and read back in development. The key is fixed and public knowledge, like every key of this index.
|
|
99
|
+
const exporterKey = PrivateKey.fromHex('55'.repeat(32))
|
|
100
|
+
const service = await host.startOverlayService(engine, {
|
|
101
|
+
port: 0,
|
|
102
|
+
host: '127.0.0.1',
|
|
103
|
+
network,
|
|
104
|
+
submitToken,
|
|
105
|
+
proofToken: callbackToken,
|
|
106
|
+
exportIdentityKey: exporterKey.toHex(),
|
|
107
|
+
components: { records, engineStorage: storage, lookupServices, publisherPolicy: policy, managedAcceptance, ...(publisherTokens == null ? {} : { publisherTokens }), ...(registration == null ? {} : { registration }) },
|
|
108
|
+
})
|
|
109
|
+
const url = `http://127.0.0.1:${service.port}`
|
|
110
|
+
if (registration != null) registration.indexUrl = url
|
|
111
|
+
const approve = registration == null
|
|
112
|
+
? undefined
|
|
113
|
+
: async (publisherKey: string): Promise<void> => {
|
|
114
|
+
const record = await registration.store.registration(publisherKey)
|
|
115
|
+
if (record == null || record.status !== 'pending') throw new Error(`${publisherKey} is not pending`)
|
|
116
|
+
const version = await topics.appendRegistrationVersion(policy, registration.store, operatorKey, { add: { key: publisherKey, role: 'state-publisher' } }, new Date())
|
|
117
|
+
await registration.store.saveRegistration({ ...record, status: 'approved', policyVersion: version.policyVersion, decidedAt: new Date().toISOString() })
|
|
118
|
+
}
|
|
119
|
+
return { url, submitToken, callbackToken, operatorKey: operatorKey.toPublicKey().toString(), exporterIdentityKey: exporterKey.toPublicKey().toString(), ...(approve == null ? {} : { approve }), close: service.close }
|
|
120
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// The project's .env, which go-live, connect-index and wallet write to:
|
|
2
|
+
// the named keys are rewritten in place and a missing key is appended, every
|
|
3
|
+
// other line and comment stays, and the file is written through a temporary
|
|
4
|
+
// file and a rename, readable by its owner only, because it holds the wallet
|
|
5
|
+
// root key and the index tokens.
|
|
6
|
+
import { randomBytes, randomUUID } from 'node:crypto'
|
|
7
|
+
import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
8
|
+
import { dirname, join } from 'node:path'
|
|
9
|
+
import { parseEnv } from 'node:util'
|
|
10
|
+
|
|
11
|
+
/** The file's settings, or nothing when it does not exist. */
|
|
12
|
+
export function readEnvFile(path: string): Record<string, string> {
|
|
13
|
+
if (!existsSync(path)) return {}
|
|
14
|
+
const parsed: Record<string, string> = {}
|
|
15
|
+
for (const [key, value] of Object.entries(parseEnv(readFileSync(path, 'utf8')))) if (value != null) parsed[key] = value
|
|
16
|
+
return parsed
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function updateEnvFile(path: string, values: Record<string, string>): Promise<void> {
|
|
20
|
+
const lines = existsSync(path) ? readFileSync(path, 'utf8').split('\n') : []
|
|
21
|
+
if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop()
|
|
22
|
+
// Every occurrence is rewritten: the file's readers take the last one, and a
|
|
23
|
+
// key pasted twice would otherwise keep an old value where the API reads it.
|
|
24
|
+
const seen = new Set<string>()
|
|
25
|
+
const rewritten = lines.map((line) => {
|
|
26
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line)
|
|
27
|
+
if (match == null || !(match[1] in values)) return line
|
|
28
|
+
seen.add(match[1])
|
|
29
|
+
return `${match[1]}=${values[match[1]]}`
|
|
30
|
+
})
|
|
31
|
+
for (const [key, value] of Object.entries(values)) if (!seen.has(key)) rewritten.push(`${key}=${value}`)
|
|
32
|
+
const temporary = join(dirname(path), `.${randomUUID()}.env.tmp`)
|
|
33
|
+
try {
|
|
34
|
+
writeFileSync(temporary, rewritten.join('\n') + '\n', { mode: 0o600 })
|
|
35
|
+
renameSync(temporary, path)
|
|
36
|
+
} finally {
|
|
37
|
+
rmSync(temporary, { force: true })
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const ROOT_KEY_GENERATED = 'Generated WALLET_ROOT_KEY into .env. Back the file up: this key is the wallet.'
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* A fresh project has no WALLET_ROOT_KEY, and without one a test wallet with
|
|
45
|
+
* fixed, publicly known keys stands in. go-live and wallet both generate the
|
|
46
|
+
* key into the file first, so the publisher key an index is given is the one
|
|
47
|
+
* that later goes live. Answers whether it generated one; `env` gains it.
|
|
48
|
+
*/
|
|
49
|
+
export async function generateRootKey(path: string, env: NodeJS.ProcessEnv): Promise<boolean> {
|
|
50
|
+
if ((env.WALLET_ROOT_KEY ?? '').trim() !== '') return false
|
|
51
|
+
const rootKey = randomBytes(32).toString('hex')
|
|
52
|
+
await updateEnvFile(path, { WALLET_ROOT_KEY: rootKey })
|
|
53
|
+
env.WALLET_ROOT_KEY = rootKey
|
|
54
|
+
return true
|
|
55
|
+
}
|
|
@@ -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
|
+
}
|