@originals/sdk 1.4.2 → 1.4.3

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 (212) hide show
  1. package/package.json +4 -1
  2. package/.eslintrc.json +0 -33
  3. package/src/adapters/FeeOracleMock.ts +0 -9
  4. package/src/adapters/index.ts +0 -5
  5. package/src/adapters/providers/OrdHttpProvider.ts +0 -126
  6. package/src/adapters/providers/OrdMockProvider.ts +0 -101
  7. package/src/adapters/types.ts +0 -66
  8. package/src/bitcoin/BitcoinManager.ts +0 -330
  9. package/src/bitcoin/BroadcastClient.ts +0 -54
  10. package/src/bitcoin/OrdinalsClient.ts +0 -119
  11. package/src/bitcoin/PSBTBuilder.ts +0 -106
  12. package/src/bitcoin/fee-calculation.ts +0 -38
  13. package/src/bitcoin/providers/OrdNodeProvider.ts +0 -92
  14. package/src/bitcoin/providers/OrdinalsProvider.ts +0 -56
  15. package/src/bitcoin/providers/types.ts +0 -59
  16. package/src/bitcoin/transactions/commit.ts +0 -465
  17. package/src/bitcoin/transactions/index.ts +0 -13
  18. package/src/bitcoin/transfer.ts +0 -43
  19. package/src/bitcoin/utxo-selection.ts +0 -322
  20. package/src/bitcoin/utxo.ts +0 -113
  21. package/src/contexts/credentials-v1.json +0 -237
  22. package/src/contexts/credentials-v2-examples.json +0 -5
  23. package/src/contexts/credentials-v2.json +0 -340
  24. package/src/contexts/credentials.json +0 -237
  25. package/src/contexts/data-integrity-v2.json +0 -81
  26. package/src/contexts/dids.json +0 -58
  27. package/src/contexts/ed255192020.json +0 -93
  28. package/src/contexts/ordinals-plus.json +0 -23
  29. package/src/contexts/originals.json +0 -22
  30. package/src/core/OriginalsSDK.ts +0 -416
  31. package/src/crypto/Multikey.ts +0 -194
  32. package/src/crypto/Signer.ts +0 -254
  33. package/src/crypto/noble-init.ts +0 -121
  34. package/src/did/BtcoDidResolver.ts +0 -227
  35. package/src/did/DIDManager.ts +0 -694
  36. package/src/did/Ed25519Verifier.ts +0 -68
  37. package/src/did/KeyManager.ts +0 -236
  38. package/src/did/WebVHManager.ts +0 -498
  39. package/src/did/createBtcoDidDocument.ts +0 -59
  40. package/src/did/providers/OrdinalsClientProviderAdapter.ts +0 -68
  41. package/src/events/EventEmitter.ts +0 -222
  42. package/src/events/index.ts +0 -19
  43. package/src/events/types.ts +0 -331
  44. package/src/examples/basic-usage.ts +0 -78
  45. package/src/examples/create-module-original.ts +0 -435
  46. package/src/examples/full-lifecycle-flow.ts +0 -514
  47. package/src/examples/run.ts +0 -60
  48. package/src/index.ts +0 -150
  49. package/src/kinds/KindRegistry.ts +0 -290
  50. package/src/kinds/index.ts +0 -74
  51. package/src/kinds/types.ts +0 -470
  52. package/src/kinds/validators/AgentValidator.ts +0 -257
  53. package/src/kinds/validators/AppValidator.ts +0 -211
  54. package/src/kinds/validators/DatasetValidator.ts +0 -242
  55. package/src/kinds/validators/DocumentValidator.ts +0 -311
  56. package/src/kinds/validators/MediaValidator.ts +0 -269
  57. package/src/kinds/validators/ModuleValidator.ts +0 -225
  58. package/src/kinds/validators/base.ts +0 -276
  59. package/src/kinds/validators/index.ts +0 -12
  60. package/src/lifecycle/BatchOperations.ts +0 -373
  61. package/src/lifecycle/LifecycleManager.ts +0 -2126
  62. package/src/lifecycle/OriginalsAsset.ts +0 -524
  63. package/src/lifecycle/ProvenanceQuery.ts +0 -280
  64. package/src/lifecycle/ResourceVersioning.ts +0 -163
  65. package/src/migration/MigrationManager.ts +0 -527
  66. package/src/migration/audit/AuditLogger.ts +0 -176
  67. package/src/migration/checkpoint/CheckpointManager.ts +0 -112
  68. package/src/migration/checkpoint/CheckpointStorage.ts +0 -101
  69. package/src/migration/index.ts +0 -33
  70. package/src/migration/operations/BaseMigration.ts +0 -126
  71. package/src/migration/operations/PeerToBtcoMigration.ts +0 -105
  72. package/src/migration/operations/PeerToWebvhMigration.ts +0 -62
  73. package/src/migration/operations/WebvhToBtcoMigration.ts +0 -105
  74. package/src/migration/rollback/RollbackManager.ts +0 -170
  75. package/src/migration/state/StateMachine.ts +0 -92
  76. package/src/migration/state/StateTracker.ts +0 -156
  77. package/src/migration/types.ts +0 -344
  78. package/src/migration/validation/BitcoinValidator.ts +0 -107
  79. package/src/migration/validation/CredentialValidator.ts +0 -62
  80. package/src/migration/validation/DIDCompatibilityValidator.ts +0 -151
  81. package/src/migration/validation/LifecycleValidator.ts +0 -64
  82. package/src/migration/validation/StorageValidator.ts +0 -79
  83. package/src/migration/validation/ValidationPipeline.ts +0 -213
  84. package/src/resources/ResourceManager.ts +0 -655
  85. package/src/resources/index.ts +0 -21
  86. package/src/resources/types.ts +0 -202
  87. package/src/storage/LocalStorageAdapter.ts +0 -61
  88. package/src/storage/MemoryStorageAdapter.ts +0 -29
  89. package/src/storage/StorageAdapter.ts +0 -25
  90. package/src/storage/index.ts +0 -3
  91. package/src/types/bitcoin.ts +0 -98
  92. package/src/types/common.ts +0 -92
  93. package/src/types/credentials.ts +0 -88
  94. package/src/types/did.ts +0 -31
  95. package/src/types/external-shims.d.ts +0 -53
  96. package/src/types/index.ts +0 -7
  97. package/src/types/network.ts +0 -175
  98. package/src/utils/EventLogger.ts +0 -298
  99. package/src/utils/Logger.ts +0 -322
  100. package/src/utils/MetricsCollector.ts +0 -358
  101. package/src/utils/bitcoin-address.ts +0 -130
  102. package/src/utils/cbor.ts +0 -12
  103. package/src/utils/encoding.ts +0 -127
  104. package/src/utils/hash.ts +0 -6
  105. package/src/utils/retry.ts +0 -46
  106. package/src/utils/satoshi-validation.ts +0 -196
  107. package/src/utils/serialization.ts +0 -96
  108. package/src/utils/telemetry.ts +0 -40
  109. package/src/utils/validation.ts +0 -119
  110. package/src/vc/CredentialManager.ts +0 -918
  111. package/src/vc/Issuer.ts +0 -100
  112. package/src/vc/Verifier.ts +0 -47
  113. package/src/vc/cryptosuites/bbs.ts +0 -253
  114. package/src/vc/cryptosuites/bbsSimple.ts +0 -21
  115. package/src/vc/cryptosuites/eddsa.ts +0 -99
  116. package/src/vc/documentLoader.ts +0 -67
  117. package/src/vc/proofs/data-integrity.ts +0 -33
  118. package/src/vc/utils/jsonld.ts +0 -18
  119. package/tests/__mocks__/bbs-signatures.js +0 -17
  120. package/tests/__mocks__/mf-base58.js +0 -24
  121. package/tests/fixtures/did-documents.ts +0 -247
  122. package/tests/index.test.ts +0 -21
  123. package/tests/integration/BatchOperations.test.ts +0 -531
  124. package/tests/integration/CompleteLifecycle.e2e.test.ts +0 -735
  125. package/tests/integration/CredentialManager.test.ts +0 -42
  126. package/tests/integration/DIDManager.test.ts +0 -41
  127. package/tests/integration/DidPeerToWebVhFlow.test.ts +0 -351
  128. package/tests/integration/Events.test.ts +0 -435
  129. package/tests/integration/Lifecycle.transfer.btco.integration.test.ts +0 -25
  130. package/tests/integration/LifecycleManager.test.ts +0 -21
  131. package/tests/integration/MultikeyFlow.test.ts +0 -52
  132. package/tests/integration/TelemetryIntegration.test.ts +0 -395
  133. package/tests/integration/WebVhPublish.test.ts +0 -48
  134. package/tests/integration/createTypedOriginal.test.ts +0 -379
  135. package/tests/integration/migration/peer-to-webvh.test.ts +0 -172
  136. package/tests/manual/test-commit-creation.ts +0 -323
  137. package/tests/mocks/MockKeyStore.ts +0 -38
  138. package/tests/mocks/adapters/MemoryStorageAdapter.ts +0 -24
  139. package/tests/mocks/adapters/MockFeeOracle.ts +0 -11
  140. package/tests/mocks/adapters/MockOrdinalsProvider.ts +0 -76
  141. package/tests/mocks/adapters/OrdMockProvider.test.ts +0 -176
  142. package/tests/mocks/adapters/index.ts +0 -6
  143. package/tests/performance/BatchOperations.perf.test.ts +0 -403
  144. package/tests/performance/logging.perf.test.ts +0 -336
  145. package/tests/sdk.test.ts +0 -43
  146. package/tests/security/bitcoin-penetration-tests.test.ts +0 -622
  147. package/tests/setup.bun.ts +0 -69
  148. package/tests/setup.jest.ts +0 -23
  149. package/tests/stress/batch-operations-stress.test.ts +0 -571
  150. package/tests/unit/adapters/FeeOracleMock.test.ts +0 -40
  151. package/tests/unit/bitcoin/BitcoinManager.test.ts +0 -293
  152. package/tests/unit/bitcoin/BroadcastClient.test.ts +0 -52
  153. package/tests/unit/bitcoin/OrdNodeProvider.test.ts +0 -53
  154. package/tests/unit/bitcoin/OrdinalsClient.test.ts +0 -381
  155. package/tests/unit/bitcoin/OrdinalsClientProvider.test.ts +0 -102
  156. package/tests/unit/bitcoin/PSBTBuilder.test.ts +0 -84
  157. package/tests/unit/bitcoin/fee-calculation.test.ts +0 -261
  158. package/tests/unit/bitcoin/transactions/commit.test.ts +0 -649
  159. package/tests/unit/bitcoin/transfer.test.ts +0 -31
  160. package/tests/unit/bitcoin/utxo-selection-new.test.ts +0 -502
  161. package/tests/unit/bitcoin/utxo.more.test.ts +0 -39
  162. package/tests/unit/bitcoin/utxo.selection.test.ts +0 -38
  163. package/tests/unit/core/OriginalsSDK.test.ts +0 -152
  164. package/tests/unit/crypto/Multikey.test.ts +0 -206
  165. package/tests/unit/crypto/Signer.test.ts +0 -408
  166. package/tests/unit/did/BtcoDidResolver.test.ts +0 -611
  167. package/tests/unit/did/DIDManager.more.test.ts +0 -43
  168. package/tests/unit/did/DIDManager.test.ts +0 -185
  169. package/tests/unit/did/Ed25519Verifier.test.ts +0 -160
  170. package/tests/unit/did/KeyManager.test.ts +0 -452
  171. package/tests/unit/did/OrdinalsClientProviderAdapter.test.ts +0 -45
  172. package/tests/unit/did/WebVHManager.test.ts +0 -435
  173. package/tests/unit/did/createBtcoDidDocument.test.ts +0 -67
  174. package/tests/unit/did/providers/OrdinalsClientProviderAdapter.test.ts +0 -159
  175. package/tests/unit/events/EventEmitter.test.ts +0 -407
  176. package/tests/unit/kinds/KindRegistry.test.ts +0 -329
  177. package/tests/unit/kinds/types.test.ts +0 -409
  178. package/tests/unit/kinds/validators.test.ts +0 -651
  179. package/tests/unit/lifecycle/BatchOperations.test.ts +0 -527
  180. package/tests/unit/lifecycle/LifecycleManager.cleanapi.test.ts +0 -441
  181. package/tests/unit/lifecycle/LifecycleManager.keymanagement.test.ts +0 -312
  182. package/tests/unit/lifecycle/LifecycleManager.prov.test.ts +0 -18
  183. package/tests/unit/lifecycle/LifecycleManager.test.ts +0 -213
  184. package/tests/unit/lifecycle/LifecycleManager.transfer.unit.test.ts +0 -30
  185. package/tests/unit/lifecycle/OriginalsAsset.test.ts +0 -176
  186. package/tests/unit/lifecycle/ProvenanceQuery.test.ts +0 -577
  187. package/tests/unit/lifecycle/ResourceVersioning.test.ts +0 -651
  188. package/tests/unit/resources/ResourceManager.test.ts +0 -740
  189. package/tests/unit/storage/MemoryStorageAdapter.test.ts +0 -93
  190. package/tests/unit/types/network.test.ts +0 -255
  191. package/tests/unit/utils/EventIntegration.test.ts +0 -384
  192. package/tests/unit/utils/Logger.test.ts +0 -473
  193. package/tests/unit/utils/MetricsCollector.test.ts +0 -358
  194. package/tests/unit/utils/bitcoin-address.test.ts +0 -250
  195. package/tests/unit/utils/cbor.test.ts +0 -35
  196. package/tests/unit/utils/encoding.test.ts +0 -318
  197. package/tests/unit/utils/hash.test.ts +0 -12
  198. package/tests/unit/utils/retry.test.ts +0 -100
  199. package/tests/unit/utils/satoshi-validation.test.ts +0 -354
  200. package/tests/unit/utils/serialization.test.ts +0 -124
  201. package/tests/unit/utils/telemetry.test.ts +0 -52
  202. package/tests/unit/utils/validation.test.ts +0 -141
  203. package/tests/unit/vc/CredentialManager.helpers.test.ts +0 -527
  204. package/tests/unit/vc/CredentialManager.test.ts +0 -487
  205. package/tests/unit/vc/Issuer.test.ts +0 -107
  206. package/tests/unit/vc/Verifier.test.ts +0 -525
  207. package/tests/unit/vc/bbs.test.ts +0 -282
  208. package/tests/unit/vc/cryptosuites/eddsa.test.ts +0 -398
  209. package/tests/unit/vc/documentLoader.test.ts +0 -121
  210. package/tests/unit/vc/proofs/data-integrity.test.ts +0 -24
  211. package/tsconfig.json +0 -31
  212. package/tsconfig.test.json +0 -15
@@ -1,498 +0,0 @@
1
- import { KeyManager } from './KeyManager';
2
- import { multikey } from '../crypto/Multikey';
3
- import { Ed25519Signer } from '../crypto/Signer';
4
- import { DIDDocument, KeyPair, ExternalSigner, ExternalVerifier } from '../types';
5
- import * as fs from 'fs';
6
- import * as path from 'path';
7
-
8
- // Type definitions for didwebvh-ts (to avoid module resolution issues)
9
- interface VerificationMethod {
10
- id?: string;
11
- type: string;
12
- controller?: string;
13
- publicKeyMultibase: string;
14
- secretKeyMultibase?: string;
15
- purpose?: 'authentication' | 'assertionMethod' | 'keyAgreement' | 'capabilityInvocation' | 'capabilityDelegation';
16
- }
17
-
18
- interface SigningInput {
19
- document: Record<string, unknown>;
20
- proof: Record<string, unknown>;
21
- }
22
-
23
- interface SigningOutput {
24
- proofValue: string;
25
- }
26
-
27
- interface SignerOptions {
28
- verificationMethod?: VerificationMethod | null;
29
- useStaticId?: boolean;
30
- }
31
-
32
- interface Signer {
33
- sign(input: SigningInput): Promise<SigningOutput>;
34
- getVerificationMethodId(): string;
35
- }
36
-
37
- interface Verifier {
38
- verify(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): Promise<boolean>;
39
- }
40
-
41
- interface DIDLogEntry {
42
- versionId: string;
43
- versionTime: string;
44
- parameters: Record<string, unknown>;
45
- state: Record<string, unknown>;
46
- proof?: Record<string, unknown>[];
47
- }
48
-
49
- type DIDLog = DIDLogEntry[];
50
-
51
- /**
52
- * Adapter to use Originals SDK signers with didwebvh-ts
53
- */
54
- class OriginalsWebVHSigner implements Signer, Verifier {
55
- private privateKeyMultibase: string;
56
- private signer: Ed25519Signer;
57
- protected verificationMethod?: VerificationMethod | null;
58
- protected useStaticId: boolean;
59
- private prepareDataForSigning: (document: Record<string, unknown>, proof: Record<string, unknown>) => Promise<Uint8Array>;
60
-
61
- constructor(
62
- privateKeyMultibase: string,
63
- verificationMethod: VerificationMethod,
64
- prepareDataForSigning: (document: Record<string, unknown>, proof: Record<string, unknown>) => Promise<Uint8Array>,
65
- options: SignerOptions = {}
66
- ) {
67
- this.privateKeyMultibase = privateKeyMultibase;
68
- this.verificationMethod = options.verificationMethod || verificationMethod;
69
- this.useStaticId = options.useStaticId || false;
70
- this.signer = new Ed25519Signer();
71
- this.prepareDataForSigning = prepareDataForSigning;
72
- }
73
-
74
- async sign(input: SigningInput): Promise<SigningOutput> {
75
- // Prepare the data for signing using didwebvh-ts's canonical approach
76
- const dataToSign = await this.prepareDataForSigning(input.document, input.proof);
77
-
78
- // Sign using our Ed25519 signer
79
- const signature: Buffer = await this.signer.sign(
80
- Buffer.from(dataToSign),
81
- this.privateKeyMultibase
82
- );
83
-
84
- // Encode signature as multibase
85
- const proofValue = multikey.encodeMultibase(signature);
86
-
87
- return { proofValue };
88
- }
89
-
90
- async verify(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): Promise<boolean> {
91
- // Decode the public key to multibase format
92
- const publicKeyMultibase = multikey.encodePublicKey(publicKey, 'Ed25519');
93
-
94
- // Verify using our Ed25519 signer
95
- const messageBuffer: Buffer = Buffer.from(message);
96
- const signatureBuffer: Buffer = Buffer.from(signature);
97
-
98
- return this.signer.verify(
99
- messageBuffer,
100
- signatureBuffer,
101
- publicKeyMultibase
102
- );
103
- }
104
-
105
- getVerificationMethodId(): string {
106
- // didwebvh-ts requires verification method to be a did:key: identifier
107
- // Extract the multibase key from the verification method
108
- const publicKeyMultibase = this.verificationMethod?.publicKeyMultibase;
109
- if (!publicKeyMultibase) {
110
- throw new Error('Verification method must have publicKeyMultibase');
111
- }
112
- // Return as did:key format which didwebvh-ts expects
113
- return `did:key:${publicKeyMultibase}`;
114
- }
115
- }
116
-
117
- export interface CreateWebVHOptions {
118
- domain: string;
119
- keyPair?: KeyPair;
120
- paths?: string[];
121
- portable?: boolean;
122
- outputDir?: string; // Directory to save the DID log (did.jsonl)
123
- externalSigner?: ExternalSigner; // External signer (e.g., Turnkey integration)
124
- externalVerifier?: ExternalVerifier; // External verifier
125
- verificationMethods?: VerificationMethod[]; // Pre-configured verification methods
126
- updateKeys?: string[]; // Pre-configured update keys (e.g., ["did:key:z6Mk..."])
127
- }
128
-
129
- export interface CreateWebVHResult {
130
- did: string;
131
- didDocument: DIDDocument;
132
- log: DIDLog;
133
- keyPair: KeyPair;
134
- logPath?: string; // Path where the DID log was saved
135
- }
136
-
137
- /**
138
- * WebVH DID Manager for creating and managing did:webvh identifiers
139
- */
140
- export class WebVHManager {
141
- private keyManager: KeyManager;
142
-
143
- constructor() {
144
- this.keyManager = new KeyManager();
145
- }
146
-
147
- /**
148
- * Creates a new did:webvh DID with proper cryptographic signing
149
- * @param options - Creation options including domain and optional key pair or external signer
150
- * @returns The created DID, document, log, and key pair (if generated)
151
- */
152
- async createDIDWebVH(options: CreateWebVHOptions): Promise<CreateWebVHResult> {
153
- const {
154
- domain,
155
- keyPair: providedKeyPair,
156
- paths = [],
157
- portable = false,
158
- outputDir,
159
- externalSigner,
160
- externalVerifier,
161
- verificationMethods: providedVerificationMethods,
162
- updateKeys: providedUpdateKeys
163
- } = options;
164
-
165
- // Validate path segments before creating DID to prevent directory traversal
166
- if (paths && paths.length > 0) {
167
- for (const segment of paths) {
168
- if (!this.isValidPathSegment(segment)) {
169
- throw new Error(`Invalid path segment in DID: "${segment}". Path segments cannot contain '.', '..', path separators, or be absolute paths.`);
170
- }
171
- }
172
- }
173
-
174
- // Dynamically import didwebvh-ts to avoid module resolution issues
175
- const mod = await import('didwebvh-ts') as unknown as {
176
- createDID: (options: Record<string, unknown>) => Promise<{
177
- did: string;
178
- doc: Record<string, unknown>;
179
- log: DIDLog;
180
- }>;
181
- prepareDataForSigning: (
182
- document: Record<string, unknown>,
183
- proof: Record<string, unknown>
184
- ) => Promise<Uint8Array>;
185
- };
186
- const { createDID, prepareDataForSigning } = mod;
187
-
188
- // Runtime validation of imported module
189
- if (typeof createDID !== 'function' || typeof prepareDataForSigning !== 'function') {
190
- throw new Error('Failed to load didwebvh-ts: invalid module exports');
191
- }
192
-
193
- let signer: Signer | ExternalSigner;
194
- let verifier: Verifier | ExternalVerifier;
195
- let keyPair: KeyPair | undefined;
196
- let verificationMethods: VerificationMethod[];
197
- let updateKeys: string[];
198
-
199
- // Use external signer if provided (e.g., Turnkey integration)
200
- if (externalSigner) {
201
- if (!providedVerificationMethods || providedVerificationMethods.length === 0) {
202
- throw new Error('verificationMethods are required when using externalSigner');
203
- }
204
- if (!providedUpdateKeys || providedUpdateKeys.length === 0) {
205
- throw new Error('updateKeys are required when using externalSigner');
206
- }
207
-
208
- signer = externalSigner;
209
- verifier = externalVerifier || externalSigner as any; // Use signer as verifier if not provided
210
- verificationMethods = providedVerificationMethods;
211
- updateKeys = providedUpdateKeys;
212
- keyPair = undefined; // No key pair when using external signer
213
- } else {
214
- // Generate or use provided key pair (Ed25519 for did:webvh)
215
- keyPair = providedKeyPair || await this.keyManager.generateKeyPair('Ed25519');
216
-
217
- // Create verification methods
218
- verificationMethods = [
219
- {
220
- type: 'Multikey',
221
- publicKeyMultibase: keyPair.publicKey,
222
- }
223
- ];
224
-
225
- // Create signer using our adapter
226
- const internalSigner = new OriginalsWebVHSigner(
227
- keyPair.privateKey,
228
- verificationMethods[0],
229
- prepareDataForSigning,
230
- { verificationMethod: verificationMethods[0] }
231
- );
232
-
233
- signer = internalSigner;
234
- verifier = internalSigner; // Use the same signer as verifier
235
- updateKeys = [`did:key:${keyPair.publicKey}`]; // Use did:key format for authorization
236
- }
237
-
238
- // Create the DID using didwebvh-ts
239
- const result = await createDID({
240
- domain,
241
- signer,
242
- verifier,
243
- updateKeys,
244
- verificationMethods,
245
- context: [
246
- 'https://www.w3.org/ns/did/v1',
247
- 'https://w3id.org/security/multikey/v1'
248
- ],
249
- paths,
250
- portable,
251
- authentication: ['#key-0'],
252
- assertionMethod: ['#key-0'],
253
- });
254
-
255
- // Validate the returned DID document
256
- if (!this.isDIDDocument(result.doc)) {
257
- throw new Error('Invalid DID document returned from createDID');
258
- }
259
-
260
- // Save the log to did.jsonl if output directory is provided
261
- let logPath: string | undefined;
262
- if (outputDir) {
263
- logPath = await this.saveDIDLog(result.did, result.log, outputDir);
264
- }
265
-
266
- return {
267
- did: result.did,
268
- didDocument: result.doc,
269
- log: result.log,
270
- keyPair: keyPair || { publicKey: '', privateKey: '' }, // Return empty keypair if using external signer
271
- logPath,
272
- };
273
- }
274
-
275
- /**
276
- * Validates a path segment to prevent directory traversal attacks
277
- * @param segment - Path segment to validate
278
- * @returns true if valid, false otherwise
279
- */
280
- private isValidPathSegment(segment: string): boolean {
281
- // Reject empty segments, dots, or segments with path separators
282
- if (!segment || segment === '.' || segment === '..') {
283
- return false;
284
- }
285
-
286
- // Reject segments containing path separators or other dangerous characters
287
- if (segment.includes('/') || segment.includes('\\') || segment.includes('\0')) {
288
- return false;
289
- }
290
-
291
- // Reject absolute paths (starting with / or drive letter on Windows)
292
- if (path.isAbsolute(segment)) {
293
- return false;
294
- }
295
-
296
- return true;
297
- }
298
-
299
- /**
300
- * Type guard to validate a DID document structure
301
- * @param doc - Object to validate
302
- * @returns true if the object is a valid DIDDocument
303
- */
304
- private isDIDDocument(doc: unknown): doc is DIDDocument {
305
- if (!doc || typeof doc !== 'object') {
306
- return false;
307
- }
308
-
309
- const d = doc as Record<string, unknown>;
310
-
311
- // Check required fields
312
- if (!Array.isArray(d['@context']) || d['@context'].length === 0) {
313
- return false;
314
- }
315
-
316
- if (typeof d.id !== 'string' || !d.id.startsWith('did:')) {
317
- return false;
318
- }
319
-
320
- return true;
321
- }
322
-
323
- /**
324
- * Saves the DID log to the appropriate did.jsonl path
325
- * @param did - The DID identifier
326
- * @param log - The DID log to save
327
- * @param baseDir - Base directory for saving (e.g., public/.well-known)
328
- * @returns The full path where the log was saved
329
- */
330
- async saveDIDLog(did: string, log: DIDLog, baseDir: string): Promise<string> {
331
- // Parse the DID to extract domain and path components
332
- // Format: did:webvh:domain[:port]:path1:path2...
333
- const didParts = did.split(':');
334
- if (didParts.length < 3 || didParts[0] !== 'did' || didParts[1] !== 'webvh') {
335
- throw new Error('Invalid did:webvh format');
336
- }
337
-
338
- // Extract path parts (everything after domain)
339
- const pathParts = didParts.slice(3);
340
-
341
- // Validate all path segments to prevent directory traversal
342
- for (const segment of pathParts) {
343
- if (!this.isValidPathSegment(segment)) {
344
- throw new Error(`Invalid path segment in DID: "${segment}". Path segments cannot contain '.', '..', path separators, or be absolute paths.`);
345
- }
346
- }
347
-
348
- // Extract and sanitize domain for filesystem safety
349
- const rawDomain = decodeURIComponent(didParts[2]);
350
- // Normalize: lowercase and replace any characters not in [a-z0-9._-] with '_'
351
- const safeDomain = rawDomain
352
- .toLowerCase()
353
- .replace(/[^a-z0-9._-]/g, '_');
354
-
355
- // Validate the sanitized domain (reject '..' and other dangerous patterns)
356
- if (!this.isValidPathSegment(safeDomain)) {
357
- throw new Error(`Invalid domain segment in DID: "${rawDomain}"`);
358
- }
359
-
360
- // Construct the file path with domain isolation
361
- // For did:webvh:example.com:user:alice -> baseDir/did/example.com/user/alice/did.jsonl
362
- // For did:webvh:example.com:alice -> baseDir/did/example.com/alice/did.jsonl
363
- const segments = [safeDomain, ...pathParts];
364
- const didPath = path.join(baseDir, 'did', ...segments, 'did.jsonl');
365
-
366
- // Verify the resolved path is still within baseDir (defense in depth)
367
- const resolvedBaseDir = path.resolve(baseDir);
368
- const resolvedPath = path.resolve(didPath);
369
- const relativePath = path.relative(resolvedBaseDir, resolvedPath);
370
- if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) {
371
- throw new Error('Invalid DID path: resolved path is outside base directory');
372
- }
373
-
374
- // Create directories if they don't exist
375
- const dirPath = path.dirname(didPath);
376
- await fs.promises.mkdir(dirPath, { recursive: true });
377
-
378
- // Convert log to JSONL format (one JSON object per line)
379
- const jsonlContent = log.map((entry: DIDLogEntry) => JSON.stringify(entry)).join('\n');
380
-
381
- // Write the log file
382
- await fs.promises.writeFile(didPath, jsonlContent, 'utf8');
383
-
384
- return didPath;
385
- }
386
-
387
- /**
388
- * Loads a DID log from a did.jsonl file
389
- * @param logPath - Path to the did.jsonl file
390
- * @returns The loaded DID log
391
- */
392
- async loadDIDLog(logPath: string): Promise<DIDLog> {
393
- const content = await fs.promises.readFile(logPath, 'utf8');
394
- const lines = content.trim().split('\n');
395
- return lines.map(line => JSON.parse(line));
396
- }
397
-
398
- /**
399
- * Updates a DID:WebVH document
400
- * @param did - The DID to update
401
- * @param currentLog - The current DID log
402
- * @param updates - Updates to apply to the DID document
403
- * @param signer - The signer to use (must be authorized in updateKeys)
404
- * @param verifier - Optional verifier
405
- * @param outputDir - Optional directory to save the updated log
406
- * @returns Updated DID document and log
407
- */
408
- async updateDIDWebVH(options: {
409
- did: string;
410
- currentLog: DIDLog;
411
- updates: Partial<DIDDocument>;
412
- signer: ExternalSigner | { privateKey: string; publicKey: string };
413
- verifier?: ExternalVerifier;
414
- outputDir?: string;
415
- }): Promise<{ didDocument: DIDDocument; log: DIDLog; logPath?: string }> {
416
- const { did, currentLog, updates, signer: providedSigner, verifier: providedVerifier, outputDir } = options;
417
-
418
- // Dynamically import didwebvh-ts
419
- const mod = await import('didwebvh-ts') as unknown as {
420
- updateDID: (options: Record<string, unknown>) => Promise<{
421
- doc: Record<string, unknown>;
422
- log: DIDLog;
423
- }>;
424
- prepareDataForSigning: (
425
- document: Record<string, unknown>,
426
- proof: Record<string, unknown>
427
- ) => Promise<Uint8Array>;
428
- };
429
- const { updateDID, prepareDataForSigning } = mod;
430
-
431
- if (typeof updateDID !== 'function') {
432
- throw new Error('Failed to load didwebvh-ts: invalid module exports');
433
- }
434
-
435
- let signer: Signer | ExternalSigner;
436
- let verifier: Verifier | ExternalVerifier | undefined;
437
-
438
- // Check if using external signer or internal keypair
439
- if ('sign' in providedSigner && 'getVerificationMethodId' in providedSigner) {
440
- // External signer
441
- signer = providedSigner as ExternalSigner;
442
- verifier = providedVerifier;
443
- } else {
444
- // Internal signer with keypair
445
- const keyPair = providedSigner as { privateKey: string; publicKey: string };
446
- const verificationMethod: VerificationMethod = {
447
- type: 'Multikey',
448
- publicKeyMultibase: keyPair.publicKey,
449
- };
450
-
451
- const internalSigner = new OriginalsWebVHSigner(
452
- keyPair.privateKey,
453
- verificationMethod,
454
- prepareDataForSigning,
455
- { verificationMethod }
456
- );
457
-
458
- signer = internalSigner;
459
- verifier = internalSigner;
460
- }
461
-
462
- // Get the current document from the log
463
- const currentEntry = currentLog[currentLog.length - 1];
464
- const currentDoc = currentEntry.state as unknown as DIDDocument;
465
-
466
- // Merge updates with current document
467
- const updatedDoc = {
468
- ...currentDoc,
469
- ...updates,
470
- id: did, // Ensure ID doesn't change
471
- };
472
-
473
- // Update the DID using didwebvh-ts
474
- const result = await updateDID({
475
- log: currentLog,
476
- doc: updatedDoc,
477
- signer,
478
- verifier,
479
- });
480
-
481
- // Validate the returned DID document
482
- if (!this.isDIDDocument(result.doc)) {
483
- throw new Error('Invalid DID document returned from updateDID');
484
- }
485
-
486
- // Save the updated log if output directory is provided
487
- let logPath: string | undefined;
488
- if (outputDir) {
489
- logPath = await this.saveDIDLog(did, result.log, outputDir);
490
- }
491
-
492
- return {
493
- didDocument: result.doc,
494
- log: result.log,
495
- logPath,
496
- };
497
- }
498
- }
@@ -1,59 +0,0 @@
1
- import { DIDDocument, VerificationMethod } from '../types/did';
2
- import { multikey, MultikeyType } from '../crypto/Multikey';
3
- import { validateSatoshiNumber } from '../utils/satoshi-validation';
4
-
5
- export type BitcoinNetwork = 'mainnet' | 'regtest' | 'signet';
6
-
7
- interface CreateBtcoDidDocumentParams {
8
- publicKey: Uint8Array;
9
- keyType: MultikeyType;
10
- controller?: string;
11
- }
12
-
13
- function getDidPrefix(network: BitcoinNetwork): string {
14
- if (network === 'mainnet') return 'did:btco';
15
- if (network === 'signet') return 'did:btco:sig';
16
- if (network === 'regtest') return 'did:btco:reg';
17
- throw new Error(`Unsupported Bitcoin network: ${network}`);
18
- }
19
-
20
- function buildVerificationMethod(did: string, params: CreateBtcoDidDocumentParams): VerificationMethod {
21
- const fragment = '#0';
22
- const id = `${did}${fragment}`;
23
- const controller = params.controller ?? did;
24
- return {
25
- id,
26
- type: 'Multikey',
27
- controller,
28
- publicKeyMultibase: multikey.encodePublicKey(params.publicKey, params.keyType)
29
- };
30
- }
31
-
32
- export function createBtcoDidDocument(
33
- satNumber: number | string,
34
- network: BitcoinNetwork,
35
- params: CreateBtcoDidDocumentParams
36
- ): DIDDocument {
37
- // Validate satNumber parameter at entry
38
- const validation = validateSatoshiNumber(satNumber);
39
- if (!validation.valid) {
40
- throw new Error(`Invalid satoshi number: ${validation.error}`);
41
- }
42
-
43
- const did = `${getDidPrefix(network)}:${String(satNumber)}`;
44
- const vm = buildVerificationMethod(did, params);
45
-
46
- const document: DIDDocument = {
47
- '@context': [
48
- 'https://www.w3.org/ns/did/v1',
49
- 'https://w3id.org/security/multikey/v1'
50
- ],
51
- id: did,
52
- verificationMethod: [vm],
53
- authentication: [vm.id],
54
- assertionMethod: [vm.id]
55
- };
56
-
57
- return document;
58
- }
59
-
@@ -1,68 +0,0 @@
1
- import type { ResourceProviderLike } from '../BtcoDidResolver';
2
- import { OrdinalsClient } from '../../bitcoin/OrdinalsClient';
3
-
4
- export interface OrdinalsClientProviderConfig {
5
- baseUrl: string;
6
- fetchFn?: (url: string, init?: RequestInit) => Promise<Response>;
7
- timeout?: number;
8
- }
9
-
10
- export class OrdinalsClientProviderAdapter implements ResourceProviderLike {
11
- private readonly config: OrdinalsClientProviderConfig;
12
-
13
- constructor(private client: OrdinalsClient, configOrBaseUrl: string | OrdinalsClientProviderConfig) {
14
- if (typeof configOrBaseUrl === 'string') {
15
- this.config = { baseUrl: configOrBaseUrl };
16
- } else {
17
- this.config = configOrBaseUrl;
18
- }
19
- }
20
-
21
- async getSatInfo(satNumber: string): Promise<{ inscription_ids: string[] }> {
22
- return this.client.getSatInfo(satNumber);
23
- }
24
-
25
- async resolveInscription(inscriptionId: string): Promise<{ id: string; sat: number; content_type: string; content_url: string }> {
26
- const base = (this.config.baseUrl || '').replace(/\/$/, '');
27
- if (!base) {
28
- throw new Error('OrdinalsClientProviderAdapter requires a baseUrl');
29
- }
30
-
31
- try {
32
- // Use configurable fetch function or default to global fetch
33
- const fetchFn = this.config.fetchFn || fetch;
34
- const timeout = this.config.timeout || 10000; // 10 second default timeout
35
-
36
- const fetchOptions: RequestInit = {
37
- headers: { 'Accept': 'application/json' },
38
- signal: AbortSignal.timeout(timeout)
39
- };
40
-
41
- const res = await fetchFn(`${base}/inscription/${inscriptionId}`, fetchOptions);
42
- if (!res.ok) {
43
- // Log warning but don't throw - allow graceful degradation
44
- console.warn(`Failed to resolve inscription ${inscriptionId}: HTTP ${res.status}`);
45
- throw new Error(`HTTP ${res.status}: ${res.statusText}`);
46
- }
47
-
48
- const info: any = await res.json();
49
- return {
50
- id: info.inscription_id || inscriptionId,
51
- sat: typeof info.sat === 'number' ? info.sat : Number(info.sat || 0),
52
- content_type: info.content_type || 'text/plain',
53
- content_url: info.content_url || `${base}/content/${inscriptionId}`
54
- };
55
- } catch (err: any) {
56
- // Log error for debugging but re-throw for caller to handle
57
- console.warn(`Failed to resolve inscription ${inscriptionId}:`, err.message || String(err));
58
- throw new Error(`Failed to resolve inscription: ${inscriptionId}`);
59
- }
60
- }
61
-
62
- async getMetadata(inscriptionId: string): Promise<any> {
63
- return this.client.getMetadata(inscriptionId);
64
- }
65
- }
66
-
67
- export default OrdinalsClientProviderAdapter;
68
-