@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.
- package/dist/utils/hash.js +1 -0
- package/package.json +6 -5
- package/src/adapters/FeeOracleMock.ts +9 -0
- package/src/adapters/index.ts +5 -0
- package/src/adapters/providers/OrdHttpProvider.ts +126 -0
- package/src/adapters/providers/OrdMockProvider.ts +101 -0
- package/src/adapters/types.ts +66 -0
- package/src/bitcoin/BitcoinManager.ts +329 -0
- package/src/bitcoin/BroadcastClient.ts +54 -0
- package/src/bitcoin/OrdinalsClient.ts +120 -0
- package/src/bitcoin/PSBTBuilder.ts +106 -0
- package/src/bitcoin/fee-calculation.ts +38 -0
- package/src/bitcoin/providers/OrdNodeProvider.ts +92 -0
- package/src/bitcoin/providers/OrdinalsProvider.ts +56 -0
- package/src/bitcoin/providers/types.ts +59 -0
- package/src/bitcoin/transactions/commit.ts +465 -0
- package/src/bitcoin/transactions/index.ts +13 -0
- package/src/bitcoin/transfer.ts +43 -0
- package/src/bitcoin/utxo-selection.ts +322 -0
- package/src/bitcoin/utxo.ts +113 -0
- package/src/cel/ExternalReferenceManager.ts +87 -0
- package/src/cel/OriginalsCel.ts +460 -0
- package/src/cel/algorithms/createEventLog.ts +68 -0
- package/src/cel/algorithms/deactivateEventLog.ts +109 -0
- package/src/cel/algorithms/index.ts +11 -0
- package/src/cel/algorithms/updateEventLog.ts +99 -0
- package/src/cel/algorithms/verifyEventLog.ts +306 -0
- package/src/cel/algorithms/witnessEvent.ts +87 -0
- package/src/cel/cli/create.ts +330 -0
- package/src/cel/cli/index.ts +383 -0
- package/src/cel/cli/inspect.ts +549 -0
- package/src/cel/cli/migrate.ts +473 -0
- package/src/cel/cli/verify.ts +249 -0
- package/src/cel/hash.ts +71 -0
- package/src/cel/index.ts +16 -0
- package/src/cel/layers/BtcoCelManager.ts +408 -0
- package/src/cel/layers/PeerCelManager.ts +371 -0
- package/src/cel/layers/WebVHCelManager.ts +361 -0
- package/src/cel/layers/index.ts +27 -0
- package/src/cel/serialization/cbor.ts +189 -0
- package/src/cel/serialization/index.ts +10 -0
- package/src/cel/serialization/json.ts +209 -0
- package/src/cel/types.ts +160 -0
- package/src/cel/witnesses/BitcoinWitness.ts +184 -0
- package/src/cel/witnesses/HttpWitness.ts +241 -0
- package/src/cel/witnesses/WitnessService.ts +51 -0
- package/src/cel/witnesses/index.ts +11 -0
- package/src/contexts/credentials-v1.json +237 -0
- package/src/contexts/credentials-v2-examples.json +5 -0
- package/src/contexts/credentials-v2.json +340 -0
- package/src/contexts/credentials.json +237 -0
- package/src/contexts/data-integrity-v2.json +81 -0
- package/src/contexts/dids.json +58 -0
- package/src/contexts/ed255192020.json +93 -0
- package/src/contexts/ordinals-plus.json +23 -0
- package/src/contexts/originals.json +22 -0
- package/src/core/OriginalsSDK.ts +420 -0
- package/src/crypto/Multikey.ts +194 -0
- package/src/crypto/Signer.ts +262 -0
- package/src/crypto/noble-init.ts +138 -0
- package/src/did/BtcoDidResolver.ts +231 -0
- package/src/did/DIDManager.ts +705 -0
- package/src/did/Ed25519Verifier.ts +68 -0
- package/src/did/KeyManager.ts +239 -0
- package/src/did/WebVHManager.ts +499 -0
- package/src/did/createBtcoDidDocument.ts +60 -0
- package/src/did/providers/OrdinalsClientProviderAdapter.ts +68 -0
- package/src/events/EventEmitter.ts +222 -0
- package/src/events/index.ts +19 -0
- package/src/events/types.ts +331 -0
- package/src/examples/basic-usage.ts +78 -0
- package/src/examples/create-module-original.ts +435 -0
- package/src/examples/full-lifecycle-flow.ts +514 -0
- package/src/examples/run.ts +60 -0
- package/src/index.ts +204 -0
- package/src/kinds/KindRegistry.ts +320 -0
- package/src/kinds/index.ts +74 -0
- package/src/kinds/types.ts +470 -0
- package/src/kinds/validators/AgentValidator.ts +257 -0
- package/src/kinds/validators/AppValidator.ts +211 -0
- package/src/kinds/validators/DatasetValidator.ts +242 -0
- package/src/kinds/validators/DocumentValidator.ts +311 -0
- package/src/kinds/validators/MediaValidator.ts +269 -0
- package/src/kinds/validators/ModuleValidator.ts +225 -0
- package/src/kinds/validators/base.ts +276 -0
- package/src/kinds/validators/index.ts +12 -0
- package/src/lifecycle/BatchOperations.ts +381 -0
- package/src/lifecycle/LifecycleManager.ts +2156 -0
- package/src/lifecycle/OriginalsAsset.ts +524 -0
- package/src/lifecycle/ProvenanceQuery.ts +280 -0
- package/src/lifecycle/ResourceVersioning.ts +163 -0
- package/src/migration/MigrationManager.ts +587 -0
- package/src/migration/audit/AuditLogger.ts +176 -0
- package/src/migration/checkpoint/CheckpointManager.ts +112 -0
- package/src/migration/checkpoint/CheckpointStorage.ts +101 -0
- package/src/migration/index.ts +33 -0
- package/src/migration/operations/BaseMigration.ts +126 -0
- package/src/migration/operations/PeerToBtcoMigration.ts +105 -0
- package/src/migration/operations/PeerToWebvhMigration.ts +62 -0
- package/src/migration/operations/WebvhToBtcoMigration.ts +105 -0
- package/src/migration/rollback/RollbackManager.ts +170 -0
- package/src/migration/state/StateMachine.ts +92 -0
- package/src/migration/state/StateTracker.ts +156 -0
- package/src/migration/types.ts +356 -0
- package/src/migration/validation/BitcoinValidator.ts +107 -0
- package/src/migration/validation/CredentialValidator.ts +62 -0
- package/src/migration/validation/DIDCompatibilityValidator.ts +151 -0
- package/src/migration/validation/LifecycleValidator.ts +64 -0
- package/src/migration/validation/StorageValidator.ts +79 -0
- package/src/migration/validation/ValidationPipeline.ts +213 -0
- package/src/resources/ResourceManager.ts +655 -0
- package/src/resources/index.ts +21 -0
- package/src/resources/types.ts +202 -0
- package/src/storage/LocalStorageAdapter.ts +64 -0
- package/src/storage/MemoryStorageAdapter.ts +29 -0
- package/src/storage/StorageAdapter.ts +25 -0
- package/src/storage/index.ts +3 -0
- package/src/types/bitcoin.ts +98 -0
- package/src/types/common.ts +92 -0
- package/src/types/credentials.ts +89 -0
- package/src/types/did.ts +31 -0
- package/src/types/external-shims.d.ts +53 -0
- package/src/types/index.ts +7 -0
- package/src/types/network.ts +178 -0
- package/src/utils/EventLogger.ts +298 -0
- package/src/utils/Logger.ts +324 -0
- package/src/utils/MetricsCollector.ts +358 -0
- package/src/utils/bitcoin-address.ts +132 -0
- package/src/utils/cbor.ts +31 -0
- package/src/utils/encoding.ts +135 -0
- package/src/utils/hash.ts +12 -0
- package/src/utils/retry.ts +46 -0
- package/src/utils/satoshi-validation.ts +196 -0
- package/src/utils/serialization.ts +102 -0
- package/src/utils/telemetry.ts +44 -0
- package/src/utils/validation.ts +123 -0
- package/src/vc/CredentialManager.ts +955 -0
- package/src/vc/Issuer.ts +105 -0
- package/src/vc/Verifier.ts +54 -0
- package/src/vc/cryptosuites/bbs.ts +253 -0
- package/src/vc/cryptosuites/bbsSimple.ts +21 -0
- package/src/vc/cryptosuites/eddsa.ts +99 -0
- package/src/vc/documentLoader.ts +81 -0
- package/src/vc/proofs/data-integrity.ts +33 -0
- package/src/vc/utils/jsonld.ts +18 -0
|
@@ -0,0 +1,499 @@
|
|
|
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
|
+
|
|
209
|
+
signer = externalSigner;
|
|
210
|
+
verifier = externalVerifier || (externalSigner as unknown as ExternalVerifier); // Use signer as verifier if not provided
|
|
211
|
+
verificationMethods = providedVerificationMethods;
|
|
212
|
+
updateKeys = providedUpdateKeys;
|
|
213
|
+
keyPair = undefined; // No key pair when using external signer
|
|
214
|
+
} else {
|
|
215
|
+
// Generate or use provided key pair (Ed25519 for did:webvh)
|
|
216
|
+
keyPair = providedKeyPair || await this.keyManager.generateKeyPair('Ed25519');
|
|
217
|
+
|
|
218
|
+
// Create verification methods
|
|
219
|
+
verificationMethods = [
|
|
220
|
+
{
|
|
221
|
+
type: 'Multikey',
|
|
222
|
+
publicKeyMultibase: keyPair.publicKey,
|
|
223
|
+
}
|
|
224
|
+
];
|
|
225
|
+
|
|
226
|
+
// Create signer using our adapter
|
|
227
|
+
const internalSigner = new OriginalsWebVHSigner(
|
|
228
|
+
keyPair.privateKey,
|
|
229
|
+
verificationMethods[0],
|
|
230
|
+
prepareDataForSigning,
|
|
231
|
+
{ verificationMethod: verificationMethods[0] }
|
|
232
|
+
);
|
|
233
|
+
|
|
234
|
+
signer = internalSigner;
|
|
235
|
+
verifier = internalSigner; // Use the same signer as verifier
|
|
236
|
+
updateKeys = [`did:key:${keyPair.publicKey}`]; // Use did:key format for authorization
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Create the DID using didwebvh-ts
|
|
240
|
+
const result = await createDID({
|
|
241
|
+
domain,
|
|
242
|
+
signer,
|
|
243
|
+
verifier,
|
|
244
|
+
updateKeys,
|
|
245
|
+
verificationMethods,
|
|
246
|
+
context: [
|
|
247
|
+
'https://www.w3.org/ns/did/v1',
|
|
248
|
+
'https://w3id.org/security/multikey/v1'
|
|
249
|
+
],
|
|
250
|
+
paths,
|
|
251
|
+
portable,
|
|
252
|
+
authentication: ['#key-0'],
|
|
253
|
+
assertionMethod: ['#key-0'],
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
// Validate the returned DID document
|
|
257
|
+
if (!this.isDIDDocument(result.doc)) {
|
|
258
|
+
throw new Error('Invalid DID document returned from createDID');
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Save the log to did.jsonl if output directory is provided
|
|
262
|
+
let logPath: string | undefined;
|
|
263
|
+
if (outputDir) {
|
|
264
|
+
logPath = await this.saveDIDLog(result.did, result.log, outputDir);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return {
|
|
268
|
+
did: result.did,
|
|
269
|
+
didDocument: result.doc,
|
|
270
|
+
log: result.log,
|
|
271
|
+
keyPair: keyPair || { publicKey: '', privateKey: '' }, // Return empty keypair if using external signer
|
|
272
|
+
logPath,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Validates a path segment to prevent directory traversal attacks
|
|
278
|
+
* @param segment - Path segment to validate
|
|
279
|
+
* @returns true if valid, false otherwise
|
|
280
|
+
*/
|
|
281
|
+
private isValidPathSegment(segment: string): boolean {
|
|
282
|
+
// Reject empty segments, dots, or segments with path separators
|
|
283
|
+
if (!segment || segment === '.' || segment === '..') {
|
|
284
|
+
return false;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Reject segments containing path separators or other dangerous characters
|
|
288
|
+
if (segment.includes('/') || segment.includes('\\') || segment.includes('\0')) {
|
|
289
|
+
return false;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Reject absolute paths (starting with / or drive letter on Windows)
|
|
293
|
+
if (path.isAbsolute(segment)) {
|
|
294
|
+
return false;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return true;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Type guard to validate a DID document structure
|
|
302
|
+
* @param doc - Object to validate
|
|
303
|
+
* @returns true if the object is a valid DIDDocument
|
|
304
|
+
*/
|
|
305
|
+
private isDIDDocument(doc: unknown): doc is DIDDocument {
|
|
306
|
+
if (!doc || typeof doc !== 'object') {
|
|
307
|
+
return false;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const d = doc as Record<string, unknown>;
|
|
311
|
+
|
|
312
|
+
// Check required fields
|
|
313
|
+
if (!Array.isArray(d['@context']) || d['@context'].length === 0) {
|
|
314
|
+
return false;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (typeof d.id !== 'string' || !d.id.startsWith('did:')) {
|
|
318
|
+
return false;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return true;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Saves the DID log to the appropriate did.jsonl path
|
|
326
|
+
* @param did - The DID identifier
|
|
327
|
+
* @param log - The DID log to save
|
|
328
|
+
* @param baseDir - Base directory for saving (e.g., public/.well-known)
|
|
329
|
+
* @returns The full path where the log was saved
|
|
330
|
+
*/
|
|
331
|
+
async saveDIDLog(did: string, log: DIDLog, baseDir: string): Promise<string> {
|
|
332
|
+
// Parse the DID to extract domain and path components
|
|
333
|
+
// Format: did:webvh:domain[:port]:path1:path2...
|
|
334
|
+
const didParts = did.split(':');
|
|
335
|
+
if (didParts.length < 3 || didParts[0] !== 'did' || didParts[1] !== 'webvh') {
|
|
336
|
+
throw new Error('Invalid did:webvh format');
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Extract path parts (everything after domain)
|
|
340
|
+
const pathParts = didParts.slice(3);
|
|
341
|
+
|
|
342
|
+
// Validate all path segments to prevent directory traversal
|
|
343
|
+
for (const segment of pathParts) {
|
|
344
|
+
if (!this.isValidPathSegment(segment)) {
|
|
345
|
+
throw new Error(`Invalid path segment in DID: "${segment}". Path segments cannot contain '.', '..', path separators, or be absolute paths.`);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// Extract and sanitize domain for filesystem safety
|
|
350
|
+
const rawDomain = decodeURIComponent(didParts[2]);
|
|
351
|
+
// Normalize: lowercase and replace any characters not in [a-z0-9._-] with '_'
|
|
352
|
+
const safeDomain = rawDomain
|
|
353
|
+
.toLowerCase()
|
|
354
|
+
.replace(/[^a-z0-9._-]/g, '_');
|
|
355
|
+
|
|
356
|
+
// Validate the sanitized domain (reject '..' and other dangerous patterns)
|
|
357
|
+
if (!this.isValidPathSegment(safeDomain)) {
|
|
358
|
+
throw new Error(`Invalid domain segment in DID: "${rawDomain}"`);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// Construct the file path with domain isolation
|
|
362
|
+
// For did:webvh:example.com:user:alice -> baseDir/did/example.com/user/alice/did.jsonl
|
|
363
|
+
// For did:webvh:example.com:alice -> baseDir/did/example.com/alice/did.jsonl
|
|
364
|
+
const segments = [safeDomain, ...pathParts];
|
|
365
|
+
const didPath = path.join(baseDir, 'did', ...segments, 'did.jsonl');
|
|
366
|
+
|
|
367
|
+
// Verify the resolved path is still within baseDir (defense in depth)
|
|
368
|
+
const resolvedBaseDir = path.resolve(baseDir);
|
|
369
|
+
const resolvedPath = path.resolve(didPath);
|
|
370
|
+
const relativePath = path.relative(resolvedBaseDir, resolvedPath);
|
|
371
|
+
if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) {
|
|
372
|
+
throw new Error('Invalid DID path: resolved path is outside base directory');
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// Create directories if they don't exist
|
|
376
|
+
const dirPath = path.dirname(didPath);
|
|
377
|
+
await fs.promises.mkdir(dirPath, { recursive: true });
|
|
378
|
+
|
|
379
|
+
// Convert log to JSONL format (one JSON object per line)
|
|
380
|
+
const jsonlContent = log.map((entry: DIDLogEntry) => JSON.stringify(entry)).join('\n');
|
|
381
|
+
|
|
382
|
+
// Write the log file
|
|
383
|
+
await fs.promises.writeFile(didPath, jsonlContent, 'utf8');
|
|
384
|
+
|
|
385
|
+
return didPath;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Loads a DID log from a did.jsonl file
|
|
390
|
+
* @param logPath - Path to the did.jsonl file
|
|
391
|
+
* @returns The loaded DID log
|
|
392
|
+
*/
|
|
393
|
+
async loadDIDLog(logPath: string): Promise<DIDLog> {
|
|
394
|
+
const content = await fs.promises.readFile(logPath, 'utf8');
|
|
395
|
+
const lines = content.trim().split('\n');
|
|
396
|
+
return lines.map(line => JSON.parse(line) as DIDLogEntry);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Updates a DID:WebVH document
|
|
401
|
+
* @param did - The DID to update
|
|
402
|
+
* @param currentLog - The current DID log
|
|
403
|
+
* @param updates - Updates to apply to the DID document
|
|
404
|
+
* @param signer - The signer to use (must be authorized in updateKeys)
|
|
405
|
+
* @param verifier - Optional verifier
|
|
406
|
+
* @param outputDir - Optional directory to save the updated log
|
|
407
|
+
* @returns Updated DID document and log
|
|
408
|
+
*/
|
|
409
|
+
async updateDIDWebVH(options: {
|
|
410
|
+
did: string;
|
|
411
|
+
currentLog: DIDLog;
|
|
412
|
+
updates: Partial<DIDDocument>;
|
|
413
|
+
signer: ExternalSigner | { privateKey: string; publicKey: string };
|
|
414
|
+
verifier?: ExternalVerifier;
|
|
415
|
+
outputDir?: string;
|
|
416
|
+
}): Promise<{ didDocument: DIDDocument; log: DIDLog; logPath?: string }> {
|
|
417
|
+
const { did, currentLog, updates, signer: providedSigner, verifier: providedVerifier, outputDir } = options;
|
|
418
|
+
|
|
419
|
+
// Dynamically import didwebvh-ts
|
|
420
|
+
const mod = await import('didwebvh-ts') as unknown as {
|
|
421
|
+
updateDID: (options: Record<string, unknown>) => Promise<{
|
|
422
|
+
doc: Record<string, unknown>;
|
|
423
|
+
log: DIDLog;
|
|
424
|
+
}>;
|
|
425
|
+
prepareDataForSigning: (
|
|
426
|
+
document: Record<string, unknown>,
|
|
427
|
+
proof: Record<string, unknown>
|
|
428
|
+
) => Promise<Uint8Array>;
|
|
429
|
+
};
|
|
430
|
+
const { updateDID, prepareDataForSigning } = mod;
|
|
431
|
+
|
|
432
|
+
if (typeof updateDID !== 'function') {
|
|
433
|
+
throw new Error('Failed to load didwebvh-ts: invalid module exports');
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
let signer: Signer | ExternalSigner;
|
|
437
|
+
let verifier: Verifier | ExternalVerifier | undefined;
|
|
438
|
+
|
|
439
|
+
// Check if using external signer or internal keypair
|
|
440
|
+
if ('sign' in providedSigner && 'getVerificationMethodId' in providedSigner) {
|
|
441
|
+
// External signer
|
|
442
|
+
signer = providedSigner;
|
|
443
|
+
verifier = providedVerifier;
|
|
444
|
+
} else {
|
|
445
|
+
// Internal signer with keypair
|
|
446
|
+
const keyPair = providedSigner;
|
|
447
|
+
const verificationMethod: VerificationMethod = {
|
|
448
|
+
type: 'Multikey',
|
|
449
|
+
publicKeyMultibase: keyPair.publicKey,
|
|
450
|
+
};
|
|
451
|
+
|
|
452
|
+
const internalSigner = new OriginalsWebVHSigner(
|
|
453
|
+
keyPair.privateKey,
|
|
454
|
+
verificationMethod,
|
|
455
|
+
prepareDataForSigning,
|
|
456
|
+
{ verificationMethod }
|
|
457
|
+
);
|
|
458
|
+
|
|
459
|
+
signer = internalSigner;
|
|
460
|
+
verifier = internalSigner;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// Get the current document from the log
|
|
464
|
+
const currentEntry = currentLog[currentLog.length - 1];
|
|
465
|
+
const currentDoc = currentEntry.state as unknown as DIDDocument;
|
|
466
|
+
|
|
467
|
+
// Merge updates with current document
|
|
468
|
+
const updatedDoc = {
|
|
469
|
+
...currentDoc,
|
|
470
|
+
...updates,
|
|
471
|
+
id: did, // Ensure ID doesn't change
|
|
472
|
+
};
|
|
473
|
+
|
|
474
|
+
// Update the DID using didwebvh-ts
|
|
475
|
+
const result = await updateDID({
|
|
476
|
+
log: currentLog,
|
|
477
|
+
doc: updatedDoc,
|
|
478
|
+
signer,
|
|
479
|
+
verifier: verifier || undefined,
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
// Validate the returned DID document
|
|
483
|
+
if (!this.isDIDDocument(result.doc)) {
|
|
484
|
+
throw new Error('Invalid DID document returned from updateDID');
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// Save the updated log if output directory is provided
|
|
488
|
+
let logPath: string | undefined;
|
|
489
|
+
if (outputDir) {
|
|
490
|
+
logPath = await this.saveDIDLog(did, result.log, outputDir);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
return {
|
|
494
|
+
didDocument: result.doc,
|
|
495
|
+
log: result.log,
|
|
496
|
+
logPath,
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
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
|
+
const _exhaustiveCheck: never = network;
|
|
18
|
+
throw new Error(`Unsupported Bitcoin network: ${String(_exhaustiveCheck)}`);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function buildVerificationMethod(did: string, params: CreateBtcoDidDocumentParams): VerificationMethod {
|
|
22
|
+
const fragment = '#0';
|
|
23
|
+
const id = `${did}${fragment}`;
|
|
24
|
+
const controller = params.controller ?? did;
|
|
25
|
+
return {
|
|
26
|
+
id,
|
|
27
|
+
type: 'Multikey',
|
|
28
|
+
controller,
|
|
29
|
+
publicKeyMultibase: multikey.encodePublicKey(params.publicKey, params.keyType)
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function createBtcoDidDocument(
|
|
34
|
+
satNumber: number | string,
|
|
35
|
+
network: BitcoinNetwork,
|
|
36
|
+
params: CreateBtcoDidDocumentParams
|
|
37
|
+
): DIDDocument {
|
|
38
|
+
// Validate satNumber parameter at entry
|
|
39
|
+
const validation = validateSatoshiNumber(satNumber);
|
|
40
|
+
if (!validation.valid) {
|
|
41
|
+
throw new Error(`Invalid satoshi number: ${validation.error}`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const did = `${getDidPrefix(network)}:${String(satNumber)}`;
|
|
45
|
+
const vm = buildVerificationMethod(did, params);
|
|
46
|
+
|
|
47
|
+
const document: DIDDocument = {
|
|
48
|
+
'@context': [
|
|
49
|
+
'https://www.w3.org/ns/did/v1',
|
|
50
|
+
'https://w3id.org/security/multikey/v1'
|
|
51
|
+
],
|
|
52
|
+
id: did,
|
|
53
|
+
verificationMethod: [vm],
|
|
54
|
+
authentication: [vm.id],
|
|
55
|
+
assertionMethod: [vm.id]
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
return document;
|
|
59
|
+
}
|
|
60
|
+
|
|
@@ -0,0 +1,68 @@
|
|
|
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
|
+
|