@oneaddress/partner-sdk 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,9 @@
1
1
  import {
2
+ encryptEnvelopeForPartner,
3
+ encryptSessionForPartner,
2
4
  isFreshTimestamp,
3
5
  isSafeWebhookUrl
4
- } from "./chunk-DUVPNFU6.mjs";
6
+ } from "./chunk-LIHXDUUA.mjs";
5
7
 
6
8
  // src/index.ts
7
9
  import crypto from "crypto";
@@ -10,6 +12,45 @@ import crypto from "crypto";
10
12
  var CURRENT_VERSION = "2026.1";
11
13
  var SUPPORTED_VERSIONS = ["2026.1"];
12
14
 
15
+ // ../protocol/src/d5-body.ts
16
+ var D5_BODY_ALWAYS = [
17
+ "event",
18
+ "id_verification",
19
+ "key_share_expiry",
20
+ "oneaddress_version",
21
+ "partner_id",
22
+ "session_envelope",
23
+ "session_key_share",
24
+ "stripe_session_id",
25
+ "timestamp",
26
+ "update_id",
27
+ "user_id"
28
+ ];
29
+ var D5_BODY_CONDITIONAL = {
30
+ /**
31
+ * The signed Letter of Authority, sealed to the same key_id as the session.
32
+ * Present whenever the partner has a usable key — i.e. on every dispatch a
33
+ * live partner receives. Omitted best-effort when no key is available, which
34
+ * is a state a live partner is never in.
35
+ */
36
+ loa_encrypted: "partner has a usable encryption key",
37
+ /**
38
+ * The shared webhook event id. Set ONLY on a key-crossover copy, where every
39
+ * copy of one update carries the same id so a receiver holding more than one
40
+ * rotation key applies it once. Absent on an ordinary dispatch, whose
41
+ * receiver idempotency falls back to the `X-OneAddress-Dispatch` header.
42
+ */
43
+ id: "key-crossover copy only",
44
+ /** The sibling marker naming the other key_ids this update was sealed to. */
45
+ crossover_key_ids: "key-crossover copy only"
46
+ };
47
+ var D5_BODY_DRILL_ONLY = ["conformance"];
48
+ var D5_BODY_ALL_ALLOWED = [
49
+ ...D5_BODY_ALWAYS,
50
+ ...Object.keys(D5_BODY_CONDITIONAL),
51
+ ...D5_BODY_DRILL_ONLY
52
+ ];
53
+
13
54
  // ../name-match/src/index.ts
14
55
  function isEmailLike(value) {
15
56
  return value.includes("@");
@@ -132,9 +173,17 @@ function createOutboxConsumer(opts) {
132
173
  if (!Number.isFinite(batchSize) || batchSize < 1) {
133
174
  throw new Error(`[OneAddress SDK] batchSize must be a positive integer, got ${opts.batchSize}`);
134
175
  }
176
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 0) {
177
+ throw new Error(`[OneAddress SDK] maxAttempts must be an integer >= 0, got ${opts.maxAttempts}`);
178
+ }
135
179
  const ph = d.ph;
136
180
  const token = () => randomBytes(16).toString("hex");
137
181
  const stamp = (at) => toOutboxTimestamp(dialect, at);
182
+ const heldTokens = /* @__PURE__ */ new Map();
183
+ const claimPredicate = (dispatchId, firstPh) => {
184
+ const tok = heldTokens.get(dispatchId);
185
+ 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] };
186
+ };
138
187
  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})` : "");
139
188
  const toRow = (r) => ({
140
189
  dispatchId: String(r.dispatch_id ?? r.dispatchId ?? ""),
@@ -142,6 +191,10 @@ function createOutboxConsumer(opts) {
142
191
  attempts: Number(r[ATTEMPTS] ?? 0) || 0,
143
192
  fields: r
144
193
  });
194
+ const claimed = (rows, tok) => rows.map(toRow).map((row) => {
195
+ heldTokens.set(row.dispatchId, tok);
196
+ return row;
197
+ });
145
198
  async function claimBatch() {
146
199
  const at = now();
147
200
  const claimedAt = stamp(at);
@@ -152,14 +205,14 @@ function createOutboxConsumer(opts) {
152
205
  `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 *`,
153
206
  [claimedAt, tok, cutoff]
154
207
  );
155
- return rows2.map(toRow);
208
+ return claimed(rows2, tok);
156
209
  }
157
210
  if (dialect === "mssql") {
158
211
  const rows2 = await opts.query(
159
212
  `UPDATE TOP (${batchSize}) ${table} WITH (UPDLOCK, READPAST, ROWLOCK) SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} OUTPUT INSERTED.* WHERE ${claimable(ph(3))}`,
160
213
  [claimedAt, tok, cutoff]
161
214
  );
162
- return rows2.map(toRow);
215
+ return claimed(rows2, tok);
163
216
  }
164
217
  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})`;
165
218
  await opts.query(claim, [claimedAt, tok, cutoff]);
@@ -167,7 +220,7 @@ function createOutboxConsumer(opts) {
167
220
  `SELECT * FROM ${table} WHERE ${CLAIM_TOKEN} = ${ph(1)} AND processed_at IS NULL`,
168
221
  [tok]
169
222
  );
170
- return rows.map(toRow);
223
+ return claimed(rows, tok);
171
224
  }
172
225
  return {
173
226
  async ensureSchema() {
@@ -196,23 +249,29 @@ function createOutboxConsumer(opts) {
196
249
  },
197
250
  claimBatch,
198
251
  async markProcessed(dispatchId) {
252
+ const where = claimPredicate(dispatchId, 2);
199
253
  await opts.query(
200
- `UPDATE ${table} SET processed_at = ${ph(1)}, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(2)}`,
201
- [stamp(now()), dispatchId]
254
+ `UPDATE ${table} SET processed_at = ${ph(1)}, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
255
+ [stamp(now()), ...where.params]
202
256
  );
257
+ heldTokens.delete(dispatchId);
203
258
  },
204
259
  async markFailed(dispatchId, error) {
205
260
  const message = error instanceof Error ? error.message : String(error);
261
+ const where = claimPredicate(dispatchId, 2);
206
262
  await opts.query(
207
- `UPDATE ${table} SET processing_error = ${ph(1)}, ${ATTEMPTS} = COALESCE(${ATTEMPTS}, 0) + 1, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(2)}`,
208
- [message.slice(0, 500), dispatchId]
263
+ `UPDATE ${table} SET processing_error = ${ph(1)}, ${ATTEMPTS} = COALESCE(${ATTEMPTS}, 0) + 1, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
264
+ [message.slice(0, 500), ...where.params]
209
265
  );
266
+ heldTokens.delete(dispatchId);
210
267
  },
211
268
  async release(dispatchId) {
269
+ const where = claimPredicate(dispatchId, 1);
212
270
  await opts.query(
213
- `UPDATE ${table} SET ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(1)}`,
214
- [dispatchId]
271
+ `UPDATE ${table} SET ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
272
+ where.params
215
273
  );
274
+ heldTokens.delete(dispatchId);
216
275
  },
217
276
  async process(handler) {
218
277
  const rows = await claimBatch();
@@ -253,15 +312,62 @@ function createOutboxConsumer(opts) {
253
312
  }
254
313
 
255
314
  // src/index.ts
315
+ var IDEMPOTENCY_DIALECTS = ["postgres", "sqlite", "mysql", "mssql"];
256
316
  function createSqlIdempotencyStore(opts) {
257
317
  const table = opts.table ?? "oneaddress_dispatches";
258
- const ph = opts.placeholder ?? ((n) => `$${n}`);
318
+ const dialect = opts.dialect ?? "postgres";
319
+ if (!IDEMPOTENCY_DIALECTS.includes(dialect)) {
320
+ throw new Error(
321
+ `[OneAddress SDK] createSqlIdempotencyStore: unknown dialect "${dialect}". Supported: ${IDEMPOTENCY_DIALECTS.join(", ")}.`
322
+ );
323
+ }
324
+ const defaultPh = dialect === "postgres" ? (n) => `$${n}` : dialect === "mssql" ? (n) => `@p${n}` : () => "?";
325
+ const ph = opts.placeholder ?? defaultPh;
259
326
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
260
327
  throw new Error(`[OneAddress SDK] invalid table name: ${table}`);
261
328
  }
262
329
  const completedOf = (row) => row?.completed_at ?? row?.completedAt ?? null;
330
+ const tokenOf = (row) => row?.claim_token ?? row?.claimToken ?? null;
331
+ async function claimByToken(dispatchId) {
332
+ const token = crypto.randomBytes(16).toString("hex");
333
+ await opts.query(
334
+ 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)})`,
335
+ [dispatchId, token]
336
+ );
337
+ const rows = await opts.query(
338
+ `SELECT claim_token, completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
339
+ [dispatchId]
340
+ );
341
+ if (tokenOf(rows[0]) === token) return "fresh";
342
+ return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
343
+ }
344
+ async function setByUpsert(dispatchId) {
345
+ if (dialect === "mysql") {
346
+ await opts.query(
347
+ `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE completed_at = CURRENT_TIMESTAMP`,
348
+ [dispatchId]
349
+ );
350
+ return;
351
+ }
352
+ if (dialect === "mssql") {
353
+ await opts.query(
354
+ `UPDATE ${table} SET completed_at = CURRENT_TIMESTAMP WHERE dispatch_id = ${ph(1)}`,
355
+ [dispatchId]
356
+ );
357
+ await opts.query(
358
+ `INSERT INTO ${table} (dispatch_id, completed_at) SELECT ${ph(1)}, CURRENT_TIMESTAMP WHERE NOT EXISTS (SELECT 1 FROM ${table} WHERE dispatch_id = ${ph(1)})`,
359
+ [dispatchId]
360
+ );
361
+ return;
362
+ }
363
+ await opts.query(
364
+ `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON CONFLICT (dispatch_id) DO UPDATE SET completed_at = CURRENT_TIMESTAMP`,
365
+ [dispatchId]
366
+ );
367
+ }
263
368
  return {
264
369
  async claim(dispatchId) {
370
+ if (dialect === "mysql" || dialect === "mssql") return claimByToken(dispatchId);
265
371
  const inserted = await opts.query(
266
372
  `INSERT INTO ${table} (dispatch_id) VALUES (${ph(1)}) ON CONFLICT (dispatch_id) DO NOTHING RETURNING dispatch_id`,
267
373
  [dispatchId]
@@ -289,10 +395,7 @@ function createSqlIdempotencyStore(opts) {
289
395
  return rows.length > 0 && Boolean(completedOf(rows[0]));
290
396
  },
291
397
  async set(dispatchId) {
292
- await opts.query(
293
- `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON CONFLICT (dispatch_id) DO UPDATE SET completed_at = CURRENT_TIMESTAMP`,
294
- [dispatchId]
295
- );
398
+ await setByUpsert(dispatchId);
296
399
  }
297
400
  };
298
401
  }
@@ -318,7 +421,8 @@ function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousS
318
421
  function base64urlToBuffer(b64) {
319
422
  return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
320
423
  }
321
- function pemToBase64(pem) {
424
+ function pemToBase64(pemRaw) {
425
+ const pem = pemRaw.replace(/(?:\\r)?\\n/g, "\n");
322
426
  const begin = pem.indexOf("-----BEGIN");
323
427
  if (begin === -1) return pem.replace(/\s/g, "");
324
428
  const armourEnd = pem.indexOf("-----", begin + "-----BEGIN".length);
@@ -379,7 +483,7 @@ async function decryptAddress(payload, privateKeyPem, partnerId) {
379
483
  return JSON.parse(new TextDecoder().decode(plaintext));
380
484
  }
381
485
  async function decryptSession(share, envelopeB64, privateKeyPem, partnerId, expectedAlg) {
382
- const { decryptSession: decryptSessionCrypto } = await import("./src-UACTYQGX.mjs");
486
+ const { decryptSession: decryptSessionCrypto } = await import("./src-ENJJ6YZU.mjs");
383
487
  return decryptSessionCrypto(
384
488
  share,
385
489
  envelopeB64,
@@ -526,6 +630,10 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
526
630
  `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...allowedHosts].join(", ")}`
527
631
  );
528
632
  }
633
+ const loopback = parsedBase.hostname === "localhost" || parsedBase.hostname === "127.0.0.1";
634
+ if (parsedBase.protocol !== "https:" && !loopback) {
635
+ throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl must use https (plain http is accepted for localhost only)");
636
+ }
529
637
  const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
530
638
  const res = await fetch(url);
531
639
  if (!res.ok) {
@@ -602,12 +710,13 @@ async function verifyD5LOA(loa, publicKeyPem) {
602
710
  return false;
603
711
  }
604
712
  }
605
- async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId) {
713
+ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId, expectedAlg) {
606
714
  const data = await decryptSession(
607
715
  loaEncrypted.session_key_share,
608
716
  loaEncrypted.session_envelope,
609
717
  privateKeyPem,
610
- partnerId
718
+ partnerId,
719
+ expectedAlg
611
720
  );
612
721
  return data;
613
722
  }
@@ -792,14 +901,61 @@ function requireContactValue(kind, value) {
792
901
  }
793
902
  var HANDLED_EVENTS = ["address.updated", "contact.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
794
903
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
904
+ var warnedConsentUnverified = false;
905
+ var warnedNoIdempotencyStore = false;
906
+ function _resetOnceWarningsForTests() {
907
+ warnedConsentUnverified = false;
908
+ warnedNoIdempotencyStore = false;
909
+ }
910
+ var MAX_TIMESTAMP_TOLERANCE_SECS = 86400;
911
+ var XWING_SEED_BYTES = 32;
912
+ function assertUsablePrivateKey(privateKeyPem) {
913
+ if (typeof privateKeyPem !== "string") {
914
+ if (!privateKeyPem || typeof privateKeyPem !== "object" || typeof privateKeyPem.name !== "string") {
915
+ throw new Error("[OneAddress SDK] privateKeyPem must be a PEM string or a PrivateKeyOperations delegate");
916
+ }
917
+ return;
918
+ }
919
+ if (privateKeyPem.trim() === "") {
920
+ throw new Error("[OneAddress SDK] privateKeyPem is required: set it to your PKCS#8 private key from the Partner Portal");
921
+ }
922
+ const der = pemToBuffer(privateKeyPem);
923
+ if (der.length === XWING_SEED_BYTES) return;
924
+ try {
925
+ crypto.createPrivateKey({ key: der, format: "der", type: "pkcs8" });
926
+ } catch (err) {
927
+ const refused = new Error(
928
+ `[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.`
929
+ );
930
+ refused.cause = err;
931
+ throw refused;
932
+ }
933
+ }
934
+ function requirePemFor(purpose, key) {
935
+ if (typeof key === "string") return key;
936
+ throw new Error(
937
+ `[OneAddress SDK] ${purpose} needs the raw private key; a PrivateKeyOperations delegate ("${key.name}") covers session envelopes only`
938
+ );
939
+ }
940
+ function assertLoaBoundToEnvelope(loa, envelopeUpdateUid) {
941
+ if (typeof loa.update_uid !== "string" || typeof envelopeUpdateUid !== "string") return;
942
+ if (loa.update_uid !== envelopeUpdateUid) {
943
+ throw new Error(
944
+ "[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"
945
+ );
946
+ }
947
+ }
795
948
  function createOneAddressHandler(options) {
796
949
  const {
797
950
  webhookSecret,
798
951
  previousWebhookSecret,
799
952
  webhookSecretGraceUntil,
800
953
  privateKeyPem,
954
+ expectedAlg,
801
955
  keyId,
802
956
  loaPublicKeyPem,
957
+ requireLoa = Boolean(loaPublicKeyPem),
958
+ confirm,
803
959
  onUpdate,
804
960
  onVerify,
805
961
  onAccountVerify,
@@ -809,6 +965,40 @@ function createOneAddressHandler(options) {
809
965
  acceptedUpdateTypes: acceptedUpdateTypesRaw,
810
966
  allowedCallbackHosts
811
967
  } = options;
968
+ if (typeof webhookSecret !== "string" || webhookSecret === "") {
969
+ throw new Error("[OneAddress SDK] webhookSecret is required: an empty secret would verify no signature at all");
970
+ }
971
+ assertUsablePrivateKey(privateKeyPem);
972
+ if (typeof timestampToleranceSecs !== "number" || !Number.isFinite(timestampToleranceSecs) || timestampToleranceSecs <= 0 || timestampToleranceSecs > MAX_TIMESTAMP_TOLERANCE_SECS) {
973
+ throw new Error(
974
+ `[OneAddress SDK] timestampToleranceSecs must be a positive number of seconds up to ${MAX_TIMESTAMP_TOLERANCE_SECS}, got ${String(timestampToleranceSecs)}`
975
+ );
976
+ }
977
+ if (webhookSecretGraceUntil !== void 0) {
978
+ const until = typeof webhookSecretGraceUntil === "number" ? webhookSecretGraceUntil : Date.parse(webhookSecretGraceUntil);
979
+ if (Number.isNaN(until)) {
980
+ throw new Error(`[OneAddress SDK] webhookSecretGraceUntil is not a date: ${String(webhookSecretGraceUntil)}`);
981
+ }
982
+ }
983
+ if (confirm && (!confirm.partnerId || !confirm.confirmSecret)) {
984
+ throw new Error("[OneAddress SDK] confirm needs both partnerId and confirmSecret");
985
+ }
986
+ function enforceLoaPresence(body) {
987
+ const present = !!body.loa_encrypted && typeof body.loa_encrypted === "object";
988
+ if (present) return;
989
+ if (requireLoa) {
990
+ throw new Error(
991
+ "[OneAddress SDK] dispatch carries no loa_encrypted and requireLoa is on: refusing to apply an update whose consent proof is missing"
992
+ );
993
+ }
994
+ if (!warnedConsentUnverified) {
995
+ warnedConsentUnverified = true;
996
+ console.warn(
997
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
998
+ "[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."
999
+ );
1000
+ }
1001
+ }
812
1002
  const acceptedUpdateTypes = normaliseAcceptedUpdateTypes(acceptedUpdateTypesRaw);
813
1003
  function declared(status, payload) {
814
1004
  return new Response(JSON.stringify({ ...payload, accepted_update_types: acceptedUpdateTypes }), {
@@ -818,7 +1008,7 @@ function createOneAddressHandler(options) {
818
1008
  }
819
1009
  async function buildD5Pieces(body, partnerId) {
820
1010
  const share = body.session_key_share;
821
- const data = await decryptSession(share, body.session_envelope, privateKeyPem, partnerId);
1011
+ const data = await decryptSession(share, body.session_envelope, privateKeyPem, partnerId, expectedAlg);
822
1012
  const updateTypes = readUpdateTypes(data.update_types);
823
1013
  if (updateTypes === null) throw new InvalidUpdateTypesError(data.update_types);
824
1014
  const address = updateTypes.includes("address") ? validateAddress({
@@ -843,13 +1033,15 @@ function createOneAddressHandler(options) {
843
1033
  loa = await decryptLoaEncrypted(
844
1034
  body.loa_encrypted,
845
1035
  privateKeyPem,
846
- partnerId
1036
+ partnerId,
1037
+ expectedAlg
847
1038
  );
848
1039
  loa_ref = d5LoaRef(loa);
849
1040
  if (loaPublicKeyPem) {
850
1041
  const valid = await verifyD5LOA(loa, loaPublicKeyPem);
851
1042
  if (!valid) throw new Error("D5 LOA signature verification failed");
852
1043
  }
1044
+ assertLoaBoundToEnvelope(loa, data.update_uid);
853
1045
  }
854
1046
  return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
855
1047
  }
@@ -882,7 +1074,11 @@ function createOneAddressHandler(options) {
882
1074
  }
883
1075
  let body;
884
1076
  try {
885
- body = JSON.parse(rawBody);
1077
+ const parsed = JSON.parse(rawBody);
1078
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1079
+ throw new TypeError("body is not a JSON object");
1080
+ }
1081
+ body = parsed;
886
1082
  } catch {
887
1083
  return new Response(JSON.stringify({ error: "Invalid JSON" }), {
888
1084
  status: 400,
@@ -904,11 +1100,19 @@ function createOneAddressHandler(options) {
904
1100
  }
905
1101
  if (dispatchId) {
906
1102
  if (!idempotencyStore) {
907
- if (process.env.NODE_ENV === "test") {
1103
+ const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
1104
+ if (nodeEnv === "test") {
908
1105
  throw new Error(
909
1106
  "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
910
1107
  );
911
1108
  }
1109
+ if (!warnedNoIdempotencyStore) {
1110
+ warnedNoIdempotencyStore = true;
1111
+ console.warn(
1112
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
1113
+ "[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."
1114
+ );
1115
+ }
912
1116
  } else if (idempotencyStore.claim) {
913
1117
  const claim = await idempotencyStore.claim(dispatchId);
914
1118
  if (claim === "duplicate") {
@@ -925,6 +1129,7 @@ function createOneAddressHandler(options) {
925
1129
  if (body.event === "address.updated" || body.event === "contact.updated") {
926
1130
  const wireEvent = body.event;
927
1131
  let event;
1132
+ enforceLoaPresence(body);
928
1133
  if (isD5Body(body)) {
929
1134
  let d5;
930
1135
  try {
@@ -977,19 +1182,25 @@ function createOneAddressHandler(options) {
977
1182
  });
978
1183
  }
979
1184
  const encrypted = body.address_encrypted;
980
- const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
1185
+ const rawAddress = await decryptAddress(
1186
+ encrypted,
1187
+ requirePemFor("legacy address_encrypted decryption", privateKeyPem),
1188
+ partnerId
1189
+ );
981
1190
  let loa;
982
1191
  let loa_ref;
983
1192
  if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
984
1193
  loa = await decryptLoaEncrypted(
985
1194
  body.loa_encrypted,
986
1195
  privateKeyPem,
987
- partnerId
1196
+ partnerId,
1197
+ expectedAlg
988
1198
  );
989
1199
  loa_ref = d5LoaRef(loa);
990
1200
  if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
991
1201
  throw new Error("D5 LOA signature verification failed");
992
1202
  }
1203
+ assertLoaBoundToEnvelope(loa, rawAddress.update_uid);
993
1204
  }
994
1205
  const customer = {
995
1206
  email: "",
@@ -1022,6 +1233,25 @@ function createOneAddressHandler(options) {
1022
1233
  // NOSONAR
1023
1234
  );
1024
1235
  }
1236
+ if (confirm && dispatchId) {
1237
+ const status = result && typeof result === "object" && result.status ? result.status : "confirmed";
1238
+ void confirmUpdate({
1239
+ partnerId: confirm.partnerId,
1240
+ secret: confirm.confirmSecret,
1241
+ dispatchId,
1242
+ status,
1243
+ loaRef: event.loa_ref,
1244
+ ...confirm.oneAddressApi ? { appBaseUrl: confirm.oneAddressApi } : {},
1245
+ ...confirm.fetchImpl ? { fetchImpl: confirm.fetchImpl } : {}
1246
+ }).then(
1247
+ (r) => {
1248
+ if (!r.ok) console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} failed: HTTP ${r.status} ${r.error ?? ""}`);
1249
+ },
1250
+ // NOSONAR
1251
+ (err) => console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} threw:`, err)
1252
+ // NOSONAR
1253
+ );
1254
+ }
1025
1255
  return declared(200, { ok: true, ...result });
1026
1256
  }
1027
1257
  if (body.event === "address.verify" && onVerify) {
@@ -1032,7 +1262,11 @@ function createOneAddressHandler(options) {
1032
1262
  });
1033
1263
  }
1034
1264
  const encrypted = body.address_encrypted;
1035
- const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
1265
+ const rawAddress = await decryptAddress(
1266
+ encrypted,
1267
+ requirePemFor("address.verify decryption", privateKeyPem),
1268
+ partnerId
1269
+ );
1036
1270
  const event = {
1037
1271
  event: "address.verify",
1038
1272
  version: body.oneaddress_version ?? body.version ?? "1",
@@ -1079,7 +1313,7 @@ function createOneAddressHandler(options) {
1079
1313
  if (body.customer_encrypted && typeof body.customer_encrypted === "object") {
1080
1314
  const raw = await decryptAddress(
1081
1315
  body.customer_encrypted,
1082
- privateKeyPem,
1316
+ requirePemFor("account.verify decryption", privateKeyPem),
1083
1317
  partnerId
1084
1318
  );
1085
1319
  customer = {
@@ -1125,7 +1359,12 @@ function createOneAddressHandler(options) {
1125
1359
  address: d5.address,
1126
1360
  raw: d5.raw
1127
1361
  });
1128
- return declared(200, { ok: true, test: true });
1362
+ return declared(200, {
1363
+ ok: true,
1364
+ test: true,
1365
+ verification: true,
1366
+ index: typeof body.index === "number" ? body.index : void 0
1367
+ });
1129
1368
  }
1130
1369
  const evt = typeof body.event === "string" ? body.event : "(none)";
1131
1370
  const callbackFor = {
@@ -1198,6 +1437,112 @@ function toExpressHandler(handler) {
1198
1437
  res.send(bodyText);
1199
1438
  };
1200
1439
  }
1440
+ async function buildSignedTestWebhook(opts) {
1441
+ const nowSecs = opts.timestamp ?? Math.floor(Date.now() / 1e3);
1442
+ const nowIso = new Date(nowSecs * 1e3).toISOString();
1443
+ const updateIdNum = crypto.randomInt(9e8, 901e6);
1444
+ const updateUid = opts.session?.update_uid ?? String(updateIdNum);
1445
+ const partnerKey = {
1446
+ partner_id: opts.partnerId,
1447
+ key_id: opts.keyId ?? "test-key-1",
1448
+ public_key_b64: pemToBase64(opts.publicKey),
1449
+ algorithm: opts.algorithm ?? "ECDH-P256-AES-GCM-256"
1450
+ };
1451
+ const kinds = readUpdateTypes(opts.session?.update_types) ?? ["address"];
1452
+ const sessionData = {
1453
+ v: 2,
1454
+ update_uid: updateUid,
1455
+ dispatch_timestamp: nowIso,
1456
+ verified_name: "Test Person",
1457
+ ...kinds.includes("address") ? { new_address: { street: "42 Collins Street", suburb: "Melbourne", state: "VIC", postcode: "3000", country: "AU" } } : {},
1458
+ ...kinds.includes("phone") ? { new_phone: "+61412345678" } : {},
1459
+ ...kinds.includes("email") ? { new_email: "test.person@example.com" } : {},
1460
+ account_number: "TEST-0001",
1461
+ id_verification_ref: crypto.randomUUID(),
1462
+ known_names: [],
1463
+ ...opts.session ?? {}
1464
+ };
1465
+ const envelope = await encryptSessionForPartner(sessionData, partnerKey);
1466
+ let loa;
1467
+ let loa_encrypted;
1468
+ if (opts.loa !== false) {
1469
+ loa = {
1470
+ consumer_name: sessionData.verified_name,
1471
+ authorisation_date: nowIso,
1472
+ scope: "Authority to update address records on file.",
1473
+ update_uid: updateUid,
1474
+ oneaddress_acn: "696 078 869",
1475
+ oneaddress_signature: "00".repeat(64),
1476
+ signature_algorithm: "ECDSA-P256",
1477
+ ...opts.loa ?? {}
1478
+ };
1479
+ if (opts.loaSigningKeyPem) {
1480
+ const key = await crypto.subtle.importKey(
1481
+ "pkcs8",
1482
+ pemToBuffer(opts.loaSigningKeyPem),
1483
+ { name: "ECDSA", namedCurve: "P-256" },
1484
+ false,
1485
+ ["sign"]
1486
+ );
1487
+ const sig2 = await crypto.subtle.sign(
1488
+ { name: "ECDSA", hash: "SHA-256" },
1489
+ key,
1490
+ new TextEncoder().encode(canonicalD5LoaForm(loa))
1491
+ );
1492
+ loa.oneaddress_signature = Buffer.from(sig2).toString("hex");
1493
+ }
1494
+ const sealed = await encryptEnvelopeForPartner(loa, partnerKey);
1495
+ loa_encrypted = { session_envelope: sealed.session_envelope, session_key_share: sealed.session_key_share };
1496
+ }
1497
+ const event = opts.event ?? (kinds.includes("address") ? "address.updated" : "contact.updated");
1498
+ const body = JSON.stringify({
1499
+ event,
1500
+ oneaddress_version: CURRENT_VERSION,
1501
+ // A NUMBER. The relay sends `user_updates.id`; `update_uid` inside the
1502
+ // envelope and the LOA is its string form, which is the relationship a
1503
+ // receiver uses to bind the decrypted authorisation to the update.
1504
+ update_id: updateIdNum,
1505
+ partner_id: opts.partnerId,
1506
+ user_id: opts.userId ?? "test:consumer",
1507
+ timestamp: nowIso,
1508
+ session_envelope: envelope.session_envelope,
1509
+ session_key_share: envelope.session_key_share,
1510
+ key_share_expiry: new Date((nowSecs + 90 * 24 * 3600) * 1e3).toISOString(),
1511
+ id_verification: { method: "identity_document", verified_at: nowIso, verified: true, platform: "oneaddress/v1" },
1512
+ ...loa_encrypted ? { loa_encrypted } : {},
1513
+ // On the wire with a `null` value when no PaymentIntent backed the update,
1514
+ // so the KEY is present either way.
1515
+ stripe_session_id: opts.stripeSessionId ?? null,
1516
+ // `id` and `crossover_key_ids` are crossover-only and therefore NOT emitted
1517
+ // by default. A test that needs them passes them through `extraBody`, which
1518
+ // is exactly the circumstance the relay emits them in.
1519
+ ...opts.extraBody ?? {}
1520
+ });
1521
+ const ts = String(nowSecs);
1522
+ const sig = crypto.createHmac("sha256", opts.webhookSecret).update(`${ts}.${body}`).digest("hex");
1523
+ const dispatchId = opts.dispatchId ?? "1";
1524
+ const headers = {
1525
+ "Content-Type": "application/json",
1526
+ "X-OneAddress-Event": event,
1527
+ "X-OneAddress-Partner": opts.partnerId,
1528
+ "X-OneAddress-Version": CURRENT_VERSION,
1529
+ "X-OneAddress-Timestamp": ts,
1530
+ "X-OneAddress-Signature": sig,
1531
+ ...dispatchId ? { "X-OneAddress-Dispatch": dispatchId } : {}
1532
+ };
1533
+ const lower = new Map(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]));
1534
+ return {
1535
+ body,
1536
+ headers,
1537
+ sessionData,
1538
+ loa,
1539
+ request: {
1540
+ text: async () => body,
1541
+ headers: { get: (name) => lower.get(name.toLowerCase()) ?? null }
1542
+ },
1543
+ toRequest: (url = "https://receiver.example/webhook") => new Request(url, { method: "POST", headers, body })
1544
+ };
1545
+ }
1201
1546
 
1202
1547
  export {
1203
1548
  CURRENT_VERSION,
@@ -1228,6 +1573,8 @@ export {
1228
1573
  formatAddressParts,
1229
1574
  compareAddresses,
1230
1575
  sendVerifyResult,
1576
+ _resetOnceWarningsForTests,
1231
1577
  createOneAddressHandler,
1232
- toExpressHandler
1578
+ toExpressHandler,
1579
+ buildSignedTestWebhook
1233
1580
  };