@bsv/create-dpp-app 0.1.0-beta.1 → 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.
Files changed (143) hide show
  1. package/NOTICE +2 -0
  2. package/PATENTS +12 -0
  3. package/README.md +26 -6
  4. package/dist/index.js +36 -8
  5. package/package.json +9 -5
  6. package/template/Dockerfile +4 -2
  7. package/template/README.md +297 -42
  8. package/template/_env.example +82 -13
  9. package/template/_github/workflows/ci.yml +3 -3
  10. package/template/apps/api/API.md +86 -16
  11. package/template/apps/api/package.json +9 -4
  12. package/template/apps/api/src/bound-profiles.ts +590 -0
  13. package/template/apps/api/src/claims.ts +175 -56
  14. package/template/apps/api/src/cli.ts +64 -7
  15. package/template/apps/api/src/config.ts +124 -10
  16. package/template/apps/api/src/custody.ts +241 -69
  17. package/template/apps/api/src/dev-index.ts +58 -9
  18. package/template/apps/api/src/env-file.ts +55 -0
  19. package/template/apps/api/src/epcis/exchange.ts +434 -0
  20. package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
  21. package/template/apps/api/src/epcis/routes.ts +364 -0
  22. package/template/apps/api/src/epcis/sources.ts +142 -0
  23. package/template/apps/api/src/go-live.ts +226 -0
  24. package/template/apps/api/src/http-error.ts +15 -0
  25. package/template/apps/api/src/identifiers.ts +1 -1
  26. package/template/apps/api/src/index-client.ts +131 -6
  27. package/template/apps/api/src/index-projects.ts +53 -0
  28. package/template/apps/api/src/lifecycle-authority.ts +49 -0
  29. package/template/apps/api/src/lifecycle.ts +485 -0
  30. package/template/apps/api/src/main.ts +10 -2
  31. package/template/apps/api/src/parties.ts +2 -2
  32. package/template/apps/api/src/platform.ts +72 -17
  33. package/template/apps/api/src/portability/commands.ts +224 -0
  34. package/template/apps/api/src/portability/export.ts +708 -0
  35. package/template/apps/api/src/portability/package.ts +270 -0
  36. package/template/apps/api/src/portability/restore.ts +863 -0
  37. package/template/apps/api/src/profiles.ts +38 -13
  38. package/template/apps/api/src/reader.ts +172 -3
  39. package/template/apps/api/src/resolver.ts +159 -0
  40. package/template/apps/api/src/sector-examples.ts +390 -0
  41. package/template/apps/api/src/server.ts +253 -60
  42. package/template/apps/api/src/store.ts +198 -21
  43. package/template/apps/api/src/validation-engine.ts +172 -0
  44. package/template/apps/api/src/wallet.ts +30 -17
  45. package/template/apps/api/src/worker.ts +20 -13
  46. package/template/apps/api/src/writer.ts +383 -131
  47. package/template/apps/api/test/bound-http.test.ts +496 -0
  48. package/template/apps/api/test/bound-profiles.test.ts +547 -0
  49. package/template/apps/api/test/config.test.ts +148 -3
  50. package/template/apps/api/test/custody-journal.test.ts +415 -0
  51. package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
  52. package/template/apps/api/test/custom-profile.test.ts +167 -0
  53. package/template/apps/api/test/env-file.test.ts +53 -0
  54. package/template/apps/api/test/epcis-fixtures.ts +270 -0
  55. package/template/apps/api/test/epcis-http.test.ts +1179 -0
  56. package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
  57. package/template/apps/api/test/epcis-separation.test.ts +253 -0
  58. package/template/apps/api/test/epcis-web.test.ts +230 -0
  59. package/template/apps/api/test/exit-exercise.test.ts +1038 -0
  60. package/template/apps/api/test/external-index.test.ts +3 -2
  61. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
  62. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
  63. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
  64. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
  65. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
  66. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
  67. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
  68. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
  69. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
  70. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
  71. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
  72. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
  73. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
  74. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
  75. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
  76. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
  77. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
  78. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
  79. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
  80. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
  81. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
  82. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
  83. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
  84. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
  85. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
  86. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
  87. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
  88. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
  89. package/template/apps/api/test/go-live.test.ts +179 -0
  90. package/template/apps/api/test/gs1-global-setup.ts +33 -0
  91. package/template/apps/api/test/gs1-test-env.ts +5 -0
  92. package/template/apps/api/test/identifier-host.test.ts +256 -0
  93. package/template/apps/api/test/index-projects.test.ts +81 -0
  94. package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
  95. package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
  96. package/template/apps/api/test/lifecycle.test.ts +17 -6
  97. package/template/apps/api/test/manifest-notice.test.ts +36 -0
  98. package/template/apps/api/test/network-guard.ts +113 -0
  99. package/template/apps/api/test/portability.test.ts +655 -0
  100. package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
  101. package/template/apps/api/test/retired-profiles.test.ts +216 -0
  102. package/template/apps/api/test/sector-cutover.test.ts +95 -0
  103. package/template/apps/api/test/sector-forms.test.ts +420 -0
  104. package/template/apps/api/test/unjoined-index.test.ts +62 -0
  105. package/template/apps/api/test/validation-engine.test.ts +328 -0
  106. package/template/apps/api/test/wallet-monitor.test.ts +38 -0
  107. package/template/apps/api/test/writer-journal.test.ts +327 -0
  108. package/template/apps/api/vitest.config.ts +3 -0
  109. package/template/apps/web/src/app.tsx +8 -4
  110. package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
  111. package/template/apps/web/src/components/bound/field-view.tsx +237 -0
  112. package/template/apps/web/src/components/bound/pieces.tsx +169 -0
  113. package/template/apps/web/src/components/bound/readings.tsx +152 -0
  114. package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
  115. package/template/apps/web/src/components/claim-dialog.tsx +344 -0
  116. package/template/apps/web/src/components/epcis-events.tsx +119 -0
  117. package/template/apps/web/src/components/layout.tsx +17 -0
  118. package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
  119. package/template/apps/web/src/components/passport-form.tsx +2 -2
  120. package/template/apps/web/src/components/read-passport.tsx +4 -3
  121. package/template/apps/web/src/components/reading.tsx +32 -39
  122. package/template/apps/web/src/lib/api.ts +136 -26
  123. package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
  124. package/template/apps/web/src/lib/bound/display.ts +122 -0
  125. package/template/apps/web/src/lib/bound/fields.ts +128 -0
  126. package/template/apps/web/src/lib/bound/form-model.ts +521 -0
  127. package/template/apps/web/src/lib/bound/forms.ts +15 -0
  128. package/template/apps/web/src/lib/bound/identity.ts +48 -0
  129. package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
  130. package/template/apps/web/src/lib/bound/units.ts +37 -0
  131. package/template/apps/web/src/lib/epcis.ts +345 -0
  132. package/template/apps/web/src/lib/format.ts +27 -4
  133. package/template/apps/web/src/lib/lifecycle.ts +350 -0
  134. package/template/apps/web/src/pages/accept.tsx +8 -3
  135. package/template/apps/web/src/pages/events.tsx +388 -0
  136. package/template/apps/web/src/pages/new-passport.tsx +25 -2
  137. package/template/apps/web/src/pages/operations.tsx +22 -3
  138. package/template/apps/web/src/pages/passport.tsx +226 -162
  139. package/template/apps/web/src/pages/public-passport.tsx +50 -10
  140. package/template/apps/web/src/pages/wallet.tsx +1 -1
  141. package/template/apps/web/vite.config.ts +12 -4
  142. package/template/deploy/compose.yml +14 -2
  143. package/template/package.json +9 -3
@@ -1,16 +1,16 @@
1
- // Hand-ons under managed-custody@1 (spec/managed-custody.md): offer,
1
+ // Hand-ons under managed-custody@2 (spec/managed-custody.md): offer,
2
2
  // acceptance, transfer. The custodian, this platform, fixes the current tip,
3
3
  // a digest of the exact terms shown to the recipient and an expiry; the
4
4
  // recipient accepts with a claim code or as a named identity; the custodian
5
5
  // signs and keeps the acceptance record; the TRANSFER commits to it in
6
6
  // field 15 and moves control to the recipient's managed key. Only the third
7
7
  // step touches the chain. A declined or expired offer writes nothing.
8
- import { Hash, PrivateKey, Utils } from '@bsv/sdk'
9
- import { bindAcceptanceToState, canonicalJson, inspectManagedAcceptance, signManagedAcceptance, type ManagedAcceptanceClaim, type ManagedAcceptanceRecord } from '@bsv/dpp-protocol'
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
10
  import type { Parties, Party } from './parties.js'
11
- import type { OfferRecord, PassportRecord, Store } from './store.js'
11
+ import { isInterrupted, type OfferRecord, type PassportRecord, type Store } from './store.js'
12
12
  import type { PlatformWallet } from './wallet.js'
13
- import { WriteRefused, type Writer } from './writer.js'
13
+ import { WriteRefused, refuseRetiredProfile, type Writer } from './writer.js'
14
14
 
15
15
  const instant = (offsetSeconds = 0): string => new Date(Date.now() + offsetSeconds * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z')
16
16
  const sha256hex = (text: string): string => Utils.toHex(Hash.sha256(Utils.toArray(text, 'utf8')))
@@ -24,8 +24,68 @@ export interface CustodyOptions {
24
24
  offerLifetimeSeconds?: number
25
25
  }
26
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
+
27
86
  export class Custody {
28
87
  private readonly lifetime: number
88
+ private readonly accepting = new Map<string, Promise<AcceptedTransfer>>()
29
89
 
30
90
  constructor(private readonly options: CustodyOptions) {
31
91
  this.lifetime = options.offerLifetimeSeconds ?? 7 * 24 * 3600
@@ -35,34 +95,90 @@ export class Custody {
35
95
  * The holder asks the custodian to offer the passport, by claim code (the
36
96
  * code is returned once and only its hash is kept) or to a named identity.
37
97
  */
38
- async offer(args: { record: PassportRecord; holder: Party; terms: Record<string, unknown>; mechanism?: 'claim-code' | 'named-recipient'; recipientIdentityKey?: string }): Promise<{ offer: OfferRecord; claimCode?: string }> {
39
- const { record, holder } = args
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)
40
122
  if (record.status === 'retired') throw new WriteRefused('retired', `${record.passportId} is retired`)
41
123
  if (record.holder.party !== holder.name) throw new WriteRefused('not-the-holder', `${holder.name} does not hold ${record.passportId}`)
42
124
  const tip = record.states.at(-1)
43
125
  if (tip == null) throw new WriteRefused('not-issued', `${record.passportId} has no state`)
44
- const open = await this.options.store.listOffers({ passportId: record.passportId, status: 'open' })
45
- if (open.length > 0) throw new WriteRefused('offer-open', `${record.passportId} already has an open offer ${open[0].requestId}; withdraw it first`)
46
- const mechanism = args.mechanism ?? 'claim-code'
47
- if (mechanism === 'named-recipient' && args.recipientIdentityKey == null) throw new WriteRefused('recipient-missing', 'a named-recipient offer needs the recipient identity key')
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
+ }
48
131
  const claimCode = mechanism === 'claim-code' ? Utils.toHex(PrivateKey.fromRandom().toArray().slice(0, 8)) : undefined
49
132
  const offer: OfferRecord = {
50
- requestId: `offer-${Date.now().toString(36)}-${Utils.toHex(PrivateKey.fromRandom().toArray().slice(0, 4))}`,
133
+ requestId: requestId ?? `offer-${Date.now().toString(36)}-${Utils.toHex(PrivateKey.fromRandom().toArray().slice(0, 4))}`,
51
134
  passportId: record.passportId,
52
135
  brandId: record.brandId,
53
136
  mechanism,
54
- claimCodeHash: claimCode == null ? undefined : sha256hex(claimCode),
55
- recipientIdentityKey: args.recipientIdentityKey,
137
+ ...(claimCode == null ? {} : { claimCodeHash: sha256hex(claimCode) }),
138
+ ...(recipientIdentityKey === undefined ? {} : { recipientIdentityKey }),
56
139
  terms: args.terms,
57
- termsDigest: sha256hex(canonicalJson(args.terms)),
140
+ termsDigest,
58
141
  holderIdentityKey: holder.identityKey,
59
142
  expectedPredecessor: { txid: tip.txid, outputIndex: tip.outputIndex },
60
143
  createdAt: instant(),
61
144
  expiresAt: instant(this.lifetime),
62
145
  status: 'open',
63
146
  }
64
- await this.options.store.saveOffer(offer)
65
- return { offer, claimCode }
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
66
182
  }
67
183
 
68
184
  async withdraw(requestId: string, holder: Party): Promise<OfferRecord> {
@@ -70,9 +186,7 @@ export class Custody {
70
186
  if (offer == null) throw new WriteRefused('offer-unknown', `no offer ${requestId}`)
71
187
  if (offer.holderIdentityKey !== holder.identityKey) throw new WriteRefused('not-the-holder', 'only the holder withdraws an offer')
72
188
  if (offer.status !== 'open') throw new WriteRefused('offer-closed', `offer ${requestId} is ${offer.status}`)
73
- offer.status = 'withdrawn'
74
- await this.options.store.saveOffer(offer)
75
- return offer
189
+ return await this.closeOpenOffer(offer, 'withdrawn')
76
190
  }
77
191
 
78
192
  /** What a recipient sees before deciding: the terms the digest covers, and when the offer closes. */
@@ -82,11 +196,29 @@ export class Custody {
82
196
  return { requestId, passportId: offer.passportId, terms: offer.terms, expiresAt: offer.expiresAt, status: offer.status }
83
197
  }
84
198
 
85
- async decline(requestId: string, claimCode?: string): Promise<OfferRecord> {
86
- const offer = await this.openOffer(requestId, claimCode)
87
- offer.status = 'declined'
88
- await this.options.store.saveOffer(offer)
89
- return offer
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
90
222
  }
91
223
 
92
224
  private async openOffer(requestId: string, claimCode?: string, recipientIdentityKey?: string): Promise<OfferRecord> {
@@ -94,12 +226,10 @@ export class Custody {
94
226
  if (offer == null) throw new WriteRefused('offer-unknown', `no offer ${requestId}`)
95
227
  if (offer.status !== 'open') throw new WriteRefused('offer-closed', `offer ${requestId} is ${offer.status}`)
96
228
  if (offer.expiresAt <= instant()) {
97
- offer.status = 'expired'
98
- await this.options.store.saveOffer(offer)
229
+ await this.closeOpenOffer(offer, 'expired')
99
230
  throw new WriteRefused('offer-expired', `offer ${requestId} expired at ${offer.expiresAt}`)
100
231
  }
101
- if (offer.mechanism === 'claim-code' && (claimCode == null || sha256hex(claimCode) !== offer.claimCodeHash)) throw new WriteRefused('claim-code-wrong', 'the claim code does not match this offer')
102
- if (offer.mechanism === 'named-recipient' && recipientIdentityKey !== offer.recipientIdentityKey) throw new WriteRefused('recipient-wrong', 'this offer is addressed to another identity')
232
+ this.checkRecipient(offer, claimCode, recipientIdentityKey)
103
233
  return offer
104
234
  }
105
235
 
@@ -108,30 +238,41 @@ export class Custody {
108
238
  * identity, records and signs the acceptance, keeps it, then writes the
109
239
  * TRANSFER that commits to it. The tip must still be the one the offer named.
110
240
  */
111
- async accept(args: { requestId: string; claimCode?: string; recipientIdentityKey?: string }): Promise<{ offer: OfferRecord; record: ManagedAcceptanceRecord; transferTxid: string }> {
112
- const { store, wallet, parties, writer } = this.options
113
- // An acceptance whose TRANSFER did not get written is retried with the same record, never signed twice.
114
- const earlier = await store.getOffer(args.requestId)
115
- const retrying = earlier?.status === 'accepted' && earlier.record != null && earlier.transferTxid == null
116
- const offer = retrying ? earlier : await this.openOffer(args.requestId, args.claimCode, args.recipientIdentityKey)
117
- if (retrying && offer.mechanism === 'claim-code' && (args.claimCode == null || sha256hex(args.claimCode) !== offer.claimCodeHash)) throw new WriteRefused('claim-code-wrong', 'the claim code does not match this offer')
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}`)
118
259
  const passport = await store.getPassport(offer.passportId)
119
260
  if (passport == null) throw new WriteRefused('passport-unknown', `no passport ${offer.passportId}`)
120
- const tip = passport.states.at(-1)
121
- if (tip == null || tip.txid !== offer.expectedPredecessor.txid) throw new WriteRefused('tip-moved', 'the passport moved since the offer was made; ask for a new offer')
122
- const holder = this.holderOf(passport)
123
- const recipient = parties.recipient(offer.requestId)
124
- if (retrying) {
125
- const record = offer.record!
126
- const outcome = await writer.transfer({ record: passport, holder, recipient, acceptance: record, eventData: { word: typeof offer.terms.word === 'string' ? offer.terms.word : 'Handed on' } })
127
- offer.status = 'transferred'
128
- offer.transferTxid = outcome.entry.txid
129
- await store.saveOffer(offer)
130
- return { offer, record, transferTxid: outcome.entry.txid }
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}`)
131
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')
132
273
 
133
274
  const claim: ManagedAcceptanceClaim = {
134
- acceptanceFormat: 'dpp-managed-acceptance@1',
275
+ acceptanceFormat: 'dpp-managed-acceptance@2',
135
276
  requestId: offer.requestId,
136
277
  passportId: offer.passportId,
137
278
  lineageGenesis: { txid: passport.states[0].txid, outputIndex: passport.states[0].outputIndex },
@@ -152,32 +293,63 @@ export class Custody {
152
293
  },
153
294
  custodian: wallet.identityKey,
154
295
  }
155
- const record = await signManagedAcceptance(claim, wallet.acceptanceSigner)
156
- const inspection = inspectManagedAcceptance(record, { custodians: [wallet.identityKey] })
157
- if (!inspection.structureValid || !inspection.signatureValid || inspection.failures.length > 0) throw new WriteRefused('acceptance-invalid', `the acceptance record does not inspect clean: ${inspection.failures.map((f) => f.detail).join('; ')}`)
158
- offer.status = 'accepted'
159
- offer.record = record
160
- await store.saveOffer(offer)
161
-
162
- const outcome = await writer.transfer({
163
- record: passport,
164
- holder,
165
- recipient,
166
- acceptance: record,
167
- eventData: { word: typeof offer.terms.word === 'string' ? offer.terms.word : 'Handed on' },
168
- })
169
- const mismatches = bindAcceptanceToState(record, outcome.state)
170
- if (mismatches.length > 0) throw new WriteRefused('acceptance-mismatch', `the record does not bind to the TRANSFER: ${mismatches.map((m) => m.detail).join('; ')}`)
171
- offer.status = 'transferred'
172
- offer.transferTxid = outcome.entry.txid
173
- await store.saveOffer(offer)
174
- return { offer, record, transferTxid: outcome.entry.txid }
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 }
175
345
  }
176
346
 
177
347
  /** The party that controls the passport now, resolved from the journal's holder name. */
178
348
  holderOf(passport: PassportRecord): Party {
179
349
  const { parties } = this.options
180
- const [scope, id] = passport.holder.party.split(':', 2)
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)
181
353
  if (scope === 'brand') return parties.brand(id)
182
354
  if (scope === 'recipient') return parties.recipient(id)
183
355
  if (scope === 'member') return parties.member(id)
@@ -1,29 +1,52 @@
1
1
  // An index in this process for development and tests: the real topic
2
- // manager, lookup service and HTTP host the reference deployment runs, over
2
+ // managers, lookup services and HTTP host the reference deployment runs, over
3
3
  // in-memory storage, on a loopback port, with a publisher policy naming the
4
4
  // platform wallet and the managed-custody profile selected. Its header
5
5
  // checks are off, so it takes the made-up proofs a dry run pushes and claims
6
- // no inclusion. Production runs the reference index as its own service
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
7
10
  // (a separate operator project or an existing provider) and never this.
8
11
  //
9
12
  // The HTTP host is the package's ./server export. Imported, it is a library
10
13
  // and starts nothing by itself.
11
14
  import { PrivateKey } from '@bsv/sdk'
12
15
  import { policySigningPreimage, type PublisherPolicy } from '@bsv/dpp-protocol'
16
+ import type { RegistrationSettings } from '@bsv/dpp-overlay'
17
+ import type { Network } from './config.js'
13
18
 
14
19
  export interface DevIndex {
15
20
  url: string
16
21
  submitToken: string
17
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>
18
29
  close: () => Promise<void>
19
30
  }
20
31
 
21
- export async function startDevIndex(publisherKey: string): Promise<DevIndex> {
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
22
45
  const overlay = await import('@bsv/overlay')
23
46
  const topics = await import('@bsv/dpp-overlay')
24
47
  const host = await import('@bsv/dpp-overlay/server')
25
48
 
26
- // The policy chain of spec/services.md section 1: one operator signs a genesis naming the platform wallet as a state publisher.
49
+ // The publisher key policy of the @bsv/dpp-overlay README: one operator signs a genesis naming the platform wallet as a state publisher.
27
50
  const operatorKey = PrivateKey.fromHex('44'.repeat(32))
28
51
  const operator = 'Development operator'
29
52
  const genesis: PublisherPolicy = {
@@ -37,12 +60,14 @@ export async function startDevIndex(publisherKey: string): Promise<DevIndex> {
37
60
  genesis.authorisation.value = operatorKey.sign(policySigningPreimage(genesis)).toDER('hex') as string
38
61
  const policy = topics.loadPublisherPolicyJson(JSON.stringify([genesis]), { [operator]: operatorKey.toPublicKey().toString() })
39
62
 
63
+ const managedAcceptance = (options.custody ?? 'managed-custody@2') === 'managed-custody@2'
40
64
  const records = new topics.InMemoryDppStorage()
41
65
  const storage = new topics.InMemoryOverlayStorage()
42
- const lookupServices = { ls_dpp: new topics.DppLookupService(records) }
66
+ const attestations = new topics.InMemoryAttestationStorage()
67
+ const lookupServices = { ls_dpp: new topics.DppLookupService(records), ls_attestation: new topics.AttestationLookupService(attestations) }
43
68
  const silent = { ...console, log() {}, info() {}, warn() {}, error() {} }
44
69
  const engine = new overlay.Engine(
45
- { tm_dpp: new topics.DppTopicManager('', { publisherPolicy: policy.chain, managedAcceptance: true, admittedOutputs: storage }) },
70
+ { tm_dpp: new topics.DppTopicManager('', { publisherPolicy: policy.chain, managedAcceptance, admittedOutputs: storage }), tm_attestation: new topics.AttestationTopicManager() },
46
71
  lookupServices,
47
72
  storage,
48
73
  'scripts only',
@@ -51,7 +76,7 @@ export async function startDevIndex(publisherKey: string): Promise<DevIndex> {
51
76
  undefined,
52
77
  undefined,
53
78
  undefined,
54
- { tm_dpp: false },
79
+ { tm_dpp: false, tm_attestation: false },
55
80
  false,
56
81
  '[index] ',
57
82
  false,
@@ -60,12 +85,36 @@ export async function startDevIndex(publisherKey: string): Promise<DevIndex> {
60
85
  )
61
86
  const submitToken = 'dev-submit-token'
62
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))
63
100
  const service = await host.startOverlayService(engine, {
64
101
  port: 0,
65
102
  host: '127.0.0.1',
103
+ network,
66
104
  submitToken,
67
105
  proofToken: callbackToken,
68
- components: { records, engineStorage: storage, lookupServices, publisherPolicy: policy, managedAcceptance: true },
106
+ exportIdentityKey: exporterKey.toHex(),
107
+ components: { records, engineStorage: storage, lookupServices, publisherPolicy: policy, managedAcceptance, ...(publisherTokens == null ? {} : { publisherTokens }), ...(registration == null ? {} : { registration }) },
69
108
  })
70
- return { url: `http://127.0.0.1:${service.port}`, submitToken, callbackToken, close: service.close }
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 }
71
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
+ }