@private.me/xbind 3.0.1 → 3.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +2419 -216
  2. package/README.md.backup +2121 -0
  3. package/dist-standalone/_deps/shared/cjs/errors.js +1 -1
  4. package/dist-standalone/_deps/shared/cjs/index.js +1 -1
  5. package/dist-standalone/_deps/shared/cjs/types.js +1 -1
  6. package/dist-standalone/_deps/shared/errors.js +1 -1
  7. package/dist-standalone/_deps/shared/index.js +1 -1
  8. package/dist-standalone/_deps/shared/types.js +1 -1
  9. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  10. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  11. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  12. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  13. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  14. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  15. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  16. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  17. package/dist-standalone/_deps/xchange/errors.js +1 -1
  18. package/dist-standalone/_deps/xchange/index.js +1 -1
  19. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  20. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  21. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  22. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  23. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  24. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  25. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  26. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  27. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  28. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  29. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  30. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  31. package/dist-standalone/_deps/xregistry/index.js +1 -1
  32. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  33. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  34. package/dist-standalone/_deps/xregistry/types.js +1 -1
  35. package/dist-standalone/agent-call.d.ts +2 -2
  36. package/dist-standalone/agent-call.js +1 -1
  37. package/dist-standalone/agent.d.ts +2 -0
  38. package/dist-standalone/agent.js +1 -1
  39. package/dist-standalone/async-iterators.d.ts +3 -3
  40. package/dist-standalone/backup.js +1 -1
  41. package/dist-standalone/cjs/agent-call.js +1 -1
  42. package/dist-standalone/cjs/agent.js +1 -1
  43. package/dist-standalone/cjs/backup.js +1 -1
  44. package/dist-standalone/cjs/cli/init.js +1 -1
  45. package/dist-standalone/cjs/connection-pool.js +1 -1
  46. package/dist-standalone/cjs/crypto-utils.js +1 -1
  47. package/dist-standalone/cjs/debug-mode.js +1 -1
  48. package/dist-standalone/cjs/email-transport.js +1 -1
  49. package/dist-standalone/cjs/errors.js +1 -1
  50. package/dist-standalone/cjs/http-compat.js +1 -1
  51. package/dist-standalone/cjs/index.js +1 -1
  52. package/dist-standalone/cjs/lazy-init.js +1 -1
  53. package/dist-standalone/cjs/loopback-transport.js +1 -0
  54. package/dist-standalone/cjs/mdns-discovery.js +1 -1
  55. package/dist-standalone/cjs/plugins/logging.js +1 -1
  56. package/dist-standalone/cjs/runtime/edge.js +1 -1
  57. package/dist-standalone/cjs/security-policy.js +1 -1
  58. package/dist-standalone/cjs/serialization.js +1 -1
  59. package/dist-standalone/cjs/transport.js +1 -1
  60. package/dist-standalone/cjs/trust-registry.js +1 -1
  61. package/dist-standalone/cjs/vault-store-loader.js +1 -1
  62. package/dist-standalone/cjs/version-info.js +1 -1
  63. package/dist-standalone/cjs/xfetch.js +1 -1
  64. package/dist-standalone/cli/init.js +1 -1
  65. package/dist-standalone/cli/setup.js +1 -1
  66. package/dist-standalone/cli/xbind.js +1 -1
  67. package/dist-standalone/connection-pool.js +1 -1
  68. package/dist-standalone/crypto-utils.d.ts +2 -7
  69. package/dist-standalone/crypto-utils.js +1 -1
  70. package/dist-standalone/debug-mode.js +1 -1
  71. package/dist-standalone/email-transport.d.ts +2 -2
  72. package/dist-standalone/email-transport.js +1 -1
  73. package/dist-standalone/errors.d.ts +13 -3
  74. package/dist-standalone/errors.js +1 -1
  75. package/dist-standalone/gateway-state.d.ts +1 -1
  76. package/dist-standalone/health-check.d.ts +5 -1
  77. package/dist-standalone/http-compat.d.ts +1 -1
  78. package/dist-standalone/http-compat.js +1 -1
  79. package/dist-standalone/index.d.ts +15 -4
  80. package/dist-standalone/index.js +1 -1
  81. package/dist-standalone/lazy-init.d.ts +11 -6
  82. package/dist-standalone/lazy-init.js +1 -1
  83. package/dist-standalone/loopback-transport.d.ts +87 -0
  84. package/dist-standalone/loopback-transport.js +1 -0
  85. package/dist-standalone/mdns-discovery.js +1 -1
  86. package/dist-standalone/plugins/logging.js +1 -1
  87. package/dist-standalone/plugins/metrics.d.ts +4 -4
  88. package/dist-standalone/runtime/edge.js +1 -1
  89. package/dist-standalone/runtime/react-native.d.ts +1 -1
  90. package/dist-standalone/security-policy.js +1 -1
  91. package/dist-standalone/serialization.js +1 -1
  92. package/dist-standalone/transport.js +1 -1
  93. package/dist-standalone/trust-registry.d.ts +3 -3
  94. package/dist-standalone/trust-registry.js +1 -1
  95. package/dist-standalone/vault-store-loader.d.ts +9 -0
  96. package/dist-standalone/vault-store-loader.js +1 -1
  97. package/dist-standalone/version-info.js +1 -1
  98. package/dist-standalone/xfetch.js +1 -1
  99. package/package.json +4 -13
  100. package/share1.dat +0 -0
  101. package/dist-standalone/_deps/mldsa-wasm/LICENSE +0 -24
  102. package/dist-standalone/_deps/mldsa-wasm/package.json +0 -46
  103. package/dist-standalone/_deps/shared/cjs/package.json +0 -1
  104. package/dist-standalone/_deps/ux-helpers/cjs/package.json +0 -1
  105. package/dist-standalone/_deps/xchange/cjs/package.json +0 -1
  106. package/dist-standalone/_deps/xregistry/cjs/package.json +0 -1
  107. package/dist-standalone/cjs/package.json +0 -3
  108. package/dist-standalone/package.json +0 -10
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,i)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var s=e(t),i=0;i<s.length;i++)"default"!==s[i]&&__createBinding(r,t,s[i]);return __setModuleDefault(r,t),r}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.generateSharedKey=exports.Agent=void 0,exports.parseAgentError=parseAgentError;const shared_1=require("../_deps/shared/index.js"),crypto_utils_js_1=require("./crypto-utils.js"),vault_store_loader_js_1=require("./vault-store-loader.js"),errors_js_1=require("./errors.js"),identity_js_1=require("./identity.js"),envelope_js_1=require("./envelope.js");Object.defineProperty(exports,"generateSharedKey",{enumerable:!0,get:function(){return envelope_js_1.generateSharedKey}});const xchange_1=require("../_deps/xchange/index.js"),identity_js_2=require("./identity.js"),key_agreement_js_1=require("./key-agreement.js"),split_channel_js_1=require("./split-channel.js"),nonce_store_js_1=require("./nonce-store.js"),transport_js_1=require("./transport.js"),trust_registry_js_1=require("./trust-registry.js"),ux_helpers_1=require("../_deps/ux-helpers/index.js"),security_policy_js_1=require("./security-policy.js"),backup_config_js_1=require("./backup-config.js"),DEFAULT_RELAY_URL=process.env.XBIND_RELAY_URL||"https://private.me/relay",DEFAULT_REGISTRY_URL=process.env.XBIND_REGISTRY_URL||"https://private.me/registry";function parseAgentError(e){const t=e.split(":");return 1===t.length?{code:t[0]??e}:{code:t[0]??e,subCode:t.slice(1).join(":")}}const TIMESTAMP_WINDOW_MS=3e4;function toArrayBuffer(e){const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}function compareBytes(e,t){const r=Math.min(e.length,t.length);for(let s=0;s<r;s++){const r=e[s]??0,i=t[s]??0;if(r!==i)return r-i}return e.length-t.length}function concatBytes(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}class Agent{identity;name;registry;transports;nonceStore;timestampWindowMs;securityPolicy;backupConfig;shareAccumulator=new Map;lastDetail="";lastSecurityDecision;cleanupTimer;cryptoModule=null;get lastErrorDetail(){return this.lastDetail}get lastSecurity(){return this.lastSecurityDecision}constructor(e,t,r,s,i,a,n,o){this.identity=e,this.name=t,this.registry=r,this.transports=s,this.nonceStore=i,this.timestampWindowMs=a,this.securityPolicy=n??new security_policy_js_1.DefaultSecurityPolicy,this.backupConfig=o??backup_config_js_1.DEFAULT_BACKUP_CONFIG}get did(){return this.identity.did}getTransports(){return this.transports}async ensureCrypto(){if(this.cryptoModule)return this.cryptoModule;const e=(0,vault_store_loader_js_1.getCrypto)();if(e)return this.cryptoModule=e,e;const t=await(0,vault_store_loader_js_1.loadCryptoPackage)(this.identity);if(!t.ok){if("VAULT_QUOTA_EXCEEDED"===t.error){const e="https://private.me/subscribe?product=xbind&tier=pro";throw new errors_js_1.QuotaExceededError(`Monthly usage quota exceeded (Free tier: 100K operations/month). Upgrade to Pro tier for unlimited access at $5 per 100K operations. Visit: ${e}`,e)}throw new errors_js_1.VaultStoreError(t.error,`Failed to load crypto package: ${t.error}`)}return this.cryptoModule=t.value,t.value}static isSupported(){try{return void 0!==globalThis.crypto&&void 0!==globalThis.crypto.subtle&&"function"==typeof globalThis.crypto.subtle.generateKey&&"function"==typeof globalThis.crypto.subtle.sign&&"function"==typeof globalThis.crypto.subtle.verify&&"function"==typeof globalThis.crypto.subtle.encrypt&&"function"==typeof globalThis.crypto.getRandomValues}catch{return!1}}static async fromIdentity(e,t){const r=t.nonceStore??new nonce_store_js_1.MemoryNonceStore,s=t.timestampWindowMs??3e4,i=Array.isArray(t.transport)?t.transport:[t.transport],a=new Agent(e,t.name??e.did,t.registry,i,r,s,t.securityPolicy,t.backupConfig);return(0,shared_1.ok)(a)}static fromParts(e,t,r,s){const i=Array.isArray(r)?r:[r];return new Agent(e,s?.name??e.did,t,i,s?.nonceStore??new nonce_store_js_1.MemoryNonceStore,s?.timestampWindowMs??3e4,s?.securityPolicy,s?.backupConfig)}static async fromSeed(e,t){const r=await(0,identity_js_1.identityFromSeed)(e,{postQuantumSig:t.postQuantumSig});if(!r.ok)return(0,shared_1.err)("IDENTITY_FAILED:KEYGEN");const s=await t.registry.register(r.value.did,r.value.rawPublicKey,t.name??r.value.did,t.scopes,r.value.rawX25519PublicKey,r.value.mlKemPublicKey,r.value.mlDsaPublicKey,t.xchange??!1);if(!s.ok&&"ALREADY_REGISTERED"!==s.error){const e="NETWORK_ERROR"===s.error?"REGISTRATION_FAILED:NETWORK_ERROR":"REGISTRATION_FAILED";return(0,shared_1.err)(e)}const i=t.nonceStore??new nonce_store_js_1.MemoryNonceStore,a=t.timestampWindowMs??3e4,n=Array.isArray(t.transport)?t.transport:[t.transport];return(0,shared_1.ok)(new Agent(r.value,t.name??r.value.did,t.registry,n,i,a,t.securityPolicy,t.backupConfig))}static async lazy(e){const{createLazyAgent:t}=await Promise.resolve().then(()=>__importStar(require("./lazy-init.js")));return t(e)}isReady(){return void 0!==this.identity&&void 0!==this.registry&&this.transports.length>0}static async create(e){const t=await(0,identity_js_1.generateIdentity)({postQuantumSig:e.postQuantumSig});if(!t.ok)return(0,shared_1.err)("IDENTITY_FAILED:KEYGEN");const r=await e.registry.register(t.value.did,t.value.rawPublicKey,e.name,e.scopes,t.value.rawX25519PublicKey,t.value.mlKemPublicKey,t.value.mlDsaPublicKey,e.xchange??!1);if(!r.ok){const e="ALREADY_REGISTERED"===r.error?"REGISTRATION_FAILED:ALREADY_REGISTERED":"NETWORK_ERROR"===r.error?"REGISTRATION_FAILED:NETWORK_ERROR":"REGISTRATION_FAILED";return(0,shared_1.err)(e)}const s=e.nonceStore??new nonce_store_js_1.MemoryNonceStore,i=e.timestampWindowMs??3e4,a=Array.isArray(e.transport)?e.transport:[e.transport],n=new Agent(t.value,e.name,e.registry,a,s,i,e.securityPolicy,e.backupConfig);try{await n.ensureCrypto()}catch(e){return e instanceof errors_js_1.QuotaExceededError?(0,shared_1.err)("QUOTA_EXCEEDED"):e instanceof errors_js_1.VaultStoreError?(0,shared_1.err)("IDENTITY_FAILED:VAULT_STORE"):(0,shared_1.err)("IDENTITY_FAILED")}return(0,shared_1.ok)(n)}static async quickstart(e){const t=new trust_registry_js_1.MemoryTrustRegistry,r=new transport_js_1.HttpsTransportAdapter({baseUrl:DEFAULT_RELAY_URL}),s=await(0,identity_js_1.generateIdentity)({postQuantumSig:!1});if(!s.ok)throw new Error("Failed to generate ephemeral identity");const i=e?.name??`agent-${Date.now()}`,a=await t.register(s.value.did,s.value.rawPublicKey,i,void 0,s.value.rawX25519PublicKey,s.value.mlKemPublicKey,s.value.mlDsaPublicKey,!1);if(!a.ok)throw new Error(`Failed to register ephemeral identity: ${a.error}`);const n=new Agent(s.value,i,t,[r],new nonce_store_js_1.MemoryNonceStore,3e4,void 0,void 0);return n.cleanupTimer=setTimeout(async()=>{await t.revoke(s.value.did)},36e5),n}static async from(e={}){const t=e.identity??"persistent",r=e.identityTTL??36e5,s="ephemeral"===t,i="string"==typeof e.registry?new trust_registry_js_1.HttpTrustRegistry({baseUrl:e.registry}):e.registry??(s?new trust_registry_js_1.MemoryTrustRegistry:new trust_registry_js_1.HttpTrustRegistry({baseUrl:DEFAULT_REGISTRY_URL})),a=e.transport?Array.isArray(e.transport)?e.transport:[e.transport]:[new transport_js_1.HttpsTransportAdapter({baseUrl:DEFAULT_RELAY_URL})],n=await(0,identity_js_1.generateIdentity)({postQuantumSig:e.postQuantumSig??!1});if(!n.ok)throw new Error("Failed to generate identity");const o=s?`ephemeral-agent-${Date.now()}`:`agent-${Date.now()}`,c=await i.register(n.value.did,n.value.rawPublicKey,o,void 0,n.value.rawX25519PublicKey,n.value.mlKemPublicKey,n.value.mlDsaPublicKey,!1);if(!c.ok)throw new Error(`Failed to register identity: ${c.error}`);const l=new Agent(n.value,o,i,a,new nonce_store_js_1.MemoryNonceStore,3e4,e.securityPolicy,e.backupConfig);return s&&(l.cleanupTimer=setTimeout(async()=>{await i.revoke(n.value.did)},r)),l}async send(e){const t=new ux_helpers_1.ProgressReporter(e.onProgress);t.start("Resolving recipient identity...");const r=await this.registry.resolve(e.to);if(!r.ok)return(0,shared_1.err)("REVOKED"===r.error?"RECIPIENT_REVOKED":"RECIPIENT_NOT_FOUND");t.update("Checking recipient authorization...",10);if(!await this.registry.hasReceiveScope(e.to,e.scope))return this.lastDetail=`recipient=${e.to}, scope=${e.scope}`,(0,shared_1.err)("RECEIVER_SCOPE_DENIED");t.update("Preparing message...",15);const s=(new TextEncoder).encode(JSON.stringify(e.payload));t.update("Determining security level...",20);const i=this.securityPolicy.classify({action:e.action??"send",params:"object"==typeof e.payload&&null!==e.payload?e.payload:{},sender:this.did,recipient:e.to,scope:e.scope,securityOverride:e.security});this.lastSecurityDecision=i,t.update(`Security: ${(0,security_policy_js_1.describeSecurityMode)(i.mode)} — ${i.reason}`,25);const a=void 0!==e.splitChannel?e.splitChannel:"split"===i.mode.type;if(a&&(e.xchange||"xchange"===i.mode.type)){t.update("Checking Xchange support...",20);if(await this.canUseXchange(e.to))return this.sendXchange(e,s,t)}t.update("Establishing key agreement...",30);const n=await this.trySenderECDH(e.to);return n?a?this.sendSplitChannel(e,s,n.sharedKey,n.ephemeralPublicKey,n.kemCiphertext,n.recipientHasMlDsa,t):n.kemCiphertext&&n.recipientHasMlDsa&&this.identity.mlDsaSecretKey?this.sendWithHybridV3(e,s,n.sharedKey,n.ephemeralPublicKey,n.kemCiphertext,t):n.kemCiphertext?this.sendWithHybrid(e,s,n.sharedKey,n.ephemeralPublicKey,n.kemCiphertext,t):this.sendWithECDH(e,s,n.sharedKey,n.ephemeralPublicKey,t):(0,shared_1.err)("KEY_AGREEMENT_FAILED:RECIPIENT_HAS_NO_X25519_KEY")}async receive(e,t){this.lastDetail="";const r=new ux_helpers_1.ProgressReporter(t?.onProgress);r.start("Verifying envelope signature...");const s=await this.verifyEnvelope(e);if(!s.ok)return s;const{senderRawKey:i,payloadBytes:a}=s.value;let n;if(4===e.v)return(0,shared_1.err)("VERIFICATION_FAILED:UNSUPPORTED_VERSION");if(r.update("Deriving shared key...",30),2!==e.v&&3!==e.v||!("kemCiphertext"in e)){if(!e.ephemeralPub){if(t?.allowCleartext){let t;try{t=JSON.parse((new TextDecoder).decode(a))}catch{return(0,shared_1.err)("DECRYPT_FAILED:PARSE")}return r.complete(),(0,shared_1.ok)({sender:e.sender,payload:t,scope:e.scope,timestamp:e.timestamp})}return(0,shared_1.err)("DECRYPT_FAILED:NO_EPHEMERAL_KEY")}{if("string"!=typeof e.ephemeralPub)return this.lastDetail="ephemeralPub not string",(0,shared_1.err)("VERIFICATION_FAILED:INVALID_ENVELOPE");const t=(0,crypto_utils_js_1.fromBase64)(e.ephemeralPub),s=await(0,key_agreement_js_1.receiverKeyAgreement)(this.identity.x25519PrivateKey,t);if(s.ok)n=s.value;else{if(this.identity.rotatedKeys&&this.identity.rotatedKeys.length>0)for(const e of this.identity.rotatedKeys){const s=await(0,key_agreement_js_1.receiverKeyAgreement)(e.x25519PrivateKey,t);if(s.ok){n=s.value,r.update("Decrypting with rotated keys...",45);break}}if(!n)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT")}}}else{if(!this.identity.mlKemSecretKey)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT");if("string"!=typeof e.ephemeralPub||"string"!=typeof e.kemCiphertext)return this.lastDetail="ephemeralPub or kemCiphertext not string",(0,shared_1.err)("VERIFICATION_FAILED:INVALID_ENVELOPE");const t=(0,crypto_utils_js_1.fromBase64)(e.ephemeralPub),s=(0,crypto_utils_js_1.fromBase64)(e.kemCiphertext);if(!this.identity.mlKemPublicKey||!this.identity.mlKemSecretKey)return this.lastDetail="ML-KEM keys not available in identity",(0,shared_1.err)("DECRYPT_FAILED:MISSING_MLKEM_KEYS");const i=await(0,key_agreement_js_1.receiverHybridKeyAgreement)(this.identity.x25519PrivateKey,this.identity.rawX25519PublicKey,t,s,this.identity.mlKemSecretKey,this.identity.mlKemPublicKey);if(i.ok)n=i.value;else{if(this.identity.rotatedKeys&&this.identity.rotatedKeys.length>0)for(const e of this.identity.rotatedKeys){if(!e.mlKemSecretKey)continue;const i=await(0,key_agreement_js_1.receiverHybridKeyAgreement)(e.x25519PrivateKey,this.identity.rawX25519PublicKey,t,s,e.mlKemSecretKey,this.identity.mlKemPublicKey);if(i.ok){n=i.value,r.update("Decrypting with rotated keys...",45);break}}if(!n)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT")}}if(r.update("Decrypting payload...",60),!n)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT");const o=await(0,envelope_js_1.decryptPayload)(e,n);if(!o.ok)return(0,shared_1.err)("DECRYPT_FAILED:DECRYPTION");let c;r.update("Parsing message...",90);try{c=JSON.parse((new TextDecoder).decode(o.value))}catch{return(0,shared_1.err)("DECRYPT_FAILED:PARSE")}return r.complete(),(0,shared_1.ok)({sender:e.sender,payload:c,scope:e.scope,timestamp:e.timestamp,metadata:e.protocol&&e.documentationUrl?{protocol:e.protocol,documentationUrl:e.documentationUrl}:void 0})}async verifySignature(e){const t=await this.registry.resolve(e.sender);if(!t.ok)return(0,shared_1.err)("VERIFICATION_FAILED:DID_NOT_IN_REGISTRY");const r=await(0,identity_js_1.importPublicKey)(t.value);if(!r.ok)return(0,shared_1.err)("VERIFICATION_FAILED:KEY_IMPORT_FAILED");const s=(0,crypto_utils_js_1.fromBase64)(e.signature),i=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}),a=(new TextEncoder).encode(i),n=await(0,identity_js_1.verify)(r.value,s,a);return n.ok?(0,shared_1.ok)({sender:e.sender,valid:n.value}):(0,shared_1.err)("VERIFICATION_FAILED:SIGNATURE_MISMATCH")}async exportSeeds(){const e=await(0,identity_js_1.exportPKCS8)(this.identity.privateKey);if(!e.ok)return(0,shared_1.err)("IDENTITY_FAILED");const t=await(0,identity_js_1.exportX25519PKCS8)(this.identity.x25519PrivateKey);if(!t.ok)return(0,shared_1.err)("IDENTITY_FAILED");const r=(0,identity_js_1.extractRawEd25519)(e.value);if(!r.ok)return(0,shared_1.err)("IDENTITY_FAILED");const s=(0,identity_js_1.extractRawX25519)(t.value);return s.ok?(0,shared_1.ok)({ed25519:r.value,x25519:s.value,mlKemSecretKey:this.identity.mlKemSecretKey,mlKemPublicKey:this.identity.mlKemPublicKey}):(0,shared_1.err)("IDENTITY_FAILED")}async splitKey(e){const{splitKeyWithBackup:t}=await Promise.resolve().then(()=>__importStar(require("./backup-config.js"))),r=await t(e,this.backupConfig);return r.ok?r:(0,shared_1.err)("ENVELOPE_FAILED:SPLIT")}async reconstructKey(e){const{reconstructKeyFromBackup:t}=await Promise.resolve().then(()=>__importStar(require("./backup-config.js"))),r=await t(e);return r.ok?r:(0,shared_1.err)("DECRYPT_FAILED")}async receiveSigned(e){this.lastDetail="";const t=await this.verifyEnvelope(e);if(!t.ok)return t;let r;try{r=JSON.parse((new TextDecoder).decode(t.value.payloadBytes))}catch{return(0,shared_1.err)("DECRYPT_FAILED:PARSE")}return(0,shared_1.ok)({sender:e.sender,payload:r,scope:e.scope,timestamp:e.timestamp,metadata:e.protocol&&e.documentationUrl?{protocol:e.protocol,documentationUrl:e.documentationUrl}:void 0})}async discover(e){const{getToolRegistry:t}=await Promise.resolve().then(()=>__importStar(require("./agent-call.js"))),r=t();if(!r)return[];if(!e)return r.listAll();return r.search(e)}middleware(){return async(e,t,r)=>{const s=(0,envelope_js_1.validateEnvelope)(e.body);if(!s.ok)return void t.status(400).json({error:s.error});const i=await this.receive(s.value);if(!i.ok){const e="TIMESTAMP_EXPIRED"===i.error||"REPLAY_DETECTED"===i.error?403:401;return void t.status(e).json({error:i.error})}e.agentMessage=i.value,r()}}cleanup(){this.cleanupTimer&&(clearTimeout(this.cleanupTimer),this.cleanupTimer=void 0)}dispose(){this.cleanup()}async trySenderECDH(e){const t=await this.registry.getEntry(e);if(!t.ok||!t.value.x25519PublicKey)return null;const r=!!t.value.mlDsaPublicKey,s=await(0,key_agreement_js_1.importX25519PublicKey)(t.value.x25519PublicKey);if(!s.ok)return null;if(t.value.mlKemPublicKey&&this.identity.mlKemSecretKey){const e=await(0,key_agreement_js_1.senderHybridKeyAgreement)(s.value,t.value.mlKemPublicKey);if(e.ok)return{sharedKey:e.value.sharedKey,ephemeralPublicKey:e.value.ephemeralPublicKey,kemCiphertext:e.value.kemCiphertext,recipientHasMlDsa:r}}const i=await(0,key_agreement_js_1.senderKeyAgreement)(s.value);return i.ok?{...i.value,recipientHasMlDsa:r}:null}async sendWithECDH(e,t,r,s,i){i?.update("Encrypting message with ECDH...",60);const a=await(0,envelope_js_1.createEnvelope)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:t,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:s});if(!a.ok)return(0,shared_1.err)("ENVELOPE_FAILED:ENCRYPT");i?.update("Sending message...",90);const n=await this.transports[0].send(a.value,e.to);return n.ok&&i?.complete(),n}async sendWithHybrid(e,t,r,s,i,a){a?.update("Encrypting message with hybrid KEM...",60);const n=await(0,envelope_js_1.createEnvelopeV2)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:t,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:s,kemCiphertext:i});if(!n.ok)return(0,shared_1.err)("ENVELOPE_FAILED:ENCRYPT");a?.update("Sending message...",90);const o=await this.transports[0].send(n.value,e.to);return o.ok&&a?.complete(),o}async sendWithHybridV3(e,t,r,s,i,a){if(!this.identity.mlDsaSecretKey)return(0,shared_1.err)("ENVELOPE_FAILED:PQ_KEY_MISSING");a?.update("Encrypting with post-quantum signatures...",60);const n=await(0,envelope_js_1.createEnvelopeV3)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:t,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:s,kemCiphertext:i,mlDsaSecretKey:this.identity.mlDsaSecretKey});if(!n.ok)return this.lastDetail=`v3 envelope error: ${n.error}`,(0,shared_1.err)("ENVELOPE_FAILED:ENCRYPT");a?.update("Sending message...",90);const o=await this.transports[0].send(n.value,e.to);return o.ok&&a?.complete(),o}async sendDirect(e,t,r,s){s?.update("Encrypting message...",60);const i=await(0,envelope_js_1.createEnvelope)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:t,privateKey:this.identity.privateKey,sharedKey:r});if(!i.ok)return(0,shared_1.err)("ENVELOPE_FAILED:ENCRYPT");s?.update("Sending message...",90);const a=await this.transports[0].send(i.value,e.to);return a.ok&&s?.complete(),a}async canUseXchange(e){const t=await this.registry.getEntry(e);return!!t.ok&&!0===t.value.xchange}async sendXchange(e,t,r){const s=e.splitChannelConfig??split_channel_js_1.DEFAULT_SPLIT_CONFIG;this.transports.length<s.totalShares&&console.warn(`Split-channel: ${s.totalShares} shares but only ${this.transports.length} transport(s). For channel separation, provide at least ${s.totalShares} transports.`),r?.update("Generating Xchange key...",40);const i=await(0,xchange_1.generateXchangeKey)();if(!i.ok)return(0,shared_1.err)("KEY_AGREEMENT_FAILED");r?.update("Encrypting message...",50);const a=await(0,xchange_1.xchangeEncrypt)(t,i.value);if(!a.ok)return(0,shared_1.err)("ENVELOPE_FAILED:ENCRYPT");const n=await this.ensureCrypto(),o=s.totalShares,c=s.threshold,l=n.nextOddPrime(o)-1,d=n.pkcs7Pad(a.value,l),{key:u,signature:h}=await n.generateHMAC(d);let y;r?.update("Splitting message into shares...",60);try{y=n.splitXorIDA(d,o,c)}catch{return(0,shared_1.err)("ENVELOPE_FAILED:SPLIT")}const _=(0,crypto_utils_js_1.toBase64)(u),p=(0,crypto_utils_js_1.toBase64)(h),E=(0,crypto_utils_js_1.generateUUID)(),m=[];r?.update("Sending shares...",70);for(let t=0;t<y.length;t++){const s=y[t],i=(0,crypto_utils_js_1.formatShareHeader)((0,crypto_utils_js_1.toBase64)(s)),a=(new TextEncoder).encode(i),n=await(0,envelope_js_1.createEnvelopeV4)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,shareData:a,privateKey:this.identity.privateKey,shareIndex:t,shareTotal:o,shareThreshold:c,shareGroupId:E,shareHmacKey:_,shareHmacSig:p});if(!n.ok){m.push((0,shared_1.err)("ENVELOPE_FAILED:ENCRYPT"));continue}const l=this.transports[t%this.transports.length],d=await l.send(n.value,e.to);m.push(d);const u=70+Math.floor((t+1)/y.length*20);r?.update(`Sent share ${t+1}/${y.length}...`,u)}return m.filter(e=>e.ok).length<c?(0,shared_1.err)("SEND_FAILED:BELOW_THRESHOLD"):(r?.complete(),(0,shared_1.ok)(void 0))}async sendSplitChannel(e,t,r,s,i,a,n){const o=e.splitChannelConfig??split_channel_js_1.DEFAULT_SPLIT_CONFIG;this.transports.length<o.totalShares&&console.warn(`Split-channel: ${o.totalShares} shares but only ${this.transports.length} transport(s). For channel separation, provide at least ${o.totalShares} transports.`),n?.update("Splitting message into shares...",50);const c=await(0,split_channel_js_1.splitForChannel)(t,o);if(!c.ok)return(0,shared_1.err)("ENVELOPE_FAILED:SPLIT");const l=c.value;n?.update("Encrypting and sending shares...",70);return(await this.sendShareEnvelopes(e,l,r,s,i,a,n)).filter(e=>e.ok).length<o.threshold?(0,shared_1.err)("SEND_FAILED:BELOW_THRESHOLD"):(n?.complete(),(0,shared_1.ok)(void 0))}async sendShareEnvelopes(e,t,r,s,i,a,n){const o=[];for(let c=0;c<t.length;c++){const l=t[c],d=(new TextEncoder).encode(l.data);let u;if(u=i&&s&&a&&this.identity.mlDsaSecretKey?await(0,envelope_js_1.createEnvelopeV3)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:d,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:s,kemCiphertext:i,mlDsaSecretKey:this.identity.mlDsaSecretKey,shareIndex:l.index,shareTotal:l.total,shareThreshold:l.threshold,shareGroupId:l.groupId,shareHmacKey:l.hmacKey,shareHmacSig:l.hmacSig}):i&&s?await(0,envelope_js_1.createEnvelopeV2)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:d,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:s,kemCiphertext:i,shareIndex:l.index,shareTotal:l.total,shareThreshold:l.threshold,shareGroupId:l.groupId,shareHmacKey:l.hmacKey,shareHmacSig:l.hmacSig}):await(0,envelope_js_1.createEnvelope)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:d,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:s,shareIndex:l.index,shareTotal:l.total,shareThreshold:l.threshold,shareGroupId:l.groupId,shareHmacKey:l.hmacKey,shareHmacSig:l.hmacSig}),!u.ok){o.push((0,shared_1.err)("ENVELOPE_FAILED:ENCRYPT"));continue}const h=this.transports[c%this.transports.length],y=await h.send(u.value,e.to);o.push(y);const _=70+Math.floor((c+1)/t.length*20);n?.update(`Sent share ${c+1}/${t.length}...`,_)}return o}async receiveSplitShare(e){if(void 0===e.shareGroupId)return(0,shared_1.err)("VERIFICATION_FAILED");const t=await this.receiveRaw(e);if(!t.ok)return t;const{sender:r,decryptedText:s,scope:i,timestamp:a}=t.value,n={data:s,index:e.shareIndex??0,total:e.shareTotal??2,threshold:e.shareThreshold??2,groupId:e.shareGroupId,hmacKey:e.shareHmacKey??"",hmacSig:e.shareHmacSig??""};return this.accumulateShare(n,r,i,a)}async receiveXchangeShare(e){this.lastDetail="";const t=await this.verifyEnvelope(e);if(!t.ok)return t;const r={data:(new TextDecoder).decode(t.value.payloadBytes),index:e.shareIndex,total:e.shareTotal,threshold:e.shareThreshold,groupId:e.shareGroupId,hmacKey:e.shareHmacKey,hmacSig:e.shareHmacSig};return this.accumulateXchangeShare(r,e.sender,e.scope,e.timestamp)}async accumulateXchangeShare(e,t,r,s){const i=this.shareAccumulator.get(e.groupId)??[];if(i.some(t=>t.index===e.index)||(i.push(e),this.shareAccumulator.set(e.groupId,i)),i.length<e.threshold)return(0,shared_1.ok)(null);this.shareAccumulator.delete(e.groupId);const a=i.slice(0,e.threshold),n=e.total,o=e.threshold;let c;try{c=a.map(e=>(0,crypto_utils_js_1.fromBase64)((0,crypto_utils_js_1.parseShareHeader)(e.data)))}catch{return(0,shared_1.err)("DECRYPT_FAILED")}const l=a.map(e=>e.index),d=await this.ensureCrypto();let u,h,y;try{u=d.reconstructXorIDA(c,l,n,o)}catch{return(0,shared_1.err)("DECRYPT_FAILED")}try{h=(0,crypto_utils_js_1.fromBase64)(a[0].hmacKey),y=(0,crypto_utils_js_1.fromBase64)(a[0].hmacSig)}catch{return(0,shared_1.err)("DECRYPT_FAILED")}if(!await d.verifyHMAC(h,u,y))return this.lastDetail="HMAC verification failed before decrypt",(0,shared_1.err)("DECRYPT_FAILED");const _=d.nextOddPrime(n)-1,p=d.pkcs7Unpad(u,_);if(!p.ok)return(0,shared_1.err)("DECRYPT_FAILED");const E=await(0,xchange_1.xchangeDecrypt)(p.value);if(!E.ok)return(0,shared_1.err)("DECRYPT_FAILED:DECRYPTION");let m;try{m=JSON.parse((new TextDecoder).decode(E.value))}catch{return(0,shared_1.err)("DECRYPT_FAILED:PARSE")}return(0,shared_1.ok)({sender:t,payload:m,scope:r,timestamp:s})}async accumulateShare(e,t,r,s){const i=this.shareAccumulator.get(e.groupId)??[];if(i.some(t=>t.index===e.index)||(i.push(e),this.shareAccumulator.set(e.groupId,i)),i.length<e.threshold)return(0,shared_1.ok)(null);this.shareAccumulator.delete(e.groupId);const a=await(0,split_channel_js_1.reconstructFromChannel)(i);if(!a.ok)return(0,shared_1.err)("DECRYPT_FAILED");let n;try{n=JSON.parse((new TextDecoder).decode(a.value))}catch{return(0,shared_1.err)("DECRYPT_FAILED")}return(0,shared_1.ok)({sender:t,payload:n,scope:r,timestamp:s})}async verifyEnvelope(e){if(!e||"object"!=typeof e)return this.lastDetail="envelope is null or not an object",(0,shared_1.err)("VERIFICATION_FAILED:INVALID_ENVELOPE");if(1!==e.v&&2!==e.v&&3!==e.v&&4!==e.v||"Ed25519"!==e.alg)return this.lastDetail=`v=${String(e.v)}, alg=${String(e.alg)}`,(0,shared_1.err)("VERIFICATION_FAILED:UNSUPPORTED_VERSION");if("number"!=typeof e.timestamp||!Number.isFinite(e.timestamp))return this.lastDetail=`timestamp=${String(e.timestamp)} (must be finite number)`,(0,shared_1.err)("VERIFICATION_FAILED:INVALID_ENVELOPE");const t=Math.abs(Date.now()-e.timestamp);if(t>this.timestampWindowMs)return this.lastDetail=`age=${t}ms, max=${this.timestampWindowMs}ms`,(0,shared_1.err)("TIMESTAMP_EXPIRED");const r=void 0!==e.shareGroupId?{shareGroupId:e.shareGroupId,shareIndex:e.shareIndex}:void 0;if(!await this.nonceStore.check(e.nonce,e.sender,r))return this.lastDetail=`nonce=${e.nonce}`,(0,shared_1.err)("REPLAY_DETECTED");const s=await this.registry.resolve(e.sender);if(!s.ok)return this.lastDetail=`did=${e.sender}`,(0,shared_1.err)("VERIFICATION_FAILED:DID_NOT_IN_REGISTRY");const i=await(0,identity_js_1.importPublicKey)(s.value);if(!i.ok)return this.lastDetail=`did=${e.sender}`,(0,shared_1.err)("VERIFICATION_FAILED:KEY_IMPORT_FAILED");if(!e.signature||"string"!=typeof e.signature)return this.lastDetail="signature field missing or invalid",(0,shared_1.err)("VERIFICATION_FAILED:SIGNATURE_MISMATCH");const a=(0,crypto_utils_js_1.fromBase64)(e.signature),n=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}),o=(new TextEncoder).encode(n),c=await(0,identity_js_1.verify)(i.value,a,o);if(!c.ok||!c.value)return this.lastDetail="signature does not match canonical envelope (v1.1.3+ required)",(0,shared_1.err)("VERIFICATION_FAILED:SIGNATURE_MISMATCH");if(3===e.v&&"pqSignature"in e){if("string"!=typeof e.pqSignature)return this.lastDetail="pqSignature field not a string",(0,shared_1.err)("VERIFICATION_FAILED:INVALID_ENVELOPE");const t=await this.registry.getEntry(e.sender);if(!t.ok||!t.value.mlDsaPublicKey)return this.lastDetail=`did=${e.sender} missing ML-DSA public key`,(0,shared_1.err)("VERIFICATION_FAILED:PQ_KEY_MISSING");const r=(0,crypto_utils_js_1.fromBase64)(e.pqSignature),s=await(0,identity_js_2.verifyMlDsa65)(t.value.mlDsaPublicKey,r,o);if(!s.ok||!s.value)return this.lastDetail="ML-DSA-65 signature does not match canonical envelope (v1.1.3+ required)",(0,shared_1.err)("VERIFICATION_FAILED:PQ_SIGNATURE_MISMATCH")}if(!await this.registry.hasScope(e.sender,e.scope))return this.lastDetail=`scope=${e.scope}`,(0,shared_1.err)("SCOPE_DENIED");if("string"!=typeof e.payload)return this.lastDetail="payload field not a string",(0,shared_1.err)("VERIFICATION_FAILED:INVALID_ENVELOPE");const l=(0,crypto_utils_js_1.fromBase64)(e.payload);return(0,shared_1.ok)({senderRawKey:s.value,payloadBytes:l})}async receiveRaw(e){const t=await this.verifyEnvelope(e);if(!t.ok)return t;const{senderRawKey:r}=t.value;if(4===e.v)return(0,shared_1.err)("VERIFICATION_FAILED:UNSUPPORTED_VERSION");let s;if(2!==e.v&&3!==e.v||!("kemCiphertext"in e)){if(!e.ephemeralPub)return(0,shared_1.err)("DECRYPT_FAILED:NO_EPHEMERAL_KEY");{if("string"!=typeof e.ephemeralPub)return(0,shared_1.err)("DECRYPT_FAILED:INVALID_ENVELOPE");const t=(0,crypto_utils_js_1.fromBase64)(e.ephemeralPub),r=await(0,key_agreement_js_1.receiverKeyAgreement)(this.identity.x25519PrivateKey,t);if(r.ok)s=r.value;else{if(this.identity.rotatedKeys&&this.identity.rotatedKeys.length>0)for(const e of this.identity.rotatedKeys){const r=await(0,key_agreement_js_1.receiverKeyAgreement)(e.x25519PrivateKey,t);if(r.ok){s=r.value;break}}if(!s)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT")}}}else{if(!this.identity.mlKemSecretKey)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT");if("string"!=typeof e.ephemeralPub||"string"!=typeof e.kemCiphertext)return(0,shared_1.err)("DECRYPT_FAILED:INVALID_ENVELOPE");const t=(0,crypto_utils_js_1.fromBase64)(e.ephemeralPub),r=(0,crypto_utils_js_1.fromBase64)(e.kemCiphertext);if(!this.identity.mlKemPublicKey||!this.identity.mlKemSecretKey)return this.lastDetail="ML-KEM keys not available in identity",(0,shared_1.err)("DECRYPT_FAILED:MISSING_MLKEM_KEYS");const i=await(0,key_agreement_js_1.receiverHybridKeyAgreement)(this.identity.x25519PrivateKey,this.identity.rawX25519PublicKey,t,r,this.identity.mlKemSecretKey,this.identity.mlKemPublicKey);if(i.ok)s=i.value;else{if(this.identity.rotatedKeys&&this.identity.rotatedKeys.length>0)for(const e of this.identity.rotatedKeys){if(!e.mlKemSecretKey)continue;const i=await(0,key_agreement_js_1.receiverHybridKeyAgreement)(e.x25519PrivateKey,this.identity.rawX25519PublicKey,t,r,e.mlKemSecretKey,this.identity.mlKemPublicKey);if(i.ok){s=i.value;break}}if(!s)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT")}}if(!s)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT");const i=await(0,envelope_js_1.decryptPayload)(e,s);if(!i.ok)return(0,shared_1.err)("DECRYPT_FAILED:DECRYPTION");const a=(new TextDecoder).decode(i.value);return(0,shared_1.ok)({sender:e.sender,decryptedText:a,scope:e.scope,timestamp:e.timestamp})}async createTestEnvelope(e,t,r){const s=await this.registry.getEntry(e);if(!s.ok||!s.value.x25519PublicKey)return null;const i=await(0,key_agreement_js_1.importX25519PublicKey)(s.value.x25519PublicKey);if(!i.ok)return null;const a=await(0,key_agreement_js_1.senderKeyAgreement)(i.value);if(!a.ok)return null;const n=(new TextEncoder).encode(JSON.stringify(t)),o=await(0,envelope_js_1.createEnvelope)({senderDid:this.identity.did,recipientDid:e,scope:r,plaintext:n,privateKey:this.identity.privateKey,sharedKey:a.value.sharedKey,ephemeralPublicKey:a.value.ephemeralPublicKey});return o.ok?o.value:null}async invite(e){if(!this.transports||0===this.transports.length)return(0,shared_1.err)("SEND_FAILED");const t=Buffer.from(this.identity.rawPublicKey).toString("base64"),r={from:this.identity.did,to:e.to,payload:{agentName:this.name,message:e.message,publicKey:t,endpoint:""}},s=this.transports[0];if(!s)return(0,shared_1.err)("SEND_FAILED");return(await s.send(r,e.to)).ok?(0,shared_1.ok)(void 0):(0,shared_1.err)("SEND_FAILED")}}exports.Agent=Agent;
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,s)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),s=0;s<i.length;s++)"default"!==i[s]&&__createBinding(r,t,i[s]);return __setModuleDefault(r,t),r}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.generateSharedKey=exports.Agent=void 0,exports.parseAgentError=parseAgentError;const shared_1=require("../_deps/shared/index.js"),crypto_utils_js_1=require("./crypto-utils.js"),vault_store_loader_js_1=require("./vault-store-loader.js"),errors_js_1=require("./errors.js"),identity_js_1=require("./identity.js"),envelope_js_1=require("./envelope.js");Object.defineProperty(exports,"generateSharedKey",{enumerable:!0,get:function(){return envelope_js_1.generateSharedKey}});const xchange_1=require("../_deps/xchange/index.js"),identity_js_2=require("./identity.js"),key_agreement_js_1=require("./key-agreement.js"),split_channel_js_1=require("./split-channel.js"),nonce_store_js_1=require("./nonce-store.js"),transport_js_1=require("./transport.js"),trust_registry_js_1=require("./trust-registry.js"),ux_helpers_1=require("../_deps/ux-helpers/index.js"),security_policy_js_1=require("./security-policy.js"),backup_config_js_1=require("./backup-config.js"),DEFAULT_RELAY_URL=process.env.XBIND_RELAY_URL||"https://private.me/relay",DEFAULT_REGISTRY_URL=process.env.XBIND_REGISTRY_URL||"https://private.me/registry";function parseAgentError(e){const t=e.split(":");return 1===t.length?{code:t[0]??e}:{code:t[0]??e,subCode:t.slice(1).join(":")}}const TIMESTAMP_WINDOW_MS=3e4;class Agent{identity;name;registry;transports;nonceStore;timestampWindowMs;securityPolicy;backupConfig;shareAccumulator=new Map;lastDetail="";lastSecurityDecision;cleanupTimer;cryptoModule=null;get lastErrorDetail(){return this.lastDetail}get lastSecurity(){return this.lastSecurityDecision}constructor(e,t,r,i,s,a,n,o){this.identity=e,this.name=t,this.registry=r,this.transports=i,this.nonceStore=s,this.timestampWindowMs=a,this.securityPolicy=n??new security_policy_js_1.DefaultSecurityPolicy,this.backupConfig=o??backup_config_js_1.DEFAULT_BACKUP_CONFIG}get did(){return this.identity.did}getTransports(){return this.transports}async ensureCrypto(){if(this.cryptoModule)return this.cryptoModule;const e=(0,vault_store_loader_js_1.getCrypto)();if(e)return this.cryptoModule=e,e;const t=await(0,vault_store_loader_js_1.loadCryptoPackage)(this.identity);if(!t.ok){if("VAULT_QUOTA_EXCEEDED"===t.error){const e="https://private.me/subscribe?product=xbind&tier=pro";throw new errors_js_1.QuotaExceededError(`Monthly usage quota exceeded (Free tier: 100K operations/month). Upgrade to Pro tier for unlimited access at $5 per 100K operations. Visit: ${e}`,e)}throw new errors_js_1.VaultStoreError(t.error,`Failed to load crypto package: ${t.error}`)}return this.cryptoModule=t.value,t.value}static isSupported(){try{return void 0!==globalThis.crypto&&void 0!==globalThis.crypto.subtle&&"function"==typeof globalThis.crypto.subtle.generateKey&&"function"==typeof globalThis.crypto.subtle.sign&&"function"==typeof globalThis.crypto.subtle.verify&&"function"==typeof globalThis.crypto.subtle.encrypt&&"function"==typeof globalThis.crypto.getRandomValues}catch{return!1}}static async fromIdentity(e,t){const r=t.nonceStore??new nonce_store_js_1.MemoryNonceStore,i=t.timestampWindowMs??3e4,s=Array.isArray(t.transport)?t.transport:[t.transport],a=new Agent(e,t.name??e.did,t.registry,s,r,i,t.securityPolicy,t.backupConfig);return(0,shared_1.ok)(a)}static fromParts(e,t,r,i){const s=Array.isArray(r)?r:[r];return new Agent(e,i?.name??e.did,t,s,i?.nonceStore??new nonce_store_js_1.MemoryNonceStore,i?.timestampWindowMs??3e4,i?.securityPolicy,i?.backupConfig)}static async fromSeed(e,t){const r=await(0,identity_js_1.identityFromSeed)(e,{postQuantumSig:t.postQuantumSig});if(!r.ok)return(0,shared_1.err)("IDENTITY_FAILED:KEYGEN");const i=await t.registry.register(r.value.did,r.value.rawPublicKey,t.name??r.value.did,t.scopes,r.value.rawX25519PublicKey,r.value.mlKemPublicKey,r.value.mlDsaPublicKey,t.xchange??!1);if(!i.ok&&"ALREADY_REGISTERED"!==i.error){const e="NETWORK_ERROR"===i.error?"REGISTRATION_FAILED:NETWORK_ERROR":"REGISTRATION_FAILED";return(0,shared_1.err)(e)}const s=t.nonceStore??new nonce_store_js_1.MemoryNonceStore,a=t.timestampWindowMs??3e4,n=Array.isArray(t.transport)?t.transport:[t.transport];return(0,shared_1.ok)(new Agent(r.value,t.name??r.value.did,t.registry,n,s,a,t.securityPolicy,t.backupConfig))}static async lazy(e){const{createLazyAgent:t}=await Promise.resolve().then(()=>__importStar(require("./lazy-init.js")));return t(e)}isReady(){return void 0!==this.identity&&void 0!==this.registry&&this.transports.length>0}static async create(e){const t=await(0,identity_js_1.generateIdentity)({postQuantumSig:e.postQuantumSig});if(!t.ok)return(0,shared_1.err)("IDENTITY_FAILED:KEYGEN");const r=await e.registry.register(t.value.did,t.value.rawPublicKey,e.name,e.scopes,t.value.rawX25519PublicKey,t.value.mlKemPublicKey,t.value.mlDsaPublicKey,e.xchange??!1);if(!r.ok){const e="ALREADY_REGISTERED"===r.error?"REGISTRATION_FAILED:ALREADY_REGISTERED":"NETWORK_ERROR"===r.error?"REGISTRATION_FAILED:NETWORK_ERROR":"REGISTRATION_FAILED";return(0,shared_1.err)(e)}const i=e.nonceStore??new nonce_store_js_1.MemoryNonceStore,s=e.timestampWindowMs??3e4,a=Array.isArray(e.transport)?e.transport:[e.transport],n=new Agent(t.value,e.name,e.registry,a,i,s,e.securityPolicy,e.backupConfig);return(0,shared_1.ok)(n)}static async quickstart(e){const t=new trust_registry_js_1.MemoryTrustRegistry,r=new transport_js_1.HttpsTransportAdapter({baseUrl:DEFAULT_RELAY_URL}),i=await(0,identity_js_1.generateIdentity)({postQuantumSig:e?.postQuantumSig??!1});if(!i.ok)throw new Error("Failed to generate ephemeral identity");const s=e?.name??`agent-${Date.now()}`,a=await t.register(i.value.did,i.value.rawPublicKey,s,void 0,i.value.rawX25519PublicKey,i.value.mlKemPublicKey,i.value.mlDsaPublicKey,!1);if(!a.ok)throw new Error(`Failed to register ephemeral identity: ${a.error}`);const n=new Agent(i.value,s,t,[r],new nonce_store_js_1.MemoryNonceStore,3e4,void 0,void 0);return n.cleanupTimer=setTimeout(async()=>{await t.revoke(i.value.did)},36e5),n}static async from(e={}){const t=e.identity??"persistent",r=e.identityTTL??36e5,i="ephemeral"===t,s="string"==typeof e.registry?new trust_registry_js_1.HttpTrustRegistry({baseUrl:e.registry}):e.registry??(i?new trust_registry_js_1.MemoryTrustRegistry:new trust_registry_js_1.HttpTrustRegistry({baseUrl:DEFAULT_REGISTRY_URL})),a=e.transport?Array.isArray(e.transport)?e.transport:[e.transport]:[new transport_js_1.HttpsTransportAdapter({baseUrl:DEFAULT_RELAY_URL})],n=await(0,identity_js_1.generateIdentity)({postQuantumSig:e.postQuantumSig??!1});if(!n.ok)throw new Error("Failed to generate identity");const o=i?`ephemeral-agent-${Date.now()}`:`agent-${Date.now()}`,c=await s.register(n.value.did,n.value.rawPublicKey,o,void 0,n.value.rawX25519PublicKey,n.value.mlKemPublicKey,n.value.mlDsaPublicKey,!1);if(!c.ok)throw new Error(`Failed to register identity: ${c.error}`);const l=new Agent(n.value,o,s,a,new nonce_store_js_1.MemoryNonceStore,3e4,e.securityPolicy,e.backupConfig);return i&&(l.cleanupTimer=setTimeout(async()=>{await s.revoke(n.value.did)},r)),l}async send(e){const t=new ux_helpers_1.ProgressReporter(e.onProgress);t.start("Resolving recipient identity...");const r=await this.registry.resolve(e.to);if(!r.ok)return(0,shared_1.err)("REVOKED"===r.error?"RECIPIENT_REVOKED":"RECIPIENT_NOT_FOUND");const i=e.scope??"default";t.update("Checking recipient authorization...",10);if(!await this.registry.hasReceiveScope(e.to,i))return this.lastDetail=`recipient=${e.to}, scope=${i}`,(0,shared_1.err)("RECEIVER_SCOPE_DENIED");t.update("Preparing message...",15);const s=(new TextEncoder).encode(JSON.stringify(e.payload));t.update("Determining security level...",20);const a=this.securityPolicy.classify({action:e.action??"send",params:"object"==typeof e.payload&&null!==e.payload?e.payload:{},sender:this.did,recipient:e.to,scope:i,securityOverride:e.security});this.lastSecurityDecision=a,t.update(`Security: ${(0,security_policy_js_1.describeSecurityMode)(a.mode)} — ${a.reason}`,25);const n=void 0!==e.splitChannel?e.splitChannel:"split"===a.mode.type;if(n&&(e.xchange||"xchange"===a.mode.type)){t.update("Checking Xchange support...",20);if(await this.canUseXchange(e.to))return this.sendXchange(e,s,t)}t.update("Establishing key agreement...",30);const o=await this.trySenderECDH(e.to);return o?n?this.sendSplitChannel(e,s,o.sharedKey,o.ephemeralPublicKey,o.kemCiphertext,o.recipientHasMlDsa,t):o.kemCiphertext&&o.recipientHasMlDsa&&this.identity.mlDsaSecretKey?this.sendWithHybridV3(e,s,o.sharedKey,o.ephemeralPublicKey,o.kemCiphertext,t):o.kemCiphertext?this.sendWithHybrid(e,s,o.sharedKey,o.ephemeralPublicKey,o.kemCiphertext,t):this.sendWithECDH(e,s,o.sharedKey,o.ephemeralPublicKey,t):(0,shared_1.err)("KEY_AGREEMENT_FAILED:RECIPIENT_HAS_NO_X25519_KEY")}async receive(e,t){this.lastDetail="";const r=new ux_helpers_1.ProgressReporter(t?.onProgress);r.start("Verifying envelope signature...");const i=await this.verifyEnvelope(e);if(!i.ok)return i;const{payloadBytes:s}=i.value;let a;if(4===e.v)return(0,shared_1.err)("VERIFICATION_FAILED:UNSUPPORTED_VERSION");if(r.update("Deriving shared key...",30),2!==e.v&&3!==e.v||!("kemCiphertext"in e)){if(!e.ephemeralPub){if(t?.allowCleartext){let t;try{t=JSON.parse((new TextDecoder).decode(s))}catch{return(0,shared_1.err)("DECRYPT_FAILED:PARSE")}return r.complete(),(0,shared_1.ok)({sender:e.sender,payload:t,scope:e.scope,timestamp:e.timestamp})}return(0,shared_1.err)("DECRYPT_FAILED:NO_EPHEMERAL_KEY")}{if("string"!=typeof e.ephemeralPub)return this.lastDetail="ephemeralPub not string",(0,shared_1.err)("VERIFICATION_FAILED:INVALID_ENVELOPE");const t=(0,crypto_utils_js_1.fromBase64)(e.ephemeralPub),i=await(0,key_agreement_js_1.receiverKeyAgreement)(this.identity.x25519PrivateKey,t);if(i.ok)a=i.value;else{if(this.identity.rotatedKeys&&this.identity.rotatedKeys.length>0)for(const e of this.identity.rotatedKeys){const i=await(0,key_agreement_js_1.receiverKeyAgreement)(e.x25519PrivateKey,t);if(i.ok){a=i.value,r.update("Decrypting with rotated keys...",45);break}}if(!a)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT")}}}else{if(!this.identity.mlKemSecretKey)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT");if("string"!=typeof e.ephemeralPub||"string"!=typeof e.kemCiphertext)return this.lastDetail="ephemeralPub or kemCiphertext not string",(0,shared_1.err)("VERIFICATION_FAILED:INVALID_ENVELOPE");const t=(0,crypto_utils_js_1.fromBase64)(e.ephemeralPub),i=(0,crypto_utils_js_1.fromBase64)(e.kemCiphertext);if(!this.identity.mlKemPublicKey||!this.identity.mlKemSecretKey)return this.lastDetail="ML-KEM keys not available in identity",(0,shared_1.err)("DECRYPT_FAILED:MISSING_MLKEM_KEYS");const s=await(0,key_agreement_js_1.receiverHybridKeyAgreement)(this.identity.x25519PrivateKey,this.identity.rawX25519PublicKey,t,i,this.identity.mlKemSecretKey,this.identity.mlKemPublicKey);if(s.ok)a=s.value;else{if(this.identity.rotatedKeys&&this.identity.rotatedKeys.length>0)for(const e of this.identity.rotatedKeys){if(!e.mlKemSecretKey)continue;const s=await(0,key_agreement_js_1.receiverHybridKeyAgreement)(e.x25519PrivateKey,this.identity.rawX25519PublicKey,t,i,e.mlKemSecretKey,this.identity.mlKemPublicKey);if(s.ok){a=s.value,r.update("Decrypting with rotated keys...",45);break}}if(!a)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT")}}if(r.update("Decrypting payload...",60),!a)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT");const n=await(0,envelope_js_1.decryptPayload)(e,a);if(!n.ok)return(0,shared_1.err)("DECRYPT_FAILED:DECRYPTION");let o;r.update("Parsing message...",90);try{o=JSON.parse((new TextDecoder).decode(n.value))}catch{return(0,shared_1.err)("DECRYPT_FAILED:PARSE")}return r.complete(),(0,shared_1.ok)({sender:e.sender,payload:o,scope:e.scope,timestamp:e.timestamp,metadata:e.protocol&&e.documentationUrl?{protocol:e.protocol,documentationUrl:e.documentationUrl}:void 0})}async verifySignature(e){const t=await this.registry.resolve(e.sender);if(!t.ok)return(0,shared_1.err)("VERIFICATION_FAILED:DID_NOT_IN_REGISTRY");const r=await(0,identity_js_1.importPublicKey)(t.value);if(!r.ok)return(0,shared_1.err)("VERIFICATION_FAILED:KEY_IMPORT_FAILED");const i=(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}),a=(new TextEncoder).encode(s),n=await(0,identity_js_1.verify)(r.value,i,a);return n.ok?(0,shared_1.ok)({sender:e.sender,valid:n.value}):(0,shared_1.err)("VERIFICATION_FAILED:SIGNATURE_MISMATCH")}async exportSeeds(){const e=await(0,identity_js_1.exportPKCS8)(this.identity.privateKey);if(!e.ok)return(0,shared_1.err)("IDENTITY_FAILED");const t=await(0,identity_js_1.exportX25519PKCS8)(this.identity.x25519PrivateKey);if(!t.ok)return(0,shared_1.err)("IDENTITY_FAILED");const r=(0,identity_js_1.extractRawEd25519)(e.value);if(!r.ok)return(0,shared_1.err)("IDENTITY_FAILED");const i=(0,identity_js_1.extractRawX25519)(t.value);return i.ok?(0,shared_1.ok)({ed25519:r.value,x25519:i.value,mlKemSecretKey:this.identity.mlKemSecretKey,mlKemPublicKey:this.identity.mlKemPublicKey}):(0,shared_1.err)("IDENTITY_FAILED")}async splitKey(e){const{splitKeyWithBackup:t}=await Promise.resolve().then(()=>__importStar(require("./backup-config.js"))),r=await t(e,this.backupConfig);return r.ok?r:(0,shared_1.err)("ENVELOPE_FAILED:SPLIT")}async reconstructKey(e){const{reconstructKeyFromBackup:t}=await Promise.resolve().then(()=>__importStar(require("./backup-config.js"))),r=await t(e);return r.ok?r:(0,shared_1.err)("DECRYPT_FAILED")}async receiveSigned(e){this.lastDetail="";const t=await this.verifyEnvelope(e);if(!t.ok)return t;let r;try{r=JSON.parse((new TextDecoder).decode(t.value.payloadBytes))}catch{return(0,shared_1.err)("DECRYPT_FAILED:PARSE")}return(0,shared_1.ok)({sender:e.sender,payload:r,scope:e.scope,timestamp:e.timestamp,metadata:e.protocol&&e.documentationUrl?{protocol:e.protocol,documentationUrl:e.documentationUrl}:void 0})}async discover(e){const{getToolRegistry:t}=await Promise.resolve().then(()=>__importStar(require("./agent-call.js"))),r=t();if(!r)return[];if(!e)return r.listAll();return r.search(e)}middleware(){return async(e,t,r)=>{const i=(0,envelope_js_1.validateEnvelope)(e.body);if(!i.ok)return void t.status(400).json({error:i.error});const s=await this.receive(i.value);if(!s.ok){const e="TIMESTAMP_EXPIRED"===s.error||"REPLAY_DETECTED"===s.error?403:401;return void t.status(e).json({error:s.error})}e.agentMessage=s.value,r()}}cleanup(){this.cleanupTimer&&(clearTimeout(this.cleanupTimer),this.cleanupTimer=void 0)}dispose(){this.cleanup()}async trySenderECDH(e){const t=await this.registry.getEntry(e);if(!t.ok||!t.value.x25519PublicKey)return null;const r=!!t.value.mlDsaPublicKey,i=await(0,key_agreement_js_1.importX25519PublicKey)(t.value.x25519PublicKey);if(!i.ok)return null;if(t.value.mlKemPublicKey&&this.identity.mlKemSecretKey){const e=await(0,key_agreement_js_1.senderHybridKeyAgreement)(i.value,t.value.mlKemPublicKey);if(e.ok)return{sharedKey:e.value.sharedKey,ephemeralPublicKey:e.value.ephemeralPublicKey,kemCiphertext:e.value.kemCiphertext,recipientHasMlDsa:r}}const s=await(0,key_agreement_js_1.senderKeyAgreement)(i.value);return s.ok?{...s.value,recipientHasMlDsa:r}:null}async sendWithECDH(e,t,r,i,s){s?.update("Encrypting message with ECDH...",60);const a=await(0,envelope_js_1.createEnvelope)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:t,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:i});if(!a.ok)return(0,shared_1.err)("ENVELOPE_FAILED:ENCRYPT");s?.update("Sending message...",90);const n=await this.transports[0].send(a.value,e.to);return n.ok&&s?.complete(),n}async sendWithHybrid(e,t,r,i,s,a){a?.update("Encrypting message with hybrid KEM...",60);const n=await(0,envelope_js_1.createEnvelopeV2)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:t,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:i,kemCiphertext:s});if(!n.ok)return(0,shared_1.err)("ENVELOPE_FAILED:ENCRYPT");a?.update("Sending message...",90);const o=await this.transports[0].send(n.value,e.to);return o.ok&&a?.complete(),o}async sendWithHybridV3(e,t,r,i,s,a){if(!this.identity.mlDsaSecretKey)return(0,shared_1.err)("ENVELOPE_FAILED:PQ_KEY_MISSING");a?.update("Encrypting with post-quantum signatures...",60);const n=await(0,envelope_js_1.createEnvelopeV3)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:t,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:i,kemCiphertext:s,mlDsaSecretKey:this.identity.mlDsaSecretKey});if(!n.ok)return this.lastDetail=`v3 envelope error: ${n.error}`,(0,shared_1.err)("ENVELOPE_FAILED:ENCRYPT");a?.update("Sending message...",90);const o=await this.transports[0].send(n.value,e.to);return o.ok&&a?.complete(),o}async sendDirect(e,t,r,i){i?.update("Encrypting message...",60);const s=await(0,envelope_js_1.createEnvelope)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:t,privateKey:this.identity.privateKey,sharedKey:r});if(!s.ok)return(0,shared_1.err)("ENVELOPE_FAILED:ENCRYPT");i?.update("Sending message...",90);const a=await this.transports[0].send(s.value,e.to);return a.ok&&i?.complete(),a}async canUseXchange(e){const t=await this.registry.getEntry(e);return!!t.ok&&!0===t.value.xchange}async sendXchange(e,t,r){const i=e.splitChannelConfig??split_channel_js_1.DEFAULT_SPLIT_CONFIG;this.transports.length<i.totalShares&&console.warn(`Split-channel: ${i.totalShares} shares but only ${this.transports.length} transport(s). For channel separation, provide at least ${i.totalShares} transports.`),r?.update("Generating Xchange key...",40);const s=await(0,xchange_1.generateXchangeKey)();if(!s.ok)return(0,shared_1.err)("KEY_AGREEMENT_FAILED");r?.update("Encrypting message...",50);const a=await(0,xchange_1.xchangeEncrypt)(t,s.value);if(!a.ok)return(0,shared_1.err)("ENVELOPE_FAILED:ENCRYPT");const n=await this.ensureCrypto(),o=i.totalShares,c=i.threshold,l=n.nextOddPrime(o)-1,d=n.pkcs7Pad(a.value,l),{key:u,signature:h}=await n.generateHMAC(d);let y;r?.update("Splitting message into shares...",60);try{y=n.splitXorIDA(d,o,c)}catch{return(0,shared_1.err)("ENVELOPE_FAILED:SPLIT")}const p=(0,crypto_utils_js_1.toBase64)(u),_=(0,crypto_utils_js_1.toBase64)(h),E=(0,crypto_utils_js_1.generateUUID)(),m=[];r?.update("Sending shares...",70);for(let t=0;t<y.length;t++){const i=y[t],s=(0,crypto_utils_js_1.formatShareHeader)((0,crypto_utils_js_1.toBase64)(i)),a=(new TextEncoder).encode(s),n=await(0,envelope_js_1.createEnvelopeV4)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,shareData:a,privateKey:this.identity.privateKey,shareIndex:t,shareTotal:o,shareThreshold:c,shareGroupId:E,shareHmacKey:p,shareHmacSig:_});if(!n.ok){m.push((0,shared_1.err)("ENVELOPE_FAILED:ENCRYPT"));continue}const l=this.transports[t%this.transports.length],d=await l.send(n.value,e.to);m.push(d);const u=70+Math.floor((t+1)/y.length*20);r?.update(`Sent share ${t+1}/${y.length}...`,u)}return m.filter(e=>e.ok).length<c?(0,shared_1.err)("SEND_FAILED:BELOW_THRESHOLD"):(r?.complete(),(0,shared_1.ok)(void 0))}async sendSplitChannel(e,t,r,i,s,a,n){const o=e.splitChannelConfig??split_channel_js_1.DEFAULT_SPLIT_CONFIG;this.transports.length<o.totalShares&&console.warn(`Split-channel: ${o.totalShares} shares but only ${this.transports.length} transport(s). For channel separation, provide at least ${o.totalShares} transports.`),n?.update("Splitting message into shares...",50);const c=await(0,split_channel_js_1.splitForChannel)(t,o);if(!c.ok)return(0,shared_1.err)("ENVELOPE_FAILED:SPLIT");const l=c.value;n?.update("Encrypting and sending shares...",70);return(await this.sendShareEnvelopes(e,l,r,i,s,a,n)).filter(e=>e.ok).length<o.threshold?(0,shared_1.err)("SEND_FAILED:BELOW_THRESHOLD"):(n?.complete(),(0,shared_1.ok)(void 0))}async sendShareEnvelopes(e,t,r,i,s,a,n){const o=[];for(let c=0;c<t.length;c++){const l=t[c],d=(new TextEncoder).encode(l.data);let u;if(u=s&&i&&a&&this.identity.mlDsaSecretKey?await(0,envelope_js_1.createEnvelopeV3)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:d,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:i,kemCiphertext:s,mlDsaSecretKey:this.identity.mlDsaSecretKey,shareIndex:l.index,shareTotal:l.total,shareThreshold:l.threshold,shareGroupId:l.groupId,shareHmacKey:l.hmacKey,shareHmacSig:l.hmacSig}):s&&i?await(0,envelope_js_1.createEnvelopeV2)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:d,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:i,kemCiphertext:s,shareIndex:l.index,shareTotal:l.total,shareThreshold:l.threshold,shareGroupId:l.groupId,shareHmacKey:l.hmacKey,shareHmacSig:l.hmacSig}):await(0,envelope_js_1.createEnvelope)({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:d,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:i,shareIndex:l.index,shareTotal:l.total,shareThreshold:l.threshold,shareGroupId:l.groupId,shareHmacKey:l.hmacKey,shareHmacSig:l.hmacSig}),!u.ok){o.push((0,shared_1.err)("ENVELOPE_FAILED:ENCRYPT"));continue}const h=this.transports[c%this.transports.length],y=await h.send(u.value,e.to);o.push(y);const p=70+Math.floor((c+1)/t.length*20);n?.update(`Sent share ${c+1}/${t.length}...`,p)}return o}async receiveSplitShare(e){if(void 0===e.shareGroupId)return(0,shared_1.err)("VERIFICATION_FAILED");const t=await this.receiveRaw(e);if(!t.ok)return t;const{sender:r,decryptedText:i,scope:s,timestamp:a}=t.value,n={data:i,index:e.shareIndex??0,total:e.shareTotal??2,threshold:e.shareThreshold??2,groupId:e.shareGroupId,hmacKey:e.shareHmacKey??"",hmacSig:e.shareHmacSig??""};return this.accumulateShare(n,r,s,a)}async receiveXchangeShare(e){this.lastDetail="";const t=await this.verifyEnvelope(e);if(!t.ok)return t;const r={data:(new TextDecoder).decode(t.value.payloadBytes),index:e.shareIndex,total:e.shareTotal,threshold:e.shareThreshold,groupId:e.shareGroupId,hmacKey:e.shareHmacKey,hmacSig:e.shareHmacSig};return this.accumulateXchangeShare(r,e.sender,e.scope,e.timestamp)}async accumulateXchangeShare(e,t,r,i){const s=this.shareAccumulator.get(e.groupId)??[];if(s.some(t=>t.index===e.index)||(s.push(e),this.shareAccumulator.set(e.groupId,s)),s.length<e.threshold)return(0,shared_1.ok)(null);this.shareAccumulator.delete(e.groupId);const a=s.slice(0,e.threshold),n=e.total,o=e.threshold;let c;try{c=a.map(e=>(0,crypto_utils_js_1.fromBase64)((0,crypto_utils_js_1.parseShareHeader)(e.data)))}catch{return(0,shared_1.err)("DECRYPT_FAILED")}const l=a.map(e=>e.index),d=await this.ensureCrypto();let u,h,y;try{u=d.reconstructXorIDA(c,l,n,o)}catch{return(0,shared_1.err)("DECRYPT_FAILED")}try{h=(0,crypto_utils_js_1.fromBase64)(a[0].hmacKey),y=(0,crypto_utils_js_1.fromBase64)(a[0].hmacSig)}catch{return(0,shared_1.err)("DECRYPT_FAILED")}if(!await d.verifyHMAC(h,u,y))return this.lastDetail="HMAC verification failed before decrypt",(0,shared_1.err)("DECRYPT_FAILED");const p=d.nextOddPrime(n)-1,_=d.pkcs7Unpad(u,p);if(!_.ok)return(0,shared_1.err)("DECRYPT_FAILED");const E=await(0,xchange_1.xchangeDecrypt)(_.value);if(!E.ok)return(0,shared_1.err)("DECRYPT_FAILED:DECRYPTION");let m;try{m=JSON.parse((new TextDecoder).decode(E.value))}catch{return(0,shared_1.err)("DECRYPT_FAILED:PARSE")}return(0,shared_1.ok)({sender:t,payload:m,scope:r,timestamp:i})}async accumulateShare(e,t,r,i){const s=this.shareAccumulator.get(e.groupId)??[];if(s.some(t=>t.index===e.index)||(s.push(e),this.shareAccumulator.set(e.groupId,s)),s.length<e.threshold)return(0,shared_1.ok)(null);this.shareAccumulator.delete(e.groupId);const a=await(0,split_channel_js_1.reconstructFromChannel)(s);if(!a.ok)return(0,shared_1.err)("DECRYPT_FAILED");let n;try{n=JSON.parse((new TextDecoder).decode(a.value))}catch{return(0,shared_1.err)("DECRYPT_FAILED")}return(0,shared_1.ok)({sender:t,payload:n,scope:r,timestamp:i})}async verifyEnvelope(e){if(!e||"object"!=typeof e)return this.lastDetail="envelope is null or not an object",(0,shared_1.err)("VERIFICATION_FAILED:INVALID_ENVELOPE");if(1!==e.v&&2!==e.v&&3!==e.v&&4!==e.v||"Ed25519"!==e.alg)return this.lastDetail=`v=${String(e.v)}, alg=${String(e.alg)}`,(0,shared_1.err)("VERIFICATION_FAILED:UNSUPPORTED_VERSION");if("number"!=typeof e.timestamp||!Number.isFinite(e.timestamp))return this.lastDetail=`timestamp=${String(e.timestamp)} (must be finite number)`,(0,shared_1.err)("VERIFICATION_FAILED:INVALID_ENVELOPE");const t=Math.abs(Date.now()-e.timestamp);if(t>this.timestampWindowMs)return this.lastDetail=`age=${t}ms, max=${this.timestampWindowMs}ms`,(0,shared_1.err)("TIMESTAMP_EXPIRED");const r=void 0!==e.shareGroupId?{shareGroupId:e.shareGroupId,shareIndex:e.shareIndex}:void 0;if(!await this.nonceStore.check(e.nonce,e.sender,r))return this.lastDetail=`nonce=${e.nonce}`,(0,shared_1.err)("REPLAY_DETECTED");const i=await this.registry.resolve(e.sender);if(!i.ok)return this.lastDetail=`did=${e.sender}`,(0,shared_1.err)("VERIFICATION_FAILED:DID_NOT_IN_REGISTRY");const s=await(0,identity_js_1.importPublicKey)(i.value);if(!s.ok)return this.lastDetail=`did=${e.sender}`,(0,shared_1.err)("VERIFICATION_FAILED:KEY_IMPORT_FAILED");if(!e.signature||"string"!=typeof e.signature)return this.lastDetail="signature field missing or invalid",(0,shared_1.err)("VERIFICATION_FAILED:SIGNATURE_MISMATCH");const a=(0,crypto_utils_js_1.fromBase64)(e.signature),n=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}),o=(new TextEncoder).encode(n),c=await(0,identity_js_1.verify)(s.value,a,o);if(!c.ok||!c.value)return this.lastDetail="signature does not match canonical envelope (v1.1.3+ required)",(0,shared_1.err)("VERIFICATION_FAILED:SIGNATURE_MISMATCH");if(3===e.v&&"pqSignature"in e){if("string"!=typeof e.pqSignature)return this.lastDetail="pqSignature field not a string",(0,shared_1.err)("VERIFICATION_FAILED:INVALID_ENVELOPE");const t=await this.registry.getEntry(e.sender);if(!t.ok||!t.value.mlDsaPublicKey)return this.lastDetail=`did=${e.sender} missing ML-DSA public key`,(0,shared_1.err)("VERIFICATION_FAILED:PQ_KEY_MISSING");const r=(0,crypto_utils_js_1.fromBase64)(e.pqSignature),i=await(0,identity_js_2.verifyMlDsa65)(t.value.mlDsaPublicKey,r,o);if(!i.ok||!i.value)return this.lastDetail="ML-DSA-65 signature does not match canonical envelope (v1.1.3+ required)",(0,shared_1.err)("VERIFICATION_FAILED:PQ_SIGNATURE_MISMATCH")}if(!await this.registry.hasScope(e.sender,e.scope))return this.lastDetail=`scope=${e.scope}`,(0,shared_1.err)("SCOPE_DENIED");if("string"!=typeof e.payload)return this.lastDetail="payload field not a string",(0,shared_1.err)("VERIFICATION_FAILED:INVALID_ENVELOPE");const l=(0,crypto_utils_js_1.fromBase64)(e.payload);return(0,shared_1.ok)({senderRawKey:i.value,payloadBytes:l})}async receiveRaw(e){const t=await this.verifyEnvelope(e);if(!t.ok)return t;if(4===e.v)return(0,shared_1.err)("VERIFICATION_FAILED:UNSUPPORTED_VERSION");let r;if(2!==e.v&&3!==e.v||!("kemCiphertext"in e)){if(!e.ephemeralPub)return(0,shared_1.err)("DECRYPT_FAILED:NO_EPHEMERAL_KEY");{if("string"!=typeof e.ephemeralPub)return(0,shared_1.err)("DECRYPT_FAILED:INVALID_ENVELOPE");const t=(0,crypto_utils_js_1.fromBase64)(e.ephemeralPub),i=await(0,key_agreement_js_1.receiverKeyAgreement)(this.identity.x25519PrivateKey,t);if(i.ok)r=i.value;else{if(this.identity.rotatedKeys&&this.identity.rotatedKeys.length>0)for(const e of this.identity.rotatedKeys){const i=await(0,key_agreement_js_1.receiverKeyAgreement)(e.x25519PrivateKey,t);if(i.ok){r=i.value;break}}if(!r)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT")}}}else{if(!this.identity.mlKemSecretKey)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT");if("string"!=typeof e.ephemeralPub||"string"!=typeof e.kemCiphertext)return(0,shared_1.err)("DECRYPT_FAILED:INVALID_ENVELOPE");const t=(0,crypto_utils_js_1.fromBase64)(e.ephemeralPub),i=(0,crypto_utils_js_1.fromBase64)(e.kemCiphertext);if(!this.identity.mlKemPublicKey||!this.identity.mlKemSecretKey)return this.lastDetail="ML-KEM keys not available in identity",(0,shared_1.err)("DECRYPT_FAILED:MISSING_MLKEM_KEYS");const s=await(0,key_agreement_js_1.receiverHybridKeyAgreement)(this.identity.x25519PrivateKey,this.identity.rawX25519PublicKey,t,i,this.identity.mlKemSecretKey,this.identity.mlKemPublicKey);if(s.ok)r=s.value;else{if(this.identity.rotatedKeys&&this.identity.rotatedKeys.length>0)for(const e of this.identity.rotatedKeys){if(!e.mlKemSecretKey)continue;const s=await(0,key_agreement_js_1.receiverHybridKeyAgreement)(e.x25519PrivateKey,this.identity.rawX25519PublicKey,t,i,e.mlKemSecretKey,this.identity.mlKemPublicKey);if(s.ok){r=s.value;break}}if(!r)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT")}}if(!r)return(0,shared_1.err)("DECRYPT_FAILED:KEY_AGREEMENT");const i=await(0,envelope_js_1.decryptPayload)(e,r);if(!i.ok)return(0,shared_1.err)("DECRYPT_FAILED:DECRYPTION");const s=(new TextDecoder).decode(i.value);return(0,shared_1.ok)({sender:e.sender,decryptedText:s,scope:e.scope,timestamp:e.timestamp})}async createTestEnvelope(e,t,r){const i=await this.registry.getEntry(e);if(!i.ok||!i.value.x25519PublicKey)return null;const s=await(0,key_agreement_js_1.importX25519PublicKey)(i.value.x25519PublicKey);if(!s.ok)return null;const a=await(0,key_agreement_js_1.senderKeyAgreement)(s.value);if(!a.ok)return null;const n=(new TextEncoder).encode(JSON.stringify(t)),o=await(0,envelope_js_1.createEnvelope)({senderDid:this.identity.did,recipientDid:e,scope:r,plaintext:n,privateKey:this.identity.privateKey,sharedKey:a.value.sharedKey,ephemeralPublicKey:a.value.ephemeralPublicKey});return o.ok?o.value:null}async invite(e){if(!this.transports||0===this.transports.length)return(0,shared_1.err)("SEND_FAILED");const t=Buffer.from(this.identity.rawPublicKey).toString("base64"),r={from:this.identity.did,to:e.to,payload:{agentName:this.name,message:e.message,publicKey:t,endpoint:""}},i=this.transports[0];if(!i)return(0,shared_1.err)("SEND_FAILED");return(await i.send(r,e.to)).ok?(0,shared_1.ok)(void 0):(0,shared_1.err)("SEND_FAILED")}}exports.Agent=Agent;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.exportBackup=exportBackup,exports.importBackup=importBackup;const shared_1=require("../_deps/shared/index.js"),crypto_utils_js_1=require("./crypto-utils.js"),identity_js_1=require("./identity.js"),PBKDF2_ITERATIONS=31e4,SALT_LENGTH=16,IV_LENGTH=12,KEY_LENGTH=32;function toArrayBuffer(e){const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}async function deriveKey(e,t){try{if(t.length!==SALT_LENGTH)return(0,shared_1.err)("INVALID_BACKUP");const r=await crypto.subtle.importKey("raw",(new TextEncoder).encode(e),"PBKDF2",!1,["deriveBits"]),s=new Uint8Array(await crypto.subtle.deriveBits({name:"PBKDF2",hash:"SHA-256",salt:toArrayBuffer(t),iterations:31e4},r,256)),a=await crypto.subtle.importKey("raw",toArrayBuffer(s),{name:"AES-GCM"},!1,["encrypt","decrypt"]);return(0,shared_1.ok)(a)}catch{return(0,shared_1.err)("PBKDF2_FAILED")}}async function serializeIdentity(e){try{const t=await(0,identity_js_1.exportPKCS8)(e.privateKey);if(!t.ok)return(0,shared_1.err)("EXPORT_FAILED");const r=await(0,identity_js_1.exportX25519PKCS8)(e.x25519PrivateKey);if(!r.ok)return(0,shared_1.err)("EXPORT_FAILED");const s=(0,identity_js_1.exportMlKemSecretKey)(e),a=(0,identity_js_1.exportMlKemPublicKey)(e),o=(0,identity_js_1.exportMlDsaSecretKey)(e),i=(0,identity_js_1.exportMlDsaPublicKey)(e),_=e.rotatedKeys?await Promise.all(e.rotatedKeys.map(async e=>{const t=await(0,identity_js_1.exportX25519PKCS8)(e.x25519PrivateKey);if(!t.ok)throw new Error("Failed to export rotated X25519 key");return{rotatedAt:e.rotatedAt,x25519Pkcs8:(0,crypto_utils_js_1.toBase64)(t.value),...e.mlKemSecretKey?{mlKemSecretKey:(0,crypto_utils_js_1.toBase64)(e.mlKemSecretKey)}:{}}})):void 0;return(0,shared_1.ok)({did:e.did,rawPublicKey:(0,crypto_utils_js_1.toBase64)(e.rawPublicKey),ed25519Pkcs8:(0,crypto_utils_js_1.toBase64)(t.value),x25519Pkcs8:(0,crypto_utils_js_1.toBase64)(r.value),...s?{mlKemSecretKey:(0,crypto_utils_js_1.toBase64)(s)}:{},...a?{mlKemPublicKey:(0,crypto_utils_js_1.toBase64)(a)}:{},...o?{mlDsaSecretKey:(0,crypto_utils_js_1.toBase64)(o)}:{},...i?{mlDsaPublicKey:(0,crypto_utils_js_1.toBase64)(i)}:{},..._?{rotatedKeys:_}:{},exportedAt:Date.now()})}catch{return(0,shared_1.err)("EXPORT_FAILED")}}async function exportBackup(e,t){try{const r=await serializeIdentity(e);if(!r.ok)return r;const s=crypto.getRandomValues(new Uint8Array(SALT_LENGTH)),a=crypto.getRandomValues(new Uint8Array(IV_LENGTH)),o=await deriveKey(t,s);if(!o.ok)return o;const i=JSON.stringify(r.value),_=(new TextEncoder).encode(i),c=await crypto.subtle.encrypt({name:"AES-GCM",iv:toArrayBuffer(a)},o.value,_),n=new Uint8Array(c);if(n.length<16)return(0,shared_1.err)("ENCRYPTION_FAILED");const y=n.length-16,u=n.slice(0,y),l=n.slice(y);return(0,shared_1.ok)({version:1,salt:(0,crypto_utils_js_1.toBase64)(s),iv:(0,crypto_utils_js_1.toBase64)(a),ciphertext:(0,crypto_utils_js_1.toBase64)(u),tag:(0,crypto_utils_js_1.toBase64)(l)})}catch{return(0,shared_1.err)("ENCRYPTION_FAILED")}}async function importBackup(e,t){try{if(1!==e.version)return(0,shared_1.err)("INVALID_BACKUP");let r,s,a,o;try{r=(0,crypto_utils_js_1.fromBase64)(e.salt),s=(0,crypto_utils_js_1.fromBase64)(e.iv),a=(0,crypto_utils_js_1.fromBase64)(e.ciphertext),o=(0,crypto_utils_js_1.fromBase64)(e.tag)}catch{return(0,shared_1.err)("INVALID_BACKUP")}if(r.length!==SALT_LENGTH||s.length!==IV_LENGTH||16!==o.length)return(0,shared_1.err)("INVALID_BACKUP");const i=await deriveKey(t,r);if(!i.ok)return i;const _=new Uint8Array(a.length+o.length);let c,n,y,u,l,d,p,K;_.set(a),_.set(o,a.length);try{c=await crypto.subtle.decrypt({name:"AES-GCM",iv:toArrayBuffer(s)},i.value,toArrayBuffer(_))}catch(e){return console.warn("[xBind] GCM verification failed:",e),(0,shared_1.err)("INVALID_PASSWORD")}try{const e=(new TextDecoder).decode(c);n=JSON.parse(e)}catch{return(0,shared_1.err)("INVALID_BACKUP")}if(!n.did||!n.ed25519Pkcs8||!n.x25519Pkcs8)return(0,shared_1.err)("INVALID_BACKUP");try{y=(0,crypto_utils_js_1.fromBase64)(n.ed25519Pkcs8),u=(0,crypto_utils_js_1.fromBase64)(n.x25519Pkcs8),n.mlKemSecretKey&&(l=(0,crypto_utils_js_1.fromBase64)(n.mlKemSecretKey)),n.mlKemPublicKey&&(d=(0,crypto_utils_js_1.fromBase64)(n.mlKemPublicKey)),n.mlDsaSecretKey&&(p=(0,crypto_utils_js_1.fromBase64)(n.mlDsaSecretKey)),n.mlDsaPublicKey&&(K=(0,crypto_utils_js_1.fromBase64)(n.mlDsaPublicKey))}catch{return(0,shared_1.err)("INVALID_BACKUP")}const m=await(0,identity_js_1.importIdentity)(y,u,l,d,p,K);if(!m.ok)return(0,shared_1.err)("IMPORT_FAILED");if(n.rotatedKeys&&n.rotatedKeys.length>0){const e=m.value,t=await Promise.all(n.rotatedKeys.map(async e=>{const t=(0,crypto_utils_js_1.fromBase64)(e.x25519Pkcs8),r=await crypto.subtle.importKey("pkcs8",toArrayBuffer(t),{name:"X25519"},!0,["deriveBits"]),s=e.mlKemSecretKey?(0,crypto_utils_js_1.fromBase64)(e.mlKemSecretKey):void 0;return{rotatedAt:e.rotatedAt,x25519PrivateKey:r,...s?{mlKemSecretKey:s}:{}}}));return(0,shared_1.ok)({...e,rotatedKeys:t})}return m}catch(e){return console.warn("[xBind] Import backup failed:",e),(0,shared_1.err)("DECRYPTION_FAILED")}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.exportBackup=exportBackup,exports.importBackup=importBackup;const shared_1=require("../_deps/shared/index.js"),crypto_utils_js_1=require("./crypto-utils.js"),identity_js_1=require("./identity.js"),PBKDF2_ITERATIONS=31e4,SALT_LENGTH=16,IV_LENGTH=12;function toArrayBuffer(e){const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}async function deriveKey(e,t){try{if(t.length!==SALT_LENGTH)return(0,shared_1.err)("INVALID_BACKUP");const r=await crypto.subtle.importKey("raw",(new TextEncoder).encode(e),"PBKDF2",!1,["deriveBits"]),s=new Uint8Array(await crypto.subtle.deriveBits({name:"PBKDF2",hash:"SHA-256",salt:toArrayBuffer(t),iterations:31e4},r,256)),a=await crypto.subtle.importKey("raw",toArrayBuffer(s),{name:"AES-GCM"},!1,["encrypt","decrypt"]);return(0,shared_1.ok)(a)}catch{return(0,shared_1.err)("PBKDF2_FAILED")}}async function serializeIdentity(e){try{const t=await(0,identity_js_1.exportPKCS8)(e.privateKey);if(!t.ok)return(0,shared_1.err)("EXPORT_FAILED");const r=await(0,identity_js_1.exportX25519PKCS8)(e.x25519PrivateKey);if(!r.ok)return(0,shared_1.err)("EXPORT_FAILED");const s=(0,identity_js_1.exportMlKemSecretKey)(e),a=(0,identity_js_1.exportMlKemPublicKey)(e),o=(0,identity_js_1.exportMlDsaSecretKey)(e),i=(0,identity_js_1.exportMlDsaPublicKey)(e),_=e.rotatedKeys?await Promise.all(e.rotatedKeys.map(async e=>{const t=await(0,identity_js_1.exportX25519PKCS8)(e.x25519PrivateKey);if(!t.ok)throw new Error("Failed to export rotated X25519 key");return{rotatedAt:e.rotatedAt,x25519Pkcs8:(0,crypto_utils_js_1.toBase64)(t.value),...e.mlKemSecretKey?{mlKemSecretKey:(0,crypto_utils_js_1.toBase64)(e.mlKemSecretKey)}:{}}})):void 0;return(0,shared_1.ok)({did:e.did,rawPublicKey:(0,crypto_utils_js_1.toBase64)(e.rawPublicKey),ed25519Pkcs8:(0,crypto_utils_js_1.toBase64)(t.value),x25519Pkcs8:(0,crypto_utils_js_1.toBase64)(r.value),...s?{mlKemSecretKey:(0,crypto_utils_js_1.toBase64)(s)}:{},...a?{mlKemPublicKey:(0,crypto_utils_js_1.toBase64)(a)}:{},...o?{mlDsaSecretKey:(0,crypto_utils_js_1.toBase64)(o)}:{},...i?{mlDsaPublicKey:(0,crypto_utils_js_1.toBase64)(i)}:{},..._?{rotatedKeys:_}:{},exportedAt:Date.now()})}catch{return(0,shared_1.err)("EXPORT_FAILED")}}async function exportBackup(e,t){try{const r=await serializeIdentity(e);if(!r.ok)return r;const s=crypto.getRandomValues(new Uint8Array(SALT_LENGTH)),a=crypto.getRandomValues(new Uint8Array(IV_LENGTH)),o=await deriveKey(t,s);if(!o.ok)return o;const i=JSON.stringify(r.value),_=(new TextEncoder).encode(i),c=await crypto.subtle.encrypt({name:"AES-GCM",iv:toArrayBuffer(a)},o.value,_),y=new Uint8Array(c);if(y.length<16)return(0,shared_1.err)("ENCRYPTION_FAILED");const n=y.length-16,u=y.slice(0,n),l=y.slice(n);return(0,shared_1.ok)({version:1,salt:(0,crypto_utils_js_1.toBase64)(s),iv:(0,crypto_utils_js_1.toBase64)(a),ciphertext:(0,crypto_utils_js_1.toBase64)(u),tag:(0,crypto_utils_js_1.toBase64)(l)})}catch{return(0,shared_1.err)("ENCRYPTION_FAILED")}}async function importBackup(e,t){try{if(1!==e.version)return(0,shared_1.err)("INVALID_BACKUP");let r,s,a,o;try{r=(0,crypto_utils_js_1.fromBase64)(e.salt),s=(0,crypto_utils_js_1.fromBase64)(e.iv),a=(0,crypto_utils_js_1.fromBase64)(e.ciphertext),o=(0,crypto_utils_js_1.fromBase64)(e.tag)}catch{return(0,shared_1.err)("INVALID_BACKUP")}if(r.length!==SALT_LENGTH||s.length!==IV_LENGTH||16!==o.length)return(0,shared_1.err)("INVALID_BACKUP");const i=await deriveKey(t,r);if(!i.ok)return i;const _=new Uint8Array(a.length+o.length);let c,y,n,u,l,d,p,K;_.set(a),_.set(o,a.length);try{c=await crypto.subtle.decrypt({name:"AES-GCM",iv:toArrayBuffer(s)},i.value,toArrayBuffer(_))}catch{return(0,shared_1.err)("INVALID_PASSWORD")}try{const e=(new TextDecoder).decode(c);y=JSON.parse(e)}catch{return(0,shared_1.err)("INVALID_BACKUP")}if(!y.did||!y.ed25519Pkcs8||!y.x25519Pkcs8)return(0,shared_1.err)("INVALID_BACKUP");try{n=(0,crypto_utils_js_1.fromBase64)(y.ed25519Pkcs8),u=(0,crypto_utils_js_1.fromBase64)(y.x25519Pkcs8),y.mlKemSecretKey&&(l=(0,crypto_utils_js_1.fromBase64)(y.mlKemSecretKey)),y.mlKemPublicKey&&(d=(0,crypto_utils_js_1.fromBase64)(y.mlKemPublicKey)),y.mlDsaSecretKey&&(p=(0,crypto_utils_js_1.fromBase64)(y.mlDsaSecretKey)),y.mlDsaPublicKey&&(K=(0,crypto_utils_js_1.fromBase64)(y.mlDsaPublicKey))}catch{return(0,shared_1.err)("INVALID_BACKUP")}const m=await(0,identity_js_1.importIdentity)(n,u,l,d,p,K);if(!m.ok)return(0,shared_1.err)("IMPORT_FAILED");if(y.rotatedKeys&&y.rotatedKeys.length>0){const e=m.value,t=await Promise.all(y.rotatedKeys.map(async e=>{const t=(0,crypto_utils_js_1.fromBase64)(e.x25519Pkcs8),r=await crypto.subtle.importKey("pkcs8",toArrayBuffer(t),{name:"X25519"},!0,["deriveBits"]),s=e.mlKemSecretKey?(0,crypto_utils_js_1.fromBase64)(e.mlKemSecretKey):void 0;return{rotatedAt:e.rotatedAt,x25519PrivateKey:r,...s?{mlKemSecretKey:s}:{}}}));return(0,shared_1.ok)({...e,rotatedKeys:t})}return m}catch{return(0,shared_1.err)("DECRYPTION_FAILED")}}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(null!=t)for(var r=e(t),i=0;i<r.length;i++)"default"!==r[i]&&__createBinding(n,t,r[i]);return __setModuleDefault(n,t),n}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.initCommand=initCommand,exports.main=main;const node_util_1=require("node:util"),fs=__importStar(require("node:fs")),path=__importStar(require("node:path")),node_child_process_1=require("node:child_process"),readline=__importStar(require("node:readline/promises")),node_process_1=require("node:process"),invite_js_1=require("../invite.js");function getTemplateDir(){let e=__dirname;for(;"/"!==e;){if(fs.existsSync(path.join(e,"package.json")))return path.join(e,"templates");e=path.dirname(e)}return path.join(__dirname,"../../templates")}const TEMPLATES={"node-typescript":{name:"Node.js + TypeScript",description:"Node.js with TypeScript, best for backend services",packageManager:"npm",entryPoint:"src/index.ts",startCommand:"npm run dev"},"node-javascript":{name:"Node.js + JavaScript",description:"Node.js with JavaScript, minimal setup",packageManager:"npm",entryPoint:"src/index.js",startCommand:"npm start"},deno:{name:"Deno",description:"Modern TypeScript runtime",packageManager:"deno",entryPoint:"mod.ts",startCommand:"deno run --allow-net --allow-env --allow-read mod.ts"},"cloudflare-worker":{name:"Cloudflare Worker",description:"Edge runtime on Cloudflare",packageManager:"npm",entryPoint:"src/index.ts",startCommand:"npm run dev"},"vercel-function":{name:"Vercel Function",description:"Serverless function on Vercel",packageManager:"npm",entryPoint:"api/xbind.ts",startCommand:"npm run dev"}};class Spinner{frames=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];currentFrame=0;intervalId;message;constructor(e){this.message=e}start(){this.intervalId=setInterval(()=>{const e=this.frames[this.currentFrame];process.stdout.write(`\r${e} ${this.message}`),this.currentFrame=(this.currentFrame+1)%this.frames.length},80)}succeed(e){this.stop(),process.stdout.write(`\r✅ ${e??this.message}\n`)}fail(e){this.stop(),process.stdout.write(`\r❌ ${e??this.message}\n`)}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}}function normalizeInviteUrl(e,t){return e.startsWith("http://")||e.startsWith("https://")?e:(e.startsWith("XBD-"),`${t}/invite/${e}`)}function isValidProjectName(e){return/^[a-z0-9-_]+$/i.test(e)&&e.length>0&&e.length<=100}async function prompt(e,t){const n=readline.createInterface({input:node_process_1.stdin,output:node_process_1.stdout}),r=await n.question(t?`${e} (${t}): `:`${e}: `);return n.close(),r.trim()||t||""}async function select(e,t,n=0){console.log(e),t.forEach((e,t)=>{const r=t===n?"→":" ";console.log(` ${r} ${t+1}. ${e.label} - ${e.description}`)});const r=readline.createInterface({input:node_process_1.stdin,output:node_process_1.stdout}),i=await r.question(`Select (1-${t.length}): `);r.close();const o=parseInt(i.trim(),10)-1;return o>=0&&o<t.length?t[o]?.value??t[n]?.value??"":t[n]?.value??""}function runCommand(e,t,n){return new Promise((r,i)=>{const o=(0,node_child_process_1.spawn)(e,t,{cwd:n,stdio:"ignore",shell:!0});o.on("close",e=>{0===e?r():i(new Error(`Command failed with code ${e??"unknown"}`))}),o.on("error",i)})}async function copyTemplate(e,t,n){const r=path.join(getTemplateDir(),e),i=await fs.promises.readdir(r,{recursive:!0,withFileTypes:!0});for(const e of i)if(e.isFile()){const i=e.parentPath||e.path||r,o=path.relative(r,path.join(i,e.name)),s=path.join(r,o),a=path.join(t,o);await fs.promises.mkdir(path.dirname(a),{recursive:!0});let c=await fs.promises.readFile(s,"utf-8");n&&(c=c.replace(/{{INVITE_URL}}/g,n.url),c=c.replace(/{{INVITE_ID}}/g,n.id),c=c.replace(/{{SERVICE_NAME}}/g,n.from.name),c=c.replace(/{{SERVICE_DID}}/g,n.from.did),c=c.replace(/{{SERVICE_ENDPOINT}}/g,n.from.endpoint)),await fs.promises.writeFile(a,c,"utf-8")}}async function installDependencies(e,t){"npm"===t&&await runCommand("npm",["install"],e)}async function initCommand(e={}){const t=e.registryUrl||"https://xbind.to";let n,r;if(e.invite){r=normalizeInviteUrl(e.invite,t);const i=new Spinner("Fetching invite details...");i.start();try{const e=new invite_js_1.InviteService({inviteApiUrl:t}),o=await e.get(r);if(!o.ok)return i.fail(`Failed to fetch invite: ${o.error.message}`),o.error.hint&&console.error(`Hint: ${o.error.hint}`),void(process.exitCode=1);if(n=o.value,!n)return i.fail("Invalid invite data received"),void(process.exitCode=1);i.succeed(`Connected to ${n.from.name}`)}catch(e){return i.fail("Failed to fetch invite details"),console.error(e instanceof Error?e.message:String(e)),void(process.exitCode=1)}}let i=e.name,o=e.runtime;if(e.yes)i=i||"my-xbind-app",o=o||"node-typescript";else{if(!i){const e=n?`connect-${n.from.name}`:"my-xbind-app";i=await prompt("Project name",e)}o||(o=await select("\nSelect runtime:",Object.entries(TEMPLATES).map(([e,t])=>({value:e,label:t.name,description:t.description})),0))}if(!isValidProjectName(i))return console.error("❌ Invalid project name. Use only letters, numbers, hyphens, and underscores."),void(process.exitCode=1);const s=path.resolve(process.cwd(),i);if(fs.existsSync(s))return console.error(`❌ Directory "${i}" already exists.`),void(process.exitCode=1);if(!o||!TEMPLATES[o])return console.error("❌ Invalid runtime selection."),void(process.exitCode=1);const a=TEMPLATES[o];console.log(`\n📦 Creating ${a.name} project: ${i}`);const c=new Spinner("Creating project structure...");c.start();try{await fs.promises.mkdir(s,{recursive:!0}),await copyTemplate(o,s,n),c.succeed("Project structure created")}catch(e){return c.fail("Failed to create project structure"),console.error(e instanceof Error?e.message:String(e)),void(process.exitCode=1)}if("none"!==a.packageManager&&"test"!==process.env.NODE_ENV){const e=new Spinner("Installing dependencies...");e.start();try{await installDependencies(s,a.packageManager),e.succeed("Dependencies installed")}catch(t){e.fail("Failed to install dependencies"),console.error("You can install them manually later.")}}if(n||r){const e=n?.url||r||"";process.env.DEBUG_CLI&&console.log("[DEBUG] Writing .env file:",{invite:!!n,inviteUrl:r,finalInviteUrl:e,projectPath:s}),e&&await fs.promises.writeFile(path.join(s,".env"),`XBIND_INVITE_CODE=${e}\n`,"utf-8")}else process.env.DEBUG_CLI&&console.log("[DEBUG] Not writing .env file:",{invite:!!n,inviteUrl:r});console.log("\n✅ Ready!\n"),console.log("Next steps:"),console.log(` cd ${i}`),console.log(` ${a.startCommand}`),n?(console.log(`\n🔗 Connected to: ${n.from.name}`),console.log(` DID: ${n.from.did}`)):console.log("\n💡 To connect to a service, get an invite code and update .env file.")}async function main(e=process.argv.slice(2)){const{values:t}=(0,node_util_1.parseArgs)({args:e,options:{invite:{type:"string",short:"i"},name:{type:"string",short:"n"},runtime:{type:"string",short:"r"},yes:{type:"boolean",short:"y"},"registry-url":{type:"string"},help:{type:"boolean",short:"h"}}});t.help?console.log("\nXBind CLI - One-Line M2M Setup\n\nUsage:\n npx xbind-init [options]\n\nOptions:\n -i, --invite <url> Invite URL or code\n -n, --name <name> Project name\n -r, --runtime <runtime> Runtime template (node-typescript, node-javascript, deno, cloudflare-worker, vercel-function)\n -y, --yes Skip interactive prompts (use defaults)\n --registry-url <url> Custom registry URL (default: https://xbind.to)\n -h, --help Show this help message\n\nExamples:\n npx xbind-init --invite https://xbind.to/invite/XBD-abc123\n npx xbind-init --invite XBD-abc123 --name my-app --runtime node-typescript\n npx xbind-init --yes\n ".trim()):await initCommand({invite:t.invite,name:t.name,runtime:t.runtime,yes:t.yes,"registry-url":t["registry-url"]})}const isDirectRun=process.argv[1]?.endsWith("init.ts")||process.argv[1]?.endsWith("init.js");isDirectRun&&main().catch(e=>{console.error("Fatal:",e instanceof Error?e.message:String(e)),process.exitCode=1});
2
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(null!=t)for(var r=e(t),i=0;i<r.length;i++)"default"!==r[i]&&__createBinding(n,t,r[i]);return __setModuleDefault(n,t),n}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.initCommand=initCommand,exports.main=main;const node_util_1=require("node:util"),fs=__importStar(require("node:fs")),path=__importStar(require("node:path")),node_child_process_1=require("node:child_process"),readline=__importStar(require("node:readline/promises")),node_process_1=require("node:process"),invite_js_1=require("../invite.js");function getTemplateDir(){let e=__dirname;for(;"/"!==e;){if(fs.existsSync(path.join(e,"package.json")))return path.join(e,"templates");e=path.dirname(e)}return path.join(__dirname,"../../templates")}const TEMPLATES={"node-typescript":{name:"Node.js + TypeScript",description:"Node.js with TypeScript, best for backend services",packageManager:"npm",entryPoint:"src/index.ts",startCommand:"npm run dev"},"node-javascript":{name:"Node.js + JavaScript",description:"Node.js with JavaScript, minimal setup",packageManager:"npm",entryPoint:"src/index.js",startCommand:"npm start"},deno:{name:"Deno",description:"Modern TypeScript runtime",packageManager:"deno",entryPoint:"mod.ts",startCommand:"deno run --allow-net --allow-env --allow-read mod.ts"},"cloudflare-worker":{name:"Cloudflare Worker",description:"Edge runtime on Cloudflare",packageManager:"npm",entryPoint:"src/index.ts",startCommand:"npm run dev"},"vercel-function":{name:"Vercel Function",description:"Serverless function on Vercel",packageManager:"npm",entryPoint:"api/xbind.ts",startCommand:"npm run dev"}};class Spinner{frames=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];currentFrame=0;intervalId;message;constructor(e){this.message=e}start(){this.intervalId=setInterval(()=>{const e=this.frames[this.currentFrame];process.stdout.write(`\r${e} ${this.message}`),this.currentFrame=(this.currentFrame+1)%this.frames.length},80)}succeed(e){this.stop(),process.stdout.write(`\r✅ ${e??this.message}\n`)}fail(e){this.stop(),process.stdout.write(`\r❌ ${e??this.message}\n`)}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}}function normalizeInviteUrl(e,t){return e.startsWith("http://")||e.startsWith("https://")?e:(e.startsWith("XBD-"),`${t}/invite/${e}`)}function isValidProjectName(e){return/^[a-z0-9-_]+$/i.test(e)&&e.length>0&&e.length<=100}async function prompt(e,t){const n=readline.createInterface({input:node_process_1.stdin,output:node_process_1.stdout}),r=await n.question(t?`${e} (${t}): `:`${e}: `);return n.close(),r.trim()||t||""}async function select(e,t,n=0){console.log(e),t.forEach((e,t)=>{const r=t===n?"→":" ";console.log(` ${r} ${t+1}. ${e.label} - ${e.description}`)});const r=readline.createInterface({input:node_process_1.stdin,output:node_process_1.stdout}),i=await r.question(`Select (1-${t.length}): `);r.close();const o=parseInt(i.trim(),10)-1;return o>=0&&o<t.length?t[o]?.value??t[n]?.value??"":t[n]?.value??""}function runCommand(e,t,n){return new Promise((r,i)=>{const o=(0,node_child_process_1.spawn)(e,t,{cwd:n,stdio:"ignore",shell:!0});o.on("close",e=>{0===e?r():i(new Error(`Command failed with code ${e??"unknown"}`))}),o.on("error",i)})}async function copyTemplate(e,t,n){const r=path.join(getTemplateDir(),e),i=await fs.promises.readdir(r,{recursive:!0,withFileTypes:!0});for(const e of i)if(e.isFile()){const i=e.parentPath||e.path||r,o=path.relative(r,path.join(i,e.name)),s=path.join(r,o),a=path.join(t,o);await fs.promises.mkdir(path.dirname(a),{recursive:!0});let c=await fs.promises.readFile(s,"utf-8");n&&(c=c.replace(/{{INVITE_URL}}/g,n.url),c=c.replace(/{{INVITE_ID}}/g,n.id),c=c.replace(/{{SERVICE_NAME}}/g,n.from.name),c=c.replace(/{{SERVICE_DID}}/g,n.from.did),c=c.replace(/{{SERVICE_ENDPOINT}}/g,n.from.endpoint)),await fs.promises.writeFile(a,c,"utf-8")}}async function installDependencies(e,t){"npm"===t&&await runCommand("npm",["install"],e)}async function initCommand(e={}){const t=e.registryUrl||"https://xbind.to";let n,r;if(e.invite){r=normalizeInviteUrl(e.invite,t);const i=new Spinner("Fetching invite details...");i.start();try{const e=new invite_js_1.InviteService({inviteApiUrl:t}),o=await e.get(r);if(!o.ok)return i.fail(`Failed to fetch invite: ${o.error.message}`),o.error.hint&&console.error(`Hint: ${o.error.hint}`),void(process.exitCode=1);if(n=o.value,!n)return i.fail("Invalid invite data received"),void(process.exitCode=1);i.succeed(`Connected to ${n.from.name}`)}catch(e){return i.fail("Failed to fetch invite details"),console.error(e instanceof Error?e.message:String(e)),void(process.exitCode=1)}}let i=e.name,o=e.runtime;if(e.yes)i=i||"my-xbind-app",o=o||"node-typescript";else{if(!i){const e=n?`connect-${n.from.name}`:"my-xbind-app";i=await prompt("Project name",e)}o||(o=await select("\nSelect runtime:",Object.entries(TEMPLATES).map(([e,t])=>({value:e,label:t.name,description:t.description})),0))}if(!isValidProjectName(i))return console.error("❌ Invalid project name. Use only letters, numbers, hyphens, and underscores."),void(process.exitCode=1);const s=path.resolve(process.cwd(),i);if(fs.existsSync(s))return console.error(`❌ Directory "${i}" already exists.`),void(process.exitCode=1);if(!o||!TEMPLATES[o])return console.error("❌ Invalid runtime selection."),void(process.exitCode=1);const a=TEMPLATES[o];console.log(`\n📦 Creating ${a.name} project: ${i}`);const c=new Spinner("Creating project structure...");c.start();try{await fs.promises.mkdir(s,{recursive:!0}),await copyTemplate(o,s,n),c.succeed("Project structure created")}catch(e){return c.fail("Failed to create project structure"),console.error(e instanceof Error?e.message:String(e)),void(process.exitCode=1)}if("none"!==a.packageManager&&"test"!==process.env.NODE_ENV){const e=new Spinner("Installing dependencies...");e.start();try{await installDependencies(s,a.packageManager),e.succeed("Dependencies installed")}catch{e.fail("Failed to install dependencies"),console.error("You can install them manually later.")}}if(n||r){const e=n?.url||r||"";process.env.DEBUG_CLI&&console.log("[DEBUG] Writing .env file:",{invite:!!n,inviteUrl:r,finalInviteUrl:e,projectPath:s}),e&&await fs.promises.writeFile(path.join(s,".env"),`XBIND_INVITE_CODE=${e}\n`,"utf-8")}else process.env.DEBUG_CLI&&console.log("[DEBUG] Not writing .env file:",{invite:!!n,inviteUrl:r});console.log("\n✅ Ready!\n"),console.log("Next steps:"),console.log(` cd ${i}`),console.log(` ${a.startCommand}`),n?(console.log(`\n🔗 Connected to: ${n.from.name}`),console.log(` DID: ${n.from.did}`)):console.log("\n💡 To connect to a service, get an invite code and update .env file.")}async function main(e=process.argv.slice(2)){const{values:t}=(0,node_util_1.parseArgs)({args:e,options:{invite:{type:"string",short:"i"},name:{type:"string",short:"n"},runtime:{type:"string",short:"r"},yes:{type:"boolean",short:"y"},"registry-url":{type:"string"},help:{type:"boolean",short:"h"}}});t.help?console.log("\nXBind CLI - One-Line M2M Setup\n\nUsage:\n npx xbind-init [options]\n\nOptions:\n -i, --invite <url> Invite URL or code\n -n, --name <name> Project name\n -r, --runtime <runtime> Runtime template (node-typescript, node-javascript, deno, cloudflare-worker, vercel-function)\n -y, --yes Skip interactive prompts (use defaults)\n --registry-url <url> Custom registry URL (default: https://xbind.to)\n -h, --help Show this help message\n\nExamples:\n npx xbind-init --invite https://xbind.to/invite/XBD-abc123\n npx xbind-init --invite XBD-abc123 --name my-app --runtime node-typescript\n npx xbind-init --yes\n ".trim()):await initCommand({invite:t.invite,name:t.name,runtime:t.runtime,yes:t.yes,"registry-url":t["registry-url"]})}const isDirectRun=process.argv[1]?.endsWith("init.ts")||process.argv[1]?.endsWith("init.js");isDirectRun&&main().catch(e=>{console.error("Fatal:",e instanceof Error?e.message:String(e)),process.exitCode=1});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ConnectionPool=void 0,exports.getGlobalPool=getGlobalPool,exports.resetGlobalPool=resetGlobalPool;class ConnectionPool{options;connections=new Map;metrics;cleanupInterval=null;constructor(t={}){this.options={maxConnections:t.maxConnections??10,minConnections:t.minConnections??2,keepAliveTimeout:t.keepAliveTimeout??3e4,idleTimeout:t.idleTimeout??6e4,requestTimeout:t.requestTimeout??3e4,enableMetrics:t.enableMetrics??!0,retryOnFailure:t.retryOnFailure??!0,maxRetries:t.maxRetries??3},this.metrics={totalRequests:0,reuseCount:0,failedRequests:0,requestDurations:[],byOrigin:new Map},this.startCleanup()}async fetch(t,e){const s=Date.now(),n=this.getOrigin(t);try{const o=await this.acquireConnection(n);this.options.enableMetrics&&(this.metrics.totalRequests++,o.requestCount>0&&this.metrics.reuseCount++);const i={...e,signal:e?.signal??o.controller.signal,keepalive:!0},r=await fetch(t,i);if(o.requestCount++,o.lastUsedAt=Date.now(),o.state="idle",this.options.enableMetrics){const t=Date.now()-s;this.recordMetrics(n,t)}return r}catch(s){if(this.options.enableMetrics&&this.metrics.failedRequests++,this.options.retryOnFailure&&!0!==e?.signal?.aborted)return this.retryRequest(t,e,1);throw s}}async retryRequest(t,e,s){if(s>this.options.maxRetries)throw new Error(`Request failed after ${this.options.maxRetries} retries: ${t}`);const n=100*Math.pow(2,s-1);await new Promise(t=>setTimeout(t,n));const o=this.getOrigin(t);try{const s=await this.acquireConnection(o),n={...e,signal:e?.signal??s.controller.signal,keepalive:!0},i=await fetch(t,n);return s.requestCount++,s.lastUsedAt=Date.now(),s.state="idle",i}catch(n){if(s>=this.options.maxRetries)throw new Error(`Request failed after ${this.options.maxRetries} retries: ${t}`);return this.retryRequest(t,e,s+1)}}async acquireConnection(t){let e=this.connections.get(t);e||(e=[],this.connections.set(t,e));const s=e.find(t=>"idle"===t.state);if(s)return s.state="active",s;if(e.length<this.options.maxConnections){const s=this.createConnection(t);return e.push(s),s}return this.waitForConnection(t)}async waitForConnection(t){const e=Date.now(),s=this.options.requestTimeout;for(;Date.now()-e<s;){const e=this.connections.get(t);if(!e)throw new Error(`Connection pool for ${t} disappeared`);const s=e.find(t=>"idle"===t.state);if(s)return s.state="active",s;await new Promise(t=>setTimeout(t,10))}throw new Error(`Timeout waiting for connection to ${t} after ${s}ms`)}createConnection(t){const e=new Uint8Array(8);crypto.getRandomValues(e);return{id:`conn_${Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}`,origin:t,createdAt:Date.now(),lastUsedAt:Date.now(),requestCount:0,state:"active",controller:new AbortController}}getOrigin(t){try{const e=new URL(t);return`${e.protocol}//${e.host}`}catch(e){throw new Error(`Invalid URL: ${t}`)}}recordMetrics(t,e){this.metrics.requestDurations.push(e),this.metrics.requestDurations.length>1e3&&this.metrics.requestDurations.shift();let s=this.metrics.byOrigin.get(t);s||(s={requests:0,durations:[]},this.metrics.byOrigin.set(t,s)),s.requests++,s.durations.push(e),s.durations.length>100&&s.durations.shift()}getMetrics(){let t=0,e=0,s=0;const n=new Map;for(const[o,i]of this.connections.entries()){t+=i.length,e+=i.filter(t=>"active"===t.state).length,s+=i.filter(t=>"idle"===t.state).length;const r=this.metrics.byOrigin.get(o);if(r){const t=r.durations.length>0?r.durations.reduce((t,e)=>t+e,0)/r.durations.length:0;n.set(o,{connections:i.length,requests:r.requests,avgDuration:Math.round(t)})}}const o=this.metrics.requestDurations.length>0?Math.round(this.metrics.requestDurations.reduce((t,e)=>t+e,0)/this.metrics.requestDurations.length):0,i=this.metrics.totalRequests>0?this.metrics.reuseCount/this.metrics.totalRequests:0;return{totalConnections:t,activeConnections:e,idleConnections:s,totalRequests:this.metrics.totalRequests,reuseCount:this.metrics.reuseCount,failedRequests:this.metrics.failedRequests,avgRequestDuration:o,hitRate:i,byOrigin:n}}resetMetrics(){this.metrics={totalRequests:0,reuseCount:0,failedRequests:0,requestDurations:[],byOrigin:new Map}}startCleanup(){this.cleanupInterval=setInterval(()=>{this.cleanup()},1e4)}cleanup(){const t=Date.now();for(const[e,s]of this.connections.entries()){const n=s.filter(e=>t-e.lastUsedAt>this.options.idleTimeout&&"idle"===e.state?(e.controller.abort(),e.state="closed",!1):"closed"!==e.state);for(;n.length<this.options.minConnections&&n.length<this.options.maxConnections;){const t=this.createConnection(e);t.state="idle",n.push(t)}n.length>0?this.connections.set(e,n):this.connections.delete(e)}}cleanupNow(){this.cleanup()}async close(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null);for(const[t,e]of this.connections.entries())for(const t of e)t.controller.abort(),t.state="closed";this.connections.clear()}getConnectionCount(t){const e=this.connections.get(t);return e?e.length:0}getOrigins(){return Array.from(this.connections.keys())}isHealthy(){const t=this.getMetrics();return!((t.totalRequests>0?t.failedRequests/t.totalRequests:0)>.1)&&!(t.avgRequestDuration>5e3)}}exports.ConnectionPool=ConnectionPool;let globalPool=null;function getGlobalPool(t){return globalPool||(globalPool=new ConnectionPool(t)),globalPool}async function resetGlobalPool(){globalPool&&(await globalPool.close(),globalPool=null)}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ConnectionPool=void 0,exports.getGlobalPool=getGlobalPool,exports.resetGlobalPool=resetGlobalPool;class ConnectionPool{options;connections=new Map;metrics;cleanupInterval=null;constructor(t={}){this.options={maxConnections:t.maxConnections??10,minConnections:t.minConnections??2,keepAliveTimeout:t.keepAliveTimeout??3e4,idleTimeout:t.idleTimeout??6e4,requestTimeout:t.requestTimeout??3e4,enableMetrics:t.enableMetrics??!0,retryOnFailure:t.retryOnFailure??!0,maxRetries:t.maxRetries??3},this.metrics={totalRequests:0,reuseCount:0,failedRequests:0,requestDurations:[],byOrigin:new Map},this.startCleanup()}async fetch(t,e){const s=Date.now(),n=this.getOrigin(t);try{const o=await this.acquireConnection(n);this.options.enableMetrics&&(this.metrics.totalRequests++,o.requestCount>0&&this.metrics.reuseCount++);const i={...e,signal:e?.signal??o.controller.signal,keepalive:!0},r=await fetch(t,i);if(o.requestCount++,o.lastUsedAt=Date.now(),o.state="idle",this.options.enableMetrics){const t=Date.now()-s;this.recordMetrics(n,t)}return r}catch(s){if(this.options.enableMetrics&&this.metrics.failedRequests++,this.options.retryOnFailure&&!0!==e?.signal?.aborted)return this.retryRequest(t,e,1);throw s}}async retryRequest(t,e,s){if(s>this.options.maxRetries)throw new Error(`Request failed after ${this.options.maxRetries} retries: ${t}`);const n=100*Math.pow(2,s-1);await new Promise(t=>setTimeout(t,n));const o=this.getOrigin(t);try{const s=await this.acquireConnection(o),n={...e,signal:e?.signal??s.controller.signal,keepalive:!0},i=await fetch(t,n);return s.requestCount++,s.lastUsedAt=Date.now(),s.state="idle",i}catch{if(s>=this.options.maxRetries)throw new Error(`Request failed after ${this.options.maxRetries} retries: ${t}`);return this.retryRequest(t,e,s+1)}}async acquireConnection(t){let e=this.connections.get(t);e||(e=[],this.connections.set(t,e));const s=e.find(t=>"idle"===t.state);if(s)return s.state="active",s;if(e.length<this.options.maxConnections){const s=this.createConnection(t);return e.push(s),s}return this.waitForConnection(t)}async waitForConnection(t){const e=Date.now(),s=this.options.requestTimeout;for(;Date.now()-e<s;){const e=this.connections.get(t);if(!e)throw new Error(`Connection pool for ${t} disappeared`);const s=e.find(t=>"idle"===t.state);if(s)return s.state="active",s;await new Promise(t=>setTimeout(t,10))}throw new Error(`Timeout waiting for connection to ${t} after ${s}ms`)}createConnection(t){const e=new Uint8Array(8);crypto.getRandomValues(e);return{id:`conn_${Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}`,origin:t,createdAt:Date.now(),lastUsedAt:Date.now(),requestCount:0,state:"active",controller:new AbortController}}getOrigin(t){try{const e=new URL(t);return`${e.protocol}//${e.host}`}catch{throw new Error(`Invalid URL: ${t}`)}}recordMetrics(t,e){this.metrics.requestDurations.push(e),this.metrics.requestDurations.length>1e3&&this.metrics.requestDurations.shift();let s=this.metrics.byOrigin.get(t);s||(s={requests:0,durations:[]},this.metrics.byOrigin.set(t,s)),s.requests++,s.durations.push(e),s.durations.length>100&&s.durations.shift()}getMetrics(){let t=0,e=0,s=0;const n=new Map;for(const[o,i]of this.connections.entries()){t+=i.length,e+=i.filter(t=>"active"===t.state).length,s+=i.filter(t=>"idle"===t.state).length;const r=this.metrics.byOrigin.get(o);if(r){const t=r.durations.length>0?r.durations.reduce((t,e)=>t+e,0)/r.durations.length:0;n.set(o,{connections:i.length,requests:r.requests,avgDuration:Math.round(t)})}}const o=this.metrics.requestDurations.length>0?Math.round(this.metrics.requestDurations.reduce((t,e)=>t+e,0)/this.metrics.requestDurations.length):0,i=this.metrics.totalRequests>0?this.metrics.reuseCount/this.metrics.totalRequests:0;return{totalConnections:t,activeConnections:e,idleConnections:s,totalRequests:this.metrics.totalRequests,reuseCount:this.metrics.reuseCount,failedRequests:this.metrics.failedRequests,avgRequestDuration:o,hitRate:i,byOrigin:n}}resetMetrics(){this.metrics={totalRequests:0,reuseCount:0,failedRequests:0,requestDurations:[],byOrigin:new Map}}startCleanup(){this.cleanupInterval=setInterval(()=>{this.cleanup()},1e4)}cleanup(){const t=Date.now();for(const[e,s]of this.connections.entries()){const n=s.filter(e=>t-e.lastUsedAt>this.options.idleTimeout&&"idle"===e.state?(e.controller.abort(),e.state="closed",!1):"closed"!==e.state);for(;n.length<this.options.minConnections&&n.length<this.options.maxConnections;){const t=this.createConnection(e);t.state="idle",n.push(t)}n.length>0?this.connections.set(e,n):this.connections.delete(e)}}cleanupNow(){this.cleanup()}async close(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null);for(const[t,e]of this.connections.entries())for(const t of e)t.controller.abort(),t.state="closed";this.connections.clear()}getConnectionCount(t){const e=this.connections.get(t);return e?e.length:0}getOrigins(){return Array.from(this.connections.keys())}isHealthy(){const t=this.getMetrics();return!((t.totalRequests>0?t.failedRequests/t.totalRequests:0)>.1)&&!(t.avgRequestDuration>5e3)}}exports.ConnectionPool=ConnectionPool;let globalPool=null;function getGlobalPool(t){return globalPool||(globalPool=new ConnectionPool(t)),globalPool}async function resetGlobalPool(){globalPool&&(await globalPool.close(),globalPool=null)}
@@ -1 +1 @@
1
- "use strict";function toBase64(r){if("undefined"!=typeof Buffer)return Buffer.from(r).toString("base64");const e=String.fromCharCode(...r);return btoa(e)}function fromBase64(r){if("undefined"!=typeof Buffer)return new Uint8Array(Buffer.from(r,"base64"));const e=atob(r),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function toBase64Url(r){return toBase64(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function fromBase64Url(r){let e=r.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";return fromBase64(e)}function generateUUID(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const r=new Uint8Array(16);crypto.getRandomValues(r),r[6]=15&r[6]|64,r[8]=63&r[8]|128;const e=Array.from(r).map(r=>r.toString(16).padStart(2,"0")).join("");return`${e.substring(0,8)}-${e.substring(8,12)}-${e.substring(12,16)}-${e.substring(16,20)}-${e.substring(20)}`}Object.defineProperty(exports,"__esModule",{value:!0}),exports.isCryptoLoaded=exports.getCrypto=exports.loadCryptoPackage=void 0,exports.toBase64=toBase64,exports.fromBase64=fromBase64,exports.toBase64Url=toBase64Url,exports.fromBase64Url=fromBase64Url,exports.generateUUID=generateUUID,exports.formatShareHeader=formatShareHeader,exports.parseShareHeader=parseShareHeader,exports.hasShareHeader=hasShareHeader,exports.splitXorIDA=splitXorIDA,exports.reconstructXorIDA=reconstructXorIDA,exports.nextOddPrime=nextOddPrime,exports.pkcs7Pad=pkcs7Pad,exports.pkcs7Unpad=pkcs7Unpad,exports.generateHMAC=generateHMAC,exports.verifyHMAC=verifyHMAC;const START_MARKER="Encrypted://",END_MARKER="=> Generated by Xecret (TM)",BRAND_PREFIX="Xecret (TM) -> PRIVATE .ME (R) -> IDA5 -> ";function formatShareHeader(r){return`${BRAND_PREFIX}${START_MARKER} ${r} ${END_MARKER}`}function parseShareHeader(r){const e=r.indexOf(START_MARKER);if(e<0)return r.trim();const t=e+START_MARKER.length,o=r.indexOf(END_MARKER,t);return o<0?r.trim():r.substring(t,o).trim()}function hasShareHeader(r){return r.includes(START_MARKER)&&r.includes(END_MARKER)}const vault_store_loader_js_1=require("./vault-store-loader.js");function splitXorIDA(r,e,t){const o=(0,vault_store_loader_js_1.getCrypto)();if(!o)throw new Error("Crypto package not loaded. Call loadCryptoPackage() first.");return o.splitXorIDA(r,e,t)}function reconstructXorIDA(r,e,t,o){const a=(0,vault_store_loader_js_1.getCrypto)();if(!a)throw new Error("Crypto package not loaded. Call loadCryptoPackage() first.");return a.reconstructXorIDA(r,e,t,o)}function nextOddPrime(r){const e=(0,vault_store_loader_js_1.getCrypto)();if(!e)throw new Error("Crypto package not loaded. Call loadCryptoPackage() first.");return e.nextOddPrime(r)}function pkcs7Pad(r,e){const t=(0,vault_store_loader_js_1.getCrypto)();if(!t)throw new Error("Crypto package not loaded. Call loadCryptoPackage() first.");return t.pkcs7Pad(r,e)}function pkcs7Unpad(r,e){const t=(0,vault_store_loader_js_1.getCrypto)();if(!t)throw new Error("Crypto package not loaded. Call loadCryptoPackage() first.");return t.pkcs7Unpad(r,e)}async function generateHMAC(r){const e=(0,vault_store_loader_js_1.getCrypto)();if(!e)throw new Error("Crypto package not loaded. Call loadCryptoPackage() first.");return e.generateHMAC(r)}async function verifyHMAC(r,e,t){const o=(0,vault_store_loader_js_1.getCrypto)();if(!o)throw new Error("Crypto package not loaded. Call loadCryptoPackage() first.");return o.verifyHMAC(r,e,t)}Object.defineProperty(exports,"getCrypto",{enumerable:!0,get:function(){return vault_store_loader_js_1.getCrypto}}),Object.defineProperty(exports,"loadCryptoPackage",{enumerable:!0,get:function(){return vault_store_loader_js_1.loadCryptoPackage}}),Object.defineProperty(exports,"isCryptoLoaded",{enumerable:!0,get:function(){return vault_store_loader_js_1.isCryptoLoaded}});
1
+ "use strict";function toBase64(r){if("undefined"!=typeof Buffer)return Buffer.from(r).toString("base64");const e=String.fromCharCode(...r);return btoa(e)}function fromBase64(r){if("undefined"!=typeof Buffer)return new Uint8Array(Buffer.from(r,"base64"));const e=atob(r),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function toBase64Url(r){return toBase64(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function fromBase64Url(r){let e=r.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";return fromBase64(e)}function generateUUID(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const r=new Uint8Array(16);crypto.getRandomValues(r),r[6]=15&r[6]|64,r[8]=63&r[8]|128;const e=Array.from(r).map(r=>r.toString(16).padStart(2,"0")).join("");return`${e.substring(0,8)}-${e.substring(8,12)}-${e.substring(12,16)}-${e.substring(16,20)}-${e.substring(20)}`}Object.defineProperty(exports,"__esModule",{value:!0}),exports.clearCryptoCache=exports.setMockCrypto=exports.isCryptoLoaded=exports.getCrypto=exports.loadCryptoPackage=void 0,exports.toBase64=toBase64,exports.fromBase64=fromBase64,exports.toBase64Url=toBase64Url,exports.fromBase64Url=fromBase64Url,exports.generateUUID=generateUUID,exports.formatShareHeader=formatShareHeader,exports.parseShareHeader=parseShareHeader,exports.hasShareHeader=hasShareHeader,exports.splitXorIDA=splitXorIDA,exports.reconstructXorIDA=reconstructXorIDA,exports.nextOddPrime=nextOddPrime,exports.pkcs7Pad=pkcs7Pad,exports.pkcs7Unpad=pkcs7Unpad,exports.generateHMAC=generateHMAC,exports.verifyHMAC=verifyHMAC;const START_MARKER="Encrypted://",END_MARKER="=> Generated by Xecret (TM)",BRAND_PREFIX="Xecret (TM) -> PRIVATE .ME (R) -> IDA5 -> ";function formatShareHeader(r){return`${BRAND_PREFIX}${START_MARKER} ${r} ${END_MARKER}`}function parseShareHeader(r){const e=r.indexOf(START_MARKER);if(e<0)return r.trim();const t=e+START_MARKER.length,o=r.indexOf(END_MARKER,t);return o<0?r.trim():r.substring(t,o).trim()}function hasShareHeader(r){return r.includes(START_MARKER)&&r.includes(END_MARKER)}const vault_store_loader_js_1=require("./vault-store-loader.js");var vault_store_loader_js_2=require("./vault-store-loader.js");function splitXorIDA(r,e,t){const o=(0,vault_store_loader_js_1.getCrypto)();if(!o)throw new Error("Crypto package not loaded. Call loadCryptoPackage() first.");return o.splitXorIDA(r,e,t)}function reconstructXorIDA(r,e,t,o){const a=(0,vault_store_loader_js_1.getCrypto)();if(!a)throw new Error("Crypto package not loaded. Call loadCryptoPackage() first.");return a.reconstructXorIDA(r,e,t,o)}function nextOddPrime(r){const e=(0,vault_store_loader_js_1.getCrypto)();if(!e)throw new Error("Crypto package not loaded. Call loadCryptoPackage() first.");return e.nextOddPrime(r)}function pkcs7Pad(r,e){const t=(0,vault_store_loader_js_1.getCrypto)();if(!t)throw new Error("Crypto package not loaded. Call loadCryptoPackage() first.");return t.pkcs7Pad(r,e)}function pkcs7Unpad(r,e){const t=(0,vault_store_loader_js_1.getCrypto)();if(!t)throw new Error("Crypto package not loaded. Call loadCryptoPackage() first.");return t.pkcs7Unpad(r,e)}async function generateHMAC(r){const e=(0,vault_store_loader_js_1.getCrypto)();if(!e)throw new Error("Crypto package not loaded. Call loadCryptoPackage() first.");return e.generateHMAC(r)}async function verifyHMAC(r,e,t){const o=(0,vault_store_loader_js_1.getCrypto)();if(!o)throw new Error("Crypto package not loaded. Call loadCryptoPackage() first.");return o.verifyHMAC(r,e,t)}Object.defineProperty(exports,"loadCryptoPackage",{enumerable:!0,get:function(){return vault_store_loader_js_2.loadCryptoPackage}}),Object.defineProperty(exports,"getCrypto",{enumerable:!0,get:function(){return vault_store_loader_js_2.getCrypto}}),Object.defineProperty(exports,"isCryptoLoaded",{enumerable:!0,get:function(){return vault_store_loader_js_2.isCryptoLoaded}}),Object.defineProperty(exports,"setMockCrypto",{enumerable:!0,get:function(){return vault_store_loader_js_2.setMockCrypto}}),Object.defineProperty(exports,"clearCryptoCache",{enumerable:!0,get:function(){return vault_store_loader_js_2.clearCryptoCache}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.enableDebugMode=enableDebugMode,exports.disableDebugMode=disableDebugMode,exports.isDebugEnabled=isDebugEnabled,exports.getDebugOptions=getDebugOptions,exports.createDebugLogger=createDebugLogger,exports.startProfiling=startProfiling,exports.endProfiling=endProfiling,exports.getPerformanceMeasurements=getPerformanceMeasurements,exports.clearPerformanceMeasurements=clearPerformanceMeasurements,exports.traceNetworkRequest=traceNetworkRequest,exports.traceNetworkResponse=traceNetworkResponse,exports.getNetworkTraces=getNetworkTraces,exports.clearNetworkTraces=clearNetworkTraces,exports.traceCryptoOperation=traceCryptoOperation,exports.getCryptoTraces=getCryptoTraces,exports.clearCryptoTraces=clearCryptoTraces,exports.dumpState=dumpState,exports.getStateSnapshots=getStateSnapshots,exports.clearStateSnapshots=clearStateSnapshots,exports.exportDebugData=exportDebugData,exports.clearAllDebugData=clearAllDebugData,exports.generateDebugReport=generateDebugReport;const logger_js_1=require("./logger.js");class DebugModeState{enabled=!1;options={};measurements=[];networkTraces=[];cryptoTraces=[];stateSnapshots=[];activeTimers=new Map}const globalDebugState=new DebugModeState;function enableDebugMode(e={}){globalDebugState.enabled=!0,globalDebugState.options={verbose:e.verbose??!1,traceNetwork:e.traceNetwork??!1,traceCrypto:e.traceCrypto??!1,profile:e.profile??!1,trackMemory:e.trackMemory??!1,traceState:e.traceState??!1,output:e.output??console.log,filters:e.filters};const t=(0,logger_js_1.createLogger)("debug-mode");t.setLevel(logger_js_1.LogLevel.DEBUG),t.info("Debug mode enabled",{options:globalDebugState.options})}function disableDebugMode(){globalDebugState.enabled=!1,globalDebugState.measurements=[],globalDebugState.networkTraces=[],globalDebugState.cryptoTraces=[],globalDebugState.stateSnapshots=[],globalDebugState.activeTimers.clear();(0,logger_js_1.createLogger)("debug-mode").info("Debug mode disabled")}function isDebugEnabled(){return globalDebugState.enabled}function getDebugOptions(){return{...globalDebugState.options}}function createDebugLogger(e){const t=(0,logger_js_1.createLogger)(e);return globalDebugState.enabled&&globalDebugState.options.verbose&&t.setLevel(logger_js_1.LogLevel.DEBUG),{...t,trace(e,o){if(globalDebugState.enabled&&globalDebugState.options.verbose){if(globalDebugState.options.filters){const{include:t,exclude:o}=globalDebugState.options.filters;if(t&&!t.some(t=>t.test(e)))return;if(o&&o.some(t=>t.test(e)))return}t.debug(e,o)}}}}function startProfiling(e,t){if(!globalDebugState.enabled||!globalDebugState.options.profile)return;const o=performance.now();globalDebugState.activeTimers.set(e,{startTime:o,context:t});createDebugLogger("profiler").trace(`[PROFILE] Starting: ${e}`,t)}function endProfiling(e,t){if(!globalDebugState.enabled||!globalDebugState.options.profile)return;const o=globalDebugState.activeTimers.get(e);if(!o){return void createDebugLogger("profiler").warn(`[PROFILE] No start time found for: ${e}`)}const r=performance.now(),a=r-o.startTime,s=t??o.context;let n,u,g;if(globalDebugState.options.trackMemory&&"undefined"!=typeof process&&process.memoryUsage){u=process.memoryUsage().heapUsed,n=u,g=0}const l={operation:e,startTime:o.startTime,endTime:r,duration:a,memoryBefore:n,memoryAfter:u,memoryDelta:g,context:s};globalDebugState.measurements.push(l),globalDebugState.activeTimers.delete(e);createDebugLogger("profiler").trace(`[PROFILE] Completed: ${e} (${a.toFixed(2)}ms)`,{duration:a,memoryDelta:g,...t})}function getPerformanceMeasurements(){return[...globalDebugState.measurements]}function clearPerformanceMeasurements(){globalDebugState.measurements=[],globalDebugState.activeTimers.clear()}function traceNetworkRequest(e,t,o,r,a){if(!globalDebugState.enabled||!globalDebugState.options.traceNetwork)return;const s={id:e,method:t,url:o,requestHeaders:redactHeaders(r),requestBody:truncateBody(a),startTime:performance.now()};globalDebugState.networkTraces.push(s);createDebugLogger("network").trace(`[NETWORK] ${t} ${o}`,{requestId:e,headers:s.requestHeaders,bodyLength:a?.length??0})}function traceNetworkResponse(e,t,o,r,a){if(!globalDebugState.enabled||!globalDebugState.options.traceNetwork)return;const s=globalDebugState.networkTraces.find(t=>t.id===e);if(!s)return;s.endTime=performance.now(),s.duration=s.endTime-s.startTime,s.status=t,s.responseHeaders=o?redactHeaders(o):void 0,s.responseBody=truncateBody(r),s.error=a;createDebugLogger("network").trace(`[NETWORK] Response ${t??"ERROR"} (${s.duration.toFixed(2)}ms)`,{requestId:e,status:t,duration:s.duration,error:a})}function getNetworkTraces(){return[...globalDebugState.networkTraces]}function clearNetworkTraces(){globalDebugState.networkTraces=[]}function traceCryptoOperation(e,t,o,r,a,s,n){if(!globalDebugState.enabled||!globalDebugState.options.traceCrypto)return;const u={operation:e,algorithm:t,inputSize:o,outputSize:r,duration:a??0,success:s??!0,error:n,timestamp:Date.now()};globalDebugState.cryptoTraces.push(u);createDebugLogger("crypto").trace(`[CRYPTO] ${e} (${t})`,{inputSize:o,outputSize:r,duration:a,success:s,error:n})}function getCryptoTraces(){return[...globalDebugState.cryptoTraces]}function clearCryptoTraces(){globalDebugState.cryptoTraces=[]}function dumpState(e){const t={did:e.did,identityMode:e.identityMode??"persistent",registered:e.registered??!1,registryUrl:e.registry?.url,nonceStoreType:e.nonceStore?.constructor?.name??"unknown",nonceCount:e.nonceStore?.size??0,transportType:e.transport?.constructor?.name??"unknown",securityPolicy:{level:e.securityPolicy?.level??"unknown",replayWindow:e.securityPolicy?.replayWindow??0,timestampTolerance:e.securityPolicy?.timestampTolerance??0},postQuantum:e.postQuantum??!1,memoryUsage:"undefined"!=typeof process&&process.memoryUsage?process.memoryUsage().heapUsed:void 0,timestamp:Date.now()};globalDebugState.enabled&&globalDebugState.options.traceState&&globalDebugState.stateSnapshots.push(t);return createDebugLogger("state").trace("[STATE] Agent snapshot",t),t}function getStateSnapshots(){return[...globalDebugState.stateSnapshots]}function clearStateSnapshots(){globalDebugState.stateSnapshots=[]}function exportDebugData(){const e={enabled:globalDebugState.enabled,options:globalDebugState.options,measurements:globalDebugState.measurements,networkTraces:globalDebugState.networkTraces,cryptoTraces:globalDebugState.cryptoTraces,stateSnapshots:globalDebugState.stateSnapshots,exportedAt:(new Date).toISOString()};return JSON.stringify(e,null,2)}function clearAllDebugData(){clearPerformanceMeasurements(),clearNetworkTraces(),clearCryptoTraces(),clearStateSnapshots()}function redactHeaders(e){const t={},o=new Set(["authorization","cookie","set-cookie","x-api-key","x-auth-token"]);for(const[r,a]of Object.entries(e)){const e=r.toLowerCase();o.has(e)?t[r]="[REDACTED]":t[r]=a}return t}function truncateBody(e){if(!e)return;const t=1e3;return e.length<=t?e:e.substring(0,t)+`... (${e.length-t} more bytes)`}function generateDebugReport(){const e=[];if(e.push("=".repeat(80)),e.push("xBind Debug Report"),e.push("=".repeat(80)),e.push(""),e.push(`Generated: ${(new Date).toISOString()}`),e.push("Debug Mode: "+(globalDebugState.enabled?"ENABLED":"DISABLED")),e.push(""),globalDebugState.measurements.length>0){e.push("Performance Measurements:"),e.push("-".repeat(80));for(const t of globalDebugState.measurements)e.push(` ${t.operation}: ${t.duration.toFixed(2)}ms`),void 0!==t.memoryDelta&&e.push(` Memory: ${formatBytes(t.memoryDelta)}`);e.push("")}if(globalDebugState.networkTraces.length>0){e.push("Network Traces:"),e.push("-".repeat(80));for(const t of globalDebugState.networkTraces)e.push(` ${t.method} ${t.url}`),t.status&&e.push(` Status: ${t.status}`),t.duration&&e.push(` Duration: ${t.duration.toFixed(2)}ms`),t.error&&e.push(` Error: ${t.error}`);e.push("")}if(globalDebugState.cryptoTraces.length>0){e.push("Crypto Operations:"),e.push("-".repeat(80));for(const t of globalDebugState.cryptoTraces)e.push(` ${t.operation} (${t.algorithm})`),e.push(` Input: ${formatBytes(t.inputSize)}`),t.outputSize&&e.push(` Output: ${formatBytes(t.outputSize)}`),e.push(` Duration: ${t.duration.toFixed(2)}ms`),e.push(` Success: ${t.success}`),t.error&&e.push(` Error: ${t.error}`);e.push("")}if(globalDebugState.stateSnapshots.length>0){e.push("State Snapshots:"),e.push("-".repeat(80));const t=globalDebugState.stateSnapshots[globalDebugState.stateSnapshots.length-1];t&&(e.push(` DID: ${t.did}`),e.push(` Mode: ${t.identityMode}`),e.push(` Registered: ${t.registered}`),e.push(` Post-Quantum: ${t.postQuantum}`),e.push(` Nonce Count: ${t.nonceCount}`),t.memoryUsage&&e.push(` Memory Usage: ${formatBytes(t.memoryUsage)}`)),e.push("")}return e.push("=".repeat(80)),e.join("\n")}function formatBytes(e){if(0===e)return"0 B";const t=Math.floor(Math.log(Math.abs(e))/Math.log(1024));return`${(e/Math.pow(1024,t)).toFixed(2)} ${["B","KB","MB","GB"][t]}`}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.enableDebugMode=enableDebugMode,exports.disableDebugMode=disableDebugMode,exports.isDebugEnabled=isDebugEnabled,exports.getDebugOptions=getDebugOptions,exports.createDebugLogger=createDebugLogger,exports.startProfiling=startProfiling,exports.endProfiling=endProfiling,exports.getPerformanceMeasurements=getPerformanceMeasurements,exports.clearPerformanceMeasurements=clearPerformanceMeasurements,exports.traceNetworkRequest=traceNetworkRequest,exports.traceNetworkResponse=traceNetworkResponse,exports.getNetworkTraces=getNetworkTraces,exports.clearNetworkTraces=clearNetworkTraces,exports.traceCryptoOperation=traceCryptoOperation,exports.getCryptoTraces=getCryptoTraces,exports.clearCryptoTraces=clearCryptoTraces,exports.dumpState=dumpState,exports.getStateSnapshots=getStateSnapshots,exports.clearStateSnapshots=clearStateSnapshots,exports.exportDebugData=exportDebugData,exports.clearAllDebugData=clearAllDebugData,exports.generateDebugReport=generateDebugReport;const logger_js_1=require("./logger.js");class DebugModeState{enabled=!1;options={};measurements=[];networkTraces=[];cryptoTraces=[];stateSnapshots=[];activeTimers=new Map}const globalDebugState=new DebugModeState;function enableDebugMode(e={}){globalDebugState.enabled=!0,globalDebugState.options={verbose:e.verbose??!1,traceNetwork:e.traceNetwork??!1,traceCrypto:e.traceCrypto??!1,profile:e.profile??!1,trackMemory:e.trackMemory??!1,traceState:e.traceState??!1,output:e.output??console.log,filters:e.filters};const t=(0,logger_js_1.createLogger)("debug-mode");t.setLevel(logger_js_1.LogLevel.DEBUG),t.info("Debug mode enabled",{options:globalDebugState.options})}function disableDebugMode(){globalDebugState.enabled=!1,globalDebugState.measurements=[],globalDebugState.networkTraces=[],globalDebugState.cryptoTraces=[],globalDebugState.stateSnapshots=[],globalDebugState.activeTimers.clear();(0,logger_js_1.createLogger)("debug-mode").info("Debug mode disabled")}function isDebugEnabled(){return globalDebugState.enabled}function getDebugOptions(){return{...globalDebugState.options}}function createDebugLogger(e){const t=(0,logger_js_1.createLogger)(e);return globalDebugState.enabled&&globalDebugState.options.verbose&&t.setLevel(logger_js_1.LogLevel.DEBUG),{...t,trace(e,o){if(globalDebugState.enabled&&globalDebugState.options.verbose){if(globalDebugState.options.filters){const{include:t,exclude:o}=globalDebugState.options.filters;if(t&&!t.some(t=>t.test(e)))return;if(o&&o.some(t=>t.test(e)))return}t.debug(e,o)}}}}function startProfiling(e,t){if(!globalDebugState.enabled||!globalDebugState.options.profile)return;const o=performance.now();globalDebugState.activeTimers.set(e,{startTime:o,context:t});createDebugLogger("profiler").trace(`[PROFILE] Starting: ${e}`,t)}function endProfiling(e,t){if(!globalDebugState.enabled||!globalDebugState.options.profile)return;const o=globalDebugState.activeTimers.get(e);if(!o){return void createDebugLogger("profiler").warn(`[PROFILE] No start time found for: ${e}`)}const r=performance.now(),a=r-o.startTime,s=t??o.context;let n,u,g;if(globalDebugState.options.trackMemory&&"undefined"!=typeof process&&process.memoryUsage){u=process.memoryUsage().heapUsed,n=u,g=0}const l={operation:e,startTime:o.startTime,endTime:r,duration:a,memoryBefore:n,memoryAfter:u,memoryDelta:g,context:s};globalDebugState.measurements.push(l),globalDebugState.activeTimers.delete(e);createDebugLogger("profiler").trace(`[PROFILE] Completed: ${e} (${a.toFixed(2)}ms)`,{duration:a,memoryDelta:g,...t})}function getPerformanceMeasurements(){return[...globalDebugState.measurements]}function clearPerformanceMeasurements(){globalDebugState.measurements=[],globalDebugState.activeTimers.clear()}function traceNetworkRequest(e,t,o,r,a){if(!globalDebugState.enabled||!globalDebugState.options.traceNetwork)return;const s={id:e,method:t,url:o,requestHeaders:redactHeaders(r),requestBody:truncateBody(a),startTime:performance.now()};globalDebugState.networkTraces.push(s);createDebugLogger("network").trace(`[NETWORK] ${t} ${o}`,{requestId:e,headers:s.requestHeaders,bodyLength:a?.length??0})}function traceNetworkResponse(e,t,o,r,a){if(!globalDebugState.enabled||!globalDebugState.options.traceNetwork)return;const s=globalDebugState.networkTraces.find(t=>t.id===e);if(!s)return;s.endTime=performance.now(),s.duration=s.endTime-s.startTime,s.status=t,s.responseHeaders=o?redactHeaders(o):void 0,s.responseBody=truncateBody(r),s.error=a;createDebugLogger("network").trace(`[NETWORK] Response ${t??"ERROR"} (${s.duration.toFixed(2)}ms)`,{requestId:e,status:t,duration:s.duration,error:a})}function getNetworkTraces(){return[...globalDebugState.networkTraces]}function clearNetworkTraces(){globalDebugState.networkTraces=[]}function traceCryptoOperation(e,t,o,r,a,s,n){if(!globalDebugState.enabled||!globalDebugState.options.traceCrypto)return;const u={operation:e,algorithm:t,inputSize:o,outputSize:r,duration:a??0,success:s??!0,error:n,timestamp:Date.now()};globalDebugState.cryptoTraces.push(u);createDebugLogger("crypto").trace(`[CRYPTO] ${e} (${t})`,{inputSize:o,outputSize:r,duration:a,success:s,error:n})}function getCryptoTraces(){return[...globalDebugState.cryptoTraces]}function clearCryptoTraces(){globalDebugState.cryptoTraces=[]}function dumpState(e){const t=e,o={did:e.did,identityMode:t.identityMode??"persistent",registered:t.registered??!1,registryUrl:t.registry?.url,nonceStoreType:t.nonceStore?.constructor?.name??"unknown",nonceCount:t.nonceStore?.size??0,transportType:t.transport?.constructor?.name??"unknown",securityPolicy:{level:t.securityPolicy?.level??"unknown",replayWindow:t.securityPolicy?.replayWindow??0,timestampTolerance:t.securityPolicy?.timestampTolerance??0},postQuantum:t.postQuantum??!1,memoryUsage:"undefined"!=typeof process&&process.memoryUsage?process.memoryUsage().heapUsed:void 0,timestamp:Date.now()};globalDebugState.enabled&&globalDebugState.options.traceState&&globalDebugState.stateSnapshots.push(o);return createDebugLogger("state").trace("[STATE] Agent snapshot",o),o}function getStateSnapshots(){return[...globalDebugState.stateSnapshots]}function clearStateSnapshots(){globalDebugState.stateSnapshots=[]}function exportDebugData(){const e={enabled:globalDebugState.enabled,options:globalDebugState.options,measurements:globalDebugState.measurements,networkTraces:globalDebugState.networkTraces,cryptoTraces:globalDebugState.cryptoTraces,stateSnapshots:globalDebugState.stateSnapshots,exportedAt:(new Date).toISOString()};return JSON.stringify(e,null,2)}function clearAllDebugData(){clearPerformanceMeasurements(),clearNetworkTraces(),clearCryptoTraces(),clearStateSnapshots()}function redactHeaders(e){const t={},o=new Set(["authorization","cookie","set-cookie","x-api-key","x-auth-token"]);for(const[r,a]of Object.entries(e)){const e=r.toLowerCase();o.has(e)?t[r]="[REDACTED]":t[r]=a}return t}function truncateBody(e){if(!e)return;const t=1e3;return e.length<=t?e:e.substring(0,t)+`... (${e.length-t} more bytes)`}function generateDebugReport(){const e=[];if(e.push("=".repeat(80)),e.push("xBind Debug Report"),e.push("=".repeat(80)),e.push(""),e.push(`Generated: ${(new Date).toISOString()}`),e.push("Debug Mode: "+(globalDebugState.enabled?"ENABLED":"DISABLED")),e.push(""),globalDebugState.measurements.length>0){e.push("Performance Measurements:"),e.push("-".repeat(80));for(const t of globalDebugState.measurements)e.push(` ${t.operation}: ${t.duration.toFixed(2)}ms`),void 0!==t.memoryDelta&&e.push(` Memory: ${formatBytes(t.memoryDelta)}`);e.push("")}if(globalDebugState.networkTraces.length>0){e.push("Network Traces:"),e.push("-".repeat(80));for(const t of globalDebugState.networkTraces)e.push(` ${t.method} ${t.url}`),t.status&&e.push(` Status: ${t.status}`),t.duration&&e.push(` Duration: ${t.duration.toFixed(2)}ms`),t.error&&e.push(` Error: ${t.error}`);e.push("")}if(globalDebugState.cryptoTraces.length>0){e.push("Crypto Operations:"),e.push("-".repeat(80));for(const t of globalDebugState.cryptoTraces)e.push(` ${t.operation} (${t.algorithm})`),e.push(` Input: ${formatBytes(t.inputSize)}`),t.outputSize&&e.push(` Output: ${formatBytes(t.outputSize)}`),e.push(` Duration: ${t.duration.toFixed(2)}ms`),e.push(` Success: ${t.success}`),t.error&&e.push(` Error: ${t.error}`);e.push("")}if(globalDebugState.stateSnapshots.length>0){e.push("State Snapshots:"),e.push("-".repeat(80));const t=globalDebugState.stateSnapshots[globalDebugState.stateSnapshots.length-1];t&&(e.push(` DID: ${t.did}`),e.push(` Mode: ${t.identityMode}`),e.push(` Registered: ${t.registered}`),e.push(` Post-Quantum: ${t.postQuantum}`),e.push(` Nonce Count: ${t.nonceCount}`),t.memoryUsage&&e.push(` Memory Usage: ${formatBytes(t.memoryUsage)}`)),e.push("")}return e.push("=".repeat(80)),e.join("\n")}function formatBytes(e){if(0===e)return"0 B";const t=Math.floor(Math.log(Math.abs(e))/Math.log(1024));return`${(e/Math.pow(1024,t)).toFixed(2)} ${["B","KB","MB","GB"][t]}`}
@@ -1 +1 @@
1
- "use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.EmailTransport=void 0;const shared_1=require("../_deps/shared/index.js"),email_templates_js_1=require("./email-templates.js"),nodemailer_1=__importDefault(require("nodemailer"));class EmailTransport{config;transporter;rateLimits;constructor(e){this.config={...e,rateLimit:e.rateLimit??10,tokenExpiryHours:e.tokenExpiryHours??48},this.transporter=nodemailer_1.default.createTransport({host:this.config.smtpHost,port:this.config.smtpPort,secure:!1,auth:{user:this.config.smtpUser,pass:this.config.smtpPass}}),this.rateLimits=new Map}async send(e,t){const{from:r,to:i,payload:s}=e;if(!this.isValidEmail(i))return(0,shared_1.err)("SEND_FAILED");if(!this.checkRateLimit(r).ok)return(0,shared_1.err)("SEND_FAILED");try{const t=await this.generateInviteToken(e),a=`${this.config.acceptBaseUrl}/${t}`,o=(0,email_templates_js_1.renderInviteEmail)({agentName:s.agentName||r,did:r,acceptUrl:a,message:s.message});return await this.transporter.sendMail({from:`"${this.config.fromName}" <${this.config.fromEmail}>`,to:i,subject:`${s.agentName||"Agent"} wants to connect`,html:o}),this.incrementRateLimit(r),(0,shared_1.ok)(void 0)}catch(e){return(0,shared_1.err)("NETWORK_ERROR")}}isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}checkRateLimit(e){const t=Date.now(),r=this.rateLimits.get(e);return r?t>=r.resetAt?(this.rateLimits.delete(e),(0,shared_1.ok)(void 0)):r.count>=this.config.rateLimit?(0,shared_1.err)(void 0):(0,shared_1.ok)(void 0):(0,shared_1.ok)(void 0)}incrementRateLimit(e){const t=Date.now(),r=this.rateLimits.get(e);r?r.count+=1:this.rateLimits.set(e,{count:1,resetAt:t+36e5})}async generateInviteToken(e){const t={from:e.from,publicKey:e.payload.publicKey,endpoint:e.payload.endpoint,timestamp:Date.now(),expiresAt:Date.now()+60*this.config.tokenExpiryHours*60*1e3},r=JSON.stringify(t);return Buffer.from(r).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async verify(){try{return await this.transporter.verify(),(0,shared_1.ok)(void 0)}catch(e){return(0,shared_1.err)("NETWORK_ERROR")}}async close(){this.transporter.close()}onReceive(e){}dispose(){this.transporter.close()}}exports.EmailTransport=EmailTransport;
1
+ "use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.EmailTransport=void 0;const shared_1=require("../_deps/shared/index.js"),email_templates_js_1=require("./email-templates.js"),nodemailer_1=__importDefault(require("nodemailer"));class EmailTransport{config;transporter;rateLimits;constructor(e){this.config={...e,rateLimit:e.rateLimit??10,tokenExpiryHours:e.tokenExpiryHours??48},this.transporter=nodemailer_1.default.createTransport({host:this.config.smtpHost,port:this.config.smtpPort,secure:!1,auth:{user:this.config.smtpUser,pass:this.config.smtpPass}}),this.rateLimits=new Map}async send(e,t){const{from:r,to:i,payload:s}=e;if(!this.isValidEmail(i))return(0,shared_1.err)("SEND_FAILED");if(!this.checkRateLimit(r).ok)return(0,shared_1.err)("SEND_FAILED");try{const t=await this.generateInviteToken(e),a=`${this.config.acceptBaseUrl}/${t}`,o=(0,email_templates_js_1.renderInviteEmail)({agentName:s.agentName||r,did:r,acceptUrl:a,message:s.message});return await this.transporter.sendMail({from:`"${this.config.fromName}" <${this.config.fromEmail}>`,to:i,subject:`${s.agentName||"Agent"} wants to connect`,html:o}),this.incrementRateLimit(r),(0,shared_1.ok)(void 0)}catch{return(0,shared_1.err)("NETWORK_ERROR")}}isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}checkRateLimit(e){const t=Date.now(),r=this.rateLimits.get(e);return r?t>=r.resetAt?(this.rateLimits.delete(e),(0,shared_1.ok)(void 0)):r.count>=this.config.rateLimit?(0,shared_1.err)(void 0):(0,shared_1.ok)(void 0):(0,shared_1.ok)(void 0)}incrementRateLimit(e){const t=Date.now(),r=this.rateLimits.get(e);r?r.count+=1:this.rateLimits.set(e,{count:1,resetAt:t+36e5})}async generateInviteToken(e){const t={from:e.from,publicKey:e.payload.publicKey,endpoint:e.payload.endpoint,timestamp:Date.now(),expiresAt:Date.now()+60*this.config.tokenExpiryHours*60*1e3},r=JSON.stringify(t);return Buffer.from(r).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async verify(){try{return await this.transporter.verify(),(0,shared_1.ok)(void 0)}catch{return(0,shared_1.err)("NETWORK_ERROR")}}async close(){this.transporter.close()}onReceive(e){}dispose(){this.transporter.close()}}exports.EmailTransport=EmailTransport;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.QuotaExceededError=exports.VaultStoreError=exports.XBindBillingError=exports.XBindAgentError=exports.XBindSplitChannelError=exports.XBindKeyAgreementError=exports.XBindRegistryError=exports.XBindTransportError=exports.XBindEnvelopeError=exports.XBindIdentityError=exports.XBindError=void 0,exports.createXBindErrorDetail=createXBindErrorDetail,exports.toXBindError=toXBindError,exports.isXBindError=isXBindError;const ux_helpers_1=require("../_deps/ux-helpers/index.js"),DOC_BASE="https://private.me/docs/xbind";class XBindError extends Error{code;subCode;docUrl;constructor(e,t,i){super(t),this.name="XBindError";const r=e.split(":");this.code=r[0]??e,this.subCode=r.length>1?r.slice(1).join(":"):void 0,this.docUrl=i}}exports.XBindError=XBindError;class XBindIdentityError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#identity`),this.name="XBindIdentityError"}}exports.XBindIdentityError=XBindIdentityError;class XBindEnvelopeError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#envelope`),this.name="XBindEnvelopeError"}}exports.XBindEnvelopeError=XBindEnvelopeError;class XBindTransportError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#transport`),this.name="XBindTransportError"}}exports.XBindTransportError=XBindTransportError;class XBindRegistryError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#registry`),this.name="XBindRegistryError"}}exports.XBindRegistryError=XBindRegistryError;class XBindKeyAgreementError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#key-agreement`),this.name="XBindKeyAgreementError"}}exports.XBindKeyAgreementError=XBindKeyAgreementError;class XBindSplitChannelError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#split-channel`),this.name="XBindSplitChannelError"}}exports.XBindSplitChannelError=XBindSplitChannelError;class XBindAgentError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#agent`),this.name="XBindAgentError"}}exports.XBindAgentError=XBindAgentError;class XBindBillingError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#billing`),this.name="XBindBillingError"}}exports.XBindBillingError=XBindBillingError;class VaultStoreError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#vault-store`),this.name="VaultStoreError"}}exports.VaultStoreError=VaultStoreError;class QuotaExceededError extends XBindBillingError{upgradeUrl;constructor(e,t){super("QUOTA_EXCEEDED",e),this.name="QuotaExceededError",this.upgradeUrl=t||"https://private.me/subscribe?product=xbind&tier=pro"}}function createXBindErrorDetail(e,t){const i=e.split(":")[0]??e,r=ERROR_DETAILS[i];return r?(0,ux_helpers_1.createDetailedError)(e,r.message,{hint:t?.hint??r.hint,field:t?.field??r.field,docs:r.docs}):(0,ux_helpers_1.createDetailedError)(e,`XBind error: ${e}`,{docs:DOC_BASE})}exports.QuotaExceededError=QuotaExceededError;const ERROR_DETAILS={KEYGEN_FAILED:{message:"Key generation failed",hint:"Verify Web Crypto API available: Run in HTTPS/localhost (browser) or Node.js 15+ (server). Check browser console for WebCryptoAPI warnings.",suggested_action:"Verify runtime environment supports Web Crypto API and retry key generation",severity:"critical",docs:`${DOC_BASE}#identity`,aws:"InternalFailure",grpc:13,http:500},SIGN_FAILED:{message:"Signing failed",hint:"Verify private key format is PKCS8 and was imported with extractable:true flag. Check key is not corrupted.",suggested_action:"Verify private key is valid and properly imported with extractable flag",severity:"high",docs:`${DOC_BASE}#identity`,aws:"InternalFailure",grpc:13,http:500},VERIFY_FAILED:{message:"Signature verification failed",hint:"Confirm sender public key matches signer identity. Verify message and signature were not truncated or modified in transit.",suggested_action:"Verify sender public key and message integrity before retrying",severity:"critical",docs:`${DOC_BASE}#identity`,aws:"InvalidParameterValue",grpc:3,http:400},INVALID_DID:{message:"DID format is invalid",hint:'DID must start with "did:" followed by method name (e.g., did:key:z6Mk...). Use validateDID() helper to check format.',field:"did",suggested_action:"Use validateDID() helper to verify format before processing",severity:"high",docs:`${DOC_BASE}#identity`,aws:"InvalidParameterValue",grpc:3,http:400},INVALID_KEY_LENGTH:{message:"Key material has incorrect length",hint:"X25519 keys must be exactly 32 bytes. Log key.length to verify. Check base64 decoding is correct.",suggested_action:"Verify key is exactly 32 bytes and properly base64-decoded",severity:"high",docs:`${DOC_BASE}#key-agreement`,aws:"InvalidParameterValue",grpc:3,http:400},EXPORT_FAILED:{message:"PKCS8 export failed",hint:"Key must be created with extractable:true flag. See https://mdn.io/SubtleCrypto.exportKey for details.",suggested_action:"Create key with extractable:true flag and verify Web Crypto API support",severity:"medium",docs:`${DOC_BASE}#identity`,aws:"InternalFailure",grpc:13,http:500},IMPORT_FAILED:{message:"PKCS8 import failed",hint:"Verify PKCS8 format (PEM or raw bytes), algorithm matches (Ed25519/X25519), and key data is not corrupted.",suggested_action:"Validate PKCS8 format and verify key data is not corrupted",severity:"high",docs:`${DOC_BASE}#identity`,aws:"InvalidParameterValue",grpc:3,http:400},INVALID_VERSION:{message:"Unsupported envelope version",hint:"This SDK supports versions v1-v4. Check envelope.version field and update SDK or request sender upgrade.",field:"version",suggested_action:"Update SDK or request sender to use compatible version (v1-v4)",severity:"high",docs:`${DOC_BASE}#envelope`,aws:"ValidationException",grpc:3,http:400},INVALID_ALG:{message:"Unknown encryption algorithm",hint:"Only AES-256-GCM is supported. Verify envelope.alg value and check sender SDK version.",field:"alg",suggested_action:"Verify sender uses AES-256-GCM algorithm",severity:"high",docs:`${DOC_BASE}#envelope`,aws:"ValidationException",grpc:3,http:400},INVALID_NONCE:{message:"Nonce is missing or invalid",hint:"Nonce must be exactly 12 bytes and properly base64-encoded. Ensure nonce is unique per envelope.",field:"nonce",suggested_action:"Verify nonce is 12 bytes and properly base64-encoded",severity:"critical",docs:`${DOC_BASE}#envelope`,aws:"ValidationException",grpc:3,http:400},INVALID_FIELDS:{message:"Required envelope fields are missing",hint:"Envelope must have: version, alg, nonce, ciphertext, tag, sender, recipient. Check none are null/undefined.",suggested_action:"Validate all required envelope fields are present",severity:"high",docs:`${DOC_BASE}#envelope`,aws:"ValidationException",grpc:3,http:400},ENCRYPT_FAILED:{message:"AES-256-GCM encryption failed",hint:"Verify shared key is exactly 32 bytes, nonce is 12 bytes, and plaintext is valid UTF-8.",suggested_action:"Verify key is 32 bytes and nonce is 12 bytes before encryption",severity:"high",docs:`${DOC_BASE}#envelope`,aws:"InternalFailure",grpc:13,http:500},DECRYPT_FAILED:{message:"Decryption failed",hint:"Verify you are using the correct decryption key. Check ciphertext and authentication tag are not corrupted in transit.",suggested_action:"Verify correct key and check ciphertext integrity",severity:"critical",docs:`${DOC_BASE}#envelope`,aws:"InternalFailure",grpc:13,http:500},PARSE_FAILED:{message:"Envelope deserialization failed",hint:"Validate JSON structure for syntax errors. Check for truncation or corruption. Verify base64 fields are properly encoded.",suggested_action:"Validate JSON structure and check for data corruption",severity:"high",docs:`${DOC_BASE}#envelope`,aws:"ValidationException",grpc:3,http:400},SEND_FAILED:{message:"Message send failed",hint:"Check network connectivity and recipient registration. Use exponential backoff retry (2s, 4s, 8s).",suggested_action:"Check network connectivity and retry with exponential backoff",severity:"high",docs:`${DOC_BASE}#transport`,aws:"ServiceUnavailable",grpc:14,http:503},NETWORK_ERROR:{message:"Network request failed",hint:"Verify internet connection and DNS resolution. Ping registry endpoint to check availability.",suggested_action:"Verify internet connection and implement exponential backoff retry",severity:"high",docs:`${DOC_BASE}#transport`,aws:"ServiceUnavailable",grpc:14,http:503},RECIPIENT_UNREACHABLE:{message:"Recipient is unreachable",hint:"Verify recipient email address is correct and recipient is registered with xBind. Ask recipient to verify registration.",field:"to",suggested_action:"Verify recipient is registered with xBind and online",severity:"medium",docs:`${DOC_BASE}#transport`,aws:"ServiceUnavailable",grpc:14,http:503},TIMEOUT:{message:"Transport operation timed out",hint:"Check network latency and registry responsiveness. Increase timeout threshold if needed (default: 30s).",suggested_action:"Increase timeout threshold and check network latency",severity:"medium",docs:`${DOC_BASE}#transport`,aws:"RequestTimeout",grpc:4,http:408},NOT_FOUND:{message:"Agent not found in trust registry",hint:"Recipient may not be registered with xBind yet. Ask recipient to register or verify email address is correct.",field:"to",suggested_action:"Ask recipient to register with xBind",severity:"medium",docs:`${DOC_BASE}#registry`,aws:"ResourceNotFoundException",grpc:5,http:404},ALREADY_REGISTERED:{message:"Agent is already registered",hint:"Use updateAgent() instead of registerAgent() to update existing registration with new keys or metadata.",suggested_action:"Use updateAgent() instead of registerAgent()",severity:"low",docs:`${DOC_BASE}#registry`,aws:"ResourceAlreadyExists",grpc:6,http:409},REVOKED:{message:"Agent has been revoked from the registry",hint:"Contact registry administrator to determine revocation reason and request re-registration if accidental.",suggested_action:"Contact registry administrator to resolve revocation",severity:"high",docs:`${DOC_BASE}#registry`,aws:"AccessDenied",grpc:7,http:403},DERIVE_FAILED:{message:"ECDH key derivation failed",hint:"Verify peer public key is valid X25519 (32 bytes) and not corrupted. Check algorithm is X25519 ECDH.",suggested_action:"Verify peer public key is valid X25519 and not corrupted",severity:"high",docs:`${DOC_BASE}#key-agreement`,aws:"InternalFailure",grpc:13,http:500},KEM_ENCAPSULATE_FAILED:{message:"ML-KEM-768 encapsulation failed",hint:"Verify recipient ML-KEM-768 public key is valid and properly formatted. Confirm post-quantum support is enabled.",suggested_action:"Verify recipient ML-KEM-768 public key and post-quantum support",severity:"high",docs:`${DOC_BASE}#key-agreement`,aws:"InternalFailure",grpc:13,http:500},KEM_DECAPSULATE_FAILED:{message:"ML-KEM-768 decapsulation failed",hint:"Verify ciphertext is not truncated and matches this secret key. Confirm ML-KEM library is initialized.",suggested_action:"Verify ciphertext integrity and ML-KEM secret key",severity:"high",docs:`${DOC_BASE}#key-agreement`,aws:"InternalFailure",grpc:13,http:500},HKDF_FAILED:{message:"HKDF key derivation failed",hint:"Verify ECDH and KEM shared secrets are valid. Ensure SHA-256 is available and HKDF input size is correct.",suggested_action:"Verify shared secrets are valid and SHA-256 is available",severity:"high",docs:`${DOC_BASE}#key-agreement`,aws:"InternalFailure",grpc:13,http:500},MLKEM_NOT_AVAILABLE:{message:"ML-KEM-768 key not available",hint:"Enable post-quantum support: Agent.create({postQuantum: true}). Regenerate identity with PQ keys enabled.",suggested_action:"Create agent with postQuantum: true",severity:"medium",docs:`${DOC_BASE}#key-agreement`},PQ_SIGN_FAILED:{message:"ML-DSA-65 signing failed",hint:"Actions: (1) Verify ML-DSA-65 secret key is valid and not corrupted, (2) Check post-quantum support is enabled, (3) Ensure message to sign is not empty, (4) Review ML-DSA library logs",suggested_action:"Verify ML-DSA-65 secret key and post-quantum support",severity:"high",docs:`${DOC_BASE}#identity`,aws:"InternalFailure",grpc:13,http:500},PQ_VERIFY_FAILED:{message:"ML-DSA-65 verification failed",hint:"Actions: (1) Verify public key matches signer, (2) Check signature format and encoding, (3) Confirm message matches what was signed, (4) Ensure post-quantum keys are synchronized",suggested_action:"Verify signer public key and signature format",severity:"high",docs:`${DOC_BASE}#identity`,aws:"InvalidParameterValue",grpc:3,http:400},SPLIT_FAILED:{message:"XorIDA split failed",hint:"Verify threshold >= 2 and <= shareCount. Ensure payload < 1MB. Check system has sufficient memory.",suggested_action:"Verify threshold parameters and payload size",severity:"high",docs:`${DOC_BASE}#split-channel`,aws:"InternalFailure",grpc:13,http:500},INSUFFICIENT_SHARES:{message:"Not enough shares to reconstruct",hint:"Log current share count and compare to threshold requirement. Collect more shares from recipients matching the split group ID.",suggested_action:"Collect more shares to meet threshold requirement",severity:"high",docs:`${DOC_BASE}#split-channel`,aws:"ValidationException",grpc:3,http:400},INCONSISTENT_SHARES:{message:"Shares have mismatched group IDs or lengths",hint:"Verify all shares have matching group IDs and identical lengths. Discard mismatched shares and request correct ones.",suggested_action:"Verify all shares are from the same split operation",severity:"high",docs:`${DOC_BASE}#split-channel`,aws:"ValidationException",grpc:3,http:400},HMAC_VERIFICATION_FAILED:{message:"Share HMAC check failed",hint:"Share may be corrupted in transit or tampered with. Request fresh share from sender using same HMAC key.",suggested_action:"Request fresh share from sender",severity:"critical",docs:`${DOC_BASE}#split-channel`,aws:"UnauthorizedOperation",grpc:16,http:401},UNPAD_FAILED:{message:"Padding removal failed after reconstruction",hint:"Verify reconstruction succeeded and data is valid UTF-8. Check padding algorithm is PKCS7.",suggested_action:"Verify reconstruction succeeded and data is valid UTF-8",severity:"high",docs:`${DOC_BASE}#split-channel`,aws:"InternalFailure",grpc:13,http:500},INVALID_SHARE_DATA:{message:"Share data is malformed",hint:"Verify share is valid base64 and has correct structure. Log raw bytes to inspect. Request correctly-formatted share.",suggested_action:"Verify share is valid base64 and request correctly-formatted share",severity:"high",docs:`${DOC_BASE}#split-channel`,aws:"ValidationException",grpc:3,http:400},XCHANGE_KEYGEN_FAILED:{message:"Xchange key generation failed",hint:"Verify Web Crypto API available (HTTPS/localhost). Check runtime supports key generation with sufficient entropy.",suggested_action:"Verify Web Crypto API available and retry",severity:"high",docs:`${DOC_BASE}#xchange`,aws:"InternalFailure",grpc:13,http:500},XCHANGE_ENCRYPT_FAILED:{message:"Xchange bundle encryption failed",hint:"Verify payload < 64KB, encryption key is 32 bytes, and bundle structure is valid.",suggested_action:"Verify payload size and encryption key length",severity:"high",docs:`${DOC_BASE}#xchange`,aws:"InternalFailure",grpc:13,http:500},XCHANGE_DECRYPT_FAILED:{message:"Xchange bundle decryption failed",hint:"Verify decryption key matches encryption key and bundle integrity is valid (auth tag correct).",suggested_action:"Verify reconstruction completed and decryption key is correct",severity:"high",docs:`${DOC_BASE}#xchange`,aws:"InternalFailure",grpc:13,http:500},INVALID_BUNDLE:{message:"Xchange bundle is malformed",hint:"Verify bundle size >= 60 bytes (32B key + 12B IV + 16B tag). Check structure and request correctly-formed bundle.",suggested_action:"Verify bundle size and request correctly-formed bundle",severity:"high",docs:`${DOC_BASE}#xchange`,aws:"ValidationException",grpc:3,http:400},IDENTITY_FAILED:{message:"Agent identity creation failed",hint:"Verify Web Crypto API is available (HTTPS/localhost context, Node.js 15+, or modern browser).",suggested_action:"Verify Web Crypto API available and retry agent initialization",severity:"critical",docs:`${DOC_BASE}#agent`,aws:"InternalFailure",grpc:13,http:500},REGISTRATION_FAILED:{message:"Agent registration with trust registry failed",hint:"Verify registry URL is reachable and auth token is valid and not expired. Check registry status page.",suggested_action:"Verify registry URL and auth token, then retry with exponential backoff",severity:"high",docs:`${DOC_BASE}#agent`,aws:"ServiceUnavailable",grpc:14,http:503},RECIPIENT_NOT_FOUND:{message:"Recipient agent not found in registry",hint:"Verify recipient email/DID is correct. Ask recipient to register with xBind first. Allow time for registration to propagate.",field:"to",suggested_action:"Ask recipient to register with xBind",severity:"medium",docs:`${DOC_BASE}#agent`,aws:"ResourceNotFoundException",grpc:5,http:404},RECIPIENT_REVOKED:{message:"Recipient agent has been revoked",hint:"Inform recipient to contact registry administrator to determine revocation reason and request re-registration if accidental.",field:"to",suggested_action:"Inform recipient to contact registry administrator",severity:"high",docs:`${DOC_BASE}#agent`,aws:"AccessDenied",grpc:7,http:403},KEY_AGREEMENT_FAILED:{message:"ECDH key agreement with recipient failed",hint:"Verify recipient public key is valid X25519 (32 bytes). Request fresh key from recipient.",suggested_action:"Request fresh key from recipient",severity:"high",docs:`${DOC_BASE}#agent`,aws:"InternalFailure",grpc:13,http:500},ENVELOPE_FAILED:{message:"Envelope creation failed",hint:"Verify payload < 10MB, recipient DID is valid, sender identity is set, and all required fields present.",suggested_action:"Verify payload size and recipient DID",severity:"high",docs:`${DOC_BASE}#agent`,aws:"InternalFailure",grpc:13,http:500},VERIFICATION_FAILED:{message:"Incoming envelope verification failed",hint:"Verify sender DID is in trust registry, sender signature is valid, and sender is not revoked. Review trust policy settings.",suggested_action:"Verify sender is in trust registry and not revoked",severity:"critical",docs:`${DOC_BASE}#agent`,aws:"UnauthorizedOperation",grpc:16,http:401},REPLAY_DETECTED:{message:"Duplicate nonce detected — possible replay attack",hint:"DISCARD MESSAGE immediately for security. Log nonce and sender DID. Alert user to potential attack.",suggested_action:"DISCARD MESSAGE and alert user to potential replay attack",severity:"critical",docs:`${DOC_BASE}#agent`,aws:"AccessDenied",grpc:7,http:403},SCOPE_DENIED:{message:"Sender does not have permission for the requested scope",hint:"Verify scope value is correct. Contact registry admin to grant sender permission for requested scope.",field:"scope",suggested_action:"Contact registry admin to grant permission",severity:"medium",docs:`${DOC_BASE}#agent`,aws:"AccessDenied",grpc:7,http:403},RECEIVER_SCOPE_DENIED:{message:"Recipient does not accept messages with this scope",hint:"Ask recipient to enable this scope in their settings. Verify scope matches recipient policy.",field:"scope",suggested_action:"Ask recipient to enable scope in settings",severity:"medium",docs:`${DOC_BASE}#agent`,aws:"AccessDenied",grpc:7,http:403},TIMESTAMP_EXPIRED:{message:"Envelope timestamp is outside the allowed window",hint:"Synchronize system clocks using NTP. Check time difference between sender and receiver.",suggested_action:"Synchronize system clocks using NTP",severity:"medium",docs:`${DOC_BASE}#agent`,aws:"RequestExpired",grpc:9,http:412},INCOMPATIBLE_VERSION:{message:"Client version is incompatible with server",hint:"Update xBind SDK to latest version. Check minimum supported version in documentation.",suggested_action:"Update xBind SDK to latest version",severity:"high",docs:`${DOC_BASE}#agent`,aws:"ValidationException",grpc:3,http:400},FEATURE_NOT_SUPPORTED:{message:"Requested feature is not supported",hint:"Verify SDK version supports this feature and it is available in current plan. Consider upgrading.",suggested_action:"Check feature availability in current plan or SDK version",severity:"medium",docs:`${DOC_BASE}#agent`,aws:"ValidationException",grpc:12,http:501},QUOTA_EXCEEDED:{message:"Operation quota exceeded",hint:"Check usage against plan limits. Implement rate limiting or upgrade to higher tier plan.",suggested_action:"Implement rate limiting or upgrade plan",severity:"medium",docs:`${DOC_BASE}#agent`,aws:"ThrottlingException",grpc:8,http:429},ACCOUNT_SUSPENDED:{message:"Account has been suspended",hint:"Contact support to determine suspension reason. Review terms of service and resolve any payment or policy issues.",suggested_action:"Contact support to resolve suspension",severity:"critical",docs:`${DOC_BASE}#agent`,aws:"AccessDeniedException",grpc:7,http:403},ACCOUNT_NOT_FOUND:{message:"Account does not exist",hint:"Verify account identifier is correct. Check if account was deleted. Create new account if needed.",suggested_action:"Verify account identifier or create new account",severity:"high",docs:`${DOC_BASE}#agent`,aws:"ResourceNotFoundException",grpc:5,http:404},BILLING_FAILURE:{message:"Billing operation failed",hint:"Verify payment method is valid and not expired. Check Stripe account status. Review billing logs.",suggested_action:"Verify payment method and check billing logs",severity:"high",docs:`${DOC_BASE}#billing`,aws:"RequestLimitExceeded",grpc:8,http:402},PAYMENT_REQUIRED:{message:"Payment required to access this resource",hint:"Add payment method in account settings and subscribe to appropriate tier.",suggested_action:"Add payment method and subscribe to access this resource",severity:"medium",docs:`${DOC_BASE}#billing`,aws:"AccessDenied",grpc:7,http:402},SUBSCRIPTION_REQUIRED:{message:"Valid subscription required",hint:"Subscribe to a paid tier in account settings. Verify subscription is active and not expired.",suggested_action:"Subscribe to a paid tier to access this feature",severity:"medium",docs:`${DOC_BASE}#billing`,aws:"AccessDenied",grpc:7,http:403},TIER_LIMIT_EXCEEDED:{message:"Current tier usage limit exceeded",hint:"Check current usage vs tier limits. Upgrade to higher tier for increased limits or wait for monthly reset.",suggested_action:"Upgrade to higher tier or wait for limit reset",severity:"medium",docs:`${DOC_BASE}#billing`,aws:"RequestLimitExceeded",grpc:8,http:403},VERIFICATION_REQUIRED:{message:"Account verification required",hint:"Complete email and payment method verification. Check account verification status in settings.",suggested_action:"Complete account verification steps in settings",severity:"high",docs:`${DOC_BASE}#billing`,aws:"AccessDenied",grpc:7,http:403},VAULT_FETCH_FAILED:{message:"Failed to fetch crypto package from Vault Store",hint:"Check network connectivity to private.me. Verify Vault Store endpoint is reachable. Try again in a few moments.",suggested_action:"Verify network connectivity and retry with exponential backoff",severity:"high",docs:`${DOC_BASE}#vault-store`,aws:"ServiceUnavailable",grpc:14,http:503},VAULT_AUTH_FAILED:{message:"Vault Store authentication failed",hint:"DID signature verification failed. Verify agent identity is valid and properly initialized. Check system clock is synchronized.",suggested_action:"Verify agent identity and synchronize system clock (NTP)",severity:"critical",docs:`${DOC_BASE}#vault-store`,aws:"UnauthorizedOperation",grpc:16,http:401},VAULT_QUOTA_EXCEEDED:{message:"Monthly usage quota exceeded",hint:"Free tier allows 100,000 operations per month (120,000 with grace buffer). Upgrade to Pro tier for unlimited access at $5 per 100K operations.",suggested_action:"Upgrade to Pro tier: https://private.me/subscribe?product=xbind&tier=pro",severity:"medium",docs:`${DOC_BASE}#vault-store`,aws:"RequestLimitExceeded",grpc:8,http:402},VAULT_PAYMENT_REQUIRED:{message:"Payment required to access Vault Store",hint:"Subscription expired or payment method failed. Update payment method and verify subscription is active.",suggested_action:"Update payment method and verify subscription status",severity:"high",docs:`${DOC_BASE}#vault-store`,aws:"AccessDenied",grpc:7,http:451},VAULT_LOAD_FAILED:{message:"Failed to load crypto package",hint:"Crypto bundle evaluation failed. This may indicate corrupted bundle or incompatible version. Contact support if issue persists.",suggested_action:"Clear cache and retry. Contact support if issue persists.",severity:"high",docs:`${DOC_BASE}#vault-store`,aws:"InternalFailure",grpc:13,http:500},VAULT_INVALID_RESPONSE:{message:"Invalid response from Vault Store",hint:"Server returned malformed data. This may indicate version mismatch or server issue. Try updating SDK or contact support.",suggested_action:"Update xBind SDK to latest version or contact support",severity:"high",docs:`${DOC_BASE}#vault-store`,aws:"InternalFailure",grpc:13,http:500}},ERROR_MESSAGES={KEYGEN_FAILED:[XBindIdentityError,"Key generation failed. Actions: (1) Verify Web Crypto API is available in HTTPS or localhost, (2) Check runtime is Node.js 15+ or modern browser, (3) Retry initialization."],SIGN_FAILED:[XBindIdentityError,"Signing failed. Actions: (1) Verify private key is valid and not corrupted, (2) Check key was properly imported, (3) Ensure key is extractable."],VERIFY_FAILED:[XBindIdentityError,"Signature verification failed. Actions: (1) Confirm public key matches signer, (2) Check message integrity, (3) Verify signature format is valid base64."],INVALID_DID:[XBindIdentityError,"The DID string is malformed. Actions: (1) Verify format: did:key:z6Mk..., (2) Check no extra whitespace, (3) Use validateDID() helper."],INVALID_KEY_LENGTH:[XBindKeyAgreementError,"Key material is the wrong length. Actions: (1) Verify X25519 key is exactly 32 bytes, (2) Check base64 decoding, (3) Log key.length to confirm."],EXPORT_FAILED:[XBindIdentityError,"PKCS8 export failed. Actions: (1) Create key with extractable:true, (2) Check Web Crypto support, (3) See: https://mdn.io/SubtleCrypto.exportKey."],IMPORT_FAILED:[XBindIdentityError,"PKCS8 import failed. Actions: (1) Validate PKCS8 format (PEM or bytes), (2) Decode base64 if needed, (3) Check algorithm (Ed25519/X25519)."],INVALID_VERSION:[XBindEnvelopeError,"Unsupported envelope version. Actions: (1) Check envelope.version field, (2) Verify sender uses v1-v4, (3) Request sender SDK update."],INVALID_ALG:[XBindEnvelopeError,'Unknown encryption algorithm. Actions: (1) Verify envelope.alg === "AES-256-GCM", (2) Log alg value to debug, (3) Check sender SDK version.'],INVALID_NONCE:[XBindEnvelopeError,"Nonce is missing or invalid. Actions: (1) Verify nonce exists and is 12 bytes, (2) Check base64 decoding, (3) Inspect replay buffer."],INVALID_FIELDS:[XBindEnvelopeError,"Required envelope fields are missing. Actions: (1) Verify sender/recipient DIDs, (2) Check payload exists, (3) Validate: version, alg, nonce, ciphertext, tag."],ENCRYPT_FAILED:[XBindEnvelopeError,"AES-256-GCM encryption failed. Actions: (1) Verify key is exactly 32 bytes, (2) Check plaintext is valid, (3) Ensure nonce is 12 bytes."],DECRYPT_FAILED:[XBindEnvelopeError,"Decryption failed. Actions: (1) Verify correct key is being used, (2) Check ciphertext integrity, (3) Confirm auth tag is valid."],PARSE_FAILED:[XBindEnvelopeError,"Envelope deserialization failed. Actions: (1) Validate JSON structure, (2) Check for truncation, (3) Verify base64 encoding of fields."],SEND_FAILED:[XBindTransportError,"Message send failed. Actions: (1) Check network connectivity (ping registry), (2) Verify recipient address, (3) Confirm recipient registered, (4) Retry with backoff."],NETWORK_ERROR:[XBindTransportError,"Network request failed. Actions: (1) Verify internet connection, (2) Check DNS resolution, (3) Ping registry endpoint, (4) Implement exponential backoff (2s, 4s, 8s)."],RECIPIENT_UNREACHABLE:[XBindTransportError,"Recipient is unreachable. Actions: (1) Verify recipient email is correct, (2) Check if recipient is registered, (3) Confirm recipient is online, (4) Provide human follow-up."],TIMEOUT:[XBindTransportError,"Transport operation timed out. Actions: (1) Increase timeout threshold, (2) Check network latency, (3) Verify registry responsiveness, (4) Retry operation."],NOT_FOUND:[XBindRegistryError,"Agent not found in trust registry. Actions: (1) Ask recipient to register with xBind, (2) Verify recipient email/DID, (3) Check registration status, (4) Retry after propagation."],ALREADY_REGISTERED:[XBindRegistryError,"Agent is already registered. Actions: (1) Use updateAgent() instead, (2) Provide new keys or metadata, (3) Verify DID matches existing entry."],REVOKED:[XBindRegistryError,"Agent has been revoked from the registry. Actions: (1) Contact registry admin, (2) Check revocation reason, (3) Request re-registration if accidental."],DERIVE_FAILED:[XBindKeyAgreementError,"ECDH key derivation failed. Actions: (1) Verify peer public key is valid X25519 (32 bytes), (2) Check key is not corrupted, (3) Confirm X25519 ECDH support."],KEM_ENCAPSULATE_FAILED:[XBindKeyAgreementError,"ML-KEM-768 encapsulation failed. Actions: (1) Verify recipient key is valid ML-KEM-768, (2) Check key format, (3) Confirm post-quantum support enabled."],KEM_DECAPSULATE_FAILED:[XBindKeyAgreementError,"ML-KEM-768 decapsulation failed. Actions: (1) Verify ciphertext integrity, (2) Check secret key is valid, (3) Confirm ciphertext matches key."],HKDF_FAILED:[XBindKeyAgreementError,"HKDF key derivation failed. Actions: (1) Verify both shared secrets are valid, (2) Check HKDF input size, (3) Ensure SHA-256 support."],MLKEM_NOT_AVAILABLE:[XBindKeyAgreementError,"ML-KEM-768 key not available. Actions: (1) Create agent with postQuantum: true, (2) Check runtime supports ML-KEM-768, (3) Regenerate identity with PQ enabled."],PQ_SIGN_FAILED:[XBindIdentityError,"ML-DSA-65 signing failed. Actions: (1) Verify secret key is valid, (2) Check post-quantum support enabled, (3) Ensure message is not empty."],PQ_VERIFY_FAILED:[XBindIdentityError,"ML-DSA-65 verification failed. Actions: (1) Verify public key matches signer, (2) Check signature format, (3) Confirm message integrity."],SPLIT_FAILED:[XBindSplitChannelError,"XorIDA split failed. Actions: (1) Verify threshold <= shareCount, (2) Check threshold >= 2, (3) Validate payload < 1MB."],INSUFFICIENT_SHARES:[XBindSplitChannelError,"Not enough shares to reconstruct. Actions: (1) Log number of shares collected, (2) Check threshold requirement, (3) Collect more shares."],INCONSISTENT_SHARES:[XBindSplitChannelError,"Shares have mismatched group IDs or lengths. Actions: (1) Verify all from same split, (2) Check group IDs match, (3) Discard mismatched shares."],HMAC_VERIFICATION_FAILED:[XBindSplitChannelError,"Share HMAC check failed. Actions: (1) Check share integrity in transit, (2) Verify not tampered with, (3) Request fresh share."],UNPAD_FAILED:[XBindSplitChannelError,"Padding removal failed after reconstruction. Actions: (1) Verify reconstruction succeeded, (2) Check data is valid UTF-8, (3) Inspect raw bytes."],INVALID_SHARE_DATA:[XBindSplitChannelError,"Share data is malformed. Actions: (1) Verify share is valid base64, (2) Check TLV structure, (3) Log raw bytes to inspect."],XCHANGE_KEYGEN_FAILED:[XBindKeyAgreementError,"Xchange key generation failed. Actions: (1) Verify Web Crypto available (HTTPS/localhost), (2) Check runtime support, (3) Ensure entropy."],XCHANGE_ENCRYPT_FAILED:[XBindEnvelopeError,"Xchange bundle encryption failed. Actions: (1) Check payload < 64KB, (2) Verify key is 32 bytes, (3) Validate bundle structure."],XCHANGE_DECRYPT_FAILED:[XBindEnvelopeError,"Xchange bundle decryption failed. Actions: (1) Verify reconstruction succeeded, (2) Check key matches encryption key, (3) Confirm bundle integrity."],INVALID_BUNDLE:[XBindSplitChannelError,"Xchange bundle is malformed. Actions: (1) Verify size >= 60 bytes (32B + 12B + 16B), (2) Check structure, (3) Decode to inspect."],IDENTITY_FAILED:[XBindAgentError,"Agent identity creation failed. Actions: (1) Verify Web Crypto available, (2) Check HTTPS/localhost, (3) Ensure Node.js 15+ or modern browser."],REGISTRATION_FAILED:[XBindAgentError,"Agent registration with trust registry failed. Actions: (1) Verify registry URL is correct, (2) Check auth token valid/not expired, (3) Confirm registry online."],RECIPIENT_NOT_FOUND:[XBindAgentError,"Recipient agent not found in registry. Actions: (1) Verify recipient email/DID, (2) Ask recipient to register first, (3) Wait for propagation."],RECIPIENT_REVOKED:[XBindAgentError,"Recipient agent has been revoked. Actions: (1) Inform recipient to contact admin, (2) Verify revocation reason, (3) Request re-registration."],KEY_AGREEMENT_FAILED:[XBindAgentError,"ECDH key agreement with recipient failed. Actions: (1) Verify recipient key valid, (2) Check key format (X25519, 32B), (3) Request fresh key."],ENVELOPE_FAILED:[XBindAgentError,"Envelope creation failed. Actions: (1) Check payload < 10MB, (2) Verify recipient DID valid, (3) Confirm sender identity set."],VERIFICATION_FAILED:[XBindAgentError,"Incoming envelope verification failed. Actions: (1) Check sender in registry, (2) Verify signature valid, (3) Confirm sender not revoked."],REPLAY_DETECTED:[XBindAgentError,"Duplicate nonce detected — possible replay attack. Actions: (1) DISCARD message, (2) Log nonce/sender, (3) Alert user to potential attack."],SCOPE_DENIED:[XBindAgentError,"Sender does not have permission for the requested scope. Actions: (1) Check sender scope in registry, (2) Contact admin to grant, (3) Verify scope value."],RECEIVER_SCOPE_DENIED:[XBindAgentError,"Recipient does not accept messages with this scope. Actions: (1) Check recipient receive scope settings, (2) Ask to enable scope, (3) Verify registry entry."],TIMESTAMP_EXPIRED:[XBindAgentError,"Envelope timestamp is outside the allowed window. Actions: (1) Synchronize system clocks (NTP), (2) Check time difference, (3) Verify no time drift."],INCOMPATIBLE_VERSION:[XBindAgentError,"Client version is incompatible with server. Actions: (1) Update xBind SDK to latest version, (2) Check minimum supported version, (3) Contact support if upgrade not possible."],FEATURE_NOT_SUPPORTED:[XBindAgentError,"Requested feature is not supported. Actions: (1) Check feature availability in plan, (2) Verify SDK version, (3) Consider upgrading plan."],QUOTA_EXCEEDED:[XBindAgentError,"Operation quota exceeded. Actions: (1) Check usage against plan limits, (2) Implement rate limiting, (3) Upgrade plan, (4) Wait for quota reset."],ACCOUNT_SUSPENDED:[XBindAgentError,"Account has been suspended. Actions: (1) Contact support for suspension reason, (2) Review terms compliance, (3) Resolve payment/policy issues."],ACCOUNT_NOT_FOUND:[XBindAgentError,"Account does not exist. Actions: (1) Verify account identifier, (2) Check if account was deleted, (3) Create new account if needed."],BILLING_FAILURE:[XBindBillingError,"Billing operation failed. Actions: (1) Verify payment method is valid and not expired, (2) Check Stripe account status, (3) Review billing logs, (4) Contact support if issue persists."],PAYMENT_REQUIRED:[XBindBillingError,"Payment required to access this resource. Actions: (1) Add payment method in account settings, (2) Subscribe to appropriate tier, (3) Verify billing information is current."],SUBSCRIPTION_REQUIRED:[XBindBillingError,"Valid subscription required. Actions: (1) Subscribe to a paid tier in account settings, (2) Verify subscription is active and not expired, (3) Check billing status."],TIER_LIMIT_EXCEEDED:[XBindBillingError,"Current tier usage limit exceeded. Actions: (1) Upgrade to higher tier for increased limits, (2) Check current usage vs tier limits, (3) Wait for limit reset (typically monthly)."],VERIFICATION_REQUIRED:[XBindBillingError,"Account verification required. Actions: (1) Complete email verification, (2) Verify payment method, (3) Complete identity verification if required, (4) Check account verification status in settings."],VAULT_FETCH_FAILED:[VaultStoreError,"Failed to fetch crypto package from Vault Store. Actions: (1) Check network connectivity to private.me, (2) Verify Vault Store endpoint is reachable, (3) Retry with exponential backoff, (4) Check server status page."],VAULT_AUTH_FAILED:[VaultStoreError,"Vault Store authentication failed. Actions: (1) Verify agent identity is valid, (2) Check DID signature is correct, (3) Synchronize system clock (NTP), (4) Regenerate identity if corrupted."],VAULT_QUOTA_EXCEEDED:[QuotaExceededError,"Monthly usage quota exceeded. Free tier: 100K operations/month (120K with grace). Actions: (1) Upgrade to Pro tier for unlimited access ($5/100K ops), (2) Visit https://private.me/subscribe?product=xbind&tier=pro, (3) Wait for monthly reset (1st of month, 00:00 UTC)."],VAULT_PAYMENT_REQUIRED:[VaultStoreError,"Payment required to access Vault Store. Actions: (1) Update payment method in account settings, (2) Verify subscription is active, (3) Check billing status, (4) Contact support if payment issue persists."],VAULT_LOAD_FAILED:[VaultStoreError,"Failed to load crypto package. Actions: (1) Clear crypto cache and retry, (2) Verify SDK version is compatible, (3) Check bundle integrity, (4) Contact support if issue persists."],VAULT_INVALID_RESPONSE:[VaultStoreError,"Invalid response from Vault Store. Actions: (1) Update xBind SDK to latest version, (2) Check API compatibility, (3) Retry request, (4) Contact support if issue persists."]};function toXBindError(e){const t=e.split(":")[0]??e,i=ERROR_MESSAGES[t];if(i){const[t,r]=i;return new t(e,r)}return new XBindError(e,`XBind error: ${e}`)}function isXBindError(e){return e instanceof XBindError}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.QuotaExceededError=exports.VaultStoreError=exports.XBindBillingError=exports.XBindAgentError=exports.XBindSplitChannelError=exports.XBindKeyAgreementError=exports.XBindRegistryError=exports.XBindTransportError=exports.XBindEnvelopeError=exports.XBindIdentityError=exports.XBindError=void 0,exports.createXBindErrorDetail=createXBindErrorDetail,exports.toXBindError=toXBindError,exports.isXBindError=isXBindError;const ux_helpers_1=require("../_deps/ux-helpers/index.js"),DOC_BASE="https://private.me/docs/xbind";class XBindError extends Error{code;subCode;docUrl;constructor(e,t,i){super(t),this.name="XBindError";const r=e.split(":");this.code=r[0]??e,this.subCode=r.length>1?r.slice(1).join(":"):void 0,this.docUrl=i}}exports.XBindError=XBindError;class XBindIdentityError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#identity`),this.name="XBindIdentityError"}}exports.XBindIdentityError=XBindIdentityError;class XBindEnvelopeError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#envelope`),this.name="XBindEnvelopeError"}}exports.XBindEnvelopeError=XBindEnvelopeError;class XBindTransportError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#transport`),this.name="XBindTransportError"}}exports.XBindTransportError=XBindTransportError;class XBindRegistryError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#registry`),this.name="XBindRegistryError"}}exports.XBindRegistryError=XBindRegistryError;class XBindKeyAgreementError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#key-agreement`),this.name="XBindKeyAgreementError"}}exports.XBindKeyAgreementError=XBindKeyAgreementError;class XBindSplitChannelError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#split-channel`),this.name="XBindSplitChannelError"}}exports.XBindSplitChannelError=XBindSplitChannelError;class XBindAgentError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#agent`),this.name="XBindAgentError"}}exports.XBindAgentError=XBindAgentError;class XBindBillingError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#billing`),this.name="XBindBillingError"}}exports.XBindBillingError=XBindBillingError;class VaultStoreError extends XBindError{constructor(e,t){super(e,t,`${DOC_BASE}#vault-store`),this.name="VaultStoreError"}}exports.VaultStoreError=VaultStoreError;class QuotaExceededError extends XBindBillingError{upgradeUrl;constructor(e,t,i){super(e,t),this.name="QuotaExceededError",this.upgradeUrl=i||"https://private.me/subscribe?product=xbind&tier=pro"}}function createXBindErrorDetail(e,t){const i=e.split(":")[0]??e,r=ERROR_DETAILS[i];return r?(0,ux_helpers_1.createDetailedError)(e,r.message,{hint:t?.hint??r.hint,field:t?.field??r.field,docs:r.docs}):(0,ux_helpers_1.createDetailedError)(e,`XBind error: ${e}`,{docs:DOC_BASE})}exports.QuotaExceededError=QuotaExceededError;const ERROR_DETAILS={KEYGEN_FAILED:{message:"Key generation failed",hint:"Verify Web Crypto API available: Run in HTTPS/localhost (browser) or Node.js 15+ (server). Check browser console for WebCryptoAPI warnings.",suggested_action:"Verify runtime environment supports Web Crypto API and retry key generation",severity:"critical",docs:`${DOC_BASE}#identity`,aws:"InternalFailure",grpc:13,http:500},SIGN_FAILED:{message:"Signing failed",hint:"Verify private key format is PKCS8 and was imported with extractable:true flag. Check key is not corrupted.",suggested_action:"Verify private key is valid and properly imported with extractable flag",severity:"high",docs:`${DOC_BASE}#identity`,aws:"InternalFailure",grpc:13,http:500},VERIFY_FAILED:{message:"Signature verification failed",hint:"Confirm sender public key matches signer identity. Verify message and signature were not truncated or modified in transit.",suggested_action:"Verify sender public key and message integrity before retrying",severity:"critical",docs:`${DOC_BASE}#identity`,aws:"InvalidParameterValue",grpc:3,http:400},INVALID_DID:{message:"DID format is invalid",hint:'DID must start with "did:" followed by method name (e.g., did:key:z6Mk...). Use validateDID() helper to check format.',field:"did",suggested_action:"Use validateDID() helper to verify format before processing",severity:"high",docs:`${DOC_BASE}#identity`,aws:"InvalidParameterValue",grpc:3,http:400},INVALID_KEY_LENGTH:{message:"Key material has incorrect length",hint:"X25519 keys must be exactly 32 bytes. Log key.length to verify. Check base64 decoding is correct.",suggested_action:"Verify key is exactly 32 bytes and properly base64-decoded",severity:"high",docs:`${DOC_BASE}#key-agreement`,aws:"InvalidParameterValue",grpc:3,http:400},EXPORT_FAILED:{message:"PKCS8 export failed",hint:"Key must be created with extractable:true flag. See https://mdn.io/SubtleCrypto.exportKey for details.",suggested_action:"Create key with extractable:true flag and verify Web Crypto API support",severity:"medium",docs:`${DOC_BASE}#identity`,aws:"InternalFailure",grpc:13,http:500},IMPORT_FAILED:{message:"PKCS8 import failed",hint:"Verify PKCS8 format (PEM or raw bytes), algorithm matches (Ed25519/X25519), and key data is not corrupted.",suggested_action:"Validate PKCS8 format and verify key data is not corrupted",severity:"high",docs:`${DOC_BASE}#identity`,aws:"InvalidParameterValue",grpc:3,http:400},INVALID_VERSION:{message:"Unsupported envelope version",hint:"This SDK supports versions v1-v4. Check envelope.version field and update SDK or request sender upgrade.",field:"version",suggested_action:"Update SDK or request sender to use compatible version (v1-v4)",severity:"high",docs:`${DOC_BASE}#envelope`,aws:"ValidationException",grpc:3,http:400},INVALID_ALG:{message:"Unknown encryption algorithm",hint:"Only AES-256-GCM is supported. Verify envelope.alg value and check sender SDK version.",field:"alg",suggested_action:"Verify sender uses AES-256-GCM algorithm",severity:"high",docs:`${DOC_BASE}#envelope`,aws:"ValidationException",grpc:3,http:400},INVALID_NONCE:{message:"Nonce is missing or invalid",hint:"Nonce must be exactly 12 bytes and properly base64-encoded. Ensure nonce is unique per envelope.",field:"nonce",suggested_action:"Verify nonce is 12 bytes and properly base64-encoded",severity:"critical",docs:`${DOC_BASE}#envelope`,aws:"ValidationException",grpc:3,http:400},INVALID_FIELDS:{message:"Required envelope fields are missing",hint:"Envelope must have: version, alg, nonce, ciphertext, tag, sender, recipient. Check none are null/undefined.",suggested_action:"Validate all required envelope fields are present",severity:"high",docs:`${DOC_BASE}#envelope`,aws:"ValidationException",grpc:3,http:400},ENCRYPT_FAILED:{message:"AES-256-GCM encryption failed",hint:"Verify shared key is exactly 32 bytes, nonce is 12 bytes, and plaintext is valid UTF-8.",suggested_action:"Verify key is 32 bytes and nonce is 12 bytes before encryption",severity:"high",docs:`${DOC_BASE}#envelope`,aws:"InternalFailure",grpc:13,http:500},DECRYPT_FAILED:{message:"Decryption failed",hint:"Verify you are using the correct decryption key. Check ciphertext and authentication tag are not corrupted in transit.",suggested_action:"Verify correct key and check ciphertext integrity",severity:"critical",docs:`${DOC_BASE}#envelope`,aws:"InternalFailure",grpc:13,http:500},PARSE_FAILED:{message:"Envelope deserialization failed",hint:"Validate JSON structure for syntax errors. Check for truncation or corruption. Verify base64 fields are properly encoded.",suggested_action:"Validate JSON structure and check for data corruption",severity:"high",docs:`${DOC_BASE}#envelope`,aws:"ValidationException",grpc:3,http:400},SEND_FAILED:{message:"Message send failed",hint:"Check network connectivity and recipient registration. Use exponential backoff retry (2s, 4s, 8s).",suggested_action:"Check network connectivity and retry with exponential backoff",severity:"high",docs:`${DOC_BASE}#transport`,aws:"ServiceUnavailable",grpc:14,http:503},NETWORK_ERROR:{message:"Network request failed",hint:"Verify internet connection and DNS resolution. Ping registry endpoint to check availability.",suggested_action:"Verify internet connection and implement exponential backoff retry",severity:"high",docs:`${DOC_BASE}#transport`,aws:"ServiceUnavailable",grpc:14,http:503},RECIPIENT_UNREACHABLE:{message:"Recipient is unreachable",hint:"Verify recipient email address is correct and recipient is registered with xBind. Ask recipient to verify registration.",field:"to",suggested_action:"Verify recipient is registered with xBind and online",severity:"medium",docs:`${DOC_BASE}#transport`,aws:"ServiceUnavailable",grpc:14,http:503},TIMEOUT:{message:"Transport operation timed out",hint:"Check network latency and registry responsiveness. Increase timeout threshold if needed (default: 30s).",suggested_action:"Increase timeout threshold and check network latency",severity:"medium",docs:`${DOC_BASE}#transport`,aws:"RequestTimeout",grpc:4,http:408},NOT_FOUND:{message:"Agent not found in trust registry",hint:"Recipient may not be registered with xBind yet. Ask recipient to register or verify email address is correct.",field:"to",suggested_action:"Ask recipient to register with xBind",severity:"medium",docs:`${DOC_BASE}#registry`,aws:"ResourceNotFoundException",grpc:5,http:404},ALREADY_REGISTERED:{message:"Agent is already registered",hint:"Use updateAgent() instead of registerAgent() to update existing registration with new keys or metadata.",suggested_action:"Use updateAgent() instead of registerAgent()",severity:"low",docs:`${DOC_BASE}#registry`,aws:"ResourceAlreadyExists",grpc:6,http:409},REVOKED:{message:"Agent has been revoked from the registry",hint:"Contact registry administrator to determine revocation reason and request re-registration if accidental.",suggested_action:"Contact registry administrator to resolve revocation",severity:"high",docs:`${DOC_BASE}#registry`,aws:"AccessDenied",grpc:7,http:403},DERIVE_FAILED:{message:"ECDH key derivation failed",hint:"Verify peer public key is valid X25519 (32 bytes) and not corrupted. Check algorithm is X25519 ECDH.",suggested_action:"Verify peer public key is valid X25519 and not corrupted",severity:"high",docs:`${DOC_BASE}#key-agreement`,aws:"InternalFailure",grpc:13,http:500},KEM_ENCAPSULATE_FAILED:{message:"ML-KEM-768 encapsulation failed",hint:"Verify recipient ML-KEM-768 public key is valid and properly formatted. Confirm post-quantum support is enabled.",suggested_action:"Verify recipient ML-KEM-768 public key and post-quantum support",severity:"high",docs:`${DOC_BASE}#key-agreement`,aws:"InternalFailure",grpc:13,http:500},KEM_DECAPSULATE_FAILED:{message:"ML-KEM-768 decapsulation failed",hint:"Verify ciphertext is not truncated and matches this secret key. Confirm ML-KEM library is initialized.",suggested_action:"Verify ciphertext integrity and ML-KEM secret key",severity:"high",docs:`${DOC_BASE}#key-agreement`,aws:"InternalFailure",grpc:13,http:500},HKDF_FAILED:{message:"HKDF key derivation failed",hint:"Verify ECDH and KEM shared secrets are valid. Ensure SHA-256 is available and HKDF input size is correct.",suggested_action:"Verify shared secrets are valid and SHA-256 is available",severity:"high",docs:`${DOC_BASE}#key-agreement`,aws:"InternalFailure",grpc:13,http:500},MLKEM_NOT_AVAILABLE:{message:"ML-KEM-768 key not available",hint:"Enable post-quantum support: Agent.create({postQuantum: true}). Regenerate identity with PQ keys enabled.",suggested_action:"Create agent with postQuantum: true",severity:"medium",docs:`${DOC_BASE}#key-agreement`},PQ_SIGN_FAILED:{message:"ML-DSA-65 signing failed",hint:"Actions: (1) Verify ML-DSA-65 secret key is valid and not corrupted, (2) Check post-quantum support is enabled, (3) Ensure message to sign is not empty, (4) Review ML-DSA library logs",suggested_action:"Verify ML-DSA-65 secret key and post-quantum support",severity:"high",docs:`${DOC_BASE}#identity`,aws:"InternalFailure",grpc:13,http:500},PQ_VERIFY_FAILED:{message:"ML-DSA-65 verification failed",hint:"Actions: (1) Verify public key matches signer, (2) Check signature format and encoding, (3) Confirm message matches what was signed, (4) Ensure post-quantum keys are synchronized",suggested_action:"Verify signer public key and signature format",severity:"high",docs:`${DOC_BASE}#identity`,aws:"InvalidParameterValue",grpc:3,http:400},SPLIT_FAILED:{message:"XorIDA split failed",hint:"Verify threshold >= 2 and <= shareCount. Ensure payload < 1MB. Check system has sufficient memory.",suggested_action:"Verify threshold parameters and payload size",severity:"high",docs:`${DOC_BASE}#split-channel`,aws:"InternalFailure",grpc:13,http:500},INSUFFICIENT_SHARES:{message:"Not enough shares to reconstruct",hint:"Log current share count and compare to threshold requirement. Collect more shares from recipients matching the split group ID.",suggested_action:"Collect more shares to meet threshold requirement",severity:"high",docs:`${DOC_BASE}#split-channel`,aws:"ValidationException",grpc:3,http:400},INCONSISTENT_SHARES:{message:"Shares have mismatched group IDs or lengths",hint:"Verify all shares have matching group IDs and identical lengths. Discard mismatched shares and request correct ones.",suggested_action:"Verify all shares are from the same split operation",severity:"high",docs:`${DOC_BASE}#split-channel`,aws:"ValidationException",grpc:3,http:400},HMAC_VERIFICATION_FAILED:{message:"Share HMAC check failed",hint:"Share may be corrupted in transit or tampered with. Request fresh share from sender using same HMAC key.",suggested_action:"Request fresh share from sender",severity:"critical",docs:`${DOC_BASE}#split-channel`,aws:"UnauthorizedOperation",grpc:16,http:401},UNPAD_FAILED:{message:"Padding removal failed after reconstruction",hint:"Verify reconstruction succeeded and data is valid UTF-8. Check padding algorithm is PKCS7.",suggested_action:"Verify reconstruction succeeded and data is valid UTF-8",severity:"high",docs:`${DOC_BASE}#split-channel`,aws:"InternalFailure",grpc:13,http:500},INVALID_SHARE_DATA:{message:"Share data is malformed",hint:"Verify share is valid base64 and has correct structure. Log raw bytes to inspect. Request correctly-formatted share.",suggested_action:"Verify share is valid base64 and request correctly-formatted share",severity:"high",docs:`${DOC_BASE}#split-channel`,aws:"ValidationException",grpc:3,http:400},XCHANGE_KEYGEN_FAILED:{message:"Xchange key generation failed",hint:"Verify Web Crypto API available (HTTPS/localhost). Check runtime supports key generation with sufficient entropy.",suggested_action:"Verify Web Crypto API available and retry",severity:"high",docs:`${DOC_BASE}#xchange`,aws:"InternalFailure",grpc:13,http:500},XCHANGE_ENCRYPT_FAILED:{message:"Xchange bundle encryption failed",hint:"Verify payload < 64KB, encryption key is 32 bytes, and bundle structure is valid.",suggested_action:"Verify payload size and encryption key length",severity:"high",docs:`${DOC_BASE}#xchange`,aws:"InternalFailure",grpc:13,http:500},XCHANGE_DECRYPT_FAILED:{message:"Xchange bundle decryption failed",hint:"Verify decryption key matches encryption key and bundle integrity is valid (auth tag correct).",suggested_action:"Verify reconstruction completed and decryption key is correct",severity:"high",docs:`${DOC_BASE}#xchange`,aws:"InternalFailure",grpc:13,http:500},INVALID_BUNDLE:{message:"Xchange bundle is malformed",hint:"Verify bundle size >= 60 bytes (32B key + 12B IV + 16B tag). Check structure and request correctly-formed bundle.",suggested_action:"Verify bundle size and request correctly-formed bundle",severity:"high",docs:`${DOC_BASE}#xchange`,aws:"ValidationException",grpc:3,http:400},IDENTITY_FAILED:{message:"Agent identity creation failed",hint:"Verify Web Crypto API is available (HTTPS/localhost context, Node.js 15+, or modern browser).",suggested_action:"Verify Web Crypto API available and retry agent initialization",severity:"critical",docs:`${DOC_BASE}#agent`,aws:"InternalFailure",grpc:13,http:500},REGISTRATION_FAILED:{message:"Agent registration with trust registry failed",hint:"Verify registry URL is reachable and auth token is valid and not expired. Check registry status page.",suggested_action:"Verify registry URL and auth token, then retry with exponential backoff",severity:"high",docs:`${DOC_BASE}#agent`,aws:"ServiceUnavailable",grpc:14,http:503},RECIPIENT_NOT_FOUND:{message:"Recipient agent not found in registry",hint:"Verify recipient email/DID is correct. Ask recipient to register with xBind first. Allow time for registration to propagate.",field:"to",suggested_action:"Ask recipient to register with xBind",severity:"medium",docs:`${DOC_BASE}#agent`,aws:"ResourceNotFoundException",grpc:5,http:404},RECIPIENT_REVOKED:{message:"Recipient agent has been revoked",hint:"Inform recipient to contact registry administrator to determine revocation reason and request re-registration if accidental.",field:"to",suggested_action:"Inform recipient to contact registry administrator",severity:"high",docs:`${DOC_BASE}#agent`,aws:"AccessDenied",grpc:7,http:403},KEY_AGREEMENT_FAILED:{message:"ECDH key agreement with recipient failed",hint:"Verify recipient public key is valid X25519 (32 bytes). Request fresh key from recipient.",suggested_action:"Request fresh key from recipient",severity:"high",docs:`${DOC_BASE}#agent`,aws:"InternalFailure",grpc:13,http:500},ENVELOPE_FAILED:{message:"Envelope creation failed",hint:"Verify payload < 10MB, recipient DID is valid, sender identity is set, and all required fields present.",suggested_action:"Verify payload size and recipient DID",severity:"high",docs:`${DOC_BASE}#agent`,aws:"InternalFailure",grpc:13,http:500},VERIFICATION_FAILED:{message:"Incoming envelope verification failed",hint:"Verify sender DID is in trust registry, sender signature is valid, and sender is not revoked. Review trust policy settings.",suggested_action:"Verify sender is in trust registry and not revoked",severity:"critical",docs:`${DOC_BASE}#agent`,aws:"UnauthorizedOperation",grpc:16,http:401},REPLAY_DETECTED:{message:"Duplicate nonce detected — possible replay attack",hint:"DISCARD MESSAGE immediately for security. Log nonce and sender DID. Alert user to potential attack.",suggested_action:"DISCARD MESSAGE and alert user to potential replay attack",severity:"critical",docs:`${DOC_BASE}#agent`,aws:"AccessDenied",grpc:7,http:403},SCOPE_DENIED:{message:"Sender does not have permission for the requested scope",hint:"Verify scope value is correct. Contact registry admin to grant sender permission for requested scope.",field:"scope",suggested_action:"Contact registry admin to grant permission",severity:"medium",docs:`${DOC_BASE}#agent`,aws:"AccessDenied",grpc:7,http:403},RECEIVER_SCOPE_DENIED:{message:"Recipient does not accept messages with this scope",hint:"Ask recipient to enable this scope in their settings. Verify scope matches recipient policy.",field:"scope",suggested_action:"Ask recipient to enable scope in settings",severity:"medium",docs:`${DOC_BASE}#agent`,aws:"AccessDenied",grpc:7,http:403},TIMESTAMP_EXPIRED:{message:"Envelope timestamp is outside the allowed window",hint:"Synchronize system clocks using NTP. Check time difference between sender and receiver.",suggested_action:"Synchronize system clocks using NTP",severity:"medium",docs:`${DOC_BASE}#agent`,aws:"RequestExpired",grpc:9,http:412},INCOMPATIBLE_VERSION:{message:"Client version is incompatible with server",hint:"Update xBind SDK to latest version. Check minimum supported version in documentation.",suggested_action:"Update xBind SDK to latest version",severity:"high",docs:`${DOC_BASE}#agent`,aws:"ValidationException",grpc:3,http:400},FEATURE_NOT_SUPPORTED:{message:"Requested feature is not supported",hint:"Verify SDK version supports this feature and it is available in current plan. Consider upgrading.",suggested_action:"Check feature availability in current plan or SDK version",severity:"medium",docs:`${DOC_BASE}#agent`,aws:"ValidationException",grpc:12,http:501},QUOTA_EXCEEDED:{message:"Operation quota exceeded",hint:"Check usage against plan limits. Implement rate limiting or upgrade to higher tier plan.",suggested_action:"Implement rate limiting or upgrade plan",severity:"medium",docs:`${DOC_BASE}#agent`,aws:"ThrottlingException",grpc:8,http:429},ACCOUNT_SUSPENDED:{message:"Account has been suspended",hint:"Contact support to determine suspension reason. Review terms of service and resolve any payment or policy issues.",suggested_action:"Contact support to resolve suspension",severity:"critical",docs:`${DOC_BASE}#agent`,aws:"AccessDeniedException",grpc:7,http:403},ACCOUNT_NOT_FOUND:{message:"Account does not exist",hint:"Verify account identifier is correct. Check if account was deleted. Create new account if needed.",suggested_action:"Verify account identifier or create new account",severity:"high",docs:`${DOC_BASE}#agent`,aws:"ResourceNotFoundException",grpc:5,http:404},BILLING_FAILURE:{message:"Billing operation failed",hint:"Verify payment method is valid and not expired. Check Stripe account status. Review billing logs.",suggested_action:"Verify payment method and check billing logs",severity:"high",docs:`${DOC_BASE}#billing`,aws:"RequestLimitExceeded",grpc:8,http:402},PAYMENT_REQUIRED:{message:"Payment required to access this resource",hint:"Add payment method in account settings and subscribe to appropriate tier.",suggested_action:"Add payment method and subscribe to access this resource",severity:"medium",docs:`${DOC_BASE}#billing`,aws:"AccessDenied",grpc:7,http:402},SUBSCRIPTION_REQUIRED:{message:"Valid subscription required",hint:"Subscribe to a paid tier in account settings. Verify subscription is active and not expired.",suggested_action:"Subscribe to a paid tier to access this feature",severity:"medium",docs:`${DOC_BASE}#billing`,aws:"AccessDenied",grpc:7,http:403},TIER_LIMIT_EXCEEDED:{message:"Current tier usage limit exceeded",hint:"Check current usage vs tier limits. Upgrade to higher tier for increased limits or wait for monthly reset.",suggested_action:"Upgrade to higher tier or wait for limit reset",severity:"medium",docs:`${DOC_BASE}#billing`,aws:"RequestLimitExceeded",grpc:8,http:403},VERIFICATION_REQUIRED:{message:"Account verification required",hint:"Complete email and payment method verification. Check account verification status in settings.",suggested_action:"Complete account verification steps in settings",severity:"high",docs:`${DOC_BASE}#billing`,aws:"AccessDenied",grpc:7,http:403},VAULT_FETCH_FAILED:{message:"Failed to fetch crypto package from Vault Store",hint:"Check network connectivity to private.me. Verify Vault Store endpoint is reachable. Try again in a few moments.",suggested_action:"Verify network connectivity and retry with exponential backoff",severity:"high",docs:`${DOC_BASE}#vault-store`,aws:"ServiceUnavailable",grpc:14,http:503},VAULT_AUTH_FAILED:{message:"Vault Store authentication failed",hint:"DID signature verification failed. Verify agent identity is valid and properly initialized. Check system clock is synchronized.",suggested_action:"Verify agent identity and synchronize system clock (NTP)",severity:"critical",docs:`${DOC_BASE}#vault-store`,aws:"UnauthorizedOperation",grpc:16,http:401},VAULT_QUOTA_EXCEEDED:{message:"Monthly usage quota exceeded",hint:"Free tier allows 100,000 operations per month (120,000 with grace buffer). Upgrade to Pro tier for unlimited access at $5 per 100K operations.",suggested_action:"Upgrade to Pro tier: https://private.me/subscribe?product=xbind&tier=pro",severity:"medium",docs:`${DOC_BASE}#vault-store`,aws:"RequestLimitExceeded",grpc:8,http:402},VAULT_PAYMENT_REQUIRED:{message:"Payment required to access Vault Store",hint:"Subscription expired or payment method failed. Update payment method and verify subscription is active.",suggested_action:"Update payment method and verify subscription status",severity:"high",docs:`${DOC_BASE}#vault-store`,aws:"AccessDenied",grpc:7,http:451},VAULT_LOAD_FAILED:{message:"Failed to load crypto package",hint:"Crypto bundle evaluation failed. This may indicate corrupted bundle or incompatible version. Contact support if issue persists.",suggested_action:"Clear cache and retry. Contact support if issue persists.",severity:"high",docs:`${DOC_BASE}#vault-store`,aws:"InternalFailure",grpc:13,http:500},VAULT_INVALID_RESPONSE:{message:"Invalid response from Vault Store",hint:"Server returned malformed data. This may indicate version mismatch or server issue. Try updating SDK or contact support.",suggested_action:"Update xBind SDK to latest version or contact support",severity:"high",docs:`${DOC_BASE}#vault-store`,aws:"InternalFailure",grpc:13,http:500}},ERROR_MESSAGES={KEYGEN_FAILED:[XBindIdentityError,"Key generation failed. Actions: (1) Verify Web Crypto API is available in HTTPS or localhost, (2) Check runtime is Node.js 15+ or modern browser, (3) Retry initialization."],SIGN_FAILED:[XBindIdentityError,"Signing failed. Actions: (1) Verify private key is valid and not corrupted, (2) Check key was properly imported, (3) Ensure key is extractable."],VERIFY_FAILED:[XBindIdentityError,"Signature verification failed. Actions: (1) Confirm public key matches signer, (2) Check message integrity, (3) Verify signature format is valid base64."],INVALID_DID:[XBindIdentityError,"The DID string is malformed. Actions: (1) Verify format: did:key:z6Mk..., (2) Check no extra whitespace, (3) Use validateDID() helper."],INVALID_KEY_LENGTH:[XBindKeyAgreementError,"Key material is the wrong length. Actions: (1) Verify X25519 key is exactly 32 bytes, (2) Check base64 decoding, (3) Log key.length to confirm."],EXPORT_FAILED:[XBindIdentityError,"PKCS8 export failed. Actions: (1) Create key with extractable:true, (2) Check Web Crypto support, (3) See: https://mdn.io/SubtleCrypto.exportKey."],IMPORT_FAILED:[XBindIdentityError,"PKCS8 import failed. Actions: (1) Validate PKCS8 format (PEM or bytes), (2) Decode base64 if needed, (3) Check algorithm (Ed25519/X25519)."],INVALID_VERSION:[XBindEnvelopeError,"Unsupported envelope version. Actions: (1) Check envelope.version field, (2) Verify sender uses v1-v4, (3) Request sender SDK update."],INVALID_ALG:[XBindEnvelopeError,'Unknown encryption algorithm. Actions: (1) Verify envelope.alg === "AES-256-GCM", (2) Log alg value to debug, (3) Check sender SDK version.'],INVALID_NONCE:[XBindEnvelopeError,"Nonce is missing or invalid. Actions: (1) Verify nonce exists and is 12 bytes, (2) Check base64 decoding, (3) Inspect replay buffer."],INVALID_FIELDS:[XBindEnvelopeError,"Required envelope fields are missing. Actions: (1) Verify sender/recipient DIDs, (2) Check payload exists, (3) Validate: version, alg, nonce, ciphertext, tag."],ENCRYPT_FAILED:[XBindEnvelopeError,"AES-256-GCM encryption failed. Actions: (1) Verify key is exactly 32 bytes, (2) Check plaintext is valid, (3) Ensure nonce is 12 bytes."],DECRYPT_FAILED:[XBindEnvelopeError,"Decryption failed. Actions: (1) Verify correct key is being used, (2) Check ciphertext integrity, (3) Confirm auth tag is valid."],PARSE_FAILED:[XBindEnvelopeError,"Envelope deserialization failed. Actions: (1) Validate JSON structure, (2) Check for truncation, (3) Verify base64 encoding of fields."],SEND_FAILED:[XBindTransportError,"Message send failed. Actions: (1) Check network connectivity (ping registry), (2) Verify recipient address, (3) Confirm recipient registered, (4) Retry with backoff."],NETWORK_ERROR:[XBindTransportError,"Network request failed. Actions: (1) Verify internet connection, (2) Check DNS resolution, (3) Ping registry endpoint, (4) Implement exponential backoff (2s, 4s, 8s)."],RECIPIENT_UNREACHABLE:[XBindTransportError,"Recipient is unreachable. Actions: (1) Verify recipient email is correct, (2) Check if recipient is registered, (3) Confirm recipient is online, (4) Provide human follow-up."],TIMEOUT:[XBindTransportError,"Transport operation timed out. Actions: (1) Increase timeout threshold, (2) Check network latency, (3) Verify registry responsiveness, (4) Retry operation."],NOT_FOUND:[XBindRegistryError,"Agent not found in trust registry. Actions: (1) Ask recipient to register with xBind, (2) Verify recipient email/DID, (3) Check registration status, (4) Retry after propagation."],ALREADY_REGISTERED:[XBindRegistryError,"Agent is already registered. Actions: (1) Use updateAgent() instead, (2) Provide new keys or metadata, (3) Verify DID matches existing entry."],REVOKED:[XBindRegistryError,"Agent has been revoked from the registry. Actions: (1) Contact registry admin, (2) Check revocation reason, (3) Request re-registration if accidental."],DERIVE_FAILED:[XBindKeyAgreementError,"ECDH key derivation failed. Actions: (1) Verify peer public key is valid X25519 (32 bytes), (2) Check key is not corrupted, (3) Confirm X25519 ECDH support."],KEM_ENCAPSULATE_FAILED:[XBindKeyAgreementError,"ML-KEM-768 encapsulation failed. Actions: (1) Verify recipient key is valid ML-KEM-768, (2) Check key format, (3) Confirm post-quantum support enabled."],KEM_DECAPSULATE_FAILED:[XBindKeyAgreementError,"ML-KEM-768 decapsulation failed. Actions: (1) Verify ciphertext integrity, (2) Check secret key is valid, (3) Confirm ciphertext matches key."],HKDF_FAILED:[XBindKeyAgreementError,"HKDF key derivation failed. Actions: (1) Verify both shared secrets are valid, (2) Check HKDF input size, (3) Ensure SHA-256 support."],MLKEM_NOT_AVAILABLE:[XBindKeyAgreementError,"ML-KEM-768 key not available. Actions: (1) Create agent with postQuantum: true, (2) Check runtime supports ML-KEM-768, (3) Regenerate identity with PQ enabled."],PQ_SIGN_FAILED:[XBindIdentityError,"ML-DSA-65 signing failed. Actions: (1) Verify secret key is valid, (2) Check post-quantum support enabled, (3) Ensure message is not empty."],PQ_VERIFY_FAILED:[XBindIdentityError,"ML-DSA-65 verification failed. Actions: (1) Verify public key matches signer, (2) Check signature format, (3) Confirm message integrity."],SPLIT_FAILED:[XBindSplitChannelError,"XorIDA split failed. Actions: (1) Verify threshold <= shareCount, (2) Check threshold >= 2, (3) Validate payload < 1MB."],INSUFFICIENT_SHARES:[XBindSplitChannelError,"Not enough shares to reconstruct. Actions: (1) Log number of shares collected, (2) Check threshold requirement, (3) Collect more shares."],INCONSISTENT_SHARES:[XBindSplitChannelError,"Shares have mismatched group IDs or lengths. Actions: (1) Verify all from same split, (2) Check group IDs match, (3) Discard mismatched shares."],HMAC_VERIFICATION_FAILED:[XBindSplitChannelError,"Share HMAC check failed. Actions: (1) Check share integrity in transit, (2) Verify not tampered with, (3) Request fresh share."],UNPAD_FAILED:[XBindSplitChannelError,"Padding removal failed after reconstruction. Actions: (1) Verify reconstruction succeeded, (2) Check data is valid UTF-8, (3) Inspect raw bytes."],INVALID_SHARE_DATA:[XBindSplitChannelError,"Share data is malformed. Actions: (1) Verify share is valid base64, (2) Check TLV structure, (3) Log raw bytes to inspect."],XCHANGE_KEYGEN_FAILED:[XBindKeyAgreementError,"Xchange key generation failed. Actions: (1) Verify Web Crypto available (HTTPS/localhost), (2) Check runtime support, (3) Ensure entropy."],XCHANGE_ENCRYPT_FAILED:[XBindEnvelopeError,"Xchange bundle encryption failed. Actions: (1) Check payload < 64KB, (2) Verify key is 32 bytes, (3) Validate bundle structure."],XCHANGE_DECRYPT_FAILED:[XBindEnvelopeError,"Xchange bundle decryption failed. Actions: (1) Verify reconstruction succeeded, (2) Check key matches encryption key, (3) Confirm bundle integrity."],INVALID_BUNDLE:[XBindSplitChannelError,"Xchange bundle is malformed. Actions: (1) Verify size >= 60 bytes (32B + 12B + 16B), (2) Check structure, (3) Decode to inspect."],IDENTITY_FAILED:[XBindAgentError,"Agent identity creation failed. Actions: (1) Verify Web Crypto available, (2) Check HTTPS/localhost, (3) Ensure Node.js 15+ or modern browser."],REGISTRATION_FAILED:[XBindAgentError,"Agent registration with trust registry failed. Actions: (1) Verify registry URL is correct, (2) Check auth token valid/not expired, (3) Confirm registry online."],RECIPIENT_NOT_FOUND:[XBindAgentError,"Recipient agent not found in registry. Actions: (1) Verify recipient email/DID, (2) Ask recipient to register first, (3) Wait for propagation."],RECIPIENT_REVOKED:[XBindAgentError,"Recipient agent has been revoked. Actions: (1) Inform recipient to contact admin, (2) Verify revocation reason, (3) Request re-registration."],KEY_AGREEMENT_FAILED:[XBindAgentError,"ECDH key agreement with recipient failed. Actions: (1) Verify recipient key valid, (2) Check key format (X25519, 32B), (3) Request fresh key."],ENVELOPE_FAILED:[XBindAgentError,"Envelope creation failed. Actions: (1) Check payload < 10MB, (2) Verify recipient DID valid, (3) Confirm sender identity set."],VERIFICATION_FAILED:[XBindAgentError,"Incoming envelope verification failed. Actions: (1) Check sender in registry, (2) Verify signature valid, (3) Confirm sender not revoked."],REPLAY_DETECTED:[XBindAgentError,"Duplicate nonce detected — possible replay attack. Actions: (1) DISCARD message, (2) Log nonce/sender, (3) Alert user to potential attack."],SCOPE_DENIED:[XBindAgentError,"Sender does not have permission for the requested scope. Actions: (1) Check sender scope in registry, (2) Contact admin to grant, (3) Verify scope value."],RECEIVER_SCOPE_DENIED:[XBindAgentError,"Recipient does not accept messages with this scope. Actions: (1) Check recipient receive scope settings, (2) Ask to enable scope, (3) Verify registry entry."],TIMESTAMP_EXPIRED:[XBindAgentError,"Envelope timestamp is outside the allowed window. Actions: (1) Synchronize system clocks (NTP), (2) Check time difference, (3) Verify no time drift."],INCOMPATIBLE_VERSION:[XBindAgentError,"Client version is incompatible with server. Actions: (1) Update xBind SDK to latest version, (2) Check minimum supported version, (3) Contact support if upgrade not possible."],FEATURE_NOT_SUPPORTED:[XBindAgentError,"Requested feature is not supported. Actions: (1) Check feature availability in plan, (2) Verify SDK version, (3) Consider upgrading plan."],QUOTA_EXCEEDED:[QuotaExceededError,"Operation quota exceeded. Actions: (1) Check usage against plan limits, (2) Implement rate limiting, (3) Upgrade plan, (4) Wait for quota reset."],ACCOUNT_SUSPENDED:[XBindAgentError,"Account has been suspended. Actions: (1) Contact support for suspension reason, (2) Review terms compliance, (3) Resolve payment/policy issues."],ACCOUNT_NOT_FOUND:[XBindAgentError,"Account does not exist. Actions: (1) Verify account identifier, (2) Check if account was deleted, (3) Create new account if needed."],BILLING_FAILURE:[XBindBillingError,"Billing operation failed. Actions: (1) Verify payment method is valid and not expired, (2) Check Stripe account status, (3) Review billing logs, (4) Contact support if issue persists."],PAYMENT_REQUIRED:[XBindBillingError,"Payment required to access this resource. Actions: (1) Add payment method in account settings, (2) Subscribe to appropriate tier, (3) Verify billing information is current."],SUBSCRIPTION_REQUIRED:[XBindBillingError,"Valid subscription required. Actions: (1) Subscribe to a paid tier in account settings, (2) Verify subscription is active and not expired, (3) Check billing status."],TIER_LIMIT_EXCEEDED:[XBindBillingError,"Current tier usage limit exceeded. Actions: (1) Upgrade to higher tier for increased limits, (2) Check current usage vs tier limits, (3) Wait for limit reset (typically monthly)."],VERIFICATION_REQUIRED:[XBindBillingError,"Account verification required. Actions: (1) Complete email verification, (2) Verify payment method, (3) Complete identity verification if required, (4) Check account verification status in settings."],VAULT_FETCH_FAILED:[VaultStoreError,"Failed to fetch crypto package from Vault Store. Actions: (1) Check network connectivity to private.me, (2) Verify Vault Store endpoint is reachable, (3) Retry with exponential backoff, (4) Check server status page."],VAULT_AUTH_FAILED:[VaultStoreError,"Vault Store authentication failed. Actions: (1) Verify agent identity is valid, (2) Check DID signature is correct, (3) Synchronize system clock (NTP), (4) Regenerate identity if corrupted."],VAULT_QUOTA_EXCEEDED:[QuotaExceededError,"Monthly usage quota exceeded. Free tier: 100K operations/month (120K with grace). Actions: (1) Upgrade to Pro tier for unlimited access ($5/100K ops), (2) Visit https://private.me/subscribe?product=xbind&tier=pro, (3) Wait for monthly reset (1st of month, 00:00 UTC)."],VAULT_PAYMENT_REQUIRED:[VaultStoreError,"Payment required to access Vault Store. Actions: (1) Update payment method in account settings, (2) Verify subscription is active, (3) Check billing status, (4) Contact support if payment issue persists."],VAULT_LOAD_FAILED:[VaultStoreError,"Failed to load crypto package. Actions: (1) Clear crypto cache and retry, (2) Verify SDK version is compatible, (3) Check bundle integrity, (4) Contact support if issue persists."],VAULT_INVALID_RESPONSE:[VaultStoreError,"Invalid response from Vault Store. Actions: (1) Update xBind SDK to latest version, (2) Check API compatibility, (3) Retry request, (4) Contact support if issue persists."]};function toXBindError(e){const t=e.split(":")[0]??e,i=ERROR_MESSAGES[t];if(i){const[t,r]=i;return new t(e,r)}return new XBindError(e,`XBind error: ${e}`)}function isXBindError(e){return e instanceof XBindError}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createAxiosCompat=createAxiosCompat,exports.createGotCompat=createGotCompat,exports.wrapFetch=wrapFetch;const xfetch_js_1=require("./xfetch.js");function createAxiosCompat(){async function t(t){const e="string"==typeof t?{url:t}:t,a=e.method?.toUpperCase()??"GET",r=e.baseURL?new URL(e.url??"",e.baseURL).toString():e.url??"",o={...e.headers};let s,n=r;if(e.params){const t=new URLSearchParams;for(const[a,r]of Object.entries(e.params))t.append(a,String(r));n=`${r}?${t.toString()}`}e.data&&("string"==typeof e.data?s=e.data:(s=JSON.stringify(e.data),o["Content-Type"]="application/json"));const c={method:a,headers:o,body:s,timeout:e.timeout,forceXBind:e.forceXBind,disableXBind:e.disableXBind},i=await(0,xfetch_js_1.xfetch)(n,c);let u;switch(e.responseType??"json"){case"json":default:u=await i.json();break;case"text":u=await i.text();break;case"blob":u=await i.blob();break;case"arraybuffer":u=await i.arrayBuffer()}if(e.validateStatus&&!e.validateStatus(i.status))throw new Error(`Request failed with status ${i.status}`);const d={};return i.headers.forEach((t,e)=>{d[e]=t}),{data:u,status:i.status,statusText:i.statusText,headers:d,config:e,xbind:{used:i.usedXBind,protocol:i.transport.protocol,latency:i.transport.latency,peerDID:i.transport.peerDID}}}return{request:t,get:async function(e,a){return t({...a,url:e,method:"GET"})},post:async function(e,a,r){return t({...r,url:e,method:"POST",data:a})},put:async function(e,a,r){return t({...r,url:e,method:"PUT",data:a})},patch:async function(e,a,r){return t({...r,url:e,method:"PATCH",data:a})},delete:async function(e,a){return t({...a,url:e,method:"DELETE"})}}}function createGotCompat(){async function t(t,e){const a="string"==typeof t?{...e,url:t}:t,r=a.method?.toUpperCase()??"GET",o=a.url??"",s={...a.headers};let n,c=o;if(a.searchParams){const t=new URLSearchParams;for(const[e,r]of Object.entries(a.searchParams))t.append(e,String(r));c=`${o}?${t.toString()}`}a.json?(n=JSON.stringify(a.json),s["Content-Type"]="application/json"):a.body&&(n=a.body instanceof Buffer?a.body.toString():a.body);const i={method:r,headers:s,body:n,timeout:"number"==typeof a.timeout?a.timeout:a.timeout?.request,forceXBind:a.forceXBind,disableXBind:a.disableXBind},u=await(0,xfetch_js_1.xfetch)(c,i);let d;switch(a.responseType??"text"){case"json":d=await u.json();break;case"text":default:d=await u.text();break;case"buffer":const t=await u.arrayBuffer();d=Buffer.from(t)}const p={};return u.headers.forEach((t,e)=>{p[e]=t}),{body:d,statusCode:u.status,headers:p,url:u.url,requestUrl:c,xbind:{used:u.usedXBind,protocol:u.transport.protocol,latency:u.transport.latency,peerDID:u.transport.peerDID}}}return t.get=(e,a)=>t(e,{...a,method:"GET"}),t.post=(e,a)=>t(e,{...a,method:"POST"}),t.put=(e,a)=>t(e,{...a,method:"PUT"}),t.patch=(e,a)=>t(e,{...a,method:"PATCH"}),t.delete=(e,a)=>t(e,{...a,method:"DELETE"}),t}function wrapFetch(){return xfetch_js_1.xfetch}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createAxiosCompat=createAxiosCompat,exports.createGotCompat=createGotCompat,exports.wrapFetch=wrapFetch;const xfetch_js_1=require("./xfetch.js");function createAxiosCompat(){async function t(t){const e="string"==typeof t?{url:t}:t,a=e.method?.toUpperCase()??"GET",r=e.baseURL?new URL(e.url??"",e.baseURL).toString():e.url??"",o={...e.headers};let s,n=r;if(e.params){const t=new URLSearchParams;for(const[a,r]of Object.entries(e.params))t.append(a,String(r));n=`${r}?${t.toString()}`}e.data&&("string"==typeof e.data?s=e.data:(s=JSON.stringify(e.data),o["Content-Type"]="application/json"));const c={method:a,headers:o,body:s,timeout:e.timeout,forceXBind:e.forceXBind,disableXBind:e.disableXBind},i=await(0,xfetch_js_1.xfetch)(n,c);let u;switch(e.responseType??"json"){case"json":default:u=await i.json();break;case"text":u=await i.text();break;case"blob":u=await i.blob();break;case"arraybuffer":u=await i.arrayBuffer()}if(e.validateStatus&&!e.validateStatus(i.status))throw new Error(`Request failed with status ${i.status}`);const d={};return i.headers.forEach((t,e)=>{d[e]=t}),{data:u,status:i.status,statusText:i.statusText,headers:d,config:e,xbind:{used:i.usedXBind,protocol:i.transport.protocol,latency:i.transport.latency,peerDID:i.transport.peerDID}}}return{request:t,get:async function(e,a){return t({...a,url:e,method:"GET"})},post:async function(e,a,r){return t({...r,url:e,method:"POST",data:a})},put:async function(e,a,r){return t({...r,url:e,method:"PUT",data:a})},patch:async function(e,a,r){return t({...r,url:e,method:"PATCH",data:a})},delete:async function(e,a){return t({...a,url:e,method:"DELETE"})}}}function createGotCompat(){async function t(t,e){const a="string"==typeof t?{...e,url:t}:t,r=a.method?.toUpperCase()??"GET",o=a.url??"",s={...a.headers};let n,c=o;if(a.searchParams){const t=new URLSearchParams;for(const[e,r]of Object.entries(a.searchParams))t.append(e,String(r));c=`${o}?${t.toString()}`}a.json?(n=JSON.stringify(a.json),s["Content-Type"]="application/json"):a.body&&(n=a.body instanceof Buffer?a.body.toString():a.body);const i={method:r,headers:s,body:n,timeout:"number"==typeof a.timeout?a.timeout:a.timeout?.request,forceXBind:a.forceXBind,disableXBind:a.disableXBind},u=await(0,xfetch_js_1.xfetch)(c,i);let d;switch(a.responseType??"text"){case"json":d=await u.json();break;case"text":default:d=await u.text();break;case"buffer":{const t=await u.arrayBuffer();d=Buffer.from(t);break}}const p={};return u.headers.forEach((t,e)=>{p[e]=t}),{body:d,statusCode:u.status,headers:p,url:u.url,requestUrl:c,xbind:{used:u.usedXBind,protocol:u.transport.protocol,latency:u.transport.latency,peerDID:u.transport.peerDID}}}return t.get=(e,a)=>t(e,{...a,method:"GET"}),t.post=(e,a)=>t(e,{...a,method:"POST"}),t.put=(e,a)=>t(e,{...a,method:"PUT"}),t.patch=(e,a)=>t(e,{...a,method:"PATCH"}),t.delete=(e,a)=>t(e,{...a,method:"DELETE"}),t}function wrapFetch(){return xfetch_js_1.xfetch}