@oneaddress/partner-sdk 2.0.0 → 2.1.0

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.
package/dist/edge.js CHANGED
@@ -3684,6 +3684,301 @@ var init_registry_head = __esm({
3684
3684
  }
3685
3685
  });
3686
3686
 
3687
+ // ../crypto/src/verify-partner-keys.ts
3688
+ async function saysRootNotConfigured(res) {
3689
+ if (res.status !== 503) return false;
3690
+ try {
3691
+ const body = await res.json();
3692
+ return typeof body.error === "string" && body.error.includes("root not configured");
3693
+ } catch {
3694
+ return false;
3695
+ }
3696
+ }
3697
+ async function outcomeFor(partnerId, key, reg, bound) {
3698
+ if (!reg.head) return "head-unusable";
3699
+ if (!key.key_signature || !key.root_key_id) {
3700
+ if (!key.countersignature_exempt) return "unsigned";
3701
+ if (headNamesPartner(reg.head, partnerId)) return "exempt-in-head";
3702
+ return bound.has(partnerId) ? "exempt" : "exempt-unbound";
3703
+ }
3704
+ const attested = await verifyPartnerKeyAttestationWithRoots(
3705
+ {
3706
+ partnerId,
3707
+ keyId: key.key_id,
3708
+ algorithm: key.algorithm,
3709
+ publicKeyB64: key.public_key_b64
3710
+ },
3711
+ key.key_signature,
3712
+ key.root_key_id,
3713
+ reg.roots
3714
+ );
3715
+ if (!attested) return "bad-attestation";
3716
+ return headNamesKey(reg.head, partnerId, key.key_id) ? "ok" : "not-in-head";
3717
+ }
3718
+ async function crossoverOutcomeFor(partnerId, crossover, reg) {
3719
+ if (!reg.head) return "head-unusable";
3720
+ return await headNamesStagedKey(reg.head, partnerId, crossover.key_id, crossover.public_key_b64) ? "ok" : "not-authorised";
3721
+ }
3722
+ function createPartnerKeyVerifier(env = {}) {
3723
+ const baseUrl = env.baseUrl ?? "";
3724
+ const report = env.report ?? (() => {
3725
+ });
3726
+ let registryPromise = null;
3727
+ function worthCaching(load) {
3728
+ return load.ok && load.registry.head !== null;
3729
+ }
3730
+ async function loadRegistry() {
3731
+ try {
3732
+ const [rootsRes, headRes] = await Promise.all([
3733
+ fetch(baseUrl + "/.well-known/oneaddress-key-registry.json", { cache: "no-cache" }),
3734
+ fetch(baseUrl + "/.well-known/oneaddress-key-registry-head.json", { cache: "no-cache" })
3735
+ ]);
3736
+ if (!rootsRes.ok) {
3737
+ const configured = await saysRootNotConfigured(rootsRes);
3738
+ return {
3739
+ ok: false,
3740
+ failure: {
3741
+ reason: configured ? "roots-not-configured" : "roots-http",
3742
+ status: rootsRes.status
3743
+ }
3744
+ };
3745
+ }
3746
+ let roots;
3747
+ try {
3748
+ const rootsBody = await rootsRes.json();
3749
+ roots = rootsBody.keys ?? [];
3750
+ } catch {
3751
+ return { ok: false, failure: { reason: "roots-unreadable", status: rootsRes.status } };
3752
+ }
3753
+ if (roots.length === 0) {
3754
+ return { ok: false, failure: { reason: "roots-empty", status: rootsRes.status } };
3755
+ }
3756
+ let head = null;
3757
+ let headVerdict = "absent";
3758
+ if (headRes.ok) {
3759
+ head = await headRes.json();
3760
+ headVerdict = await verifyRegistryHead(head, roots);
3761
+ if (headVerdict !== "ok" && headVerdict !== "expired") head = null;
3762
+ }
3763
+ return { ok: true, registry: { roots, head, headVerdict } };
3764
+ } catch {
3765
+ return { ok: false, failure: { reason: "fetch-failed" } };
3766
+ }
3767
+ }
3768
+ async function verifyActivePartnerKeys(keys, context) {
3769
+ try {
3770
+ const pending = registryPromise ?? (registryPromise = loadRegistry());
3771
+ const load = await pending;
3772
+ if (!worthCaching(load)) registryPromise = null;
3773
+ if (!load.ok) {
3774
+ report(context, { registry: "unavailable", enforced: false, ...load.failure });
3775
+ return { blocked: {}, crossoverBlocked: {} };
3776
+ }
3777
+ const reg = load.registry;
3778
+ let bound = EMPTY_BOUND;
3779
+ if (env.bindSenderHeldKeys) {
3780
+ try {
3781
+ bound = await env.bindSenderHeldKeys(keys);
3782
+ } catch {
3783
+ report(context, { binder: "threw", enforced: true });
3784
+ }
3785
+ }
3786
+ const tally = {
3787
+ "ok": [],
3788
+ "exempt": [],
3789
+ "exempt-in-head": [],
3790
+ "exempt-unbound": [],
3791
+ "unsigned": [],
3792
+ "bad-attestation": [],
3793
+ "not-in-head": [],
3794
+ "head-unusable": [],
3795
+ "error": []
3796
+ };
3797
+ const blocked = {};
3798
+ const crossoverBlocked = {};
3799
+ const crossoverTally = { "ok": [], "not-authorised": [], "head-unusable": [], "error": [] };
3800
+ for (const [partnerId, key] of Object.entries(keys)) {
3801
+ let outcome;
3802
+ try {
3803
+ outcome = await outcomeFor(partnerId, key, reg, bound);
3804
+ } catch {
3805
+ outcome = "error";
3806
+ }
3807
+ tally[outcome].push(partnerId);
3808
+ if (!ACCEPTABLE.has(outcome)) blocked[partnerId] = outcome;
3809
+ if (!key?.crossover) continue;
3810
+ let xo;
3811
+ try {
3812
+ xo = await crossoverOutcomeFor(partnerId, key.crossover, reg);
3813
+ } catch {
3814
+ xo = "error";
3815
+ }
3816
+ crossoverTally[xo].push(partnerId);
3817
+ if (xo !== "ok") crossoverBlocked[partnerId] = xo;
3818
+ }
3819
+ if (Object.keys(crossoverBlocked).length > 0) {
3820
+ const failedXo = Object.keys(crossoverTally).filter((o) => o !== "ok" && crossoverTally[o].length > 0);
3821
+ report(context, {
3822
+ headVerdict: reg.headVerdict,
3823
+ enforced: true,
3824
+ surface: "crossover",
3825
+ ...Object.fromEntries(failedXo.map((o) => [`crossover-${o}`, crossoverTally[o]]))
3826
+ });
3827
+ }
3828
+ if (Object.keys(blocked).length > 0) {
3829
+ const failed = Object.keys(tally).filter((o) => !ACCEPTABLE.has(o) && tally[o].length > 0);
3830
+ report(context, {
3831
+ headVerdict: reg.headVerdict,
3832
+ enforced: true,
3833
+ total: Object.keys(keys).length,
3834
+ ok: tally.ok.length,
3835
+ // Counted, not listed: an operator reading a real finding needs to know
3836
+ // how many keys were skipped as exempt, without the ids adding noise.
3837
+ exempt: tally.exempt.length,
3838
+ ...Object.fromEntries(failed.map((o) => [o, tally[o]]))
3839
+ });
3840
+ }
3841
+ return { blocked, crossoverBlocked };
3842
+ } catch {
3843
+ report(context, { registry: "verifier-error", enforced: false });
3844
+ return { blocked: {}, crossoverBlocked: {} };
3845
+ }
3846
+ }
3847
+ function __resetRegistryCacheForTests() {
3848
+ registryPromise = null;
3849
+ }
3850
+ return { verifyActivePartnerKeys, __resetRegistryCacheForTests };
3851
+ }
3852
+ var ACCEPTABLE, EMPTY_BOUND, PARTNER_KEY_REFUSED_MESSAGE;
3853
+ var init_verify_partner_keys = __esm({
3854
+ "../crypto/src/verify-partner-keys.ts"() {
3855
+ "use strict";
3856
+ init_partner_key_attestation();
3857
+ init_registry_head();
3858
+ ACCEPTABLE = /* @__PURE__ */ new Set(["ok", "exempt"]);
3859
+ EMPTY_BOUND = /* @__PURE__ */ new Set();
3860
+ PARTNER_KEY_REFUSED_MESSAGE = "Some services are temporarily unavailable and were not updated. Please try again in a moment.";
3861
+ }
3862
+ });
3863
+
3864
+ // ../crypto/src/sender-held-keys.ts
3865
+ function memorySenderHeldKeyStore() {
3866
+ const keys = /* @__PURE__ */ new Map();
3867
+ return {
3868
+ all: async () => [...keys.values()],
3869
+ put: async (key) => {
3870
+ keys.set(key.keyId, key);
3871
+ }
3872
+ };
3873
+ }
3874
+ function toB64(bytes) {
3875
+ let s = "";
3876
+ for (const b of bytes) s += String.fromCharCode(b);
3877
+ return btoa(s);
3878
+ }
3879
+ async function keyIdForPublicKey(spki) {
3880
+ const d = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", spki)).slice(0, 16);
3881
+ d[6] = d[6] & 15 | 128;
3882
+ d[8] = d[8] & 63 | 128;
3883
+ const h = [...d].map((b) => b.toString(16).padStart(2, "0")).join("");
3884
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
3885
+ }
3886
+ function createSenderHeldKeyBinder(storeFor) {
3887
+ let pending = null;
3888
+ async function mint() {
3889
+ if (typeof globalThis.crypto === "undefined" || !globalThis.crypto.subtle) return null;
3890
+ let store = storeFor();
3891
+ try {
3892
+ const existing = await store.all();
3893
+ if (existing.length > 0) {
3894
+ return [...existing].sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0];
3895
+ }
3896
+ } catch {
3897
+ store = memorySenderHeldKeyStore();
3898
+ }
3899
+ const pair = await globalThis.crypto.subtle.generateKey(
3900
+ { name: "ECDH", namedCurve: "P-256" },
3901
+ false,
3902
+ ["deriveBits"]
3903
+ );
3904
+ const spki = new Uint8Array(await globalThis.crypto.subtle.exportKey("spki", pair.publicKey));
3905
+ const key = {
3906
+ keyId: await keyIdForPublicKey(spki),
3907
+ publicKeyB64: toB64(spki),
3908
+ privateKey: pair.privateKey,
3909
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
3910
+ };
3911
+ try {
3912
+ await store.put(key);
3913
+ } catch {
3914
+ }
3915
+ return key;
3916
+ }
3917
+ function getOrCreate() {
3918
+ pending ??= mint().catch(() => {
3919
+ pending = null;
3920
+ return null;
3921
+ });
3922
+ return pending;
3923
+ }
3924
+ const bind = async (keys) => {
3925
+ const bound = /* @__PURE__ */ new Set();
3926
+ const flagged = Object.entries(keys).filter(([, k]) => k?.countersignature_exempt === true);
3927
+ if (flagged.length === 0) return bound;
3928
+ const own = await getOrCreate();
3929
+ if (!own) return bound;
3930
+ for (const [partnerId, k] of flagged) {
3931
+ k.key_id = own.keyId;
3932
+ k.public_key_b64 = own.publicKeyB64;
3933
+ k.algorithm = SENDER_HELD_KEY_ALGORITHM;
3934
+ k.key_signature = null;
3935
+ k.root_key_id = null;
3936
+ delete k.crossover;
3937
+ bound.add(partnerId);
3938
+ }
3939
+ return bound;
3940
+ };
3941
+ return Object.assign(bind, { getOrCreate });
3942
+ }
3943
+ async function openSealedWithSenderHeldKey(share, envelope, partnerId, store) {
3944
+ let keys;
3945
+ try {
3946
+ keys = await store.all();
3947
+ } catch {
3948
+ return { ok: false, reason: "no-key" };
3949
+ }
3950
+ const key = keys.find((k) => k.keyId === share.key_id);
3951
+ if (!key) return { ok: false, reason: "no-key" };
3952
+ try {
3953
+ const data = await decryptSession(share, envelope, {
3954
+ name: "this device",
3955
+ async deriveSharedSecret(epkSpki) {
3956
+ const epk = await globalThis.crypto.subtle.importKey(
3957
+ "spki",
3958
+ epkSpki,
3959
+ { name: "ECDH", namedCurve: "P-256" },
3960
+ false,
3961
+ []
3962
+ );
3963
+ return new Uint8Array(
3964
+ await globalThis.crypto.subtle.deriveBits({ name: "ECDH", public: epk }, key.privateKey, 256)
3965
+ );
3966
+ }
3967
+ }, partnerId);
3968
+ return { ok: true, data };
3969
+ } catch {
3970
+ return { ok: false, reason: "unreadable" };
3971
+ }
3972
+ }
3973
+ var SENDER_HELD_KEY_ALGORITHM;
3974
+ var init_sender_held_keys = __esm({
3975
+ "../crypto/src/sender-held-keys.ts"() {
3976
+ "use strict";
3977
+ init_src();
3978
+ SENDER_HELD_KEY_ALGORITHM = "ECDH-P256-AES-GCM-256";
3979
+ }
3980
+ });
3981
+
3687
3982
  // ../crypto/src/index.ts
3688
3983
  var src_exports = {};
3689
3984
  __export(src_exports, {
@@ -3691,9 +3986,11 @@ __export(src_exports, {
3691
3986
  ENDPOINT_FAILURE_THRESHOLD: () => ENDPOINT_FAILURE_THRESHOLD,
3692
3987
  PARTNER_KEY_ATTESTATION_ALG: () => PARTNER_KEY_ATTESTATION_ALG,
3693
3988
  PARTNER_KEY_ATTESTATION_V1: () => PARTNER_KEY_ATTESTATION_V1,
3989
+ PARTNER_KEY_REFUSED_MESSAGE: () => PARTNER_KEY_REFUSED_MESSAGE,
3694
3990
  REGISTRY_HEAD_ALG: () => REGISTRY_HEAD_ALG,
3695
3991
  REGISTRY_HEAD_V1: () => REGISTRY_HEAD_V1,
3696
3992
  REGISTRY_HEAD_V2: () => REGISTRY_HEAD_V2,
3993
+ SENDER_HELD_KEY_ALGORITHM: () => SENDER_HELD_KEY_ALGORITHM,
3697
3994
  buildPartnerKeyAttestation: () => buildPartnerKeyAttestation,
3698
3995
  buildRegistryHeadStatement: () => buildRegistryHeadStatement,
3699
3996
  classifyEndpointProbe: () => classifyEndpointProbe,
@@ -3701,6 +3998,8 @@ __export(src_exports, {
3701
3998
  computeBlindIndex: () => computeBlindIndex,
3702
3999
  computeCustomerBlindIndex: () => computeCustomerBlindIndex,
3703
4000
  countsAsFailure: () => countsAsFailure,
4001
+ createPartnerKeyVerifier: () => createPartnerKeyVerifier,
4002
+ createSenderHeldKeyBinder: () => createSenderHeldKeyBinder,
3704
4003
  decryptAddress: () => decryptAddress,
3705
4004
  decryptSession: () => decryptSession,
3706
4005
  encryptAddressForAll: () => encryptAddressForAll,
@@ -3718,8 +4017,11 @@ __export(src_exports, {
3718
4017
  isFreshTimestamp: () => isFreshTimestamp,
3719
4018
  isIpLiteralHost: () => isIpLiteralHost,
3720
4019
  isSafeWebhookUrl: () => isSafeWebhookUrl,
4020
+ keyIdForPublicKey: () => keyIdForPublicKey,
4021
+ memorySenderHeldKeyStore: () => memorySenderHeldKeyStore,
3721
4022
  normaliseAddress: () => normaliseAddress,
3722
4023
  normalizeForBlindIndex: () => normalizeForBlindIndex,
4024
+ openSealedWithSenderHeldKey: () => openSealedWithSenderHeldKey,
3723
4025
  partnerKeyFingerprint: () => partnerKeyFingerprint,
3724
4026
  rootKeyIdFromSpki: () => rootKeyIdFromSpki,
3725
4027
  rootKeyIdFromSpkiB64: () => rootKeyIdFromSpkiB64,
@@ -4118,12 +4420,7 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId, expe
4118
4420
  }
4119
4421
  const ops = typeof privateKeyB64 === "string" ? null : privateKeyB64;
4120
4422
  if (ops) {
4121
- if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
4122
- throw new Error(
4123
- `decryptSession: key source "${ops.name}" performs private-key operations without releasing the key, which no KMS offers for ML-KEM. Use an exportable key source for post-quantum shares.`
4124
- );
4125
- }
4126
- const needed = share.alg === "RSA-OAEP-256+A256GCM" ? "decryptRsaOaep" : "deriveSharedSecret";
4423
+ const needed = share.alg === "RSA-OAEP-256+A256GCM" ? "decryptRsaOaep" : share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM" ? "decapsulateXWing" : "deriveSharedSecret";
4127
4424
  if (typeof ops[needed] !== "function") {
4128
4425
  throw new Error(
4129
4426
  `decryptSession: key source "${ops.name}" cannot do ${needed}, which ${share.alg} requires.`
@@ -4135,7 +4432,13 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId, expe
4135
4432
  if (!share.epk) {
4136
4433
  throw new Error("decryptSession: hybrid share missing epk (KEM ciphertext)");
4137
4434
  }
4138
- const sharedSecret = XWing.decapsulate(b64UrlToBytes(share.epk), b64ToBytes3(privateKeyB64));
4435
+ const kemCiphertext = b64UrlToBytes(share.epk);
4436
+ const sharedSecret = ops ? toArrayBuffer(await ops.decapsulateXWing(kemCiphertext)) : toArrayBuffer(XWing.decapsulate(kemCiphertext, b64ToBytes3(privateKeyB64)));
4437
+ if (ops && sharedSecret.byteLength !== 32) {
4438
+ throw new Error(
4439
+ `decryptSession: key source "${ops.name}" returned a ${sharedSecret.byteLength}-byte shared secret; X-Wing decapsulation is 32 bytes with no KDF applied.`
4440
+ );
4441
+ }
4139
4442
  const wrappedBytes = b64UrlToBytes(share.wrapped_key);
4140
4443
  if (wrappedBytes.length < WRAP_SALT_LENGTH + WRAP_IV_LENGTH + 16) {
4141
4444
  throw new Error("decryptSession: wrapped_key too short");
@@ -4353,6 +4656,8 @@ var init_src = __esm({
4353
4656
  init_endpoint_health();
4354
4657
  init_partner_key_attestation();
4355
4658
  init_registry_head();
4659
+ init_verify_partner_keys();
4660
+ init_sender_held_keys();
4356
4661
  subtle = () => {
4357
4662
  const webcrypto = globalThis.crypto;
4358
4663
  if (!webcrypto?.subtle) {
@@ -4427,6 +4732,45 @@ init_src();
4427
4732
  var CURRENT_VERSION = "2026.1";
4428
4733
  var SUPPORTED_VERSIONS = ["2026.1"];
4429
4734
 
4735
+ // ../protocol/src/d5-body.ts
4736
+ var D5_BODY_ALWAYS = [
4737
+ "event",
4738
+ "id_verification",
4739
+ "key_share_expiry",
4740
+ "oneaddress_version",
4741
+ "partner_id",
4742
+ "session_envelope",
4743
+ "session_key_share",
4744
+ "stripe_session_id",
4745
+ "timestamp",
4746
+ "update_id",
4747
+ "user_id"
4748
+ ];
4749
+ var D5_BODY_CONDITIONAL = {
4750
+ /**
4751
+ * The signed Letter of Authority, sealed to the same key_id as the session.
4752
+ * Present whenever the partner has a usable key — i.e. on every dispatch a
4753
+ * live partner receives. Omitted best-effort when no key is available, which
4754
+ * is a state a live partner is never in.
4755
+ */
4756
+ loa_encrypted: "partner has a usable encryption key",
4757
+ /**
4758
+ * The shared webhook event id. Set ONLY on a key-crossover copy, where every
4759
+ * copy of one update carries the same id so a receiver holding more than one
4760
+ * rotation key applies it once. Absent on an ordinary dispatch, whose
4761
+ * receiver idempotency falls back to the `X-OneAddress-Dispatch` header.
4762
+ */
4763
+ id: "key-crossover copy only",
4764
+ /** The sibling marker naming the other key_ids this update was sealed to. */
4765
+ crossover_key_ids: "key-crossover copy only"
4766
+ };
4767
+ var D5_BODY_DRILL_ONLY = ["conformance"];
4768
+ var D5_BODY_ALL_ALLOWED = [
4769
+ ...D5_BODY_ALWAYS,
4770
+ ...Object.keys(D5_BODY_CONDITIONAL),
4771
+ ...D5_BODY_DRILL_ONLY
4772
+ ];
4773
+
4430
4774
  // src/index.ts
4431
4775
  init_src();
4432
4776
  init_src();
@@ -4499,7 +4843,8 @@ function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousS
4499
4843
  function base64urlToBuffer(b64) {
4500
4844
  return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
4501
4845
  }
4502
- function pemToBase64(pem) {
4846
+ function pemToBase64(pemRaw) {
4847
+ const pem = pemRaw.replace(/(?:\\r)?\\n/g, "\n");
4503
4848
  const begin = pem.indexOf("-----BEGIN");
4504
4849
  if (begin === -1) return pem.replace(/\s/g, "");
4505
4850
  const armourEnd = pem.indexOf("-----", begin + "-----BEGIN".length);
@@ -4628,6 +4973,65 @@ async function transformSession(share, envelopeB64, privateKeyPem, partnerId, re
4628
4973
  );
4629
4974
  }
4630
4975
  var OA_APP_BASE_URL = "https://oneaddress.io";
4976
+ async function confirmUpdate(opts2) {
4977
+ const {
4978
+ partnerId,
4979
+ secret,
4980
+ dispatchId,
4981
+ status = "confirmed",
4982
+ note,
4983
+ loaRef,
4984
+ memberName,
4985
+ appBaseUrl = OA_APP_BASE_URL,
4986
+ fetchImpl = fetch
4987
+ } = opts2;
4988
+ if (!partnerId) return { ok: false, status: 0, error: "partnerId is required" };
4989
+ if (!secret) return { ok: false, status: 0, error: "secret is required" };
4990
+ const id = typeof dispatchId === "string" ? Number(dispatchId) : dispatchId;
4991
+ if (!Number.isInteger(id) || id <= 0) {
4992
+ return {
4993
+ ok: false,
4994
+ status: 0,
4995
+ error: `dispatchId must be a positive integer, received ${JSON.stringify(dispatchId)} \u2014 it comes from the X-OneAddress-Dispatch header on the webhook you are confirming`
4996
+ };
4997
+ }
4998
+ const body = JSON.stringify({
4999
+ dispatch_id: id,
5000
+ partner_id: partnerId,
5001
+ status,
5002
+ ...note !== void 0 ? { note } : {},
5003
+ ...loaRef !== void 0 ? { loa_ref: loaRef } : {},
5004
+ ...memberName !== void 0 ? { member_name: memberName } : {}
5005
+ });
5006
+ const timestamp = String(Math.floor(Date.now() / 1e3));
5007
+ const signature = import_crypto.default.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
5008
+ let base = appBaseUrl;
5009
+ while (base.endsWith("/")) base = base.slice(0, -1);
5010
+ let res;
5011
+ try {
5012
+ res = await fetchImpl(`${base}/api/confirm`, {
5013
+ method: "POST",
5014
+ headers: {
5015
+ "Content-Type": "application/json",
5016
+ "Authorization": `Bearer ${secret}`,
5017
+ "X-OneAddress-Timestamp": timestamp,
5018
+ "X-OneAddress-Signature": signature
5019
+ },
5020
+ // The SAME string that was signed. Not an object, and not re-stringified.
5021
+ body
5022
+ });
5023
+ } catch (err) {
5024
+ return { ok: false, status: 0, error: err instanceof Error ? err.message : String(err) };
5025
+ }
5026
+ if (res.ok) return { ok: true, status: res.status };
5027
+ let error;
5028
+ try {
5029
+ const parsed = await res.json();
5030
+ if (typeof parsed?.error === "string") error = parsed.error;
5031
+ } catch {
5032
+ }
5033
+ return { ok: false, status: res.status, error };
5034
+ }
4631
5035
  function allowedLoaHosts() {
4632
5036
  const hosts = ["oneaddress.io", "app.oneaddress.io"];
4633
5037
  if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
@@ -4648,6 +5052,10 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
4648
5052
  `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...allowedHosts].join(", ")}`
4649
5053
  );
4650
5054
  }
5055
+ const loopback = parsedBase.hostname === "localhost" || parsedBase.hostname === "127.0.0.1";
5056
+ if (parsedBase.protocol !== "https:" && !loopback) {
5057
+ throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl must use https (plain http is accepted for localhost only)");
5058
+ }
4651
5059
  const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
4652
5060
  const res = await fetch(url);
4653
5061
  if (!res.ok) {
@@ -4724,12 +5132,13 @@ async function verifyD5LOA(loa, publicKeyPem) {
4724
5132
  return false;
4725
5133
  }
4726
5134
  }
4727
- async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId) {
5135
+ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId, expectedAlg) {
4728
5136
  const data = await decryptSession2(
4729
5137
  loaEncrypted.session_key_share,
4730
5138
  loaEncrypted.session_envelope,
4731
5139
  privateKeyPem,
4732
- partnerId
5140
+ partnerId,
5141
+ expectedAlg
4733
5142
  );
4734
5143
  return data;
4735
5144
  }
@@ -4886,14 +5295,57 @@ function requireContactValue(kind, value) {
4886
5295
  }
4887
5296
  var HANDLED_EVENTS = ["address.updated", "contact.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
4888
5297
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
5298
+ var warnedConsentUnverified = false;
5299
+ var warnedNoIdempotencyStore = false;
5300
+ var MAX_TIMESTAMP_TOLERANCE_SECS = 86400;
5301
+ var XWING_SEED_BYTES = 32;
5302
+ function assertUsablePrivateKey(privateKeyPem) {
5303
+ if (typeof privateKeyPem !== "string") {
5304
+ if (!privateKeyPem || typeof privateKeyPem !== "object" || typeof privateKeyPem.name !== "string") {
5305
+ throw new Error("[OneAddress SDK] privateKeyPem must be a PEM string or a PrivateKeyOperations delegate");
5306
+ }
5307
+ return;
5308
+ }
5309
+ if (privateKeyPem.trim() === "") {
5310
+ throw new Error("[OneAddress SDK] privateKeyPem is required: set it to your PKCS#8 private key from the Partner Portal");
5311
+ }
5312
+ const der = pemToBuffer(privateKeyPem);
5313
+ if (der.length === XWING_SEED_BYTES) return;
5314
+ try {
5315
+ import_crypto.default.createPrivateKey({ key: der, format: "der", type: "pkcs8" });
5316
+ } catch (err) {
5317
+ const refused = new Error(
5318
+ `[OneAddress SDK] privateKeyPem does not import as a PKCS#8 private key (${err instanceof Error ? err.message : String(err)}). Paste the whole key including the BEGIN/END lines; a key stored as one line with literal \\n sequences is accepted, a truncated one is not.`
5319
+ );
5320
+ refused.cause = err;
5321
+ throw refused;
5322
+ }
5323
+ }
5324
+ function requirePemFor(purpose, key) {
5325
+ if (typeof key === "string") return key;
5326
+ throw new Error(
5327
+ `[OneAddress SDK] ${purpose} needs the raw private key; a PrivateKeyOperations delegate ("${key.name}") covers session envelopes only`
5328
+ );
5329
+ }
5330
+ function assertLoaBoundToEnvelope(loa, envelopeUpdateUid) {
5331
+ if (typeof loa.update_uid !== "string" || typeof envelopeUpdateUid !== "string") return;
5332
+ if (loa.update_uid !== envelopeUpdateUid) {
5333
+ throw new Error(
5334
+ "[OneAddress SDK] D5 LOA is for a different update than the envelope it arrived with (update_uid mismatch); refusing rather than applying an address under someone else's consent"
5335
+ );
5336
+ }
5337
+ }
4889
5338
  function createOneAddressHandler(options) {
4890
5339
  const {
4891
5340
  webhookSecret,
4892
5341
  previousWebhookSecret,
4893
5342
  webhookSecretGraceUntil,
4894
5343
  privateKeyPem,
5344
+ expectedAlg,
4895
5345
  keyId,
4896
5346
  loaPublicKeyPem,
5347
+ requireLoa = Boolean(loaPublicKeyPem),
5348
+ confirm,
4897
5349
  onUpdate,
4898
5350
  onVerify,
4899
5351
  onAccountVerify,
@@ -4903,6 +5355,40 @@ function createOneAddressHandler(options) {
4903
5355
  acceptedUpdateTypes: acceptedUpdateTypesRaw,
4904
5356
  allowedCallbackHosts
4905
5357
  } = options;
5358
+ if (typeof webhookSecret !== "string" || webhookSecret === "") {
5359
+ throw new Error("[OneAddress SDK] webhookSecret is required: an empty secret would verify no signature at all");
5360
+ }
5361
+ assertUsablePrivateKey(privateKeyPem);
5362
+ if (typeof timestampToleranceSecs !== "number" || !Number.isFinite(timestampToleranceSecs) || timestampToleranceSecs <= 0 || timestampToleranceSecs > MAX_TIMESTAMP_TOLERANCE_SECS) {
5363
+ throw new Error(
5364
+ `[OneAddress SDK] timestampToleranceSecs must be a positive number of seconds up to ${MAX_TIMESTAMP_TOLERANCE_SECS}, got ${String(timestampToleranceSecs)}`
5365
+ );
5366
+ }
5367
+ if (webhookSecretGraceUntil !== void 0) {
5368
+ const until = typeof webhookSecretGraceUntil === "number" ? webhookSecretGraceUntil : Date.parse(webhookSecretGraceUntil);
5369
+ if (Number.isNaN(until)) {
5370
+ throw new Error(`[OneAddress SDK] webhookSecretGraceUntil is not a date: ${String(webhookSecretGraceUntil)}`);
5371
+ }
5372
+ }
5373
+ if (confirm && (!confirm.partnerId || !confirm.confirmSecret)) {
5374
+ throw new Error("[OneAddress SDK] confirm needs both partnerId and confirmSecret");
5375
+ }
5376
+ function enforceLoaPresence(body) {
5377
+ const present = !!body.loa_encrypted && typeof body.loa_encrypted === "object";
5378
+ if (present) return;
5379
+ if (requireLoa) {
5380
+ throw new Error(
5381
+ "[OneAddress SDK] dispatch carries no loa_encrypted and requireLoa is on: refusing to apply an update whose consent proof is missing"
5382
+ );
5383
+ }
5384
+ if (!warnedConsentUnverified) {
5385
+ warnedConsentUnverified = true;
5386
+ console.warn(
5387
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
5388
+ "[OneAddress SDK] a dispatch arrived with no loa_encrypted and requireLoa is off, so consent for this update is UNVERIFIED. Set loaPublicKeyPem (which turns requireLoa on) to refuse such dispatches. Logged once per process."
5389
+ );
5390
+ }
5391
+ }
4906
5392
  const acceptedUpdateTypes = normaliseAcceptedUpdateTypes(acceptedUpdateTypesRaw);
4907
5393
  function declared(status, payload) {
4908
5394
  return new Response(JSON.stringify({ ...payload, accepted_update_types: acceptedUpdateTypes }), {
@@ -4912,7 +5398,7 @@ function createOneAddressHandler(options) {
4912
5398
  }
4913
5399
  async function buildD5Pieces(body, partnerId) {
4914
5400
  const share = body.session_key_share;
4915
- const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId);
5401
+ const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId, expectedAlg);
4916
5402
  const updateTypes = readUpdateTypes(data.update_types);
4917
5403
  if (updateTypes === null) throw new InvalidUpdateTypesError(data.update_types);
4918
5404
  const address = updateTypes.includes("address") ? validateAddress({
@@ -4937,13 +5423,15 @@ function createOneAddressHandler(options) {
4937
5423
  loa = await decryptLoaEncrypted(
4938
5424
  body.loa_encrypted,
4939
5425
  privateKeyPem,
4940
- partnerId
5426
+ partnerId,
5427
+ expectedAlg
4941
5428
  );
4942
5429
  loa_ref = d5LoaRef(loa);
4943
5430
  if (loaPublicKeyPem) {
4944
5431
  const valid = await verifyD5LOA(loa, loaPublicKeyPem);
4945
5432
  if (!valid) throw new Error("D5 LOA signature verification failed");
4946
5433
  }
5434
+ assertLoaBoundToEnvelope(loa, data.update_uid);
4947
5435
  }
4948
5436
  return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
4949
5437
  }
@@ -4976,7 +5464,11 @@ function createOneAddressHandler(options) {
4976
5464
  }
4977
5465
  let body;
4978
5466
  try {
4979
- body = JSON.parse(rawBody);
5467
+ const parsed = JSON.parse(rawBody);
5468
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
5469
+ throw new TypeError("body is not a JSON object");
5470
+ }
5471
+ body = parsed;
4980
5472
  } catch {
4981
5473
  return new Response(JSON.stringify({ error: "Invalid JSON" }), {
4982
5474
  status: 400,
@@ -4998,11 +5490,19 @@ function createOneAddressHandler(options) {
4998
5490
  }
4999
5491
  if (dispatchId) {
5000
5492
  if (!idempotencyStore) {
5001
- if (process.env.NODE_ENV === "test") {
5493
+ const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
5494
+ if (nodeEnv === "test") {
5002
5495
  throw new Error(
5003
5496
  "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
5004
5497
  );
5005
5498
  }
5499
+ if (!warnedNoIdempotencyStore) {
5500
+ warnedNoIdempotencyStore = true;
5501
+ console.warn(
5502
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
5503
+ "[OneAddress SDK] a dispatch arrived with X-OneAddress-Dispatch and no idempotencyStore is wired, so a retried delivery will be processed again. Pass idempotencyStore: createSqlIdempotencyStore({ query }) to createOneAddressHandler. Logged once per process."
5504
+ );
5505
+ }
5006
5506
  } else if (idempotencyStore.claim) {
5007
5507
  const claim = await idempotencyStore.claim(dispatchId);
5008
5508
  if (claim === "duplicate") {
@@ -5019,6 +5519,7 @@ function createOneAddressHandler(options) {
5019
5519
  if (body.event === "address.updated" || body.event === "contact.updated") {
5020
5520
  const wireEvent = body.event;
5021
5521
  let event;
5522
+ enforceLoaPresence(body);
5022
5523
  if (isD5Body(body)) {
5023
5524
  let d5;
5024
5525
  try {
@@ -5071,19 +5572,25 @@ function createOneAddressHandler(options) {
5071
5572
  });
5072
5573
  }
5073
5574
  const encrypted = body.address_encrypted;
5074
- const rawAddress = await decryptAddress2(encrypted, privateKeyPem, partnerId);
5575
+ const rawAddress = await decryptAddress2(
5576
+ encrypted,
5577
+ requirePemFor("legacy address_encrypted decryption", privateKeyPem),
5578
+ partnerId
5579
+ );
5075
5580
  let loa;
5076
5581
  let loa_ref;
5077
5582
  if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
5078
5583
  loa = await decryptLoaEncrypted(
5079
5584
  body.loa_encrypted,
5080
5585
  privateKeyPem,
5081
- partnerId
5586
+ partnerId,
5587
+ expectedAlg
5082
5588
  );
5083
5589
  loa_ref = d5LoaRef(loa);
5084
5590
  if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
5085
5591
  throw new Error("D5 LOA signature verification failed");
5086
5592
  }
5593
+ assertLoaBoundToEnvelope(loa, rawAddress.update_uid);
5087
5594
  }
5088
5595
  const customer = {
5089
5596
  email: "",
@@ -5116,6 +5623,25 @@ function createOneAddressHandler(options) {
5116
5623
  // NOSONAR
5117
5624
  );
5118
5625
  }
5626
+ if (confirm && dispatchId) {
5627
+ const status = result && typeof result === "object" && result.status ? result.status : "confirmed";
5628
+ void confirmUpdate({
5629
+ partnerId: confirm.partnerId,
5630
+ secret: confirm.confirmSecret,
5631
+ dispatchId,
5632
+ status,
5633
+ loaRef: event.loa_ref,
5634
+ ...confirm.oneAddressApi ? { appBaseUrl: confirm.oneAddressApi } : {},
5635
+ ...confirm.fetchImpl ? { fetchImpl: confirm.fetchImpl } : {}
5636
+ }).then(
5637
+ (r) => {
5638
+ if (!r.ok) console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} failed: HTTP ${r.status} ${r.error ?? ""}`);
5639
+ },
5640
+ // NOSONAR
5641
+ (err) => console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} threw:`, err)
5642
+ // NOSONAR
5643
+ );
5644
+ }
5119
5645
  return declared(200, { ok: true, ...result });
5120
5646
  }
5121
5647
  if (body.event === "address.verify" && onVerify) {
@@ -5126,7 +5652,11 @@ function createOneAddressHandler(options) {
5126
5652
  });
5127
5653
  }
5128
5654
  const encrypted = body.address_encrypted;
5129
- const rawAddress = await decryptAddress2(encrypted, privateKeyPem, partnerId);
5655
+ const rawAddress = await decryptAddress2(
5656
+ encrypted,
5657
+ requirePemFor("address.verify decryption", privateKeyPem),
5658
+ partnerId
5659
+ );
5130
5660
  const event = {
5131
5661
  event: "address.verify",
5132
5662
  version: body.oneaddress_version ?? body.version ?? "1",
@@ -5173,7 +5703,7 @@ function createOneAddressHandler(options) {
5173
5703
  if (body.customer_encrypted && typeof body.customer_encrypted === "object") {
5174
5704
  const raw = await decryptAddress2(
5175
5705
  body.customer_encrypted,
5176
- privateKeyPem,
5706
+ requirePemFor("account.verify decryption", privateKeyPem),
5177
5707
  partnerId
5178
5708
  );
5179
5709
  customer = {
@@ -5219,7 +5749,12 @@ function createOneAddressHandler(options) {
5219
5749
  address: d5.address,
5220
5750
  raw: d5.raw
5221
5751
  });
5222
- return declared(200, { ok: true, test: true });
5752
+ return declared(200, {
5753
+ ok: true,
5754
+ test: true,
5755
+ verification: true,
5756
+ index: typeof body.index === "number" ? body.index : void 0
5757
+ });
5223
5758
  }
5224
5759
  const evt = typeof body.event === "string" ? body.event : "(none)";
5225
5760
  const callbackFor = {