@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.
Files changed (178) hide show
  1. package/LICENSE +203 -0
  2. package/NOTICE +2 -0
  3. package/PATENTS +12 -0
  4. package/README.md +93 -2
  5. package/dist/index.js +125 -0
  6. package/package.json +57 -4
  7. package/template/Dockerfile +37 -0
  8. package/template/README.md +389 -0
  9. package/template/_dockerignore +6 -0
  10. package/template/_env.example +122 -0
  11. package/template/_github/workflows/ci.yml +23 -0
  12. package/template/_gitignore +8 -0
  13. package/template/_prettierrc +6 -0
  14. package/template/apps/api/API.md +119 -0
  15. package/template/apps/api/package.json +39 -0
  16. package/template/apps/api/src/auth.ts +55 -0
  17. package/template/apps/api/src/bound-profiles.ts +590 -0
  18. package/template/apps/api/src/claims.ts +204 -0
  19. package/template/apps/api/src/cli.ts +99 -0
  20. package/template/apps/api/src/config.ts +180 -0
  21. package/template/apps/api/src/custody.ts +358 -0
  22. package/template/apps/api/src/dev-index.ts +120 -0
  23. package/template/apps/api/src/env-file.ts +55 -0
  24. package/template/apps/api/src/env.ts +14 -0
  25. package/template/apps/api/src/epcis/exchange.ts +434 -0
  26. package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
  27. package/template/apps/api/src/epcis/routes.ts +364 -0
  28. package/template/apps/api/src/epcis/sources.ts +142 -0
  29. package/template/apps/api/src/go-live.ts +226 -0
  30. package/template/apps/api/src/http-error.ts +15 -0
  31. package/template/apps/api/src/identifiers.ts +57 -0
  32. package/template/apps/api/src/index-client.ts +261 -0
  33. package/template/apps/api/src/index-projects.ts +53 -0
  34. package/template/apps/api/src/lifecycle-authority.ts +49 -0
  35. package/template/apps/api/src/lifecycle.ts +485 -0
  36. package/template/apps/api/src/main.ts +58 -0
  37. package/template/apps/api/src/parties.ts +68 -0
  38. package/template/apps/api/src/platform.ts +176 -0
  39. package/template/apps/api/src/portability/commands.ts +224 -0
  40. package/template/apps/api/src/portability/export.ts +708 -0
  41. package/template/apps/api/src/portability/package.ts +270 -0
  42. package/template/apps/api/src/portability/restore.ts +863 -0
  43. package/template/apps/api/src/profiles.ts +125 -0
  44. package/template/apps/api/src/reader.ts +265 -0
  45. package/template/apps/api/src/resolver.ts +159 -0
  46. package/template/apps/api/src/sector-examples.ts +390 -0
  47. package/template/apps/api/src/server.ts +613 -0
  48. package/template/apps/api/src/store.ts +426 -0
  49. package/template/apps/api/src/validation-engine.ts +172 -0
  50. package/template/apps/api/src/wallet.ts +359 -0
  51. package/template/apps/api/src/worker.ts +113 -0
  52. package/template/apps/api/src/writer.ts +603 -0
  53. package/template/apps/api/test/bound-http.test.ts +496 -0
  54. package/template/apps/api/test/bound-profiles.test.ts +547 -0
  55. package/template/apps/api/test/config.test.ts +160 -0
  56. package/template/apps/api/test/custody-journal.test.ts +415 -0
  57. package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
  58. package/template/apps/api/test/custom-profile.test.ts +167 -0
  59. package/template/apps/api/test/env-file.test.ts +53 -0
  60. package/template/apps/api/test/epcis-fixtures.ts +270 -0
  61. package/template/apps/api/test/epcis-http.test.ts +1179 -0
  62. package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
  63. package/template/apps/api/test/epcis-separation.test.ts +253 -0
  64. package/template/apps/api/test/epcis-web.test.ts +230 -0
  65. package/template/apps/api/test/exit-exercise.test.ts +1038 -0
  66. package/template/apps/api/test/external-index.test.ts +32 -0
  67. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
  68. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
  69. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
  70. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
  71. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
  72. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
  73. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
  74. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
  75. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
  76. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
  77. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
  78. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
  79. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
  80. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
  81. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
  82. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
  83. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
  84. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
  85. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
  86. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
  87. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
  88. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
  89. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
  90. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
  91. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
  92. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
  93. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
  94. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
  95. package/template/apps/api/test/go-live.test.ts +179 -0
  96. package/template/apps/api/test/gs1-global-setup.ts +33 -0
  97. package/template/apps/api/test/gs1-test-env.ts +5 -0
  98. package/template/apps/api/test/identifier-host.test.ts +256 -0
  99. package/template/apps/api/test/index-projects.test.ts +81 -0
  100. package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
  101. package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
  102. package/template/apps/api/test/lifecycle.test.ts +147 -0
  103. package/template/apps/api/test/manifest-notice.test.ts +36 -0
  104. package/template/apps/api/test/network-guard.ts +113 -0
  105. package/template/apps/api/test/portability.test.ts +655 -0
  106. package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
  107. package/template/apps/api/test/retired-profiles.test.ts +216 -0
  108. package/template/apps/api/test/sector-cutover.test.ts +95 -0
  109. package/template/apps/api/test/sector-forms.test.ts +420 -0
  110. package/template/apps/api/test/unjoined-index.test.ts +62 -0
  111. package/template/apps/api/test/validation-engine.test.ts +328 -0
  112. package/template/apps/api/test/wallet-monitor.test.ts +38 -0
  113. package/template/apps/api/test/writer-journal.test.ts +327 -0
  114. package/template/apps/api/tsconfig.json +9 -0
  115. package/template/apps/api/vitest.config.ts +12 -0
  116. package/template/apps/web/components.json +21 -0
  117. package/template/apps/web/index.html +12 -0
  118. package/template/apps/web/package.json +33 -0
  119. package/template/apps/web/src/app.tsx +55 -0
  120. package/template/apps/web/src/components/bits.tsx +188 -0
  121. package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
  122. package/template/apps/web/src/components/bound/field-view.tsx +237 -0
  123. package/template/apps/web/src/components/bound/pieces.tsx +169 -0
  124. package/template/apps/web/src/components/bound/readings.tsx +152 -0
  125. package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
  126. package/template/apps/web/src/components/claim-dialog.tsx +344 -0
  127. package/template/apps/web/src/components/epcis-events.tsx +119 -0
  128. package/template/apps/web/src/components/layout.tsx +135 -0
  129. package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
  130. package/template/apps/web/src/components/passport-form.tsx +244 -0
  131. package/template/apps/web/src/components/read-passport.tsx +49 -0
  132. package/template/apps/web/src/components/reading.tsx +150 -0
  133. package/template/apps/web/src/components/ui/alert.tsx +65 -0
  134. package/template/apps/web/src/components/ui/badge.tsx +47 -0
  135. package/template/apps/web/src/components/ui/button.tsx +63 -0
  136. package/template/apps/web/src/components/ui/card.tsx +91 -0
  137. package/template/apps/web/src/components/ui/dialog.tsx +156 -0
  138. package/template/apps/web/src/components/ui/input.tsx +20 -0
  139. package/template/apps/web/src/components/ui/label.tsx +21 -0
  140. package/template/apps/web/src/components/ui/select.tsx +189 -0
  141. package/template/apps/web/src/components/ui/separator.tsx +25 -0
  142. package/template/apps/web/src/components/ui/table.tsx +115 -0
  143. package/template/apps/web/src/components/ui/tabs.tsx +90 -0
  144. package/template/apps/web/src/components/ui/textarea.tsx +17 -0
  145. package/template/apps/web/src/index.css +81 -0
  146. package/template/apps/web/src/lib/api.ts +396 -0
  147. package/template/apps/web/src/lib/auth.ts +10 -0
  148. package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
  149. package/template/apps/web/src/lib/bound/display.ts +122 -0
  150. package/template/apps/web/src/lib/bound/fields.ts +128 -0
  151. package/template/apps/web/src/lib/bound/form-model.ts +521 -0
  152. package/template/apps/web/src/lib/bound/forms.ts +15 -0
  153. package/template/apps/web/src/lib/bound/identity.ts +48 -0
  154. package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
  155. package/template/apps/web/src/lib/bound/units.ts +37 -0
  156. package/template/apps/web/src/lib/epcis.ts +345 -0
  157. package/template/apps/web/src/lib/format.ts +87 -0
  158. package/template/apps/web/src/lib/lifecycle.ts +350 -0
  159. package/template/apps/web/src/lib/session.tsx +92 -0
  160. package/template/apps/web/src/lib/use-load.ts +46 -0
  161. package/template/apps/web/src/main.tsx +18 -0
  162. package/template/apps/web/src/pages/accept.tsx +113 -0
  163. package/template/apps/web/src/pages/brand.tsx +94 -0
  164. package/template/apps/web/src/pages/brands.tsx +104 -0
  165. package/template/apps/web/src/pages/events.tsx +388 -0
  166. package/template/apps/web/src/pages/home.tsx +51 -0
  167. package/template/apps/web/src/pages/new-passport.tsx +137 -0
  168. package/template/apps/web/src/pages/operations.tsx +169 -0
  169. package/template/apps/web/src/pages/passport.tsx +632 -0
  170. package/template/apps/web/src/pages/public-passport.tsx +64 -0
  171. package/template/apps/web/src/pages/sign-in.tsx +93 -0
  172. package/template/apps/web/src/pages/verify.tsx +30 -0
  173. package/template/apps/web/src/pages/wallet.tsx +141 -0
  174. package/template/apps/web/tsconfig.json +29 -0
  175. package/template/apps/web/vite.config.ts +23 -0
  176. package/template/deploy/compose.yml +38 -0
  177. package/template/package.json +48 -0
  178. package/template/tsconfig.base.json +13 -0
@@ -0,0 +1,426 @@
1
+ // The application's records and its journal. The journal is the single
2
+ // source of truth for every write: each state is recorded before it is acted
3
+ // on, with the index's answer, the network's answer and the proof, so a retry
4
+ // continues an operation instead of building a second transaction. The
5
+ // worker loop reads the same records to find what is still owed.
6
+ //
7
+ // Two implementations: MongoDB for a running platform, memory for tests.
8
+ import { isDeepStrictEqual } from 'node:util'
9
+ import { randomUUID } from 'node:crypto'
10
+ import { MongoServerError, type Collection, type Db, type ObjectId } from 'mongodb'
11
+ import type { ManagedAcceptanceRecord, SignedLifecycleClaim } from '@bsv/dpp-protocol'
12
+
13
+ export type IndexAnswer = 'pending' | 'admitted' | 'duplicate' | 'refused' | 'unauthorised' | 'unreachable' | 'not-asked'
14
+ export type NetworkAnswer = 'pending' | 'accepted' | 'refused' | 'unanswered' | 'not-sent' | 'dry-run'
15
+
16
+ export interface StateEntry {
17
+ op: 'ISSUE' | 'UPDATE' | 'TRANSFER' | 'RETIRE'
18
+ txid: string
19
+ outputIndex: number
20
+ /** The transaction as hex, and the BEEF the index and a reader take, base64. */
21
+ rawTx: string
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
31
+ timestamp: string
32
+ actor: string
33
+ controllerKey: string
34
+ payloadPublic: string
35
+ /** The owner tier the state commits to: only the hash goes on chain; the ciphertext lives here, nowhere else. */
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
+ }
42
+ index: IndexAnswer
43
+ refusal?: string
44
+ network: NetworkAnswer
45
+ proof?: { merklePath: string; blockHeight: number }
46
+ proofPushed?: boolean
47
+ }
48
+
49
+ export interface PassportRecord {
50
+ passportId: string
51
+ brandId: string
52
+ profile: string
53
+ createdAt: string
54
+ status: 'active' | 'retired'
55
+ /** Who controls the passport now: the party name the platform derives the controller key for. */
56
+ holder: { party: string; controllerKey: string }
57
+ states: StateEntry[]
58
+ /** Every acceptance record the platform signed for this passport, kept for its life: a reader needs it to check a transfer. */
59
+ acceptanceRecords: ManagedAcceptanceRecord[]
60
+ }
61
+
62
+ export interface OfferRecord {
63
+ requestId: string
64
+ passportId: string
65
+ brandId: string
66
+ mechanism: 'claim-code' | 'named-recipient'
67
+ /** SHA-256 of the claim code, hex; the code itself is shown once and never stored. */
68
+ claimCodeHash?: string
69
+ recipientIdentityKey?: string
70
+ terms: Record<string, unknown>
71
+ termsDigest: string
72
+ holderIdentityKey: string
73
+ expectedPredecessor: { txid: string; outputIndex: number }
74
+ createdAt: string
75
+ expiresAt: string
76
+ status: 'open' | 'accepted' | 'transferred' | 'declined' | 'withdrawn' | 'expired'
77
+ record?: ManagedAcceptanceRecord
78
+ transferTxid?: string
79
+ }
80
+
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 {
121
+ id: string
122
+ claimFormat?: 'dpp-lifecycle-v1'
123
+ passportId: string
124
+ issuer: string
125
+ issuedBy: string
126
+ claim: SignedLifecycleClaim
127
+ registry?: ClaimRegistryAnswer
128
+ createdAt: string
129
+ }
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
+
134
+ export interface BrandRecord {
135
+ id: string
136
+ name: string
137
+ identityKey: string
138
+ did: string
139
+ createdAt: string
140
+ }
141
+
142
+ export interface SpendRecord {
143
+ txid: string
144
+ satoshis: number
145
+ at: string
146
+ }
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
+
160
+ export interface Store {
161
+ getPassport(passportId: string): Promise<PassportRecord | undefined>
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>
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>
168
+ /** Only for a passport whose genesis was never written: a journal with states is never deleted. */
169
+ deletePassport(passportId: string): Promise<void>
170
+ getOffer(requestId: string): Promise<OfferRecord | undefined>
171
+ listOffers(filter?: { passportId?: string; brandId?: string; status?: OfferRecord['status'] }): Promise<OfferRecord[]>
172
+ createOpenOffer(record: OfferRecord): Promise<boolean>
173
+ saveOffer(record: OfferRecord): Promise<void>
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[]>
177
+ saveClaim(record: ClaimRecord): Promise<void>
178
+ getBrand(id: string): Promise<BrandRecord | undefined>
179
+ listBrands(ids?: string[]): Promise<BrandRecord[]>
180
+ saveBrand(record: BrandRecord): Promise<void>
181
+ recordSpend(spend: SpendRecord): Promise<void>
182
+ spentSince(at: string): Promise<number>
183
+ }
184
+
185
+ const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T
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
+
198
+ export class MemoryStore implements Store {
199
+ private passports = new Map<string, PassportRecord>()
200
+ private offers = new Map<string, OfferRecord>()
201
+ private claims = new Map<string, ClaimRecord>()
202
+ private brands = new Map<string, BrandRecord>()
203
+ private spends: SpendRecord[] = []
204
+
205
+ async getPassport(passportId: string) {
206
+ const record = this.passports.get(passportId)
207
+ return record == null ? undefined : clone(record)
208
+ }
209
+ async listPassports(filter: { brandId?: string } = {}) {
210
+ return [...this.passports.values()].filter((p) => filter.brandId == null || p.brandId === filter.brandId).map(clone)
211
+ }
212
+ async anyPassportUnder(idPrefix: string) {
213
+ return [...this.passports.keys()].some((passportId) => passportId.startsWith(idPrefix))
214
+ }
215
+ async savePassport(record: PassportRecord) {
216
+ this.passports.set(record.passportId, clone(record))
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
+ }
225
+ async deletePassport(passportId: string) {
226
+ this.passports.delete(passportId)
227
+ }
228
+ async getOffer(requestId: string) {
229
+ const record = this.offers.get(requestId)
230
+ return record == null ? undefined : clone(record)
231
+ }
232
+ async listOffers(filter: { passportId?: string; brandId?: string; status?: OfferRecord['status'] } = {}) {
233
+ return [...this.offers.values()]
234
+ .filter((o) => (filter.passportId == null || o.passportId === filter.passportId) && (filter.brandId == null || o.brandId === filter.brandId) && (filter.status == null || o.status === filter.status))
235
+ .map(clone)
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
+ }
243
+ async saveOffer(record: OfferRecord) {
244
+ this.offers.set(record.requestId, clone(record))
245
+ }
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
258
+ }
259
+ async saveClaim(record: ClaimRecord) {
260
+ this.claims.set(record.id, clone(record))
261
+ }
262
+ async getBrand(id: string) {
263
+ const record = this.brands.get(id)
264
+ return record == null ? undefined : clone(record)
265
+ }
266
+ async listBrands(ids?: string[]) {
267
+ return [...this.brands.values()].filter((b) => ids == null || ids.includes(b.id)).map(clone)
268
+ }
269
+ async saveBrand(record: BrandRecord) {
270
+ this.brands.set(record.id, clone(record))
271
+ }
272
+ async recordSpend(spend: SpendRecord) {
273
+ if (!this.spends.some((held) => held.txid === spend.txid)) this.spends.push(clone(spend))
274
+ }
275
+ async spentSince(at: string) {
276
+ return this.spends.filter((s) => s.at >= at).reduce((sum, s) => sum + s.satoshis, 0)
277
+ }
278
+ }
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
+
285
+ export class MongoStore implements Store {
286
+ private passports: Collection<PassportRecord & { _journalRevision?: string }>
287
+ private offers: Collection<OfferRecord & { _openSlot?: string | string[] }>
288
+ private claims: Collection<ClaimRecord>
289
+ private brands: Collection<BrandRecord>
290
+ private spends: Collection<SpendRecord & { _id: string | ObjectId }>
291
+
292
+ constructor(db: Db) {
293
+ this.passports = db.collection<PassportRecord & { _journalRevision?: string }>('passports')
294
+ this.offers = db.collection<OfferRecord & { _openSlot?: string | string[] }>('offers')
295
+ this.claims = db.collection<ClaimRecord>('claims')
296
+ this.brands = db.collection<BrandRecord>('brands')
297
+ this.spends = db.collection<SpendRecord & { _id: string | ObjectId }>('spends')
298
+ }
299
+
300
+ async init(): Promise<void> {
301
+ await this.passports.createIndex({ passportId: 1 }, { unique: true })
302
+ await this.passports.createIndex({ brandId: 1 })
303
+ await this.offers.createIndex({ requestId: 1 }, { unique: true })
304
+ await this.offers.createIndex({ passportId: 1 })
305
+ await this.offers.createIndex({ _openSlot: 1 }, { unique: true, sparse: true })
306
+ await this.claims.createIndex({ id: 1 }, { unique: true })
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 })
311
+ await this.brands.createIndex({ id: 1 }, { unique: true })
312
+ await this.spends.createIndex({ at: 1 })
313
+ }
314
+
315
+ private strip<T extends object>(doc: (T & { _id?: unknown }) | null): T | undefined {
316
+ if (doc == null) return undefined
317
+ const { _id: _ignored, _journalRevision: _revision, _openSlot: _slot, ...rest } = doc as T & { _id?: unknown; _journalRevision?: string; _openSlot?: string | string[] }
318
+ return rest as T
319
+ }
320
+
321
+ async getPassport(passportId: string) {
322
+ return this.strip(await this.passports.findOne({ passportId }))
323
+ }
324
+ async listPassports(filter: { brandId?: string } = {}) {
325
+ const docs = await this.passports.find(filter.brandId == null ? {} : { brandId: filter.brandId }).sort({ createdAt: -1 }).toArray()
326
+ return docs.map((d) => this.strip(d)!)
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
+ }
332
+ async savePassport(record: PassportRecord) {
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
+ }
358
+ }
359
+ async deletePassport(passportId: string) {
360
+ await this.passports.deleteOne({ passportId, states: { $size: 0 } })
361
+ }
362
+ async getOffer(requestId: string) {
363
+ return this.strip(await this.offers.findOne({ requestId: { $eq: requestId } }))
364
+ }
365
+ async listOffers(filter: { passportId?: string; brandId?: string; status?: OfferRecord['status'] } = {}) {
366
+ const query: Record<string, unknown> = {}
367
+ if (filter.passportId != null) query.passportId = filter.passportId
368
+ if (filter.brandId != null) query.brandId = filter.brandId
369
+ if (filter.status != null) query.status = filter.status
370
+ const docs = await this.offers.find(query).sort({ createdAt: -1 }).toArray()
371
+ return docs.map((d) => this.strip(d)!)
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
+ }
387
+ async saveOffer(record: OfferRecord) {
388
+ await this.offers.replaceOne({ requestId: record.requestId }, record, { upsert: true })
389
+ }
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))
403
+ }
404
+ async saveClaim(record: ClaimRecord) {
405
+ await this.claims.replaceOne({ id: record.id }, record, { upsert: true })
406
+ }
407
+ async getBrand(id: string) {
408
+ return this.strip(await this.brands.findOne({ id }))
409
+ }
410
+ async listBrands(ids?: string[]) {
411
+ const docs = await this.brands.find(ids == null ? {} : { id: { $in: ids } }).sort({ createdAt: 1 }).toArray()
412
+ return docs.map((d) => this.strip(d)!)
413
+ }
414
+ async saveBrand(record: BrandRecord) {
415
+ await this.brands.replaceOne({ id: record.id }, record, { upsert: true })
416
+ }
417
+ async recordSpend(spend: SpendRecord) {
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 })
421
+ }
422
+ async spentSince(at: string) {
423
+ const docs = await this.spends.find({ at: { $gte: at } }).toArray()
424
+ return docs.reduce((sum, s) => sum + s.satoshis, 0)
425
+ }
426
+ }
@@ -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
+ }