@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/index.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) {
@@ -4395,6 +4700,8 @@ __export(index_exports, {
4395
4700
  DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
4396
4701
  OUTBOX_LEASE_COLUMNS: () => OUTBOX_LEASE_COLUMNS,
4397
4702
  SUPPORTED_VERSIONS: () => SUPPORTED_VERSIONS,
4703
+ _resetOnceWarningsForTests: () => _resetOnceWarningsForTests,
4704
+ buildSignedTestWebhook: () => buildSignedTestWebhook,
4398
4705
  canonicalD5LoaForm: () => canonicalD5LoaForm,
4399
4706
  compareAddresses: () => compareAddresses,
4400
4707
  computeBlindIndex: () => computeBlindIndex,
@@ -4438,6 +4745,45 @@ init_src();
4438
4745
  var CURRENT_VERSION = "2026.1";
4439
4746
  var SUPPORTED_VERSIONS = ["2026.1"];
4440
4747
 
4748
+ // ../protocol/src/d5-body.ts
4749
+ var D5_BODY_ALWAYS = [
4750
+ "event",
4751
+ "id_verification",
4752
+ "key_share_expiry",
4753
+ "oneaddress_version",
4754
+ "partner_id",
4755
+ "session_envelope",
4756
+ "session_key_share",
4757
+ "stripe_session_id",
4758
+ "timestamp",
4759
+ "update_id",
4760
+ "user_id"
4761
+ ];
4762
+ var D5_BODY_CONDITIONAL = {
4763
+ /**
4764
+ * The signed Letter of Authority, sealed to the same key_id as the session.
4765
+ * Present whenever the partner has a usable key — i.e. on every dispatch a
4766
+ * live partner receives. Omitted best-effort when no key is available, which
4767
+ * is a state a live partner is never in.
4768
+ */
4769
+ loa_encrypted: "partner has a usable encryption key",
4770
+ /**
4771
+ * The shared webhook event id. Set ONLY on a key-crossover copy, where every
4772
+ * copy of one update carries the same id so a receiver holding more than one
4773
+ * rotation key applies it once. Absent on an ordinary dispatch, whose
4774
+ * receiver idempotency falls back to the `X-OneAddress-Dispatch` header.
4775
+ */
4776
+ id: "key-crossover copy only",
4777
+ /** The sibling marker naming the other key_ids this update was sealed to. */
4778
+ crossover_key_ids: "key-crossover copy only"
4779
+ };
4780
+ var D5_BODY_DRILL_ONLY = ["conformance"];
4781
+ var D5_BODY_ALL_ALLOWED = [
4782
+ ...D5_BODY_ALWAYS,
4783
+ ...Object.keys(D5_BODY_CONDITIONAL),
4784
+ ...D5_BODY_DRILL_ONLY
4785
+ ];
4786
+
4441
4787
  // src/index.ts
4442
4788
  init_src();
4443
4789
  init_src();
@@ -4564,9 +4910,17 @@ function createOutboxConsumer(opts2) {
4564
4910
  if (!Number.isFinite(batchSize) || batchSize < 1) {
4565
4911
  throw new Error(`[OneAddress SDK] batchSize must be a positive integer, got ${opts2.batchSize}`);
4566
4912
  }
4913
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 0) {
4914
+ throw new Error(`[OneAddress SDK] maxAttempts must be an integer >= 0, got ${opts2.maxAttempts}`);
4915
+ }
4567
4916
  const ph = d.ph;
4568
4917
  const token = () => (0, import_node_crypto.randomBytes)(16).toString("hex");
4569
4918
  const stamp = (at) => toOutboxTimestamp(dialect, at);
4919
+ const heldTokens = /* @__PURE__ */ new Map();
4920
+ const claimPredicate = (dispatchId, firstPh) => {
4921
+ const tok = heldTokens.get(dispatchId);
4922
+ return tok === void 0 ? { sql: `dispatch_id = ${ph(firstPh)}`, params: [dispatchId] } : { sql: `dispatch_id = ${ph(firstPh)} AND ${CLAIM_TOKEN} = ${ph(firstPh + 1)}`, params: [dispatchId, tok] };
4923
+ };
4570
4924
  const claimable = (cutoffPh) => `written_at IS NOT NULL AND processed_at IS NULL AND (${CLAIMED_AT} IS NULL OR ${CLAIMED_AT} < ${cutoffPh})` + (maxAttempts > 0 ? ` AND (${ATTEMPTS} IS NULL OR ${ATTEMPTS} < ${maxAttempts})` : "");
4571
4925
  const toRow = (r) => ({
4572
4926
  dispatchId: String(r.dispatch_id ?? r.dispatchId ?? ""),
@@ -4574,6 +4928,10 @@ function createOutboxConsumer(opts2) {
4574
4928
  attempts: Number(r[ATTEMPTS] ?? 0) || 0,
4575
4929
  fields: r
4576
4930
  });
4931
+ const claimed = (rows, tok) => rows.map(toRow).map((row) => {
4932
+ heldTokens.set(row.dispatchId, tok);
4933
+ return row;
4934
+ });
4577
4935
  async function claimBatch() {
4578
4936
  const at = now();
4579
4937
  const claimedAt = stamp(at);
@@ -4584,14 +4942,14 @@ function createOutboxConsumer(opts2) {
4584
4942
  `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE dispatch_id IN (SELECT dispatch_id FROM ${table} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize} FOR UPDATE SKIP LOCKED) RETURNING *`,
4585
4943
  [claimedAt, tok, cutoff]
4586
4944
  );
4587
- return rows2.map(toRow);
4945
+ return claimed(rows2, tok);
4588
4946
  }
4589
4947
  if (dialect === "mssql") {
4590
4948
  const rows2 = await opts2.query(
4591
4949
  `UPDATE TOP (${batchSize}) ${table} WITH (UPDLOCK, READPAST, ROWLOCK) SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} OUTPUT INSERTED.* WHERE ${claimable(ph(3))}`,
4592
4950
  [claimedAt, tok, cutoff]
4593
4951
  );
4594
- return rows2.map(toRow);
4952
+ return claimed(rows2, tok);
4595
4953
  }
4596
4954
  const claim = dialect === "mysql" ? `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize}` : `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE dispatch_id IN (SELECT dispatch_id FROM ${table} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize})`;
4597
4955
  await opts2.query(claim, [claimedAt, tok, cutoff]);
@@ -4599,7 +4957,7 @@ function createOutboxConsumer(opts2) {
4599
4957
  `SELECT * FROM ${table} WHERE ${CLAIM_TOKEN} = ${ph(1)} AND processed_at IS NULL`,
4600
4958
  [tok]
4601
4959
  );
4602
- return rows.map(toRow);
4960
+ return claimed(rows, tok);
4603
4961
  }
4604
4962
  return {
4605
4963
  async ensureSchema() {
@@ -4628,23 +4986,29 @@ function createOutboxConsumer(opts2) {
4628
4986
  },
4629
4987
  claimBatch,
4630
4988
  async markProcessed(dispatchId) {
4989
+ const where = claimPredicate(dispatchId, 2);
4631
4990
  await opts2.query(
4632
- `UPDATE ${table} SET processed_at = ${ph(1)}, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(2)}`,
4633
- [stamp(now()), dispatchId]
4991
+ `UPDATE ${table} SET processed_at = ${ph(1)}, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
4992
+ [stamp(now()), ...where.params]
4634
4993
  );
4994
+ heldTokens.delete(dispatchId);
4635
4995
  },
4636
4996
  async markFailed(dispatchId, error) {
4637
4997
  const message = error instanceof Error ? error.message : String(error);
4998
+ const where = claimPredicate(dispatchId, 2);
4638
4999
  await opts2.query(
4639
- `UPDATE ${table} SET processing_error = ${ph(1)}, ${ATTEMPTS} = COALESCE(${ATTEMPTS}, 0) + 1, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(2)}`,
4640
- [message.slice(0, 500), dispatchId]
5000
+ `UPDATE ${table} SET processing_error = ${ph(1)}, ${ATTEMPTS} = COALESCE(${ATTEMPTS}, 0) + 1, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
5001
+ [message.slice(0, 500), ...where.params]
4641
5002
  );
5003
+ heldTokens.delete(dispatchId);
4642
5004
  },
4643
5005
  async release(dispatchId) {
5006
+ const where = claimPredicate(dispatchId, 1);
4644
5007
  await opts2.query(
4645
- `UPDATE ${table} SET ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(1)}`,
4646
- [dispatchId]
5008
+ `UPDATE ${table} SET ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
5009
+ where.params
4647
5010
  );
5011
+ heldTokens.delete(dispatchId);
4648
5012
  },
4649
5013
  async process(handler) {
4650
5014
  const rows = await claimBatch();
@@ -4685,15 +5049,62 @@ function createOutboxConsumer(opts2) {
4685
5049
  }
4686
5050
 
4687
5051
  // src/index.ts
5052
+ var IDEMPOTENCY_DIALECTS = ["postgres", "sqlite", "mysql", "mssql"];
4688
5053
  function createSqlIdempotencyStore(opts2) {
4689
5054
  const table = opts2.table ?? "oneaddress_dispatches";
4690
- const ph = opts2.placeholder ?? ((n) => `$${n}`);
5055
+ const dialect = opts2.dialect ?? "postgres";
5056
+ if (!IDEMPOTENCY_DIALECTS.includes(dialect)) {
5057
+ throw new Error(
5058
+ `[OneAddress SDK] createSqlIdempotencyStore: unknown dialect "${dialect}". Supported: ${IDEMPOTENCY_DIALECTS.join(", ")}.`
5059
+ );
5060
+ }
5061
+ const defaultPh = dialect === "postgres" ? (n) => `$${n}` : dialect === "mssql" ? (n) => `@p${n}` : () => "?";
5062
+ const ph = opts2.placeholder ?? defaultPh;
4691
5063
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
4692
5064
  throw new Error(`[OneAddress SDK] invalid table name: ${table}`);
4693
5065
  }
4694
5066
  const completedOf = (row) => row?.completed_at ?? row?.completedAt ?? null;
5067
+ const tokenOf = (row) => row?.claim_token ?? row?.claimToken ?? null;
5068
+ async function claimByToken(dispatchId) {
5069
+ const token = import_crypto.default.randomBytes(16).toString("hex");
5070
+ await opts2.query(
5071
+ dialect === "mysql" ? `INSERT IGNORE INTO ${table} (dispatch_id, claim_token) VALUES (${ph(1)}, ${ph(2)})` : `INSERT INTO ${table} (dispatch_id, claim_token) SELECT ${ph(1)}, ${ph(2)} WHERE NOT EXISTS (SELECT 1 FROM ${table} WHERE dispatch_id = ${ph(1)})`,
5072
+ [dispatchId, token]
5073
+ );
5074
+ const rows = await opts2.query(
5075
+ `SELECT claim_token, completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
5076
+ [dispatchId]
5077
+ );
5078
+ if (tokenOf(rows[0]) === token) return "fresh";
5079
+ return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
5080
+ }
5081
+ async function setByUpsert(dispatchId) {
5082
+ if (dialect === "mysql") {
5083
+ await opts2.query(
5084
+ `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE completed_at = CURRENT_TIMESTAMP`,
5085
+ [dispatchId]
5086
+ );
5087
+ return;
5088
+ }
5089
+ if (dialect === "mssql") {
5090
+ await opts2.query(
5091
+ `UPDATE ${table} SET completed_at = CURRENT_TIMESTAMP WHERE dispatch_id = ${ph(1)}`,
5092
+ [dispatchId]
5093
+ );
5094
+ await opts2.query(
5095
+ `INSERT INTO ${table} (dispatch_id, completed_at) SELECT ${ph(1)}, CURRENT_TIMESTAMP WHERE NOT EXISTS (SELECT 1 FROM ${table} WHERE dispatch_id = ${ph(1)})`,
5096
+ [dispatchId]
5097
+ );
5098
+ return;
5099
+ }
5100
+ await opts2.query(
5101
+ `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON CONFLICT (dispatch_id) DO UPDATE SET completed_at = CURRENT_TIMESTAMP`,
5102
+ [dispatchId]
5103
+ );
5104
+ }
4695
5105
  return {
4696
5106
  async claim(dispatchId) {
5107
+ if (dialect === "mysql" || dialect === "mssql") return claimByToken(dispatchId);
4697
5108
  const inserted = await opts2.query(
4698
5109
  `INSERT INTO ${table} (dispatch_id) VALUES (${ph(1)}) ON CONFLICT (dispatch_id) DO NOTHING RETURNING dispatch_id`,
4699
5110
  [dispatchId]
@@ -4721,10 +5132,7 @@ function createSqlIdempotencyStore(opts2) {
4721
5132
  return rows.length > 0 && Boolean(completedOf(rows[0]));
4722
5133
  },
4723
5134
  async set(dispatchId) {
4724
- await opts2.query(
4725
- `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON CONFLICT (dispatch_id) DO UPDATE SET completed_at = CURRENT_TIMESTAMP`,
4726
- [dispatchId]
4727
- );
5135
+ await setByUpsert(dispatchId);
4728
5136
  }
4729
5137
  };
4730
5138
  }
@@ -4750,7 +5158,8 @@ function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousS
4750
5158
  function base64urlToBuffer(b64) {
4751
5159
  return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
4752
5160
  }
4753
- function pemToBase64(pem) {
5161
+ function pemToBase64(pemRaw) {
5162
+ const pem = pemRaw.replace(/(?:\\r)?\\n/g, "\n");
4754
5163
  const begin = pem.indexOf("-----BEGIN");
4755
5164
  if (begin === -1) return pem.replace(/\s/g, "");
4756
5165
  const armourEnd = pem.indexOf("-----", begin + "-----BEGIN".length);
@@ -4958,6 +5367,10 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
4958
5367
  `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...allowedHosts].join(", ")}`
4959
5368
  );
4960
5369
  }
5370
+ const loopback = parsedBase.hostname === "localhost" || parsedBase.hostname === "127.0.0.1";
5371
+ if (parsedBase.protocol !== "https:" && !loopback) {
5372
+ throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl must use https (plain http is accepted for localhost only)");
5373
+ }
4961
5374
  const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
4962
5375
  const res = await fetch(url);
4963
5376
  if (!res.ok) {
@@ -5034,12 +5447,13 @@ async function verifyD5LOA(loa, publicKeyPem) {
5034
5447
  return false;
5035
5448
  }
5036
5449
  }
5037
- async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId) {
5450
+ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId, expectedAlg) {
5038
5451
  const data = await decryptSession2(
5039
5452
  loaEncrypted.session_key_share,
5040
5453
  loaEncrypted.session_envelope,
5041
5454
  privateKeyPem,
5042
- partnerId
5455
+ partnerId,
5456
+ expectedAlg
5043
5457
  );
5044
5458
  return data;
5045
5459
  }
@@ -5224,14 +5638,61 @@ function requireContactValue(kind, value) {
5224
5638
  }
5225
5639
  var HANDLED_EVENTS = ["address.updated", "contact.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
5226
5640
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
5641
+ var warnedConsentUnverified = false;
5642
+ var warnedNoIdempotencyStore = false;
5643
+ function _resetOnceWarningsForTests() {
5644
+ warnedConsentUnverified = false;
5645
+ warnedNoIdempotencyStore = false;
5646
+ }
5647
+ var MAX_TIMESTAMP_TOLERANCE_SECS = 86400;
5648
+ var XWING_SEED_BYTES = 32;
5649
+ function assertUsablePrivateKey(privateKeyPem) {
5650
+ if (typeof privateKeyPem !== "string") {
5651
+ if (!privateKeyPem || typeof privateKeyPem !== "object" || typeof privateKeyPem.name !== "string") {
5652
+ throw new Error("[OneAddress SDK] privateKeyPem must be a PEM string or a PrivateKeyOperations delegate");
5653
+ }
5654
+ return;
5655
+ }
5656
+ if (privateKeyPem.trim() === "") {
5657
+ throw new Error("[OneAddress SDK] privateKeyPem is required: set it to your PKCS#8 private key from the Partner Portal");
5658
+ }
5659
+ const der = pemToBuffer(privateKeyPem);
5660
+ if (der.length === XWING_SEED_BYTES) return;
5661
+ try {
5662
+ import_crypto.default.createPrivateKey({ key: der, format: "der", type: "pkcs8" });
5663
+ } catch (err) {
5664
+ const refused = new Error(
5665
+ `[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.`
5666
+ );
5667
+ refused.cause = err;
5668
+ throw refused;
5669
+ }
5670
+ }
5671
+ function requirePemFor(purpose, key) {
5672
+ if (typeof key === "string") return key;
5673
+ throw new Error(
5674
+ `[OneAddress SDK] ${purpose} needs the raw private key; a PrivateKeyOperations delegate ("${key.name}") covers session envelopes only`
5675
+ );
5676
+ }
5677
+ function assertLoaBoundToEnvelope(loa, envelopeUpdateUid) {
5678
+ if (typeof loa.update_uid !== "string" || typeof envelopeUpdateUid !== "string") return;
5679
+ if (loa.update_uid !== envelopeUpdateUid) {
5680
+ throw new Error(
5681
+ "[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"
5682
+ );
5683
+ }
5684
+ }
5227
5685
  function createOneAddressHandler(options) {
5228
5686
  const {
5229
5687
  webhookSecret,
5230
5688
  previousWebhookSecret,
5231
5689
  webhookSecretGraceUntil,
5232
5690
  privateKeyPem,
5691
+ expectedAlg,
5233
5692
  keyId,
5234
5693
  loaPublicKeyPem,
5694
+ requireLoa = Boolean(loaPublicKeyPem),
5695
+ confirm,
5235
5696
  onUpdate,
5236
5697
  onVerify,
5237
5698
  onAccountVerify,
@@ -5241,6 +5702,40 @@ function createOneAddressHandler(options) {
5241
5702
  acceptedUpdateTypes: acceptedUpdateTypesRaw,
5242
5703
  allowedCallbackHosts
5243
5704
  } = options;
5705
+ if (typeof webhookSecret !== "string" || webhookSecret === "") {
5706
+ throw new Error("[OneAddress SDK] webhookSecret is required: an empty secret would verify no signature at all");
5707
+ }
5708
+ assertUsablePrivateKey(privateKeyPem);
5709
+ if (typeof timestampToleranceSecs !== "number" || !Number.isFinite(timestampToleranceSecs) || timestampToleranceSecs <= 0 || timestampToleranceSecs > MAX_TIMESTAMP_TOLERANCE_SECS) {
5710
+ throw new Error(
5711
+ `[OneAddress SDK] timestampToleranceSecs must be a positive number of seconds up to ${MAX_TIMESTAMP_TOLERANCE_SECS}, got ${String(timestampToleranceSecs)}`
5712
+ );
5713
+ }
5714
+ if (webhookSecretGraceUntil !== void 0) {
5715
+ const until = typeof webhookSecretGraceUntil === "number" ? webhookSecretGraceUntil : Date.parse(webhookSecretGraceUntil);
5716
+ if (Number.isNaN(until)) {
5717
+ throw new Error(`[OneAddress SDK] webhookSecretGraceUntil is not a date: ${String(webhookSecretGraceUntil)}`);
5718
+ }
5719
+ }
5720
+ if (confirm && (!confirm.partnerId || !confirm.confirmSecret)) {
5721
+ throw new Error("[OneAddress SDK] confirm needs both partnerId and confirmSecret");
5722
+ }
5723
+ function enforceLoaPresence(body) {
5724
+ const present = !!body.loa_encrypted && typeof body.loa_encrypted === "object";
5725
+ if (present) return;
5726
+ if (requireLoa) {
5727
+ throw new Error(
5728
+ "[OneAddress SDK] dispatch carries no loa_encrypted and requireLoa is on: refusing to apply an update whose consent proof is missing"
5729
+ );
5730
+ }
5731
+ if (!warnedConsentUnverified) {
5732
+ warnedConsentUnverified = true;
5733
+ console.warn(
5734
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
5735
+ "[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."
5736
+ );
5737
+ }
5738
+ }
5244
5739
  const acceptedUpdateTypes = normaliseAcceptedUpdateTypes(acceptedUpdateTypesRaw);
5245
5740
  function declared(status, payload) {
5246
5741
  return new Response(JSON.stringify({ ...payload, accepted_update_types: acceptedUpdateTypes }), {
@@ -5250,7 +5745,7 @@ function createOneAddressHandler(options) {
5250
5745
  }
5251
5746
  async function buildD5Pieces(body, partnerId) {
5252
5747
  const share = body.session_key_share;
5253
- const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId);
5748
+ const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId, expectedAlg);
5254
5749
  const updateTypes = readUpdateTypes(data.update_types);
5255
5750
  if (updateTypes === null) throw new InvalidUpdateTypesError(data.update_types);
5256
5751
  const address = updateTypes.includes("address") ? validateAddress({
@@ -5275,13 +5770,15 @@ function createOneAddressHandler(options) {
5275
5770
  loa = await decryptLoaEncrypted(
5276
5771
  body.loa_encrypted,
5277
5772
  privateKeyPem,
5278
- partnerId
5773
+ partnerId,
5774
+ expectedAlg
5279
5775
  );
5280
5776
  loa_ref = d5LoaRef(loa);
5281
5777
  if (loaPublicKeyPem) {
5282
5778
  const valid = await verifyD5LOA(loa, loaPublicKeyPem);
5283
5779
  if (!valid) throw new Error("D5 LOA signature verification failed");
5284
5780
  }
5781
+ assertLoaBoundToEnvelope(loa, data.update_uid);
5285
5782
  }
5286
5783
  return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
5287
5784
  }
@@ -5314,7 +5811,11 @@ function createOneAddressHandler(options) {
5314
5811
  }
5315
5812
  let body;
5316
5813
  try {
5317
- body = JSON.parse(rawBody);
5814
+ const parsed = JSON.parse(rawBody);
5815
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
5816
+ throw new TypeError("body is not a JSON object");
5817
+ }
5818
+ body = parsed;
5318
5819
  } catch {
5319
5820
  return new Response(JSON.stringify({ error: "Invalid JSON" }), {
5320
5821
  status: 400,
@@ -5336,11 +5837,19 @@ function createOneAddressHandler(options) {
5336
5837
  }
5337
5838
  if (dispatchId) {
5338
5839
  if (!idempotencyStore) {
5339
- if (process.env.NODE_ENV === "test") {
5840
+ const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
5841
+ if (nodeEnv === "test") {
5340
5842
  throw new Error(
5341
5843
  "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
5342
5844
  );
5343
5845
  }
5846
+ if (!warnedNoIdempotencyStore) {
5847
+ warnedNoIdempotencyStore = true;
5848
+ console.warn(
5849
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
5850
+ "[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."
5851
+ );
5852
+ }
5344
5853
  } else if (idempotencyStore.claim) {
5345
5854
  const claim = await idempotencyStore.claim(dispatchId);
5346
5855
  if (claim === "duplicate") {
@@ -5357,6 +5866,7 @@ function createOneAddressHandler(options) {
5357
5866
  if (body.event === "address.updated" || body.event === "contact.updated") {
5358
5867
  const wireEvent = body.event;
5359
5868
  let event;
5869
+ enforceLoaPresence(body);
5360
5870
  if (isD5Body(body)) {
5361
5871
  let d5;
5362
5872
  try {
@@ -5409,19 +5919,25 @@ function createOneAddressHandler(options) {
5409
5919
  });
5410
5920
  }
5411
5921
  const encrypted = body.address_encrypted;
5412
- const rawAddress = await decryptAddress2(encrypted, privateKeyPem, partnerId);
5922
+ const rawAddress = await decryptAddress2(
5923
+ encrypted,
5924
+ requirePemFor("legacy address_encrypted decryption", privateKeyPem),
5925
+ partnerId
5926
+ );
5413
5927
  let loa;
5414
5928
  let loa_ref;
5415
5929
  if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
5416
5930
  loa = await decryptLoaEncrypted(
5417
5931
  body.loa_encrypted,
5418
5932
  privateKeyPem,
5419
- partnerId
5933
+ partnerId,
5934
+ expectedAlg
5420
5935
  );
5421
5936
  loa_ref = d5LoaRef(loa);
5422
5937
  if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
5423
5938
  throw new Error("D5 LOA signature verification failed");
5424
5939
  }
5940
+ assertLoaBoundToEnvelope(loa, rawAddress.update_uid);
5425
5941
  }
5426
5942
  const customer = {
5427
5943
  email: "",
@@ -5454,6 +5970,25 @@ function createOneAddressHandler(options) {
5454
5970
  // NOSONAR
5455
5971
  );
5456
5972
  }
5973
+ if (confirm && dispatchId) {
5974
+ const status = result && typeof result === "object" && result.status ? result.status : "confirmed";
5975
+ void confirmUpdate({
5976
+ partnerId: confirm.partnerId,
5977
+ secret: confirm.confirmSecret,
5978
+ dispatchId,
5979
+ status,
5980
+ loaRef: event.loa_ref,
5981
+ ...confirm.oneAddressApi ? { appBaseUrl: confirm.oneAddressApi } : {},
5982
+ ...confirm.fetchImpl ? { fetchImpl: confirm.fetchImpl } : {}
5983
+ }).then(
5984
+ (r) => {
5985
+ if (!r.ok) console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} failed: HTTP ${r.status} ${r.error ?? ""}`);
5986
+ },
5987
+ // NOSONAR
5988
+ (err) => console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} threw:`, err)
5989
+ // NOSONAR
5990
+ );
5991
+ }
5457
5992
  return declared(200, { ok: true, ...result });
5458
5993
  }
5459
5994
  if (body.event === "address.verify" && onVerify) {
@@ -5464,7 +5999,11 @@ function createOneAddressHandler(options) {
5464
5999
  });
5465
6000
  }
5466
6001
  const encrypted = body.address_encrypted;
5467
- const rawAddress = await decryptAddress2(encrypted, privateKeyPem, partnerId);
6002
+ const rawAddress = await decryptAddress2(
6003
+ encrypted,
6004
+ requirePemFor("address.verify decryption", privateKeyPem),
6005
+ partnerId
6006
+ );
5468
6007
  const event = {
5469
6008
  event: "address.verify",
5470
6009
  version: body.oneaddress_version ?? body.version ?? "1",
@@ -5511,7 +6050,7 @@ function createOneAddressHandler(options) {
5511
6050
  if (body.customer_encrypted && typeof body.customer_encrypted === "object") {
5512
6051
  const raw = await decryptAddress2(
5513
6052
  body.customer_encrypted,
5514
- privateKeyPem,
6053
+ requirePemFor("account.verify decryption", privateKeyPem),
5515
6054
  partnerId
5516
6055
  );
5517
6056
  customer = {
@@ -5557,7 +6096,12 @@ function createOneAddressHandler(options) {
5557
6096
  address: d5.address,
5558
6097
  raw: d5.raw
5559
6098
  });
5560
- return declared(200, { ok: true, test: true });
6099
+ return declared(200, {
6100
+ ok: true,
6101
+ test: true,
6102
+ verification: true,
6103
+ index: typeof body.index === "number" ? body.index : void 0
6104
+ });
5561
6105
  }
5562
6106
  const evt = typeof body.event === "string" ? body.event : "(none)";
5563
6107
  const callbackFor = {
@@ -5630,12 +6174,120 @@ function toExpressHandler(handler) {
5630
6174
  res.send(bodyText);
5631
6175
  };
5632
6176
  }
6177
+ async function buildSignedTestWebhook(opts2) {
6178
+ const nowSecs = opts2.timestamp ?? Math.floor(Date.now() / 1e3);
6179
+ const nowIso = new Date(nowSecs * 1e3).toISOString();
6180
+ const updateIdNum = import_crypto.default.randomInt(9e8, 901e6);
6181
+ const updateUid = opts2.session?.update_uid ?? String(updateIdNum);
6182
+ const partnerKey = {
6183
+ partner_id: opts2.partnerId,
6184
+ key_id: opts2.keyId ?? "test-key-1",
6185
+ public_key_b64: pemToBase64(opts2.publicKey),
6186
+ algorithm: opts2.algorithm ?? "ECDH-P256-AES-GCM-256"
6187
+ };
6188
+ const kinds = readUpdateTypes(opts2.session?.update_types) ?? ["address"];
6189
+ const sessionData = {
6190
+ v: 2,
6191
+ update_uid: updateUid,
6192
+ dispatch_timestamp: nowIso,
6193
+ verified_name: "Test Person",
6194
+ ...kinds.includes("address") ? { new_address: { street: "42 Collins Street", suburb: "Melbourne", state: "VIC", postcode: "3000", country: "AU" } } : {},
6195
+ ...kinds.includes("phone") ? { new_phone: "+61412345678" } : {},
6196
+ ...kinds.includes("email") ? { new_email: "test.person@example.com" } : {},
6197
+ account_number: "TEST-0001",
6198
+ id_verification_ref: import_crypto.default.randomUUID(),
6199
+ known_names: [],
6200
+ ...opts2.session ?? {}
6201
+ };
6202
+ const envelope = await encryptSessionForPartner(sessionData, partnerKey);
6203
+ let loa;
6204
+ let loa_encrypted;
6205
+ if (opts2.loa !== false) {
6206
+ loa = {
6207
+ consumer_name: sessionData.verified_name,
6208
+ authorisation_date: nowIso,
6209
+ scope: "Authority to update address records on file.",
6210
+ update_uid: updateUid,
6211
+ oneaddress_acn: "696 078 869",
6212
+ oneaddress_signature: "00".repeat(64),
6213
+ signature_algorithm: "ECDSA-P256",
6214
+ ...opts2.loa ?? {}
6215
+ };
6216
+ if (opts2.loaSigningKeyPem) {
6217
+ const key = await import_crypto.default.subtle.importKey(
6218
+ "pkcs8",
6219
+ pemToBuffer(opts2.loaSigningKeyPem),
6220
+ { name: "ECDSA", namedCurve: "P-256" },
6221
+ false,
6222
+ ["sign"]
6223
+ );
6224
+ const sig2 = await import_crypto.default.subtle.sign(
6225
+ { name: "ECDSA", hash: "SHA-256" },
6226
+ key,
6227
+ new TextEncoder().encode(canonicalD5LoaForm(loa))
6228
+ );
6229
+ loa.oneaddress_signature = Buffer.from(sig2).toString("hex");
6230
+ }
6231
+ const sealed = await encryptEnvelopeForPartner(loa, partnerKey);
6232
+ loa_encrypted = { session_envelope: sealed.session_envelope, session_key_share: sealed.session_key_share };
6233
+ }
6234
+ const event = opts2.event ?? (kinds.includes("address") ? "address.updated" : "contact.updated");
6235
+ const body = JSON.stringify({
6236
+ event,
6237
+ oneaddress_version: CURRENT_VERSION,
6238
+ // A NUMBER. The relay sends `user_updates.id`; `update_uid` inside the
6239
+ // envelope and the LOA is its string form, which is the relationship a
6240
+ // receiver uses to bind the decrypted authorisation to the update.
6241
+ update_id: updateIdNum,
6242
+ partner_id: opts2.partnerId,
6243
+ user_id: opts2.userId ?? "test:consumer",
6244
+ timestamp: nowIso,
6245
+ session_envelope: envelope.session_envelope,
6246
+ session_key_share: envelope.session_key_share,
6247
+ key_share_expiry: new Date((nowSecs + 90 * 24 * 3600) * 1e3).toISOString(),
6248
+ id_verification: { method: "identity_document", verified_at: nowIso, verified: true, platform: "oneaddress/v1" },
6249
+ ...loa_encrypted ? { loa_encrypted } : {},
6250
+ // On the wire with a `null` value when no PaymentIntent backed the update,
6251
+ // so the KEY is present either way.
6252
+ stripe_session_id: opts2.stripeSessionId ?? null,
6253
+ // `id` and `crossover_key_ids` are crossover-only and therefore NOT emitted
6254
+ // by default. A test that needs them passes them through `extraBody`, which
6255
+ // is exactly the circumstance the relay emits them in.
6256
+ ...opts2.extraBody ?? {}
6257
+ });
6258
+ const ts = String(nowSecs);
6259
+ const sig = import_crypto.default.createHmac("sha256", opts2.webhookSecret).update(`${ts}.${body}`).digest("hex");
6260
+ const dispatchId = opts2.dispatchId ?? "1";
6261
+ const headers = {
6262
+ "Content-Type": "application/json",
6263
+ "X-OneAddress-Event": event,
6264
+ "X-OneAddress-Partner": opts2.partnerId,
6265
+ "X-OneAddress-Version": CURRENT_VERSION,
6266
+ "X-OneAddress-Timestamp": ts,
6267
+ "X-OneAddress-Signature": sig,
6268
+ ...dispatchId ? { "X-OneAddress-Dispatch": dispatchId } : {}
6269
+ };
6270
+ const lower = new Map(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]));
6271
+ return {
6272
+ body,
6273
+ headers,
6274
+ sessionData,
6275
+ loa,
6276
+ request: {
6277
+ text: async () => body,
6278
+ headers: { get: (name) => lower.get(name.toLowerCase()) ?? null }
6279
+ },
6280
+ toRequest: (url = "https://receiver.example/webhook") => new Request(url, { method: "POST", headers, body })
6281
+ };
6282
+ }
5633
6283
  // Annotate the CommonJS export names for ESM import in node:
5634
6284
  0 && (module.exports = {
5635
6285
  CURRENT_VERSION,
5636
6286
  DEFAULT_REPLAY_WINDOW_SECS,
5637
6287
  OUTBOX_LEASE_COLUMNS,
5638
6288
  SUPPORTED_VERSIONS,
6289
+ _resetOnceWarningsForTests,
6290
+ buildSignedTestWebhook,
5639
6291
  canonicalD5LoaForm,
5640
6292
  compareAddresses,
5641
6293
  computeBlindIndex,