@originals/sdk 1.8.1 → 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,194 @@
1
+ import { base58 } from '@scure/base';
2
+
3
+ // Multicodec headers (varints) for supported key types
4
+ export const MULTICODEC_ED25519_PUB_HEADER = new Uint8Array([0xed, 0x01]);
5
+ export const MULTICODEC_ED25519_PRIV_HEADER = new Uint8Array([0x80, 0x26]);
6
+ export const MULTICODEC_SECP256K1_PUB_HEADER = new Uint8Array([0xe7, 0x01]);
7
+ export const MULTICODEC_SECP256K1_PRIV_HEADER = new Uint8Array([0x13, 0x01]);
8
+ export const MULTICODEC_BLS12381_G2_PUB_HEADER = new Uint8Array([0xeb, 0x01]);
9
+ export const MULTICODEC_BLS12381_G2_PRIV_HEADER = new Uint8Array([0x82, 0x26]);
10
+ export const MULTICODEC_P256_PUB_HEADER = new Uint8Array([0x80, 0x24]);
11
+ export const MULTICODEC_P256_PRIV_HEADER = new Uint8Array([0x81, 0x26]);
12
+
13
+ export type MultikeyType = 'Ed25519' | 'Secp256k1' | 'Bls12381G2' | 'P256';
14
+
15
+ function concatBytes(a: Uint8Array, b: Uint8Array): Uint8Array {
16
+ const out = new Uint8Array(a.length + b.length);
17
+ out.set(a, 0);
18
+ out.set(b, a.length);
19
+ return out;
20
+ }
21
+
22
+ /**
23
+ * Validates that a key string uses proper multikey format.
24
+ * @param key - The multibase-encoded key string to validate
25
+ * @param expectedType - The expected key type (e.g., 'Ed25519', 'Secp256k1')
26
+ * @param isPrivate - Whether this is a private key (true) or public key (false)
27
+ * @throws Error with descriptive message if validation fails
28
+ */
29
+ export function validateMultikeyFormat(
30
+ key: string,
31
+ expectedType: MultikeyType,
32
+ isPrivate: boolean
33
+ ): void {
34
+ // Validate multibase prefix
35
+ if (!key || typeof key !== 'string') {
36
+ throw new Error('Invalid multibase key format. Key must be a non-empty string.');
37
+ }
38
+
39
+ if (key[0] !== 'z') {
40
+ throw new Error(
41
+ 'Invalid multibase key format. Keys must use z-base58btc encoding (prefix "z").'
42
+ );
43
+ }
44
+
45
+ // Attempt to decode and validate multicodec header
46
+ try {
47
+ const mc = base58.decode(key.slice(1));
48
+
49
+ if (mc.length < 2) {
50
+ throw new Error(
51
+ 'Invalid multibase key format. Keys must use multicodec headers.'
52
+ );
53
+ }
54
+
55
+ // Validate header matches expected type
56
+ const header = mc.slice(0, 2);
57
+ const expectedHeaders = isPrivate
58
+ ? {
59
+ Ed25519: MULTICODEC_ED25519_PRIV_HEADER,
60
+ Secp256k1: MULTICODEC_SECP256K1_PRIV_HEADER,
61
+ Bls12381G2: MULTICODEC_BLS12381_G2_PRIV_HEADER,
62
+ P256: MULTICODEC_P256_PRIV_HEADER
63
+ }
64
+ : {
65
+ Ed25519: MULTICODEC_ED25519_PUB_HEADER,
66
+ Secp256k1: MULTICODEC_SECP256K1_PUB_HEADER,
67
+ Bls12381G2: MULTICODEC_BLS12381_G2_PUB_HEADER,
68
+ P256: MULTICODEC_P256_PUB_HEADER
69
+ };
70
+
71
+ const expectedHeader = expectedHeaders[expectedType];
72
+
73
+ if (header[0] !== expectedHeader[0] || header[1] !== expectedHeader[1]) {
74
+ throw new Error(
75
+ `Invalid multibase key format. Expected ${expectedType} ${
76
+ isPrivate ? 'private' : 'public'
77
+ } key with multicodec header [0x${expectedHeader[0].toString(
78
+ 16
79
+ )}, 0x${expectedHeader[1].toString(16)}], but found [0x${header[0].toString(
80
+ 16
81
+ )}, 0x${header[1].toString(16)}].`
82
+ );
83
+ }
84
+
85
+ // Validate key length (basic sanity check)
86
+ const keyBytes = mc.slice(2);
87
+ const expectedLengths: Record<MultikeyType, { private: number; public: number }> = {
88
+ Ed25519: { private: 32, public: 32 },
89
+ Secp256k1: { private: 32, public: 33 },
90
+ P256: { private: 32, public: 33 },
91
+ Bls12381G2: { private: 32, public: 96 }
92
+ };
93
+
94
+ const expectedLength = isPrivate
95
+ ? expectedLengths[expectedType].private
96
+ : expectedLengths[expectedType].public;
97
+
98
+ if (keyBytes.length !== expectedLength) {
99
+ throw new Error(
100
+ `Invalid multibase key format. Expected ${expectedType} ${
101
+ isPrivate ? 'private' : 'public'
102
+ } key to be ${expectedLength} bytes, but found ${keyBytes.length} bytes.`
103
+ );
104
+ }
105
+ } catch (error) {
106
+ // Re-throw our own errors as-is
107
+ if (error instanceof Error && error.message.startsWith('Invalid multibase key format')) {
108
+ throw error;
109
+ }
110
+ // Base58 decode errors or other unexpected errors
111
+ throw new Error(
112
+ `Invalid multibase key format. Keys must use multicodec headers. Decode error: ${
113
+ error instanceof Error ? error.message : String(error)
114
+ }`
115
+ );
116
+ }
117
+ }
118
+
119
+ export const multikey = {
120
+ encodePublicKey: (publicKey: Uint8Array, type: MultikeyType): string => {
121
+ const header =
122
+ type === 'Ed25519'
123
+ ? MULTICODEC_ED25519_PUB_HEADER
124
+ : type === 'Secp256k1'
125
+ ? MULTICODEC_SECP256K1_PUB_HEADER
126
+ : type === 'Bls12381G2'
127
+ ? MULTICODEC_BLS12381_G2_PUB_HEADER
128
+ : MULTICODEC_P256_PUB_HEADER;
129
+ const mcBytes = concatBytes(header, publicKey);
130
+ return 'z' + base58.encode(mcBytes);
131
+ },
132
+
133
+ encodePrivateKey: (privateKey: Uint8Array, type: MultikeyType): string => {
134
+ const header =
135
+ type === 'Ed25519'
136
+ ? MULTICODEC_ED25519_PRIV_HEADER
137
+ : type === 'Secp256k1'
138
+ ? MULTICODEC_SECP256K1_PRIV_HEADER
139
+ : type === 'Bls12381G2'
140
+ ? MULTICODEC_BLS12381_G2_PRIV_HEADER
141
+ : MULTICODEC_P256_PRIV_HEADER;
142
+ const mcBytes = concatBytes(header, privateKey);
143
+ return 'z' + base58.encode(mcBytes);
144
+ },
145
+
146
+ encodeMultibase: (data: Uint8Array | Buffer): string => {
147
+ return 'z' + base58.encode(data instanceof Buffer ? new Uint8Array(data) : data);
148
+ },
149
+
150
+ decodePublicKey: (publicKeyMultibase: string): { key: Uint8Array; type: MultikeyType } => {
151
+ if (!publicKeyMultibase || publicKeyMultibase[0] !== 'z') {
152
+ throw new Error('Invalid Multibase encoding');
153
+ }
154
+ const mc = base58.decode(publicKeyMultibase.slice(1));
155
+ const header = mc.slice(0, 2);
156
+ const key = mc.slice(2);
157
+ if (header[0] === MULTICODEC_ED25519_PUB_HEADER[0] && header[1] === MULTICODEC_ED25519_PUB_HEADER[1]) {
158
+ return { key, type: 'Ed25519' };
159
+ }
160
+ if (header[0] === MULTICODEC_SECP256K1_PUB_HEADER[0] && header[1] === MULTICODEC_SECP256K1_PUB_HEADER[1]) {
161
+ return { key, type: 'Secp256k1' };
162
+ }
163
+ if (header[0] === MULTICODEC_BLS12381_G2_PUB_HEADER[0] && header[1] === MULTICODEC_BLS12381_G2_PUB_HEADER[1]) {
164
+ return { key, type: 'Bls12381G2' };
165
+ }
166
+ if (header[0] === MULTICODEC_P256_PUB_HEADER[0] && header[1] === MULTICODEC_P256_PUB_HEADER[1]) {
167
+ return { key, type: 'P256' };
168
+ }
169
+ throw new Error('Unsupported key type');
170
+ },
171
+
172
+ decodePrivateKey: (privateKeyMultibase: string): { key: Uint8Array; type: MultikeyType } => {
173
+ if (!privateKeyMultibase || privateKeyMultibase[0] !== 'z') {
174
+ throw new Error('Invalid Multibase encoding');
175
+ }
176
+ const mc = base58.decode(privateKeyMultibase.slice(1));
177
+ const header = mc.slice(0, 2);
178
+ const key = mc.slice(2);
179
+ if (header[0] === MULTICODEC_ED25519_PRIV_HEADER[0] && header[1] === MULTICODEC_ED25519_PRIV_HEADER[1]) {
180
+ return { key, type: 'Ed25519' };
181
+ }
182
+ if (header[0] === MULTICODEC_SECP256K1_PRIV_HEADER[0] && header[1] === MULTICODEC_SECP256K1_PRIV_HEADER[1]) {
183
+ return { key, type: 'Secp256k1' };
184
+ }
185
+ if (header[0] === MULTICODEC_BLS12381_G2_PRIV_HEADER[0] && header[1] === MULTICODEC_BLS12381_G2_PRIV_HEADER[1]) {
186
+ return { key, type: 'Bls12381G2' };
187
+ }
188
+ if (header[0] === MULTICODEC_P256_PRIV_HEADER[0] && header[1] === MULTICODEC_P256_PRIV_HEADER[1]) {
189
+ return { key, type: 'P256' };
190
+ }
191
+ throw new Error('Unsupported key type');
192
+ }
193
+ };
194
+
@@ -0,0 +1,262 @@
1
+ // Initialize noble crypto libraries first (idempotent - safe to import multiple times)
2
+ import './noble-init.js';
3
+
4
+ export abstract class Signer {
5
+ abstract sign(data: Buffer, privateKeyMultibase: string): Promise<Buffer>;
6
+ abstract verify(data: Buffer, signature: Buffer, publicKeyMultibase: string): Promise<boolean>;
7
+ }
8
+
9
+ import { bls12_381 as bls } from '@noble/curves/bls12-381';
10
+ import { p256 } from '@noble/curves/p256';
11
+ import { sha256 } from '@noble/hashes/sha2.js';
12
+ import * as secp256k1 from '@noble/secp256k1';
13
+ import * as ed25519 from '@noble/ed25519';
14
+ import { multikey } from './Multikey';
15
+
16
+ export class ES256KSigner extends Signer {
17
+ async sign(data: Buffer, privateKeyMultibase: string): Promise<Buffer> {
18
+ if (!privateKeyMultibase || privateKeyMultibase[0] !== 'z') {
19
+ throw new Error('Invalid multibase key format. Keys must use multicodec headers.');
20
+ }
21
+
22
+ let decoded;
23
+ try {
24
+ decoded = multikey.decodePrivateKey(privateKeyMultibase);
25
+ } catch (error) {
26
+ throw new Error(
27
+ `Invalid multibase key format. Keys must use multicodec headers. ${
28
+ error instanceof Error ? error.message : String(error)
29
+ }`
30
+ );
31
+ }
32
+
33
+ if (decoded.type !== 'Secp256k1') {
34
+ throw new Error('Invalid key type for ES256K');
35
+ }
36
+
37
+ const privateKey = decoded.key;
38
+ const hash = sha256(data);
39
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
40
+ const sigAny: any = await (secp256k1 as any).signAsync(hash, privateKey);
41
+ /* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call */
42
+ const sigBytes: Uint8Array = sigAny instanceof Uint8Array
43
+ ? sigAny
44
+ : typeof sigAny?.toCompactRawBytes === 'function'
45
+ ? sigAny.toCompactRawBytes()
46
+ : typeof sigAny?.toRawBytes === 'function'
47
+ ? sigAny.toRawBytes()
48
+ : new Uint8Array(sigAny);
49
+ /* eslint-enable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call */
50
+ return Buffer.from(sigBytes);
51
+ }
52
+
53
+ async verify(data: Buffer, signature: Buffer, publicKeyMultibase: string): Promise<boolean> {
54
+ if (!publicKeyMultibase || publicKeyMultibase[0] !== 'z') {
55
+ throw new Error('Invalid multibase key format. Keys must use multicodec headers.');
56
+ }
57
+
58
+ let decoded;
59
+ try {
60
+ decoded = multikey.decodePublicKey(publicKeyMultibase);
61
+ } catch (error) {
62
+ throw new Error(
63
+ `Invalid multibase key format. Keys must use multicodec headers. ${
64
+ error instanceof Error ? error.message : String(error)
65
+ }`
66
+ );
67
+ }
68
+
69
+ if (decoded.type !== 'Secp256k1') {
70
+ throw new Error('Invalid key type for ES256K');
71
+ }
72
+
73
+ const publicKey = decoded.key;
74
+ const hash = sha256(data);
75
+ try {
76
+ return await Promise.resolve(secp256k1.verify(signature, hash, publicKey));
77
+ } catch {
78
+ return false;
79
+ }
80
+ }
81
+ }
82
+
83
+ export class Ed25519Signer extends Signer {
84
+ async sign(data: Buffer, privateKeyMultibase: string): Promise<Buffer> {
85
+ if (!privateKeyMultibase || privateKeyMultibase[0] !== 'z') {
86
+ throw new Error('Invalid multibase key format. Keys must use multicodec headers.');
87
+ }
88
+
89
+ let decoded;
90
+ try {
91
+ decoded = multikey.decodePrivateKey(privateKeyMultibase);
92
+ } catch (error) {
93
+ throw new Error(
94
+ `Invalid multibase key format. Keys must use multicodec headers. ${
95
+ error instanceof Error ? error.message : String(error)
96
+ }`
97
+ );
98
+ }
99
+
100
+ if (decoded.type !== 'Ed25519') {
101
+ throw new Error('Invalid key type for Ed25519');
102
+ }
103
+
104
+ const privateKey = decoded.key;
105
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
106
+ const signature = await (ed25519 as any).signAsync(data, privateKey);
107
+ return Buffer.from(signature);
108
+ }
109
+
110
+ async verify(data: Buffer, signature: Buffer, publicKeyMultibase: string): Promise<boolean> {
111
+ if (!publicKeyMultibase || publicKeyMultibase[0] !== 'z') {
112
+ throw new Error('Invalid multibase key format. Keys must use multicodec headers.');
113
+ }
114
+
115
+ let decoded;
116
+ try {
117
+ decoded = multikey.decodePublicKey(publicKeyMultibase);
118
+ } catch (error) {
119
+ throw new Error(
120
+ `Invalid multibase key format. Keys must use multicodec headers. ${
121
+ error instanceof Error ? error.message : String(error)
122
+ }`
123
+ );
124
+ }
125
+
126
+ if (decoded.type !== 'Ed25519') {
127
+ throw new Error('Invalid key type for Ed25519');
128
+ }
129
+
130
+ const publicKey = decoded.key;
131
+ try {
132
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
133
+ return await (ed25519 as any).verifyAsync(signature, data, publicKey);
134
+ } catch {
135
+ return false;
136
+ }
137
+ }
138
+ }
139
+
140
+ export class ES256Signer extends Signer {
141
+ async sign(data: Buffer, privateKeyMultibase: string): Promise<Buffer> {
142
+ if (!privateKeyMultibase || privateKeyMultibase[0] !== 'z') {
143
+ throw new Error('Invalid multibase key format. Keys must use multicodec headers.');
144
+ }
145
+
146
+ let decoded;
147
+ try {
148
+ decoded = multikey.decodePrivateKey(privateKeyMultibase);
149
+ } catch (error) {
150
+ throw new Error(
151
+ `Invalid multibase key format. Keys must use multicodec headers. ${
152
+ error instanceof Error ? error.message : String(error)
153
+ }`
154
+ );
155
+ }
156
+
157
+ if (decoded.type !== 'P256') {
158
+ throw new Error('Invalid key type for ES256');
159
+ }
160
+
161
+ const privateKey = decoded.key;
162
+ const hash = sha256(data);
163
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
164
+ const sigAny: any = p256.sign(hash, privateKey);
165
+ /* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call */
166
+ const sigBytes: Uint8Array = sigAny instanceof Uint8Array
167
+ ? sigAny
168
+ : typeof sigAny?.toCompactRawBytes === 'function'
169
+ ? sigAny.toCompactRawBytes()
170
+ : typeof sigAny?.toRawBytes === 'function'
171
+ ? sigAny.toRawBytes()
172
+ : new Uint8Array(sigAny);
173
+ /* eslint-enable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call */
174
+ return await Promise.resolve(Buffer.from(sigBytes));
175
+ }
176
+
177
+ async verify(data: Buffer, signature: Buffer, publicKeyMultibase: string): Promise<boolean> {
178
+ if (!publicKeyMultibase || publicKeyMultibase[0] !== 'z') {
179
+ throw new Error('Invalid multibase key format. Keys must use multicodec headers.');
180
+ }
181
+
182
+ let decoded;
183
+ try {
184
+ decoded = multikey.decodePublicKey(publicKeyMultibase);
185
+ } catch (error) {
186
+ throw new Error(
187
+ `Invalid multibase key format. Keys must use multicodec headers. ${
188
+ error instanceof Error ? error.message : String(error)
189
+ }`
190
+ );
191
+ }
192
+
193
+ if (decoded.type !== 'P256') {
194
+ throw new Error('Invalid key type for ES256');
195
+ }
196
+
197
+ const publicKey = decoded.key;
198
+ const hash = sha256(data);
199
+ try {
200
+ return await Promise.resolve(p256.verify(signature, hash, publicKey));
201
+ } catch {
202
+ return false;
203
+ }
204
+ }
205
+ }
206
+
207
+ export class Bls12381G2Signer extends Signer {
208
+ async sign(data: Buffer, privateKeyMultibase: string): Promise<Buffer> {
209
+ if (!privateKeyMultibase || privateKeyMultibase[0] !== 'z') {
210
+ throw new Error('Invalid multibase key format. Keys must use multicodec headers.');
211
+ }
212
+
213
+ let decoded;
214
+ try {
215
+ decoded = multikey.decodePrivateKey(privateKeyMultibase);
216
+ } catch (error) {
217
+ throw new Error(
218
+ `Invalid multibase key format. Keys must use multicodec headers. ${
219
+ error instanceof Error ? error.message : String(error)
220
+ }`
221
+ );
222
+ }
223
+
224
+ if (decoded.type !== 'Bls12381G2') {
225
+ throw new Error('Invalid key type for Bls12381G2');
226
+ }
227
+
228
+ const sk = decoded.key;
229
+ const sig = bls.sign(data, sk);
230
+ return await Promise.resolve(Buffer.from(sig));
231
+ }
232
+
233
+ async verify(data: Buffer, signature: Buffer, publicKeyMultibase: string): Promise<boolean> {
234
+ if (!publicKeyMultibase || publicKeyMultibase[0] !== 'z') {
235
+ throw new Error('Invalid multibase key format. Keys must use multicodec headers.');
236
+ }
237
+
238
+ let decoded;
239
+ try {
240
+ decoded = multikey.decodePublicKey(publicKeyMultibase);
241
+ } catch (error) {
242
+ throw new Error(
243
+ `Invalid multibase key format. Keys must use multicodec headers. ${
244
+ error instanceof Error ? error.message : String(error)
245
+ }`
246
+ );
247
+ }
248
+
249
+ if (decoded.type !== 'Bls12381G2') {
250
+ throw new Error('Invalid key type for Bls12381G2');
251
+ }
252
+
253
+ const pk = decoded.key;
254
+ try {
255
+ return await Promise.resolve(bls.verify(signature, data, pk));
256
+ } catch {
257
+ return false;
258
+ }
259
+ }
260
+ }
261
+
262
+
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Noble Crypto Library Initialization
3
+ *
4
+ * @noble/ed25519 v2.x and @noble/secp256k1 require manual configuration of hash functions.
5
+ * This is by design - they don't bundle hash implementations to allow flexibility.
6
+ *
7
+ * This module centralizes the initialization to ensure:
8
+ * 1. Libraries are configured before any crypto operations
9
+ * 2. Configuration is consistent across the SDK
10
+ * 3. Readonly property issues (Bun) are handled gracefully
11
+ *
12
+ * This should be imported at the SDK entry point (index.ts) to ensure it runs first.
13
+ */
14
+
15
+ import * as secp256k1 from '@noble/secp256k1';
16
+ import * as ed25519 from '@noble/ed25519';
17
+ import { sha256, sha512 } from '@noble/hashes/sha2.js';
18
+ import { hmac } from '@noble/hashes/hmac.js';
19
+ import { concatBytes } from '@noble/hashes/utils.js';
20
+
21
+ // Implementation functions
22
+ const sha512Impl = (...msgs: Uint8Array[]) => sha512(concatBytes(...msgs));
23
+ const hmacSha256Impl = (key: Uint8Array, ...msgs: Uint8Array[]) =>
24
+ hmac(sha256, key, concatBytes(...msgs));
25
+
26
+ /**
27
+ * Safely set a property on an object, handling readonly properties
28
+ */
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
+ function safeSetProperty(
31
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
32
+ obj: any,
33
+ prop: string,
34
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
35
+ value: any,
36
+ options?: { writable?: boolean; configurable?: boolean }
37
+ ): boolean {
38
+ try {
39
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
40
+ obj[prop] = value;
41
+ return true;
42
+ } catch {
43
+ // Property might be readonly, try defineProperty
44
+ try {
45
+ Object.defineProperty(obj, prop, {
46
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
47
+ value,
48
+ writable: options?.writable ?? true,
49
+ configurable: options?.configurable ?? true,
50
+ });
51
+ return true;
52
+ } catch {
53
+ // If both fail, property might already be set or truly readonly
54
+ return false;
55
+ }
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Initialize @noble/secp256k1 with hmacSha256Sync utility
61
+ */
62
+ function initSecp256k1(): void {
63
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
64
+ const sAny: any = secp256k1 as any;
65
+
66
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
67
+ if (!sAny?.utils) {
68
+ // Try to create utils object if it doesn't exist
69
+ try {
70
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
71
+ sAny.utils = {};
72
+ } catch {
73
+ // If we can't create it, try defineProperty
74
+ Object.defineProperty(sAny, 'utils', {
75
+ value: {},
76
+ writable: true,
77
+ configurable: true,
78
+ });
79
+ }
80
+ }
81
+
82
+ // Set hmacSha256Sync if not already set
83
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
84
+ if (typeof sAny.utils.hmacSha256Sync !== 'function') {
85
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
86
+ safeSetProperty(sAny.utils, 'hmacSha256Sync', hmacSha256Impl);
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Initialize @noble/ed25519 with sha512Sync utility
92
+ * Handles both etc.sha512Sync (v2.x) and utils.sha512Sync (backward compat)
93
+ */
94
+ function initEd25519(): void {
95
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
96
+ const eAny: any = ed25519 as any;
97
+
98
+ // Set etc.sha512Sync for @noble/ed25519 v2.x (required)
99
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
100
+ if (eAny?.etc && typeof eAny.etc.sha512Sync !== 'function') {
101
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
102
+ safeSetProperty(eAny.etc, 'sha512Sync', sha512Impl);
103
+ }
104
+
105
+ // Set utils.sha512Sync for backward compatibility
106
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
107
+ if (!eAny?.utils) {
108
+ try {
109
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
110
+ eAny.utils = {};
111
+ } catch {
112
+ Object.defineProperty(eAny, 'utils', {
113
+ value: {},
114
+ writable: true,
115
+ configurable: true,
116
+ });
117
+ }
118
+ }
119
+
120
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
121
+ if (typeof eAny.utils.sha512Sync !== 'function') {
122
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
123
+ safeSetProperty(eAny.utils, 'sha512Sync', sha512Impl);
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Initialize all noble crypto libraries
129
+ * This should be called once at SDK startup
130
+ */
131
+ export function initNobleCrypto(): void {
132
+ initSecp256k1();
133
+ initEd25519();
134
+ }
135
+
136
+ // Auto-initialize when this module is imported
137
+ initNobleCrypto();
138
+