@oneaddress/partner-sdk 1.8.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-O2D5XGSN.mjs";
4
+ } from "./chunk-DUVPNFU6.mjs";
5
5
 
6
6
  // src/index.ts
7
7
  import crypto from "crypto";
@@ -378,13 +378,14 @@ 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-UOJOUUGB.mjs");
381
+ async function decryptSession(share, envelopeB64, privateKeyPem, partnerId, expectedAlg) {
382
+ const { decryptSession: decryptSessionCrypto } = await import("./src-UACTYQGX.mjs");
383
383
  return decryptSessionCrypto(
384
384
  share,
385
385
  envelopeB64,
386
386
  typeof privateKeyPem === "string" ? pemToBase64(privateKeyPem) : privateKeyPem,
387
- partnerId
387
+ partnerId,
388
+ expectedAlg
388
389
  );
389
390
  }
390
391
  async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
@@ -716,12 +717,32 @@ function compareAddresses(a, b) {
716
717
  if (aCountry && bCountry && aCountry !== bCountry) return false;
717
718
  return true;
718
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
+ }
719
737
  async function sendVerifyResult(params) {
720
- const { callbackUrl, callbackToken, batchId, partnerId, match, note } = params;
738
+ const { callbackUrl, callbackToken, batchId, partnerId, match, note, allowedCallbackHosts } = params;
721
739
  const safe = isSafeWebhookUrl(callbackUrl);
722
740
  if (!safe.ok) {
723
741
  throw new Error(`[OneAddress SDK] refusing verify-result callback to unsafe URL: ${safe.reason}`);
724
742
  }
743
+ if (!isAllowedCallbackHost(callbackUrl, allowedCallbackHosts)) {
744
+ throw new Error(`[OneAddress SDK] refusing verify-result callback to non-OneAddress host: ${callbackUrl}`);
745
+ }
725
746
  const res = await fetch(callbackUrl, {
726
747
  method: "POST",
727
748
  headers: { "Content-Type": "application/json" },
@@ -738,7 +759,38 @@ async function sendVerifyResult(params) {
738
759
  throw new Error(`[OneAddress SDK] verify-result callback to ${callbackUrl} failed: HTTP ${res.status}`);
739
760
  }
740
761
  }
741
- var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
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"];
742
794
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
743
795
  function createOneAddressHandler(options) {
744
796
  const {
@@ -746,25 +798,39 @@ function createOneAddressHandler(options) {
746
798
  previousWebhookSecret,
747
799
  webhookSecretGraceUntil,
748
800
  privateKeyPem,
801
+ keyId,
749
802
  loaPublicKeyPem,
750
803
  onUpdate,
751
804
  onVerify,
752
805
  onAccountVerify,
753
806
  onTest,
754
807
  timestampToleranceSecs = 300,
755
- idempotencyStore
808
+ idempotencyStore,
809
+ acceptedUpdateTypes: acceptedUpdateTypesRaw,
810
+ allowedCallbackHosts
756
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
+ }
757
819
  async function buildD5Pieces(body, partnerId) {
758
820
  const share = body.session_key_share;
759
821
  const data = await decryptSession(share, body.session_envelope, privateKeyPem, partnerId);
760
- 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({
761
825
  street: data.new_address?.street,
762
826
  suburb: data.new_address?.suburb,
763
827
  state: data.new_address?.state,
764
828
  postcode: data.new_address?.postcode,
765
829
  country: data.new_address?.country,
766
830
  updated_at: data.dispatch_timestamp ?? body.timestamp ?? ""
767
- });
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;
768
834
  const customer = {
769
835
  email: "",
770
836
  name: data.verified_name ?? "",
@@ -785,11 +851,19 @@ function createOneAddressHandler(options) {
785
851
  if (!valid) throw new Error("D5 LOA signature verification failed");
786
852
  }
787
853
  }
788
- return { address, customer, loa, loa_ref, raw: data };
854
+ return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
789
855
  }
790
856
  function isD5Body(body) {
791
857
  return typeof body.session_envelope === "string" && !!body.session_key_share && typeof body.session_key_share === "object";
792
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
+ }
793
867
  return async function handler(req) {
794
868
  const rawBody = await req.text();
795
869
  const sig = req.headers.get("x-oneaddress-signature") ?? "";
@@ -825,6 +899,9 @@ function createOneAddressHandler(options) {
825
899
  const partnerId = body.partner_id ?? "";
826
900
  const tsNum = Number(tsHeader);
827
901
  const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
902
+ if (isCrossoverSiblingToSkip(body)) {
903
+ return declared(200, { ok: true, skipped: true, crossover: true });
904
+ }
828
905
  if (dispatchId) {
829
906
  if (!idempotencyStore) {
830
907
  if (process.env.NODE_ENV === "test") {
@@ -835,41 +912,64 @@ function createOneAddressHandler(options) {
835
912
  } else if (idempotencyStore.claim) {
836
913
  const claim = await idempotencyStore.claim(dispatchId);
837
914
  if (claim === "duplicate") {
838
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
839
- status: 200,
840
- headers: { "Content-Type": "application/json" }
841
- });
915
+ return declared(200, { ok: true, duplicate: true });
842
916
  }
843
917
  } else {
844
918
  const alreadySeen = await idempotencyStore.has(dispatchId);
845
919
  if (alreadySeen) {
846
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
847
- status: 200,
848
- headers: { "Content-Type": "application/json" }
849
- });
920
+ return declared(200, { ok: true, duplicate: true });
850
921
  }
851
922
  }
852
923
  }
853
924
  try {
854
- if (body.event === "address.updated") {
925
+ if (body.event === "address.updated" || body.event === "contact.updated") {
926
+ const wireEvent = body.event;
855
927
  let event;
856
928
  if (isD5Body(body)) {
857
- 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
+ }
858
949
  event = {
859
- event: "address.updated",
950
+ event: wireEvent,
860
951
  version: body.oneaddress_version ?? body.version ?? "2.0",
861
952
  id: body.id ?? "",
862
953
  timestamp: tsNum,
863
954
  partner_id: partnerId,
864
955
  dispatchId,
865
956
  customer: d5.customer,
957
+ update_types: d5.updateTypes,
866
958
  address: d5.address,
959
+ new_phone: d5.newPhone,
960
+ new_email: d5.newEmail,
867
961
  loa: d5.loa,
868
962
  loa_ref: d5.loa_ref,
869
963
  id_verification: body.id_verification,
870
964
  raw: d5.raw
871
965
  };
872
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
+ }
873
973
  if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
874
974
  return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
875
975
  status: 400,
@@ -905,6 +1005,8 @@ function createOneAddressHandler(options) {
905
1005
  partner_id: partnerId,
906
1006
  dispatchId,
907
1007
  customer,
1008
+ // The legacy blob predates kinds and always carries an address.
1009
+ update_types: ["address"],
908
1010
  address: validateAddress(rawAddress),
909
1011
  loa,
910
1012
  loa_ref,
@@ -920,10 +1022,7 @@ function createOneAddressHandler(options) {
920
1022
  // NOSONAR
921
1023
  );
922
1024
  }
923
- return new Response(JSON.stringify({ ok: true, ...result }), {
924
- status: 200,
925
- headers: { "Content-Type": "application/json" }
926
- });
1025
+ return declared(200, { ok: true, ...result });
927
1026
  }
928
1027
  if (body.event === "address.verify" && onVerify) {
929
1028
  if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
@@ -966,16 +1065,14 @@ function createOneAddressHandler(options) {
966
1065
  batchId: body.batch_id ?? 0,
967
1066
  partnerId,
968
1067
  match: matched,
969
- note: result && typeof result.note === "string" ? result.note : void 0
1068
+ note: result && typeof result.note === "string" ? result.note : void 0,
1069
+ allowedCallbackHosts
970
1070
  });
971
1071
  } catch (err) {
972
1072
  console.error("[OneAddress SDK] verify-result callback failed:", err);
973
1073
  }
974
1074
  }
975
- return new Response(JSON.stringify({ ok: true, match: matched }), {
976
- status: 200,
977
- headers: { "Content-Type": "application/json" }
978
- });
1075
+ return declared(200, { ok: true, match: matched });
979
1076
  }
980
1077
  if (body.event === "account.verify" && onAccountVerify) {
981
1078
  let customer;
@@ -1006,10 +1103,7 @@ function createOneAddressHandler(options) {
1006
1103
  raw: body
1007
1104
  };
1008
1105
  const result = await onAccountVerify(event);
1009
- return new Response(JSON.stringify({ ok: true, ...result }), {
1010
- status: 200,
1011
- headers: { "Content-Type": "application/json" }
1012
- });
1106
+ return declared(200, { ok: true, ...result });
1013
1107
  }
1014
1108
  if ((body.event === "address.test" || body.event === "address.test-dispatch") && onTest) {
1015
1109
  if (!isD5Body(body)) {
@@ -1019,6 +1113,7 @@ function createOneAddressHandler(options) {
1019
1113
  });
1020
1114
  }
1021
1115
  const d5 = await buildD5Pieces(body, partnerId);
1116
+ if (!d5.address) throw new Error("[OneAddress SDK] test record carries no address");
1022
1117
  await onTest({
1023
1118
  event: body.event,
1024
1119
  index: typeof body.index === "number" ? body.index : void 0,
@@ -1030,10 +1125,7 @@ function createOneAddressHandler(options) {
1030
1125
  address: d5.address,
1031
1126
  raw: d5.raw
1032
1127
  });
1033
- return new Response(JSON.stringify({ ok: true, test: true }), {
1034
- status: 200,
1035
- headers: { "Content-Type": "application/json" }
1036
- });
1128
+ return declared(200, { ok: true, test: true });
1037
1129
  }
1038
1130
  const evt = typeof body.event === "string" ? body.event : "(none)";
1039
1131
  const callbackFor = {
@@ -1059,7 +1151,7 @@ function createOneAddressHandler(options) {
1059
1151
  // NOSONAR
1060
1152
  );
1061
1153
  }
1062
- 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 }), {
1063
1155
  status: 200,
1064
1156
  headers: { "Content-Type": "application/json" }
1065
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';