@private.me/xbind 3.0.2 → 3.0.4

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 (222) hide show
  1. package/README.md +2366 -204
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  3. package/dist-standalone/_deps/shared/cjs/errors.js +1 -729
  4. package/dist-standalone/_deps/shared/cjs/index.js +1 -463
  5. package/dist-standalone/_deps/shared/cjs/types.js +1 -315
  6. package/dist-standalone/_deps/shared/errors.js +1 -244
  7. package/dist-standalone/_deps/shared/index.js +1 -72
  8. package/dist-standalone/_deps/shared/types.js +1 -86
  9. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  10. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  20. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  21. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  28. package/dist-standalone/_deps/xchange/errors.js +1 -1
  29. package/dist-standalone/_deps/xchange/index.js +1 -1
  30. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  31. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  32. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  33. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  34. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  40. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  41. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  42. package/dist-standalone/_deps/xregistry/index.js +1 -1
  43. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  44. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  45. package/dist-standalone/_deps/xregistry/types.js +1 -1
  46. package/dist-standalone/agent-call.d.ts +2 -2
  47. package/dist-standalone/agent-call.js +1 -659
  48. package/dist-standalone/agent-sdk.js +1 -328
  49. package/dist-standalone/agent.d.ts +2 -0
  50. package/dist-standalone/agent.js +1 -1800
  51. package/dist-standalone/approval.js +1 -193
  52. package/dist-standalone/async-iterators.d.ts +3 -3
  53. package/dist-standalone/async-iterators.js +1 -382
  54. package/dist-standalone/auth.js +1 -219
  55. package/dist-standalone/auto-accept.js +1 -229
  56. package/dist-standalone/backup-config.js +1 -201
  57. package/dist-standalone/backup.js +1 -326
  58. package/dist-standalone/batch-operations.js +1 -388
  59. package/dist-standalone/cancellation.js +1 -477
  60. package/dist-standalone/checkpoint.js +1 -186
  61. package/dist-standalone/circuit-breaker.js +1 -468
  62. package/dist-standalone/cjs/agent-call.js +1 -701
  63. package/dist-standalone/cjs/agent-sdk.js +1 -332
  64. package/dist-standalone/cjs/agent.js +1 -1837
  65. package/dist-standalone/cjs/approval.js +1 -199
  66. package/dist-standalone/cjs/async-iterators.js +1 -392
  67. package/dist-standalone/cjs/auth.js +1 -225
  68. package/dist-standalone/cjs/auto-accept.js +1 -233
  69. package/dist-standalone/cjs/backup-config.js +1 -207
  70. package/dist-standalone/cjs/backup.js +1 -330
  71. package/dist-standalone/cjs/batch-operations.js +1 -397
  72. package/dist-standalone/cjs/cancellation.js +1 -490
  73. package/dist-standalone/cjs/checkpoint.js +1 -193
  74. package/dist-standalone/cjs/circuit-breaker.js +1 -476
  75. package/dist-standalone/cjs/cli/init.js +1 -492
  76. package/dist-standalone/cjs/config-validation.js +1 -522
  77. package/dist-standalone/cjs/connect.js +1 -312
  78. package/dist-standalone/cjs/connection-pool.js +1 -506
  79. package/dist-standalone/cjs/correlation-id.js +1 -339
  80. package/dist-standalone/cjs/crypto-utils.js +1 -176
  81. package/dist-standalone/cjs/debug-mode.js +1 -534
  82. package/dist-standalone/cjs/did-document.js +1 -101
  83. package/dist-standalone/cjs/did-privateme.js +1 -130
  84. package/dist-standalone/cjs/did-web.js +1 -201
  85. package/dist-standalone/cjs/discovery.js +1 -462
  86. package/dist-standalone/cjs/dual-mode.js +1 -251
  87. package/dist-standalone/cjs/email-templates.js +1 -313
  88. package/dist-standalone/cjs/email-transport.js +1 -239
  89. package/dist-standalone/cjs/envelope.js +1 -538
  90. package/dist-standalone/cjs/errors.js +1 -913
  91. package/dist-standalone/cjs/event-emitter.js +1 -461
  92. package/dist-standalone/cjs/gateway-state.js +1 -55
  93. package/dist-standalone/cjs/gateway-transport.js +1 -120
  94. package/dist-standalone/cjs/graceful-degradation.js +1 -403
  95. package/dist-standalone/cjs/guardrails.js +1 -223
  96. package/dist-standalone/cjs/health-check.js +1 -336
  97. package/dist-standalone/cjs/http-compat.js +1 -272
  98. package/dist-standalone/cjs/http-status-map.js +1 -571
  99. package/dist-standalone/cjs/identity.js +1 -645
  100. package/dist-standalone/cjs/index.js +1 -406
  101. package/dist-standalone/cjs/invitation.js +1 -421
  102. package/dist-standalone/cjs/invite.js +1 -328
  103. package/dist-standalone/cjs/key-agreement.js +1 -335
  104. package/dist-standalone/cjs/lazy-init.js +1 -300
  105. package/dist-standalone/cjs/logger.js +1 -291
  106. package/dist-standalone/cjs/loopback-transport.js +1 -0
  107. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  108. package/dist-standalone/cjs/nonce-store.js +1 -80
  109. package/dist-standalone/cjs/pairing-manager.js +1 -223
  110. package/dist-standalone/cjs/plugin-system.js +1 -264
  111. package/dist-standalone/cjs/plugins/logging.js +1 -168
  112. package/dist-standalone/cjs/plugins/metrics.js +1 -181
  113. package/dist-standalone/cjs/plugins/validation.js +1 -302
  114. package/dist-standalone/cjs/policy.js +1 -320
  115. package/dist-standalone/cjs/progress-callbacks.js +1 -583
  116. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  117. package/dist-standalone/cjs/registry-middleware.js +1 -50
  118. package/dist-standalone/cjs/retry-strategies.js +1 -544
  119. package/dist-standalone/cjs/retry-transport.js +1 -102
  120. package/dist-standalone/cjs/runtime/browser.js +1 -533
  121. package/dist-standalone/cjs/runtime/edge.js +1 -526
  122. package/dist-standalone/cjs/runtime/react-native.js +1 -394
  123. package/dist-standalone/cjs/security-policy.js +1 -245
  124. package/dist-standalone/cjs/serialization.js +1 -1040
  125. package/dist-standalone/cjs/split-channel.js +1 -225
  126. package/dist-standalone/cjs/subscription-proof.js +1 -230
  127. package/dist-standalone/cjs/succession.js +1 -148
  128. package/dist-standalone/cjs/timeouts.js +1 -412
  129. package/dist-standalone/cjs/trace-context.js +1 -424
  130. package/dist-standalone/cjs/trace-spans.js +1 -495
  131. package/dist-standalone/cjs/transport.js +1 -63
  132. package/dist-standalone/cjs/trust-registry.js +1 -991
  133. package/dist-standalone/cjs/types/error-response.js +1 -56
  134. package/dist-standalone/cjs/vault-auth.js +1 -178
  135. package/dist-standalone/cjs/vault-store-loader.js +1 -194
  136. package/dist-standalone/cjs/verify.js +1 -25
  137. package/dist-standalone/cjs/version-info.js +1 -543
  138. package/dist-standalone/cjs/xfetch.js +1 -340
  139. package/dist-standalone/cli/init.js +1 -455
  140. package/dist-standalone/cli/setup.js +1 -514
  141. package/dist-standalone/cli/types.js +1 -27
  142. package/dist-standalone/cli/xbind.js +1 -148
  143. package/dist-standalone/config-validation.js +1 -513
  144. package/dist-standalone/connect.js +1 -274
  145. package/dist-standalone/connection-pool.js +1 -500
  146. package/dist-standalone/correlation-id.js +1 -326
  147. package/dist-standalone/crypto-utils.d.ts +2 -7
  148. package/dist-standalone/crypto-utils.js +1 -157
  149. package/dist-standalone/debug-mode.js +1 -510
  150. package/dist-standalone/did-document.js +1 -96
  151. package/dist-standalone/did-privateme.js +1 -121
  152. package/dist-standalone/did-web.js +1 -196
  153. package/dist-standalone/discovery.js +1 -458
  154. package/dist-standalone/dual-mode.js +1 -247
  155. package/dist-standalone/email-templates.js +1 -309
  156. package/dist-standalone/email-transport.d.ts +2 -2
  157. package/dist-standalone/email-transport.js +1 -232
  158. package/dist-standalone/envelope.js +1 -525
  159. package/dist-standalone/errors.d.ts +13 -3
  160. package/dist-standalone/errors.js +1 -896
  161. package/dist-standalone/event-emitter.js +1 -456
  162. package/dist-standalone/gateway-state.d.ts +1 -1
  163. package/dist-standalone/gateway-state.js +1 -51
  164. package/dist-standalone/gateway-transport.js +1 -116
  165. package/dist-standalone/graceful-degradation.js +1 -396
  166. package/dist-standalone/guardrails.js +1 -216
  167. package/dist-standalone/health-check.d.ts +5 -1
  168. package/dist-standalone/health-check.js +1 -332
  169. package/dist-standalone/http-compat.d.ts +1 -1
  170. package/dist-standalone/http-compat.js +1 -267
  171. package/dist-standalone/http-status-map.js +1 -561
  172. package/dist-standalone/identity.js +1 -619
  173. package/dist-standalone/index.d.ts +15 -4
  174. package/dist-standalone/index.js +1 -78
  175. package/dist-standalone/invitation.js +1 -415
  176. package/dist-standalone/invite.js +1 -324
  177. package/dist-standalone/key-agreement.js +1 -325
  178. package/dist-standalone/lazy-init.d.ts +11 -6
  179. package/dist-standalone/lazy-init.js +1 -295
  180. package/dist-standalone/logger.js +1 -285
  181. package/dist-standalone/loopback-transport.d.ts +87 -0
  182. package/dist-standalone/loopback-transport.js +1 -0
  183. package/dist-standalone/mdns-discovery.js +1 -195
  184. package/dist-standalone/nonce-store.js +1 -76
  185. package/dist-standalone/pairing-manager.js +1 -219
  186. package/dist-standalone/plugin-system.js +1 -257
  187. package/dist-standalone/plugins/logging.js +1 -163
  188. package/dist-standalone/plugins/metrics.d.ts +4 -4
  189. package/dist-standalone/plugins/metrics.js +1 -176
  190. package/dist-standalone/plugins/validation.js +1 -297
  191. package/dist-standalone/policy.js +1 -315
  192. package/dist-standalone/progress-callbacks.js +1 -576
  193. package/dist-standalone/redis-nonce-store.js +1 -72
  194. package/dist-standalone/registry-middleware.js +1 -47
  195. package/dist-standalone/retry-strategies.js +1 -534
  196. package/dist-standalone/retry-transport.js +1 -98
  197. package/dist-standalone/runtime/browser.js +1 -516
  198. package/dist-standalone/runtime/edge.js +1 -511
  199. package/dist-standalone/runtime/react-native.d.ts +1 -1
  200. package/dist-standalone/runtime/react-native.js +1 -383
  201. package/dist-standalone/security-policy.js +1 -239
  202. package/dist-standalone/serialization.js +1 -1031
  203. package/dist-standalone/split-channel.d.ts +1 -1
  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.d.ts +1 -1
  211. package/dist-standalone/transport.js +1 -59
  212. package/dist-standalone/trust-registry.d.ts +3 -3
  213. package/dist-standalone/trust-registry.js +1 -950
  214. package/dist-standalone/types/error-response.js +1 -52
  215. package/dist-standalone/vault-auth.js +1 -174
  216. package/dist-standalone/vault-store-loader.d.ts +9 -0
  217. package/dist-standalone/vault-store-loader.js +1 -187
  218. package/dist-standalone/verify.js +1 -16
  219. package/dist-standalone/version-info.js +1 -530
  220. package/dist-standalone/xfetch.js +1 -335
  221. package/package.json +1 -1
  222. package/share1.dat +0 -0
@@ -1,538 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createEnvelope = createEnvelope;
4
- exports.createEnvelopeV2 = createEnvelopeV2;
5
- exports.createEnvelopeV3 = createEnvelopeV3;
6
- exports.createEnvelopeV4 = createEnvelopeV4;
7
- exports.decryptPayload = decryptPayload;
8
- exports.serializeEnvelope = serializeEnvelope;
9
- exports.deserializeEnvelope = deserializeEnvelope;
10
- exports.validateEnvelope = validateEnvelope;
11
- exports.generateSharedKey = generateSharedKey;
12
- exports.createSignedEnvelope = createSignedEnvelope;
13
- exports.openSignedEnvelope = openSignedEnvelope;
14
- const shared_1 = require("../_deps/shared/index.js");
15
- const crypto_utils_js_1 = require("./crypto-utils.js");
16
- const identity_js_1 = require("./identity.js");
17
- /* ── Constants ── */
18
- const NONCE_BYTES = 16;
19
- const AES_IV_BYTES = 12;
20
- const AES_ALGO = 'AES-GCM';
21
- /** ML-KEM-768 ciphertext length in bytes. */
22
- const KEM_CIPHERTEXT_BYTES = 1088;
23
- /** ML-DSA-65 signature length in bytes. */
24
- const ML_DSA65_SIG_BYTES = 3309;
25
- /* ── Helpers ── */
26
- /** Copy Uint8Array to fresh ArrayBuffer. */
27
- function toArrayBuffer(data) {
28
- const buf = new ArrayBuffer(data.byteLength);
29
- new Uint8Array(buf).set(data);
30
- return buf;
31
- }
32
- /**
33
- * Create canonical representation of envelope fields for signing.
34
- *
35
- * SECURITY FIX (v1.1.3): Sign ALL envelope metadata (nonce, timestamp, sender,
36
- * recipient, scope, payload) to prevent replay attacks via nonce substitution.
37
- *
38
- * Previous versions only signed the payload, allowing attackers to:
39
- * 1. Capture an envelope
40
- * 2. Change the nonce to a fresh value
41
- * 3. Replay the message (signature still verified)
42
- *
43
- * Canonical format: UTF-8 JSON with sorted keys, no whitespace.
44
- * Example: {"alg":"Ed25519","nonce":"...","payload":"...","recipient":"...","scope":"...","sender":"...","timestamp":1234567890,"v":1}
45
- */
46
- function createSignedData(envelope) {
47
- // Create canonical JSON representation (sorted keys)
48
- const canonical = JSON.stringify({
49
- v: envelope.v,
50
- alg: envelope.alg,
51
- sender: envelope.sender,
52
- recipient: envelope.recipient,
53
- timestamp: envelope.timestamp,
54
- nonce: envelope.nonce,
55
- scope: envelope.scope,
56
- payload: envelope.payload,
57
- });
58
- return new TextEncoder().encode(canonical);
59
- }
60
- /* ── Envelope Creation ── */
61
- /**
62
- * Create a signed, encrypted TransportEnvelope (version 1).
63
- *
64
- * Encrypt-then-sign: AES-256-GCM encrypts payload, Ed25519 signs ciphertext.
65
- * All envelope metadata (nonce, timestamp, sender, recipient, scope) is included
66
- * in the signature to prevent replay attacks.
67
- *
68
- * @param opts - Envelope creation options
69
- * @returns Result containing the envelope or error
70
- *
71
- * @example
72
- * ```typescript
73
- * import { createEnvelope, generateSharedKey } from '@private.me/xbind';
74
- *
75
- * // Generate shared key (typically from ECDH key agreement)
76
- * const sharedKey = await generateSharedKey(senderDid, recipientDid);
77
- * if (!sharedKey.ok) throw new Error(sharedKey.error);
78
- *
79
- * // Create encrypted envelope
80
- * const envelope = await createEnvelope({
81
- * sender: 'did:key:z6Mk...',
82
- * recipient: 'did:key:z6Mk...',
83
- * plaintext: new TextEncoder().encode(JSON.stringify({ message: 'Hello' })),
84
- * sharedKey: sharedKey.value,
85
- * privateKey: senderPrivateKey,
86
- * scope: 'read:messages'
87
- * });
88
- *
89
- * if (envelope.ok) {
90
- * console.log('Envelope created:', envelope.value);
91
- * }
92
- * ```
93
- */
94
- async function createEnvelope(opts) {
95
- const nonce = new Uint8Array(NONCE_BYTES);
96
- crypto.getRandomValues(nonce);
97
- const iv = new Uint8Array(AES_IV_BYTES);
98
- crypto.getRandomValues(iv);
99
- let ciphertext;
100
- try {
101
- const encrypted = await crypto.subtle.encrypt({ name: AES_ALGO, iv: toArrayBuffer(iv) }, opts.sharedKey, toArrayBuffer(opts.plaintext));
102
- const ivAndCipher = new Uint8Array(iv.length + encrypted.byteLength);
103
- ivAndCipher.set(iv);
104
- ivAndCipher.set(new Uint8Array(encrypted), iv.length);
105
- ciphertext = ivAndCipher;
106
- }
107
- catch {
108
- return (0, shared_1.err)('ENCRYPT_FAILED');
109
- }
110
- // SECURITY FIX (v1.1.3): Sign canonical representation of ENTIRE envelope
111
- // (not just payload) to prevent replay attacks via nonce substitution
112
- const timestamp = Date.now();
113
- const envelopeFields = {
114
- v: 1,
115
- alg: 'Ed25519',
116
- sender: opts.senderDid,
117
- recipient: opts.recipientDid,
118
- timestamp,
119
- nonce: (0, crypto_utils_js_1.toBase64)(nonce),
120
- scope: opts.scope,
121
- payload: (0, crypto_utils_js_1.toBase64)(ciphertext),
122
- };
123
- const signedData = createSignedData(envelopeFields);
124
- const sigResult = await (0, identity_js_1.sign)(opts.privateKey, signedData);
125
- if (!sigResult.ok)
126
- return (0, shared_1.err)('SIGN_FAILED');
127
- const envelope = {
128
- ...envelopeFields,
129
- signature: (0, crypto_utils_js_1.toBase64)(sigResult.value),
130
- ...(opts.ephemeralPublicKey
131
- ? { ephemeralPub: (0, crypto_utils_js_1.toBase64)(opts.ephemeralPublicKey) }
132
- : {}),
133
- ...(opts.shareIndex !== undefined
134
- ? {
135
- shareIndex: opts.shareIndex,
136
- shareTotal: opts.shareTotal,
137
- shareThreshold: opts.shareThreshold,
138
- shareGroupId: opts.shareGroupId,
139
- shareHmacKey: opts.shareHmacKey,
140
- shareHmacSig: opts.shareHmacSig,
141
- }
142
- : {}),
143
- protocol: 'PRIVATE.ME/xBind/v3',
144
- documentationUrl: 'https://private.me/docs/xbind.html',
145
- };
146
- return (0, shared_1.ok)(envelope);
147
- }
148
- /* ── V2 Envelope Creation ── */
149
- /**
150
- * Create a signed, encrypted TransportEnvelopeV2 with hybrid KEM.
151
- *
152
- * Same encrypt-then-sign as v1, but includes ML-KEM-768 ciphertext.
153
- */
154
- async function createEnvelopeV2(opts) {
155
- const nonce = new Uint8Array(NONCE_BYTES);
156
- crypto.getRandomValues(nonce);
157
- const iv = new Uint8Array(AES_IV_BYTES);
158
- crypto.getRandomValues(iv);
159
- let ciphertext;
160
- try {
161
- const encrypted = await crypto.subtle.encrypt({ name: AES_ALGO, iv: toArrayBuffer(iv) }, opts.sharedKey, toArrayBuffer(opts.plaintext));
162
- const ivAndCipher = new Uint8Array(iv.length + encrypted.byteLength);
163
- ivAndCipher.set(iv);
164
- ivAndCipher.set(new Uint8Array(encrypted), iv.length);
165
- ciphertext = ivAndCipher;
166
- }
167
- catch {
168
- return (0, shared_1.err)('ENCRYPT_FAILED');
169
- }
170
- // SECURITY FIX (v1.1.3): Sign canonical representation of ENTIRE envelope
171
- const timestamp = Date.now();
172
- const envelopeFields = {
173
- v: 2,
174
- alg: 'Ed25519',
175
- sender: opts.senderDid,
176
- recipient: opts.recipientDid,
177
- timestamp,
178
- nonce: (0, crypto_utils_js_1.toBase64)(nonce),
179
- scope: opts.scope,
180
- payload: (0, crypto_utils_js_1.toBase64)(ciphertext),
181
- };
182
- const signedData = createSignedData(envelopeFields);
183
- const sigResult = await (0, identity_js_1.sign)(opts.privateKey, signedData);
184
- if (!sigResult.ok)
185
- return (0, shared_1.err)('SIGN_FAILED');
186
- const envelope = {
187
- ...envelopeFields,
188
- kem: 'X25519-MLKEM768',
189
- signature: (0, crypto_utils_js_1.toBase64)(sigResult.value),
190
- ephemeralPub: (0, crypto_utils_js_1.toBase64)(opts.ephemeralPublicKey),
191
- kemCiphertext: (0, crypto_utils_js_1.toBase64)(opts.kemCiphertext),
192
- ...(opts.shareIndex !== undefined
193
- ? {
194
- shareIndex: opts.shareIndex,
195
- shareTotal: opts.shareTotal,
196
- shareThreshold: opts.shareThreshold,
197
- shareGroupId: opts.shareGroupId,
198
- shareHmacKey: opts.shareHmacKey,
199
- shareHmacSig: opts.shareHmacSig,
200
- }
201
- : {}),
202
- protocol: 'PRIVATE.ME/xBind/v3',
203
- documentationUrl: 'https://private.me/docs/xbind.html',
204
- };
205
- return (0, shared_1.ok)(envelope);
206
- }
207
- /* ── V3 Envelope Creation ── */
208
- /**
209
- * Create a signed, encrypted TransportEnvelopeV3 with hybrid KEM + dual signatures.
210
- *
211
- * Encrypt-then-sign: AES-256-GCM encrypts payload, Ed25519 AND ML-DSA-65 sign ciphertext.
212
- * Both signatures must verify for the envelope to be accepted.
213
- */
214
- async function createEnvelopeV3(opts) {
215
- const nonce = new Uint8Array(NONCE_BYTES);
216
- crypto.getRandomValues(nonce);
217
- const iv = new Uint8Array(AES_IV_BYTES);
218
- crypto.getRandomValues(iv);
219
- let ciphertext;
220
- try {
221
- const encrypted = await crypto.subtle.encrypt({ name: AES_ALGO, iv: toArrayBuffer(iv) }, opts.sharedKey, toArrayBuffer(opts.plaintext));
222
- const ivAndCipher = new Uint8Array(iv.length + encrypted.byteLength);
223
- ivAndCipher.set(iv);
224
- ivAndCipher.set(new Uint8Array(encrypted), iv.length);
225
- ciphertext = ivAndCipher;
226
- }
227
- catch {
228
- return (0, shared_1.err)('ENCRYPT_FAILED');
229
- }
230
- // SECURITY FIX (v1.1.3): Sign canonical representation of ENTIRE envelope
231
- const timestamp = Date.now();
232
- const envelopeFields = {
233
- v: 3,
234
- alg: 'Ed25519',
235
- sender: opts.senderDid,
236
- recipient: opts.recipientDid,
237
- timestamp,
238
- nonce: (0, crypto_utils_js_1.toBase64)(nonce),
239
- scope: opts.scope,
240
- payload: (0, crypto_utils_js_1.toBase64)(ciphertext),
241
- };
242
- const signedData = createSignedData(envelopeFields);
243
- const sigResult = await (0, identity_js_1.sign)(opts.privateKey, signedData);
244
- if (!sigResult.ok)
245
- return (0, shared_1.err)('SIGN_FAILED');
246
- const pqSigResult = await (0, identity_js_1.signMlDsa65)(opts.mlDsaSecretKey, signedData);
247
- if (!pqSigResult.ok)
248
- return (0, shared_1.err)('PQ_SIGN_FAILED');
249
- const envelope = {
250
- ...envelopeFields,
251
- sig: 'Ed25519+MLDSA65',
252
- kem: 'X25519-MLKEM768',
253
- signature: (0, crypto_utils_js_1.toBase64)(sigResult.value),
254
- pqSignature: (0, crypto_utils_js_1.toBase64)(pqSigResult.value),
255
- ephemeralPub: (0, crypto_utils_js_1.toBase64)(opts.ephemeralPublicKey),
256
- kemCiphertext: (0, crypto_utils_js_1.toBase64)(opts.kemCiphertext),
257
- ...(opts.shareIndex !== undefined
258
- ? {
259
- shareIndex: opts.shareIndex,
260
- shareTotal: opts.shareTotal,
261
- shareThreshold: opts.shareThreshold,
262
- shareGroupId: opts.shareGroupId,
263
- shareHmacKey: opts.shareHmacKey,
264
- shareHmacSig: opts.shareHmacSig,
265
- }
266
- : {}),
267
- protocol: 'PRIVATE.ME/xBind/v3',
268
- documentationUrl: 'https://private.me/docs/xbind.html',
269
- };
270
- return (0, shared_1.ok)(envelope);
271
- }
272
- /* ── Xchange Mode Envelope Creation ── */
273
- /**
274
- * Create a signed Xchange mode envelope (v4 wire format).
275
- *
276
- * Opt-in performance mode. No encryption — the share IS the payload.
277
- * Ed25519 signs the raw share data for sender authentication.
278
- * The XorIDA split provides confidentiality (information-theoretic).
279
- */
280
- async function createEnvelopeV4(opts) {
281
- const nonce = new Uint8Array(NONCE_BYTES);
282
- crypto.getRandomValues(nonce);
283
- // SECURITY FIX (v1.1.3): Sign canonical representation of ENTIRE envelope
284
- const timestamp = Date.now();
285
- const envelopeFields = {
286
- v: 4,
287
- alg: 'Ed25519',
288
- sender: opts.senderDid,
289
- recipient: opts.recipientDid,
290
- timestamp,
291
- nonce: (0, crypto_utils_js_1.toBase64)(nonce),
292
- scope: opts.scope,
293
- payload: (0, crypto_utils_js_1.toBase64)(opts.shareData),
294
- };
295
- const signedData = createSignedData(envelopeFields);
296
- const sigResult = await (0, identity_js_1.sign)(opts.privateKey, signedData);
297
- if (!sigResult.ok)
298
- return (0, shared_1.err)('SIGN_FAILED');
299
- const envelope = {
300
- ...envelopeFields,
301
- kem: 'Xchange',
302
- signature: (0, crypto_utils_js_1.toBase64)(sigResult.value),
303
- shareIndex: opts.shareIndex,
304
- shareTotal: opts.shareTotal,
305
- shareThreshold: opts.shareThreshold,
306
- shareGroupId: opts.shareGroupId,
307
- shareHmacKey: opts.shareHmacKey,
308
- shareHmacSig: opts.shareHmacSig,
309
- protocol: 'PRIVATE.ME/xBind/v3',
310
- documentationUrl: 'https://private.me/docs/xbind.html',
311
- };
312
- return (0, shared_1.ok)(envelope);
313
- }
314
- /* ── Decryption ── */
315
- /**
316
- * Decrypt the payload from a v1, v2, or v3 TransportEnvelope.
317
- * Caller must verify signature before calling this.
318
- */
319
- async function decryptPayload(envelope, sharedKey) {
320
- try {
321
- const ciphertext = (0, crypto_utils_js_1.fromBase64)(envelope.payload);
322
- const iv = ciphertext.slice(0, AES_IV_BYTES);
323
- const data = ciphertext.slice(AES_IV_BYTES);
324
- const decrypted = await crypto.subtle.decrypt({ name: AES_ALGO, iv: toArrayBuffer(iv) }, sharedKey, toArrayBuffer(data));
325
- return (0, shared_1.ok)(new Uint8Array(decrypted));
326
- }
327
- catch {
328
- return (0, shared_1.err)('DECRYPT_FAILED');
329
- }
330
- }
331
- /* ── Serialization ── */
332
- /** Serialize envelope to UTF-8 bytes. */
333
- function serializeEnvelope(envelope) {
334
- return new TextEncoder().encode(JSON.stringify(envelope));
335
- }
336
- /** Deserialize bytes to a validated v1 or v2 TransportEnvelope. */
337
- function deserializeEnvelope(bytes) {
338
- let parsed;
339
- try {
340
- parsed = JSON.parse(new TextDecoder().decode(bytes));
341
- }
342
- catch {
343
- return (0, shared_1.err)('PARSE_FAILED');
344
- }
345
- return validateEnvelope(parsed);
346
- }
347
- /* ── Validation ── */
348
- /** Validate a parsed object is a valid v1 or v2 TransportEnvelope. */
349
- function validateEnvelope(obj) {
350
- if (typeof obj !== 'object' || obj === null)
351
- return (0, shared_1.err)('PARSE_FAILED');
352
- const e = obj;
353
- if (e['v'] !== 1 && e['v'] !== 2 && e['v'] !== 3 && e['v'] !== 4)
354
- return (0, shared_1.err)('INVALID_VERSION');
355
- if (e['alg'] !== 'Ed25519')
356
- return (0, shared_1.err)('INVALID_ALG');
357
- if (typeof e['sender'] !== 'string' || !e['sender'].startsWith('did:'))
358
- return (0, shared_1.err)('INVALID_DID');
359
- if (typeof e['recipient'] !== 'string' || !e['recipient'].startsWith('did:'))
360
- return (0, shared_1.err)('INVALID_DID');
361
- if (typeof e['timestamp'] !== 'number')
362
- return (0, shared_1.err)('INVALID_FIELDS');
363
- if (typeof e['scope'] !== 'string')
364
- return (0, shared_1.err)('INVALID_FIELDS');
365
- if (typeof e['payload'] !== 'string')
366
- return (0, shared_1.err)('INVALID_FIELDS');
367
- if (typeof e['signature'] !== 'string')
368
- return (0, shared_1.err)('INVALID_FIELDS');
369
- if (typeof e['nonce'] !== 'string')
370
- return (0, shared_1.err)('INVALID_NONCE');
371
- try {
372
- const nonceBytes = (0, crypto_utils_js_1.fromBase64)(e['nonce']);
373
- if (nonceBytes.length !== NONCE_BYTES)
374
- return (0, shared_1.err)('INVALID_NONCE');
375
- }
376
- catch {
377
- return (0, shared_1.err)('INVALID_NONCE');
378
- }
379
- if (e['ephemeralPub'] !== undefined && typeof e['ephemeralPub'] !== 'string') {
380
- return (0, shared_1.err)('INVALID_FIELDS');
381
- }
382
- // V2-specific validation
383
- if (e['v'] === 2) {
384
- if (e['kem'] !== 'X25519-MLKEM768')
385
- return (0, shared_1.err)('INVALID_KEM');
386
- if (typeof e['ephemeralPub'] !== 'string')
387
- return (0, shared_1.err)('INVALID_FIELDS');
388
- if (typeof e['kemCiphertext'] !== 'string')
389
- return (0, shared_1.err)('INVALID_FIELDS');
390
- try {
391
- const kemBytes = (0, crypto_utils_js_1.fromBase64)(e['kemCiphertext']);
392
- if (kemBytes.length !== KEM_CIPHERTEXT_BYTES)
393
- return (0, shared_1.err)('INVALID_FIELDS');
394
- }
395
- catch {
396
- return (0, shared_1.err)('INVALID_FIELDS');
397
- }
398
- }
399
- // V3-specific validation (hybrid KEM + dual signatures)
400
- if (e['v'] === 3) {
401
- if (e['sig'] !== 'Ed25519+MLDSA65')
402
- return (0, shared_1.err)('INVALID_ALG');
403
- if (e['kem'] !== 'X25519-MLKEM768')
404
- return (0, shared_1.err)('INVALID_KEM');
405
- if (typeof e['ephemeralPub'] !== 'string')
406
- return (0, shared_1.err)('INVALID_FIELDS');
407
- if (typeof e['kemCiphertext'] !== 'string')
408
- return (0, shared_1.err)('INVALID_FIELDS');
409
- if (typeof e['pqSignature'] !== 'string')
410
- return (0, shared_1.err)('INVALID_FIELDS');
411
- try {
412
- const kemBytes = (0, crypto_utils_js_1.fromBase64)(e['kemCiphertext']);
413
- if (kemBytes.length !== KEM_CIPHERTEXT_BYTES)
414
- return (0, shared_1.err)('INVALID_FIELDS');
415
- }
416
- catch {
417
- return (0, shared_1.err)('INVALID_FIELDS');
418
- }
419
- try {
420
- const pqSigBytes = (0, crypto_utils_js_1.fromBase64)(e['pqSignature']);
421
- if (pqSigBytes.length !== ML_DSA65_SIG_BYTES)
422
- return (0, shared_1.err)('INVALID_FIELDS');
423
- }
424
- catch {
425
- return (0, shared_1.err)('INVALID_FIELDS');
426
- }
427
- }
428
- // V4-specific validation (Xchange — no encryption, share metadata required)
429
- if (e['v'] === 4) {
430
- if (e['kem'] !== 'Xchange')
431
- return (0, shared_1.err)('INVALID_KEM');
432
- if (typeof e['shareIndex'] !== 'number')
433
- return (0, shared_1.err)('INVALID_FIELDS');
434
- if (typeof e['shareTotal'] !== 'number')
435
- return (0, shared_1.err)('INVALID_FIELDS');
436
- if (typeof e['shareThreshold'] !== 'number')
437
- return (0, shared_1.err)('INVALID_FIELDS');
438
- if (typeof e['shareGroupId'] !== 'string')
439
- return (0, shared_1.err)('INVALID_FIELDS');
440
- if (typeof e['shareHmacKey'] !== 'string')
441
- return (0, shared_1.err)('INVALID_FIELDS');
442
- if (typeof e['shareHmacSig'] !== 'string')
443
- return (0, shared_1.err)('INVALID_FIELDS');
444
- return (0, shared_1.ok)(e);
445
- }
446
- if (e['shareIndex'] !== undefined && typeof e['shareIndex'] !== 'number') {
447
- return (0, shared_1.err)('INVALID_FIELDS');
448
- }
449
- if (e['shareTotal'] !== undefined && typeof e['shareTotal'] !== 'number') {
450
- return (0, shared_1.err)('INVALID_FIELDS');
451
- }
452
- if (e['shareThreshold'] !== undefined && typeof e['shareThreshold'] !== 'number') {
453
- return (0, shared_1.err)('INVALID_FIELDS');
454
- }
455
- if (e['shareGroupId'] !== undefined && typeof e['shareGroupId'] !== 'string') {
456
- return (0, shared_1.err)('INVALID_FIELDS');
457
- }
458
- if (e['shareHmacKey'] !== undefined && typeof e['shareHmacKey'] !== 'string') {
459
- return (0, shared_1.err)('INVALID_FIELDS');
460
- }
461
- if (e['shareHmacSig'] !== undefined && typeof e['shareHmacSig'] !== 'string') {
462
- return (0, shared_1.err)('INVALID_FIELDS');
463
- }
464
- return (0, shared_1.ok)(e);
465
- }
466
- /** Generate an AES-256-GCM key for envelope encryption. */
467
- async function generateSharedKey() {
468
- return crypto.subtle.generateKey({ name: AES_ALGO, length: 256 }, true, ['encrypt', 'decrypt']);
469
- }
470
- /* ── Signed (Unencrypted) Envelopes ── */
471
- /**
472
- * Create a signed but unencrypted TransportEnvelope.
473
- *
474
- * Payload is base64-encoded plaintext (NOT encrypted).
475
- * Signature covers the raw plaintext bytes.
476
- * Use for public announcements, audit logs, or telemetry where
477
- * confidentiality is not required but integrity is.
478
- *
479
- * @param opts - Sender, recipient, scope, plaintext, and signing key.
480
- * @returns Signed envelope or error.
481
- */
482
- async function createSignedEnvelope(opts) {
483
- const nonce = new Uint8Array(NONCE_BYTES);
484
- crypto.getRandomValues(nonce);
485
- const timestamp = Date.now();
486
- const payloadBase64 = (0, crypto_utils_js_1.toBase64)(opts.plaintext);
487
- const nonceBase64 = (0, crypto_utils_js_1.toBase64)(nonce);
488
- // SECURITY FIX (v1.1.3): Sign canonical representation of ENTIRE envelope
489
- // (not just payload) to prevent replay attacks via nonce/timestamp mutation
490
- const envelopeFields = {
491
- v: 1,
492
- alg: 'Ed25519',
493
- sender: opts.senderDid,
494
- recipient: opts.recipientDid,
495
- timestamp,
496
- nonce: nonceBase64,
497
- scope: opts.scope,
498
- payload: payloadBase64,
499
- };
500
- const signedData = createSignedData(envelopeFields);
501
- const sigResult = await (0, identity_js_1.sign)(opts.privateKey, signedData);
502
- if (!sigResult.ok)
503
- return (0, shared_1.err)('SIGN_FAILED');
504
- const envelope = {
505
- ...envelopeFields,
506
- signature: (0, crypto_utils_js_1.toBase64)(sigResult.value),
507
- };
508
- return (0, shared_1.ok)(envelope);
509
- }
510
- /**
511
- * Verify signature on a signed (unencrypted) envelope and return plaintext.
512
- *
513
- * @param envelope - The signed envelope to verify.
514
- * @param senderPublicKey - The sender's Ed25519 public key.
515
- * @returns Plaintext bytes if signature is valid, error otherwise.
516
- */
517
- async function openSignedEnvelope(envelope, senderPublicKey) {
518
- const payloadBytes = (0, crypto_utils_js_1.fromBase64)(envelope.payload);
519
- const sigBytes = (0, crypto_utils_js_1.fromBase64)(envelope.signature);
520
- // SECURITY FIX (v1.1.3): Verify canonical representation (not just payload)
521
- const canonicalData = JSON.stringify({
522
- v: envelope.v,
523
- alg: envelope.alg,
524
- sender: envelope.sender,
525
- recipient: envelope.recipient,
526
- timestamp: envelope.timestamp,
527
- nonce: envelope.nonce,
528
- scope: envelope.scope,
529
- payload: envelope.payload,
530
- });
531
- const canonicalBytes = new TextEncoder().encode(canonicalData);
532
- const valid = await (0, identity_js_1.verify)(senderPublicKey, sigBytes, canonicalBytes);
533
- if (!valid.ok)
534
- return (0, shared_1.err)('VERIFY_FAILED');
535
- if (!valid.value)
536
- return (0, shared_1.err)('VERIFY_FAILED');
537
- return (0, shared_1.ok)(payloadBytes);
538
- }
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createEnvelope=createEnvelope,exports.createEnvelopeV2=createEnvelopeV2,exports.createEnvelopeV3=createEnvelopeV3,exports.createEnvelopeV4=createEnvelopeV4,exports.decryptPayload=decryptPayload,exports.serializeEnvelope=serializeEnvelope,exports.deserializeEnvelope=deserializeEnvelope,exports.validateEnvelope=validateEnvelope,exports.generateSharedKey=generateSharedKey,exports.createSignedEnvelope=createSignedEnvelope,exports.openSignedEnvelope=openSignedEnvelope;const shared_1=require("../_deps/shared/index.js"),crypto_utils_js_1=require("./crypto-utils.js"),identity_js_1=require("./identity.js"),NONCE_BYTES=16,AES_IV_BYTES=12,AES_ALGO="AES-GCM",KEM_CIPHERTEXT_BYTES=1088,ML_DSA65_SIG_BYTES=3309;function toArrayBuffer(e){const r=new ArrayBuffer(e.byteLength);return new Uint8Array(r).set(e),r}function createSignedData(e){const r=JSON.stringify({v:e.v,alg:e.alg,sender:e.sender,recipient:e.recipient,timestamp:e.timestamp,nonce:e.nonce,scope:e.scope,payload:e.payload});return(new TextEncoder).encode(r)}async function createEnvelope(e){const r=new Uint8Array(NONCE_BYTES);crypto.getRandomValues(r);const t=new Uint8Array(AES_IV_BYTES);let a;crypto.getRandomValues(t);try{const r=await crypto.subtle.encrypt({name:AES_ALGO,iv:toArrayBuffer(t)},e.sharedKey,toArrayBuffer(e.plaintext)),s=new Uint8Array(t.length+r.byteLength);s.set(t),s.set(new Uint8Array(r),t.length),a=s}catch{return(0,shared_1.err)("ENCRYPT_FAILED")}const s=Date.now(),n={v:1,alg:"Ed25519",sender:e.senderDid,recipient:e.recipientDid,timestamp:s,nonce:(0,crypto_utils_js_1.toBase64)(r),scope:e.scope,payload:(0,crypto_utils_js_1.toBase64)(a)},o=createSignedData(n),i=await(0,identity_js_1.sign)(e.privateKey,o);if(!i.ok)return(0,shared_1.err)("SIGN_FAILED");const _={...n,signature:(0,crypto_utils_js_1.toBase64)(i.value),...e.ephemeralPublicKey?{ephemeralPub:(0,crypto_utils_js_1.toBase64)(e.ephemeralPublicKey)}:{},...void 0!==e.shareIndex?{shareIndex:e.shareIndex,shareTotal:e.shareTotal,shareThreshold:e.shareThreshold,shareGroupId:e.shareGroupId,shareHmacKey:e.shareHmacKey,shareHmacSig:e.shareHmacSig}:{},protocol:"PRIVATE.ME/xBind/v3",documentationUrl:"https://private.me/docs/xbind.html"};return(0,shared_1.ok)(_)}async function createEnvelopeV2(e){const r=new Uint8Array(NONCE_BYTES);crypto.getRandomValues(r);const t=new Uint8Array(AES_IV_BYTES);let a;crypto.getRandomValues(t);try{const r=await crypto.subtle.encrypt({name:AES_ALGO,iv:toArrayBuffer(t)},e.sharedKey,toArrayBuffer(e.plaintext)),s=new Uint8Array(t.length+r.byteLength);s.set(t),s.set(new Uint8Array(r),t.length),a=s}catch{return(0,shared_1.err)("ENCRYPT_FAILED")}const s=Date.now(),n={v:2,alg:"Ed25519",sender:e.senderDid,recipient:e.recipientDid,timestamp:s,nonce:(0,crypto_utils_js_1.toBase64)(r),scope:e.scope,payload:(0,crypto_utils_js_1.toBase64)(a)},o=createSignedData(n),i=await(0,identity_js_1.sign)(e.privateKey,o);if(!i.ok)return(0,shared_1.err)("SIGN_FAILED");const _={...n,kem:"X25519-MLKEM768",signature:(0,crypto_utils_js_1.toBase64)(i.value),ephemeralPub:(0,crypto_utils_js_1.toBase64)(e.ephemeralPublicKey),kemCiphertext:(0,crypto_utils_js_1.toBase64)(e.kemCiphertext),...void 0!==e.shareIndex?{shareIndex:e.shareIndex,shareTotal:e.shareTotal,shareThreshold:e.shareThreshold,shareGroupId:e.shareGroupId,shareHmacKey:e.shareHmacKey,shareHmacSig:e.shareHmacSig}:{},protocol:"PRIVATE.ME/xBind/v3",documentationUrl:"https://private.me/docs/xbind.html"};return(0,shared_1.ok)(_)}async function createEnvelopeV3(e){const r=new Uint8Array(NONCE_BYTES);crypto.getRandomValues(r);const t=new Uint8Array(AES_IV_BYTES);let a;crypto.getRandomValues(t);try{const r=await crypto.subtle.encrypt({name:AES_ALGO,iv:toArrayBuffer(t)},e.sharedKey,toArrayBuffer(e.plaintext)),s=new Uint8Array(t.length+r.byteLength);s.set(t),s.set(new Uint8Array(r),t.length),a=s}catch{return(0,shared_1.err)("ENCRYPT_FAILED")}const s=Date.now(),n={v:3,alg:"Ed25519",sender:e.senderDid,recipient:e.recipientDid,timestamp:s,nonce:(0,crypto_utils_js_1.toBase64)(r),scope:e.scope,payload:(0,crypto_utils_js_1.toBase64)(a)},o=createSignedData(n),i=await(0,identity_js_1.sign)(e.privateKey,o);if(!i.ok)return(0,shared_1.err)("SIGN_FAILED");const _=await(0,identity_js_1.signMlDsa65)(e.mlDsaSecretKey,o);if(!_.ok)return(0,shared_1.err)("PQ_SIGN_FAILED");const c={...n,sig:"Ed25519+MLDSA65",kem:"X25519-MLKEM768",signature:(0,crypto_utils_js_1.toBase64)(i.value),pqSignature:(0,crypto_utils_js_1.toBase64)(_.value),ephemeralPub:(0,crypto_utils_js_1.toBase64)(e.ephemeralPublicKey),kemCiphertext:(0,crypto_utils_js_1.toBase64)(e.kemCiphertext),...void 0!==e.shareIndex?{shareIndex:e.shareIndex,shareTotal:e.shareTotal,shareThreshold:e.shareThreshold,shareGroupId:e.shareGroupId,shareHmacKey:e.shareHmacKey,shareHmacSig:e.shareHmacSig}:{},protocol:"PRIVATE.ME/xBind/v3",documentationUrl:"https://private.me/docs/xbind.html"};return(0,shared_1.ok)(c)}async function createEnvelopeV4(e){const r=new Uint8Array(NONCE_BYTES);crypto.getRandomValues(r);const t=Date.now(),a={v:4,alg:"Ed25519",sender:e.senderDid,recipient:e.recipientDid,timestamp:t,nonce:(0,crypto_utils_js_1.toBase64)(r),scope:e.scope,payload:(0,crypto_utils_js_1.toBase64)(e.shareData)},s=createSignedData(a),n=await(0,identity_js_1.sign)(e.privateKey,s);if(!n.ok)return(0,shared_1.err)("SIGN_FAILED");const o={...a,kem:"Xchange",signature:(0,crypto_utils_js_1.toBase64)(n.value),shareIndex:e.shareIndex,shareTotal:e.shareTotal,shareThreshold:e.shareThreshold,shareGroupId:e.shareGroupId,shareHmacKey:e.shareHmacKey,shareHmacSig:e.shareHmacSig,protocol:"PRIVATE.ME/xBind/v3",documentationUrl:"https://private.me/docs/xbind.html"};return(0,shared_1.ok)(o)}async function decryptPayload(e,r){try{const t=(0,crypto_utils_js_1.fromBase64)(e.payload),a=t.slice(0,AES_IV_BYTES),s=t.slice(AES_IV_BYTES),n=await crypto.subtle.decrypt({name:AES_ALGO,iv:toArrayBuffer(a)},r,toArrayBuffer(s));return(0,shared_1.ok)(new Uint8Array(n))}catch{return(0,shared_1.err)("DECRYPT_FAILED")}}function serializeEnvelope(e){return(new TextEncoder).encode(JSON.stringify(e))}function deserializeEnvelope(e){let r;try{r=JSON.parse((new TextDecoder).decode(e))}catch{return(0,shared_1.err)("PARSE_FAILED")}return validateEnvelope(r)}function validateEnvelope(e){if("object"!=typeof e||null===e)return(0,shared_1.err)("PARSE_FAILED");const r=e;if(1!==r.v&&2!==r.v&&3!==r.v&&4!==r.v)return(0,shared_1.err)("INVALID_VERSION");if("Ed25519"!==r.alg)return(0,shared_1.err)("INVALID_ALG");if("string"!=typeof r.sender||!r.sender.startsWith("did:"))return(0,shared_1.err)("INVALID_DID");if("string"!=typeof r.recipient||!r.recipient.startsWith("did:"))return(0,shared_1.err)("INVALID_DID");if("number"!=typeof r.timestamp)return(0,shared_1.err)("INVALID_FIELDS");if("string"!=typeof r.scope)return(0,shared_1.err)("INVALID_FIELDS");if("string"!=typeof r.payload)return(0,shared_1.err)("INVALID_FIELDS");if("string"!=typeof r.signature)return(0,shared_1.err)("INVALID_FIELDS");if("string"!=typeof r.nonce)return(0,shared_1.err)("INVALID_NONCE");try{if((0,crypto_utils_js_1.fromBase64)(r.nonce).length!==NONCE_BYTES)return(0,shared_1.err)("INVALID_NONCE")}catch{return(0,shared_1.err)("INVALID_NONCE")}if(void 0!==r.ephemeralPub&&"string"!=typeof r.ephemeralPub)return(0,shared_1.err)("INVALID_FIELDS");if(2===r.v){if("X25519-MLKEM768"!==r.kem)return(0,shared_1.err)("INVALID_KEM");if("string"!=typeof r.ephemeralPub)return(0,shared_1.err)("INVALID_FIELDS");if("string"!=typeof r.kemCiphertext)return(0,shared_1.err)("INVALID_FIELDS");try{if((0,crypto_utils_js_1.fromBase64)(r.kemCiphertext).length!==KEM_CIPHERTEXT_BYTES)return(0,shared_1.err)("INVALID_FIELDS")}catch{return(0,shared_1.err)("INVALID_FIELDS")}}if(3===r.v){if("Ed25519+MLDSA65"!==r.sig)return(0,shared_1.err)("INVALID_ALG");if("X25519-MLKEM768"!==r.kem)return(0,shared_1.err)("INVALID_KEM");if("string"!=typeof r.ephemeralPub)return(0,shared_1.err)("INVALID_FIELDS");if("string"!=typeof r.kemCiphertext)return(0,shared_1.err)("INVALID_FIELDS");if("string"!=typeof r.pqSignature)return(0,shared_1.err)("INVALID_FIELDS");try{if((0,crypto_utils_js_1.fromBase64)(r.kemCiphertext).length!==KEM_CIPHERTEXT_BYTES)return(0,shared_1.err)("INVALID_FIELDS")}catch{return(0,shared_1.err)("INVALID_FIELDS")}try{if((0,crypto_utils_js_1.fromBase64)(r.pqSignature).length!==ML_DSA65_SIG_BYTES)return(0,shared_1.err)("INVALID_FIELDS")}catch{return(0,shared_1.err)("INVALID_FIELDS")}}return 4===r.v?"Xchange"!==r.kem?(0,shared_1.err)("INVALID_KEM"):"number"!=typeof r.shareIndex||"number"!=typeof r.shareTotal||"number"!=typeof r.shareThreshold||"string"!=typeof r.shareGroupId||"string"!=typeof r.shareHmacKey||"string"!=typeof r.shareHmacSig?(0,shared_1.err)("INVALID_FIELDS"):(0,shared_1.ok)(r):void 0!==r.shareIndex&&"number"!=typeof r.shareIndex||void 0!==r.shareTotal&&"number"!=typeof r.shareTotal||void 0!==r.shareThreshold&&"number"!=typeof r.shareThreshold||void 0!==r.shareGroupId&&"string"!=typeof r.shareGroupId||void 0!==r.shareHmacKey&&"string"!=typeof r.shareHmacKey||void 0!==r.shareHmacSig&&"string"!=typeof r.shareHmacSig?(0,shared_1.err)("INVALID_FIELDS"):(0,shared_1.ok)(r)}async function generateSharedKey(){return crypto.subtle.generateKey({name:AES_ALGO,length:256},!0,["encrypt","decrypt"])}async function createSignedEnvelope(e){const r=new Uint8Array(NONCE_BYTES);crypto.getRandomValues(r);const t=Date.now(),a=(0,crypto_utils_js_1.toBase64)(e.plaintext),s=(0,crypto_utils_js_1.toBase64)(r),n={v:1,alg:"Ed25519",sender:e.senderDid,recipient:e.recipientDid,timestamp:t,nonce:s,scope:e.scope,payload:a},o=createSignedData(n),i=await(0,identity_js_1.sign)(e.privateKey,o);if(!i.ok)return(0,shared_1.err)("SIGN_FAILED");const _={...n,signature:(0,crypto_utils_js_1.toBase64)(i.value)};return(0,shared_1.ok)(_)}async function openSignedEnvelope(e,r){const t=(0,crypto_utils_js_1.fromBase64)(e.payload),a=(0,crypto_utils_js_1.fromBase64)(e.signature),s=JSON.stringify({v:e.v,alg:e.alg,sender:e.sender,recipient:e.recipient,timestamp:e.timestamp,nonce:e.nonce,scope:e.scope,payload:e.payload}),n=(new TextEncoder).encode(s),o=await(0,identity_js_1.verify)(r,a,n);return o.ok&&o.value?(0,shared_1.ok)(t):(0,shared_1.err)("VERIFY_FAILED")}