@oneaddress/partner-sdk 2.0.0 → 2.2.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,48 @@ 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
+
4774
+ // ../protocol/src/retention.ts
4775
+ var DAY_MS = 24 * 60 * 60 * 1e3;
4776
+
4430
4777
  // src/index.ts
4431
4778
  init_src();
4432
4779
  init_src();
@@ -4499,7 +4846,8 @@ function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousS
4499
4846
  function base64urlToBuffer(b64) {
4500
4847
  return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
4501
4848
  }
4502
- function pemToBase64(pem) {
4849
+ function pemToBase64(pemRaw) {
4850
+ const pem = pemRaw.replace(/(?:\\r)?\\n/g, "\n");
4503
4851
  const begin = pem.indexOf("-----BEGIN");
4504
4852
  if (begin === -1) return pem.replace(/\s/g, "");
4505
4853
  const armourEnd = pem.indexOf("-----", begin + "-----BEGIN".length);
@@ -4628,6 +4976,65 @@ async function transformSession(share, envelopeB64, privateKeyPem, partnerId, re
4628
4976
  );
4629
4977
  }
4630
4978
  var OA_APP_BASE_URL = "https://oneaddress.io";
4979
+ async function confirmUpdate(opts2) {
4980
+ const {
4981
+ partnerId,
4982
+ secret,
4983
+ dispatchId,
4984
+ status = "confirmed",
4985
+ note,
4986
+ loaRef,
4987
+ memberName,
4988
+ appBaseUrl = OA_APP_BASE_URL,
4989
+ fetchImpl = fetch
4990
+ } = opts2;
4991
+ if (!partnerId) return { ok: false, status: 0, error: "partnerId is required" };
4992
+ if (!secret) return { ok: false, status: 0, error: "secret is required" };
4993
+ const id = typeof dispatchId === "string" ? Number(dispatchId) : dispatchId;
4994
+ if (!Number.isInteger(id) || id <= 0) {
4995
+ return {
4996
+ ok: false,
4997
+ status: 0,
4998
+ 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`
4999
+ };
5000
+ }
5001
+ const body = JSON.stringify({
5002
+ dispatch_id: id,
5003
+ partner_id: partnerId,
5004
+ status,
5005
+ ...note !== void 0 ? { note } : {},
5006
+ ...loaRef !== void 0 ? { loa_ref: loaRef } : {},
5007
+ ...memberName !== void 0 ? { member_name: memberName } : {}
5008
+ });
5009
+ const timestamp = String(Math.floor(Date.now() / 1e3));
5010
+ const signature = import_crypto.default.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
5011
+ let base = appBaseUrl;
5012
+ while (base.endsWith("/")) base = base.slice(0, -1);
5013
+ let res;
5014
+ try {
5015
+ res = await fetchImpl(`${base}/api/confirm`, {
5016
+ method: "POST",
5017
+ headers: {
5018
+ "Content-Type": "application/json",
5019
+ "Authorization": `Bearer ${secret}`,
5020
+ "X-OneAddress-Timestamp": timestamp,
5021
+ "X-OneAddress-Signature": signature
5022
+ },
5023
+ // The SAME string that was signed. Not an object, and not re-stringified.
5024
+ body
5025
+ });
5026
+ } catch (err) {
5027
+ return { ok: false, status: 0, error: err instanceof Error ? err.message : String(err) };
5028
+ }
5029
+ if (res.ok) return { ok: true, status: res.status };
5030
+ let error;
5031
+ try {
5032
+ const parsed = await res.json();
5033
+ if (typeof parsed?.error === "string") error = parsed.error;
5034
+ } catch {
5035
+ }
5036
+ return { ok: false, status: res.status, error };
5037
+ }
4631
5038
  function allowedLoaHosts() {
4632
5039
  const hosts = ["oneaddress.io", "app.oneaddress.io"];
4633
5040
  if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
@@ -4648,6 +5055,10 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
4648
5055
  `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...allowedHosts].join(", ")}`
4649
5056
  );
4650
5057
  }
5058
+ const loopback = parsedBase.hostname === "localhost" || parsedBase.hostname === "127.0.0.1";
5059
+ if (parsedBase.protocol !== "https:" && !loopback) {
5060
+ throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl must use https (plain http is accepted for localhost only)");
5061
+ }
4651
5062
  const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
4652
5063
  const res = await fetch(url);
4653
5064
  if (!res.ok) {
@@ -4724,12 +5135,13 @@ async function verifyD5LOA(loa, publicKeyPem) {
4724
5135
  return false;
4725
5136
  }
4726
5137
  }
4727
- async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId) {
5138
+ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId, expectedAlg) {
4728
5139
  const data = await decryptSession2(
4729
5140
  loaEncrypted.session_key_share,
4730
5141
  loaEncrypted.session_envelope,
4731
5142
  privateKeyPem,
4732
- partnerId
5143
+ partnerId,
5144
+ expectedAlg
4733
5145
  );
4734
5146
  return data;
4735
5147
  }
@@ -4886,14 +5298,57 @@ function requireContactValue(kind, value) {
4886
5298
  }
4887
5299
  var HANDLED_EVENTS = ["address.updated", "contact.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
4888
5300
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
5301
+ var warnedConsentUnverified = false;
5302
+ var warnedNoIdempotencyStore = false;
5303
+ var MAX_TIMESTAMP_TOLERANCE_SECS = 86400;
5304
+ var XWING_SEED_BYTES = 32;
5305
+ function assertUsablePrivateKey(privateKeyPem) {
5306
+ if (typeof privateKeyPem !== "string") {
5307
+ if (!privateKeyPem || typeof privateKeyPem !== "object" || typeof privateKeyPem.name !== "string") {
5308
+ throw new Error("[OneAddress SDK] privateKeyPem must be a PEM string or a PrivateKeyOperations delegate");
5309
+ }
5310
+ return;
5311
+ }
5312
+ if (privateKeyPem.trim() === "") {
5313
+ throw new Error("[OneAddress SDK] privateKeyPem is required: set it to your PKCS#8 private key from the Partner Portal");
5314
+ }
5315
+ const der = pemToBuffer(privateKeyPem);
5316
+ if (der.length === XWING_SEED_BYTES) return;
5317
+ try {
5318
+ import_crypto.default.createPrivateKey({ key: der, format: "der", type: "pkcs8" });
5319
+ } catch (err) {
5320
+ const refused = new Error(
5321
+ `[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.`
5322
+ );
5323
+ refused.cause = err;
5324
+ throw refused;
5325
+ }
5326
+ }
5327
+ function requirePemFor(purpose, key) {
5328
+ if (typeof key === "string") return key;
5329
+ throw new Error(
5330
+ `[OneAddress SDK] ${purpose} needs the raw private key; a PrivateKeyOperations delegate ("${key.name}") covers session envelopes only`
5331
+ );
5332
+ }
5333
+ function assertLoaBoundToEnvelope(loa, envelopeUpdateUid) {
5334
+ if (typeof loa.update_uid !== "string" || typeof envelopeUpdateUid !== "string") return;
5335
+ if (loa.update_uid !== envelopeUpdateUid) {
5336
+ throw new Error(
5337
+ "[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"
5338
+ );
5339
+ }
5340
+ }
4889
5341
  function createOneAddressHandler(options) {
4890
5342
  const {
4891
5343
  webhookSecret,
4892
5344
  previousWebhookSecret,
4893
5345
  webhookSecretGraceUntil,
4894
5346
  privateKeyPem,
5347
+ expectedAlg,
4895
5348
  keyId,
4896
5349
  loaPublicKeyPem,
5350
+ requireLoa = Boolean(loaPublicKeyPem),
5351
+ confirm,
4897
5352
  onUpdate,
4898
5353
  onVerify,
4899
5354
  onAccountVerify,
@@ -4903,6 +5358,40 @@ function createOneAddressHandler(options) {
4903
5358
  acceptedUpdateTypes: acceptedUpdateTypesRaw,
4904
5359
  allowedCallbackHosts
4905
5360
  } = options;
5361
+ if (typeof webhookSecret !== "string" || webhookSecret === "") {
5362
+ throw new Error("[OneAddress SDK] webhookSecret is required: an empty secret would verify no signature at all");
5363
+ }
5364
+ assertUsablePrivateKey(privateKeyPem);
5365
+ if (typeof timestampToleranceSecs !== "number" || !Number.isFinite(timestampToleranceSecs) || timestampToleranceSecs <= 0 || timestampToleranceSecs > MAX_TIMESTAMP_TOLERANCE_SECS) {
5366
+ throw new Error(
5367
+ `[OneAddress SDK] timestampToleranceSecs must be a positive number of seconds up to ${MAX_TIMESTAMP_TOLERANCE_SECS}, got ${String(timestampToleranceSecs)}`
5368
+ );
5369
+ }
5370
+ if (webhookSecretGraceUntil !== void 0) {
5371
+ const until = typeof webhookSecretGraceUntil === "number" ? webhookSecretGraceUntil : Date.parse(webhookSecretGraceUntil);
5372
+ if (Number.isNaN(until)) {
5373
+ throw new Error(`[OneAddress SDK] webhookSecretGraceUntil is not a date: ${String(webhookSecretGraceUntil)}`);
5374
+ }
5375
+ }
5376
+ if (confirm && (!confirm.partnerId || !confirm.confirmSecret)) {
5377
+ throw new Error("[OneAddress SDK] confirm needs both partnerId and confirmSecret");
5378
+ }
5379
+ function enforceLoaPresence(body) {
5380
+ const present = !!body.loa_encrypted && typeof body.loa_encrypted === "object";
5381
+ if (present) return;
5382
+ if (requireLoa) {
5383
+ throw new Error(
5384
+ "[OneAddress SDK] dispatch carries no loa_encrypted and requireLoa is on: refusing to apply an update whose consent proof is missing"
5385
+ );
5386
+ }
5387
+ if (!warnedConsentUnverified) {
5388
+ warnedConsentUnverified = true;
5389
+ console.warn(
5390
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
5391
+ "[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."
5392
+ );
5393
+ }
5394
+ }
4906
5395
  const acceptedUpdateTypes = normaliseAcceptedUpdateTypes(acceptedUpdateTypesRaw);
4907
5396
  function declared(status, payload) {
4908
5397
  return new Response(JSON.stringify({ ...payload, accepted_update_types: acceptedUpdateTypes }), {
@@ -4912,7 +5401,7 @@ function createOneAddressHandler(options) {
4912
5401
  }
4913
5402
  async function buildD5Pieces(body, partnerId) {
4914
5403
  const share = body.session_key_share;
4915
- const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId);
5404
+ const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId, expectedAlg);
4916
5405
  const updateTypes = readUpdateTypes(data.update_types);
4917
5406
  if (updateTypes === null) throw new InvalidUpdateTypesError(data.update_types);
4918
5407
  const address = updateTypes.includes("address") ? validateAddress({
@@ -4937,13 +5426,15 @@ function createOneAddressHandler(options) {
4937
5426
  loa = await decryptLoaEncrypted(
4938
5427
  body.loa_encrypted,
4939
5428
  privateKeyPem,
4940
- partnerId
5429
+ partnerId,
5430
+ expectedAlg
4941
5431
  );
4942
5432
  loa_ref = d5LoaRef(loa);
4943
5433
  if (loaPublicKeyPem) {
4944
5434
  const valid = await verifyD5LOA(loa, loaPublicKeyPem);
4945
5435
  if (!valid) throw new Error("D5 LOA signature verification failed");
4946
5436
  }
5437
+ assertLoaBoundToEnvelope(loa, data.update_uid);
4947
5438
  }
4948
5439
  return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
4949
5440
  }
@@ -4976,7 +5467,11 @@ function createOneAddressHandler(options) {
4976
5467
  }
4977
5468
  let body;
4978
5469
  try {
4979
- body = JSON.parse(rawBody);
5470
+ const parsed = JSON.parse(rawBody);
5471
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
5472
+ throw new TypeError("body is not a JSON object");
5473
+ }
5474
+ body = parsed;
4980
5475
  } catch {
4981
5476
  return new Response(JSON.stringify({ error: "Invalid JSON" }), {
4982
5477
  status: 400,
@@ -4998,11 +5493,19 @@ function createOneAddressHandler(options) {
4998
5493
  }
4999
5494
  if (dispatchId) {
5000
5495
  if (!idempotencyStore) {
5001
- if (process.env.NODE_ENV === "test") {
5496
+ const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
5497
+ if (nodeEnv === "test") {
5002
5498
  throw new Error(
5003
5499
  "[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
5500
  );
5005
5501
  }
5502
+ if (!warnedNoIdempotencyStore) {
5503
+ warnedNoIdempotencyStore = true;
5504
+ console.warn(
5505
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
5506
+ "[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."
5507
+ );
5508
+ }
5006
5509
  } else if (idempotencyStore.claim) {
5007
5510
  const claim = await idempotencyStore.claim(dispatchId);
5008
5511
  if (claim === "duplicate") {
@@ -5019,6 +5522,7 @@ function createOneAddressHandler(options) {
5019
5522
  if (body.event === "address.updated" || body.event === "contact.updated") {
5020
5523
  const wireEvent = body.event;
5021
5524
  let event;
5525
+ enforceLoaPresence(body);
5022
5526
  if (isD5Body(body)) {
5023
5527
  let d5;
5024
5528
  try {
@@ -5071,19 +5575,25 @@ function createOneAddressHandler(options) {
5071
5575
  });
5072
5576
  }
5073
5577
  const encrypted = body.address_encrypted;
5074
- const rawAddress = await decryptAddress2(encrypted, privateKeyPem, partnerId);
5578
+ const rawAddress = await decryptAddress2(
5579
+ encrypted,
5580
+ requirePemFor("legacy address_encrypted decryption", privateKeyPem),
5581
+ partnerId
5582
+ );
5075
5583
  let loa;
5076
5584
  let loa_ref;
5077
5585
  if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
5078
5586
  loa = await decryptLoaEncrypted(
5079
5587
  body.loa_encrypted,
5080
5588
  privateKeyPem,
5081
- partnerId
5589
+ partnerId,
5590
+ expectedAlg
5082
5591
  );
5083
5592
  loa_ref = d5LoaRef(loa);
5084
5593
  if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
5085
5594
  throw new Error("D5 LOA signature verification failed");
5086
5595
  }
5596
+ assertLoaBoundToEnvelope(loa, rawAddress.update_uid);
5087
5597
  }
5088
5598
  const customer = {
5089
5599
  email: "",
@@ -5116,6 +5626,25 @@ function createOneAddressHandler(options) {
5116
5626
  // NOSONAR
5117
5627
  );
5118
5628
  }
5629
+ if (confirm && dispatchId) {
5630
+ const status = result && typeof result === "object" && result.status ? result.status : "confirmed";
5631
+ void confirmUpdate({
5632
+ partnerId: confirm.partnerId,
5633
+ secret: confirm.confirmSecret,
5634
+ dispatchId,
5635
+ status,
5636
+ loaRef: event.loa_ref,
5637
+ ...confirm.oneAddressApi ? { appBaseUrl: confirm.oneAddressApi } : {},
5638
+ ...confirm.fetchImpl ? { fetchImpl: confirm.fetchImpl } : {}
5639
+ }).then(
5640
+ (r) => {
5641
+ if (!r.ok) console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} failed: HTTP ${r.status} ${r.error ?? ""}`);
5642
+ },
5643
+ // NOSONAR
5644
+ (err) => console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} threw:`, err)
5645
+ // NOSONAR
5646
+ );
5647
+ }
5119
5648
  return declared(200, { ok: true, ...result });
5120
5649
  }
5121
5650
  if (body.event === "address.verify" && onVerify) {
@@ -5126,7 +5655,11 @@ function createOneAddressHandler(options) {
5126
5655
  });
5127
5656
  }
5128
5657
  const encrypted = body.address_encrypted;
5129
- const rawAddress = await decryptAddress2(encrypted, privateKeyPem, partnerId);
5658
+ const rawAddress = await decryptAddress2(
5659
+ encrypted,
5660
+ requirePemFor("address.verify decryption", privateKeyPem),
5661
+ partnerId
5662
+ );
5130
5663
  const event = {
5131
5664
  event: "address.verify",
5132
5665
  version: body.oneaddress_version ?? body.version ?? "1",
@@ -5173,7 +5706,7 @@ function createOneAddressHandler(options) {
5173
5706
  if (body.customer_encrypted && typeof body.customer_encrypted === "object") {
5174
5707
  const raw = await decryptAddress2(
5175
5708
  body.customer_encrypted,
5176
- privateKeyPem,
5709
+ requirePemFor("account.verify decryption", privateKeyPem),
5177
5710
  partnerId
5178
5711
  );
5179
5712
  customer = {
@@ -5219,7 +5752,12 @@ function createOneAddressHandler(options) {
5219
5752
  address: d5.address,
5220
5753
  raw: d5.raw
5221
5754
  });
5222
- return declared(200, { ok: true, test: true });
5755
+ return declared(200, {
5756
+ ok: true,
5757
+ test: true,
5758
+ verification: true,
5759
+ index: typeof body.index === "number" ? body.index : void 0
5760
+ });
5223
5761
  }
5224
5762
  const evt = typeof body.event === "string" ? body.event : "(none)";
5225
5763
  const callbackFor = {