@private.me/xbind 1.3.0 → 2.3.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 (305) hide show
  1. package/LICENSES.md +212 -0
  2. package/README.md +388 -6
  3. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  4. package/dist-standalone/_deps/shared/cjs/errors.js +1 -275
  5. package/dist-standalone/_deps/shared/cjs/index.js +1 -138
  6. package/dist-standalone/_deps/shared/cjs/types.js +1 -90
  7. package/dist-standalone/_deps/shared/errors.js +1 -262
  8. package/dist-standalone/_deps/shared/index.js +1 -77
  9. package/dist-standalone/_deps/shared/types.js +1 -91
  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.js +1 -642
  48. package/dist-standalone/agent-sdk.js +1 -328
  49. package/dist-standalone/agent.d.ts +95 -5
  50. package/dist-standalone/agent.js +1 -1545
  51. package/dist-standalone/approval.js +1 -193
  52. package/dist-standalone/async-iterators.d.ts +275 -0
  53. package/dist-standalone/async-iterators.js +1 -0
  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.d.ts +114 -0
  58. package/dist-standalone/backup.js +1 -0
  59. package/dist-standalone/batch-operations.d.ts +297 -0
  60. package/dist-standalone/batch-operations.js +1 -0
  61. package/dist-standalone/cancellation.d.ts +301 -0
  62. package/dist-standalone/cancellation.js +1 -0
  63. package/dist-standalone/checkpoint.js +1 -186
  64. package/dist-standalone/circuit-breaker.d.ts +351 -0
  65. package/dist-standalone/circuit-breaker.js +1 -0
  66. package/dist-standalone/cjs/agent-call.js +1 -651
  67. package/dist-standalone/cjs/agent-sdk.js +1 -332
  68. package/dist-standalone/cjs/agent.js +1 -1582
  69. package/dist-standalone/cjs/approval.js +1 -199
  70. package/dist-standalone/cjs/async-iterators.js +1 -0
  71. package/dist-standalone/cjs/auth.js +1 -225
  72. package/dist-standalone/cjs/auto-accept.js +1 -233
  73. package/dist-standalone/cjs/backup-config.js +1 -207
  74. package/dist-standalone/cjs/backup.js +1 -0
  75. package/dist-standalone/cjs/batch-operations.js +1 -0
  76. package/dist-standalone/cjs/cancellation.js +1 -0
  77. package/dist-standalone/cjs/checkpoint.js +1 -193
  78. package/dist-standalone/cjs/circuit-breaker.js +1 -0
  79. package/dist-standalone/cjs/cli/init.js +1 -486
  80. package/dist-standalone/cjs/config-validation.js +1 -0
  81. package/dist-standalone/cjs/connect.js +1 -312
  82. package/dist-standalone/cjs/connection-pool.js +1 -0
  83. package/dist-standalone/cjs/correlation-id.js +1 -339
  84. package/dist-standalone/cjs/crypto-utils.js +1 -0
  85. package/dist-standalone/cjs/debug-mode.js +1 -0
  86. package/dist-standalone/cjs/did-document.js +1 -101
  87. package/dist-standalone/cjs/did-privateme.js +1 -130
  88. package/dist-standalone/cjs/did-web.js +1 -201
  89. package/dist-standalone/cjs/discovery.js +1 -462
  90. package/dist-standalone/cjs/dual-mode.js +1 -251
  91. package/dist-standalone/cjs/email-templates.js +1 -313
  92. package/dist-standalone/cjs/email-transport.js +1 -239
  93. package/dist-standalone/cjs/envelope.js +1 -510
  94. package/dist-standalone/cjs/errors.js +1 -826
  95. package/dist-standalone/cjs/event-emitter.js +1 -0
  96. package/dist-standalone/cjs/gateway-state.js +1 -55
  97. package/dist-standalone/cjs/gateway-transport.js +1 -120
  98. package/dist-standalone/cjs/graceful-degradation.js +1 -0
  99. package/dist-standalone/cjs/guardrails.js +1 -223
  100. package/dist-standalone/cjs/health-check.js +1 -0
  101. package/dist-standalone/cjs/http-compat.js +1 -272
  102. package/dist-standalone/cjs/http-status-map.js +1 -571
  103. package/dist-standalone/cjs/identity.js +1 -541
  104. package/dist-standalone/cjs/index.js +1 -237
  105. package/dist-standalone/cjs/invitation.js +1 -421
  106. package/dist-standalone/cjs/invite.js +1 -328
  107. package/dist-standalone/cjs/key-agreement.js +1 -246
  108. package/dist-standalone/cjs/lazy-init.js +1 -300
  109. package/dist-standalone/cjs/logger.js +1 -0
  110. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  111. package/dist-standalone/cjs/nonce-store.js +1 -66
  112. package/dist-standalone/cjs/pairing-manager.js +1 -223
  113. package/dist-standalone/cjs/plugin-system.js +1 -0
  114. package/dist-standalone/cjs/plugins/logging.js +1 -0
  115. package/dist-standalone/cjs/plugins/metrics.js +1 -0
  116. package/dist-standalone/cjs/plugins/validation.js +1 -0
  117. package/dist-standalone/cjs/policy.js +1 -320
  118. package/dist-standalone/cjs/progress-callbacks.js +1 -0
  119. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  120. package/dist-standalone/cjs/registry-middleware.js +1 -50
  121. package/dist-standalone/cjs/retry-strategies.js +1 -0
  122. package/dist-standalone/cjs/retry-transport.js +1 -102
  123. package/dist-standalone/cjs/runtime/browser.js +1 -0
  124. package/dist-standalone/cjs/runtime/edge.js +1 -0
  125. package/dist-standalone/cjs/runtime/react-native.js +1 -0
  126. package/dist-standalone/cjs/security-policy.js +1 -245
  127. package/dist-standalone/cjs/serialization.js +1 -0
  128. package/dist-standalone/cjs/split-channel.js +1 -177
  129. package/dist-standalone/cjs/subscription-proof.js +1 -230
  130. package/dist-standalone/cjs/succession.js +1 -148
  131. package/dist-standalone/cjs/timeouts.js +1 -0
  132. package/dist-standalone/cjs/trace-context.js +1 -0
  133. package/dist-standalone/cjs/trace-spans.js +1 -0
  134. package/dist-standalone/cjs/transport.js +1 -63
  135. package/dist-standalone/cjs/trust-registry.js +1 -742
  136. package/dist-standalone/cjs/types/error-response.js +1 -56
  137. package/dist-standalone/cjs/vault-auth.js +1 -0
  138. package/dist-standalone/cjs/vault-store-loader.js +1 -0
  139. package/dist-standalone/cjs/verify.js +1 -25
  140. package/dist-standalone/cjs/version-info.js +1 -0
  141. package/dist-standalone/cjs/xfetch.js +1 -252
  142. package/dist-standalone/cli/init.js +1 -449
  143. package/dist-standalone/cli/setup.js +1 -514
  144. package/dist-standalone/cli/types.js +1 -27
  145. package/dist-standalone/cli/xbind.js +1 -148
  146. package/dist-standalone/config-validation.d.ts +185 -0
  147. package/dist-standalone/config-validation.js +1 -0
  148. package/dist-standalone/connect.js +1 -274
  149. package/dist-standalone/connection-pool.d.ts +251 -0
  150. package/dist-standalone/connection-pool.js +1 -0
  151. package/dist-standalone/correlation-id.js +1 -326
  152. package/dist-standalone/crypto-utils.d.ts +60 -0
  153. package/dist-standalone/crypto-utils.js +1 -0
  154. package/dist-standalone/debug-mode.d.ts +286 -0
  155. package/dist-standalone/debug-mode.js +1 -0
  156. package/dist-standalone/did-document.js +1 -96
  157. package/dist-standalone/did-privateme.js +1 -121
  158. package/dist-standalone/did-web.js +1 -196
  159. package/dist-standalone/discovery.js +1 -458
  160. package/dist-standalone/dual-mode.js +1 -247
  161. package/dist-standalone/email-templates.js +1 -309
  162. package/dist-standalone/email-transport.js +1 -232
  163. package/dist-standalone/envelope.d.ts +29 -1
  164. package/dist-standalone/envelope.js +1 -497
  165. package/dist-standalone/errors.d.ts +10 -0
  166. package/dist-standalone/errors.js +1 -811
  167. package/dist-standalone/event-emitter.d.ts +395 -0
  168. package/dist-standalone/event-emitter.js +1 -0
  169. package/dist-standalone/gateway-state.js +1 -51
  170. package/dist-standalone/gateway-transport.js +1 -116
  171. package/dist-standalone/graceful-degradation.d.ts +246 -0
  172. package/dist-standalone/graceful-degradation.js +1 -0
  173. package/dist-standalone/guardrails.js +1 -216
  174. package/dist-standalone/health-check.d.ts +150 -0
  175. package/dist-standalone/health-check.js +1 -0
  176. package/dist-standalone/http-compat.js +1 -267
  177. package/dist-standalone/http-status-map.js +1 -561
  178. package/dist-standalone/identity.d.ts +64 -1
  179. package/dist-standalone/identity.js +1 -516
  180. package/dist-standalone/index.d.ts +45 -3
  181. package/dist-standalone/index.js +1 -52
  182. package/dist-standalone/invitation.js +1 -415
  183. package/dist-standalone/invite.js +1 -324
  184. package/dist-standalone/key-agreement.d.ts +61 -13
  185. package/dist-standalone/key-agreement.js +1 -236
  186. package/dist-standalone/lazy-init.js +1 -295
  187. package/dist-standalone/logger.d.ts +77 -0
  188. package/dist-standalone/logger.js +1 -0
  189. package/dist-standalone/mdns-discovery.js +1 -195
  190. package/dist-standalone/nonce-store.d.ts +16 -3
  191. package/dist-standalone/nonce-store.js +1 -62
  192. package/dist-standalone/package.json +0 -1
  193. package/dist-standalone/pairing-manager.js +1 -219
  194. package/dist-standalone/plugin-system.d.ts +145 -0
  195. package/dist-standalone/plugin-system.js +1 -0
  196. package/dist-standalone/policy.js +1 -315
  197. package/dist-standalone/progress-callbacks.d.ts +394 -0
  198. package/dist-standalone/progress-callbacks.js +1 -0
  199. package/dist-standalone/redis-nonce-store.js +1 -72
  200. package/dist-standalone/registry-middleware.js +1 -47
  201. package/dist-standalone/retry-strategies.d.ts +382 -0
  202. package/dist-standalone/retry-strategies.js +1 -0
  203. package/dist-standalone/retry-transport.js +1 -98
  204. package/dist-standalone/security-policy.js +1 -239
  205. package/dist-standalone/serialization.d.ts +244 -0
  206. package/dist-standalone/serialization.js +1 -0
  207. package/dist-standalone/split-channel.d.ts +49 -1
  208. package/dist-standalone/split-channel.js +1 -171
  209. package/dist-standalone/subscription-proof.js +1 -224
  210. package/dist-standalone/succession.js +1 -142
  211. package/dist-standalone/timeouts.d.ts +275 -0
  212. package/dist-standalone/timeouts.js +1 -0
  213. package/dist-standalone/trace-context.d.ts +252 -0
  214. package/dist-standalone/trace-context.js +1 -0
  215. package/dist-standalone/trace-spans.d.ts +360 -0
  216. package/dist-standalone/trace-spans.js +1 -0
  217. package/dist-standalone/transport.js +1 -59
  218. package/dist-standalone/trust-registry.d.ts +106 -5
  219. package/dist-standalone/trust-registry.js +1 -702
  220. package/dist-standalone/vault-auth.d.ts +91 -0
  221. package/dist-standalone/vault-auth.js +1 -0
  222. package/dist-standalone/vault-store-loader.d.ts +110 -0
  223. package/dist-standalone/vault-store-loader.js +1 -0
  224. package/dist-standalone/verify.js +1 -16
  225. package/dist-standalone/version-info.d.ts +259 -0
  226. package/dist-standalone/version-info.js +1 -0
  227. package/dist-standalone/xfetch.js +1 -247
  228. package/llms.txt +1 -0
  229. package/package.json +66 -5
  230. package/share1.dat +0 -0
  231. package/dist-standalone/_deps/crypto/base64.d.ts +0 -29
  232. package/dist-standalone/_deps/crypto/base64.js +0 -209
  233. package/dist-standalone/_deps/crypto/cjs/base64.js +0 -103
  234. package/dist-standalone/_deps/crypto/cjs/errors.js +0 -119
  235. package/dist-standalone/_deps/crypto/cjs/hmac.js +0 -71
  236. package/dist-standalone/_deps/crypto/cjs/index.js +0 -86
  237. package/dist-standalone/_deps/crypto/cjs/padding.js +0 -57
  238. package/dist-standalone/_deps/crypto/cjs/share-header.js +0 -68
  239. package/dist-standalone/_deps/crypto/cjs/shares.js +0 -152
  240. package/dist-standalone/_deps/crypto/cjs/tlv.js +0 -199
  241. package/dist-standalone/_deps/crypto/cjs/uuid.js +0 -61
  242. package/dist-standalone/_deps/crypto/cjs/verify.js +0 -24
  243. package/dist-standalone/_deps/crypto/cjs/xorida.js +0 -221
  244. package/dist-standalone/_deps/crypto/errors.d.ts +0 -51
  245. package/dist-standalone/_deps/crypto/errors.js +0 -109
  246. package/dist-standalone/_deps/crypto/hmac.d.ts +0 -39
  247. package/dist-standalone/_deps/crypto/hmac.js +0 -66
  248. package/dist-standalone/_deps/crypto/index.d.ts +0 -20
  249. package/dist-standalone/_deps/crypto/index.js +0 -45
  250. package/dist-standalone/_deps/crypto/padding.d.ts +0 -19
  251. package/dist-standalone/_deps/crypto/padding.js +0 -53
  252. package/dist-standalone/_deps/crypto/share-header.d.ts +0 -44
  253. package/dist-standalone/_deps/crypto/share-header.js +0 -63
  254. package/dist-standalone/_deps/crypto/shares.d.ts +0 -27
  255. package/dist-standalone/_deps/crypto/shares.js +0 -148
  256. package/dist-standalone/_deps/crypto/tlv.d.ts +0 -26
  257. package/dist-standalone/_deps/crypto/tlv.js +0 -195
  258. package/dist-standalone/_deps/crypto/uuid.d.ts +0 -22
  259. package/dist-standalone/_deps/crypto/uuid.js +0 -56
  260. package/dist-standalone/_deps/crypto/verify.d.ts +0 -15
  261. package/dist-standalone/_deps/crypto/verify.js +0 -15
  262. package/dist-standalone/_deps/crypto/xorida.d.ts +0 -44
  263. package/dist-standalone/_deps/crypto/xorida.js +0 -215
  264. package/dist-standalone/_deps/shared/errors.d.ts.map +0 -1
  265. package/dist-standalone/_deps/shared/errors.js.map +0 -1
  266. package/dist-standalone/_deps/shared/index.d.ts.map +0 -1
  267. package/dist-standalone/_deps/shared/index.js.map +0 -1
  268. package/dist-standalone/_deps/shared/types.d.ts.map +0 -1
  269. package/dist-standalone/_deps/shared/types.js.map +0 -1
  270. package/dist-standalone/_deps/ux-helpers/cjs/errors.d.ts.map +0 -1
  271. package/dist-standalone/_deps/ux-helpers/cjs/errors.js.map +0 -1
  272. package/dist-standalone/_deps/ux-helpers/cjs/index.d.ts.map +0 -1
  273. package/dist-standalone/_deps/ux-helpers/cjs/index.js.map +0 -1
  274. package/dist-standalone/_deps/ux-helpers/cjs/pagination.d.ts.map +0 -1
  275. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js.map +0 -1
  276. package/dist-standalone/_deps/ux-helpers/cjs/progress.d.ts.map +0 -1
  277. package/dist-standalone/_deps/ux-helpers/cjs/progress.js.map +0 -1
  278. package/dist-standalone/_deps/ux-helpers/cjs/search.d.ts.map +0 -1
  279. package/dist-standalone/_deps/ux-helpers/cjs/search.js.map +0 -1
  280. package/dist-standalone/_deps/ux-helpers/cjs/types.d.ts.map +0 -1
  281. package/dist-standalone/_deps/ux-helpers/cjs/types.js.map +0 -1
  282. package/dist-standalone/_deps/ux-helpers/errors.d.ts.map +0 -1
  283. package/dist-standalone/_deps/ux-helpers/errors.js.map +0 -1
  284. package/dist-standalone/_deps/ux-helpers/index.d.ts.map +0 -1
  285. package/dist-standalone/_deps/ux-helpers/index.js.map +0 -1
  286. package/dist-standalone/_deps/ux-helpers/pagination.d.ts.map +0 -1
  287. package/dist-standalone/_deps/ux-helpers/pagination.js.map +0 -1
  288. package/dist-standalone/_deps/ux-helpers/progress.d.ts.map +0 -1
  289. package/dist-standalone/_deps/ux-helpers/progress.js.map +0 -1
  290. package/dist-standalone/_deps/ux-helpers/search.d.ts.map +0 -1
  291. package/dist-standalone/_deps/ux-helpers/search.js.map +0 -1
  292. package/dist-standalone/_deps/ux-helpers/types.d.ts.map +0 -1
  293. package/dist-standalone/_deps/ux-helpers/types.js.map +0 -1
  294. package/dist-standalone/_deps/xregistry/discovery.d.ts.map +0 -1
  295. package/dist-standalone/_deps/xregistry/discovery.js.map +0 -1
  296. package/dist-standalone/_deps/xregistry/errors.d.ts.map +0 -1
  297. package/dist-standalone/_deps/xregistry/errors.js.map +0 -1
  298. package/dist-standalone/_deps/xregistry/index.d.ts.map +0 -1
  299. package/dist-standalone/_deps/xregistry/index.js.map +0 -1
  300. package/dist-standalone/_deps/xregistry/registry.d.ts.map +0 -1
  301. package/dist-standalone/_deps/xregistry/registry.js.map +0 -1
  302. package/dist-standalone/_deps/xregistry/schema.d.ts.map +0 -1
  303. package/dist-standalone/_deps/xregistry/schema.js.map +0 -1
  304. package/dist-standalone/_deps/xregistry/types.d.ts.map +0 -1
  305. package/dist-standalone/_deps/xregistry/types.js.map +0 -1
@@ -1,52 +1 @@
1
- // @private.me/xbind public API
2
- export { initCommand, main as cliMain } from './cli/init.js';
3
- export { generateIdentity, sign, verify, importPublicKey, publicKeyToDid, didToPublicKeyBytes, exportPKCS8, exportX25519PKCS8, importFromPKCS8, importIdentity, identityFromSeed, extractRawEd25519, extractRawX25519, exportMlKemSecretKey, exportMlKemPublicKey, signMlDsa65, verifyMlDsa65, exportMlDsaSecretKey, exportMlDsaPublicKey, ML_DSA65_SIG_BYTES, ML_DSA65_PK_BYTES, ML_DSA65_SK_BYTES, } from './identity.js';
4
- export { createEnvelope, createEnvelopeV2, createEnvelopeV3, createEnvelopeV4, decryptPayload, serializeEnvelope, deserializeEnvelope, validateEnvelope, generateSharedKey, createSignedEnvelope, openSignedEnvelope, } from './envelope.js';
5
- export { MemoryNonceStore } from './nonce-store.js';
6
- export { RedisNonceStore } from './redis-nonce-store.js';
7
- export { HttpsTransportAdapter } from './transport.js';
8
- export { RetryTransportAdapter } from './retry-transport.js';
9
- export { MemoryTrustRegistry, HttpTrustRegistry, FileTrustRegistry, createEnterpriseTrustRegistry, } from './trust-registry.js';
10
- export { generateEphemeralKeyPair, importX25519PublicKey, deriveSharedKeyECDH, senderKeyAgreement, receiverKeyAgreement, combineSharedSecrets, senderHybridKeyAgreement, receiverHybridKeyAgreement, } from './key-agreement.js';
11
- export { Agent, parseAgentError } from './agent.js';
12
- export { call, batchCall, stream, AgentErrorCode, ERROR_DETAILS, setToolRegistry, getToolRegistry, } from './agent-call.js';
13
- export { AgentError as AgentCallError } from './agent-call.js';
14
- export { xfetch, isXBindSupported, getXBindCapability, } from './xfetch.js';
15
- export { createAxiosCompat, createGotCompat, wrapFetch, } from './http-compat.js';
16
- export { DefaultSecurityPolicy, describeSecurityMode } from './security-policy.js';
17
- export { PolicyEngine, getGlobalPolicyEngine } from './policy.js';
18
- export { ApprovalFlow, CLIApprovalPresenter, ApprovalError, ApprovalErrorCode, } from './approval.js';
19
- // Guardrails (enhanced error messages with actionable suggestions)
20
- export { PolicyDenied, Guardrails, extractSuggestion, toPolicyDenied, } from './guardrails.js';
21
- // Registry auth middleware
22
- export { createRegistryAuthMiddleware } from './registry-middleware.js';
23
- export { GatewayTransport } from './gateway-transport.js';
24
- export { DidWebResolver, didWebToUrl } from './did-web.js';
25
- export { generateDidDocument, resolveDid, getServiceEndpoints, } from './did-document.js';
26
- // did:privateme method (Mechanism 4: new DID format for PRIVATE.ME)
27
- export { publicKeyToPrivateMeDid, privateMeDidToPublicKeyBytes, isPrivateMeDid, isDidKeyFormat, convertDidFormat, normalizeDid, parseDid, } from './did-privateme.js';
28
- export { splitForChannel, splitForChannelWithGroupId, reconstructFromChannel, DEFAULT_SPLIT_CONFIG, } from './split-channel.js';
29
- export { requestAuth, respondToChallenge, onChallenge, generateRegistrationQR, } from './auth.js';
30
- export { generateXchangeKey, xchangeEncrypt, xchangeDecrypt } from"./_deps/xchange/index.js";
31
- export { AES_KEY_BYTES, AES_IV_BYTES, BUNDLE_HEADER_BYTES } from"./_deps/xchange/index.js";
32
- // Error class hierarchy (supplementary — existing string codes unchanged)
33
- export { XBindError, XBindIdentityError, XBindEnvelopeError, XBindTransportError, XBindRegistryError, XBindKeyAgreementError, XBindSplitChannelError, XBindAgentError, toXBindError, isXBindError, createXBindErrorDetail, } from './errors.js';
34
- export { ProgressReporter, createStagedProgress, createDetailedError, formatErrorForUser, formatErrorForLog, isACIError, toACIError, paginate, createPaginationMetadata, search, } from"./_deps/ux-helpers/index.js";
35
- export { ServiceDiscovery, DiscoveryErrorCode } from './discovery.js';
36
- export { MdnsDiscoveryManager } from './mdns-discovery.js';
37
- export { InviteService, InviteErrorCode } from './invite.js';
38
- export { DualModeAdapter, DualModeErrorCode } from './dual-mode.js';
39
- export { PairingManager } from './pairing-manager.js';
40
- export { connect, acceptInvite, ConnectErrorCode } from './connect.js';
41
- export { autoAcceptInvite, AutoAcceptErrorCode } from './auto-accept.js';
42
- export { LazyAgent, createLazyAgent, LazyAgentErrorCode } from './lazy-init.js';
43
- export { InvitationErrorCode, InvitationClient, InvitationStore, generateInvitationToken, } from './invitation.js';
44
- export { AgentBuilder } from './agent-sdk.js';
45
- // DID Succession (trust infrastructure)
46
- export { createSuccession, verifySuccession, encodeSuccession, decodeSuccession, } from './succession.js';
47
- // Gateway Connection State (trust infrastructure)
48
- export { GatewayConnectionState } from './gateway-state.js';
49
- export { createCheckpoint, verifyCheckpoint, isCacheStale, encodeCheckpoint, decodeCheckpoint, } from './checkpoint.js';
50
- export { createSubscriptionProof, verifySubscriptionProof, resumeSubscription, hashBloomFilter, } from './subscription-proof.js';
51
- export { DEFAULT_BACKUP_CONFIG, validateBackupConfig, splitKeyWithBackup, reconstructKeyFromBackup, } from './backup-config.js';
52
- export { generateCorrelationId, validateCorrelationId, parseCorrelationId, attachCorrelationId, extractCorrelationId, getOrCreateCorrelationId, createCorrelationIdFromTimestamp, getCorrelationIdAge, isCorrelationIdExpired, correlationIdMiddleware, CORRELATION_ID_HEADER, CORRELATION_ID_ALIASES, } from './correlation-id.js';
1
+ export{initCommand,main as cliMain}from"./cli/init.js";export{generateIdentity,sign,verify,importPublicKey,publicKeyToDid,didToPublicKeyBytes,exportPKCS8,exportX25519PKCS8,importFromPKCS8,importIdentity,identityFromSeed,extractRawEd25519,extractRawX25519,exportMlKemSecretKey,exportMlKemPublicKey,signMlDsa65,verifyMlDsa65,exportMlDsaSecretKey,exportMlDsaPublicKey,rotateKeys,ML_DSA65_SIG_BYTES,ML_DSA65_PK_BYTES,ML_DSA65_SK_BYTES}from"./identity.js";export{createEnvelope,createEnvelopeV2,createEnvelopeV3,createEnvelopeV4,decryptPayload,serializeEnvelope,deserializeEnvelope,validateEnvelope,generateSharedKey,createSignedEnvelope,openSignedEnvelope}from"./envelope.js";export{MemoryNonceStore}from"./nonce-store.js";export{RedisNonceStore}from"./redis-nonce-store.js";export{HttpsTransportAdapter}from"./transport.js";export{RetryTransportAdapter}from"./retry-transport.js";export{ExponentialBackoffStrategy,LinearBackoffStrategy,FixedDelayStrategy,NoRetryStrategy,CircuitBreaker,RetryStrategy,executeWithRetry}from"./retry-strategies.js";export{TimeoutConfig,OperationTimeoutController,TimeoutError,createTimeoutController,withTimeout,withTimeoutResult,createOperationTimeoutSignal,createOperationTimeout,isTimeoutError,getTimeoutFromError,createTimeoutConfigFromEnv,globalTimeoutConfig,DEFAULT_TIMEOUTS}from"./timeouts.js";export{GracefulDegradationManager,registryLookupWithFallback,sendWithTransportFallback,enhanceError}from"./graceful-degradation.js";export{MemoryTrustRegistry,HttpTrustRegistry,FileTrustRegistry,createEnterpriseTrustRegistry}from"./trust-registry.js";export{generateEphemeralKeyPair,importX25519PublicKey,deriveSharedKeyECDH,senderKeyAgreement,receiverKeyAgreement,combineSharedSecrets,senderHybridKeyAgreement,receiverHybridKeyAgreement}from"./key-agreement.js";export{Agent,parseAgentError}from"./agent.js";export{MessageStream,collectMessages,mapStream,filterStream,takeStream,mergeStreams,installAsyncIterators}from"./async-iterators.js";export{call,batchCall,stream,AgentErrorCode,ERROR_DETAILS,setToolRegistry,getToolRegistry}from"./agent-call.js";export{AgentError as AgentCallError}from"./agent-call.js";export{xfetch,isXBindSupported,getXBindCapability}from"./xfetch.js";export{createAxiosCompat,createGotCompat,wrapFetch}from"./http-compat.js";export{DefaultSecurityPolicy,describeSecurityMode}from"./security-policy.js";export{PolicyEngine,getGlobalPolicyEngine}from"./policy.js";export{ApprovalFlow,CLIApprovalPresenter,ApprovalError,ApprovalErrorCode}from"./approval.js";export{PolicyDenied,Guardrails,extractSuggestion,toPolicyDenied}from"./guardrails.js";export{createRegistryAuthMiddleware}from"./registry-middleware.js";export{GatewayTransport}from"./gateway-transport.js";export{DidWebResolver,didWebToUrl}from"./did-web.js";export{generateDidDocument,resolveDid,getServiceEndpoints}from"./did-document.js";export{publicKeyToPrivateMeDid,privateMeDidToPublicKeyBytes,isPrivateMeDid,isDidKeyFormat,convertDidFormat,normalizeDid,parseDid}from"./did-privateme.js";export{splitForChannel,splitForChannelWithGroupId,reconstructFromChannel,DEFAULT_SPLIT_CONFIG}from"./split-channel.js";export{requestAuth,respondToChallenge,onChallenge,generateRegistrationQR}from"./auth.js";export{generateXchangeKey,xchangeEncrypt,xchangeDecrypt}from"./_deps/xchange/index.js";export{AES_KEY_BYTES,AES_IV_BYTES,BUNDLE_HEADER_BYTES}from"./_deps/xchange/index.js";export{XBindError,XBindIdentityError,XBindEnvelopeError,XBindTransportError,XBindRegistryError,XBindKeyAgreementError,XBindSplitChannelError,XBindAgentError,toXBindError,isXBindError,createXBindErrorDetail}from"./errors.js";export{ConfigValidationError,validateAgentOptions,validateAgentCreateOptions,getValidationDetails,assertValidConfig,assertValidCreateConfig,AGENT_OPTIONS_DEFAULTS,AGENT_CREATE_OPTIONS_DEFAULTS}from"./config-validation.js";export{ProgressReporter,createStagedProgress,createDetailedError,formatErrorForUser,formatErrorForLog,isACIError,toACIError,paginate,createPaginationMetadata,search}from"./_deps/ux-helpers/index.js";export{OperationProgressTracker,TransferProgressTracker,ShareDistributionTracker,EncryptionProgressTracker}from"./progress-callbacks.js";export{ServiceDiscovery,DiscoveryErrorCode}from"./discovery.js";export{MdnsDiscoveryManager}from"./mdns-discovery.js";export{InviteService,InviteErrorCode}from"./invite.js";export{DualModeAdapter,DualModeErrorCode}from"./dual-mode.js";export{PairingManager}from"./pairing-manager.js";export{connect,acceptInvite,ConnectErrorCode}from"./connect.js";export{autoAcceptInvite,AutoAcceptErrorCode}from"./auto-accept.js";export{LazyAgent,createLazyAgent,LazyAgentErrorCode}from"./lazy-init.js";export{InvitationErrorCode,InvitationClient,InvitationStore,generateInvitationToken}from"./invitation.js";export{AgentBuilder}from"./agent-sdk.js";export{createSuccession,verifySuccession,encodeSuccession,decodeSuccession}from"./succession.js";export{GatewayConnectionState}from"./gateway-state.js";export{createCheckpoint,verifyCheckpoint,isCacheStale,encodeCheckpoint,decodeCheckpoint}from"./checkpoint.js";export{createSubscriptionProof,verifySubscriptionProof,resumeSubscription,hashBloomFilter}from"./subscription-proof.js";export{DEFAULT_BACKUP_CONFIG,validateBackupConfig,splitKeyWithBackup,reconstructKeyFromBackup}from"./backup-config.js";export{exportBackup,importBackup}from"./backup.js";export{generateCorrelationId,validateCorrelationId,parseCorrelationId,attachCorrelationId,extractCorrelationId,getOrCreateCorrelationId,createCorrelationIdFromTimestamp,getCorrelationIdAge,isCorrelationIdExpired,correlationIdMiddleware,CORRELATION_ID_HEADER,CORRELATION_ID_ALIASES}from"./correlation-id.js";export{createLogger,LogLevel,getGlobalLogger,setGlobalLogger,logger}from"./logger.js";export{CancellationError,createTimeoutSignal,combineSignals,onCancellation,throwIfAborted,withCancellation,delay,withRetry,createCancellationController,isCancellationError}from"./cancellation.js";export{enableDebugMode,disableDebugMode,isDebugEnabled,getDebugOptions,createDebugLogger,startProfiling,endProfiling,getPerformanceMeasurements,clearPerformanceMeasurements,traceNetworkRequest,traceNetworkResponse,getNetworkTraces,clearNetworkTraces,traceCryptoOperation,getCryptoTraces,clearCryptoTraces,dumpState,getStateSnapshots,clearStateSnapshots,exportDebugData,clearAllDebugData,generateDebugReport}from"./debug-mode.js";export{getVersion,hasCapability,getCapabilities,getDeprecationInfo,warnIfDeprecated,parseVersion,compareVersions,checkCompatibility,getMinimumVersionFor,assertMinimumVersion,Capability}from"./version-info.js";export{createHealthChecker,healthEndpoint}from"./health-check.js";export{batchSend,batchReceive,batchRegistryOps,batchResolve,batchGetEntries,BatchOperationError}from"./batch-operations.js";export{detectRuntime,isBrowser,isNode,isServiceWorker,getRandomBytes,generateUUID,LocalStorageAdapter,IndexedDBAdapter,MemoryStorageAdapter,isWasmSupported,loadWasmModule,detectCapabilities,installNodePolyfills,initServiceWorker,DEFAULT_SERVICE_WORKER_CONFIG}from"./runtime/browser.js";import{installAsyncIterators as _installAsyncIterators}from"./async-iterators.js";import{Agent as _Agent}from"./agent.js";_installAsyncIterators(_Agent);export{XBindEventEmitter,createScopedEmitter}from"./event-emitter.js";export{MiddlewareChain,createPluginContext,createPlugin,PluginBuilder}from"./plugin-system.js";export{LoggingPlugin,createLoggingPlugin}from"./plugins/logging.js";export{MetricsPlugin,createMetricsPlugin}from"./plugins/metrics.js";export{ValidationPlugin,createValidationPlugin,CommonRules}from"./plugins/validation.js";export{serialize,deserialize,detectFormat,negotiateFormat,compareFormats,getContentType,parseContentType}from"./serialization.js";export{ConnectionPool,getGlobalPool,resetGlobalPool}from"./connection-pool.js";
@@ -1,415 +1 @@
1
- /**
2
- * @module invitation
3
- * Growth hack: Turn recipient-not-found failures into invitation opportunities.
4
- *
5
- * When agent.send() fails because recipient is not registered, this module
6
- * provides an invitation mechanism to turn failures into viral growth.
7
- *
8
- * Flow:
9
- * 1. Sender calls agent.send({ to: 'unregistered@example.com', ... })
10
- * 2. send() fails with RECIPIENT_NOT_FOUND
11
- * 3. Error includes invitationToken and inviteUrl
12
- * 4. Sender shares URL with recipient
13
- * 5. Recipient clicks link, signs up, joins Xail
14
- * 6. Connection auto-establishes
15
- */
16
- import { ok, err } from"./_deps/shared/index.js";
17
- /**
18
- * Error codes for invitation operations.
19
- */
20
- export var InvitationErrorCode;
21
- (function (InvitationErrorCode) {
22
- /** Invitation token is invalid format */
23
- InvitationErrorCode["INVALID_TOKEN"] = "INVITATION_INVALID_TOKEN";
24
- /** Invitation token has expired */
25
- InvitationErrorCode["EXPIRED_TOKEN"] = "INVITATION_EXPIRED_TOKEN";
26
- /** Invitation token already redeemed */
27
- InvitationErrorCode["ALREADY_REDEEMED"] = "INVITATION_ALREADY_REDEEMED";
28
- /** Rate limit exceeded (10 invitations/day per DID) */
29
- InvitationErrorCode["RATE_LIMIT_EXCEEDED"] = "INVITATION_RATE_LIMIT_EXCEEDED";
30
- /** Server communication failed */
31
- InvitationErrorCode["SERVER_ERROR"] = "INVITATION_SERVER_ERROR";
32
- })(InvitationErrorCode || (InvitationErrorCode = {}));
33
- /**
34
- * Client-side invitation manager.
35
- * Creates invitations after send() failures and manages their lifecycle.
36
- */
37
- export class InvitationClient {
38
- invitationApiUrl;
39
- /**
40
- * Create invitation client.
41
- *
42
- * @param options - Configuration
43
- * @param options.invitationApiUrl - Invitation API URL (default: https://api.private.me)
44
- *
45
- * @example
46
- * ```ts
47
- * const inviteClient = new InvitationClient();
48
- * ```
49
- */
50
- constructor(options = {}) {
51
- this.invitationApiUrl = options.invitationApiUrl || 'https://api.private.me';
52
- }
53
- /**
54
- * Create an invitation for a recipient who is not yet registered.
55
- *
56
- * Called automatically when agent.send() returns RECIPIENT_NOT_FOUND.
57
- * Generates a time-limited invitation token that can be shared via email/SMS.
58
- *
59
- * @param senderDid - DID of the agent sending the invitation
60
- * @param recipientContact - Email address or identifier of recipient
61
- * @param expiryDays - Days until invitation expires (default: 7)
62
- * @returns Invitation token with shareable URL or error
63
- *
64
- * @example
65
- * ```ts
66
- * const inviteResult = await inviteClient.create(
67
- * 'did:key:z6Mk...',
68
- * 'alice@example.com',
69
- * 7 // 7-day expiry
70
- * );
71
- *
72
- * if (inviteResult.ok) {
73
- * // Share inviteResult.value.inviteUrl with recipient
74
- * console.log('Share this link:', inviteResult.value.inviteUrl);
75
- * } else {
76
- * // Handle error
77
- * console.error('Failed:', inviteResult.error.message);
78
- * }
79
- * ```
80
- */
81
- async create(senderDid, recipientContact, expiryDays = 7) {
82
- try {
83
- const response = await fetch(`${this.invitationApiUrl}/invitations/create`, {
84
- method: 'POST',
85
- headers: {
86
- 'Content-Type': 'application/json',
87
- },
88
- body: JSON.stringify({
89
- senderDid,
90
- recipientContact,
91
- expiryDays,
92
- }),
93
- });
94
- if (response.status === 429) {
95
- return err({
96
- code: InvitationErrorCode.RATE_LIMIT_EXCEEDED,
97
- message: 'Too many invitations created. Limit: 10 per day',
98
- hint: 'Wait before creating more invitations',
99
- });
100
- }
101
- if (!response.ok) {
102
- return err({
103
- code: InvitationErrorCode.SERVER_ERROR,
104
- message: `Server error: ${response.status}`,
105
- });
106
- }
107
- const data = await response.json();
108
- return ok({
109
- token: data.token,
110
- expiresAt: new Date(data.expiresAt),
111
- senderDid: data.senderDid,
112
- recipientContact: data.recipientContact,
113
- inviteUrl: data.inviteUrl,
114
- });
115
- }
116
- catch (error) {
117
- return err({
118
- code: InvitationErrorCode.SERVER_ERROR,
119
- message: error instanceof Error ? error.message : 'Network error',
120
- });
121
- }
122
- }
123
- /**
124
- * Redeem an invitation token and create a new DID for the recipient.
125
- *
126
- * Called by recipient after clicking invitation link.
127
- * Returns a new DID that can be used immediately for messaging.
128
- *
129
- * @param token - Invitation token from URL query parameter
130
- * @returns New DID for recipient or error
131
- *
132
- * @example
133
- * ```ts
134
- * // From URL: https://private.me/invite?token=abc123
135
- * const urlParams = new URLSearchParams(window.location.search);
136
- * const token = urlParams.get('token');
137
- *
138
- * const redeemResult = await inviteClient.redeem(token);
139
- * if (redeemResult.ok) {
140
- * // Auto-create agent with new DID
141
- * const agent = await Agent.create(redeemResult.value);
142
- * } else {
143
- * // Handle: expired, already used, invalid
144
- * console.error(redeemResult.error.message);
145
- * }
146
- * ```
147
- */
148
- async redeem(token) {
149
- try {
150
- if (!token || typeof token !== 'string') {
151
- return err({
152
- code: InvitationErrorCode.INVALID_TOKEN,
153
- message: 'Invitation token is required',
154
- });
155
- }
156
- const response = await fetch(`${this.invitationApiUrl}/invitations/redeem`, {
157
- method: 'POST',
158
- headers: {
159
- 'Content-Type': 'application/json',
160
- },
161
- body: JSON.stringify({ token }),
162
- });
163
- if (response.status === 400) {
164
- return err({
165
- code: InvitationErrorCode.INVALID_TOKEN,
166
- message: 'Invitation token is invalid',
167
- hint: 'Check the token in your URL',
168
- });
169
- }
170
- if (response.status === 410) {
171
- const data = await response.json();
172
- if (data.reason === 'expired') {
173
- return err({
174
- code: InvitationErrorCode.EXPIRED_TOKEN,
175
- message: 'Invitation has expired',
176
- hint: 'Ask the sender for a new invitation',
177
- });
178
- }
179
- return err({
180
- code: InvitationErrorCode.ALREADY_REDEEMED,
181
- message: 'Invitation has already been used',
182
- hint: 'Each invitation can only be used once',
183
- });
184
- }
185
- if (!response.ok) {
186
- return err({
187
- code: InvitationErrorCode.SERVER_ERROR,
188
- message: `Server error: ${response.status}`,
189
- });
190
- }
191
- const data = await response.json();
192
- return ok(data.did);
193
- }
194
- catch (error) {
195
- return err({
196
- code: InvitationErrorCode.SERVER_ERROR,
197
- message: error instanceof Error ? error.message : 'Network error',
198
- });
199
- }
200
- }
201
- /**
202
- * Get invitation details without redeeming.
203
- *
204
- * Used to preview sender name before accepting invitation.
205
- *
206
- * @param token - Invitation token
207
- * @returns Invitation details or error
208
- *
209
- * @example
210
- * ```ts
211
- * const detailsResult = await inviteClient.get(token);
212
- * if (detailsResult.ok) {
213
- * console.log(`${detailsResult.value.senderDid} invited you`);
214
- * }
215
- * ```
216
- */
217
- async get(token) {
218
- try {
219
- const response = await fetch(`${this.invitationApiUrl}/invitations/${encodeURIComponent(token)}`, {
220
- headers: {
221
- 'Accept': 'application/json',
222
- },
223
- });
224
- if (response.status === 404) {
225
- return err({
226
- code: InvitationErrorCode.INVALID_TOKEN,
227
- message: 'Invitation not found',
228
- });
229
- }
230
- if (!response.ok) {
231
- return err({
232
- code: InvitationErrorCode.SERVER_ERROR,
233
- message: `Server error: ${response.status}`,
234
- });
235
- }
236
- const data = await response.json();
237
- return ok({
238
- senderDid: data.senderDid,
239
- recipientContact: data.recipientContact,
240
- expiresAt: new Date(data.expiresAt),
241
- });
242
- }
243
- catch (error) {
244
- return err({
245
- code: InvitationErrorCode.SERVER_ERROR,
246
- message: error instanceof Error ? error.message : 'Network error',
247
- });
248
- }
249
- }
250
- }
251
- /**
252
- * Server-side invitation store (in-memory with JSONL persistence).
253
- * Used by /invitations/* API endpoints.
254
- */
255
- export class InvitationStore {
256
- invitations = new Map();
257
- redeemedTokens = new Set();
258
- /** Track invitation creation per DID for rate limiting (10/day) */
259
- creationCounts = new Map();
260
- /**
261
- * Create an invitation and return token + expiry.
262
- * Enforces rate limit: 10 invitations per DID per 24 hours.
263
- *
264
- * @param senderDid - DID creating the invitation
265
- * @param recipientContact - Email or identifier
266
- * @param expiryDays - Days until expiry
267
- * @returns Token + metadata or error
268
- */
269
- create(senderDid, recipientContact, expiryDays = 7) {
270
- // Check rate limit
271
- const now = Date.now();
272
- const limit = this.creationCounts.get(senderDid);
273
- if (limit && limit.count >= 10 && now < limit.resetTime) {
274
- return err({
275
- code: InvitationErrorCode.RATE_LIMIT_EXCEEDED,
276
- message: 'Rate limit exceeded. Maximum 10 invitations per day.',
277
- });
278
- }
279
- // Reset counter if window expired
280
- if (limit && now >= limit.resetTime) {
281
- this.creationCounts.delete(senderDid);
282
- }
283
- // Generate token
284
- const token = generateInvitationToken();
285
- const expiresAt = now + (expiryDays * 24 * 60 * 60 * 1000);
286
- const invitation = {
287
- token,
288
- senderDid,
289
- recipientContact,
290
- createdAt: now,
291
- expiresAt,
292
- redeemed: false,
293
- };
294
- this.invitations.set(token, invitation);
295
- // Update rate limit counter
296
- if (!limit) {
297
- this.creationCounts.set(senderDid, {
298
- count: 1,
299
- resetTime: now + (24 * 60 * 60 * 1000), // 24-hour window
300
- });
301
- }
302
- else {
303
- limit.count += 1;
304
- }
305
- return ok(invitation);
306
- }
307
- /**
308
- * Get invitation by token without marking as redeemed.
309
- *
310
- * @param token - Token to lookup
311
- * @returns Invitation or error
312
- */
313
- get(token) {
314
- const invitation = this.invitations.get(token);
315
- if (!invitation) {
316
- return err({
317
- code: InvitationErrorCode.INVALID_TOKEN,
318
- message: 'Invitation not found',
319
- });
320
- }
321
- const now = Date.now();
322
- if (now > invitation.expiresAt) {
323
- // Clean up expired invitation
324
- this.invitations.delete(token);
325
- return err({
326
- code: InvitationErrorCode.EXPIRED_TOKEN,
327
- message: 'Invitation has expired',
328
- });
329
- }
330
- if (invitation.redeemed) {
331
- return err({
332
- code: InvitationErrorCode.ALREADY_REDEEMED,
333
- message: 'Invitation has already been redeemed',
334
- });
335
- }
336
- return ok(invitation);
337
- }
338
- /**
339
- * Redeem an invitation (one-time use).
340
- * Mark as redeemed and generate new DID.
341
- *
342
- * @param token - Token to redeem
343
- * @returns New DID or error
344
- */
345
- redeem(token) {
346
- const getResult = this.get(token);
347
- if (!getResult.ok) {
348
- return getResult;
349
- }
350
- const invitation = getResult.value;
351
- invitation.redeemed = true;
352
- this.redeemedTokens.add(token);
353
- // Generate DID for recipient
354
- const did = generateRecipientDid(invitation.senderDid, invitation.recipientContact);
355
- return ok(did);
356
- }
357
- /**
358
- * Clean up expired invitations (run daily).
359
- * @returns Number of invitations deleted
360
- */
361
- cleanup() {
362
- const now = Date.now();
363
- let count = 0;
364
- for (const [token, invitation] of this.invitations.entries()) {
365
- if (now > invitation.expiresAt || invitation.redeemed) {
366
- this.invitations.delete(token);
367
- count += 1;
368
- }
369
- }
370
- return count;
371
- }
372
- /** Get active invitation count */
373
- get count() {
374
- return this.invitations.size;
375
- }
376
- }
377
- /**
378
- * Generate a cryptographically secure invitation token.
379
- * Format: 48-character hex string (192 bits).
380
- * @returns Random token
381
- */
382
- export function generateInvitationToken() {
383
- const bytes = new Uint8Array(24);
384
- crypto.getRandomValues(bytes);
385
- return Array.from(bytes)
386
- .map(b => b.toString(16).padStart(2, '0'))
387
- .join('');
388
- }
389
- /**
390
- * Generate a deterministic DID for invited recipient.
391
- * Ensures consistent identity across sessions.
392
- *
393
- * @param senderDid - DID of sender
394
- * @param recipientContact - Email or identifier
395
- * @returns Generated DID for recipient
396
- */
397
- function generateRecipientDid(senderDid, recipientContact) {
398
- // Create a simple derived identifier
399
- // In production: derive from email + hash(senderDid) for uniqueness
400
- const hash = hashString(`${senderDid}:${recipientContact}`);
401
- return `did:key:z6Mk${hash}`;
402
- }
403
- /**
404
- * Simple hash function for DID generation.
405
- * @param input - String to hash
406
- * @returns Hex string
407
- */
408
- function hashString(input) {
409
- let hash = 0;
410
- for (let i = 0; i < input.length; i += 1) {
411
- hash = ((hash << 5) - hash) + input.charCodeAt(i);
412
- hash = hash & hash; // Convert to 32bit integer
413
- }
414
- return Math.abs(hash).toString(16).padStart(8, '0');
415
- }
1
+ import{ok,err}from"./_deps/shared/index.js";export var InvitationErrorCode;!function(e){e.INVALID_TOKEN="INVITATION_INVALID_TOKEN",e.EXPIRED_TOKEN="INVITATION_EXPIRED_TOKEN",e.ALREADY_REDEEMED="INVITATION_ALREADY_REDEEMED",e.RATE_LIMIT_EXCEEDED="INVITATION_RATE_LIMIT_EXCEEDED",e.SERVER_ERROR="INVITATION_SERVER_ERROR"}(InvitationErrorCode||(InvitationErrorCode={}));export class InvitationClient{invitationApiUrl;constructor(e={}){this.invitationApiUrl=e.invitationApiUrl||"https://api.private.me"}async create(e,t,r=7){try{const n=await fetch(`${this.invitationApiUrl}/invitations/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({senderDid:e,recipientContact:t,expiryDays:r})});if(429===n.status)return err({code:InvitationErrorCode.RATE_LIMIT_EXCEEDED,message:"Too many invitations created. Limit: 10 per day",hint:"Wait before creating more invitations"});if(!n.ok)return err({code:InvitationErrorCode.SERVER_ERROR,message:`Server error: ${n.status}`});const i=await n.json();return ok({token:i.token,expiresAt:new Date(i.expiresAt),senderDid:i.senderDid,recipientContact:i.recipientContact,inviteUrl:i.inviteUrl})}catch(e){return err({code:InvitationErrorCode.SERVER_ERROR,message:e instanceof Error?e.message:"Network error"})}}async redeem(e){try{if(!e||"string"!=typeof e)return err({code:InvitationErrorCode.INVALID_TOKEN,message:"Invitation token is required"});const t=await fetch(`${this.invitationApiUrl}/invitations/redeem`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e})});if(400===t.status)return err({code:InvitationErrorCode.INVALID_TOKEN,message:"Invitation token is invalid",hint:"Check the token in your URL"});if(410===t.status){return"expired"===(await t.json()).reason?err({code:InvitationErrorCode.EXPIRED_TOKEN,message:"Invitation has expired",hint:"Ask the sender for a new invitation"}):err({code:InvitationErrorCode.ALREADY_REDEEMED,message:"Invitation has already been used",hint:"Each invitation can only be used once"})}if(!t.ok)return err({code:InvitationErrorCode.SERVER_ERROR,message:`Server error: ${t.status}`});const r=await t.json();return ok(r.did)}catch(e){return err({code:InvitationErrorCode.SERVER_ERROR,message:e instanceof Error?e.message:"Network error"})}}async get(e){try{const t=await fetch(`${this.invitationApiUrl}/invitations/${encodeURIComponent(e)}`,{headers:{Accept:"application/json"}});if(404===t.status)return err({code:InvitationErrorCode.INVALID_TOKEN,message:"Invitation not found"});if(!t.ok)return err({code:InvitationErrorCode.SERVER_ERROR,message:`Server error: ${t.status}`});const r=await t.json();return ok({senderDid:r.senderDid,recipientContact:r.recipientContact,expiresAt:new Date(r.expiresAt)})}catch(e){return err({code:InvitationErrorCode.SERVER_ERROR,message:e instanceof Error?e.message:"Network error"})}}}export class InvitationStore{invitations=new Map;redeemedTokens=new Set;creationCounts=new Map;create(e,t,r=7){const n=Date.now(),i=this.creationCounts.get(e);if(i&&i.count>=10&&n<i.resetTime)return err({code:InvitationErrorCode.RATE_LIMIT_EXCEEDED,message:"Rate limit exceeded. Maximum 10 invitations per day."});i&&n>=i.resetTime&&this.creationCounts.delete(e);const o=generateInvitationToken(),a={token:o,senderDid:e,recipientContact:t,createdAt:n,expiresAt:n+24*r*60*60*1e3,redeemed:!1};return this.invitations.set(o,a),i?i.count+=1:this.creationCounts.set(e,{count:1,resetTime:n+864e5}),ok(a)}get(e){const t=this.invitations.get(e);if(!t)return err({code:InvitationErrorCode.INVALID_TOKEN,message:"Invitation not found"});return Date.now()>t.expiresAt?(this.invitations.delete(e),err({code:InvitationErrorCode.EXPIRED_TOKEN,message:"Invitation has expired"})):t.redeemed?err({code:InvitationErrorCode.ALREADY_REDEEMED,message:"Invitation has already been redeemed"}):ok(t)}redeem(e){const t=this.get(e);if(!t.ok)return t;const r=t.value;r.redeemed=!0,this.redeemedTokens.add(e);const n=generateRecipientDid(r.senderDid,r.recipientContact);return ok(n)}cleanup(){const e=Date.now();let t=0;for(const[r,n]of this.invitations.entries())(e>n.expiresAt||n.redeemed)&&(this.invitations.delete(r),t+=1);return t}get count(){return this.invitations.size}}export function generateInvitationToken(){const e=new Uint8Array(24);return crypto.getRandomValues(e),Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}function generateRecipientDid(e,t){return`did:key:z6Mk${hashString(`${e}:${t}`)}`}function hashString(e){let t=0;for(let r=0;r<e.length;r+=1)t=(t<<5)-t+e.charCodeAt(r),t&=t;return Math.abs(t).toString(16).padStart(8,"0")}