@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
@@ -0,0 +1,270 @@
1
+ // The shape of an export of this application, shared by the export and the
2
+ // restore. An export is one `dpp-evidence-package@1` in a folder: a signed
3
+ // manifest, `manifest.json`, over every other file, each listed once in the
4
+ // manifest's inventory under one of the format's nine categories. Nothing
5
+ // here is a second export format. The parts are the ones the packages
6
+ // already define, placed side by side:
7
+ //
8
+ // manifest.json the manifest this application signs
9
+ // application/application-export.json the descriptor: what the export covers and what it leaves out
10
+ // application/brands/<n>.json each brand record (authorised only)
11
+ // application/offers/<n>.json each hand-on offer (authorised only)
12
+ // application/claims/<n>.json each lifecycle claim this application holds (authorised only)
13
+ // application/lifecycle-claims/<n>.json each EPCIS lifecycle claim's exact signed bytes (authorised only)
14
+ // passports/<n>/index/... the index's own signed evidence for the passport, as it exported it
15
+ // passports/<n>/journal.json this application's journal of the passport (authorised only)
16
+ // passports/<n>/authority/<c>.json each acceptance record a hand-on commits to (authorised only)
17
+ // passports/<n>/reading.json how the passport verified when it was exported
18
+ // profiles/... the profile bundle of @bsv/dpp-profiles
19
+ // epcis/... the snapshot of @bsv/dpp-credentials/epcis-exchange
20
+ //
21
+ // `<n>` is the SHA-256 of the record's identifier, so no identifier becomes
22
+ // part of a file name.
23
+ //
24
+ // Two access paths, never mixed. An authorised export is a recovery backup
25
+ // for the operator of this deployment: its manifest says `all-tiers` and
26
+ // `recoveryBackup: true`. A public export carries what anyone may hold: the
27
+ // index's evidence, the profile files, the readings and the public form of
28
+ // the EPCIS exchange. Its manifest says `public`, and a restore refuses it.
29
+ // Neither carries a key, a wallet file or a credential.
30
+ import { createHash } from 'node:crypto'
31
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
32
+ import { dirname, join, sep } from 'node:path'
33
+ import { ACCEPTANCE_RECORD_REPRESENTATIONS, EVIDENCE_PACKAGE_MANIFEST_PATH, canonicalJson, inspectManagedAcceptance, pathProblem, type InventoryCategory, type InventoryEntry, type ManagedAcceptanceRecord } from '@bsv/dpp-protocol'
34
+
35
+ export const APPLICATION_EXPORT_FORMAT = 'dpp-application-export'
36
+ export const APPLICATION_EXPORT_VERSION = '1'
37
+ /** The descriptor's path in the package. */
38
+ export const APPLICATION_EXPORT_DESCRIPTOR = 'application/application-export.json'
39
+ /** What the manifest's `passportId` begins with when a package carries an export and not one passport (spec/portable-evidence.md section 2). */
40
+ export const EXPORT_SCOPE_PREFIX = 'urn:bsv:dpp:evidence-export:sha256:'
41
+ /** The folder the profile bundle sits in, and the folder the EPCIS snapshot sits in: the defaults of the two modules. */
42
+ export const PROFILES_ROOT = 'profiles'
43
+ export const EPCIS_ROOT = 'epcis'
44
+
45
+ /** What an inventory entry's `representation` says for each kind of file this application adds. The bundle's and the snapshot's files keep the ones their modules give. */
46
+ export const APPLICATION_REPRESENTATIONS = {
47
+ descriptor: 'dpp-application-export@1',
48
+ /** The manifest of the package the index signed for one passport, carried whole. */
49
+ indexManifest: 'dpp-evidence-package@1',
50
+ /** The original authority entry is read under the enclosed index manifest. */
51
+ nestedAuthority: 'dpp-nested-authority@1',
52
+ /** The signed coverage record of one part of the index's complete export. */
53
+ indexCoverage: 'dpp-evidence-export-coverage@1',
54
+ journal: 'dpp-application-passport-journal@1',
55
+ reading: 'dpp-application-passport-reading@1',
56
+ brand: 'dpp-application-brand@1',
57
+ offer: 'dpp-application-offer@1',
58
+ claim: 'dpp-application-claim@1',
59
+ } as const
60
+
61
+ /** Check an acceptance under the representation and commitment the nested exporter signed. */
62
+ export function readNestedAcceptance(entry: InventoryEntry, bytes: Uint8Array, passportId: string, custodian: string): ManagedAcceptanceRecord | undefined {
63
+ if (!ACCEPTANCE_RECORD_REPRESENTATIONS.some(format => format === entry.representation)) return undefined
64
+ let record: ManagedAcceptanceRecord
65
+ try {
66
+ record = JSON.parse(Buffer.from(bytes).toString('utf8')) as ManagedAcceptanceRecord
67
+ } catch {
68
+ throw new PortabilityRefused('index-evidence-refused', 'A signed index acceptance is not JSON.', { passportId, path: entry.path })
69
+ }
70
+ const checked = inspectManagedAcceptance(record, { custodians: [custodian] })
71
+ if (entry.category !== 'authority' || checked.signatureValid !== true || checked.failures.length || checked.commitment == null ||
72
+ record.acceptanceFormat !== entry.representation || record.passportId !== passportId ||
73
+ (entry.represents != null && entry.represents !== `sha256:${checked.commitment}`)) {
74
+ throw new PortabilityRefused('index-evidence-refused', 'A signed index acceptance does not verify for this custodian, passport and inventory entry.', { passportId, path: entry.path })
75
+ }
76
+ return record
77
+ }
78
+
79
+ /** What no export of this application carries or establishes, in fixed words. Every descriptor carries exactly these. */
80
+ export const APPLICATION_EXPORT_LIMITS = {
81
+ /** The wallet's root key and file, and the secrets brand and recipient keys are derived from. They travel by the wallet's own recovery and the operator's own secret handling. */
82
+ keys: 'never-carried',
83
+ /** The index's tokens, the registry's, the validator's and every EPCIS source's credential. The destination's operator provisions them. */
84
+ credentials: 'never-carried',
85
+ /** Sign-in accounts, sessions and memberships. */
86
+ signIn: 'never-carried',
87
+ /** The files GS1 publishes. They are named by address and digest, and the destination obtains them. */
88
+ gs1Files: 'named-by-address-and-digest',
89
+ /** The index's own records of each passport and the EPCIS associations are rebuilt at the destination from what is carried. */
90
+ derivedIndexes: 'rebuilt-at-destination',
91
+ /** A passing profile validation says a document satisfies its profile. It never says that disclosed data is what a state's payload_owner_hash commits to. */
92
+ ownerCommitment: 'not-established-by-profile-validity',
93
+ } as const
94
+
95
+ export type ApplicationExportAccess = 'authorised-recovery' | 'public-evidence'
96
+
97
+ /** How the index's evidence for one passport is carried. */
98
+ export type IndexEvidenceForm =
99
+ /** The index's bounded package, complete for its snapshot. */
100
+ | 'package'
101
+ /** The parts of the index's complete export, which tile one snapshot. */
102
+ | 'export-parts'
103
+ /** The bounded package of a lineage longer than its bound: the oldest states are declared absent. */
104
+ | 'bounded-package'
105
+ /** The index gave nothing: it holds no state of the passport, signs no package or could not be reached. `reason` says which. */
106
+ | 'none'
107
+
108
+ export interface ExportedPassport {
109
+ passportId: string
110
+ /** The folder of the passport's files: `passports/<sha256 of the identifier>`. */
111
+ folder: string
112
+ /** `id@version`, as the journal records it. */
113
+ profile: string
114
+ /** The binding digest the newest state declares, under a profile held by a binding. */
115
+ bindingDigest?: string
116
+ status: 'active' | 'retired'
117
+ states: number
118
+ /** The first and the newest state's transaction. */
119
+ genesis: string
120
+ tip: string
121
+ index: { form: IndexEvidenceForm; exporter?: string; snapshotId?: string; parts?: number; states?: number; reason?: string }
122
+ acceptanceRecords: number
123
+ claims: number
124
+ }
125
+
126
+ /** One thing the export leaves out, and why. */
127
+ export interface ApplicationExportOmission {
128
+ what: string
129
+ /** `never-carried`: no export holds it. `not-public`: a public export may not. `provisioned-by-destination`: named, and obtained there. `rebuilt-at-destination`: derived. `excluded`: left out of this export. `not-held`: this deployment has none. */
130
+ reason: 'never-carried' | 'not-public' | 'provisioned-by-destination' | 'rebuilt-at-destination' | 'excluded' | 'not-held'
131
+ detail?: string
132
+ }
133
+
134
+ /** The descriptor: what `application/application-export.json` holds. */
135
+ export interface ApplicationExportDescriptor {
136
+ format: typeof APPLICATION_EXPORT_FORMAT
137
+ version: typeof APPLICATION_EXPORT_VERSION
138
+ access: ApplicationExportAccess
139
+ /** The manifest's `passportId`: the name of this export, made from the passports it covers. */
140
+ exportId: string
141
+ exportedAt: string
142
+ selection: 'all-passports' | 'listed-passports'
143
+ application: { network: string; identifiers: { host: string; prefix: string }; publisherKey: string }
144
+ passports: ExportedPassport[]
145
+ /** The profiles the passports declare: those carried in the bundle, and those a manifest of the profiles package defines, which are named and not carried. */
146
+ profiles: { root?: string; carried: string[]; named: string[] }
147
+ /** The EPCIS exchange: the snapshot's folder, its identity and the scopes it covers, or why there is none. An authorised export also says how each source was configured, without its credential. */
148
+ epcis: {
149
+ root?: string
150
+ access?: ApplicationExportAccess
151
+ snapshotId?: string
152
+ scopes: string[]
153
+ cursors?: 'excluded' | 'included'
154
+ reason?: string
155
+ sources?: Array<{ sourceId: string; baseUrl: string; permittedOrigins: string[]; localTest: boolean; repeatListParameters: boolean; credentialConfigured: boolean; credentialScheme?: string }>
156
+ }
157
+ records: { brands: number; offers: number; claims: number }
158
+ omitted: ApplicationExportOmission[]
159
+ limits: typeof APPLICATION_EXPORT_LIMITS
160
+ }
161
+
162
+ /** What a reading of one passport came to, in the terms the export and the restore compare. It holds no restricted value: it is the public view. */
163
+ export interface ExportedReading {
164
+ passportId: string
165
+ /** What the reading could check inclusion against. `scripts only` checks no inclusion, and a reading under it is no proof that a state is in a block. */
166
+ chainTracker: 'header-source' | 'scripts only'
167
+ lineage: Array<{ op: string; txid: string }>
168
+ checks: Array<{ name: string; status: string; reasonCode?: string }>
169
+ payloadChecks: Array<{
170
+ txid: string
171
+ stateIndex: number
172
+ profile: string
173
+ status: string
174
+ cause?: string
175
+ steps: Array<{ step: string; status: string; cause?: string }>
176
+ findings: Array<{ step: string; severity: string; constraint: string; path?: string; message?: string }>
177
+ withheld: unknown[]
178
+ }>
179
+ }
180
+
181
+ export const sha256Hex = (bytes: Uint8Array | string): string => createHash('sha256').update(bytes).digest('hex')
182
+ export const utf8 = (text: string): Uint8Array => new TextEncoder().encode(text)
183
+ /**
184
+ * A value as JSON in one spelling: every object's members in the order of
185
+ * their names, no white space, and a member that is undefined left out. A
186
+ * record of this application may hold a null or a number that the protocol's
187
+ * canonical form does not admit, so its records are written with this, and
188
+ * the same record is the same bytes wherever it is exported.
189
+ */
190
+ export function stableJson(value: unknown): string {
191
+ if (Array.isArray(value)) return `[${value.map((entry) => stableJson(entry === undefined ? null : entry)).join(',')}]`
192
+ if (value !== null && typeof value === 'object') {
193
+ const members = Object.entries(value as Record<string, unknown>)
194
+ .filter(([, member]) => member !== undefined)
195
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
196
+ return `{${members.map(([name, member]) => `${JSON.stringify(name)}:${stableJson(member)}`).join(',')}}`
197
+ }
198
+ return JSON.stringify(value ?? null)
199
+ }
200
+
201
+ /** A record as the bytes an export carries. */
202
+ export const recordBytes = (value: unknown): Uint8Array => utf8(stableJson(value))
203
+ export const sameBytes = (a: Uint8Array, b: Uint8Array): boolean => a.byteLength === b.byteLength && Buffer.from(a.buffer, a.byteOffset, a.byteLength).equals(Buffer.from(b.buffer, b.byteOffset, b.byteLength))
204
+
205
+ /** The name of an export: the SHA-256 of the canonical list of the passport identifiers it covers, sorted. The same selection has the same name. */
206
+ export function exportScopeId(passportIds: readonly string[]): string {
207
+ return `${EXPORT_SCOPE_PREFIX}${sha256Hex(canonicalJson([...new Set(passportIds)].sort()))}`
208
+ }
209
+
210
+ export const passportFolder = (passportId: string): string => `passports/${sha256Hex(passportId)}`
211
+
212
+ /** One inventory entry for bytes about to be packaged, with the length and digest computed here and never typed. */
213
+ export function entryOf(path: string, category: InventoryCategory, mediaType: string, bytes: Uint8Array, extra: Pick<InventoryEntry, 'encrypted' | 'represents' | 'representation'> = {}): InventoryEntry {
214
+ return { path, category, mediaType, byteLength: bytes.byteLength, sha256: sha256Hex(bytes), ...extra }
215
+ }
216
+
217
+ /** A refusal of an export or a restore: a code to act on and one or more sentences for a person. It never repeats a credential. */
218
+ export class PortabilityRefused extends Error {
219
+ constructor(
220
+ readonly code: string,
221
+ detail: string,
222
+ /** What the refusal is about, where it is about particular things: a file, a profile, the module's own refusal. */
223
+ readonly data: Record<string, unknown> = {}
224
+ ) {
225
+ super(detail)
226
+ this.name = 'PortabilityRefused'
227
+ }
228
+ }
229
+
230
+ /* --------------------------------- folders ------------------------------- */
231
+
232
+ /** Write a package into a folder that holds nothing yet. A folder with anything in it is refused, so nothing is ever overwritten. */
233
+ export function writePackageFolder(folder: string, manifest: unknown, files: ReadonlyMap<string, Uint8Array>): void {
234
+ if (existsSync(folder) && readdirSync(folder).length > 0) throw new PortabilityRefused('destination-not-empty', `The folder ${folder} already holds files. An export is written into an empty folder and never over anything.`)
235
+ mkdirSync(folder, { recursive: true })
236
+ for (const [path, bytes] of files) {
237
+ const problem = pathProblem(path)
238
+ if (problem != null) throw new PortabilityRefused('path-invalid', `The file name ${JSON.stringify(path)} is ${problem}.`, { path })
239
+ const target = join(folder, ...path.split('/'))
240
+ mkdirSync(dirname(target), { recursive: true })
241
+ // Readable by the account that runs the application only: an authorised export holds restricted records.
242
+ writeFileSync(target, bytes, { mode: 0o600 })
243
+ }
244
+ writeFileSync(join(folder, EVIDENCE_PACKAGE_MANIFEST_PATH), `${JSON.stringify(manifest, null, 2)}\n`, { mode: 0o600 })
245
+ }
246
+
247
+ /** Every file under a folder, by its path in the package, the manifest left out. Nothing outside the folder is read: a link is not followed. */
248
+ export function readPackageFolder(folder: string): { manifestText?: string; files: Map<string, Uint8Array> } {
249
+ if (!existsSync(folder) || !statSync(folder).isDirectory()) throw new PortabilityRefused('package-missing', `There is no folder at ${folder}.`)
250
+ const files = new Map<string, Uint8Array>()
251
+ const walk = (dir: string, prefix: string): void => {
252
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
253
+ const path = prefix === '' ? entry.name : `${prefix}/${entry.name}`
254
+ if (entry.isDirectory()) walk(join(dir, entry.name), path)
255
+ else if (entry.isFile()) files.set(path, new Uint8Array(readFileSync(join(dir, entry.name))))
256
+ // Anything else, a link among them, is not a file of a package. It is listed so that the inventory check names it.
257
+ else files.set(path, new Uint8Array(0))
258
+ }
259
+ }
260
+ walk(folder, '')
261
+ const manifestBytes = files.get(EVIDENCE_PACKAGE_MANIFEST_PATH)
262
+ files.delete(EVIDENCE_PACKAGE_MANIFEST_PATH)
263
+ return { ...(manifestBytes == null ? {} : { manifestText: new TextDecoder().decode(manifestBytes) }), files }
264
+ }
265
+
266
+ /** The files of a package as the protocol package's inspection takes them. */
267
+ export const asNumberArrays = (files: ReadonlyMap<string, Uint8Array>): Map<string, number[]> => new Map([...files].map(([path, bytes]) => [path, Array.from(bytes)]))
268
+
269
+ /** A path of the package as a path of this machine, under a folder. */
270
+ export const inFolder = (folder: string, path: string): string => join(folder, ...path.split('/')).split(sep).join(sep)