@originals/sdk 1.8.0 → 1.8.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 (145) hide show
  1. package/dist/utils/hash.js +1 -0
  2. package/package.json +6 -5
  3. package/src/adapters/FeeOracleMock.ts +9 -0
  4. package/src/adapters/index.ts +5 -0
  5. package/src/adapters/providers/OrdHttpProvider.ts +126 -0
  6. package/src/adapters/providers/OrdMockProvider.ts +101 -0
  7. package/src/adapters/types.ts +66 -0
  8. package/src/bitcoin/BitcoinManager.ts +329 -0
  9. package/src/bitcoin/BroadcastClient.ts +54 -0
  10. package/src/bitcoin/OrdinalsClient.ts +120 -0
  11. package/src/bitcoin/PSBTBuilder.ts +106 -0
  12. package/src/bitcoin/fee-calculation.ts +38 -0
  13. package/src/bitcoin/providers/OrdNodeProvider.ts +92 -0
  14. package/src/bitcoin/providers/OrdinalsProvider.ts +56 -0
  15. package/src/bitcoin/providers/types.ts +59 -0
  16. package/src/bitcoin/transactions/commit.ts +465 -0
  17. package/src/bitcoin/transactions/index.ts +13 -0
  18. package/src/bitcoin/transfer.ts +43 -0
  19. package/src/bitcoin/utxo-selection.ts +322 -0
  20. package/src/bitcoin/utxo.ts +113 -0
  21. package/src/cel/ExternalReferenceManager.ts +87 -0
  22. package/src/cel/OriginalsCel.ts +460 -0
  23. package/src/cel/algorithms/createEventLog.ts +68 -0
  24. package/src/cel/algorithms/deactivateEventLog.ts +109 -0
  25. package/src/cel/algorithms/index.ts +11 -0
  26. package/src/cel/algorithms/updateEventLog.ts +99 -0
  27. package/src/cel/algorithms/verifyEventLog.ts +306 -0
  28. package/src/cel/algorithms/witnessEvent.ts +87 -0
  29. package/src/cel/cli/create.ts +330 -0
  30. package/src/cel/cli/index.ts +383 -0
  31. package/src/cel/cli/inspect.ts +549 -0
  32. package/src/cel/cli/migrate.ts +473 -0
  33. package/src/cel/cli/verify.ts +249 -0
  34. package/src/cel/hash.ts +71 -0
  35. package/src/cel/index.ts +16 -0
  36. package/src/cel/layers/BtcoCelManager.ts +408 -0
  37. package/src/cel/layers/PeerCelManager.ts +371 -0
  38. package/src/cel/layers/WebVHCelManager.ts +361 -0
  39. package/src/cel/layers/index.ts +27 -0
  40. package/src/cel/serialization/cbor.ts +189 -0
  41. package/src/cel/serialization/index.ts +10 -0
  42. package/src/cel/serialization/json.ts +209 -0
  43. package/src/cel/types.ts +160 -0
  44. package/src/cel/witnesses/BitcoinWitness.ts +184 -0
  45. package/src/cel/witnesses/HttpWitness.ts +241 -0
  46. package/src/cel/witnesses/WitnessService.ts +51 -0
  47. package/src/cel/witnesses/index.ts +11 -0
  48. package/src/contexts/credentials-v1.json +237 -0
  49. package/src/contexts/credentials-v2-examples.json +5 -0
  50. package/src/contexts/credentials-v2.json +340 -0
  51. package/src/contexts/credentials.json +237 -0
  52. package/src/contexts/data-integrity-v2.json +81 -0
  53. package/src/contexts/dids.json +58 -0
  54. package/src/contexts/ed255192020.json +93 -0
  55. package/src/contexts/ordinals-plus.json +23 -0
  56. package/src/contexts/originals.json +22 -0
  57. package/src/core/OriginalsSDK.ts +420 -0
  58. package/src/crypto/Multikey.ts +194 -0
  59. package/src/crypto/Signer.ts +262 -0
  60. package/src/crypto/noble-init.ts +138 -0
  61. package/src/did/BtcoDidResolver.ts +231 -0
  62. package/src/did/DIDManager.ts +705 -0
  63. package/src/did/Ed25519Verifier.ts +68 -0
  64. package/src/did/KeyManager.ts +239 -0
  65. package/src/did/WebVHManager.ts +499 -0
  66. package/src/did/createBtcoDidDocument.ts +60 -0
  67. package/src/did/providers/OrdinalsClientProviderAdapter.ts +68 -0
  68. package/src/events/EventEmitter.ts +222 -0
  69. package/src/events/index.ts +19 -0
  70. package/src/events/types.ts +331 -0
  71. package/src/examples/basic-usage.ts +78 -0
  72. package/src/examples/create-module-original.ts +435 -0
  73. package/src/examples/full-lifecycle-flow.ts +514 -0
  74. package/src/examples/run.ts +60 -0
  75. package/src/index.ts +204 -0
  76. package/src/kinds/KindRegistry.ts +320 -0
  77. package/src/kinds/index.ts +74 -0
  78. package/src/kinds/types.ts +470 -0
  79. package/src/kinds/validators/AgentValidator.ts +257 -0
  80. package/src/kinds/validators/AppValidator.ts +211 -0
  81. package/src/kinds/validators/DatasetValidator.ts +242 -0
  82. package/src/kinds/validators/DocumentValidator.ts +311 -0
  83. package/src/kinds/validators/MediaValidator.ts +269 -0
  84. package/src/kinds/validators/ModuleValidator.ts +225 -0
  85. package/src/kinds/validators/base.ts +276 -0
  86. package/src/kinds/validators/index.ts +12 -0
  87. package/src/lifecycle/BatchOperations.ts +381 -0
  88. package/src/lifecycle/LifecycleManager.ts +2156 -0
  89. package/src/lifecycle/OriginalsAsset.ts +524 -0
  90. package/src/lifecycle/ProvenanceQuery.ts +280 -0
  91. package/src/lifecycle/ResourceVersioning.ts +163 -0
  92. package/src/migration/MigrationManager.ts +587 -0
  93. package/src/migration/audit/AuditLogger.ts +176 -0
  94. package/src/migration/checkpoint/CheckpointManager.ts +112 -0
  95. package/src/migration/checkpoint/CheckpointStorage.ts +101 -0
  96. package/src/migration/index.ts +33 -0
  97. package/src/migration/operations/BaseMigration.ts +126 -0
  98. package/src/migration/operations/PeerToBtcoMigration.ts +105 -0
  99. package/src/migration/operations/PeerToWebvhMigration.ts +62 -0
  100. package/src/migration/operations/WebvhToBtcoMigration.ts +105 -0
  101. package/src/migration/rollback/RollbackManager.ts +170 -0
  102. package/src/migration/state/StateMachine.ts +92 -0
  103. package/src/migration/state/StateTracker.ts +156 -0
  104. package/src/migration/types.ts +356 -0
  105. package/src/migration/validation/BitcoinValidator.ts +107 -0
  106. package/src/migration/validation/CredentialValidator.ts +62 -0
  107. package/src/migration/validation/DIDCompatibilityValidator.ts +151 -0
  108. package/src/migration/validation/LifecycleValidator.ts +64 -0
  109. package/src/migration/validation/StorageValidator.ts +79 -0
  110. package/src/migration/validation/ValidationPipeline.ts +213 -0
  111. package/src/resources/ResourceManager.ts +655 -0
  112. package/src/resources/index.ts +21 -0
  113. package/src/resources/types.ts +202 -0
  114. package/src/storage/LocalStorageAdapter.ts +64 -0
  115. package/src/storage/MemoryStorageAdapter.ts +29 -0
  116. package/src/storage/StorageAdapter.ts +25 -0
  117. package/src/storage/index.ts +3 -0
  118. package/src/types/bitcoin.ts +98 -0
  119. package/src/types/common.ts +92 -0
  120. package/src/types/credentials.ts +89 -0
  121. package/src/types/did.ts +31 -0
  122. package/src/types/external-shims.d.ts +53 -0
  123. package/src/types/index.ts +7 -0
  124. package/src/types/network.ts +178 -0
  125. package/src/utils/EventLogger.ts +298 -0
  126. package/src/utils/Logger.ts +324 -0
  127. package/src/utils/MetricsCollector.ts +358 -0
  128. package/src/utils/bitcoin-address.ts +132 -0
  129. package/src/utils/cbor.ts +31 -0
  130. package/src/utils/encoding.ts +135 -0
  131. package/src/utils/hash.ts +12 -0
  132. package/src/utils/retry.ts +46 -0
  133. package/src/utils/satoshi-validation.ts +196 -0
  134. package/src/utils/serialization.ts +102 -0
  135. package/src/utils/telemetry.ts +44 -0
  136. package/src/utils/validation.ts +123 -0
  137. package/src/vc/CredentialManager.ts +955 -0
  138. package/src/vc/Issuer.ts +105 -0
  139. package/src/vc/Verifier.ts +54 -0
  140. package/src/vc/cryptosuites/bbs.ts +253 -0
  141. package/src/vc/cryptosuites/bbsSimple.ts +21 -0
  142. package/src/vc/cryptosuites/eddsa.ts +99 -0
  143. package/src/vc/documentLoader.ts +81 -0
  144. package/src/vc/proofs/data-integrity.ts +33 -0
  145. package/src/vc/utils/jsonld.ts +18 -0
@@ -0,0 +1,705 @@
1
+ import { DIDDocument, OriginalsConfig, AssetResource, KeyPair, ExternalSigner, ExternalVerifier } from '../types';
2
+ import { getNetworkDomain, DEFAULT_WEBVH_NETWORK, getBitcoinNetworkForWebVH } from '../types/network';
3
+ import { BtcoDidResolver } from './BtcoDidResolver';
4
+ import { OrdinalsClient } from '../bitcoin/OrdinalsClient';
5
+ import { createBtcoDidDocument } from './createBtcoDidDocument';
6
+ import { OrdinalsClientProviderAdapter } from './providers/OrdinalsClientProviderAdapter';
7
+ import { multikey } from '../crypto/Multikey';
8
+ import { KeyManager } from './KeyManager';
9
+ import { Ed25519Signer } from '../crypto/Signer';
10
+ import { validateSatoshiNumber, MAX_SATOSHI_SUPPLY } from '../utils/satoshi-validation';
11
+ import * as fs from 'fs';
12
+ import * as path from 'path';
13
+
14
+ export class DIDManager {
15
+ constructor(private config: OriginalsConfig) {}
16
+
17
+ async createDIDPeer(resources: AssetResource[], returnKeyPair?: false): Promise<DIDDocument>;
18
+ async createDIDPeer(resources: AssetResource[], returnKeyPair: true): Promise<{ didDocument: DIDDocument; keyPair: { privateKey: string; publicKey: string } }>;
19
+ async createDIDPeer(resources: AssetResource[], returnKeyPair?: boolean): Promise<DIDDocument | { didDocument: DIDDocument; keyPair: { privateKey: string; publicKey: string } }> {
20
+ // Generate a multikey keypair according to configured defaultKeyType
21
+ const keyManager = new KeyManager();
22
+ const desiredType = this.config.defaultKeyType || 'ES256K';
23
+ const keyPair = await keyManager.generateKeyPair(desiredType);
24
+
25
+ // Use @aviarytech/did-peer to create a did:peer (variant 4 long-form for full VM+context)
26
+ const didPeerMod = await import('@aviarytech/did-peer') as unknown as {
27
+ createNumAlgo4: (vms: unknown[], service?: unknown, extra?: unknown) => Promise<string>;
28
+ resolve: (did: string) => Promise<Record<string, unknown>>;
29
+ };
30
+ const did: string = await didPeerMod.createNumAlgo4(
31
+ [
32
+ {
33
+ // type validated by the library; controller/id not required
34
+ type: 'Multikey',
35
+ publicKeyMultibase: keyPair.publicKey
36
+ }
37
+ ],
38
+ undefined,
39
+ undefined
40
+ );
41
+
42
+ // Resolve to DID Document using the same library
43
+ const rawResolved = await didPeerMod.resolve(did);
44
+ // Type the resolved document properly
45
+ const resolved = rawResolved as unknown as {
46
+ id?: string;
47
+ verificationMethod?: Array<Record<string, unknown>>;
48
+ authentication?: string[];
49
+ assertionMethod?: string[];
50
+ [key: string]: unknown;
51
+ };
52
+ // Ensure controller is set on VM entries for compatibility
53
+ if (resolved && Array.isArray(resolved.verificationMethod)) {
54
+ resolved.verificationMethod = resolved.verificationMethod.map((vm) => ({
55
+ controller: did,
56
+ ...vm
57
+ }));
58
+ }
59
+ // Ensure relationships exist and reference a VM
60
+ const vmIds: string[] = Array.isArray(resolved?.verificationMethod)
61
+ ? (resolved.verificationMethod as Array<{ id?: string }>).map((vm) => vm.id).filter(Boolean) as string[]
62
+ : [];
63
+ if (!resolved.authentication || resolved.authentication.length === 0) {
64
+ if (vmIds.length > 0) resolved.authentication = [vmIds[0]];
65
+ }
66
+ if (!resolved.assertionMethod || resolved.assertionMethod.length === 0) {
67
+ resolved.assertionMethod = resolved.authentication || (vmIds.length > 0 ? [vmIds[0]] : []);
68
+ }
69
+
70
+ if (returnKeyPair) {
71
+ return { didDocument: resolved as unknown as DIDDocument, keyPair };
72
+ }
73
+ return resolved as unknown as DIDDocument;
74
+ }
75
+
76
+ async migrateToDIDWebVH(didDoc: DIDDocument, domain?: string): Promise<DIDDocument> {
77
+ // Use provided domain or get default from configured network
78
+ const network = this.config.webvhNetwork || DEFAULT_WEBVH_NETWORK;
79
+ const targetDomain = domain || getNetworkDomain(network);
80
+
81
+ // Flexible domain validation - allow development domains with ports
82
+ const normalized = String(targetDomain || '').trim().toLowerCase();
83
+
84
+ // Split domain and port if present
85
+ const [domainPart, portPart] = normalized.split(':');
86
+
87
+ // Validate port if present
88
+ if (portPart && (!/^\d+$/.test(portPart) || parseInt(portPart) < 1 || parseInt(portPart) > 65535)) {
89
+ throw new Error(`Invalid domain: ${domain} - invalid port`);
90
+ }
91
+
92
+ // Allow localhost and IP addresses for development
93
+ const isLocalhost = domainPart === 'localhost';
94
+ const isIP = /^(\d{1,3}\.){3}\d{1,3}$/.test(domainPart);
95
+
96
+ if (!isLocalhost && !isIP) {
97
+ // For non-localhost domains, require proper domain format
98
+ const label = '[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?';
99
+ const domainRegex = new RegExp(`^(?=.{1,253}$)(?:${label})(?:\\.(?:${label}))+?$`, 'i');
100
+ if (!domainRegex.test(domainPart)) {
101
+ throw new Error('Invalid domain');
102
+ }
103
+ }
104
+
105
+ // Stable slug derived from original peer DID suffix (or last segment)
106
+ const parts = (didDoc.id || '').split(':');
107
+ const method = parts.slice(0, 2).join(':');
108
+ const originalSuffix = method === 'did:peer' ? parts.slice(2).join(':') : parts[parts.length - 1];
109
+ const slug = (originalSuffix || '')
110
+ .toString()
111
+ .trim()
112
+ .replace(/[^a-zA-Z0-9._-]/g, '-')
113
+ .toLowerCase();
114
+
115
+ const migrated: DIDDocument = {
116
+ ...didDoc,
117
+ id: `did:webvh:${normalized}:${slug}`
118
+ };
119
+ return await Promise.resolve(migrated);
120
+ }
121
+
122
+ async migrateToDIDBTCO(didDoc: DIDDocument, satoshi: string): Promise<DIDDocument> {
123
+ // Validate satoshi parameter
124
+ const validation = validateSatoshiNumber(satoshi);
125
+ if (!validation.valid) {
126
+ throw new Error(`Invalid satoshi identifier: ${validation.error}`);
127
+ }
128
+
129
+ // Additional range validation for positive values within Bitcoin supply
130
+ const satoshiNum = Number(satoshi);
131
+ if (satoshiNum < 0) {
132
+ throw new Error('Satoshi identifier must be positive (>= 0)');
133
+ }
134
+ if (satoshiNum > MAX_SATOSHI_SUPPLY) {
135
+ throw new Error(`Satoshi identifier must be within Bitcoin's total supply (0 to ${MAX_SATOSHI_SUPPLY.toLocaleString()})`);
136
+ }
137
+
138
+ // Determine Bitcoin network from WebVH network configuration if available
139
+ // This ensures consistent environment mapping: magby→regtest, cleffa→signet, pichu→mainnet
140
+ let network: 'mainnet' | 'regtest' | 'signet';
141
+ if (this.config.webvhNetwork) {
142
+ network = getBitcoinNetworkForWebVH(this.config.webvhNetwork);
143
+ } else {
144
+ // Fall back to explicit network config
145
+ network = this.config.network || 'mainnet';
146
+ }
147
+
148
+ // Try to carry over the first multikey VM if present
149
+ const firstVm = didDoc.verificationMethod?.[0];
150
+ let publicKey: Uint8Array | undefined;
151
+ let keyType: Parameters<typeof createBtcoDidDocument>[2]['keyType'] | undefined;
152
+ try {
153
+ if (firstVm && firstVm.publicKeyMultibase) {
154
+ const decoded = multikey.decodePublicKey(firstVm.publicKeyMultibase);
155
+ publicKey = decoded.key;
156
+ keyType = decoded.type;
157
+ }
158
+ } catch (err) {
159
+ // Unable to decode public key from verification method; will proceed without key material
160
+ if (this.config.enableLogging) {
161
+ console.warn('Failed to decode verification method public key:', err);
162
+ }
163
+ }
164
+
165
+ // If no key material is available, generate a minimal btco DID doc without keys
166
+ let btcoDoc: DIDDocument;
167
+ if (publicKey && keyType) {
168
+ btcoDoc = createBtcoDidDocument(satoshi, network, { publicKey, keyType });
169
+ } else {
170
+ const prefix = network === 'mainnet' ? 'did:btco:' : network === 'regtest' ? 'did:btco:reg:' : 'did:btco:sig:';
171
+ btcoDoc = {
172
+ '@context': ['https://www.w3.org/ns/did/v1'],
173
+ id: prefix + String(satoshi)
174
+ };
175
+ }
176
+
177
+ // Carry over service endpoints if present
178
+ if (didDoc.service && didDoc.service.length > 0) {
179
+ btcoDoc.service = didDoc.service;
180
+ }
181
+ return await Promise.resolve(btcoDoc);
182
+ }
183
+
184
+ async resolveDID(did: string): Promise<DIDDocument | null> {
185
+ try {
186
+ if (did.startsWith('did:peer:')) {
187
+ try {
188
+ const mod = await import('@aviarytech/did-peer') as unknown as { resolve: (did: string) => Promise<Record<string, unknown>> };
189
+ const doc = await mod.resolve(did);
190
+ return doc as unknown as DIDDocument;
191
+ } catch (err) {
192
+ // Failed to resolve did:peer; returning minimal document
193
+ if (this.config.enableLogging) {
194
+ console.warn('Failed to resolve did:peer:', err);
195
+ }
196
+ }
197
+ return { '@context': ['https://www.w3.org/ns/did/v1'], id: did };
198
+ }
199
+ if (did.startsWith('did:btco:') || did.startsWith('did:btco:test:') || did.startsWith('did:btco:sig:')) {
200
+ const rpcUrl = this.config.bitcoinRpcUrl || 'http://localhost:3000';
201
+ const network = this.config.network || 'mainnet';
202
+ const client = new OrdinalsClient(rpcUrl, network);
203
+ const adapter = new OrdinalsClientProviderAdapter(client, rpcUrl);
204
+ const resolver = new BtcoDidResolver({ provider: adapter });
205
+ const result = await resolver.resolve(did);
206
+ return result.didDocument || null;
207
+ }
208
+ if (did.startsWith('did:webvh:')) {
209
+ try {
210
+ const mod = await import('didwebvh-ts') as { resolveDID?: (did: string) => Promise<{ doc?: Record<string, unknown> }> };
211
+ if (mod && typeof mod.resolveDID === 'function') {
212
+ const result = await mod.resolveDID(did);
213
+ if (result && result.doc) return result.doc as unknown as DIDDocument;
214
+ }
215
+ } catch (err) {
216
+ // Failed to resolve did:webvh; returning minimal document
217
+ if (this.config.enableLogging) {
218
+ console.warn('Failed to resolve did:webvh:', err);
219
+ }
220
+ }
221
+ return { '@context': ['https://www.w3.org/ns/did/v1'], id: did };
222
+ }
223
+ return { '@context': ['https://www.w3.org/ns/did/v1'], id: did };
224
+ } catch (err) {
225
+ // DID resolution failed
226
+ if (this.config.enableLogging) {
227
+ console.error('Failed to resolve DID:', err);
228
+ }
229
+ return null;
230
+ }
231
+ }
232
+
233
+ validateDIDDocument(didDoc: DIDDocument): boolean {
234
+ return !!didDoc.id && Array.isArray(didDoc['@context']);
235
+ }
236
+
237
+ private getLayerFromDID(did: string): 'did:peer' | 'did:webvh' | 'did:btco' {
238
+ if (did.startsWith('did:peer:')) return 'did:peer';
239
+ if (did.startsWith('did:webvh:')) return 'did:webvh';
240
+ if (did.startsWith('did:btco:')) return 'did:btco';
241
+ throw new Error('Unsupported DID method');
242
+ }
243
+
244
+ createBtcoDidDocument(
245
+ satNumber: number | string,
246
+ network: 'mainnet' | 'regtest' | 'signet',
247
+ options: Parameters<typeof createBtcoDidDocument>[2]
248
+ ): DIDDocument {
249
+ return createBtcoDidDocument(satNumber, network, options);
250
+ }
251
+
252
+ // ========================================================================
253
+ // DID:WebVH Methods
254
+ // ========================================================================
255
+
256
+ /**
257
+ * Creates a new did:webvh DID with proper cryptographic signing
258
+ * @param options - Creation options including domain and optional key pair or external signer
259
+ * @returns The created DID, document, log, and key pair (if generated)
260
+ */
261
+ async createDIDWebVH(options: CreateWebVHOptions): Promise<CreateWebVHResult> {
262
+ const {
263
+ domain: providedDomain,
264
+ keyPair: providedKeyPair,
265
+ paths = [],
266
+ portable = false,
267
+ outputDir,
268
+ externalSigner,
269
+ externalVerifier,
270
+ verificationMethods: providedVerificationMethods,
271
+ updateKeys: providedUpdateKeys
272
+ } = options;
273
+
274
+ // Use provided domain or get default from configured network
275
+ const network = this.config.webvhNetwork || DEFAULT_WEBVH_NETWORK;
276
+ const domain = providedDomain || getNetworkDomain(network);
277
+
278
+ // Dynamically import didwebvh-ts to avoid module resolution issues
279
+ const mod = await import('didwebvh-ts') as unknown as {
280
+ createDID: (options: Record<string, unknown>) => Promise<{
281
+ did: string;
282
+ doc: Record<string, unknown>;
283
+ log: DIDLog;
284
+ }>;
285
+ prepareDataForSigning: (
286
+ document: Record<string, unknown>,
287
+ proof: Record<string, unknown>
288
+ ) => Promise<Uint8Array>;
289
+ };
290
+ const { createDID, prepareDataForSigning } = mod;
291
+
292
+ // Runtime validation of imported module
293
+ if (typeof createDID !== 'function' || typeof prepareDataForSigning !== 'function') {
294
+ throw new Error('Failed to load didwebvh-ts: invalid module exports');
295
+ }
296
+
297
+ let signer: Signer | ExternalSigner;
298
+ let verifier: Verifier | ExternalVerifier;
299
+ let keyPair: KeyPair | undefined;
300
+ let verificationMethods: WebVHVerificationMethod[];
301
+ let updateKeys: string[];
302
+
303
+ // Use external signer if provided (e.g., Turnkey integration)
304
+ if (externalSigner) {
305
+ if (!providedVerificationMethods || providedVerificationMethods.length === 0) {
306
+ throw new Error('verificationMethods are required when using externalSigner');
307
+ }
308
+ if (!providedUpdateKeys || providedUpdateKeys.length === 0) {
309
+ throw new Error('updateKeys are required when using externalSigner');
310
+ }
311
+
312
+ signer = externalSigner;
313
+ verifier = externalVerifier || (externalSigner as unknown as ExternalVerifier); // Use signer as verifier if not provided
314
+ verificationMethods = providedVerificationMethods;
315
+ updateKeys = providedUpdateKeys;
316
+ keyPair = undefined; // No key pair when using external signer
317
+ } else {
318
+ // Generate or use provided key pair (Ed25519 for did:webvh)
319
+ const keyManager = new KeyManager();
320
+ keyPair = providedKeyPair || await keyManager.generateKeyPair('Ed25519');
321
+
322
+ // Create verification methods
323
+ verificationMethods = [
324
+ {
325
+ type: 'Multikey',
326
+ publicKeyMultibase: keyPair.publicKey,
327
+ }
328
+ ];
329
+
330
+ // Create signer using our adapter
331
+ const internalSigner = new OriginalsWebVHSigner(
332
+ keyPair.privateKey,
333
+ verificationMethods[0],
334
+ prepareDataForSigning,
335
+ { verificationMethod: verificationMethods[0] }
336
+ );
337
+
338
+ signer = internalSigner;
339
+ verifier = internalSigner; // Use the same signer as verifier
340
+ updateKeys = [`did:key:${keyPair.publicKey}`]; // Use did:key format for authorization
341
+ }
342
+
343
+ // Create the DID using didwebvh-ts
344
+ const result = await createDID({
345
+ domain,
346
+ signer,
347
+ verifier,
348
+ updateKeys,
349
+ verificationMethods,
350
+ context: [
351
+ 'https://www.w3.org/ns/did/v1',
352
+ 'https://w3id.org/security/multikey/v1'
353
+ ],
354
+ paths,
355
+ portable,
356
+ authentication: ['#key-0'],
357
+ assertionMethod: ['#key-0'],
358
+ });
359
+
360
+ // Validate the returned DID document
361
+ if (!this.validateDIDDocument(result.doc as unknown as DIDDocument)) {
362
+ throw new Error('Invalid DID document returned from createDID');
363
+ }
364
+
365
+ // Save the log to did.jsonl if output directory is provided
366
+ let logPath: string | undefined;
367
+ if (outputDir) {
368
+ logPath = await this.saveDIDLog(result.did, result.log, outputDir);
369
+ }
370
+
371
+ return {
372
+ did: result.did,
373
+ didDocument: result.doc as unknown as DIDDocument,
374
+ log: result.log,
375
+ keyPair: keyPair || { publicKey: '', privateKey: '' }, // Return empty keypair if using external signer
376
+ logPath,
377
+ };
378
+ }
379
+
380
+ /**
381
+ * Updates a DID:WebVH document
382
+ * @param options - Update options
383
+ * @returns Updated DID document and log
384
+ */
385
+ async updateDIDWebVH(options: {
386
+ did: string;
387
+ currentLog: DIDLog;
388
+ updates: Partial<DIDDocument>;
389
+ signer: ExternalSigner | { privateKey: string; publicKey: string };
390
+ verifier?: ExternalVerifier;
391
+ outputDir?: string;
392
+ }): Promise<{ didDocument: DIDDocument; log: DIDLog; logPath?: string }> {
393
+ const { did, currentLog, updates, signer: providedSigner, verifier: providedVerifier, outputDir } = options;
394
+
395
+ // Dynamically import didwebvh-ts
396
+ const mod = await import('didwebvh-ts') as unknown as {
397
+ updateDID: (options: Record<string, unknown>) => Promise<{
398
+ doc: Record<string, unknown>;
399
+ log: DIDLog;
400
+ }>;
401
+ prepareDataForSigning: (
402
+ document: Record<string, unknown>,
403
+ proof: Record<string, unknown>
404
+ ) => Promise<Uint8Array>;
405
+ };
406
+ const { updateDID, prepareDataForSigning } = mod;
407
+
408
+ if (typeof updateDID !== 'function') {
409
+ throw new Error('Failed to load didwebvh-ts: invalid module exports');
410
+ }
411
+
412
+ let signer: Signer | ExternalSigner;
413
+ let verifier: Verifier | ExternalVerifier | undefined;
414
+
415
+ // Check if using external signer or internal keypair
416
+ if ('sign' in providedSigner && 'getVerificationMethodId' in providedSigner) {
417
+ // External signer
418
+ signer = providedSigner;
419
+ verifier = providedVerifier;
420
+ } else {
421
+ // Internal signer with keypair
422
+ const keyPair = providedSigner;
423
+ const verificationMethod: WebVHVerificationMethod = {
424
+ type: 'Multikey',
425
+ publicKeyMultibase: keyPair.publicKey,
426
+ };
427
+
428
+ const internalSigner = new OriginalsWebVHSigner(
429
+ keyPair.privateKey,
430
+ verificationMethod,
431
+ prepareDataForSigning,
432
+ { verificationMethod }
433
+ );
434
+
435
+ signer = internalSigner;
436
+ verifier = internalSigner;
437
+ }
438
+
439
+ // Get the current document from the log
440
+ const currentEntry = currentLog[currentLog.length - 1];
441
+ const currentDoc = currentEntry.state as unknown as DIDDocument;
442
+
443
+ // Merge updates with current document
444
+ const updatedDoc = {
445
+ ...currentDoc,
446
+ ...updates,
447
+ id: did, // Ensure ID doesn't change
448
+ };
449
+
450
+ // Update the DID using didwebvh-ts
451
+ const result = await updateDID({
452
+ log: currentLog,
453
+ doc: updatedDoc,
454
+ signer,
455
+ verifier,
456
+ });
457
+
458
+ // Validate the returned DID document
459
+ if (!this.validateDIDDocument(result.doc as unknown as DIDDocument)) {
460
+ throw new Error('Invalid DID document returned from updateDID');
461
+ }
462
+
463
+ // Save the updated log if output directory is provided
464
+ let logPath: string | undefined;
465
+ if (outputDir) {
466
+ logPath = await this.saveDIDLog(did, result.log, outputDir);
467
+ }
468
+
469
+ return {
470
+ didDocument: result.doc as unknown as DIDDocument,
471
+ log: result.log,
472
+ logPath,
473
+ };
474
+ }
475
+
476
+ /**
477
+ * Saves the DID log to the appropriate did.jsonl path
478
+ * @param did - The DID identifier
479
+ * @param log - The DID log to save
480
+ * @param baseDir - Base directory for saving (e.g., public/.well-known)
481
+ * @returns The full path where the log was saved
482
+ */
483
+ async saveDIDLog(did: string, log: DIDLog, baseDir: string): Promise<string> {
484
+ // Parse the DID to extract domain and path components
485
+ // Format: did:webvh:domain[:port]:path1:path2...
486
+ const didParts = did.split(':');
487
+ if (didParts.length < 3 || didParts[0] !== 'did' || didParts[1] !== 'webvh') {
488
+ throw new Error('Invalid did:webvh format');
489
+ }
490
+
491
+ // Extract path parts (everything after domain)
492
+ const pathParts = didParts.slice(3);
493
+
494
+ // Validate all path segments to prevent directory traversal
495
+ for (const segment of pathParts) {
496
+ if (!this.isValidPathSegment(segment)) {
497
+ throw new Error(`Invalid path segment in DID: "${segment}". Path segments cannot contain '.', '..', path separators, or be absolute paths.`);
498
+ }
499
+ }
500
+
501
+ // Extract and sanitize domain for filesystem safety
502
+ const rawDomain = decodeURIComponent(didParts[2]);
503
+ // Normalize: lowercase and replace any characters not in [a-z0-9._-] with '_'
504
+ const safeDomain = rawDomain
505
+ .toLowerCase()
506
+ .replace(/[^a-z0-9._-]/g, '_');
507
+
508
+ // Validate the sanitized domain (reject '..' and other dangerous patterns)
509
+ if (!this.isValidPathSegment(safeDomain)) {
510
+ throw new Error(`Invalid domain segment in DID: "${rawDomain}"`);
511
+ }
512
+
513
+ // Construct the file path with domain isolation
514
+ // For did:webvh:example.com:user:alice -> baseDir/did/example.com/user/alice/did.jsonl
515
+ // For did:webvh:example.com:alice -> baseDir/did/example.com/alice/did.jsonl
516
+ const segments = [safeDomain, ...pathParts];
517
+ const didPath = path.join(baseDir, 'did', ...segments, 'did.jsonl');
518
+
519
+ // Verify the resolved path is still within baseDir (defense in depth)
520
+ const resolvedBaseDir = path.resolve(baseDir);
521
+ const resolvedPath = path.resolve(didPath);
522
+ const relativePath = path.relative(resolvedBaseDir, resolvedPath);
523
+ if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) {
524
+ throw new Error('Invalid DID path: resolved path is outside base directory');
525
+ }
526
+
527
+ // Create directories if they don't exist
528
+ const dirPath = path.dirname(didPath);
529
+ await fs.promises.mkdir(dirPath, { recursive: true });
530
+
531
+ // Convert log to JSONL format (one JSON object per line)
532
+ const jsonlContent = log.map((entry: DIDLogEntry) => JSON.stringify(entry)).join('\n');
533
+
534
+ // Write the log file
535
+ await fs.promises.writeFile(didPath, jsonlContent, 'utf8');
536
+
537
+ return didPath;
538
+ }
539
+
540
+ /**
541
+ * Loads a DID log from a did.jsonl file
542
+ * @param logPath - Path to the did.jsonl file
543
+ * @returns The loaded DID log
544
+ */
545
+ async loadDIDLog(logPath: string): Promise<DIDLog> {
546
+ const content = await fs.promises.readFile(logPath, 'utf8');
547
+ const lines = content.trim().split('\n');
548
+ return lines.map(line => JSON.parse(line) as DIDLogEntry);
549
+ }
550
+
551
+ /**
552
+ * Validates a path segment to prevent directory traversal attacks
553
+ * @param segment - Path segment to validate
554
+ * @returns true if valid, false otherwise
555
+ */
556
+ private isValidPathSegment(segment: string): boolean {
557
+ // Reject empty segments, dots, or segments with path separators
558
+ if (!segment || segment === '.' || segment === '..') {
559
+ return false;
560
+ }
561
+
562
+ // Reject segments containing path separators or other dangerous characters
563
+ if (segment.includes('/') || segment.includes('\\') || segment.includes('\0')) {
564
+ return false;
565
+ }
566
+
567
+ // Reject absolute paths (starting with / or drive letter on Windows)
568
+ if (path.isAbsolute(segment)) {
569
+ return false;
570
+ }
571
+
572
+ return true;
573
+ }
574
+ }
575
+
576
+ // Type definitions for didwebvh-ts (to avoid module resolution issues)
577
+ interface WebVHVerificationMethod {
578
+ id?: string;
579
+ type: string;
580
+ controller?: string;
581
+ publicKeyMultibase: string;
582
+ secretKeyMultibase?: string;
583
+ purpose?: 'authentication' | 'assertionMethod' | 'keyAgreement' | 'capabilityInvocation' | 'capabilityDelegation';
584
+ }
585
+
586
+ interface SigningInput {
587
+ document: Record<string, unknown>;
588
+ proof: Record<string, unknown>;
589
+ }
590
+
591
+ interface SigningOutput {
592
+ proofValue: string;
593
+ }
594
+
595
+ interface SignerOptions {
596
+ verificationMethod?: WebVHVerificationMethod | null;
597
+ useStaticId?: boolean;
598
+ }
599
+
600
+ interface Signer {
601
+ sign(input: SigningInput): Promise<SigningOutput>;
602
+ getVerificationMethodId(): string;
603
+ }
604
+
605
+ interface Verifier {
606
+ verify(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): Promise<boolean>;
607
+ }
608
+
609
+ interface DIDLogEntry {
610
+ versionId: string;
611
+ versionTime: string;
612
+ parameters: Record<string, unknown>;
613
+ state: Record<string, unknown>;
614
+ proof?: Record<string, unknown>[];
615
+ }
616
+
617
+ type DIDLog = DIDLogEntry[];
618
+
619
+ export interface CreateWebVHOptions {
620
+ domain?: string; // Optional - defaults to configured webvhNetwork domain
621
+ keyPair?: KeyPair;
622
+ paths?: string[];
623
+ portable?: boolean;
624
+ outputDir?: string;
625
+ externalSigner?: ExternalSigner;
626
+ externalVerifier?: ExternalVerifier;
627
+ verificationMethods?: WebVHVerificationMethod[];
628
+ updateKeys?: string[];
629
+ }
630
+
631
+ export interface CreateWebVHResult {
632
+ did: string;
633
+ didDocument: DIDDocument;
634
+ log: DIDLog;
635
+ keyPair: KeyPair;
636
+ logPath?: string;
637
+ }
638
+
639
+ /**
640
+ * Adapter to use Originals SDK signers with didwebvh-ts
641
+ */
642
+ class OriginalsWebVHSigner implements Signer, Verifier {
643
+ private privateKeyMultibase: string;
644
+ private signer: Ed25519Signer;
645
+ protected verificationMethod?: WebVHVerificationMethod | null;
646
+ protected useStaticId: boolean;
647
+ private prepareDataForSigning: (document: Record<string, unknown>, proof: Record<string, unknown>) => Promise<Uint8Array>;
648
+
649
+ constructor(
650
+ privateKeyMultibase: string,
651
+ verificationMethod: WebVHVerificationMethod,
652
+ prepareDataForSigning: (document: Record<string, unknown>, proof: Record<string, unknown>) => Promise<Uint8Array>,
653
+ options: SignerOptions = {}
654
+ ) {
655
+ this.privateKeyMultibase = privateKeyMultibase;
656
+ this.verificationMethod = options.verificationMethod || verificationMethod;
657
+ this.useStaticId = options.useStaticId || false;
658
+ this.signer = new Ed25519Signer();
659
+ this.prepareDataForSigning = prepareDataForSigning;
660
+ }
661
+
662
+ async sign(input: SigningInput): Promise<SigningOutput> {
663
+ // Prepare the data for signing using didwebvh-ts's canonical approach
664
+ const dataToSign = await this.prepareDataForSigning(input.document, input.proof);
665
+
666
+ // Sign using our Ed25519 signer
667
+ const signature: Buffer = await this.signer.sign(
668
+ Buffer.from(dataToSign),
669
+ this.privateKeyMultibase
670
+ );
671
+
672
+ // Encode signature as multibase
673
+ const proofValue = multikey.encodeMultibase(signature);
674
+
675
+ return { proofValue };
676
+ }
677
+
678
+ async verify(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): Promise<boolean> {
679
+ // Decode the public key to multibase format
680
+ const publicKeyMultibase = multikey.encodePublicKey(publicKey, 'Ed25519');
681
+
682
+ // Verify using our Ed25519 signer
683
+ const messageBuffer: Buffer = Buffer.from(message);
684
+ const signatureBuffer: Buffer = Buffer.from(signature);
685
+
686
+ return this.signer.verify(
687
+ messageBuffer,
688
+ signatureBuffer,
689
+ publicKeyMultibase
690
+ );
691
+ }
692
+
693
+ getVerificationMethodId(): string {
694
+ // didwebvh-ts requires verification method to be a did:key: identifier
695
+ // Extract the multibase key from the verification method
696
+ const publicKeyMultibase = this.verificationMethod?.publicKeyMultibase;
697
+ if (!publicKeyMultibase) {
698
+ throw new Error('Verification method must have publicKeyMultibase');
699
+ }
700
+ // Return as did:key format which didwebvh-ts expects
701
+ return `did:key:${publicKeyMultibase}`;
702
+ }
703
+ }
704
+
705
+