@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
@@ -5,7 +5,9 @@
5
5
  // worker loop reads the same records to find what is still owed.
6
6
  //
7
7
  // Two implementations: MongoDB for a running platform, memory for tests.
8
- import type { Collection, Db } from 'mongodb'
8
+ import { isDeepStrictEqual } from 'node:util'
9
+ import { randomUUID } from 'node:crypto'
10
+ import { MongoServerError, type Collection, type Db, type ObjectId } from 'mongodb'
9
11
  import type { ManagedAcceptanceRecord, SignedLifecycleClaim } from '@bsv/dpp-protocol'
10
12
 
11
13
  export type IndexAnswer = 'pending' | 'admitted' | 'duplicate' | 'refused' | 'unauthorised' | 'unreachable' | 'not-asked'
@@ -18,12 +20,25 @@ export interface StateEntry {
18
20
  /** The transaction as hex, and the BEEF the index and a reader take, base64. */
19
21
  rawTx: string
20
22
  beef: string
23
+ /** The original BEEF once beef has been enriched with a proof. */
24
+ sentBeef?: string
25
+ /** Recovery data for the incomplete operation. A completed entry needs only its ordinary journal fields. */
26
+ nextHolder?: PassportRecord['holder']
27
+ acceptance?: ManagedAcceptanceRecord
28
+ walletReference?: string
29
+ /** SHA-256 of the index base URL where this draft may have been announced. Older journals omit it. */
30
+ draftIndexId?: string
21
31
  timestamp: string
22
32
  actor: string
23
33
  controllerKey: string
24
34
  payloadPublic: string
25
35
  /** The owner tier the state commits to: only the hash goes on chain; the ciphertext lives here, nowhere else. */
26
- ownerTier?: { hash: string; ciphertext: string }
36
+ ownerTier?: {
37
+ hash: string
38
+ ciphertext: string
39
+ /** A transferred blob uses the giver's public identity key as the recipient wallet's decryption counterparty. */
40
+ senderIdentityKey?: string
41
+ }
27
42
  index: IndexAnswer
28
43
  refusal?: string
29
44
  network: NetworkAnswer
@@ -63,16 +78,59 @@ export interface OfferRecord {
63
78
  transferTxid?: string
64
79
  }
65
80
 
66
- export interface ClaimRecord {
81
+ /**
82
+ * A lifecycle claim this application holds. Two formats, told apart by
83
+ * `claimFormat`: an EPCIS lifecycle claim (`dpp-epcis-lifecycle@1`), which is
84
+ * what this application issues, kept as its exact signed bytes; and a
85
+ * historical native claim (`dpp-lifecycle-v1`), which this application issued
86
+ * before it moved to EPCIS lifecycle claims and still reads. A record written
87
+ * before the move carries no `claimFormat` and is a historical native claim.
88
+ */
89
+ export type ClaimRecord = EpcisLifecycleClaimRecord | HistoricalClaimRecord
90
+
91
+ export interface ClaimRegistryAnswer {
92
+ url: string
93
+ status: number
94
+ accepted: boolean
95
+ attestationId?: string
96
+ detail?: string
97
+ }
98
+
99
+ export interface EpcisLifecycleClaimRecord {
100
+ id: string
101
+ claimFormat: 'dpp-epcis-lifecycle@1'
102
+ /** The passport the claim was issued from; it is one of `boundPassports`. */
103
+ passportId: string
104
+ /** Every passport a binding of the claim names. Which of them the event concerns, and how, is decided by verifying the claim. */
105
+ boundPassports: string[]
106
+ attestationId: string
107
+ digest: string
108
+ eventId: string
109
+ eventType: string
110
+ issuer: string
111
+ issuedBy: string
112
+ /** The exact RFC 8785 bytes of the signed claim, as UTF-8 text: what is verified, sent, anchored and exported. */
113
+ bytes: string
114
+ /** The retained EPCIS event the claim was issued from, when it was imported. */
115
+ importedFrom?: { importId: string; pointer: string }
116
+ registry?: ClaimRegistryAnswer
117
+ createdAt: string
118
+ }
119
+
120
+ export interface HistoricalClaimRecord {
67
121
  id: string
122
+ claimFormat?: 'dpp-lifecycle-v1'
68
123
  passportId: string
69
124
  issuer: string
70
125
  issuedBy: string
71
126
  claim: SignedLifecycleClaim
72
- registry?: { url: string; status: number; accepted: boolean; attestationId?: string; detail?: string }
127
+ registry?: ClaimRegistryAnswer
73
128
  createdAt: string
74
129
  }
75
130
 
131
+ /** Whether a record holds an EPCIS lifecycle claim; every other record is a historical native claim. */
132
+ export const isEpcisLifecycleRecord = (record: ClaimRecord): record is EpcisLifecycleClaimRecord => record.claimFormat === 'dpp-epcis-lifecycle@1'
133
+
76
134
  export interface BrandRecord {
77
135
  id: string
78
136
  name: string
@@ -87,16 +145,35 @@ export interface SpendRecord {
87
145
  at: string
88
146
  }
89
147
 
148
+ export interface ClaimFilter {
149
+ passportId?: string
150
+ eventId?: string | string[]
151
+ attestationIds?: string[]
152
+ limit?: number
153
+ }
154
+
155
+ type JournalChange = (current: PassportRecord | undefined) => PassportRecord | undefined
156
+
157
+ export const isInterrupted = (state: StateEntry): boolean =>
158
+ state.network === 'pending' || state.network === 'unanswered' || state.network === 'refused' || state.network === 'not-sent'
159
+
90
160
  export interface Store {
91
161
  getPassport(passportId: string): Promise<PassportRecord | undefined>
92
162
  listPassports(filter?: { brandId?: string }): Promise<PassportRecord[]>
163
+ /** Whether the journal holds a passport whose identifier begins with this text, such as every item of one GTIN under this host. */
164
+ anyPassportUnder(idPrefix: string): Promise<boolean>
93
165
  savePassport(record: PassportRecord): Promise<void>
166
+ /** Apply a synchronous edit to the latest journal. Returning undefined removes it. The edit can run again on a concurrent revision. */
167
+ changePassport(id: string, edit: JournalChange): Promise<PassportRecord | undefined>
94
168
  /** Only for a passport whose genesis was never written: a journal with states is never deleted. */
95
169
  deletePassport(passportId: string): Promise<void>
96
170
  getOffer(requestId: string): Promise<OfferRecord | undefined>
97
171
  listOffers(filter?: { passportId?: string; brandId?: string; status?: OfferRecord['status'] }): Promise<OfferRecord[]>
172
+ createOpenOffer(record: OfferRecord): Promise<boolean>
98
173
  saveOffer(record: OfferRecord): Promise<void>
99
- listClaims(filter?: { passportId?: string }): Promise<ClaimRecord[]>
174
+ changeOfferStatus(record: OfferRecord, expected: OfferRecord['status']): Promise<boolean>
175
+ /** `passportId` selects the claims about that passport: a historical claim by its passport, an EPCIS lifecycle claim by any passport it binds. */
176
+ listClaims(filter?: ClaimFilter): Promise<ClaimRecord[]>
100
177
  saveClaim(record: ClaimRecord): Promise<void>
101
178
  getBrand(id: string): Promise<BrandRecord | undefined>
102
179
  listBrands(ids?: string[]): Promise<BrandRecord[]>
@@ -107,6 +184,17 @@ export interface Store {
107
184
 
108
185
  const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T
109
186
 
187
+ function claimMatches(record: ClaimRecord, filter: ClaimFilter): boolean {
188
+ if (filter.eventId != null) {
189
+ if (!isEpcisLifecycleRecord(record)) return false
190
+ const eventIds = Array.isArray(filter.eventId) ? filter.eventId : [filter.eventId]
191
+ if (!eventIds.includes(record.eventId)) return false
192
+ }
193
+ if (filter.attestationIds != null && (!isEpcisLifecycleRecord(record) || !filter.attestationIds.includes(record.attestationId))) return false
194
+ if (filter.passportId == null) return true
195
+ return isEpcisLifecycleRecord(record) ? record.boundPassports.includes(filter.passportId) : record.passportId === filter.passportId
196
+ }
197
+
110
198
  export class MemoryStore implements Store {
111
199
  private passports = new Map<string, PassportRecord>()
112
200
  private offers = new Map<string, OfferRecord>()
@@ -121,9 +209,19 @@ export class MemoryStore implements Store {
121
209
  async listPassports(filter: { brandId?: string } = {}) {
122
210
  return [...this.passports.values()].filter((p) => filter.brandId == null || p.brandId === filter.brandId).map(clone)
123
211
  }
212
+ async anyPassportUnder(idPrefix: string) {
213
+ return [...this.passports.keys()].some((passportId) => passportId.startsWith(idPrefix))
214
+ }
124
215
  async savePassport(record: PassportRecord) {
125
216
  this.passports.set(record.passportId, clone(record))
126
217
  }
218
+ async changePassport(id: string, edit: JournalChange) {
219
+ const current = this.passports.get(id)
220
+ const next = edit(current == null ? undefined : clone(current))
221
+ if (next == null) this.passports.delete(id)
222
+ else this.passports.set(id, clone(next))
223
+ return next
224
+ }
127
225
  async deletePassport(passportId: string) {
128
226
  this.passports.delete(passportId)
129
227
  }
@@ -136,11 +234,27 @@ export class MemoryStore implements Store {
136
234
  .filter((o) => (filter.passportId == null || o.passportId === filter.passportId) && (filter.brandId == null || o.brandId === filter.brandId) && (filter.status == null || o.status === filter.status))
137
235
  .map(clone)
138
236
  }
237
+ async createOpenOffer(record: OfferRecord) {
238
+ if (this.offers.has(record.requestId) || [...this.offers.values()].some(held => held.passportId === record.passportId &&
239
+ (held.status === 'open' || (held.status === 'accepted' && offerTipSlot(held) === offerTipSlot(record))))) return false
240
+ this.offers.set(record.requestId, clone(record))
241
+ return true
242
+ }
139
243
  async saveOffer(record: OfferRecord) {
140
244
  this.offers.set(record.requestId, clone(record))
141
245
  }
142
- async listClaims(filter: { passportId?: string } = {}) {
143
- return [...this.claims.values()].filter((c) => filter.passportId == null || c.passportId === filter.passportId).map(clone)
246
+ async changeOfferStatus(record: OfferRecord, expected: OfferRecord['status']) {
247
+ if (this.offers.get(record.requestId)?.status !== expected) return false
248
+ this.offers.set(record.requestId, clone(record))
249
+ return true
250
+ }
251
+ async listClaims(filter: ClaimFilter = {}) {
252
+ const matches: ClaimRecord[] = []
253
+ for (const record of this.claims.values()) {
254
+ if (claimMatches(record, filter)) matches.push(clone(record))
255
+ if (filter.limit != null && matches.length >= filter.limit) break
256
+ }
257
+ return matches
144
258
  }
145
259
  async saveClaim(record: ClaimRecord) {
146
260
  this.claims.set(record.id, clone(record))
@@ -156,26 +270,31 @@ export class MemoryStore implements Store {
156
270
  this.brands.set(record.id, clone(record))
157
271
  }
158
272
  async recordSpend(spend: SpendRecord) {
159
- this.spends.push(clone(spend))
273
+ if (!this.spends.some((held) => held.txid === spend.txid)) this.spends.push(clone(spend))
160
274
  }
161
275
  async spentSince(at: string) {
162
276
  return this.spends.filter((s) => s.at >= at).reduce((sum, s) => sum + s.satoshis, 0)
163
277
  }
164
278
  }
165
279
 
280
+ // The existing unique index accepts multiple keys on an open offer. Its passport key
281
+ // blocks other opens. Its outpoint key persists through signing until transfer settles.
282
+ const offerTipSlot = (offer: OfferRecord): string =>
283
+ JSON.stringify([offer.passportId, offer.expectedPredecessor.txid, offer.expectedPredecessor.outputIndex])
284
+
166
285
  export class MongoStore implements Store {
167
- private passports: Collection<PassportRecord>
168
- private offers: Collection<OfferRecord>
286
+ private passports: Collection<PassportRecord & { _journalRevision?: string }>
287
+ private offers: Collection<OfferRecord & { _openSlot?: string | string[] }>
169
288
  private claims: Collection<ClaimRecord>
170
289
  private brands: Collection<BrandRecord>
171
- private spends: Collection<SpendRecord>
290
+ private spends: Collection<SpendRecord & { _id: string | ObjectId }>
172
291
 
173
292
  constructor(db: Db) {
174
- this.passports = db.collection<PassportRecord>('passports')
175
- this.offers = db.collection<OfferRecord>('offers')
293
+ this.passports = db.collection<PassportRecord & { _journalRevision?: string }>('passports')
294
+ this.offers = db.collection<OfferRecord & { _openSlot?: string | string[] }>('offers')
176
295
  this.claims = db.collection<ClaimRecord>('claims')
177
296
  this.brands = db.collection<BrandRecord>('brands')
178
- this.spends = db.collection<SpendRecord>('spends')
297
+ this.spends = db.collection<SpendRecord & { _id: string | ObjectId }>('spends')
179
298
  }
180
299
 
181
300
  async init(): Promise<void> {
@@ -183,15 +302,19 @@ export class MongoStore implements Store {
183
302
  await this.passports.createIndex({ brandId: 1 })
184
303
  await this.offers.createIndex({ requestId: 1 }, { unique: true })
185
304
  await this.offers.createIndex({ passportId: 1 })
305
+ await this.offers.createIndex({ _openSlot: 1 }, { unique: true, sparse: true })
186
306
  await this.claims.createIndex({ id: 1 }, { unique: true })
187
307
  await this.claims.createIndex({ passportId: 1 })
308
+ await this.claims.createIndex({ boundPassports: 1 })
309
+ await this.claims.createIndex({ eventId: 1 })
310
+ await this.claims.createIndex({ attestationId: 1 })
188
311
  await this.brands.createIndex({ id: 1 }, { unique: true })
189
312
  await this.spends.createIndex({ at: 1 })
190
313
  }
191
314
 
192
315
  private strip<T extends object>(doc: (T & { _id?: unknown }) | null): T | undefined {
193
316
  if (doc == null) return undefined
194
- const { _id: _ignored, ...rest } = doc
317
+ const { _id: _ignored, _journalRevision: _revision, _openSlot: _slot, ...rest } = doc as T & { _id?: unknown; _journalRevision?: string; _openSlot?: string | string[] }
195
318
  return rest as T
196
319
  }
197
320
 
@@ -202,14 +325,42 @@ export class MongoStore implements Store {
202
325
  const docs = await this.passports.find(filter.brandId == null ? {} : { brandId: filter.brandId }).sort({ createdAt: -1 }).toArray()
203
326
  return docs.map((d) => this.strip(d)!)
204
327
  }
328
+ async anyPassportUnder(idPrefix: string) {
329
+ // A range over the unique index on passportId: every identifier that begins with the prefix sorts from it to it followed by the highest code point.
330
+ return (await this.passports.findOne({ passportId: { $gte: idPrefix, $lt: `${idPrefix}\u{10ffff}` } }, { projection: { _id: 1 } })) != null
331
+ }
205
332
  async savePassport(record: PassportRecord) {
206
- await this.passports.replaceOne({ passportId: record.passportId }, record, { upsert: true })
333
+ await this.passports.replaceOne({ passportId: record.passportId }, { ...record, _journalRevision: randomUUID() }, { upsert: true })
334
+ }
335
+ async changePassport(passportId: string, edit: JournalChange) {
336
+ for (;;) {
337
+ const saved = await this.passports.findOne({ passportId })
338
+ const current = this.strip(saved)
339
+ const next = edit(current == null ? undefined : clone(current))
340
+ if (isDeepStrictEqual(current, next)) return next
341
+ if (saved == null) {
342
+ if (next == null) return undefined
343
+ try {
344
+ await this.passports.insertOne({ ...next, _journalRevision: randomUUID() })
345
+ return next
346
+ } catch (cause) {
347
+ if (cause instanceof MongoServerError && cause.code === 11000) continue
348
+ throw cause
349
+ }
350
+ }
351
+ const version = { _id: saved._id, _journalRevision: saved._journalRevision ?? { $exists: false } }
352
+ if (next == null) {
353
+ if ((await this.passports.deleteOne(version)).deletedCount === 1) return undefined
354
+ } else if ((await this.passports.replaceOne(version, { ...next, _journalRevision: randomUUID() })).matchedCount === 1) {
355
+ return next
356
+ }
357
+ }
207
358
  }
208
359
  async deletePassport(passportId: string) {
209
360
  await this.passports.deleteOne({ passportId, states: { $size: 0 } })
210
361
  }
211
362
  async getOffer(requestId: string) {
212
- return this.strip(await this.offers.findOne({ requestId }))
363
+ return this.strip(await this.offers.findOne({ requestId: { $eq: requestId } }))
213
364
  }
214
365
  async listOffers(filter: { passportId?: string; brandId?: string; status?: OfferRecord['status'] } = {}) {
215
366
  const query: Record<string, unknown> = {}
@@ -219,12 +370,36 @@ export class MongoStore implements Store {
219
370
  const docs = await this.offers.find(query).sort({ createdAt: -1 }).toArray()
220
371
  return docs.map((d) => this.strip(d)!)
221
372
  }
373
+ async createOpenOffer(record: OfferRecord) {
374
+ // Earlier stores and restored offers have no reservation field. They still hold their place.
375
+ if (await this.offers.findOne({ passportId: record.passportId, $or: [
376
+ { status: 'open' },
377
+ { status: 'accepted', 'expectedPredecessor.txid': record.expectedPredecessor.txid, 'expectedPredecessor.outputIndex': record.expectedPredecessor.outputIndex },
378
+ ] }, { projection: { _id: 1 } })) return false
379
+ try {
380
+ await this.offers.insertOne({ ...record, _openSlot: [record.passportId, offerTipSlot(record)] })
381
+ return true
382
+ } catch (cause) {
383
+ if (cause instanceof MongoServerError && cause.code === 11000) return false
384
+ throw cause
385
+ }
386
+ }
222
387
  async saveOffer(record: OfferRecord) {
223
388
  await this.offers.replaceOne({ requestId: record.requestId }, record, { upsert: true })
224
389
  }
225
- async listClaims(filter: { passportId?: string } = {}) {
226
- const docs = await this.claims.find(filter.passportId == null ? {} : { passportId: filter.passportId }).sort({ createdAt: -1 }).toArray()
227
- return docs.map((d) => this.strip(d)!)
390
+ async changeOfferStatus(record: OfferRecord, expected: OfferRecord['status']) {
391
+ const replacement = record.status === 'accepted' ? { ...record, _openSlot: offerTipSlot(record) } : record
392
+ return (await this.offers.replaceOne({ requestId: record.requestId, status: expected }, replacement)).matchedCount === 1
393
+ }
394
+ async listClaims(filter: ClaimFilter = {}) {
395
+ const query: Record<string, unknown> = {}
396
+ if (filter.passportId != null) query.$or = [{ claimFormat: { $ne: 'dpp-epcis-lifecycle@1' }, passportId: filter.passportId }, { claimFormat: 'dpp-epcis-lifecycle@1', boundPassports: filter.passportId }]
397
+ if (filter.eventId != null) query.eventId = Array.isArray(filter.eventId) ? { $in: filter.eventId } : filter.eventId
398
+ if (filter.attestationIds != null) query.attestationId = { $in: filter.attestationIds }
399
+ const cursor = this.claims.find(query).sort({ createdAt: -1, id: 1 })
400
+ if (filter.limit != null) cursor.limit(filter.limit).maxTimeMS(30_000)
401
+ const docs = await cursor.toArray()
402
+ return docs.map((d) => this.strip<ClaimRecord>(d as ClaimRecord & { _id?: unknown })!).filter((c) => claimMatches(c, filter))
228
403
  }
229
404
  async saveClaim(record: ClaimRecord) {
230
405
  await this.claims.replaceOne({ id: record.id }, record, { upsert: true })
@@ -240,7 +415,9 @@ export class MongoStore implements Store {
240
415
  await this.brands.replaceOne({ id: record.id }, record, { upsert: true })
241
416
  }
242
417
  async recordSpend(spend: SpendRecord) {
243
- await this.spends.insertOne(spend)
418
+ // Older rows have ObjectId keys. New rows use txid so concurrent recovery counts a send once.
419
+ if (await this.spends.findOne({ txid: spend.txid }, { projection: { _id: 1 } })) return
420
+ await this.spends.updateOne({ _id: spend.txid }, { $setOnInsert: spend }, { upsert: true })
244
421
  }
245
422
  async spentSince(at: string) {
246
423
  const docs = await this.spends.find({ at: { $gte: at } }).toArray()
@@ -0,0 +1,172 @@
1
+ // The validation engine, chosen by configuration. A profile held by a binding
2
+ // is checked by a JSON-LD engine and a SHACL engine, and this file decides
3
+ // where they run:
4
+ //
5
+ // VALIDATOR_URL unset in this process, from the three libraries apps/api installs
6
+ // VALIDATOR_URL set in a validator service at that address, asked through
7
+ // the client of @bsv/dpp-profiles
8
+ //
9
+ // Either way the application is handed the same two engines and changes
10
+ // nothing else. The registry, the binding digests it trusts, the split into
11
+ // public and restricted parts and the comparison with the passport identifier
12
+ // all stay in this process. A service is sent the product document and the
13
+ // rule files of its binding, and answers for those only.
14
+ //
15
+ // One rule holds in both modes: an engine that cannot be used is never a
16
+ // pass. Libraries that did not load, a service that is stopped, slow, behind
17
+ // a wrong token or answering something else, all give `unknown`, and a
18
+ // document that was not validated is not written.
19
+ //
20
+ // This file imports nothing from the rest of the application, so the choice
21
+ // it makes can be exercised with the profiles package alone.
22
+ import type { ValidationEngines } from '@bsv/dpp-profiles'
23
+ import { VALIDATION_ENGINE_LIBRARIES, createValidationEngine } from '@bsv/dpp-profiles/validation-engine'
24
+ import { createValidatorClient, type ValidatorClient } from '@bsv/dpp-profiles/validator-client'
25
+
26
+ export interface ValidationEngineSettings {
27
+ /** The address of a validator service. Unset, the engine runs in this process. */
28
+ url?: string
29
+ /** The bearer token that service requires, when it requires one. */
30
+ token?: string
31
+ }
32
+
33
+ export interface ValidationEngineOptions {
34
+ /** How a validation library is loaded, for the engine in this process. Tests pass one that fails, to stand in for libraries that are not installed. */
35
+ load?: (name: string) => Promise<unknown>
36
+ /** The transport to the service. The platform's by default. */
37
+ fetch?: typeof globalThis.fetch
38
+ /** How long one exchange with the service may take, in milliseconds. The client's own default when unset. */
39
+ timeoutMs?: number
40
+ log?: (line: string) => void
41
+ }
42
+
43
+ export interface ValidationEngine {
44
+ /** Where the engines run. */
45
+ kind: 'in-process' | 'service'
46
+ /** The service's address without any path a secret could hide in: its origin. Absent for the engine in this process. */
47
+ service?: string
48
+ /** The two engines, or neither when the libraries did not load. */
49
+ engines: Pick<ValidationEngines, 'jsonLd' | 'shacl'>
50
+ /** Why the engine cannot be used, as last found. Undefined when it can. */
51
+ readonly problem: string | undefined
52
+ /**
53
+ * Look again. For a service this asks it what it is, so a service that was
54
+ * started, stopped or given another token since the last look is seen
55
+ * without restarting the API. For the engine in this process the answer is
56
+ * the one start-up found: libraries that did not load need a restart.
57
+ */
58
+ check(): Promise<string | undefined>
59
+ }
60
+
61
+ /** The settings as the environment names them. A value that cannot be used is the configuration's to refuse; this only reads. */
62
+ export function validationEngineSettings(env: Record<string, string | undefined>): ValidationEngineSettings {
63
+ const text = (name: string): string | undefined => {
64
+ const value = env[name]?.trim()
65
+ return value == null || value === '' ? undefined : value
66
+ }
67
+ const url = text('VALIDATOR_URL')
68
+ const token = text('VALIDATOR_TOKEN')
69
+ return { ...(url == null ? {} : { url }), ...(token == null ? {} : { token }) }
70
+ }
71
+
72
+ const ENGINE_INSTALL = Object.entries(VALIDATION_ENGINE_LIBRARIES)
73
+ .map(([name, version]) => `${name}@${version}`)
74
+ .join(' ')
75
+
76
+ const reasonOf = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause))
77
+
78
+ /** How long a look at the service may take: short, because a page waits for it. */
79
+ const CHECK_TIMEOUT_MS = 3_000
80
+
81
+ export async function openValidationEngine(settings: ValidationEngineSettings = {}, options: ValidationEngineOptions = {}): Promise<ValidationEngine> {
82
+ const log = options.log ?? (() => {})
83
+
84
+ if (settings.url == null) {
85
+ let engines: ValidationEngine['engines'] = {}
86
+ let problem: string | undefined
87
+ try {
88
+ engines = await createValidationEngine(options.load == null ? {} : { load: options.load })
89
+ } catch (cause) {
90
+ problem = `${reasonOf(cause)}. Install ${ENGINE_INSTALL} in apps/api and restart.`
91
+ log(`The validation engine is not available: ${problem} Until then a profile held by a binding cannot be written, and its readings say "not checked".`)
92
+ }
93
+ return {
94
+ kind: 'in-process',
95
+ engines,
96
+ get problem() {
97
+ return problem
98
+ },
99
+ check: async () => problem,
100
+ }
101
+ }
102
+
103
+ // The client refuses an address or a token it cannot use, by throwing. That is a mistake in the configuration and stops the start.
104
+ const shared = { url: settings.url, ...(settings.token == null ? {} : { token: settings.token }), ...(options.fetch == null ? {} : { fetch: options.fetch }) }
105
+ const client: ValidatorClient = createValidatorClient({ ...shared, ...(options.timeoutMs == null ? {} : { timeoutMs: options.timeoutMs }) })
106
+ const prober: ValidatorClient = createValidatorClient({ ...shared, timeoutMs: Math.min(options.timeoutMs ?? CHECK_TIMEOUT_MS, CHECK_TIMEOUT_MS) })
107
+ const service = new URL(settings.url).origin
108
+ const remedy = 'Start it, or correct VALIDATOR_URL and VALIDATOR_TOKEN. The API asks again by itself and needs no restart once the service answers.'
109
+ let problem: string | undefined
110
+
111
+ /**
112
+ * Ask the service what it is, and then ask it to do something. The first
113
+ * answer is open to anyone who can reach it. The second needs the token, so
114
+ * a service that is up and refuses this application is found here and not
115
+ * at the first write. The client's sentences name the address and never
116
+ * the token.
117
+ */
118
+ const look = async (): Promise<{ ok: true; described: string } | { ok: false; detail: string }> => {
119
+ const answer = await prober.probe()
120
+ if (!answer.ok) return { ok: false, detail: answer.detail }
121
+ // An empty document with no context is the smallest request there is. Whatever the engine makes of it, an answer from the engine means the token was taken.
122
+ const asked = await prober.jsonLd.toRdf({ document: {}, contexts: [] })
123
+ if (!asked.ok && (asked.reason === 'timeout' || asked.reason === 'engine-error')) return { ok: false, detail: asked.detail }
124
+ return { ok: true, described: `${answer.service.engine.name} ${answer.service.engine.version}, which checks ${answer.service.capabilities.join(', ')}` }
125
+ }
126
+ const check = async (): Promise<string | undefined> => {
127
+ const answer = await look()
128
+ if (!answer.ok) {
129
+ problem = `${answer.detail}. ${remedy}`
130
+ return problem
131
+ }
132
+ // The client that validates learns what the engine can check from an answer of its own.
133
+ if (client.shacl.capabilities.length === 0) await client.probe()
134
+ problem = undefined
135
+ return undefined
136
+ }
137
+
138
+ /** An engine call that did not finish may be the service's fault or the request's. Asking the service says which. */
139
+ const after = async <T extends { ok: boolean }>(result: T): Promise<T> => {
140
+ if (result.ok) problem = undefined
141
+ else if ((result as { reason?: string }).reason === 'timeout' || (result as { reason?: string }).reason === 'engine-error') await check()
142
+ return result
143
+ }
144
+
145
+ const first = await look()
146
+ if (first.ok) {
147
+ await client.probe()
148
+ log(`Validation engine: the validator service at ${service}, ${first.described}.`)
149
+ } else {
150
+ problem = `${first.detail}. ${remedy}`
151
+ log(`The validation engine is not available: ${problem} Until then a profile held by a binding cannot be written, and its readings say "not checked".`)
152
+ }
153
+
154
+ return {
155
+ kind: 'service',
156
+ service,
157
+ engines: {
158
+ jsonLd: { toRdf: async (input) => await after(await client.jsonLd.toRdf(input)) },
159
+ shacl: {
160
+ // Read each time it is asked for: the validator looks at it before every run, and it is whatever the service last said.
161
+ get capabilities() {
162
+ return client.shacl.capabilities
163
+ },
164
+ validate: async (input) => await after(await client.shacl.validate(input)),
165
+ },
166
+ },
167
+ get problem() {
168
+ return problem
169
+ },
170
+ check,
171
+ }
172
+ }