@oneaddress/partner-sdk 2.7.0 → 2.8.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
@@ -4146,6 +4146,69 @@ function isBlockedIPv4(host) {
4146
4146
  if (a === 192 && b === 168) return true;
4147
4147
  if (a === 169 && b === 254) return true;
4148
4148
  if (a === 100 && b >= 64 && b <= 127) return true;
4149
+ const c = octets[2];
4150
+ if (a === 192 && b === 0 && c === 0) return true;
4151
+ if (a === 198 && (b === 18 || b === 19)) return true;
4152
+ if (a >= 224 && a <= 239) return true;
4153
+ if (a >= 240) return true;
4154
+ return false;
4155
+ }
4156
+ function expandIPv6(clean2) {
4157
+ let text = clean2;
4158
+ const tail = [];
4159
+ const dotted = /^(.*:)(\d+\.\d+\.\d+\.\d+)$/.exec(text);
4160
+ if (dotted) {
4161
+ const parts = dotted[2].split(".").map((x) => Number.parseInt(x, 10));
4162
+ if (parts.some((x) => !Number.isInteger(x) || x > 255)) return null;
4163
+ tail.push(parts[0] << 8 | parts[1], parts[2] << 8 | parts[3]);
4164
+ text = dotted[1].endsWith("::") ? dotted[1] : dotted[1].slice(0, -1);
4165
+ }
4166
+ const halves = text.split("::");
4167
+ if (halves.length > 2) return null;
4168
+ const parse = (s) => {
4169
+ if (s === "") return [];
4170
+ const out = [];
4171
+ for (const g of s.split(":")) {
4172
+ if (!/^[0-9a-f]{1,4}$/.test(g)) return null;
4173
+ out.push(Number.parseInt(g, 16));
4174
+ }
4175
+ return out;
4176
+ };
4177
+ const head = parse(halves[0]);
4178
+ const rest = halves.length === 2 ? parse(halves[1]) : [];
4179
+ if (!head || !rest) return null;
4180
+ const known = head.length + rest.length + tail.length;
4181
+ if (halves.length === 1) {
4182
+ return known === 8 ? [...head, ...tail] : null;
4183
+ }
4184
+ if (known > 7) return null;
4185
+ return [...head, ...new Array(8 - known).fill(0), ...rest, ...tail];
4186
+ }
4187
+ function v4FromGroups(high, low) {
4188
+ return `${high >> 8 & 255}.${high & 255}.${low >> 8 & 255}.${low & 255}`;
4189
+ }
4190
+ function isBlockedIPv6Groups(g) {
4191
+ const first = g[0];
4192
+ if ((first & 65280) === 65280) return true;
4193
+ if ((first & 65472) === 65152) return true;
4194
+ if ((first & 65472) === 65216) return true;
4195
+ if ((first & 65024) === 64512) return true;
4196
+ if (first === 8194) return isBlockedIPv4(v4FromGroups(g[1], g[2]));
4197
+ if (first === 100 && g[1] === 65435) {
4198
+ if (g[2] === 0 && g[3] === 0 && g[4] === 0 && g[5] === 0) return isBlockedIPv4(v4FromGroups(g[6], g[7]));
4199
+ if (g[2] === 1) return isBlockedIPv4(v4FromGroups(g[6], g[7]));
4200
+ return true;
4201
+ }
4202
+ if (g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 0) {
4203
+ if (g[5] === 65535 || g[5] === 0) {
4204
+ if (g[5] === 0 && g[6] === 0 && g[7] <= 1) return true;
4205
+ return isBlockedIPv4(v4FromGroups(g[6], g[7]));
4206
+ }
4207
+ return true;
4208
+ }
4209
+ if (g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 65535 && g[5] === 0) {
4210
+ return isBlockedIPv4(v4FromGroups(g[6], g[7]));
4211
+ }
4149
4212
  return false;
4150
4213
  }
4151
4214
  function v4FromHexPair(highHex, lowHex) {
@@ -4165,6 +4228,9 @@ function isBlockedIPv6(host) {
4165
4228
  }
4166
4229
  clean2 = clean2.split("%")[0];
4167
4230
  if (!clean2.includes(":")) return false;
4231
+ const groups = expandIPv6(clean2);
4232
+ if (!groups) return true;
4233
+ if (isBlockedIPv6Groups(groups)) return true;
4168
4234
  if (clean2 === "::1") return true;
4169
4235
  if (clean2 === "::") return true;
4170
4236
  if (clean2.startsWith("fe80:")) return true;
@@ -4548,12 +4614,26 @@ function hexToBytes4(hex) {
4548
4614
  }
4549
4615
  return out;
4550
4616
  }
4617
+ function mapsAreCanonical(doc) {
4618
+ const canonical = (s) => typeof s === "string" && s === s.toLowerCase();
4619
+ for (const [partnerId, keyId] of Object.entries(doc.heads)) {
4620
+ if (!canonical(partnerId) || !canonical(keyId)) return false;
4621
+ }
4622
+ if (doc.staged === void 0) return true;
4623
+ if (!doc.staged || typeof doc.staged !== "object" || Array.isArray(doc.staged)) return false;
4624
+ for (const [partnerId, entry] of Object.entries(doc.staged)) {
4625
+ if (!canonical(partnerId) || !entry || typeof entry !== "object") return false;
4626
+ if (!canonical(entry.key_id) || !canonical(entry.key_sha256)) return false;
4627
+ }
4628
+ return true;
4629
+ }
4551
4630
  async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date()) {
4552
4631
  try {
4553
4632
  if (!doc || !KNOWN_VERSIONS.has(doc.version)) return "malformed";
4554
4633
  if (doc.algorithm !== REGISTRY_HEAD_ALG) return "malformed";
4555
4634
  if (typeof doc.signature !== "string" || !/^[0-9a-f]{128}$/i.test(doc.signature)) return "malformed";
4556
4635
  if (!doc.heads || typeof doc.heads !== "object") return "malformed";
4636
+ if (!mapsAreCanonical(doc)) return "malformed";
4557
4637
  const expires = Date.parse(doc.expires_at);
4558
4638
  const issued = Date.parse(doc.issued_at);
4559
4639
  if (Number.isNaN(expires) || Number.isNaN(issued)) return "malformed";
@@ -5720,12 +5800,26 @@ var init_src = __esm({
5720
5800
  var index_exports = {};
5721
5801
  __export(index_exports, {
5722
5802
  CURRENT_VERSION: () => CURRENT_VERSION,
5803
+ DEFAULT_IDEMPOTENCY_LEASE_SECS: () => DEFAULT_IDEMPOTENCY_LEASE_SECS,
5804
+ DEFAULT_MAX_BODY_BYTES: () => DEFAULT_MAX_BODY_BYTES,
5723
5805
  DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
5806
+ LOA_MAX_TYPED_ALIASES: () => LOA_MAX_TYPED_ALIASES,
5807
+ LOA_MIN_SHORT_FORM_LETTERS: () => LOA_MIN_SHORT_FORM_LETTERS,
5808
+ LOA_PUBLIC_KEY_CACHE_MS: () => LOA_PUBLIC_KEY_CACHE_MS,
5809
+ LOA_V2_REFUSALS: () => LOA_V2_REFUSALS,
5810
+ LoaPublicKeyUnavailableError: () => LoaPublicKeyUnavailableError,
5811
+ LoaV2RefusedError: () => LoaV2RefusedError,
5812
+ MAX_ADDRESS_FIELD_CHARS: () => MAX_ADDRESS_FIELD_CHARS,
5724
5813
  OUTBOX_LEASE_COLUMNS: () => OUTBOX_LEASE_COLUMNS,
5725
5814
  SUPPORTED_VERSIONS: () => SUPPORTED_VERSIONS,
5815
+ _resetLoaKeyCacheForTests: () => _resetLoaKeyCacheForTests,
5726
5816
  _resetOnceWarningsForTests: () => _resetOnceWarningsForTests,
5817
+ acceptTypedAliases: () => acceptTypedAliases,
5727
5818
  buildSignedTestWebhook: () => buildSignedTestWebhook,
5819
+ cachedLoaPublicKey: () => cachedLoaPublicKey,
5728
5820
  canonicalD5LoaForm: () => canonicalD5LoaForm,
5821
+ canonicalD5LoaFormV2: () => canonicalD5LoaFormV2,
5822
+ checkLoaV2: () => checkLoaV2,
5729
5823
  checkRegistryHead: () => checkRegistryHead,
5730
5824
  compareAddresses: () => compareAddresses,
5731
5825
  computeBlindIndex: () => computeBlindIndex,
@@ -5742,9 +5836,16 @@ __export(index_exports, {
5742
5836
  findMatchingStoredName: () => findMatchingStoredName,
5743
5837
  formatAddressParts: () => formatAddressParts,
5744
5838
  fromOutboxTimestamp: () => fromOutboxTimestamp,
5839
+ hasLoaV2: () => hasLoaV2,
5840
+ isAcceptableAlias: () => isAcceptableAlias,
5745
5841
  isEmailLike: () => isEmailLike2,
5746
5842
  isFreshTimestamp: () => isFreshTimestamp,
5843
+ loaEnvelopeSha256: () => loaEnvelopeSha256,
5844
+ loaFirstName: () => loaFirstName,
5845
+ loaNamesMatch: () => loaNamesMatch,
5846
+ loaSurname: () => loaSurname,
5747
5847
  namePoolMatches: () => namePoolMatches,
5848
+ normaliseLoaName: () => normaliseLoaName,
5748
5849
  normalizeForBlindIndex: () => normalizeForBlindIndex,
5749
5850
  parsePinnedRegistryRoots: () => parsePinnedRegistryRoots,
5750
5851
  readAddressParts: () => readAddressParts,
@@ -5755,9 +5856,11 @@ __export(index_exports, {
5755
5856
  transform: () => transformAddress,
5756
5857
  transformAddress: () => transformAddress,
5757
5858
  transformSession: () => transformSession,
5859
+ typedAliasesOf: () => typedAliasesOf,
5758
5860
  validateAddress: () => validateAddress,
5759
5861
  verify: () => verifySignature,
5760
5862
  verifyD5LOA: () => verifyD5LOA,
5863
+ verifyD5LOAv2: () => verifyD5LOAv2,
5761
5864
  verifyGrace: () => verifyWithGrace,
5762
5865
  verifyLOA: () => verifyLOA,
5763
5866
  verifySignature: () => verifySignature,
@@ -5780,7 +5883,6 @@ var D5_BODY_ALWAYS = [
5780
5883
  "partner_id",
5781
5884
  "session_envelope",
5782
5885
  "session_key_share",
5783
- "stripe_session_id",
5784
5886
  "timestamp",
5785
5887
  "update_id",
5786
5888
  "user_id"
@@ -5836,6 +5938,110 @@ function pullSigningStringV2(timestamp, method, pathAndQuery, body = "") {
5836
5938
  return `v2.${timestamp}.${method.toUpperCase()}.${pathAndQuery}.${body}`;
5837
5939
  }
5838
5940
 
5941
+ // ../protocol/src/loa-v2.ts
5942
+ var LOA_V2_VERSION_TAG = "oneaddress-loa/2";
5943
+ var LOA_V2_LEGACY_ENVELOPE_TAG = "oneaddress-legacy-envelope/1";
5944
+ var LOA_V2_FIELD_ORDER = [
5945
+ "consumer_name",
5946
+ "authorisation_date",
5947
+ "scope",
5948
+ "update_uid",
5949
+ "partner_id",
5950
+ "envelope_sha256"
5951
+ ];
5952
+ var LOA_MAX_TYPED_ALIASES = 3;
5953
+ var LoaV2FieldError = class extends Error {
5954
+ constructor(field, reason) {
5955
+ super(`LOA v2 field ${field} ${reason}`);
5956
+ this.field = field;
5957
+ this.name = "LoaV2FieldError";
5958
+ }
5959
+ };
5960
+ var CONTROL_RE = /[\u0000-\u001F\u007F]/;
5961
+ var LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
5962
+ function utf8Length(s) {
5963
+ return new TextEncoder().encode(s).length;
5964
+ }
5965
+ function encodeField(name, value) {
5966
+ if (typeof value !== "string") throw new LoaV2FieldError(name, "is not a string");
5967
+ if (CONTROL_RE.test(value)) throw new LoaV2FieldError(name, "contains a control character");
5968
+ if (LONE_SURROGATE_RE.test(value)) throw new LoaV2FieldError(name, "is not well-formed Unicode");
5969
+ return `${utf8Length(value)}:${value}
5970
+ `;
5971
+ }
5972
+ function canonicalLoaV2(fields) {
5973
+ let out = encodeField("version", LOA_V2_VERSION_TAG);
5974
+ for (const f of LOA_V2_FIELD_ORDER) out += encodeField(f, fields[f]);
5975
+ const aliases = fields.consumer_typed_aliases;
5976
+ if (!Array.isArray(aliases)) throw new LoaV2FieldError("consumer_typed_aliases", "is not a list");
5977
+ if (aliases.length > LOA_MAX_TYPED_ALIASES) {
5978
+ throw new LoaV2FieldError("consumer_typed_aliases", `has more than ${LOA_MAX_TYPED_ALIASES} entries`);
5979
+ }
5980
+ out += encodeField("consumer_typed_aliases", String(aliases.length));
5981
+ for (const a of aliases) out += encodeField("consumer_typed_aliases", a);
5982
+ return out;
5983
+ }
5984
+ function loaV2EnvelopeDigestInput(envelope) {
5985
+ if (typeof envelope === "string") return envelope;
5986
+ if (!envelope || typeof envelope !== "object") {
5987
+ throw new LoaV2FieldError("envelope", "is neither a session_envelope string nor an address_encrypted object");
5988
+ }
5989
+ return encodeField("tag", LOA_V2_LEGACY_ENVELOPE_TAG) + encodeField("ephemeralPublicKey", envelope.ephemeralPublicKey) + encodeField("iv", envelope.iv) + encodeField("ciphertext", envelope.ciphertext) + encodeField("hkdfSalt", envelope.hkdfSalt ?? "");
5990
+ }
5991
+ var ASCII_WS_RE = /[ \t\n\v\f\r]+/;
5992
+ var MARK_RE = /\p{M}/gu;
5993
+ function normaliseLoaName(name) {
5994
+ return name.normalize("NFKD").replace(MARK_RE, "").toLowerCase().replace(/\u03C2/g, "\u03C3").split(ASCII_WS_RE).filter((t) => t.length > 0).join(" ");
5995
+ }
5996
+ function loaSurname(name) {
5997
+ const tokens = normaliseLoaName(name).split(" ").filter((t) => t.length > 0);
5998
+ return tokens.length > 0 ? tokens[tokens.length - 1] : "";
5999
+ }
6000
+ function loaFirstName(name) {
6001
+ const tokens = normaliseLoaName(name).split(" ").filter((t) => t.length > 0);
6002
+ return tokens.length > 0 ? tokens[0] : "";
6003
+ }
6004
+ function loaNamesMatch(a, b) {
6005
+ const na = normaliseLoaName(a);
6006
+ return na.length > 0 && na === normaliseLoaName(b);
6007
+ }
6008
+ var LOA_MIN_SHORT_FORM_LETTERS = 3;
6009
+ function codePoints(s) {
6010
+ return Array.from(s).length;
6011
+ }
6012
+ function isAcceptableAlias(verifiedName, alias) {
6013
+ const vFirst = loaFirstName(verifiedName);
6014
+ const aFirst = loaFirstName(alias);
6015
+ if (!vFirst || !aFirst) return false;
6016
+ if (aFirst === vFirst) return true;
6017
+ const [shorter, longer] = codePoints(aFirst) <= codePoints(vFirst) ? [aFirst, vFirst] : [vFirst, aFirst];
6018
+ return codePoints(shorter) >= LOA_MIN_SHORT_FORM_LETTERS && longer.startsWith(shorter);
6019
+ }
6020
+ function acceptTypedAliases(verifiedName, aliases) {
6021
+ const out = [];
6022
+ if (!Array.isArray(aliases)) return out;
6023
+ const seen = /* @__PURE__ */ new Set([normaliseLoaName(verifiedName)]);
6024
+ for (const a of aliases) {
6025
+ if (out.length >= LOA_MAX_TYPED_ALIASES) break;
6026
+ if (typeof a !== "string") continue;
6027
+ if (CONTROL_RE.test(a) || LONE_SURROGATE_RE.test(a)) continue;
6028
+ const n = normaliseLoaName(a);
6029
+ if (!n || seen.has(n)) continue;
6030
+ if (!isAcceptableAlias(verifiedName, a)) continue;
6031
+ seen.add(n);
6032
+ out.push(a);
6033
+ }
6034
+ return out;
6035
+ }
6036
+ var LOA_V2_REFUSALS = [
6037
+ "loa_v2_malformed",
6038
+ "loa_v2_signature_invalid",
6039
+ "loa_v2_partner_mismatch",
6040
+ "loa_v2_update_mismatch",
6041
+ "loa_v2_envelope_mismatch",
6042
+ "loa_v2_name_mismatch"
6043
+ ];
6044
+
5839
6045
  // src/app-hosts.ts
5840
6046
  function allowedAppHosts() {
5841
6047
  const hosts = ["oneaddress.io", "app.oneaddress.io"];
@@ -5844,7 +6050,7 @@ function allowedAppHosts() {
5844
6050
  }
5845
6051
  return new Set(hosts);
5846
6052
  }
5847
- function resolveAppOrigin(baseUrl, label) {
6053
+ function resolveAppOrigin(baseUrl, label, extraHosts) {
5848
6054
  let parsed;
5849
6055
  try {
5850
6056
  parsed = new URL(baseUrl);
@@ -5852,6 +6058,9 @@ function resolveAppOrigin(baseUrl, label) {
5852
6058
  throw new Error(`[OneAddress SDK] ${label}: appBaseUrl is not a valid URL`);
5853
6059
  }
5854
6060
  const allowed = allowedAppHosts();
6061
+ for (const h of extraHosts ?? []) {
6062
+ if (typeof h === "string" && h.trim() !== "") allowed.add(h.trim().toLowerCase());
6063
+ }
5855
6064
  if (!allowed.has(parsed.hostname)) {
5856
6065
  throw new Error(
5857
6066
  `[OneAddress SDK] ${label}: appBaseUrl host must be one of: ${[...allowed].join(", ")}`
@@ -5887,26 +6096,38 @@ function surnameVariants(token) {
5887
6096
  if (!token.includes("-")) return [token];
5888
6097
  return [token, ...token.split("-").filter(Boolean)];
5889
6098
  }
6099
+ var MAX_ALIASES = 10;
6100
+ var MAX_TOKENS_PER_NAME = 8;
6101
+ var MAX_POOL_TOKENS = 24;
5890
6102
  function namePoolMatches(providedNames, storedName) {
5891
6103
  if (isEmailLike2(storedName)) return false;
5892
- const provided = providedNames.filter((n) => Boolean(n) && !isEmailLike2(n));
6104
+ const provided = providedNames.filter((n) => typeof n === "string" && n !== "" && !isEmailLike2(n));
5893
6105
  const primary = tokenize(provided[0] ?? "");
5894
- if (primary.length === 0) return false;
6106
+ if (primary.length === 0 || primary.length > MAX_TOKENS_PER_NAME) return false;
6107
+ const aliases = provided.slice(1, 1 + MAX_ALIASES).map(tokenize).filter((t) => t.length > 0 && t.length <= MAX_TOKENS_PER_NAME);
6108
+ const distinct = new Set(primary);
6109
+ for (const t of aliases) for (const tok of t) distinct.add(tok);
6110
+ if (distinct.size > MAX_POOL_TOKENS) return false;
5895
6111
  const surnames = new Set(surnameVariants(primary[primary.length - 1]));
5896
- for (let i = 1; i < provided.length; i++) {
5897
- const t = tokenize(provided[i]);
5898
- if (t.length >= 2) for (const v of surnameVariants(t[t.length - 1])) surnames.add(v);
5899
- }
5900
- const all = /* @__PURE__ */ new Set();
5901
- for (const n of provided) for (const t of tokenize(n)) all.add(t);
5902
- const given = [...all].filter((t) => !surnames.has(t));
6112
+ for (const t of aliases) {
6113
+ const last = t[t.length - 1];
6114
+ if (t.length >= 2 && last.length >= 2) for (const v of surnameVariants(last)) surnames.add(v);
6115
+ }
6116
+ const givenSet = /* @__PURE__ */ new Set();
6117
+ for (const tok of primary) if (!surnames.has(tok)) givenSet.add(tok);
6118
+ for (const t of aliases) for (const tok of t) if (tok.length >= 2 && !surnames.has(tok)) givenSet.add(tok);
6119
+ const given = [...givenSet];
6120
+ const fullGiven = given.filter((g) => g.length >= 2);
5903
6121
  const stored = tokenize(storedName);
5904
- if (stored.length === 0) return false;
6122
+ if (stored.length < 2) return false;
5905
6123
  const storedSurname = stored[stored.length - 1];
5906
6124
  const storedGiven = stored.slice(0, -1);
5907
6125
  if (!surnameVariants(storedSurname).some((v) => surnames.has(v))) return false;
5908
6126
  const covered = (tok) => given.includes(tok) || tok.length === 1 && given.some((g) => g[0] === tok) || given.some((g) => g.length === 1 && g === tok[0]);
5909
- return storedGiven.every(covered);
6127
+ if (!storedGiven.every(covered)) return false;
6128
+ return storedGiven.some(
6129
+ (tok) => fullGiven.includes(tok) || tok.length === 1 && fullGiven.some((g) => g[0] === tok)
6130
+ );
5910
6131
  }
5911
6132
  function findMatchingStoredName(providedNames, storedCandidates) {
5912
6133
  return storedCandidates.find((candidate) => namePoolMatches(providedNames, candidate));
@@ -6352,14 +6573,21 @@ async function checkRegistryHead(opts2) {
6352
6573
 
6353
6574
  // src/index.ts
6354
6575
  var IDEMPOTENCY_DIALECTS = ["postgres", "sqlite", "mysql", "mssql"];
6576
+ var DEFAULT_IDEMPOTENCY_LEASE_SECS = 120;
6355
6577
  function createSqlIdempotencyStore(opts2) {
6356
6578
  const table = opts2.table ?? "oneaddress_dispatches";
6357
6579
  const dialect = opts2.dialect ?? "postgres";
6580
+ const leaseSeconds = opts2.leaseSeconds ?? DEFAULT_IDEMPOTENCY_LEASE_SECS;
6358
6581
  if (!IDEMPOTENCY_DIALECTS.includes(dialect)) {
6359
6582
  throw new Error(
6360
6583
  `[OneAddress SDK] createSqlIdempotencyStore: unknown dialect "${dialect}". Supported: ${IDEMPOTENCY_DIALECTS.join(", ")}.`
6361
6584
  );
6362
6585
  }
6586
+ if (typeof leaseSeconds !== "number" || !Number.isSafeInteger(leaseSeconds) || leaseSeconds < 0 || leaseSeconds > 86400) {
6587
+ throw new Error(
6588
+ `[OneAddress SDK] createSqlIdempotencyStore: leaseSeconds must be a whole number from 0 to 86400, got ${String(leaseSeconds)}`
6589
+ );
6590
+ }
6363
6591
  const defaultPh = dialect === "postgres" ? (n) => `$${n}` : dialect === "mssql" ? (n) => `@p${n}` : () => "?";
6364
6592
  const ph = opts2.placeholder ?? defaultPh;
6365
6593
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
@@ -6378,7 +6606,26 @@ function createSqlIdempotencyStore(opts2) {
6378
6606
  [dispatchId]
6379
6607
  );
6380
6608
  if (tokenOf(rows[0]) === token) return "fresh";
6381
- return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
6609
+ if (completedOf(rows[0])) return "duplicate";
6610
+ const takeover = import_crypto2.default.randomBytes(16).toString("hex");
6611
+ await opts2.query(
6612
+ `UPDATE ${table} SET received_at = CURRENT_TIMESTAMP, claim_token = ${ph(1)} WHERE dispatch_id = ${ph(2)} AND completed_at IS NULL AND ${staleClaim(3)}`,
6613
+ leaseParams([takeover, dispatchId])
6614
+ );
6615
+ const after = await opts2.query(
6616
+ `SELECT claim_token, completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
6617
+ [dispatchId]
6618
+ );
6619
+ if (tokenOf(after[0]) === takeover) return "retry-after-incomplete";
6620
+ return completedOf(after[0]) ? "duplicate" : "in-progress";
6621
+ }
6622
+ function staleClaim(n) {
6623
+ if (leaseSeconds === 0) return "1 = 1";
6624
+ const cutoff = dialect === "postgres" ? `received_at < CURRENT_TIMESTAMP - make_interval(secs => ${ph(n)})` : dialect === "sqlite" ? `julianday(received_at) < julianday('now') - (${ph(n)} / 86400.0)` : dialect === "mysql" ? `received_at < CURRENT_TIMESTAMP - INTERVAL ${ph(n)} SECOND` : `received_at < DATEADD(second, -${ph(n)}, CURRENT_TIMESTAMP)`;
6625
+ return `(received_at IS NULL OR ${cutoff})`;
6626
+ }
6627
+ function leaseParams(params) {
6628
+ return leaseSeconds === 0 ? params : [...params, leaseSeconds];
6382
6629
  }
6383
6630
  async function setByUpsert(dispatchId) {
6384
6631
  if (dialect === "mysql") {
@@ -6412,11 +6659,22 @@ function createSqlIdempotencyStore(opts2) {
6412
6659
  [dispatchId]
6413
6660
  );
6414
6661
  if (inserted.length > 0) return "fresh";
6662
+ const took = await opts2.query(
6663
+ `UPDATE ${table} SET received_at = CURRENT_TIMESTAMP WHERE dispatch_id = ${ph(1)} AND completed_at IS NULL AND ${staleClaim(2)} RETURNING dispatch_id`,
6664
+ leaseParams([dispatchId])
6665
+ );
6666
+ if (took.length > 0) return "retry-after-incomplete";
6415
6667
  const rows = await opts2.query(
6416
6668
  `SELECT completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
6417
6669
  [dispatchId]
6418
6670
  );
6419
- return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
6671
+ return completedOf(rows[0]) ? "duplicate" : "in-progress";
6672
+ },
6673
+ async release(dispatchId) {
6674
+ await opts2.query(
6675
+ `DELETE FROM ${table} WHERE dispatch_id = ${ph(1)} AND completed_at IS NULL`,
6676
+ [dispatchId]
6677
+ );
6420
6678
  },
6421
6679
  async complete(dispatchId) {
6422
6680
  await opts2.query(
@@ -6602,6 +6860,7 @@ async function transformSession(share, envelopeB64, privateKeyPem, partnerId, re
6602
6860
  );
6603
6861
  }
6604
6862
  var OA_APP_BASE_URL2 = "https://oneaddress.io";
6863
+ var CONFIRM_PATH = "/api/confirm";
6605
6864
  async function confirmUpdate(opts2) {
6606
6865
  const {
6607
6866
  partnerId,
@@ -6633,18 +6892,22 @@ async function confirmUpdate(opts2) {
6633
6892
  ...memberName !== void 0 ? { member_name: memberName } : {}
6634
6893
  });
6635
6894
  const timestamp = String(Math.floor(Date.now() / 1e3));
6636
- const signature = import_crypto2.default.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
6637
- let base = appBaseUrl;
6638
- while (base.endsWith("/")) base = base.slice(0, -1);
6895
+ const signature = import_crypto2.default.createHmac("sha256", secret).update(pullSigningStringV2(timestamp, "POST", CONFIRM_PATH, body)).digest("hex");
6896
+ let origin;
6897
+ try {
6898
+ origin = resolveAppOrigin(appBaseUrl, "confirmUpdate", opts2.allowedHosts);
6899
+ } catch (err) {
6900
+ return { ok: false, status: 0, error: err instanceof Error ? err.message : String(err) };
6901
+ }
6639
6902
  let res;
6640
6903
  try {
6641
- res = await fetchImpl(`${base}/api/confirm`, {
6904
+ res = await fetchImpl(`${origin}${CONFIRM_PATH}`, {
6642
6905
  method: "POST",
6643
6906
  headers: {
6644
6907
  "Content-Type": "application/json",
6645
- "Authorization": `Bearer ${secret}`,
6646
6908
  "X-OneAddress-Timestamp": timestamp,
6647
- "X-OneAddress-Signature": signature
6909
+ "X-OneAddress-Signature": signature,
6910
+ [PULL_SIGNATURE_VERSION_HEADER]: "2"
6648
6911
  },
6649
6912
  // The SAME string that was signed. Not an object, and not re-stringified.
6650
6913
  body
@@ -6670,6 +6933,48 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL2) {
6670
6933
  }
6671
6934
  return res.text();
6672
6935
  }
6936
+ var LOA_PUBLIC_KEY_CACHE_MS = 24 * 60 * 60 * 1e3;
6937
+ var loaKeyCache = /* @__PURE__ */ new Map();
6938
+ var loaKeyInFlight = /* @__PURE__ */ new Map();
6939
+ var LoaPublicKeyUnavailableError = class extends Error {
6940
+ constructor(from, cause) {
6941
+ super(
6942
+ `[OneAddress SDK] could not fetch OneAddress's LOA public key from ${from} (${cause}). requireLoa is on (the default since 2.8.0), so this dispatch is refused and OneAddress will retry it. Pin the key with loaPublicKeyPem (from fetchLoaPublicKey), or set requireLoa: false to process dispatches without verifying consent.`
6943
+ );
6944
+ this.from = from;
6945
+ this.name = "LoaPublicKeyUnavailableError";
6946
+ }
6947
+ };
6948
+ async function cachedLoaPublicKey(appBaseUrl = OA_APP_BASE_URL2, now = Date.now()) {
6949
+ const origin = resolveAppOrigin(appBaseUrl, "cachedLoaPublicKey");
6950
+ const held = loaKeyCache.get(origin);
6951
+ if (held && now - held.at < LOA_PUBLIC_KEY_CACHE_MS) return held.pem;
6952
+ let pending = loaKeyInFlight.get(origin);
6953
+ if (!pending) {
6954
+ pending = (async () => {
6955
+ const pem = (await fetchLoaPublicKey(origin)).trim();
6956
+ if (!pem.includes("-----BEGIN PUBLIC KEY-----")) {
6957
+ throw new Error("the response is not a PEM public key");
6958
+ }
6959
+ loaKeyCache.set(origin, { pem, at: Date.now() });
6960
+ return pem;
6961
+ })().finally(() => loaKeyInFlight.delete(origin));
6962
+ loaKeyInFlight.set(origin, pending);
6963
+ }
6964
+ try {
6965
+ return await pending;
6966
+ } catch (err) {
6967
+ if (held) return held.pem;
6968
+ throw new LoaPublicKeyUnavailableError(
6969
+ `${origin}/.well-known/oneaddress-loa-key.pem`,
6970
+ err instanceof Error ? err.message : String(err)
6971
+ );
6972
+ }
6973
+ }
6974
+ function _resetLoaKeyCacheForTests() {
6975
+ loaKeyCache.clear();
6976
+ loaKeyInFlight.clear();
6977
+ }
6673
6978
  async function verifyLOA(loa, publicKeyPem) {
6674
6979
  if (loa.algorithm !== "ECDSA-P256") {
6675
6980
  console.warn(
@@ -6749,6 +7054,91 @@ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId, expec
6749
7054
  );
6750
7055
  return data;
6751
7056
  }
7057
+ function hasLoaV2(loa) {
7058
+ return typeof loa.oneaddress_signature_v2 === "string";
7059
+ }
7060
+ function canonicalD5LoaFormV2(loa) {
7061
+ return canonicalLoaV2({
7062
+ consumer_name: loa.consumer_name,
7063
+ authorisation_date: loa.authorisation_date,
7064
+ scope: loa.scope,
7065
+ update_uid: loa.update_uid,
7066
+ partner_id: loa.partner_id,
7067
+ envelope_sha256: loa.envelope_sha256,
7068
+ consumer_typed_aliases: loa.consumer_typed_aliases
7069
+ });
7070
+ }
7071
+ function loaEnvelopeSha256(envelope) {
7072
+ return import_crypto2.default.createHash("sha256").update(loaV2EnvelopeDigestInput(envelope), "utf8").digest("hex");
7073
+ }
7074
+ async function verifyD5LOAv2(loa, publicKeyPem) {
7075
+ if (loa.signature_algorithm !== "ECDSA-P256" || !hasLoaV2(loa)) return false;
7076
+ let text;
7077
+ try {
7078
+ text = canonicalD5LoaFormV2(loa);
7079
+ } catch {
7080
+ return false;
7081
+ }
7082
+ try {
7083
+ const key = await import_crypto2.default.subtle.importKey(
7084
+ "spki",
7085
+ pemToBuffer(publicKeyPem),
7086
+ { name: "ECDSA", namedCurve: "P-256" },
7087
+ false,
7088
+ ["verify"]
7089
+ );
7090
+ return await import_crypto2.default.subtle.verify(
7091
+ { name: "ECDSA", hash: "SHA-256" },
7092
+ key,
7093
+ Buffer.from(loa.oneaddress_signature_v2, "hex"),
7094
+ new TextEncoder().encode(text)
7095
+ );
7096
+ } catch {
7097
+ return false;
7098
+ }
7099
+ }
7100
+ function typedAliasesOf(loa) {
7101
+ if (!hasLoaV2(loa)) return [];
7102
+ return acceptTypedAliases(loa.consumer_name, loa.consumer_typed_aliases);
7103
+ }
7104
+ function bodyUpdateIdString(v) {
7105
+ if (typeof v === "string") return v;
7106
+ if (typeof v === "number" && Number.isSafeInteger(v)) return String(v);
7107
+ return null;
7108
+ }
7109
+ async function checkLoaV2(loa, ctx) {
7110
+ if (!hasLoaV2(loa) || typeof loa.partner_id !== "string" || typeof loa.envelope_sha256 !== "string") {
7111
+ return "loa_v2_malformed";
7112
+ }
7113
+ try {
7114
+ canonicalD5LoaFormV2(loa);
7115
+ } catch {
7116
+ return "loa_v2_malformed";
7117
+ }
7118
+ if (ctx.publicKeyPem !== void 0 && !await verifyD5LOAv2(loa, ctx.publicKeyPem)) {
7119
+ return "loa_v2_signature_invalid";
7120
+ }
7121
+ if (loa.partner_id !== ctx.partnerId) return "loa_v2_partner_mismatch";
7122
+ if (bodyUpdateIdString(ctx.updateId) !== loa.update_uid) return "loa_v2_update_mismatch";
7123
+ let digest;
7124
+ try {
7125
+ digest = loaEnvelopeSha256(ctx.envelope);
7126
+ } catch {
7127
+ return "loa_v2_envelope_mismatch";
7128
+ }
7129
+ if (digest !== loa.envelope_sha256) return "loa_v2_envelope_mismatch";
7130
+ if (typeof ctx.envelopeVerifiedName !== "string" || !loaNamesMatch(ctx.envelopeVerifiedName, loa.consumer_name)) {
7131
+ return "loa_v2_name_mismatch";
7132
+ }
7133
+ return null;
7134
+ }
7135
+ var LoaV2RefusedError = class extends Error {
7136
+ constructor(code) {
7137
+ super(`[OneAddress SDK] D5 LOA v2 refused (${code}); refusing rather than applying an update the consent record does not cover`);
7138
+ this.code = code;
7139
+ this.name = "LoaV2RefusedError";
7140
+ }
7141
+ };
6752
7142
  var ADDRESS_REQUIRED_FIELDS = [
6753
7143
  "street",
6754
7144
  "suburb",
@@ -6756,19 +7146,60 @@ var ADDRESS_REQUIRED_FIELDS = [
6756
7146
  "postcode",
6757
7147
  "country"
6758
7148
  ];
7149
+ var MAX_ADDRESS_FIELD_CHARS = 512;
6759
7150
  function validateAddress(raw) {
6760
- if (typeof raw !== "object" || raw === null) {
7151
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
6761
7152
  throw new Error("[OneAddress SDK] Decrypted address payload is not an object");
6762
7153
  }
6763
7154
  const obj = raw;
6764
7155
  for (const field of ADDRESS_REQUIRED_FIELDS) {
6765
- if (typeof obj[field] !== "string" || obj[field] === "") {
7156
+ const value = obj[field];
7157
+ if (typeof value !== "string" || value === "") {
7158
+ throw new Error(
7159
+ `[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change - update @oneaddress/partner-sdk.`
7160
+ );
7161
+ }
7162
+ if (value.length > MAX_ADDRESS_FIELD_CHARS) {
6766
7163
  throw new Error(
6767
- `[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change \u2014 update @oneaddress/partner-sdk.`
7164
+ `[OneAddress SDK] Decrypted address field "${field}" is ${value.length} characters, over the ${MAX_ADDRESS_FIELD_CHARS} this SDK accepts; refusing rather than truncating`
6768
7165
  );
6769
7166
  }
6770
7167
  }
6771
- return obj;
7168
+ const rawUpdatedAt = obj.updated_at;
7169
+ let updatedAt;
7170
+ if (rawUpdatedAt === void 0 || rawUpdatedAt === null) updatedAt = "";
7171
+ else if (typeof rawUpdatedAt === "number" && Number.isFinite(rawUpdatedAt)) updatedAt = String(rawUpdatedAt);
7172
+ else if (typeof rawUpdatedAt === "string") updatedAt = rawUpdatedAt;
7173
+ else throw new Error('[OneAddress SDK] Decrypted address field "updated_at" is not a string');
7174
+ if (updatedAt.length > MAX_ADDRESS_FIELD_CHARS) {
7175
+ throw new Error(
7176
+ `[OneAddress SDK] Decrypted address field "updated_at" is over the ${MAX_ADDRESS_FIELD_CHARS} characters this SDK accepts`
7177
+ );
7178
+ }
7179
+ return {
7180
+ street: obj.street,
7181
+ suburb: obj.suburb,
7182
+ state: obj.state,
7183
+ postcode: obj.postcode,
7184
+ country: obj.country,
7185
+ updated_at: updatedAt
7186
+ };
7187
+ }
7188
+ function legacyAddressOf(blob, body) {
7189
+ return validateAddress({
7190
+ street: blob.street,
7191
+ suburb: blob.suburb,
7192
+ state: blob.state,
7193
+ postcode: blob.postcode,
7194
+ country: blob.country,
7195
+ updated_at: typeof blob.updated_at === "string" ? blob.updated_at : body.timestamp ?? ""
7196
+ });
7197
+ }
7198
+ function stringOr(value, fallback) {
7199
+ return typeof value === "string" ? value : fallback;
7200
+ }
7201
+ function stringsOf(value) {
7202
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
6772
7203
  }
6773
7204
  var ADDRESS_ALIASES = {
6774
7205
  line1: ["line1", "address_line1", "street", "streetAddress"],
@@ -6952,6 +7383,41 @@ function _resetOnceWarningsForTests() {
6952
7383
  warnedNoIdempotencyStore = false;
6953
7384
  }
6954
7385
  var MAX_TIMESTAMP_TOLERANCE_SECS = 86400;
7386
+ var DEFAULT_MAX_BODY_BYTES = 1048576;
7387
+ var IN_PROGRESS_RETRY_AFTER_SECS = 30;
7388
+ async function readBodyCapped(req, max) {
7389
+ const declaredLength = req.headers.get("content-length");
7390
+ if (declaredLength !== null && /^\s*\d+\s*$/.test(declaredLength) && Number(declaredLength) > max) {
7391
+ return null;
7392
+ }
7393
+ const stream = req.body;
7394
+ if (stream && typeof stream.getReader === "function") {
7395
+ const reader = stream.getReader();
7396
+ const chunks = [];
7397
+ let total = 0;
7398
+ for (; ; ) {
7399
+ const { done, value } = await reader.read();
7400
+ if (done) break;
7401
+ if (!value) continue;
7402
+ total += value.byteLength;
7403
+ if (total > max) {
7404
+ await reader.cancel().catch(() => void 0);
7405
+ return null;
7406
+ }
7407
+ chunks.push(value);
7408
+ }
7409
+ const joined = new Uint8Array(total);
7410
+ let offset = 0;
7411
+ for (const c of chunks) {
7412
+ joined.set(c, offset);
7413
+ offset += c.byteLength;
7414
+ }
7415
+ return new TextDecoder("utf-8").decode(joined);
7416
+ }
7417
+ const text = await req.text();
7418
+ if (text.length > max || new TextEncoder().encode(text).byteLength > max) return null;
7419
+ return text;
7420
+ }
6955
7421
  var XWING_SEED_BYTES = 32;
6956
7422
  function assertUsablePrivateKey(privateKeyPem) {
6957
7423
  if (typeof privateKeyPem !== "string") {
@@ -6998,13 +7464,16 @@ function createOneAddressHandler(options) {
6998
7464
  expectedAlg,
6999
7465
  keyId,
7000
7466
  loaPublicKeyPem,
7001
- requireLoa = Boolean(loaPublicKeyPem),
7467
+ requireLoa = true,
7468
+ loaPublicKeyBaseUrl,
7002
7469
  confirm,
7470
+ partnerId: configuredPartnerId,
7003
7471
  onUpdate,
7004
7472
  onVerify,
7005
7473
  onAccountVerify,
7006
7474
  onTest,
7007
7475
  timestampToleranceSecs = 300,
7476
+ maxBodyBytes = DEFAULT_MAX_BODY_BYTES,
7008
7477
  idempotencyStore,
7009
7478
  acceptedUpdateTypes: acceptedUpdateTypesRaw,
7010
7479
  allowedCallbackHosts
@@ -7018,6 +7487,9 @@ function createOneAddressHandler(options) {
7018
7487
  `[OneAddress SDK] timestampToleranceSecs must be a positive number of seconds up to ${MAX_TIMESTAMP_TOLERANCE_SECS}, got ${String(timestampToleranceSecs)}`
7019
7488
  );
7020
7489
  }
7490
+ if (typeof maxBodyBytes !== "number" || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes <= 0) {
7491
+ throw new Error(`[OneAddress SDK] maxBodyBytes must be a positive whole number of bytes, got ${String(maxBodyBytes)}`);
7492
+ }
7021
7493
  if (webhookSecretGraceUntil !== void 0) {
7022
7494
  const until = typeof webhookSecretGraceUntil === "number" ? webhookSecretGraceUntil : Date.parse(webhookSecretGraceUntil);
7023
7495
  if (Number.isNaN(until)) {
@@ -7027,6 +7499,15 @@ function createOneAddressHandler(options) {
7027
7499
  if (confirm && (!confirm.partnerId || !confirm.confirmSecret)) {
7028
7500
  throw new Error("[OneAddress SDK] confirm needs both partnerId and confirmSecret");
7029
7501
  }
7502
+ if (typeof requireLoa !== "boolean") {
7503
+ throw new Error(`[OneAddress SDK] requireLoa must be true or false, got ${String(requireLoa)}`);
7504
+ }
7505
+ if (loaPublicKeyBaseUrl !== void 0) resolveAppOrigin(loaPublicKeyBaseUrl, "loaPublicKeyBaseUrl");
7506
+ async function loaVerificationKey() {
7507
+ if (loaPublicKeyPem) return loaPublicKeyPem;
7508
+ if (!requireLoa) return void 0;
7509
+ return cachedLoaPublicKey(loaPublicKeyBaseUrl ?? OA_APP_BASE_URL2);
7510
+ }
7030
7511
  function enforceLoaPresence(body) {
7031
7512
  const present = !!body.loa_encrypted && typeof body.loa_encrypted === "object";
7032
7513
  if (present) return;
@@ -7039,7 +7520,7 @@ function createOneAddressHandler(options) {
7039
7520
  warnedConsentUnverified = true;
7040
7521
  console.warn(
7041
7522
  // NOSONAR - intentional SDK diagnostic, not user-controlled data
7042
- "[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."
7523
+ "[OneAddress SDK] a dispatch arrived with no loa_encrypted and requireLoa is off, so consent for this update is UNVERIFIED. Remove requireLoa: false (it is on by default) to refuse such dispatches. Logged once per process."
7043
7524
  );
7044
7525
  }
7045
7526
  }
@@ -7074,9 +7555,9 @@ function createOneAddressHandler(options) {
7074
7555
  const newEmail = updateTypes.includes("email") ? requireContactValue("email", data.new_email) : void 0;
7075
7556
  const customer = {
7076
7557
  email: "",
7077
- name: data.verified_name ?? "",
7078
- account_number: data.account_number ?? null,
7079
- known_names: Array.isArray(data.known_names) ? data.known_names : []
7558
+ name: stringOr(data.verified_name, ""),
7559
+ account_number: stringOr(data.account_number, null),
7560
+ known_names: stringsOf(data.known_names)
7080
7561
  };
7081
7562
  let loa;
7082
7563
  let loa_ref;
@@ -7088,11 +7569,23 @@ function createOneAddressHandler(options) {
7088
7569
  expectedAlg
7089
7570
  );
7090
7571
  loa_ref = d5LoaRef(loa);
7091
- if (loaPublicKeyPem) {
7092
- const valid = await verifyD5LOA(loa, loaPublicKeyPem);
7572
+ const loaKey = await loaVerificationKey();
7573
+ if (loaKey) {
7574
+ const valid = await verifyD5LOA(loa, loaKey);
7093
7575
  if (!valid) throw new Error("D5 LOA signature verification failed");
7094
7576
  }
7095
7577
  assertLoaBoundToEnvelope(loa, data.update_uid);
7578
+ if (hasLoaV2(loa)) {
7579
+ const refusal = await checkLoaV2(loa, {
7580
+ partnerId: configuredPartnerId ?? confirm?.partnerId ?? partnerId,
7581
+ updateId: body.update_id,
7582
+ envelope: body.session_envelope,
7583
+ envelopeVerifiedName: data.verified_name,
7584
+ ...loaKey ? { publicKeyPem: loaKey } : {}
7585
+ });
7586
+ if (refusal) throw new LoaV2RefusedError(refusal);
7587
+ customer.known_names = typedAliasesOf(loa);
7588
+ }
7096
7589
  }
7097
7590
  return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
7098
7591
  }
@@ -7108,7 +7601,13 @@ function createOneAddressHandler(options) {
7108
7601
  return Array.isArray(siblings) && siblings.includes(keyId);
7109
7602
  }
7110
7603
  return async function handler(req) {
7111
- const rawBody = await req.text();
7604
+ const rawBody = await readBodyCapped(req, maxBodyBytes);
7605
+ if (rawBody === null) {
7606
+ return new Response(JSON.stringify({ error: "Payload too large" }), {
7607
+ status: 413,
7608
+ headers: { "Content-Type": "application/json" }
7609
+ });
7610
+ }
7112
7611
  const sig = req.headers.get("x-oneaddress-signature") ?? "";
7113
7612
  const tsHeader = req.headers.get("x-oneaddress-timestamp") ?? "";
7114
7613
  if (!isFreshTimestamp(tsHeader, timestampToleranceSecs)) {
@@ -7157,6 +7656,8 @@ function createOneAddressHandler(options) {
7157
7656
  if (isCrossoverSiblingToSkip(body)) {
7158
7657
  return declared(200, { ok: true, skipped: true, crossover: true });
7159
7658
  }
7659
+ let claimed = false;
7660
+ let completed = false;
7160
7661
  if (dispatchId) {
7161
7662
  if (!idempotencyStore) {
7162
7663
  const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
@@ -7177,6 +7678,17 @@ function createOneAddressHandler(options) {
7177
7678
  if (claim === "duplicate") {
7178
7679
  return declared(200, { ok: true, duplicate: true });
7179
7680
  }
7681
+ if (claim === "in-progress") {
7682
+ return new Response(JSON.stringify({
7683
+ error: "dispatch_in_progress",
7684
+ detail: "Another delivery of this dispatch is being processed. Retry later.",
7685
+ accepted_update_types: acceptedUpdateTypes
7686
+ }), {
7687
+ status: 503,
7688
+ headers: { "Content-Type": "application/json", "Retry-After": String(IN_PROGRESS_RETRY_AFTER_SECS) }
7689
+ });
7690
+ }
7691
+ claimed = true;
7180
7692
  } else {
7181
7693
  const alreadySeen = await idempotencyStore.has(dispatchId);
7182
7694
  if (alreadySeen) {
@@ -7272,16 +7784,27 @@ function createOneAddressHandler(options) {
7272
7784
  expectedAlg
7273
7785
  );
7274
7786
  loa_ref = d5LoaRef(loa);
7275
- if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
7787
+ const loaKey = await loaVerificationKey();
7788
+ if (loaKey && !await verifyD5LOA(loa, loaKey)) {
7276
7789
  throw new Error("D5 LOA signature verification failed");
7277
7790
  }
7278
7791
  assertLoaBoundToEnvelope(loa, rawAddress.update_uid);
7792
+ if (hasLoaV2(loa)) {
7793
+ const refusal = await checkLoaV2(loa, {
7794
+ partnerId: configuredPartnerId ?? confirm?.partnerId ?? partnerId,
7795
+ updateId: body.update_id,
7796
+ envelope: encrypted,
7797
+ envelopeVerifiedName: rawAddress.fullName,
7798
+ ...loaKey ? { publicKeyPem: loaKey } : {}
7799
+ });
7800
+ if (refusal) throw new LoaV2RefusedError(refusal);
7801
+ }
7279
7802
  }
7280
7803
  const customer = {
7281
7804
  email: "",
7282
- name: rawAddress.fullName ?? "",
7283
- account_number: rawAddress.accountReference ?? null,
7284
- known_names: Array.isArray(rawAddress.knownNames) ? rawAddress.knownNames : []
7805
+ name: stringOr(rawAddress.fullName, ""),
7806
+ account_number: stringOr(rawAddress.accountReference, null),
7807
+ known_names: loa && hasLoaV2(loa) ? typedAliasesOf(loa) : stringsOf(rawAddress.knownNames)
7285
7808
  };
7286
7809
  event = {
7287
7810
  event: "address.updated",
@@ -7293,7 +7816,8 @@ function createOneAddressHandler(options) {
7293
7816
  customer,
7294
7817
  // The legacy blob predates kinds and always carries an address.
7295
7818
  update_types: ["address"],
7296
- address: validateAddress(rawAddress),
7819
+ // Six named fields, never the blob: see validateAddress.
7820
+ address: legacyAddressOf(rawAddress, body),
7297
7821
  loa,
7298
7822
  loa_ref,
7299
7823
  id_verification: body.id_verification,
@@ -7301,6 +7825,7 @@ function createOneAddressHandler(options) {
7301
7825
  };
7302
7826
  }
7303
7827
  const result = await onUpdate(event);
7828
+ completed = true;
7304
7829
  if (dispatchId && idempotencyStore) {
7305
7830
  const record = idempotencyStore.complete ? idempotencyStore.complete(dispatchId) : idempotencyStore.set(dispatchId);
7306
7831
  await record.catch(
@@ -7317,6 +7842,7 @@ function createOneAddressHandler(options) {
7317
7842
  status,
7318
7843
  loaRef: event.loa_ref,
7319
7844
  ...confirm.oneAddressApi ? { appBaseUrl: confirm.oneAddressApi } : {},
7845
+ ...confirm.allowedHosts ? { allowedHosts: confirm.allowedHosts } : {},
7320
7846
  ...confirm.fetchImpl ? { fetchImpl: confirm.fetchImpl } : {}
7321
7847
  }).then(
7322
7848
  (r) => {
@@ -7353,7 +7879,7 @@ function createOneAddressHandler(options) {
7353
7879
  user_id: body.user_id ?? "",
7354
7880
  customer: body.customer,
7355
7881
  customer_match: body.customer_match,
7356
- address: validateAddress(rawAddress),
7882
+ address: legacyAddressOf(rawAddress, body),
7357
7883
  loa: body.loa,
7358
7884
  id_verification: body.id_verification,
7359
7885
  raw: rawAddress
@@ -7392,10 +7918,10 @@ function createOneAddressHandler(options) {
7392
7918
  partnerId
7393
7919
  );
7394
7920
  customer = {
7395
- email: raw.email ?? "",
7396
- name: raw.name ?? "",
7397
- account_number: raw.account_number ?? null,
7398
- known_names: Array.isArray(raw.known_names) ? raw.known_names : []
7921
+ email: stringOr(raw.email, ""),
7922
+ name: stringOr(raw.name, ""),
7923
+ account_number: stringOr(raw.account_number, null),
7924
+ known_names: stringsOf(raw.known_names)
7399
7925
  };
7400
7926
  } else {
7401
7927
  customer = body.customer ?? {};
@@ -7482,6 +8008,13 @@ function createOneAddressHandler(options) {
7482
8008
  status: 500,
7483
8009
  headers: { "Content-Type": "application/json" }
7484
8010
  });
8011
+ } finally {
8012
+ if (claimed && !completed && idempotencyStore?.release) {
8013
+ await idempotencyStore.release(dispatchId).catch(
8014
+ (err) => console.error("[OneAddress SDK] idempotency release failed:", err)
8015
+ // NOSONAR
8016
+ );
8017
+ }
7485
8018
  }
7486
8019
  };
7487
8020
  }
@@ -7555,6 +8088,10 @@ async function buildSignedTestWebhook(opts2) {
7555
8088
  oneaddress_acn: "696 078 869",
7556
8089
  oneaddress_signature: "00".repeat(64),
7557
8090
  signature_algorithm: "ECDSA-P256",
8091
+ partner_id: opts2.partnerId,
8092
+ envelope_sha256: loaEnvelopeSha256(envelope.session_envelope),
8093
+ consumer_typed_aliases: acceptTypedAliases(sessionData.verified_name, sessionData.known_names ?? []),
8094
+ oneaddress_signature_v2: "00".repeat(64),
7558
8095
  ...opts2.loa ?? {}
7559
8096
  };
7560
8097
  if (opts2.loaSigningKeyPem) {
@@ -7565,12 +8102,19 @@ async function buildSignedTestWebhook(opts2) {
7565
8102
  false,
7566
8103
  ["sign"]
7567
8104
  );
7568
- const sig2 = await import_crypto2.default.subtle.sign(
8105
+ const signHex = async (text) => Buffer.from(await import_crypto2.default.subtle.sign(
7569
8106
  { name: "ECDSA", hash: "SHA-256" },
7570
8107
  key,
7571
- new TextEncoder().encode(canonicalD5LoaForm(loa))
7572
- );
7573
- loa.oneaddress_signature = Buffer.from(sig2).toString("hex");
8108
+ new TextEncoder().encode(text)
8109
+ )).toString("hex");
8110
+ loa.oneaddress_signature = await signHex(canonicalD5LoaForm(loa));
8111
+ let v2Text;
8112
+ try {
8113
+ v2Text = canonicalD5LoaFormV2(loa);
8114
+ } catch {
8115
+ v2Text = null;
8116
+ }
8117
+ if (hasLoaV2(loa) && v2Text !== null) loa.oneaddress_signature_v2 = await signHex(v2Text);
7574
8118
  }
7575
8119
  const sealed = await encryptEnvelopeForPartner(loa, partnerKey);
7576
8120
  loa_encrypted = { session_envelope: sealed.session_envelope, session_key_share: sealed.session_key_share };
@@ -7594,7 +8138,6 @@ async function buildSignedTestWebhook(opts2) {
7594
8138
  ...loa_encrypted ? { loa_encrypted } : {},
7595
8139
  // On the wire with a `null` value when no PaymentIntent backed the update,
7596
8140
  // so the KEY is present either way.
7597
- stripe_session_id: opts2.stripeSessionId ?? null,
7598
8141
  // `id` and `crossover_key_ids` are crossover-only and therefore NOT emitted
7599
8142
  // by default. A test that needs them passes them through `extraBody`, which
7600
8143
  // is exactly the circumstance the relay emits them in.
@@ -7628,12 +8171,26 @@ async function buildSignedTestWebhook(opts2) {
7628
8171
  // Annotate the CommonJS export names for ESM import in node:
7629
8172
  0 && (module.exports = {
7630
8173
  CURRENT_VERSION,
8174
+ DEFAULT_IDEMPOTENCY_LEASE_SECS,
8175
+ DEFAULT_MAX_BODY_BYTES,
7631
8176
  DEFAULT_REPLAY_WINDOW_SECS,
8177
+ LOA_MAX_TYPED_ALIASES,
8178
+ LOA_MIN_SHORT_FORM_LETTERS,
8179
+ LOA_PUBLIC_KEY_CACHE_MS,
8180
+ LOA_V2_REFUSALS,
8181
+ LoaPublicKeyUnavailableError,
8182
+ LoaV2RefusedError,
8183
+ MAX_ADDRESS_FIELD_CHARS,
7632
8184
  OUTBOX_LEASE_COLUMNS,
7633
8185
  SUPPORTED_VERSIONS,
8186
+ _resetLoaKeyCacheForTests,
7634
8187
  _resetOnceWarningsForTests,
8188
+ acceptTypedAliases,
7635
8189
  buildSignedTestWebhook,
8190
+ cachedLoaPublicKey,
7636
8191
  canonicalD5LoaForm,
8192
+ canonicalD5LoaFormV2,
8193
+ checkLoaV2,
7637
8194
  checkRegistryHead,
7638
8195
  compareAddresses,
7639
8196
  computeBlindIndex,
@@ -7650,9 +8207,16 @@ async function buildSignedTestWebhook(opts2) {
7650
8207
  findMatchingStoredName,
7651
8208
  formatAddressParts,
7652
8209
  fromOutboxTimestamp,
8210
+ hasLoaV2,
8211
+ isAcceptableAlias,
7653
8212
  isEmailLike,
7654
8213
  isFreshTimestamp,
8214
+ loaEnvelopeSha256,
8215
+ loaFirstName,
8216
+ loaNamesMatch,
8217
+ loaSurname,
7655
8218
  namePoolMatches,
8219
+ normaliseLoaName,
7656
8220
  normalizeForBlindIndex,
7657
8221
  parsePinnedRegistryRoots,
7658
8222
  readAddressParts,
@@ -7663,9 +8227,11 @@ async function buildSignedTestWebhook(opts2) {
7663
8227
  transform,
7664
8228
  transformAddress,
7665
8229
  transformSession,
8230
+ typedAliasesOf,
7666
8231
  validateAddress,
7667
8232
  verify,
7668
8233
  verifyD5LOA,
8234
+ verifyD5LOAv2,
7669
8235
  verifyGrace,
7670
8236
  verifyLOA,
7671
8237
  verifySignature,