@private.me/xbind 3.0.2 → 3.0.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 (221) hide show
  1. package/README.md +2366 -204
  2. package/README.md.backup +2121 -0
  3. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  4. package/dist-standalone/_deps/shared/cjs/errors.js +1 -729
  5. package/dist-standalone/_deps/shared/cjs/index.js +1 -463
  6. package/dist-standalone/_deps/shared/cjs/types.js +1 -315
  7. package/dist-standalone/_deps/shared/errors.js +1 -244
  8. package/dist-standalone/_deps/shared/index.js +1 -72
  9. package/dist-standalone/_deps/shared/types.js +1 -86
  10. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  20. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  21. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  28. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  29. package/dist-standalone/_deps/xchange/errors.js +1 -1
  30. package/dist-standalone/_deps/xchange/index.js +1 -1
  31. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  32. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  33. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  34. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  40. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  41. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  42. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  43. package/dist-standalone/_deps/xregistry/index.js +1 -1
  44. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  45. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  46. package/dist-standalone/_deps/xregistry/types.js +1 -1
  47. package/dist-standalone/agent-call.d.ts +2 -2
  48. package/dist-standalone/agent-call.js +1 -659
  49. package/dist-standalone/agent-sdk.js +1 -328
  50. package/dist-standalone/agent.d.ts +2 -0
  51. package/dist-standalone/agent.js +1 -1800
  52. package/dist-standalone/approval.js +1 -193
  53. package/dist-standalone/async-iterators.d.ts +3 -3
  54. package/dist-standalone/async-iterators.js +1 -382
  55. package/dist-standalone/auth.js +1 -219
  56. package/dist-standalone/auto-accept.js +1 -229
  57. package/dist-standalone/backup-config.js +1 -201
  58. package/dist-standalone/backup.js +1 -326
  59. package/dist-standalone/batch-operations.js +1 -388
  60. package/dist-standalone/cancellation.js +1 -477
  61. package/dist-standalone/checkpoint.js +1 -186
  62. package/dist-standalone/circuit-breaker.js +1 -468
  63. package/dist-standalone/cjs/agent-call.js +1 -701
  64. package/dist-standalone/cjs/agent-sdk.js +1 -332
  65. package/dist-standalone/cjs/agent.js +1 -1837
  66. package/dist-standalone/cjs/approval.js +1 -199
  67. package/dist-standalone/cjs/async-iterators.js +1 -392
  68. package/dist-standalone/cjs/auth.js +1 -225
  69. package/dist-standalone/cjs/auto-accept.js +1 -233
  70. package/dist-standalone/cjs/backup-config.js +1 -207
  71. package/dist-standalone/cjs/backup.js +1 -330
  72. package/dist-standalone/cjs/batch-operations.js +1 -397
  73. package/dist-standalone/cjs/cancellation.js +1 -490
  74. package/dist-standalone/cjs/checkpoint.js +1 -193
  75. package/dist-standalone/cjs/circuit-breaker.js +1 -476
  76. package/dist-standalone/cjs/cli/init.js +1 -492
  77. package/dist-standalone/cjs/config-validation.js +1 -522
  78. package/dist-standalone/cjs/connect.js +1 -312
  79. package/dist-standalone/cjs/connection-pool.js +1 -506
  80. package/dist-standalone/cjs/correlation-id.js +1 -339
  81. package/dist-standalone/cjs/crypto-utils.js +1 -176
  82. package/dist-standalone/cjs/debug-mode.js +1 -534
  83. package/dist-standalone/cjs/did-document.js +1 -101
  84. package/dist-standalone/cjs/did-privateme.js +1 -130
  85. package/dist-standalone/cjs/did-web.js +1 -201
  86. package/dist-standalone/cjs/discovery.js +1 -462
  87. package/dist-standalone/cjs/dual-mode.js +1 -251
  88. package/dist-standalone/cjs/email-templates.js +1 -313
  89. package/dist-standalone/cjs/email-transport.js +1 -239
  90. package/dist-standalone/cjs/envelope.js +1 -538
  91. package/dist-standalone/cjs/errors.js +1 -913
  92. package/dist-standalone/cjs/event-emitter.js +1 -461
  93. package/dist-standalone/cjs/gateway-state.js +1 -55
  94. package/dist-standalone/cjs/gateway-transport.js +1 -120
  95. package/dist-standalone/cjs/graceful-degradation.js +1 -403
  96. package/dist-standalone/cjs/guardrails.js +1 -223
  97. package/dist-standalone/cjs/health-check.js +1 -336
  98. package/dist-standalone/cjs/http-compat.js +1 -272
  99. package/dist-standalone/cjs/http-status-map.js +1 -571
  100. package/dist-standalone/cjs/identity.js +1 -645
  101. package/dist-standalone/cjs/index.js +1 -406
  102. package/dist-standalone/cjs/invitation.js +1 -421
  103. package/dist-standalone/cjs/invite.js +1 -328
  104. package/dist-standalone/cjs/key-agreement.js +1 -335
  105. package/dist-standalone/cjs/lazy-init.js +1 -300
  106. package/dist-standalone/cjs/logger.js +1 -291
  107. package/dist-standalone/cjs/loopback-transport.js +1 -0
  108. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  109. package/dist-standalone/cjs/nonce-store.js +1 -80
  110. package/dist-standalone/cjs/pairing-manager.js +1 -223
  111. package/dist-standalone/cjs/plugin-system.js +1 -264
  112. package/dist-standalone/cjs/plugins/logging.js +1 -168
  113. package/dist-standalone/cjs/plugins/metrics.js +1 -181
  114. package/dist-standalone/cjs/plugins/validation.js +1 -302
  115. package/dist-standalone/cjs/policy.js +1 -320
  116. package/dist-standalone/cjs/progress-callbacks.js +1 -583
  117. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  118. package/dist-standalone/cjs/registry-middleware.js +1 -50
  119. package/dist-standalone/cjs/retry-strategies.js +1 -544
  120. package/dist-standalone/cjs/retry-transport.js +1 -102
  121. package/dist-standalone/cjs/runtime/browser.js +1 -533
  122. package/dist-standalone/cjs/runtime/edge.js +1 -526
  123. package/dist-standalone/cjs/runtime/react-native.js +1 -394
  124. package/dist-standalone/cjs/security-policy.js +1 -245
  125. package/dist-standalone/cjs/serialization.js +1 -1040
  126. package/dist-standalone/cjs/split-channel.js +1 -225
  127. package/dist-standalone/cjs/subscription-proof.js +1 -230
  128. package/dist-standalone/cjs/succession.js +1 -148
  129. package/dist-standalone/cjs/timeouts.js +1 -412
  130. package/dist-standalone/cjs/trace-context.js +1 -424
  131. package/dist-standalone/cjs/trace-spans.js +1 -495
  132. package/dist-standalone/cjs/transport.js +1 -63
  133. package/dist-standalone/cjs/trust-registry.js +1 -991
  134. package/dist-standalone/cjs/types/error-response.js +1 -56
  135. package/dist-standalone/cjs/vault-auth.js +1 -178
  136. package/dist-standalone/cjs/vault-store-loader.js +1 -194
  137. package/dist-standalone/cjs/verify.js +1 -25
  138. package/dist-standalone/cjs/version-info.js +1 -543
  139. package/dist-standalone/cjs/xfetch.js +1 -340
  140. package/dist-standalone/cli/init.js +1 -455
  141. package/dist-standalone/cli/setup.js +1 -514
  142. package/dist-standalone/cli/types.js +1 -27
  143. package/dist-standalone/cli/xbind.js +1 -148
  144. package/dist-standalone/config-validation.js +1 -513
  145. package/dist-standalone/connect.js +1 -274
  146. package/dist-standalone/connection-pool.js +1 -500
  147. package/dist-standalone/correlation-id.js +1 -326
  148. package/dist-standalone/crypto-utils.d.ts +2 -7
  149. package/dist-standalone/crypto-utils.js +1 -157
  150. package/dist-standalone/debug-mode.js +1 -510
  151. package/dist-standalone/did-document.js +1 -96
  152. package/dist-standalone/did-privateme.js +1 -121
  153. package/dist-standalone/did-web.js +1 -196
  154. package/dist-standalone/discovery.js +1 -458
  155. package/dist-standalone/dual-mode.js +1 -247
  156. package/dist-standalone/email-templates.js +1 -309
  157. package/dist-standalone/email-transport.d.ts +2 -2
  158. package/dist-standalone/email-transport.js +1 -232
  159. package/dist-standalone/envelope.js +1 -525
  160. package/dist-standalone/errors.d.ts +13 -3
  161. package/dist-standalone/errors.js +1 -896
  162. package/dist-standalone/event-emitter.js +1 -456
  163. package/dist-standalone/gateway-state.d.ts +1 -1
  164. package/dist-standalone/gateway-state.js +1 -51
  165. package/dist-standalone/gateway-transport.js +1 -116
  166. package/dist-standalone/graceful-degradation.js +1 -396
  167. package/dist-standalone/guardrails.js +1 -216
  168. package/dist-standalone/health-check.d.ts +5 -1
  169. package/dist-standalone/health-check.js +1 -332
  170. package/dist-standalone/http-compat.d.ts +1 -1
  171. package/dist-standalone/http-compat.js +1 -267
  172. package/dist-standalone/http-status-map.js +1 -561
  173. package/dist-standalone/identity.js +1 -619
  174. package/dist-standalone/index.d.ts +15 -4
  175. package/dist-standalone/index.js +1 -78
  176. package/dist-standalone/invitation.js +1 -415
  177. package/dist-standalone/invite.js +1 -324
  178. package/dist-standalone/key-agreement.js +1 -325
  179. package/dist-standalone/lazy-init.d.ts +11 -6
  180. package/dist-standalone/lazy-init.js +1 -295
  181. package/dist-standalone/logger.js +1 -285
  182. package/dist-standalone/loopback-transport.d.ts +87 -0
  183. package/dist-standalone/loopback-transport.js +1 -0
  184. package/dist-standalone/mdns-discovery.js +1 -195
  185. package/dist-standalone/nonce-store.js +1 -76
  186. package/dist-standalone/pairing-manager.js +1 -219
  187. package/dist-standalone/plugin-system.js +1 -257
  188. package/dist-standalone/plugins/logging.js +1 -163
  189. package/dist-standalone/plugins/metrics.d.ts +4 -4
  190. package/dist-standalone/plugins/metrics.js +1 -176
  191. package/dist-standalone/plugins/validation.js +1 -297
  192. package/dist-standalone/policy.js +1 -315
  193. package/dist-standalone/progress-callbacks.js +1 -576
  194. package/dist-standalone/redis-nonce-store.js +1 -72
  195. package/dist-standalone/registry-middleware.js +1 -47
  196. package/dist-standalone/retry-strategies.js +1 -534
  197. package/dist-standalone/retry-transport.js +1 -98
  198. package/dist-standalone/runtime/browser.js +1 -516
  199. package/dist-standalone/runtime/edge.js +1 -511
  200. package/dist-standalone/runtime/react-native.d.ts +1 -1
  201. package/dist-standalone/runtime/react-native.js +1 -383
  202. package/dist-standalone/security-policy.js +1 -239
  203. package/dist-standalone/serialization.js +1 -1031
  204. package/dist-standalone/split-channel.js +1 -219
  205. package/dist-standalone/subscription-proof.js +1 -224
  206. package/dist-standalone/succession.js +1 -142
  207. package/dist-standalone/timeouts.js +1 -398
  208. package/dist-standalone/trace-context.js +1 -414
  209. package/dist-standalone/trace-spans.js +1 -488
  210. package/dist-standalone/transport.js +1 -59
  211. package/dist-standalone/trust-registry.d.ts +3 -3
  212. package/dist-standalone/trust-registry.js +1 -950
  213. package/dist-standalone/types/error-response.js +1 -52
  214. package/dist-standalone/vault-auth.js +1 -174
  215. package/dist-standalone/vault-store-loader.d.ts +9 -0
  216. package/dist-standalone/vault-store-loader.js +1 -187
  217. package/dist-standalone/verify.js +1 -16
  218. package/dist-standalone/version-info.js +1 -530
  219. package/dist-standalone/xfetch.js +1 -335
  220. package/package.json +1 -1
  221. package/share1.dat +0 -0
@@ -1,619 +1 @@
1
- import { ok, err } from"./_deps/shared/index.js";
2
- import { fromBase64Url } from './crypto-utils.js';
3
- import { createMlKem768 } from 'mlkem';
4
- import mldsa from"./_deps/mldsa-wasm/dist/mldsa.js";
5
- /** Ed25519 multicodec varint prefix. */
6
- const ED25519_MULTICODEC = new Uint8Array([0xed, 0x01]);
7
- const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
8
- /** Copy Uint8Array to fresh ArrayBuffer (avoids SharedArrayBuffer type issues). */
9
- function toArrayBuffer(data) {
10
- const buf = new ArrayBuffer(data.byteLength);
11
- new Uint8Array(buf).set(data);
12
- return buf;
13
- }
14
- /* ── Key Generation ── */
15
- /**
16
- * Generate a new Ed25519 agent identity.
17
- * Creates keypair via Web Crypto API, derives did:key DID.
18
- *
19
- * @param opts - Optional configuration
20
- * @param opts.postQuantumSig - Enable ML-DSA-65 post-quantum signatures (default: false)
21
- * @returns Result containing the agent identity or error
22
- *
23
- * @example
24
- * ```typescript
25
- * import { generateIdentity } from '@private.me/xbind';
26
- *
27
- * // Generate identity with classical cryptography only
28
- * const identity = await generateIdentity();
29
- * if (!identity.ok) {
30
- * throw new Error(`Failed to generate identity: ${identity.error}`);
31
- * }
32
- * console.log('DID:', identity.value.did);
33
- *
34
- * // Generate identity with post-quantum signatures
35
- * const pqIdentity = await generateIdentity({ postQuantumSig: true });
36
- * if (pqIdentity.ok) {
37
- * console.log('Post-quantum DID:', pqIdentity.value.did);
38
- * console.log('Has ML-DSA key:', !!pqIdentity.value.mlDsaPublicKey);
39
- * }
40
- * ```
41
- */
42
- export async function generateIdentity(opts) {
43
- try {
44
- // SAFETY: Ed25519 generateKey always returns CryptoKeyPair
45
- const keyPair = await crypto.subtle.generateKey('Ed25519', true, ['sign', 'verify']);
46
- const rawPub = new Uint8Array(await crypto.subtle.exportKey('raw', keyPair.publicKey));
47
- const did = publicKeyToDid(rawPub);
48
- // SAFETY: X25519 generateKey always returns CryptoKeyPair
49
- const x25519Pair = await crypto.subtle.generateKey({ name: 'X25519' }, true, ['deriveBits']);
50
- const rawX25519Pub = new Uint8Array(await crypto.subtle.exportKey('raw', x25519Pair.publicKey));
51
- // Generate ML-KEM-768 keypair for hybrid post-quantum KEM (always-on)
52
- let mlKemPublicKey;
53
- let mlKemSecretKey;
54
- try {
55
- const mlkem = await createMlKem768();
56
- const [publicKey, secretKey] = mlkem.generateKeyPair();
57
- mlKemPublicKey = publicKey;
58
- mlKemSecretKey = secretKey;
59
- }
60
- catch (err) {
61
- console.warn('[xBind] ML-KEM-768 keygen failed, using classical crypto only:', err);
62
- }
63
- // Generate ML-DSA-65 keypair only when opt-in flag is set
64
- let mlDsaPublicKey;
65
- let mlDsaSecretKey;
66
- if (opts?.postQuantumSig) {
67
- try {
68
- const keypair = await mldsa.generateKey('ML-DSA-65', true, ['sign', 'verify']);
69
- const publicKeyRaw = await mldsa.exportKey('raw-public', keypair.publicKey);
70
- const secretKeySeed = await mldsa.exportKey('raw-seed', keypair.privateKey);
71
- mlDsaPublicKey = new Uint8Array(publicKeyRaw);
72
- // For storage, we need the full secret key, not just the seed
73
- // We'll store the seed and regenerate when needed
74
- mlDsaSecretKey = new Uint8Array(secretKeySeed);
75
- }
76
- catch (err) {
77
- console.warn('[xBind] ML-DSA-65 keygen failed, using classical crypto only:', err);
78
- }
79
- }
80
- return ok({
81
- did,
82
- publicKey: keyPair.publicKey,
83
- privateKey: keyPair.privateKey,
84
- rawPublicKey: rawPub,
85
- x25519PrivateKey: x25519Pair.privateKey,
86
- x25519PublicKey: x25519Pair.publicKey,
87
- rawX25519PublicKey: rawX25519Pub,
88
- ...(mlKemPublicKey ? { mlKemPublicKey } : {}),
89
- ...(mlKemSecretKey ? { mlKemSecretKey } : {}),
90
- ...(mlDsaPublicKey ? { mlDsaPublicKey } : {}),
91
- ...(mlDsaSecretKey ? { mlDsaSecretKey } : {}),
92
- });
93
- }
94
- catch {
95
- return err('KEYGEN_FAILED');
96
- }
97
- }
98
- /* ── Sign / Verify ── */
99
- /**
100
- * Sign data with an Ed25519 private key.
101
- * @returns 64-byte Ed25519 signature.
102
- */
103
- export async function sign(privateKey, data) {
104
- try {
105
- const sig = new Uint8Array(await crypto.subtle.sign('Ed25519', privateKey, toArrayBuffer(data)));
106
- return ok(sig);
107
- }
108
- catch {
109
- return err('SIGN_FAILED');
110
- }
111
- }
112
- /**
113
- * Verify an Ed25519 signature.
114
- * @returns true if valid, false if invalid (not an error).
115
- */
116
- export async function verify(publicKey, signature, data) {
117
- try {
118
- const valid = await crypto.subtle.verify('Ed25519', publicKey, toArrayBuffer(signature), toArrayBuffer(data));
119
- return ok(valid);
120
- }
121
- catch {
122
- return err('VERIFY_FAILED');
123
- }
124
- }
125
- /* ── Key Import ── */
126
- /**
127
- * Import a raw 32-byte Ed25519 public key into a CryptoKey.
128
- */
129
- export async function importPublicKey(rawPublicKey) {
130
- if (rawPublicKey.length !== 32)
131
- return err('INVALID_KEY_LENGTH');
132
- try {
133
- const key = await crypto.subtle.importKey('raw', toArrayBuffer(rawPublicKey), 'Ed25519', true, ['verify']);
134
- return ok(key);
135
- }
136
- catch {
137
- return err('KEYGEN_FAILED');
138
- }
139
- }
140
- /* ── DID Conversion ── */
141
- /**
142
- * Convert 32-byte Ed25519 public key to did:key DID.
143
- * Format: did:key:z + base58btc(0xed01 || publicKey).
144
- */
145
- export function publicKeyToDid(rawPublicKey) {
146
- const prefixed = new Uint8Array(2 + rawPublicKey.length);
147
- prefixed.set(ED25519_MULTICODEC);
148
- prefixed.set(rawPublicKey, 2);
149
- return `did:key:z${base58btcEncode(prefixed)}`;
150
- }
151
- /**
152
- * Extract raw 32-byte public key bytes from a did:key DID.
153
- */
154
- export function didToPublicKeyBytes(did) {
155
- if (!did.startsWith('did:key:z'))
156
- return err('INVALID_DID');
157
- try {
158
- const encoded = did.slice('did:key:z'.length);
159
- const bytes = base58btcDecode(encoded);
160
- if (bytes[0] !== 0xed || bytes[1] !== 0x01)
161
- return err('INVALID_DID');
162
- if (bytes.length !== 34)
163
- return err('INVALID_DID');
164
- return ok(bytes.slice(2));
165
- }
166
- catch {
167
- return err('INVALID_DID');
168
- }
169
- }
170
- /* ── PKCS8 Export/Import ── */
171
- /**
172
- * Export an Ed25519 private key as PKCS8 DER bytes.
173
- *
174
- * Use this to persist an agent identity across restarts.
175
- * Node 20 does not support raw export for Ed25519 private keys —
176
- * PKCS8 is the portable format.
177
- *
178
- * @param privateKey - Ed25519 CryptoKey (must be extractable).
179
- * @returns PKCS8 DER bytes or error.
180
- */
181
- export async function exportPKCS8(privateKey) {
182
- try {
183
- const buf = await crypto.subtle.exportKey('pkcs8', privateKey);
184
- return ok(new Uint8Array(buf));
185
- }
186
- catch {
187
- return err('EXPORT_FAILED');
188
- }
189
- }
190
- /**
191
- * Export an X25519 private key as PKCS8 DER bytes.
192
- *
193
- * @param privateKey - X25519 CryptoKey (must be extractable).
194
- * @returns PKCS8 DER bytes or error.
195
- */
196
- export async function exportX25519PKCS8(privateKey) {
197
- try {
198
- const buf = await crypto.subtle.exportKey('pkcs8', privateKey);
199
- return ok(new Uint8Array(buf));
200
- }
201
- catch {
202
- return err('EXPORT_FAILED');
203
- }
204
- }
205
- /**
206
- * Import an Ed25519 identity from PKCS8 DER bytes.
207
- *
208
- * Generates a new X25519 keypair for forward secrecy.
209
- * Use this when you only persisted the Ed25519 key.
210
- *
211
- * @param pkcs8 - PKCS8-encoded Ed25519 private key bytes.
212
- * @returns Full AgentIdentity or error.
213
- */
214
- export async function importFromPKCS8(pkcs8) {
215
- try {
216
- const privateKey = await crypto.subtle.importKey('pkcs8', toArrayBuffer(pkcs8), 'Ed25519', true, ['sign']);
217
- // Extract public key from JWK (PKCS8 import returns only private key)
218
- const jwk = await crypto.subtle.exportKey('jwk', privateKey);
219
- if (!jwk.x)
220
- return err('IMPORT_FAILED');
221
- // JWK x field is base64url-encoded raw public key
222
- const rawPub = fromBase64Url(jwk.x);
223
- const publicKey = await crypto.subtle.importKey('raw', toArrayBuffer(rawPub), 'Ed25519', true, ['verify']);
224
- const did = publicKeyToDid(rawPub);
225
- // Generate fresh X25519 keypair for forward secrecy
226
- // SAFETY: X25519 generateKey always returns CryptoKeyPair
227
- const x25519Pair = await crypto.subtle.generateKey({ name: 'X25519' }, true, ['deriveBits']);
228
- const rawX25519Pub = new Uint8Array(await crypto.subtle.exportKey('raw', x25519Pair.publicKey));
229
- return ok({
230
- did,
231
- publicKey,
232
- privateKey,
233
- rawPublicKey: rawPub,
234
- x25519PrivateKey: x25519Pair.privateKey,
235
- x25519PublicKey: x25519Pair.publicKey,
236
- rawX25519PublicKey: rawX25519Pub,
237
- });
238
- }
239
- catch {
240
- return err('IMPORT_FAILED');
241
- }
242
- }
243
- /**
244
- * Import a full identity from both PKCS8 blobs (Ed25519 + X25519).
245
- *
246
- * Use this when you persisted both keys for full identity restoration
247
- * including the original X25519 key (preserves registered key agreement).
248
- *
249
- * @param ed25519Pkcs8 - PKCS8-encoded Ed25519 private key bytes.
250
- * @param x25519Pkcs8 - PKCS8-encoded X25519 private key bytes.
251
- * @returns Full AgentIdentity or error.
252
- */
253
- export async function importIdentity(ed25519Pkcs8, x25519Pkcs8, mlKemSecretKey, mlKemPublicKey, mlDsaSecretKey, mlDsaPublicKey) {
254
- try {
255
- const privateKey = await crypto.subtle.importKey('pkcs8', toArrayBuffer(ed25519Pkcs8), 'Ed25519', true, ['sign']);
256
- const jwk = await crypto.subtle.exportKey('jwk', privateKey);
257
- if (!jwk.x)
258
- return err('IMPORT_FAILED');
259
- const rawPub = fromBase64Url(jwk.x);
260
- const publicKey = await crypto.subtle.importKey('raw', toArrayBuffer(rawPub), 'Ed25519', true, ['verify']);
261
- const did = publicKeyToDid(rawPub);
262
- const x25519PrivateKey = await crypto.subtle.importKey('pkcs8', toArrayBuffer(x25519Pkcs8), { name: 'X25519' }, true, ['deriveBits']);
263
- const x25519Jwk = await crypto.subtle.exportKey('jwk', x25519PrivateKey);
264
- if (!x25519Jwk.x)
265
- return err('IMPORT_FAILED');
266
- const rawX25519Pub = fromBase64Url(x25519Jwk.x);
267
- const x25519PublicKey = await crypto.subtle.importKey('raw', toArrayBuffer(rawX25519Pub), { name: 'X25519' }, true, []);
268
- return ok({
269
- did,
270
- publicKey,
271
- privateKey,
272
- rawPublicKey: rawPub,
273
- x25519PrivateKey,
274
- x25519PublicKey,
275
- rawX25519PublicKey: rawX25519Pub,
276
- ...(mlKemSecretKey ? { mlKemSecretKey } : {}),
277
- ...(mlKemPublicKey ? { mlKemPublicKey } : {}),
278
- ...(mlDsaSecretKey ? { mlDsaSecretKey } : {}),
279
- ...(mlDsaPublicKey ? { mlDsaPublicKey } : {}),
280
- });
281
- }
282
- catch {
283
- return err('IMPORT_FAILED');
284
- }
285
- }
286
- /* ── ML-KEM Key Export ── */
287
- /**
288
- * Export ML-KEM-768 secret key bytes from an identity.
289
- *
290
- * @param identity - Agent identity with ML-KEM keys.
291
- * @returns Raw 2400-byte ML-KEM secret key or undefined if not available.
292
- */
293
- export function exportMlKemSecretKey(identity) {
294
- return identity.mlKemSecretKey;
295
- }
296
- /**
297
- * Export ML-KEM-768 public key bytes from an identity.
298
- *
299
- * @param identity - Agent identity with ML-KEM keys.
300
- * @returns Raw 1184-byte ML-KEM public key or undefined if not available.
301
- */
302
- export function exportMlKemPublicKey(identity) {
303
- return identity.mlKemPublicKey;
304
- }
305
- /* ── ML-DSA-65 Sign / Verify ── */
306
- /** ML-DSA-65 signature length in bytes. */
307
- export const ML_DSA65_SIG_BYTES = 3309;
308
- /** ML-DSA-65 public key length in bytes. */
309
- export const ML_DSA65_PK_BYTES = 1952;
310
- /** ML-DSA-65 secret key seed length in bytes (using seed format for storage). */
311
- export const ML_DSA65_SK_BYTES = 32;
312
- /**
313
- * Sign data with an ML-DSA-65 secret key (FIPS 204).
314
- * @param secretKey - 32-byte ML-DSA-65 secret key seed.
315
- * @param data - Data to sign.
316
- * @returns 3309-byte ML-DSA-65 signature.
317
- */
318
- export async function signMlDsa65(secretKey, data) {
319
- try {
320
- // Import secret key seed as CryptoKey
321
- const privateKey = await mldsa.importKey('raw-seed', toArrayBuffer(secretKey), 'ML-DSA-65', false, ['sign']);
322
- // Sign using mldsa-wasm API
323
- const signature = await mldsa.sign('ML-DSA-65', privateKey, toArrayBuffer(data));
324
- return ok(new Uint8Array(signature));
325
- }
326
- catch {
327
- return err('SIGN_FAILED');
328
- }
329
- }
330
- /**
331
- * Verify an ML-DSA-65 signature (FIPS 204).
332
- * @param publicKey - 1952-byte ML-DSA-65 public key.
333
- * @param signature - 3309-byte ML-DSA-65 signature.
334
- * @param data - Data that was signed.
335
- * @returns true if valid, false if invalid (not an error).
336
- */
337
- export async function verifyMlDsa65(publicKey, signature, data) {
338
- try {
339
- // Import public key as CryptoKey
340
- const pubKey = await mldsa.importKey('raw-public', toArrayBuffer(publicKey), 'ML-DSA-65', false, ['verify']);
341
- // Verify using mldsa-wasm API
342
- const valid = await mldsa.verify('ML-DSA-65', pubKey, toArrayBuffer(signature), toArrayBuffer(data));
343
- return ok(valid);
344
- }
345
- catch {
346
- return err('VERIFY_FAILED');
347
- }
348
- }
349
- /* ── ML-DSA Key Export ── */
350
- /**
351
- * Export ML-DSA-65 secret key bytes from an identity.
352
- *
353
- * @param identity - Agent identity with ML-DSA keys.
354
- * @returns Raw 4032-byte ML-DSA-65 secret key or undefined if not available.
355
- */
356
- export function exportMlDsaSecretKey(identity) {
357
- return identity.mlDsaSecretKey;
358
- }
359
- /**
360
- * Export ML-DSA-65 public key bytes from an identity.
361
- *
362
- * @param identity - Agent identity with ML-DSA keys.
363
- * @returns Raw 1952-byte ML-DSA-65 public key or undefined if not available.
364
- */
365
- export function exportMlDsaPublicKey(identity) {
366
- return identity.mlDsaPublicKey;
367
- }
368
- /* ── PKCS8 ASN.1 Prefixes ── */
369
- /**
370
- * PKCS8 ASN.1 DER header for Ed25519 private keys (16 bytes).
371
- * Structure: SEQUENCE { INTEGER(0), SEQUENCE { OID(1.3.101.112) }, OCTET STRING header }
372
- * The 32-byte raw seed follows immediately after this prefix.
373
- */
374
- const ED25519_PKCS8_PREFIX = new Uint8Array([
375
- 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,
376
- 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
377
- ]);
378
- /**
379
- * PKCS8 ASN.1 DER header for X25519 private keys (16 bytes).
380
- * Structure: SEQUENCE { INTEGER(0), SEQUENCE { OID(1.3.101.110) }, OCTET STRING header }
381
- * The 32-byte raw seed follows immediately after this prefix.
382
- */
383
- const X25519_PKCS8_PREFIX = new Uint8Array([
384
- 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,
385
- 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20,
386
- ]);
387
- /* ── Deterministic Identity from Seed ── */
388
- /**
389
- * Derive a deterministic AgentIdentity from a 32-byte seed.
390
- *
391
- * Uses HKDF-SHA256 to derive separate Ed25519 and X25519 private keys
392
- * from the seed. The same seed always produces the same identity (same DID).
393
- *
394
- * @param seed - Exactly 32 bytes of high-entropy key material.
395
- * @returns Full AgentIdentity or error.
396
- */
397
- export async function identityFromSeed(seed, opts) {
398
- if (seed.length !== 32)
399
- return err('INVALID_KEY_LENGTH');
400
- try {
401
- // Import seed as HKDF base key
402
- const baseKey = await crypto.subtle.importKey('raw', toArrayBuffer(seed), 'HKDF', false, ['deriveBits']);
403
- // Derive 32 bytes for Ed25519
404
- const edBits = new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(32), info: new TextEncoder().encode('ed25519') }, baseKey, 256));
405
- // Derive 32 bytes for X25519
406
- const x25519Bits = new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(32), info: new TextEncoder().encode('x25519') }, baseKey, 256));
407
- // Derive 64 bytes for ML-KEM-768
408
- const mlKemBits = new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(32), info: new TextEncoder().encode('ml-kem-768') }, baseKey, 512));
409
- // Wrap as PKCS8 and import
410
- const edPkcs8 = new Uint8Array(ED25519_PKCS8_PREFIX.length + edBits.length);
411
- edPkcs8.set(ED25519_PKCS8_PREFIX);
412
- edPkcs8.set(edBits, ED25519_PKCS8_PREFIX.length);
413
- const x25519Pkcs8 = new Uint8Array(X25519_PKCS8_PREFIX.length + x25519Bits.length);
414
- x25519Pkcs8.set(X25519_PKCS8_PREFIX);
415
- x25519Pkcs8.set(x25519Bits, X25519_PKCS8_PREFIX.length);
416
- // Generate deterministic ML-KEM-768 keypair from derived seed (always-on)
417
- let mlKemPublicKey;
418
- let mlKemSecretKey;
419
- try {
420
- // Use deterministic key generation from 64-byte seed (FIPS 203 compliant)
421
- const mlkem = await createMlKem768();
422
- const [publicKey, secretKey] = mlkem.deriveKeyPair(mlKemBits);
423
- mlKemPublicKey = publicKey;
424
- mlKemSecretKey = secretKey;
425
- }
426
- catch (err) {
427
- console.warn('[xBind] ML-KEM-768 keygen failed, using classical crypto only:', err);
428
- }
429
- // Generate ML-DSA-65 keypair only when opt-in flag is set
430
- let mlDsaSecretKey;
431
- let mlDsaPublicKey;
432
- if (opts?.postQuantumSig) {
433
- try {
434
- const mlDsaBits = new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(32), info: new TextEncoder().encode('ml-dsa-65') }, baseKey, 256));
435
- // Import seed and generate deterministic keypair
436
- const privateKey = await mldsa.importKey('raw-seed', mlDsaBits, 'ML-DSA-65', true, ['sign']);
437
- const publicKey = await mldsa.getPublicKey(privateKey, ['verify']);
438
- const publicKeyRaw = await mldsa.exportKey('raw-public', publicKey);
439
- mlDsaPublicKey = new Uint8Array(publicKeyRaw);
440
- mlDsaSecretKey = mlDsaBits; // Store the seed for later use
441
- }
442
- catch (err) {
443
- console.warn('[xBind] ML-DSA-65 keygen failed, using classical crypto only:', err);
444
- }
445
- }
446
- return importIdentity(edPkcs8, x25519Pkcs8, mlKemSecretKey, mlKemPublicKey, mlDsaSecretKey, mlDsaPublicKey);
447
- }
448
- catch {
449
- return err('KEYGEN_FAILED');
450
- }
451
- }
452
- /**
453
- * Extract the raw 32-byte Ed25519 private key from a PKCS8 DER blob.
454
- *
455
- * Strips the 16-byte ASN.1 header. Validates prefix matches Ed25519 OID.
456
- *
457
- * @param pkcs8 - 48-byte PKCS8 DER for Ed25519.
458
- * @returns 32-byte raw private key or error.
459
- */
460
- export function extractRawEd25519(pkcs8) {
461
- if (pkcs8.length !== ED25519_PKCS8_PREFIX.length + 32) {
462
- return err('INVALID_KEY_LENGTH');
463
- }
464
- for (let i = 0; i < ED25519_PKCS8_PREFIX.length; i++) {
465
- if (pkcs8[i] !== ED25519_PKCS8_PREFIX[i])
466
- return err('IMPORT_FAILED');
467
- }
468
- return ok(pkcs8.slice(ED25519_PKCS8_PREFIX.length));
469
- }
470
- /**
471
- * Extract the raw 32-byte X25519 private key from a PKCS8 DER blob.
472
- *
473
- * Strips the 16-byte ASN.1 header. Validates prefix matches X25519 OID.
474
- *
475
- * @param pkcs8 - 48-byte PKCS8 DER for X25519.
476
- * @returns 32-byte raw private key or error.
477
- */
478
- export function extractRawX25519(pkcs8) {
479
- if (pkcs8.length !== X25519_PKCS8_PREFIX.length + 32) {
480
- return err('INVALID_KEY_LENGTH');
481
- }
482
- for (let i = 0; i < X25519_PKCS8_PREFIX.length; i++) {
483
- if (pkcs8[i] !== X25519_PKCS8_PREFIX[i])
484
- return err('IMPORT_FAILED');
485
- }
486
- return ok(pkcs8.slice(X25519_PKCS8_PREFIX.length));
487
- }
488
- /* ── Key Rotation (ROT-1) ── */
489
- /**
490
- * Rotate ML-KEM + X25519 keys while preserving old keys for decryption.
491
- *
492
- * Generates new X25519 and ML-KEM-768 keypairs. Saves the old keys
493
- * in rotatedKeys array (with timestamp) for backward-compatible decryption
494
- * of messages encrypted with the old keys. Ed25519 keys (for signing) are
495
- * NOT rotated — they remain constant for persistent identity.
496
- *
497
- * After rotation:
498
- * - New messages use the new X25519 + ML-KEM keys
499
- * - Old messages decrypt using preserved rotatedKeys
500
- * - DID remains unchanged (anchored to Ed25519 public key)
501
- * - Registry must be updated with new X25519 + ML-KEM public keys
502
- *
503
- * @param identity - Current identity with keys to rotate
504
- * @returns Updated identity with new keys + old keys in rotatedKeys array, or error
505
- *
506
- * @example
507
- * ```ts
508
- * const rotated = await identity.rotateKeys();
509
- * if (rotated.ok) {
510
- * // New keys are active; old keys preserved for decryption
511
- * console.log('Rotated at:', rotated.value.rotatedKeys?.[0]?.rotatedAt);
512
- * // Update registry with new X25519 + ML-KEM public keys
513
- * await registry.updateKeys(rotated.value.did, rotated.value.rawX25519PublicKey, rotated.value.mlKemPublicKey);
514
- * }
515
- * ```
516
- */
517
- export async function rotateKeys(identity) {
518
- try {
519
- // Preserve old keys in rotatedKeys array
520
- const oldRotatedKeys = identity.rotatedKeys ?? [];
521
- const currentRotation = {
522
- rotatedAt: Date.now(),
523
- x25519PrivateKey: identity.x25519PrivateKey,
524
- mlKemSecretKey: identity.mlKemSecretKey,
525
- };
526
- // Generate new X25519 keypair for forward secrecy
527
- // SAFETY: X25519 generateKey always returns CryptoKeyPair
528
- const newX25519Pair = await crypto.subtle.generateKey({ name: 'X25519' }, true, ['deriveBits']);
529
- const newRawX25519Pub = new Uint8Array(await crypto.subtle.exportKey('raw', newX25519Pair.publicKey));
530
- // Generate new ML-KEM-768 keypair (only if original identity had ML-KEM)
531
- let newMlKemPublicKey;
532
- let newMlKemSecretKey;
533
- if (identity.mlKemPublicKey || identity.mlKemSecretKey) {
534
- try {
535
- const mlkem = await createMlKem768();
536
- const [publicKey, secretKey] = mlkem.generateKeyPair();
537
- newMlKemPublicKey = publicKey;
538
- newMlKemSecretKey = secretKey;
539
- }
540
- catch (err) {
541
- console.warn('[xBind] ML-KEM-768 rotation failed, using X25519 only:', err);
542
- }
543
- }
544
- // Preserve rotation history (keep up to 10 old key sets for decryption)
545
- const maxRotationHistory = 10;
546
- const rotatedKeys = [
547
- currentRotation,
548
- ...oldRotatedKeys,
549
- ].slice(0, maxRotationHistory);
550
- return ok({
551
- did: identity.did,
552
- publicKey: identity.publicKey,
553
- privateKey: identity.privateKey,
554
- rawPublicKey: identity.rawPublicKey,
555
- x25519PrivateKey: newX25519Pair.privateKey,
556
- x25519PublicKey: newX25519Pair.publicKey,
557
- rawX25519PublicKey: newRawX25519Pub,
558
- mlKemPublicKey: newMlKemPublicKey,
559
- mlKemSecretKey: newMlKemSecretKey,
560
- mlDsaPublicKey: identity.mlDsaPublicKey,
561
- mlDsaSecretKey: identity.mlDsaSecretKey,
562
- rotatedKeys,
563
- });
564
- }
565
- catch {
566
- return err('ROTATION_FAILED');
567
- }
568
- }
569
- /* ── Base58btc (internal) ── */
570
- /** Encode bytes to base58btc string. */
571
- function base58btcEncode(bytes) {
572
- let zeros = 0;
573
- for (const b of bytes) {
574
- if (b !== 0)
575
- break;
576
- zeros++;
577
- }
578
- let num = 0n;
579
- for (const b of bytes) {
580
- num = num * 256n + BigInt(b);
581
- }
582
- const chars = [];
583
- while (num > 0n) {
584
- const ch = BASE58_ALPHABET[Number(num % 58n)];
585
- if (ch !== undefined)
586
- chars.unshift(ch);
587
- num = num / 58n;
588
- }
589
- for (let i = 0; i < zeros; i++) {
590
- chars.unshift('1');
591
- }
592
- return chars.join('');
593
- }
594
- /** Decode base58btc string to bytes. */
595
- function base58btcDecode(str) {
596
- let zeros = 0;
597
- for (const c of str) {
598
- if (c !== '1')
599
- break;
600
- zeros++;
601
- }
602
- let num = 0n;
603
- for (const c of str) {
604
- const idx = BASE58_ALPHABET.indexOf(c);
605
- if (idx === -1)
606
- throw new Error('Invalid base58 character');
607
- num = num * 58n + BigInt(idx);
608
- }
609
- if (num === 0n)
610
- return new Uint8Array(zeros);
611
- const hex = num.toString(16);
612
- const paddedHex = hex.length % 2 ? '0' + hex : hex;
613
- const byteLen = paddedHex.length / 2;
614
- const result = new Uint8Array(zeros + byteLen);
615
- for (let i = 0; i < byteLen; i++) {
616
- result[zeros + i] = parseInt(paddedHex.slice(i * 2, i * 2 + 2), 16);
617
- }
618
- return result;
619
- }
1
+ import{ok,err}from"./_deps/shared/index.js";import{fromBase64Url}from"./crypto-utils.js";import{createMlKem768}from"mlkem";import mldsa from"./_deps/mldsa-wasm/dist/mldsa.js";const ED25519_MULTICODEC=new Uint8Array([237,1]),BASE58_ALPHABET="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function toArrayBuffer(e){const r=new ArrayBuffer(e.byteLength);return new Uint8Array(r).set(e),r}export async function generateIdentity(e){try{const r=await crypto.subtle.generateKey("Ed25519",!0,["sign","verify"]),t=new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey)),n=publicKeyToDid(t),a=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"]),i=new Uint8Array(await crypto.subtle.exportKey("raw",a.publicKey));let o,c,y,s;try{const e=await createMlKem768(),[r,t]=e.generateKeyPair();o=r,c=t}catch(e){console.warn("[xBind] ML-KEM-768 keygen failed, using classical crypto only:",e)}if(e?.postQuantumSig)try{const e=await mldsa.generateKey("ML-DSA-65",!0,["sign","verify"]),r=await mldsa.exportKey("raw-public",e.publicKey),t=await mldsa.exportKey("raw-seed",e.privateKey);y=new Uint8Array(r),s=new Uint8Array(t)}catch(e){console.warn("[xBind] ML-DSA-65 keygen failed, using classical crypto only:",e)}return ok({did:n,publicKey:r.publicKey,privateKey:r.privateKey,rawPublicKey:t,x25519PrivateKey:a.privateKey,x25519PublicKey:a.publicKey,rawX25519PublicKey:i,...o?{mlKemPublicKey:o}:{},...c?{mlKemSecretKey:c}:{},...y?{mlDsaPublicKey:y}:{},...s?{mlDsaSecretKey:s}:{}})}catch{return err("KEYGEN_FAILED")}}export async function sign(e,r){try{const t=new Uint8Array(await crypto.subtle.sign("Ed25519",e,toArrayBuffer(r)));return ok(t)}catch{return err("SIGN_FAILED")}}export async function verify(e,r,t){try{const n=await crypto.subtle.verify("Ed25519",e,toArrayBuffer(r),toArrayBuffer(t));return ok(n)}catch{return err("VERIFY_FAILED")}}export async function importPublicKey(e){if(32!==e.length)return err("INVALID_KEY_LENGTH");try{const r=await crypto.subtle.importKey("raw",toArrayBuffer(e),"Ed25519",!0,["verify"]);return ok(r)}catch{return err("KEYGEN_FAILED")}}export function publicKeyToDid(e){const r=new Uint8Array(2+e.length);return r.set(ED25519_MULTICODEC),r.set(e,2),`did:key:z${base58btcEncode(r)}`}export function didToPublicKeyBytes(e){if(!e.startsWith("did:key:z"))return err("INVALID_DID");try{const r=base58btcDecode(e.slice(9));return 237!==r[0]||1!==r[1]||34!==r.length?err("INVALID_DID"):ok(r.slice(2))}catch{return err("INVALID_DID")}}export async function exportPKCS8(e){try{const r=await crypto.subtle.exportKey("pkcs8",e);return ok(new Uint8Array(r))}catch{return err("EXPORT_FAILED")}}export async function exportX25519PKCS8(e){try{const r=await crypto.subtle.exportKey("pkcs8",e);return ok(new Uint8Array(r))}catch{return err("EXPORT_FAILED")}}export async function importFromPKCS8(e){try{const r=await crypto.subtle.importKey("pkcs8",toArrayBuffer(e),"Ed25519",!0,["sign"]),t=await crypto.subtle.exportKey("jwk",r);if(!t.x)return err("IMPORT_FAILED");const n=fromBase64Url(t.x),a=await crypto.subtle.importKey("raw",toArrayBuffer(n),"Ed25519",!0,["verify"]),i=publicKeyToDid(n),o=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"]),c=new Uint8Array(await crypto.subtle.exportKey("raw",o.publicKey));return ok({did:i,publicKey:a,privateKey:r,rawPublicKey:n,x25519PrivateKey:o.privateKey,x25519PublicKey:o.publicKey,rawX25519PublicKey:c})}catch{return err("IMPORT_FAILED")}}export async function importIdentity(e,r,t,n,a,i){try{const o=await crypto.subtle.importKey("pkcs8",toArrayBuffer(e),"Ed25519",!0,["sign"]),c=await crypto.subtle.exportKey("jwk",o);if(!c.x)return err("IMPORT_FAILED");const y=fromBase64Url(c.x),s=await crypto.subtle.importKey("raw",toArrayBuffer(y),"Ed25519",!0,["verify"]),l=publicKeyToDid(y),u=await crypto.subtle.importKey("pkcs8",toArrayBuffer(r),{name:"X25519"},!0,["deriveBits"]),K=await crypto.subtle.exportKey("jwk",u);if(!K.x)return err("IMPORT_FAILED");const p=fromBase64Url(K.x),f=await crypto.subtle.importKey("raw",toArrayBuffer(p),{name:"X25519"},!0,[]);return ok({did:l,publicKey:s,privateKey:o,rawPublicKey:y,x25519PrivateKey:u,x25519PublicKey:f,rawX25519PublicKey:p,...t?{mlKemSecretKey:t}:{},...n?{mlKemPublicKey:n}:{},...a?{mlDsaSecretKey:a}:{},...i?{mlDsaPublicKey:i}:{}})}catch{return err("IMPORT_FAILED")}}export function exportMlKemSecretKey(e){return e.mlKemSecretKey}export function exportMlKemPublicKey(e){return e.mlKemPublicKey}export const ML_DSA65_SIG_BYTES=3309;export const ML_DSA65_PK_BYTES=1952;export const ML_DSA65_SK_BYTES=32;export async function signMlDsa65(e,r){try{const t=await mldsa.importKey("raw-seed",toArrayBuffer(e),"ML-DSA-65",!1,["sign"]),n=await mldsa.sign("ML-DSA-65",t,toArrayBuffer(r));return ok(new Uint8Array(n))}catch{return err("SIGN_FAILED")}}export async function verifyMlDsa65(e,r,t){try{const n=await mldsa.importKey("raw-public",toArrayBuffer(e),"ML-DSA-65",!1,["verify"]),a=await mldsa.verify("ML-DSA-65",n,toArrayBuffer(r),toArrayBuffer(t));return ok(a)}catch{return err("VERIFY_FAILED")}}export function exportMlDsaSecretKey(e){return e.mlDsaSecretKey}export function exportMlDsaPublicKey(e){return e.mlDsaPublicKey}const ED25519_PKCS8_PREFIX=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),X25519_PKCS8_PREFIX=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);export async function identityFromSeed(e,r){if(32!==e.length)return err("INVALID_KEY_LENGTH");try{const t=await crypto.subtle.importKey("raw",toArrayBuffer(e),"HKDF",!1,["deriveBits"]),n=new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(32),info:(new TextEncoder).encode("ed25519")},t,256)),a=new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(32),info:(new TextEncoder).encode("x25519")},t,256)),i=new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(32),info:(new TextEncoder).encode("ml-kem-768")},t,512)),o=new Uint8Array(ED25519_PKCS8_PREFIX.length+n.length);o.set(ED25519_PKCS8_PREFIX),o.set(n,ED25519_PKCS8_PREFIX.length);const c=new Uint8Array(X25519_PKCS8_PREFIX.length+a.length);let y,s,l,u;c.set(X25519_PKCS8_PREFIX),c.set(a,X25519_PKCS8_PREFIX.length);try{const e=await createMlKem768(),[r,t]=e.deriveKeyPair(i);y=r,s=t}catch(e){console.warn("[xBind] ML-KEM-768 keygen failed, using classical crypto only:",e)}if(r?.postQuantumSig)try{const e=new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(32),info:(new TextEncoder).encode("ml-dsa-65")},t,256)),r=await mldsa.importKey("raw-seed",e,"ML-DSA-65",!0,["sign"]),n=await mldsa.getPublicKey(r,["verify"]),a=await mldsa.exportKey("raw-public",n);u=new Uint8Array(a),l=e}catch(e){console.warn("[xBind] ML-DSA-65 keygen failed, using classical crypto only:",e)}return importIdentity(o,c,s,y,l,u)}catch{return err("KEYGEN_FAILED")}}export function extractRawEd25519(e){if(e.length!==ED25519_PKCS8_PREFIX.length+32)return err("INVALID_KEY_LENGTH");for(let r=0;r<ED25519_PKCS8_PREFIX.length;r++)if(e[r]!==ED25519_PKCS8_PREFIX[r])return err("IMPORT_FAILED");return ok(e.slice(ED25519_PKCS8_PREFIX.length))}export function extractRawX25519(e){if(e.length!==X25519_PKCS8_PREFIX.length+32)return err("INVALID_KEY_LENGTH");for(let r=0;r<X25519_PKCS8_PREFIX.length;r++)if(e[r]!==X25519_PKCS8_PREFIX[r])return err("IMPORT_FAILED");return ok(e.slice(X25519_PKCS8_PREFIX.length))}export async function rotateKeys(e){try{const r=e.rotatedKeys??[],t={rotatedAt:Date.now(),x25519PrivateKey:e.x25519PrivateKey,mlKemSecretKey:e.mlKemSecretKey},n=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"]),a=new Uint8Array(await crypto.subtle.exportKey("raw",n.publicKey));let i,o;if(e.mlKemPublicKey||e.mlKemSecretKey)try{const e=await createMlKem768(),[r,t]=e.generateKeyPair();i=r,o=t}catch(e){console.warn("[xBind] ML-KEM-768 rotation failed, using X25519 only:",e)}const c=[t,...r].slice(0,10);return ok({did:e.did,publicKey:e.publicKey,privateKey:e.privateKey,rawPublicKey:e.rawPublicKey,x25519PrivateKey:n.privateKey,x25519PublicKey:n.publicKey,rawX25519PublicKey:a,mlKemPublicKey:i,mlKemSecretKey:o,mlDsaPublicKey:e.mlDsaPublicKey,mlDsaSecretKey:e.mlDsaSecretKey,rotatedKeys:c})}catch{return err("ROTATION_FAILED")}}function base58btcEncode(e){let r=0;for(const t of e){if(0!==t)break;r++}let t=0n;for(const r of e)t=256n*t+BigInt(r);const n=[];for(;t>0n;){const e=BASE58_ALPHABET[Number(t%58n)];void 0!==e&&n.unshift(e),t/=58n}for(let e=0;e<r;e++)n.unshift("1");return n.join("")}function base58btcDecode(e){let r=0;for(const t of e){if("1"!==t)break;r++}let t=0n;for(const r of e){const e=BASE58_ALPHABET.indexOf(r);if(-1===e)throw new Error("Invalid base58 character");t=58n*t+BigInt(e)}if(0n===t)return new Uint8Array(r);const n=t.toString(16),a=n.length%2?"0"+n:n,i=a.length/2,o=new Uint8Array(r+i);for(let e=0;e<i;e++)o[r+e]=parseInt(a.slice(2*e,2*e+2),16);return o}