@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,52 +1 @@
1
- /**
2
- * Error Response Types
3
- *
4
- * Dual-code error response system supporting both AWS standard codes
5
- * and legacy xBind codes for backward compatibility.
6
- *
7
- * @packageDocumentation
8
- */
9
- /**
10
- * Type guard to check if a value is an ErrorResponse
11
- *
12
- * @param value - Value to check
13
- * @returns True if value is an ErrorResponse
14
- *
15
- * @example
16
- * ```typescript
17
- * if (isErrorResponse(result)) {
18
- * console.error(result.message);
19
- * }
20
- * ```
21
- */
22
- export function isErrorResponse(value) {
23
- if (!value || typeof value !== 'object') {
24
- return false;
25
- }
26
- const err = value;
27
- return (typeof err.code === 'string' &&
28
- typeof err.httpStatus === 'number' &&
29
- typeof err.message === 'string');
30
- }
31
- /**
32
- * Create a standardized error response
33
- *
34
- * @param params - Error response parameters
35
- * @returns Standardized ErrorResponse object
36
- *
37
- * @example
38
- * ```typescript
39
- * const error = createErrorResponse({
40
- * code: 'UnauthorizedException',
41
- * legacyCode: 'XBIND_AUTH_FAILED',
42
- * httpStatus: 401,
43
- * message: 'Invalid signature'
44
- * });
45
- * ```
46
- */
47
- export function createErrorResponse(params) {
48
- return {
49
- ...params,
50
- timestamp: params.timestamp ?? Date.now()
51
- };
52
- }
1
+ export function isErrorResponse(t){if(!t||"object"!=typeof t)return!1;const e=t;return"string"==typeof e.code&&"number"==typeof e.httpStatus&&"string"==typeof e.message}export function createErrorResponse(t){return{...t,timestamp:t.timestamp??Date.now()}}
@@ -1,174 +1 @@
1
- /**
2
- * @module vault-auth
3
- * DID-based authentication for Vault Store API requests.
4
- *
5
- * Implements Ed25519 signature over canonical request representation with:
6
- * - Timestamp (prevents replay attacks >5min old)
7
- * - Nonce (prevents duplicate requests)
8
- * - Request body hash (ensures integrity)
9
- *
10
- * Server verifies signature + timestamp + nonce before serving vault content.
11
- */
12
- import { ok, err } from"./_deps/shared/index.js";
13
- import { toBase64 } from './crypto-utils.js';
14
- /**
15
- * Sign a vault store API request with agent's DID identity.
16
- *
17
- * Creates canonical request representation:
18
- * ```
19
- * {method}\n{endpoint}\n{timestamp}\n{nonce}\n{bodyHash}
20
- * ```
21
- *
22
- * Server verifies:
23
- * 1. Signature matches DID public key
24
- * 2. Timestamp within ±5min (prevents replay)
25
- * 3. Nonce not seen before (prevents duplicate)
26
- * 4. Body hash matches (ensures integrity)
27
- *
28
- * @param identity - Agent identity (contains signing key)
29
- * @param endpoint - API endpoint (e.g., "/api/vault-store/crypto")
30
- * @param body - Request body (JSON-serializable)
31
- * @returns Signed request metadata or error
32
- *
33
- * @example
34
- * ```typescript
35
- * const sigResult = await signVaultRequest(agent.identity, '/api/vault-store/crypto', {
36
- * requestedVersion: 'latest',
37
- * clientVersion: '1.5.0',
38
- * });
39
- *
40
- * if (!sigResult.ok) {
41
- * throw new Error('Failed to sign vault request');
42
- * }
43
- *
44
- * const { signature, timestamp, nonce } = sigResult.value;
45
- *
46
- * const response = await fetch('https://private.me/api/vault-store/crypto', {
47
- * method: 'POST',
48
- * headers: {
49
- * 'X-DID': agent.did,
50
- * 'X-Signature': signature,
51
- * 'X-Timestamp': timestamp.toString(),
52
- * 'X-Nonce': nonce,
53
- * },
54
- * body: JSON.stringify(body),
55
- * });
56
- * ```
57
- */
58
- export async function signVaultRequest(identity, endpoint, body) {
59
- const timestamp = Date.now();
60
- const nonce = generateNonce();
61
- // Canonical request representation
62
- const method = 'POST';
63
- const bodyJson = JSON.stringify(body);
64
- const bodyHash = await hashString(bodyJson);
65
- const canonical = `${method}\n${endpoint}\n${timestamp}\n${nonce}\n${bodyHash}`;
66
- // Sign with Ed25519
67
- let signatureBuffer;
68
- try {
69
- const encoder = new TextEncoder();
70
- const message = encoder.encode(canonical);
71
- signatureBuffer = await crypto.subtle.sign({ name: 'Ed25519' }, identity.privateKey, message);
72
- }
73
- catch {
74
- return err('SIGN_FAILED');
75
- }
76
- return ok({
77
- signature: toBase64(new Uint8Array(signatureBuffer)),
78
- timestamp,
79
- nonce,
80
- });
81
- }
82
- /**
83
- * Generate cryptographically secure nonce (UUID v4 format).
84
- *
85
- * @returns Random UUID string
86
- */
87
- function generateNonce() {
88
- // Use crypto.randomUUID if available (Node.js 16+, modern browsers)
89
- if (typeof crypto !== 'undefined' && crypto.randomUUID) {
90
- return crypto.randomUUID();
91
- }
92
- // Fallback: manual UUID v4 generation
93
- const bytes = new Uint8Array(16);
94
- crypto.getRandomValues(bytes);
95
- // Set version (4) and variant (RFC 4122)
96
- bytes[6] = (bytes[6] & 0x0f) | 0x40;
97
- bytes[8] = (bytes[8] & 0x3f) | 0x80;
98
- const hex = Array.from(bytes)
99
- .map((b) => b.toString(16).padStart(2, '0'))
100
- .join('');
101
- return [
102
- hex.slice(0, 8),
103
- hex.slice(8, 12),
104
- hex.slice(12, 16),
105
- hex.slice(16, 20),
106
- hex.slice(20, 32),
107
- ].join('-');
108
- }
109
- /**
110
- * Hash string with SHA-256 (for request body integrity).
111
- *
112
- * @param data - String to hash
113
- * @returns Base64-encoded hash
114
- */
115
- async function hashString(data) {
116
- const encoder = new TextEncoder();
117
- const bytes = encoder.encode(data);
118
- const hashBuffer = await crypto.subtle.digest('SHA-256', bytes);
119
- return toBase64(new Uint8Array(hashBuffer));
120
- }
121
- /**
122
- * Verify vault request signature (server-side only).
123
- *
124
- * Validates:
125
- * 1. Signature matches DID public key
126
- * 2. Timestamp within ±5min window
127
- * 3. Body hash matches
128
- *
129
- * Note: Nonce verification requires server-side nonce store (not implemented here).
130
- *
131
- * @param did - Sender DID
132
- * @param publicKeyBytes - Ed25519 public key (32 bytes)
133
- * @param endpoint - API endpoint
134
- * @param body - Request body (JSON string)
135
- * @param signature - Base64-encoded signature
136
- * @param timestamp - Request timestamp (Unix ms)
137
- * @param nonce - Request nonce
138
- * @returns True if signature is valid
139
- *
140
- * @internal Server-side verification only
141
- */
142
- export async function verifyVaultRequest(did, publicKeyBytes, endpoint, body, signature, timestamp, nonce) {
143
- // Timestamp verification (±5min window)
144
- const now = Date.now();
145
- const maxAge = 5 * 60 * 1000; // 5 minutes
146
- if (Math.abs(now - timestamp) > maxAge) {
147
- return false;
148
- }
149
- // Reconstruct canonical request
150
- const method = 'POST';
151
- const bodyHash = await hashString(body);
152
- const canonical = `${method}\n${endpoint}\n${timestamp}\n${nonce}\n${bodyHash}`;
153
- // Import public key
154
- let publicKey;
155
- try {
156
- // Copy to new ArrayBuffer to avoid SharedArrayBuffer issues
157
- const keyBuffer = new ArrayBuffer(publicKeyBytes.byteLength);
158
- new Uint8Array(keyBuffer).set(publicKeyBytes);
159
- publicKey = await crypto.subtle.importKey('raw', keyBuffer, { name: 'Ed25519' }, false, ['verify']);
160
- }
161
- catch {
162
- return false;
163
- }
164
- // Verify signature
165
- try {
166
- const encoder = new TextEncoder();
167
- const message = encoder.encode(canonical);
168
- const signatureBytes = Uint8Array.from(atob(signature), (c) => c.charCodeAt(0));
169
- return await crypto.subtle.verify({ name: 'Ed25519' }, publicKey, signatureBytes, message);
170
- }
171
- catch {
172
- return false;
173
- }
174
- }
1
+ import{ok,err}from"./_deps/shared/index.js";import{toBase64}from"./crypto-utils.js";export async function signVaultRequest(t,e,n){const r=Date.now(),a=generateNonce(),o=JSON.stringify(n),c=`POST\n${e}\n${r}\n${a}\n${await hashString(o)}`;let i;try{const e=(new TextEncoder).encode(c);i=await crypto.subtle.sign({name:"Ed25519"},t.privateKey,e)}catch{return err("SIGN_FAILED")}return ok({signature:toBase64(new Uint8Array(i)),timestamp:r,nonce:a})}function generateNonce(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(16);crypto.getRandomValues(t),t[6]=15&t[6]|64,t[8]=63&t[8]|128;const e=Array.from(t).map(t=>t.toString(16).padStart(2,"0")).join("");return[e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20,32)].join("-")}async function hashString(t){const e=(new TextEncoder).encode(t),n=await crypto.subtle.digest("SHA-256",e);return toBase64(new Uint8Array(n))}export async function verifyVaultRequest(t,e,n,r,a,o,c){const i=Date.now();if(Math.abs(i-o)>3e5)return!1;const s=`POST\n${n}\n${o}\n${c}\n${await hashString(r)}`;let y;try{const t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e),y=await crypto.subtle.importKey("raw",t,{name:"Ed25519"},!1,["verify"])}catch{return!1}try{const t=(new TextEncoder).encode(s),e=Uint8Array.from(atob(a),t=>t.charCodeAt(0));return await crypto.subtle.verify({name:"Ed25519"},y,e,t)}catch{return!1}}
@@ -108,3 +108,12 @@ export declare function getCacheStatus(): {
108
108
  expiresAt?: number;
109
109
  ttlRemaining?: number;
110
110
  };
111
+ /**
112
+ * Set mock crypto package for testing.
113
+ *
114
+ * @internal For test use only
115
+ * @param crypto - Mock crypto package
116
+ * @param version - Version identifier
117
+ * @param ttlMs - Cache TTL in milliseconds (default: 7 days)
118
+ */
119
+ export declare function setMockCrypto(crypto: CryptoPackage, version?: string, ttlMs?: number): void;
@@ -1,187 +1 @@
1
- /**
2
- * @module vault-store-loader
3
- * Runtime loader for payment-gated crypto packages (Full Control IP protection).
4
- *
5
- * Fetches XorIDA algorithm from EC2 Vault Store with:
6
- * - DID-based authentication (Ed25519 signatures)
7
- * - Usage quota verification (Free: 100K/month, Pro: unlimited)
8
- * - Memory caching (7-day TTL, session-only)
9
- * - Automatic re-fetch on expiration
10
- *
11
- * Security: Crypto package NEVER bundled in npm. Always fetched at runtime
12
- * with payment gate enforcement. Share 2 (Vault Store) completes algorithm.
13
- */
14
- import { ok, err } from"./_deps/shared/index.js";
15
- import { signVaultRequest } from './vault-auth.js';
16
- /** Vault Store API endpoint (EC2) */
17
- const VAULT_STORE_URL = process.env.VAULT_STORE_URL || 'https://private.me/api/vault-store';
18
- /** Cache TTL: 7 days (in milliseconds) */
19
- const CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
20
- /** In-memory cache (cleared on process restart) */
21
- let cryptoCache = null;
22
- /**
23
- * Load crypto package from Vault Store with authentication and caching.
24
- *
25
- * Flow:
26
- * 1. Check cache (if valid, return cached)
27
- * 2. Sign vault request with DID
28
- * 3. POST to /api/vault-store/crypto
29
- * 4. Server verifies: signature + quota + payment
30
- * 5. Receive crypto bundle + share2
31
- * 6. Evaluate bundle (dynamic import)
32
- * 7. Cache for 7 days
33
- *
34
- * @param identity - Agent identity (for DID signature)
35
- * @returns Crypto package exports or error
36
- *
37
- * @example
38
- * ```typescript
39
- * const cryptoResult = await loadCryptoPackage(agent.identity);
40
- * if (!cryptoResult.ok) {
41
- * if (cryptoResult.error === 'VAULT_QUOTA_EXCEEDED') {
42
- * console.error('Free tier quota exceeded. Upgrade to Pro for unlimited access.');
43
- * }
44
- * throw new Error(cryptoResult.error);
45
- * }
46
- * const { splitXorIDA, reconstructXorIDA } = cryptoResult.value;
47
- * ```
48
- */
49
- export async function loadCryptoPackage(identity) {
50
- // Check cache first
51
- if (cryptoCache && Date.now() < cryptoCache.expiresAt) {
52
- return ok(cryptoCache.module);
53
- }
54
- // Sign vault request
55
- const signatureResult = await signVaultRequest(identity, '/api/vault-store/crypto', {
56
- requestedVersion: 'latest',
57
- clientVersion: '1.5.0',
58
- });
59
- if (!signatureResult.ok) {
60
- return err('VAULT_AUTH_FAILED');
61
- }
62
- const { signature, timestamp, nonce } = signatureResult.value;
63
- // Fetch from vault store
64
- let response;
65
- try {
66
- response = await fetch(`${VAULT_STORE_URL}/crypto`, {
67
- method: 'POST',
68
- headers: {
69
- 'Content-Type': 'application/json',
70
- 'X-DID': identity.did,
71
- 'X-Signature': signature,
72
- 'X-Timestamp': timestamp.toString(),
73
- 'X-Nonce': nonce,
74
- },
75
- body: JSON.stringify({
76
- requestedVersion: 'latest',
77
- clientVersion: '1.5.0',
78
- }),
79
- });
80
- }
81
- catch (fetchError) {
82
- return err('VAULT_FETCH_FAILED');
83
- }
84
- // Handle error responses
85
- if (!response.ok) {
86
- if (response.status === 402) {
87
- // Payment Required - quota exceeded
88
- return err('VAULT_QUOTA_EXCEEDED');
89
- }
90
- else if (response.status === 401 || response.status === 403) {
91
- // Unauthorized / Forbidden
92
- return err('VAULT_AUTH_FAILED');
93
- }
94
- else if (response.status === 451) {
95
- // Unavailable For Legal Reasons - payment required
96
- return err('VAULT_PAYMENT_REQUIRED');
97
- }
98
- return err('VAULT_FETCH_FAILED');
99
- }
100
- // Parse response
101
- let vaultData;
102
- try {
103
- vaultData = (await response.json());
104
- }
105
- catch {
106
- return err('VAULT_INVALID_RESPONSE');
107
- }
108
- if (!vaultData.cryptoBundle || !vaultData.version) {
109
- return err('VAULT_INVALID_RESPONSE');
110
- }
111
- // Decode and evaluate bundle
112
- let cryptoModule;
113
- try {
114
- const bundleCode = atob(vaultData.cryptoBundle);
115
- // Dynamic evaluation (isolated scope)
116
- // eslint-disable-next-line no-eval
117
- const moduleExports = eval(`(function() {
118
- const exports = {};
119
- ${bundleCode}
120
- return exports;
121
- })()`);
122
- cryptoModule = moduleExports;
123
- // Validate required exports
124
- if (typeof cryptoModule.splitXorIDA !== 'function' ||
125
- typeof cryptoModule.reconstructXorIDA !== 'function') {
126
- return err('VAULT_LOAD_FAILED');
127
- }
128
- }
129
- catch {
130
- return err('VAULT_LOAD_FAILED');
131
- }
132
- // Cache for 7 days (or server-provided TTL)
133
- const ttlMs = vaultData.cacheTtl ? vaultData.cacheTtl * 1000 : CACHE_TTL_MS;
134
- cryptoCache = {
135
- module: cryptoModule,
136
- expiresAt: Date.now() + ttlMs,
137
- version: vaultData.version,
138
- };
139
- return ok(cryptoModule);
140
- }
141
- /**
142
- * Get cached crypto package without fetching.
143
- *
144
- * Returns null if cache is empty or expired.
145
- * Use loadCryptoPackage() to fetch and cache.
146
- *
147
- * @returns Cached crypto package or null
148
- */
149
- export function getCrypto() {
150
- if (cryptoCache && Date.now() < cryptoCache.expiresAt) {
151
- return cryptoCache.module;
152
- }
153
- return null;
154
- }
155
- /**
156
- * Check if crypto package is loaded and valid.
157
- *
158
- * @returns True if crypto is cached and not expired
159
- */
160
- export function isCryptoLoaded() {
161
- return cryptoCache !== null && Date.now() < cryptoCache.expiresAt;
162
- }
163
- /**
164
- * Clear crypto cache (force re-fetch on next load).
165
- *
166
- * Useful for testing or forcing quota re-verification.
167
- */
168
- export function clearCryptoCache() {
169
- cryptoCache = null;
170
- }
171
- /**
172
- * Get cache status (for debugging).
173
- *
174
- * @returns Cache metadata or null if empty
175
- */
176
- export function getCacheStatus() {
177
- if (!cryptoCache) {
178
- return { loaded: false };
179
- }
180
- const now = Date.now();
181
- return {
182
- loaded: now < cryptoCache.expiresAt,
183
- version: cryptoCache.version,
184
- expiresAt: cryptoCache.expiresAt,
185
- ttlRemaining: Math.max(0, cryptoCache.expiresAt - now),
186
- };
187
- }
1
+ import{ok,err}from"./_deps/shared/index.js";import{signVaultRequest}from"./vault-auth.js";const VAULT_STORE_URL=process.env.VAULT_STORE_URL||"https://private.me/api/vault-store",CACHE_TTL_MS=6048e5;let cryptoCache=null;export async function loadCryptoPackage(identity){if(cryptoCache&&Date.now()<cryptoCache.expiresAt)return ok(cryptoCache.module);const signatureResult=await signVaultRequest(identity,"/api/vault-store/crypto",{requestedVersion:"latest",clientVersion:"1.5.0"});if(!signatureResult.ok)return err("VAULT_AUTH_FAILED");const{signature:signature,timestamp:timestamp,nonce:nonce}=signatureResult.value;let response,vaultData,cryptoModule;try{response=await fetch(`${VAULT_STORE_URL}/crypto`,{method:"POST",headers:{"Content-Type":"application/json","X-DID":identity.did,"X-Signature":signature,"X-Timestamp":timestamp.toString(),"X-Nonce":nonce},body:JSON.stringify({requestedVersion:"latest",clientVersion:"1.5.0"})})}catch{return err("VAULT_FETCH_FAILED")}if(!response.ok)return 402===response.status?err("VAULT_QUOTA_EXCEEDED"):401===response.status||403===response.status?err("VAULT_AUTH_FAILED"):451===response.status?err("VAULT_PAYMENT_REQUIRED"):err("VAULT_FETCH_FAILED");try{vaultData=await response.json()}catch{return err("VAULT_INVALID_RESPONSE")}if(!vaultData.cryptoBundle||!vaultData.version)return err("VAULT_INVALID_RESPONSE");try{const bundleCode=atob(vaultData.cryptoBundle),moduleExports=eval(`(function() {\n const exports = {};\n ${bundleCode}\n return exports;\n })()`);if(cryptoModule=moduleExports,"function"!=typeof cryptoModule.splitXorIDA||"function"!=typeof cryptoModule.reconstructXorIDA)return err("VAULT_LOAD_FAILED")}catch{return err("VAULT_LOAD_FAILED")}const ttlMs=vaultData.cacheTtl?1e3*vaultData.cacheTtl:CACHE_TTL_MS;return cryptoCache={module:cryptoModule,expiresAt:Date.now()+ttlMs,version:vaultData.version},ok(cryptoModule)}export function getCrypto(){return cryptoCache&&Date.now()<cryptoCache.expiresAt?cryptoCache.module:null}export function isCryptoLoaded(){return null!==cryptoCache&&Date.now()<cryptoCache.expiresAt}export function clearCryptoCache(){cryptoCache=null}export function getCacheStatus(){if(!cryptoCache)return{loaded:!1};const t=Date.now();return{loaded:t<cryptoCache.expiresAt,version:cryptoCache.version,expiresAt:cryptoCache.expiresAt,ttlRemaining:Math.max(0,cryptoCache.expiresAt-t)}}export function setMockCrypto(t,e="mock-1.0.0",r=CACHE_TTL_MS){cryptoCache={module:t,expiresAt:Date.now()+r,version:e}}
@@ -1,16 +1 @@
1
- /**
2
- * @module verify
3
- * Lightweight sub-path export for verification-only use cases.
4
- *
5
- * Import as `@private.me/xbind/verify` for tree-shaking on edge/serverless:
6
- * ```ts
7
- * import { verify, importPublicKey, validateEnvelope } from '@private.me/xbind/verify';
8
- * ```
9
- *
10
- * This module re-exports only the functions needed to verify signatures
11
- * and validate envelopes — no key generation, no encryption, no transport.
12
- */
13
- // Identity — verify + key import only
14
- export { verify, importPublicKey, didToPublicKeyBytes } from './identity.js';
15
- // Envelope — validation + signed envelope verification
16
- export { validateEnvelope, deserializeEnvelope, openSignedEnvelope, } from './envelope.js';
1
+ export{verify,importPublicKey,didToPublicKeyBytes}from"./identity.js";export{validateEnvelope,deserializeEnvelope,openSignedEnvelope}from"./envelope.js";