@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/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,63 @@ 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
+
4787
+ // ../protocol/src/retention.ts
4788
+ var MIN_RETENTION_DAYS = 14;
4789
+ var MAX_RETENTION_DAYS = 365;
4790
+ var DEFAULT_RETENTION_DAYS = 90;
4791
+ function resolveRetentionDays(retentionPeriodDays) {
4792
+ if (typeof retentionPeriodDays !== "number" || !Number.isFinite(retentionPeriodDays)) {
4793
+ return DEFAULT_RETENTION_DAYS;
4794
+ }
4795
+ const days = Math.trunc(retentionPeriodDays);
4796
+ if (days < MIN_RETENTION_DAYS || days > MAX_RETENTION_DAYS) return DEFAULT_RETENTION_DAYS;
4797
+ return days;
4798
+ }
4799
+ var DAY_MS = 24 * 60 * 60 * 1e3;
4800
+ function keyShareExpiryIso(dispatchAt, retentionPeriodDays) {
4801
+ const days = resolveRetentionDays(retentionPeriodDays);
4802
+ return new Date(dispatchAt.getTime() + days * DAY_MS).toISOString();
4803
+ }
4804
+
4441
4805
  // src/index.ts
4442
4806
  init_src();
4443
4807
  init_src();
@@ -4564,9 +4928,17 @@ function createOutboxConsumer(opts2) {
4564
4928
  if (!Number.isFinite(batchSize) || batchSize < 1) {
4565
4929
  throw new Error(`[OneAddress SDK] batchSize must be a positive integer, got ${opts2.batchSize}`);
4566
4930
  }
4931
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 0) {
4932
+ throw new Error(`[OneAddress SDK] maxAttempts must be an integer >= 0, got ${opts2.maxAttempts}`);
4933
+ }
4567
4934
  const ph = d.ph;
4568
4935
  const token = () => (0, import_node_crypto.randomBytes)(16).toString("hex");
4569
4936
  const stamp = (at) => toOutboxTimestamp(dialect, at);
4937
+ const heldTokens = /* @__PURE__ */ new Map();
4938
+ const claimPredicate = (dispatchId, firstPh) => {
4939
+ const tok = heldTokens.get(dispatchId);
4940
+ 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] };
4941
+ };
4570
4942
  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
4943
  const toRow = (r) => ({
4572
4944
  dispatchId: String(r.dispatch_id ?? r.dispatchId ?? ""),
@@ -4574,6 +4946,10 @@ function createOutboxConsumer(opts2) {
4574
4946
  attempts: Number(r[ATTEMPTS] ?? 0) || 0,
4575
4947
  fields: r
4576
4948
  });
4949
+ const claimed = (rows, tok) => rows.map(toRow).map((row) => {
4950
+ heldTokens.set(row.dispatchId, tok);
4951
+ return row;
4952
+ });
4577
4953
  async function claimBatch() {
4578
4954
  const at = now();
4579
4955
  const claimedAt = stamp(at);
@@ -4584,14 +4960,14 @@ function createOutboxConsumer(opts2) {
4584
4960
  `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
4961
  [claimedAt, tok, cutoff]
4586
4962
  );
4587
- return rows2.map(toRow);
4963
+ return claimed(rows2, tok);
4588
4964
  }
4589
4965
  if (dialect === "mssql") {
4590
4966
  const rows2 = await opts2.query(
4591
4967
  `UPDATE TOP (${batchSize}) ${table} WITH (UPDLOCK, READPAST, ROWLOCK) SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} OUTPUT INSERTED.* WHERE ${claimable(ph(3))}`,
4592
4968
  [claimedAt, tok, cutoff]
4593
4969
  );
4594
- return rows2.map(toRow);
4970
+ return claimed(rows2, tok);
4595
4971
  }
4596
4972
  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
4973
  await opts2.query(claim, [claimedAt, tok, cutoff]);
@@ -4599,7 +4975,7 @@ function createOutboxConsumer(opts2) {
4599
4975
  `SELECT * FROM ${table} WHERE ${CLAIM_TOKEN} = ${ph(1)} AND processed_at IS NULL`,
4600
4976
  [tok]
4601
4977
  );
4602
- return rows.map(toRow);
4978
+ return claimed(rows, tok);
4603
4979
  }
4604
4980
  return {
4605
4981
  async ensureSchema() {
@@ -4628,23 +5004,29 @@ function createOutboxConsumer(opts2) {
4628
5004
  },
4629
5005
  claimBatch,
4630
5006
  async markProcessed(dispatchId) {
5007
+ const where = claimPredicate(dispatchId, 2);
4631
5008
  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]
5009
+ `UPDATE ${table} SET processed_at = ${ph(1)}, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
5010
+ [stamp(now()), ...where.params]
4634
5011
  );
5012
+ heldTokens.delete(dispatchId);
4635
5013
  },
4636
5014
  async markFailed(dispatchId, error) {
4637
5015
  const message = error instanceof Error ? error.message : String(error);
5016
+ const where = claimPredicate(dispatchId, 2);
4638
5017
  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]
5018
+ `UPDATE ${table} SET processing_error = ${ph(1)}, ${ATTEMPTS} = COALESCE(${ATTEMPTS}, 0) + 1, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
5019
+ [message.slice(0, 500), ...where.params]
4641
5020
  );
5021
+ heldTokens.delete(dispatchId);
4642
5022
  },
4643
5023
  async release(dispatchId) {
5024
+ const where = claimPredicate(dispatchId, 1);
4644
5025
  await opts2.query(
4645
- `UPDATE ${table} SET ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(1)}`,
4646
- [dispatchId]
5026
+ `UPDATE ${table} SET ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
5027
+ where.params
4647
5028
  );
5029
+ heldTokens.delete(dispatchId);
4648
5030
  },
4649
5031
  async process(handler) {
4650
5032
  const rows = await claimBatch();
@@ -4685,15 +5067,62 @@ function createOutboxConsumer(opts2) {
4685
5067
  }
4686
5068
 
4687
5069
  // src/index.ts
5070
+ var IDEMPOTENCY_DIALECTS = ["postgres", "sqlite", "mysql", "mssql"];
4688
5071
  function createSqlIdempotencyStore(opts2) {
4689
5072
  const table = opts2.table ?? "oneaddress_dispatches";
4690
- const ph = opts2.placeholder ?? ((n) => `$${n}`);
5073
+ const dialect = opts2.dialect ?? "postgres";
5074
+ if (!IDEMPOTENCY_DIALECTS.includes(dialect)) {
5075
+ throw new Error(
5076
+ `[OneAddress SDK] createSqlIdempotencyStore: unknown dialect "${dialect}". Supported: ${IDEMPOTENCY_DIALECTS.join(", ")}.`
5077
+ );
5078
+ }
5079
+ const defaultPh = dialect === "postgres" ? (n) => `$${n}` : dialect === "mssql" ? (n) => `@p${n}` : () => "?";
5080
+ const ph = opts2.placeholder ?? defaultPh;
4691
5081
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
4692
5082
  throw new Error(`[OneAddress SDK] invalid table name: ${table}`);
4693
5083
  }
4694
5084
  const completedOf = (row) => row?.completed_at ?? row?.completedAt ?? null;
5085
+ const tokenOf = (row) => row?.claim_token ?? row?.claimToken ?? null;
5086
+ async function claimByToken(dispatchId) {
5087
+ const token = import_crypto.default.randomBytes(16).toString("hex");
5088
+ await opts2.query(
5089
+ 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)})`,
5090
+ [dispatchId, token]
5091
+ );
5092
+ const rows = await opts2.query(
5093
+ `SELECT claim_token, completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
5094
+ [dispatchId]
5095
+ );
5096
+ if (tokenOf(rows[0]) === token) return "fresh";
5097
+ return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
5098
+ }
5099
+ async function setByUpsert(dispatchId) {
5100
+ if (dialect === "mysql") {
5101
+ await opts2.query(
5102
+ `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE completed_at = CURRENT_TIMESTAMP`,
5103
+ [dispatchId]
5104
+ );
5105
+ return;
5106
+ }
5107
+ if (dialect === "mssql") {
5108
+ await opts2.query(
5109
+ `UPDATE ${table} SET completed_at = CURRENT_TIMESTAMP WHERE dispatch_id = ${ph(1)}`,
5110
+ [dispatchId]
5111
+ );
5112
+ await opts2.query(
5113
+ `INSERT INTO ${table} (dispatch_id, completed_at) SELECT ${ph(1)}, CURRENT_TIMESTAMP WHERE NOT EXISTS (SELECT 1 FROM ${table} WHERE dispatch_id = ${ph(1)})`,
5114
+ [dispatchId]
5115
+ );
5116
+ return;
5117
+ }
5118
+ await opts2.query(
5119
+ `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON CONFLICT (dispatch_id) DO UPDATE SET completed_at = CURRENT_TIMESTAMP`,
5120
+ [dispatchId]
5121
+ );
5122
+ }
4695
5123
  return {
4696
5124
  async claim(dispatchId) {
5125
+ if (dialect === "mysql" || dialect === "mssql") return claimByToken(dispatchId);
4697
5126
  const inserted = await opts2.query(
4698
5127
  `INSERT INTO ${table} (dispatch_id) VALUES (${ph(1)}) ON CONFLICT (dispatch_id) DO NOTHING RETURNING dispatch_id`,
4699
5128
  [dispatchId]
@@ -4721,10 +5150,7 @@ function createSqlIdempotencyStore(opts2) {
4721
5150
  return rows.length > 0 && Boolean(completedOf(rows[0]));
4722
5151
  },
4723
5152
  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
- );
5153
+ await setByUpsert(dispatchId);
4728
5154
  }
4729
5155
  };
4730
5156
  }
@@ -4750,7 +5176,8 @@ function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousS
4750
5176
  function base64urlToBuffer(b64) {
4751
5177
  return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
4752
5178
  }
4753
- function pemToBase64(pem) {
5179
+ function pemToBase64(pemRaw) {
5180
+ const pem = pemRaw.replace(/(?:\\r)?\\n/g, "\n");
4754
5181
  const begin = pem.indexOf("-----BEGIN");
4755
5182
  if (begin === -1) return pem.replace(/\s/g, "");
4756
5183
  const armourEnd = pem.indexOf("-----", begin + "-----BEGIN".length);
@@ -4958,6 +5385,10 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
4958
5385
  `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...allowedHosts].join(", ")}`
4959
5386
  );
4960
5387
  }
5388
+ const loopback = parsedBase.hostname === "localhost" || parsedBase.hostname === "127.0.0.1";
5389
+ if (parsedBase.protocol !== "https:" && !loopback) {
5390
+ throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl must use https (plain http is accepted for localhost only)");
5391
+ }
4961
5392
  const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
4962
5393
  const res = await fetch(url);
4963
5394
  if (!res.ok) {
@@ -5034,12 +5465,13 @@ async function verifyD5LOA(loa, publicKeyPem) {
5034
5465
  return false;
5035
5466
  }
5036
5467
  }
5037
- async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId) {
5468
+ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId, expectedAlg) {
5038
5469
  const data = await decryptSession2(
5039
5470
  loaEncrypted.session_key_share,
5040
5471
  loaEncrypted.session_envelope,
5041
5472
  privateKeyPem,
5042
- partnerId
5473
+ partnerId,
5474
+ expectedAlg
5043
5475
  );
5044
5476
  return data;
5045
5477
  }
@@ -5224,14 +5656,61 @@ function requireContactValue(kind, value) {
5224
5656
  }
5225
5657
  var HANDLED_EVENTS = ["address.updated", "contact.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
5226
5658
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
5659
+ var warnedConsentUnverified = false;
5660
+ var warnedNoIdempotencyStore = false;
5661
+ function _resetOnceWarningsForTests() {
5662
+ warnedConsentUnverified = false;
5663
+ warnedNoIdempotencyStore = false;
5664
+ }
5665
+ var MAX_TIMESTAMP_TOLERANCE_SECS = 86400;
5666
+ var XWING_SEED_BYTES = 32;
5667
+ function assertUsablePrivateKey(privateKeyPem) {
5668
+ if (typeof privateKeyPem !== "string") {
5669
+ if (!privateKeyPem || typeof privateKeyPem !== "object" || typeof privateKeyPem.name !== "string") {
5670
+ throw new Error("[OneAddress SDK] privateKeyPem must be a PEM string or a PrivateKeyOperations delegate");
5671
+ }
5672
+ return;
5673
+ }
5674
+ if (privateKeyPem.trim() === "") {
5675
+ throw new Error("[OneAddress SDK] privateKeyPem is required: set it to your PKCS#8 private key from the Partner Portal");
5676
+ }
5677
+ const der = pemToBuffer(privateKeyPem);
5678
+ if (der.length === XWING_SEED_BYTES) return;
5679
+ try {
5680
+ import_crypto.default.createPrivateKey({ key: der, format: "der", type: "pkcs8" });
5681
+ } catch (err) {
5682
+ const refused = new Error(
5683
+ `[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.`
5684
+ );
5685
+ refused.cause = err;
5686
+ throw refused;
5687
+ }
5688
+ }
5689
+ function requirePemFor(purpose, key) {
5690
+ if (typeof key === "string") return key;
5691
+ throw new Error(
5692
+ `[OneAddress SDK] ${purpose} needs the raw private key; a PrivateKeyOperations delegate ("${key.name}") covers session envelopes only`
5693
+ );
5694
+ }
5695
+ function assertLoaBoundToEnvelope(loa, envelopeUpdateUid) {
5696
+ if (typeof loa.update_uid !== "string" || typeof envelopeUpdateUid !== "string") return;
5697
+ if (loa.update_uid !== envelopeUpdateUid) {
5698
+ throw new Error(
5699
+ "[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"
5700
+ );
5701
+ }
5702
+ }
5227
5703
  function createOneAddressHandler(options) {
5228
5704
  const {
5229
5705
  webhookSecret,
5230
5706
  previousWebhookSecret,
5231
5707
  webhookSecretGraceUntil,
5232
5708
  privateKeyPem,
5709
+ expectedAlg,
5233
5710
  keyId,
5234
5711
  loaPublicKeyPem,
5712
+ requireLoa = Boolean(loaPublicKeyPem),
5713
+ confirm,
5235
5714
  onUpdate,
5236
5715
  onVerify,
5237
5716
  onAccountVerify,
@@ -5241,6 +5720,40 @@ function createOneAddressHandler(options) {
5241
5720
  acceptedUpdateTypes: acceptedUpdateTypesRaw,
5242
5721
  allowedCallbackHosts
5243
5722
  } = options;
5723
+ if (typeof webhookSecret !== "string" || webhookSecret === "") {
5724
+ throw new Error("[OneAddress SDK] webhookSecret is required: an empty secret would verify no signature at all");
5725
+ }
5726
+ assertUsablePrivateKey(privateKeyPem);
5727
+ if (typeof timestampToleranceSecs !== "number" || !Number.isFinite(timestampToleranceSecs) || timestampToleranceSecs <= 0 || timestampToleranceSecs > MAX_TIMESTAMP_TOLERANCE_SECS) {
5728
+ throw new Error(
5729
+ `[OneAddress SDK] timestampToleranceSecs must be a positive number of seconds up to ${MAX_TIMESTAMP_TOLERANCE_SECS}, got ${String(timestampToleranceSecs)}`
5730
+ );
5731
+ }
5732
+ if (webhookSecretGraceUntil !== void 0) {
5733
+ const until = typeof webhookSecretGraceUntil === "number" ? webhookSecretGraceUntil : Date.parse(webhookSecretGraceUntil);
5734
+ if (Number.isNaN(until)) {
5735
+ throw new Error(`[OneAddress SDK] webhookSecretGraceUntil is not a date: ${String(webhookSecretGraceUntil)}`);
5736
+ }
5737
+ }
5738
+ if (confirm && (!confirm.partnerId || !confirm.confirmSecret)) {
5739
+ throw new Error("[OneAddress SDK] confirm needs both partnerId and confirmSecret");
5740
+ }
5741
+ function enforceLoaPresence(body) {
5742
+ const present = !!body.loa_encrypted && typeof body.loa_encrypted === "object";
5743
+ if (present) return;
5744
+ if (requireLoa) {
5745
+ throw new Error(
5746
+ "[OneAddress SDK] dispatch carries no loa_encrypted and requireLoa is on: refusing to apply an update whose consent proof is missing"
5747
+ );
5748
+ }
5749
+ if (!warnedConsentUnverified) {
5750
+ warnedConsentUnverified = true;
5751
+ console.warn(
5752
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
5753
+ "[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."
5754
+ );
5755
+ }
5756
+ }
5244
5757
  const acceptedUpdateTypes = normaliseAcceptedUpdateTypes(acceptedUpdateTypesRaw);
5245
5758
  function declared(status, payload) {
5246
5759
  return new Response(JSON.stringify({ ...payload, accepted_update_types: acceptedUpdateTypes }), {
@@ -5250,7 +5763,7 @@ function createOneAddressHandler(options) {
5250
5763
  }
5251
5764
  async function buildD5Pieces(body, partnerId) {
5252
5765
  const share = body.session_key_share;
5253
- const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId);
5766
+ const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId, expectedAlg);
5254
5767
  const updateTypes = readUpdateTypes(data.update_types);
5255
5768
  if (updateTypes === null) throw new InvalidUpdateTypesError(data.update_types);
5256
5769
  const address = updateTypes.includes("address") ? validateAddress({
@@ -5275,13 +5788,15 @@ function createOneAddressHandler(options) {
5275
5788
  loa = await decryptLoaEncrypted(
5276
5789
  body.loa_encrypted,
5277
5790
  privateKeyPem,
5278
- partnerId
5791
+ partnerId,
5792
+ expectedAlg
5279
5793
  );
5280
5794
  loa_ref = d5LoaRef(loa);
5281
5795
  if (loaPublicKeyPem) {
5282
5796
  const valid = await verifyD5LOA(loa, loaPublicKeyPem);
5283
5797
  if (!valid) throw new Error("D5 LOA signature verification failed");
5284
5798
  }
5799
+ assertLoaBoundToEnvelope(loa, data.update_uid);
5285
5800
  }
5286
5801
  return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
5287
5802
  }
@@ -5314,7 +5829,11 @@ function createOneAddressHandler(options) {
5314
5829
  }
5315
5830
  let body;
5316
5831
  try {
5317
- body = JSON.parse(rawBody);
5832
+ const parsed = JSON.parse(rawBody);
5833
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
5834
+ throw new TypeError("body is not a JSON object");
5835
+ }
5836
+ body = parsed;
5318
5837
  } catch {
5319
5838
  return new Response(JSON.stringify({ error: "Invalid JSON" }), {
5320
5839
  status: 400,
@@ -5336,11 +5855,19 @@ function createOneAddressHandler(options) {
5336
5855
  }
5337
5856
  if (dispatchId) {
5338
5857
  if (!idempotencyStore) {
5339
- if (process.env.NODE_ENV === "test") {
5858
+ const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
5859
+ if (nodeEnv === "test") {
5340
5860
  throw new Error(
5341
5861
  "[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
5862
  );
5343
5863
  }
5864
+ if (!warnedNoIdempotencyStore) {
5865
+ warnedNoIdempotencyStore = true;
5866
+ console.warn(
5867
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
5868
+ "[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."
5869
+ );
5870
+ }
5344
5871
  } else if (idempotencyStore.claim) {
5345
5872
  const claim = await idempotencyStore.claim(dispatchId);
5346
5873
  if (claim === "duplicate") {
@@ -5357,6 +5884,7 @@ function createOneAddressHandler(options) {
5357
5884
  if (body.event === "address.updated" || body.event === "contact.updated") {
5358
5885
  const wireEvent = body.event;
5359
5886
  let event;
5887
+ enforceLoaPresence(body);
5360
5888
  if (isD5Body(body)) {
5361
5889
  let d5;
5362
5890
  try {
@@ -5409,19 +5937,25 @@ function createOneAddressHandler(options) {
5409
5937
  });
5410
5938
  }
5411
5939
  const encrypted = body.address_encrypted;
5412
- const rawAddress = await decryptAddress2(encrypted, privateKeyPem, partnerId);
5940
+ const rawAddress = await decryptAddress2(
5941
+ encrypted,
5942
+ requirePemFor("legacy address_encrypted decryption", privateKeyPem),
5943
+ partnerId
5944
+ );
5413
5945
  let loa;
5414
5946
  let loa_ref;
5415
5947
  if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
5416
5948
  loa = await decryptLoaEncrypted(
5417
5949
  body.loa_encrypted,
5418
5950
  privateKeyPem,
5419
- partnerId
5951
+ partnerId,
5952
+ expectedAlg
5420
5953
  );
5421
5954
  loa_ref = d5LoaRef(loa);
5422
5955
  if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
5423
5956
  throw new Error("D5 LOA signature verification failed");
5424
5957
  }
5958
+ assertLoaBoundToEnvelope(loa, rawAddress.update_uid);
5425
5959
  }
5426
5960
  const customer = {
5427
5961
  email: "",
@@ -5454,6 +5988,25 @@ function createOneAddressHandler(options) {
5454
5988
  // NOSONAR
5455
5989
  );
5456
5990
  }
5991
+ if (confirm && dispatchId) {
5992
+ const status = result && typeof result === "object" && result.status ? result.status : "confirmed";
5993
+ void confirmUpdate({
5994
+ partnerId: confirm.partnerId,
5995
+ secret: confirm.confirmSecret,
5996
+ dispatchId,
5997
+ status,
5998
+ loaRef: event.loa_ref,
5999
+ ...confirm.oneAddressApi ? { appBaseUrl: confirm.oneAddressApi } : {},
6000
+ ...confirm.fetchImpl ? { fetchImpl: confirm.fetchImpl } : {}
6001
+ }).then(
6002
+ (r) => {
6003
+ if (!r.ok) console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} failed: HTTP ${r.status} ${r.error ?? ""}`);
6004
+ },
6005
+ // NOSONAR
6006
+ (err) => console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} threw:`, err)
6007
+ // NOSONAR
6008
+ );
6009
+ }
5457
6010
  return declared(200, { ok: true, ...result });
5458
6011
  }
5459
6012
  if (body.event === "address.verify" && onVerify) {
@@ -5464,7 +6017,11 @@ function createOneAddressHandler(options) {
5464
6017
  });
5465
6018
  }
5466
6019
  const encrypted = body.address_encrypted;
5467
- const rawAddress = await decryptAddress2(encrypted, privateKeyPem, partnerId);
6020
+ const rawAddress = await decryptAddress2(
6021
+ encrypted,
6022
+ requirePemFor("address.verify decryption", privateKeyPem),
6023
+ partnerId
6024
+ );
5468
6025
  const event = {
5469
6026
  event: "address.verify",
5470
6027
  version: body.oneaddress_version ?? body.version ?? "1",
@@ -5511,7 +6068,7 @@ function createOneAddressHandler(options) {
5511
6068
  if (body.customer_encrypted && typeof body.customer_encrypted === "object") {
5512
6069
  const raw = await decryptAddress2(
5513
6070
  body.customer_encrypted,
5514
- privateKeyPem,
6071
+ requirePemFor("account.verify decryption", privateKeyPem),
5515
6072
  partnerId
5516
6073
  );
5517
6074
  customer = {
@@ -5557,7 +6114,12 @@ function createOneAddressHandler(options) {
5557
6114
  address: d5.address,
5558
6115
  raw: d5.raw
5559
6116
  });
5560
- return declared(200, { ok: true, test: true });
6117
+ return declared(200, {
6118
+ ok: true,
6119
+ test: true,
6120
+ verification: true,
6121
+ index: typeof body.index === "number" ? body.index : void 0
6122
+ });
5561
6123
  }
5562
6124
  const evt = typeof body.event === "string" ? body.event : "(none)";
5563
6125
  const callbackFor = {
@@ -5630,12 +6192,121 @@ function toExpressHandler(handler) {
5630
6192
  res.send(bodyText);
5631
6193
  };
5632
6194
  }
6195
+ async function buildSignedTestWebhook(opts2) {
6196
+ const nowSecs = opts2.timestamp ?? Math.floor(Date.now() / 1e3);
6197
+ const nowIso = new Date(nowSecs * 1e3).toISOString();
6198
+ const updateIdNum = import_crypto.default.randomInt(9e8, 901e6);
6199
+ const updateUid = opts2.session?.update_uid ?? String(updateIdNum);
6200
+ const partnerKey = {
6201
+ partner_id: opts2.partnerId,
6202
+ key_id: opts2.keyId ?? "test-key-1",
6203
+ public_key_b64: pemToBase64(opts2.publicKey),
6204
+ algorithm: opts2.algorithm ?? "ECDH-P256-AES-GCM-256"
6205
+ };
6206
+ const kinds = readUpdateTypes(opts2.session?.update_types) ?? ["address"];
6207
+ const sessionData = {
6208
+ v: 2,
6209
+ update_uid: updateUid,
6210
+ dispatch_timestamp: nowIso,
6211
+ verified_name: "Test Person",
6212
+ ...kinds.includes("address") ? { new_address: { street: "42 Collins Street", suburb: "Melbourne", state: "VIC", postcode: "3000", country: "AU" } } : {},
6213
+ ...kinds.includes("phone") ? { new_phone: "+61412345678" } : {},
6214
+ ...kinds.includes("email") ? { new_email: "test.person@example.com" } : {},
6215
+ account_number: "TEST-0001",
6216
+ id_verification_ref: import_crypto.default.randomUUID(),
6217
+ known_names: [],
6218
+ ...opts2.session ?? {}
6219
+ };
6220
+ const envelope = await encryptSessionForPartner(sessionData, partnerKey);
6221
+ let loa;
6222
+ let loa_encrypted;
6223
+ if (opts2.loa !== false) {
6224
+ loa = {
6225
+ consumer_name: sessionData.verified_name,
6226
+ authorisation_date: nowIso,
6227
+ scope: "Authority to update address records on file.",
6228
+ update_uid: updateUid,
6229
+ oneaddress_acn: "696 078 869",
6230
+ oneaddress_signature: "00".repeat(64),
6231
+ signature_algorithm: "ECDSA-P256",
6232
+ ...opts2.loa ?? {}
6233
+ };
6234
+ if (opts2.loaSigningKeyPem) {
6235
+ const key = await import_crypto.default.subtle.importKey(
6236
+ "pkcs8",
6237
+ pemToBuffer(opts2.loaSigningKeyPem),
6238
+ { name: "ECDSA", namedCurve: "P-256" },
6239
+ false,
6240
+ ["sign"]
6241
+ );
6242
+ const sig2 = await import_crypto.default.subtle.sign(
6243
+ { name: "ECDSA", hash: "SHA-256" },
6244
+ key,
6245
+ new TextEncoder().encode(canonicalD5LoaForm(loa))
6246
+ );
6247
+ loa.oneaddress_signature = Buffer.from(sig2).toString("hex");
6248
+ }
6249
+ const sealed = await encryptEnvelopeForPartner(loa, partnerKey);
6250
+ loa_encrypted = { session_envelope: sealed.session_envelope, session_key_share: sealed.session_key_share };
6251
+ }
6252
+ const event = opts2.event ?? (kinds.includes("address") ? "address.updated" : "contact.updated");
6253
+ const body = JSON.stringify({
6254
+ event,
6255
+ oneaddress_version: CURRENT_VERSION,
6256
+ // A NUMBER. The relay sends `user_updates.id`; `update_uid` inside the
6257
+ // envelope and the LOA is its string form, which is the relationship a
6258
+ // receiver uses to bind the decrypted authorisation to the update.
6259
+ update_id: updateIdNum,
6260
+ partner_id: opts2.partnerId,
6261
+ user_id: opts2.userId ?? "test:consumer",
6262
+ timestamp: nowIso,
6263
+ session_envelope: envelope.session_envelope,
6264
+ session_key_share: envelope.session_key_share,
6265
+ // Per RECIPIENT, from the same resolver the relay uses, not a constant.
6266
+ key_share_expiry: keyShareExpiryIso(new Date(nowSecs * 1e3), opts2.retentionPeriodDays),
6267
+ id_verification: { method: "identity_document", verified_at: nowIso, verified: true, platform: "oneaddress/v1" },
6268
+ ...loa_encrypted ? { loa_encrypted } : {},
6269
+ // On the wire with a `null` value when no PaymentIntent backed the update,
6270
+ // so the KEY is present either way.
6271
+ stripe_session_id: opts2.stripeSessionId ?? null,
6272
+ // `id` and `crossover_key_ids` are crossover-only and therefore NOT emitted
6273
+ // by default. A test that needs them passes them through `extraBody`, which
6274
+ // is exactly the circumstance the relay emits them in.
6275
+ ...opts2.extraBody ?? {}
6276
+ });
6277
+ const ts = String(nowSecs);
6278
+ const sig = import_crypto.default.createHmac("sha256", opts2.webhookSecret).update(`${ts}.${body}`).digest("hex");
6279
+ const dispatchId = opts2.dispatchId ?? "1";
6280
+ const headers = {
6281
+ "Content-Type": "application/json",
6282
+ "X-OneAddress-Event": event,
6283
+ "X-OneAddress-Partner": opts2.partnerId,
6284
+ "X-OneAddress-Version": CURRENT_VERSION,
6285
+ "X-OneAddress-Timestamp": ts,
6286
+ "X-OneAddress-Signature": sig,
6287
+ ...dispatchId ? { "X-OneAddress-Dispatch": dispatchId } : {}
6288
+ };
6289
+ const lower = new Map(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]));
6290
+ return {
6291
+ body,
6292
+ headers,
6293
+ sessionData,
6294
+ loa,
6295
+ request: {
6296
+ text: async () => body,
6297
+ headers: { get: (name) => lower.get(name.toLowerCase()) ?? null }
6298
+ },
6299
+ toRequest: (url = "https://receiver.example/webhook") => new Request(url, { method: "POST", headers, body })
6300
+ };
6301
+ }
5633
6302
  // Annotate the CommonJS export names for ESM import in node:
5634
6303
  0 && (module.exports = {
5635
6304
  CURRENT_VERSION,
5636
6305
  DEFAULT_REPLAY_WINDOW_SECS,
5637
6306
  OUTBOX_LEASE_COLUMNS,
5638
6307
  SUPPORTED_VERSIONS,
6308
+ _resetOnceWarningsForTests,
6309
+ buildSignedTestWebhook,
5639
6310
  canonicalD5LoaForm,
5640
6311
  compareAddresses,
5641
6312
  computeBlindIndex,