@oneaddress/partner-sdk 1.7.0 → 2.0.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,7 @@
1
1
  import {
2
2
  isFreshTimestamp,
3
3
  isSafeWebhookUrl
4
- } from "./chunk-TAZD6PFZ.mjs";
4
+ } from "./chunk-DUVPNFU6.mjs";
5
5
 
6
6
  // src/index.ts
7
7
  import crypto from "crypto";
@@ -378,9 +378,15 @@ async function decryptAddress(payload, privateKeyPem, partnerId) {
378
378
  );
379
379
  return JSON.parse(new TextDecoder().decode(plaintext));
380
380
  }
381
- async function decryptSession(share, envelopeB64, privateKeyPem, partnerId) {
382
- const { decryptSession: decryptSessionCrypto } = await import("./src-ESYTJ2EY.mjs");
383
- return decryptSessionCrypto(share, envelopeB64, pemToBase64(privateKeyPem), partnerId);
381
+ async function decryptSession(share, envelopeB64, privateKeyPem, partnerId, expectedAlg) {
382
+ const { decryptSession: decryptSessionCrypto } = await import("./src-UACTYQGX.mjs");
383
+ return decryptSessionCrypto(
384
+ share,
385
+ envelopeB64,
386
+ typeof privateKeyPem === "string" ? pemToBase64(privateKeyPem) : privateKeyPem,
387
+ partnerId,
388
+ expectedAlg
389
+ );
384
390
  }
385
391
  async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
386
392
  const plaintext = await decryptAddress(payload, privateKeyPem, partnerId);
@@ -711,12 +717,32 @@ function compareAddresses(a, b) {
711
717
  if (aCountry && bCountry && aCountry !== bCountry) return false;
712
718
  return true;
713
719
  }
720
+ function isAllowedCallbackHost(raw, extraHosts) {
721
+ let host;
722
+ try {
723
+ const u = new URL(raw);
724
+ if (u.protocol !== "https:") return false;
725
+ host = u.hostname.toLowerCase();
726
+ } catch {
727
+ return false;
728
+ }
729
+ if (host === "oneaddress.io" || host.endsWith(".oneaddress.io")) return true;
730
+ const envRaw = typeof process !== "undefined" ? process.env?.OA_CALLBACK_HOST_ALLOWLIST ?? "" : "";
731
+ const allowed = [
732
+ ...envRaw.split(",").map((h) => h.trim().toLowerCase()),
733
+ ...(extraHosts ?? []).map((h) => h.trim().toLowerCase())
734
+ ].filter(Boolean);
735
+ return allowed.includes(host);
736
+ }
714
737
  async function sendVerifyResult(params) {
715
- const { callbackUrl, callbackToken, batchId, partnerId, match, note } = params;
738
+ const { callbackUrl, callbackToken, batchId, partnerId, match, note, allowedCallbackHosts } = params;
716
739
  const safe = isSafeWebhookUrl(callbackUrl);
717
740
  if (!safe.ok) {
718
741
  throw new Error(`[OneAddress SDK] refusing verify-result callback to unsafe URL: ${safe.reason}`);
719
742
  }
743
+ if (!isAllowedCallbackHost(callbackUrl, allowedCallbackHosts)) {
744
+ throw new Error(`[OneAddress SDK] refusing verify-result callback to non-OneAddress host: ${callbackUrl}`);
745
+ }
720
746
  const res = await fetch(callbackUrl, {
721
747
  method: "POST",
722
748
  headers: { "Content-Type": "application/json" },
@@ -733,7 +759,38 @@ async function sendVerifyResult(params) {
733
759
  throw new Error(`[OneAddress SDK] verify-result callback to ${callbackUrl} failed: HTTP ${res.status}`);
734
760
  }
735
761
  }
736
- var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test"];
762
+ var UPDATE_TYPE_ORDER = ["address", "phone", "email"];
763
+ function normaliseAcceptedUpdateTypes(raw) {
764
+ const kept = new Set(Array.isArray(raw) ? raw.filter((v) => typeof v === "string") : []);
765
+ return UPDATE_TYPE_ORDER.filter((t) => t === "address" || kept.has(t));
766
+ }
767
+ function readUpdateTypes(raw) {
768
+ if (raw === void 0 || raw === null) return ["address"];
769
+ if (!Array.isArray(raw)) return null;
770
+ if (raw.length === 0) return ["address"];
771
+ const out = [];
772
+ for (const v of raw) {
773
+ if (typeof v !== "string" || !UPDATE_TYPE_ORDER.includes(v)) return null;
774
+ if (!out.includes(v)) out.push(v);
775
+ }
776
+ return out;
777
+ }
778
+ var InvalidUpdateTypesError = class extends Error {
779
+ constructor(raw) {
780
+ super("[OneAddress SDK] update_types names a kind this build does not know");
781
+ this.raw = raw;
782
+ this.name = "InvalidUpdateTypesError";
783
+ }
784
+ };
785
+ function requireContactValue(kind, value) {
786
+ if (typeof value !== "string" || value === "") {
787
+ throw new Error(
788
+ `[OneAddress SDK] Decrypted envelope declares update_types "${kind}" but carries no new_${kind}. This may indicate a decryption error or a schema change. Update @oneaddress/partner-sdk.`
789
+ );
790
+ }
791
+ return value;
792
+ }
793
+ var HANDLED_EVENTS = ["address.updated", "contact.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
737
794
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
738
795
  function createOneAddressHandler(options) {
739
796
  const {
@@ -741,25 +798,39 @@ function createOneAddressHandler(options) {
741
798
  previousWebhookSecret,
742
799
  webhookSecretGraceUntil,
743
800
  privateKeyPem,
801
+ keyId,
744
802
  loaPublicKeyPem,
745
803
  onUpdate,
746
804
  onVerify,
747
805
  onAccountVerify,
748
806
  onTest,
749
807
  timestampToleranceSecs = 300,
750
- idempotencyStore
808
+ idempotencyStore,
809
+ acceptedUpdateTypes: acceptedUpdateTypesRaw,
810
+ allowedCallbackHosts
751
811
  } = options;
812
+ const acceptedUpdateTypes = normaliseAcceptedUpdateTypes(acceptedUpdateTypesRaw);
813
+ function declared(status, payload) {
814
+ return new Response(JSON.stringify({ ...payload, accepted_update_types: acceptedUpdateTypes }), {
815
+ status,
816
+ headers: { "Content-Type": "application/json" }
817
+ });
818
+ }
752
819
  async function buildD5Pieces(body, partnerId) {
753
820
  const share = body.session_key_share;
754
821
  const data = await decryptSession(share, body.session_envelope, privateKeyPem, partnerId);
755
- const address = validateAddress({
822
+ const updateTypes = readUpdateTypes(data.update_types);
823
+ if (updateTypes === null) throw new InvalidUpdateTypesError(data.update_types);
824
+ const address = updateTypes.includes("address") ? validateAddress({
756
825
  street: data.new_address?.street,
757
826
  suburb: data.new_address?.suburb,
758
827
  state: data.new_address?.state,
759
828
  postcode: data.new_address?.postcode,
760
829
  country: data.new_address?.country,
761
830
  updated_at: data.dispatch_timestamp ?? body.timestamp ?? ""
762
- });
831
+ }) : void 0;
832
+ const newPhone = updateTypes.includes("phone") ? requireContactValue("phone", data.new_phone) : void 0;
833
+ const newEmail = updateTypes.includes("email") ? requireContactValue("email", data.new_email) : void 0;
763
834
  const customer = {
764
835
  email: "",
765
836
  name: data.verified_name ?? "",
@@ -780,11 +851,19 @@ function createOneAddressHandler(options) {
780
851
  if (!valid) throw new Error("D5 LOA signature verification failed");
781
852
  }
782
853
  }
783
- return { address, customer, loa, loa_ref, raw: data };
854
+ return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
784
855
  }
785
856
  function isD5Body(body) {
786
857
  return typeof body.session_envelope === "string" && !!body.session_key_share && typeof body.session_key_share === "object";
787
858
  }
859
+ function isCrossoverSiblingToSkip(body) {
860
+ if (!keyId || !isD5Body(body)) return false;
861
+ const share = body.session_key_share;
862
+ const shareKeyId = typeof share?.key_id === "string" ? share.key_id : "";
863
+ if (!shareKeyId || shareKeyId === keyId) return false;
864
+ const siblings = body.crossover_key_ids;
865
+ return Array.isArray(siblings) && siblings.includes(keyId);
866
+ }
788
867
  return async function handler(req) {
789
868
  const rawBody = await req.text();
790
869
  const sig = req.headers.get("x-oneaddress-signature") ?? "";
@@ -820,6 +899,9 @@ function createOneAddressHandler(options) {
820
899
  const partnerId = body.partner_id ?? "";
821
900
  const tsNum = Number(tsHeader);
822
901
  const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
902
+ if (isCrossoverSiblingToSkip(body)) {
903
+ return declared(200, { ok: true, skipped: true, crossover: true });
904
+ }
823
905
  if (dispatchId) {
824
906
  if (!idempotencyStore) {
825
907
  if (process.env.NODE_ENV === "test") {
@@ -830,41 +912,64 @@ function createOneAddressHandler(options) {
830
912
  } else if (idempotencyStore.claim) {
831
913
  const claim = await idempotencyStore.claim(dispatchId);
832
914
  if (claim === "duplicate") {
833
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
834
- status: 200,
835
- headers: { "Content-Type": "application/json" }
836
- });
915
+ return declared(200, { ok: true, duplicate: true });
837
916
  }
838
917
  } else {
839
918
  const alreadySeen = await idempotencyStore.has(dispatchId);
840
919
  if (alreadySeen) {
841
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
842
- status: 200,
843
- headers: { "Content-Type": "application/json" }
844
- });
920
+ return declared(200, { ok: true, duplicate: true });
845
921
  }
846
922
  }
847
923
  }
848
924
  try {
849
- if (body.event === "address.updated") {
925
+ if (body.event === "address.updated" || body.event === "contact.updated") {
926
+ const wireEvent = body.event;
850
927
  let event;
851
928
  if (isD5Body(body)) {
852
- const d5 = await buildD5Pieces(body, partnerId);
929
+ let d5;
930
+ try {
931
+ d5 = await buildD5Pieces(body, partnerId);
932
+ } catch (err) {
933
+ if (err instanceof InvalidUpdateTypesError) {
934
+ return declared(422, {
935
+ error: "invalid_update_types",
936
+ detail: "update_types must be an array of " + UPDATE_TYPE_ORDER.join("|") + ". A name this build does not know was refused rather than dropped. Update @oneaddress/partner-sdk."
937
+ });
938
+ }
939
+ throw err;
940
+ }
941
+ const notAccepted = d5.updateTypes.filter((t) => !acceptedUpdateTypes.includes(t));
942
+ if (notAccepted.length > 0) {
943
+ return declared(422, {
944
+ error: "update_type_not_accepted",
945
+ update_types: notAccepted,
946
+ detail: "This receiver declares acceptedUpdateTypes " + JSON.stringify(acceptedUpdateTypes) + " and the dispatch carries " + JSON.stringify(d5.updateTypes) + ". Nothing was processed. Widen acceptedUpdateTypes once onUpdate stores the new kind, then re-run conformance."
947
+ });
948
+ }
853
949
  event = {
854
- event: "address.updated",
950
+ event: wireEvent,
855
951
  version: body.oneaddress_version ?? body.version ?? "2.0",
856
952
  id: body.id ?? "",
857
953
  timestamp: tsNum,
858
954
  partner_id: partnerId,
859
955
  dispatchId,
860
956
  customer: d5.customer,
957
+ update_types: d5.updateTypes,
861
958
  address: d5.address,
959
+ new_phone: d5.newPhone,
960
+ new_email: d5.newEmail,
862
961
  loa: d5.loa,
863
962
  loa_ref: d5.loa_ref,
864
963
  id_verification: body.id_verification,
865
964
  raw: d5.raw
866
965
  };
867
966
  } else {
967
+ if (wireEvent === "contact.updated") {
968
+ return declared(400, {
969
+ error: "missing_session_envelope",
970
+ detail: "contact.updated requires session_envelope + session_key_share"
971
+ });
972
+ }
868
973
  if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
869
974
  return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
870
975
  status: 400,
@@ -900,6 +1005,8 @@ function createOneAddressHandler(options) {
900
1005
  partner_id: partnerId,
901
1006
  dispatchId,
902
1007
  customer,
1008
+ // The legacy blob predates kinds and always carries an address.
1009
+ update_types: ["address"],
903
1010
  address: validateAddress(rawAddress),
904
1011
  loa,
905
1012
  loa_ref,
@@ -915,10 +1022,7 @@ function createOneAddressHandler(options) {
915
1022
  // NOSONAR
916
1023
  );
917
1024
  }
918
- return new Response(JSON.stringify({ ok: true, ...result }), {
919
- status: 200,
920
- headers: { "Content-Type": "application/json" }
921
- });
1025
+ return declared(200, { ok: true, ...result });
922
1026
  }
923
1027
  if (body.event === "address.verify" && onVerify) {
924
1028
  if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
@@ -961,16 +1065,14 @@ function createOneAddressHandler(options) {
961
1065
  batchId: body.batch_id ?? 0,
962
1066
  partnerId,
963
1067
  match: matched,
964
- note: result && typeof result.note === "string" ? result.note : void 0
1068
+ note: result && typeof result.note === "string" ? result.note : void 0,
1069
+ allowedCallbackHosts
965
1070
  });
966
1071
  } catch (err) {
967
1072
  console.error("[OneAddress SDK] verify-result callback failed:", err);
968
1073
  }
969
1074
  }
970
- return new Response(JSON.stringify({ ok: true, match: matched }), {
971
- status: 200,
972
- headers: { "Content-Type": "application/json" }
973
- });
1075
+ return declared(200, { ok: true, match: matched });
974
1076
  }
975
1077
  if (body.event === "account.verify" && onAccountVerify) {
976
1078
  let customer;
@@ -1001,21 +1103,19 @@ function createOneAddressHandler(options) {
1001
1103
  raw: body
1002
1104
  };
1003
1105
  const result = await onAccountVerify(event);
1004
- return new Response(JSON.stringify({ ok: true, ...result }), {
1005
- status: 200,
1006
- headers: { "Content-Type": "application/json" }
1007
- });
1106
+ return declared(200, { ok: true, ...result });
1008
1107
  }
1009
- if (body.event === "address.test" && onTest) {
1108
+ if ((body.event === "address.test" || body.event === "address.test-dispatch") && onTest) {
1010
1109
  if (!isD5Body(body)) {
1011
- return new Response(JSON.stringify({ error: "address.test requires a session envelope" }), {
1110
+ return new Response(JSON.stringify({ error: "a test dispatch requires a session envelope" }), {
1012
1111
  status: 400,
1013
1112
  headers: { "Content-Type": "application/json" }
1014
1113
  });
1015
1114
  }
1016
1115
  const d5 = await buildD5Pieces(body, partnerId);
1116
+ if (!d5.address) throw new Error("[OneAddress SDK] test record carries no address");
1017
1117
  await onTest({
1018
- event: "address.test",
1118
+ event: body.event,
1019
1119
  index: typeof body.index === "number" ? body.index : void 0,
1020
1120
  total: typeof body.total === "number" ? body.total : void 0,
1021
1121
  verification_id: typeof body.verification_id === "string" ? body.verification_id : void 0,
@@ -1025,21 +1125,23 @@ function createOneAddressHandler(options) {
1025
1125
  address: d5.address,
1026
1126
  raw: d5.raw
1027
1127
  });
1028
- return new Response(JSON.stringify({ ok: true, test: true }), {
1029
- status: 200,
1030
- headers: { "Content-Type": "application/json" }
1031
- });
1128
+ return declared(200, { ok: true, test: true });
1032
1129
  }
1033
1130
  const evt = typeof body.event === "string" ? body.event : "(none)";
1034
1131
  const callbackFor = {
1035
1132
  "address.verify": onVerify,
1036
1133
  "account.verify": onAccountVerify,
1037
- "address.test": onTest
1134
+ "address.test": onTest,
1135
+ // Same callback as address.test: both test variants route to onTest, so
1136
+ // an unwired stress-test event must name onTest too — not fall through
1137
+ // to the "upgrade the SDK" remedy, which cannot help (marlowe-reports#126).
1138
+ "address.test-dispatch": onTest
1038
1139
  };
1039
1140
  const callbackNameFor = {
1040
1141
  "address.verify": "onVerify",
1041
1142
  "account.verify": "onAccountVerify",
1042
- "address.test": "onTest"
1143
+ "address.test": "onTest",
1144
+ "address.test-dispatch": "onTest"
1043
1145
  };
1044
1146
  const unwired = evt in callbackFor && !callbackFor[evt] ? callbackNameFor[evt] : null;
1045
1147
  if (!warnedUnhandledEvents.has(evt)) {
@@ -1049,7 +1151,7 @@ function createOneAddressHandler(options) {
1049
1151
  // NOSONAR
1050
1152
  );
1051
1153
  }
1052
- return new Response(JSON.stringify({ ok: true, skipped: true, event: evt }), {
1154
+ return new Response(JSON.stringify({ ok: true, skipped: true, event: evt, accepted_update_types: acceptedUpdateTypes }), {
1053
1155
  status: 200,
1054
1156
  headers: { "Content-Type": "application/json" }
1055
1157
  });
package/dist/edge.d.mts CHANGED
@@ -1 +1 @@
1
- export { BlindIndexField, CURRENT_VERSION, ComparableAddress, DEFAULT_REPLAY_WINDOW_SECS, EncryptedPayload, OneAddressAccountVerifyEvent, OneAddressAddress, OneAddressCustomer, OneAddressCustomerMatch, OneAddressD5LOA, OneAddressHandlerOptions, OneAddressIdVerification, OneAddressLOA, OneAddressUpdateEvent, OneAddressVerifyEvent, SUPPORTED_VERSIONS, SessionData, SessionKeyShare, VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, createOneAddressHandler, d5LoaRef, decrypt as decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, sendVerifyResult, transform as transformAddress, transformSession, validateAddress, verifyD5LOA, verifyLOA, verify as verifySignature, verifyGrace as verifyWithGrace } from './index.mjs';
1
+ export { BlindIndexField, CURRENT_VERSION, ComparableAddress, DEFAULT_REPLAY_WINDOW_SECS, EncryptedPayload, OneAddressAccountVerifyEvent, OneAddressAddress, OneAddressCustomer, OneAddressCustomerMatch, OneAddressD5LOA, OneAddressHandlerOptions, OneAddressIdVerification, OneAddressLOA, OneAddressUpdateEvent, OneAddressVerifyEvent, SUPPORTED_VERSIONS, SessionData, SessionKeyShare, SessionUpdateType, VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, createOneAddressHandler, d5LoaRef, decrypt as decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, sendVerifyResult, transform as transformAddress, transformSession, validateAddress, verifyD5LOA, verifyLOA, verify as verifySignature, verifyGrace as verifyWithGrace } from './index.mjs';
package/dist/edge.d.ts CHANGED
@@ -1 +1 @@
1
- export { BlindIndexField, CURRENT_VERSION, ComparableAddress, DEFAULT_REPLAY_WINDOW_SECS, EncryptedPayload, OneAddressAccountVerifyEvent, OneAddressAddress, OneAddressCustomer, OneAddressCustomerMatch, OneAddressD5LOA, OneAddressHandlerOptions, OneAddressIdVerification, OneAddressLOA, OneAddressUpdateEvent, OneAddressVerifyEvent, SUPPORTED_VERSIONS, SessionData, SessionKeyShare, VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, createOneAddressHandler, d5LoaRef, decrypt as decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, sendVerifyResult, transform as transformAddress, transformSession, validateAddress, verifyD5LOA, verifyLOA, verify as verifySignature, verifyGrace as verifyWithGrace } from './index.js';
1
+ export { BlindIndexField, CURRENT_VERSION, ComparableAddress, DEFAULT_REPLAY_WINDOW_SECS, EncryptedPayload, OneAddressAccountVerifyEvent, OneAddressAddress, OneAddressCustomer, OneAddressCustomerMatch, OneAddressD5LOA, OneAddressHandlerOptions, OneAddressIdVerification, OneAddressLOA, OneAddressUpdateEvent, OneAddressVerifyEvent, SUPPORTED_VERSIONS, SessionData, SessionKeyShare, SessionUpdateType, VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, createOneAddressHandler, d5LoaRef, decrypt as decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, sendVerifyResult, transform as transformAddress, transformSession, validateAddress, verifyD5LOA, verifyLOA, verify as verifySignature, verifyGrace as verifyWithGrace } from './index.js';