@oneaddress/partner-sdk 2.6.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/CHANGELOG.md +170 -0
- package/README.md +184 -61
- package/dist/{chunk-XPQERNNN.mjs → chunk-BFSYMDJI.mjs} +545 -53
- package/dist/{chunk-QAOGKPD3.mjs → chunk-PP2TM7HN.mjs} +1263 -112
- package/dist/edge.d.mts +1 -1
- package/dist/edge.d.ts +1 -1
- package/dist/edge.js +1782 -160
- package/dist/edge.mjs +28 -2
- package/dist/index.d.mts +415 -52
- package/dist/index.d.ts +415 -52
- package/dist/index.js +1881 -167
- package/dist/index.mjs +50 -2
- package/dist/{src-BPES2DKY.mjs → src-P3LR7F4A.mjs} +13 -1
- package/package.json +1 -1
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
isFreshTimestamp,
|
|
6
6
|
isSafeWebhookUrl,
|
|
7
7
|
verifyRegistryHead
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-PP2TM7HN.mjs";
|
|
9
9
|
|
|
10
10
|
// src/index.ts
|
|
11
11
|
import crypto from "crypto";
|
|
@@ -23,7 +23,6 @@ var D5_BODY_ALWAYS = [
|
|
|
23
23
|
"partner_id",
|
|
24
24
|
"session_envelope",
|
|
25
25
|
"session_key_share",
|
|
26
|
-
"stripe_session_id",
|
|
27
26
|
"timestamp",
|
|
28
27
|
"update_id",
|
|
29
28
|
"user_id"
|
|
@@ -47,10 +46,12 @@ var D5_BODY_CONDITIONAL = {
|
|
|
47
46
|
crossover_key_ids: "key-crossover copy only"
|
|
48
47
|
};
|
|
49
48
|
var D5_BODY_DRILL_ONLY = ["conformance"];
|
|
49
|
+
var D5_BODY_ADDED_AT_SEND = ["dispatch_id"];
|
|
50
50
|
var D5_BODY_ALL_ALLOWED = [
|
|
51
51
|
...D5_BODY_ALWAYS,
|
|
52
52
|
...Object.keys(D5_BODY_CONDITIONAL),
|
|
53
|
-
...D5_BODY_DRILL_ONLY
|
|
53
|
+
...D5_BODY_DRILL_ONLY,
|
|
54
|
+
...D5_BODY_ADDED_AT_SEND
|
|
54
55
|
];
|
|
55
56
|
|
|
56
57
|
// ../protocol/src/retention.ts
|
|
@@ -71,6 +72,116 @@ function keyShareExpiryIso(dispatchAt, retentionPeriodDays) {
|
|
|
71
72
|
return new Date(dispatchAt.getTime() + days * DAY_MS).toISOString();
|
|
72
73
|
}
|
|
73
74
|
|
|
75
|
+
// ../protocol/src/pull-signature.ts
|
|
76
|
+
var PULL_SIGNATURE_VERSION_HEADER = "X-OneAddress-Signature-Version";
|
|
77
|
+
function pullSigningStringV2(timestamp, method, pathAndQuery, body = "") {
|
|
78
|
+
return `v2.${timestamp}.${method.toUpperCase()}.${pathAndQuery}.${body}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// ../protocol/src/loa-v2.ts
|
|
82
|
+
var LOA_V2_VERSION_TAG = "oneaddress-loa/2";
|
|
83
|
+
var LOA_V2_LEGACY_ENVELOPE_TAG = "oneaddress-legacy-envelope/1";
|
|
84
|
+
var LOA_V2_FIELD_ORDER = [
|
|
85
|
+
"consumer_name",
|
|
86
|
+
"authorisation_date",
|
|
87
|
+
"scope",
|
|
88
|
+
"update_uid",
|
|
89
|
+
"partner_id",
|
|
90
|
+
"envelope_sha256"
|
|
91
|
+
];
|
|
92
|
+
var LOA_MAX_TYPED_ALIASES = 3;
|
|
93
|
+
var LoaV2FieldError = class extends Error {
|
|
94
|
+
constructor(field, reason) {
|
|
95
|
+
super(`LOA v2 field ${field} ${reason}`);
|
|
96
|
+
this.field = field;
|
|
97
|
+
this.name = "LoaV2FieldError";
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
var CONTROL_RE = /[\u0000-\u001F\u007F]/;
|
|
101
|
+
var LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
|
|
102
|
+
function utf8Length(s) {
|
|
103
|
+
return new TextEncoder().encode(s).length;
|
|
104
|
+
}
|
|
105
|
+
function encodeField(name, value) {
|
|
106
|
+
if (typeof value !== "string") throw new LoaV2FieldError(name, "is not a string");
|
|
107
|
+
if (CONTROL_RE.test(value)) throw new LoaV2FieldError(name, "contains a control character");
|
|
108
|
+
if (LONE_SURROGATE_RE.test(value)) throw new LoaV2FieldError(name, "is not well-formed Unicode");
|
|
109
|
+
return `${utf8Length(value)}:${value}
|
|
110
|
+
`;
|
|
111
|
+
}
|
|
112
|
+
function canonicalLoaV2(fields) {
|
|
113
|
+
let out = encodeField("version", LOA_V2_VERSION_TAG);
|
|
114
|
+
for (const f of LOA_V2_FIELD_ORDER) out += encodeField(f, fields[f]);
|
|
115
|
+
const aliases = fields.consumer_typed_aliases;
|
|
116
|
+
if (!Array.isArray(aliases)) throw new LoaV2FieldError("consumer_typed_aliases", "is not a list");
|
|
117
|
+
if (aliases.length > LOA_MAX_TYPED_ALIASES) {
|
|
118
|
+
throw new LoaV2FieldError("consumer_typed_aliases", `has more than ${LOA_MAX_TYPED_ALIASES} entries`);
|
|
119
|
+
}
|
|
120
|
+
out += encodeField("consumer_typed_aliases", String(aliases.length));
|
|
121
|
+
for (const a of aliases) out += encodeField("consumer_typed_aliases", a);
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
function loaV2EnvelopeDigestInput(envelope) {
|
|
125
|
+
if (typeof envelope === "string") return envelope;
|
|
126
|
+
if (!envelope || typeof envelope !== "object") {
|
|
127
|
+
throw new LoaV2FieldError("envelope", "is neither a session_envelope string nor an address_encrypted object");
|
|
128
|
+
}
|
|
129
|
+
return encodeField("tag", LOA_V2_LEGACY_ENVELOPE_TAG) + encodeField("ephemeralPublicKey", envelope.ephemeralPublicKey) + encodeField("iv", envelope.iv) + encodeField("ciphertext", envelope.ciphertext) + encodeField("hkdfSalt", envelope.hkdfSalt ?? "");
|
|
130
|
+
}
|
|
131
|
+
var ASCII_WS_RE = /[ \t\n\v\f\r]+/;
|
|
132
|
+
var MARK_RE = /\p{M}/gu;
|
|
133
|
+
function normaliseLoaName(name) {
|
|
134
|
+
return name.normalize("NFKD").replace(MARK_RE, "").toLowerCase().replace(/\u03C2/g, "\u03C3").split(ASCII_WS_RE).filter((t) => t.length > 0).join(" ");
|
|
135
|
+
}
|
|
136
|
+
function loaSurname(name) {
|
|
137
|
+
const tokens = normaliseLoaName(name).split(" ").filter((t) => t.length > 0);
|
|
138
|
+
return tokens.length > 0 ? tokens[tokens.length - 1] : "";
|
|
139
|
+
}
|
|
140
|
+
function loaFirstName(name) {
|
|
141
|
+
const tokens = normaliseLoaName(name).split(" ").filter((t) => t.length > 0);
|
|
142
|
+
return tokens.length > 0 ? tokens[0] : "";
|
|
143
|
+
}
|
|
144
|
+
function loaNamesMatch(a, b) {
|
|
145
|
+
const na = normaliseLoaName(a);
|
|
146
|
+
return na.length > 0 && na === normaliseLoaName(b);
|
|
147
|
+
}
|
|
148
|
+
var LOA_MIN_SHORT_FORM_LETTERS = 3;
|
|
149
|
+
function codePoints(s) {
|
|
150
|
+
return Array.from(s).length;
|
|
151
|
+
}
|
|
152
|
+
function isAcceptableAlias(verifiedName, alias) {
|
|
153
|
+
const vFirst = loaFirstName(verifiedName);
|
|
154
|
+
const aFirst = loaFirstName(alias);
|
|
155
|
+
if (!vFirst || !aFirst) return false;
|
|
156
|
+
if (aFirst === vFirst) return true;
|
|
157
|
+
const [shorter, longer] = codePoints(aFirst) <= codePoints(vFirst) ? [aFirst, vFirst] : [vFirst, aFirst];
|
|
158
|
+
return codePoints(shorter) >= LOA_MIN_SHORT_FORM_LETTERS && longer.startsWith(shorter);
|
|
159
|
+
}
|
|
160
|
+
function acceptTypedAliases(verifiedName, aliases) {
|
|
161
|
+
const out = [];
|
|
162
|
+
if (!Array.isArray(aliases)) return out;
|
|
163
|
+
const seen = /* @__PURE__ */ new Set([normaliseLoaName(verifiedName)]);
|
|
164
|
+
for (const a of aliases) {
|
|
165
|
+
if (out.length >= LOA_MAX_TYPED_ALIASES) break;
|
|
166
|
+
if (typeof a !== "string") continue;
|
|
167
|
+
if (CONTROL_RE.test(a) || LONE_SURROGATE_RE.test(a)) continue;
|
|
168
|
+
const n = normaliseLoaName(a);
|
|
169
|
+
if (!n || seen.has(n)) continue;
|
|
170
|
+
if (!isAcceptableAlias(verifiedName, a)) continue;
|
|
171
|
+
seen.add(n);
|
|
172
|
+
out.push(a);
|
|
173
|
+
}
|
|
174
|
+
return out;
|
|
175
|
+
}
|
|
176
|
+
var LOA_V2_REFUSALS = [
|
|
177
|
+
"loa_v2_malformed",
|
|
178
|
+
"loa_v2_signature_invalid",
|
|
179
|
+
"loa_v2_partner_mismatch",
|
|
180
|
+
"loa_v2_update_mismatch",
|
|
181
|
+
"loa_v2_envelope_mismatch",
|
|
182
|
+
"loa_v2_name_mismatch"
|
|
183
|
+
];
|
|
184
|
+
|
|
74
185
|
// src/app-hosts.ts
|
|
75
186
|
function allowedAppHosts() {
|
|
76
187
|
const hosts = ["oneaddress.io", "app.oneaddress.io"];
|
|
@@ -79,7 +190,7 @@ function allowedAppHosts() {
|
|
|
79
190
|
}
|
|
80
191
|
return new Set(hosts);
|
|
81
192
|
}
|
|
82
|
-
function resolveAppOrigin(baseUrl, label) {
|
|
193
|
+
function resolveAppOrigin(baseUrl, label, extraHosts) {
|
|
83
194
|
let parsed;
|
|
84
195
|
try {
|
|
85
196
|
parsed = new URL(baseUrl);
|
|
@@ -87,6 +198,9 @@ function resolveAppOrigin(baseUrl, label) {
|
|
|
87
198
|
throw new Error(`[OneAddress SDK] ${label}: appBaseUrl is not a valid URL`);
|
|
88
199
|
}
|
|
89
200
|
const allowed = allowedAppHosts();
|
|
201
|
+
for (const h of extraHosts ?? []) {
|
|
202
|
+
if (typeof h === "string" && h.trim() !== "") allowed.add(h.trim().toLowerCase());
|
|
203
|
+
}
|
|
90
204
|
if (!allowed.has(parsed.hostname)) {
|
|
91
205
|
throw new Error(
|
|
92
206
|
`[OneAddress SDK] ${label}: appBaseUrl host must be one of: ${[...allowed].join(", ")}`
|
|
@@ -118,26 +232,38 @@ function surnameVariants(token) {
|
|
|
118
232
|
if (!token.includes("-")) return [token];
|
|
119
233
|
return [token, ...token.split("-").filter(Boolean)];
|
|
120
234
|
}
|
|
235
|
+
var MAX_ALIASES = 10;
|
|
236
|
+
var MAX_TOKENS_PER_NAME = 8;
|
|
237
|
+
var MAX_POOL_TOKENS = 24;
|
|
121
238
|
function namePoolMatches(providedNames, storedName) {
|
|
122
239
|
if (isEmailLike(storedName)) return false;
|
|
123
|
-
const provided = providedNames.filter((n) =>
|
|
240
|
+
const provided = providedNames.filter((n) => typeof n === "string" && n !== "" && !isEmailLike(n));
|
|
124
241
|
const primary = tokenize(provided[0] ?? "");
|
|
125
|
-
if (primary.length === 0) return false;
|
|
242
|
+
if (primary.length === 0 || primary.length > MAX_TOKENS_PER_NAME) return false;
|
|
243
|
+
const aliases = provided.slice(1, 1 + MAX_ALIASES).map(tokenize).filter((t) => t.length > 0 && t.length <= MAX_TOKENS_PER_NAME);
|
|
244
|
+
const distinct = new Set(primary);
|
|
245
|
+
for (const t of aliases) for (const tok of t) distinct.add(tok);
|
|
246
|
+
if (distinct.size > MAX_POOL_TOKENS) return false;
|
|
126
247
|
const surnames = new Set(surnameVariants(primary[primary.length - 1]));
|
|
127
|
-
for (
|
|
128
|
-
const
|
|
129
|
-
if (t.length >= 2) for (const v of surnameVariants(
|
|
130
|
-
}
|
|
131
|
-
const
|
|
132
|
-
for (const
|
|
133
|
-
const
|
|
248
|
+
for (const t of aliases) {
|
|
249
|
+
const last = t[t.length - 1];
|
|
250
|
+
if (t.length >= 2 && last.length >= 2) for (const v of surnameVariants(last)) surnames.add(v);
|
|
251
|
+
}
|
|
252
|
+
const givenSet = /* @__PURE__ */ new Set();
|
|
253
|
+
for (const tok of primary) if (!surnames.has(tok)) givenSet.add(tok);
|
|
254
|
+
for (const t of aliases) for (const tok of t) if (tok.length >= 2 && !surnames.has(tok)) givenSet.add(tok);
|
|
255
|
+
const given = [...givenSet];
|
|
256
|
+
const fullGiven = given.filter((g) => g.length >= 2);
|
|
134
257
|
const stored = tokenize(storedName);
|
|
135
|
-
if (stored.length
|
|
258
|
+
if (stored.length < 2) return false;
|
|
136
259
|
const storedSurname = stored[stored.length - 1];
|
|
137
260
|
const storedGiven = stored.slice(0, -1);
|
|
138
261
|
if (!surnameVariants(storedSurname).some((v) => surnames.has(v))) return false;
|
|
139
262
|
const covered = (tok) => given.includes(tok) || tok.length === 1 && given.some((g) => g[0] === tok) || given.some((g) => g.length === 1 && g === tok[0]);
|
|
140
|
-
|
|
263
|
+
if (!storedGiven.every(covered)) return false;
|
|
264
|
+
return storedGiven.some(
|
|
265
|
+
(tok) => fullGiven.includes(tok) || tok.length === 1 && fullGiven.some((g) => g[0] === tok)
|
|
266
|
+
);
|
|
141
267
|
}
|
|
142
268
|
function findMatchingStoredName(providedNames, storedCandidates) {
|
|
143
269
|
return storedCandidates.find((candidate) => namePoolMatches(providedNames, candidate));
|
|
@@ -582,14 +708,21 @@ async function checkRegistryHead(opts) {
|
|
|
582
708
|
|
|
583
709
|
// src/index.ts
|
|
584
710
|
var IDEMPOTENCY_DIALECTS = ["postgres", "sqlite", "mysql", "mssql"];
|
|
711
|
+
var DEFAULT_IDEMPOTENCY_LEASE_SECS = 120;
|
|
585
712
|
function createSqlIdempotencyStore(opts) {
|
|
586
713
|
const table = opts.table ?? "oneaddress_dispatches";
|
|
587
714
|
const dialect = opts.dialect ?? "postgres";
|
|
715
|
+
const leaseSeconds = opts.leaseSeconds ?? DEFAULT_IDEMPOTENCY_LEASE_SECS;
|
|
588
716
|
if (!IDEMPOTENCY_DIALECTS.includes(dialect)) {
|
|
589
717
|
throw new Error(
|
|
590
718
|
`[OneAddress SDK] createSqlIdempotencyStore: unknown dialect "${dialect}". Supported: ${IDEMPOTENCY_DIALECTS.join(", ")}.`
|
|
591
719
|
);
|
|
592
720
|
}
|
|
721
|
+
if (typeof leaseSeconds !== "number" || !Number.isSafeInteger(leaseSeconds) || leaseSeconds < 0 || leaseSeconds > 86400) {
|
|
722
|
+
throw new Error(
|
|
723
|
+
`[OneAddress SDK] createSqlIdempotencyStore: leaseSeconds must be a whole number from 0 to 86400, got ${String(leaseSeconds)}`
|
|
724
|
+
);
|
|
725
|
+
}
|
|
593
726
|
const defaultPh = dialect === "postgres" ? (n) => `$${n}` : dialect === "mssql" ? (n) => `@p${n}` : () => "?";
|
|
594
727
|
const ph = opts.placeholder ?? defaultPh;
|
|
595
728
|
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
|
|
@@ -608,7 +741,26 @@ function createSqlIdempotencyStore(opts) {
|
|
|
608
741
|
[dispatchId]
|
|
609
742
|
);
|
|
610
743
|
if (tokenOf(rows[0]) === token) return "fresh";
|
|
611
|
-
|
|
744
|
+
if (completedOf(rows[0])) return "duplicate";
|
|
745
|
+
const takeover = crypto.randomBytes(16).toString("hex");
|
|
746
|
+
await opts.query(
|
|
747
|
+
`UPDATE ${table} SET received_at = CURRENT_TIMESTAMP, claim_token = ${ph(1)} WHERE dispatch_id = ${ph(2)} AND completed_at IS NULL AND ${staleClaim(3)}`,
|
|
748
|
+
leaseParams([takeover, dispatchId])
|
|
749
|
+
);
|
|
750
|
+
const after = await opts.query(
|
|
751
|
+
`SELECT claim_token, completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
|
|
752
|
+
[dispatchId]
|
|
753
|
+
);
|
|
754
|
+
if (tokenOf(after[0]) === takeover) return "retry-after-incomplete";
|
|
755
|
+
return completedOf(after[0]) ? "duplicate" : "in-progress";
|
|
756
|
+
}
|
|
757
|
+
function staleClaim(n) {
|
|
758
|
+
if (leaseSeconds === 0) return "1 = 1";
|
|
759
|
+
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)`;
|
|
760
|
+
return `(received_at IS NULL OR ${cutoff})`;
|
|
761
|
+
}
|
|
762
|
+
function leaseParams(params) {
|
|
763
|
+
return leaseSeconds === 0 ? params : [...params, leaseSeconds];
|
|
612
764
|
}
|
|
613
765
|
async function setByUpsert(dispatchId) {
|
|
614
766
|
if (dialect === "mysql") {
|
|
@@ -642,11 +794,22 @@ function createSqlIdempotencyStore(opts) {
|
|
|
642
794
|
[dispatchId]
|
|
643
795
|
);
|
|
644
796
|
if (inserted.length > 0) return "fresh";
|
|
797
|
+
const took = await opts.query(
|
|
798
|
+
`UPDATE ${table} SET received_at = CURRENT_TIMESTAMP WHERE dispatch_id = ${ph(1)} AND completed_at IS NULL AND ${staleClaim(2)} RETURNING dispatch_id`,
|
|
799
|
+
leaseParams([dispatchId])
|
|
800
|
+
);
|
|
801
|
+
if (took.length > 0) return "retry-after-incomplete";
|
|
645
802
|
const rows = await opts.query(
|
|
646
803
|
`SELECT completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
|
|
647
804
|
[dispatchId]
|
|
648
805
|
);
|
|
649
|
-
return completedOf(rows[0]) ? "duplicate" : "
|
|
806
|
+
return completedOf(rows[0]) ? "duplicate" : "in-progress";
|
|
807
|
+
},
|
|
808
|
+
async release(dispatchId) {
|
|
809
|
+
await opts.query(
|
|
810
|
+
`DELETE FROM ${table} WHERE dispatch_id = ${ph(1)} AND completed_at IS NULL`,
|
|
811
|
+
[dispatchId]
|
|
812
|
+
);
|
|
650
813
|
},
|
|
651
814
|
async complete(dispatchId) {
|
|
652
815
|
await opts.query(
|
|
@@ -670,6 +833,7 @@ function createSqlIdempotencyStore(opts) {
|
|
|
670
833
|
}
|
|
671
834
|
function verifySignature(rawBody, signature, timestamp, secret) {
|
|
672
835
|
if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
|
|
836
|
+
if (!secret) return false;
|
|
673
837
|
const sigPayload = `${timestamp}.${rawBody}`;
|
|
674
838
|
const expected = crypto.createHmac("sha256", secret).update(sigPayload).digest("hex");
|
|
675
839
|
const sigBuffer = Buffer.from(signature, "hex");
|
|
@@ -677,6 +841,17 @@ function verifySignature(rawBody, signature, timestamp, secret) {
|
|
|
677
841
|
if (sigBuffer.length !== expBuffer.length) return false;
|
|
678
842
|
return crypto.timingSafeEqual(sigBuffer, expBuffer);
|
|
679
843
|
}
|
|
844
|
+
function signPullRequest(opts) {
|
|
845
|
+
if (!opts.secret) throw new Error("signPullRequest: secret is required");
|
|
846
|
+
const u = new URL(opts.url);
|
|
847
|
+
const ts = String(opts.timestamp ?? Math.floor(Date.now() / 1e3));
|
|
848
|
+
const signature = crypto.createHmac("sha256", opts.secret).update(pullSigningStringV2(ts, opts.method ?? "GET", `${u.pathname}${u.search}`, opts.body ?? "")).digest("hex");
|
|
849
|
+
return {
|
|
850
|
+
"X-OneAddress-Timestamp": ts,
|
|
851
|
+
"X-OneAddress-Signature": signature,
|
|
852
|
+
[PULL_SIGNATURE_VERSION_HEADER]: "2"
|
|
853
|
+
};
|
|
854
|
+
}
|
|
680
855
|
function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousSecret, graceUntil) {
|
|
681
856
|
if (verifySignature(rawBody, signature, timestamp, currentSecret)) return true;
|
|
682
857
|
if (previousSecret && previousSecret !== currentSecret && graceUntil) {
|
|
@@ -752,7 +927,7 @@ async function decryptAddress(payload, privateKeyPem, partnerId) {
|
|
|
752
927
|
return JSON.parse(new TextDecoder().decode(plaintext));
|
|
753
928
|
}
|
|
754
929
|
async function decryptSession(share, envelopeB64, privateKeyPem, partnerId, expectedAlg) {
|
|
755
|
-
const { decryptSession: decryptSessionCrypto } = await import("./src-
|
|
930
|
+
const { decryptSession: decryptSessionCrypto } = await import("./src-P3LR7F4A.mjs");
|
|
756
931
|
return decryptSessionCrypto(
|
|
757
932
|
share,
|
|
758
933
|
envelopeB64,
|
|
@@ -820,6 +995,7 @@ async function transformSession(share, envelopeB64, privateKeyPem, partnerId, re
|
|
|
820
995
|
);
|
|
821
996
|
}
|
|
822
997
|
var OA_APP_BASE_URL2 = "https://oneaddress.io";
|
|
998
|
+
var CONFIRM_PATH = "/api/confirm";
|
|
823
999
|
async function confirmUpdate(opts) {
|
|
824
1000
|
const {
|
|
825
1001
|
partnerId,
|
|
@@ -851,18 +1027,22 @@ async function confirmUpdate(opts) {
|
|
|
851
1027
|
...memberName !== void 0 ? { member_name: memberName } : {}
|
|
852
1028
|
});
|
|
853
1029
|
const timestamp = String(Math.floor(Date.now() / 1e3));
|
|
854
|
-
const signature = crypto.createHmac("sha256", secret).update(
|
|
855
|
-
let
|
|
856
|
-
|
|
1030
|
+
const signature = crypto.createHmac("sha256", secret).update(pullSigningStringV2(timestamp, "POST", CONFIRM_PATH, body)).digest("hex");
|
|
1031
|
+
let origin;
|
|
1032
|
+
try {
|
|
1033
|
+
origin = resolveAppOrigin(appBaseUrl, "confirmUpdate", opts.allowedHosts);
|
|
1034
|
+
} catch (err) {
|
|
1035
|
+
return { ok: false, status: 0, error: err instanceof Error ? err.message : String(err) };
|
|
1036
|
+
}
|
|
857
1037
|
let res;
|
|
858
1038
|
try {
|
|
859
|
-
res = await fetchImpl(`${
|
|
1039
|
+
res = await fetchImpl(`${origin}${CONFIRM_PATH}`, {
|
|
860
1040
|
method: "POST",
|
|
861
1041
|
headers: {
|
|
862
1042
|
"Content-Type": "application/json",
|
|
863
|
-
"Authorization": `Bearer ${secret}`,
|
|
864
1043
|
"X-OneAddress-Timestamp": timestamp,
|
|
865
|
-
"X-OneAddress-Signature": signature
|
|
1044
|
+
"X-OneAddress-Signature": signature,
|
|
1045
|
+
[PULL_SIGNATURE_VERSION_HEADER]: "2"
|
|
866
1046
|
},
|
|
867
1047
|
// The SAME string that was signed. Not an object, and not re-stringified.
|
|
868
1048
|
body
|
|
@@ -888,6 +1068,48 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL2) {
|
|
|
888
1068
|
}
|
|
889
1069
|
return res.text();
|
|
890
1070
|
}
|
|
1071
|
+
var LOA_PUBLIC_KEY_CACHE_MS = 24 * 60 * 60 * 1e3;
|
|
1072
|
+
var loaKeyCache = /* @__PURE__ */ new Map();
|
|
1073
|
+
var loaKeyInFlight = /* @__PURE__ */ new Map();
|
|
1074
|
+
var LoaPublicKeyUnavailableError = class extends Error {
|
|
1075
|
+
constructor(from, cause) {
|
|
1076
|
+
super(
|
|
1077
|
+
`[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.`
|
|
1078
|
+
);
|
|
1079
|
+
this.from = from;
|
|
1080
|
+
this.name = "LoaPublicKeyUnavailableError";
|
|
1081
|
+
}
|
|
1082
|
+
};
|
|
1083
|
+
async function cachedLoaPublicKey(appBaseUrl = OA_APP_BASE_URL2, now = Date.now()) {
|
|
1084
|
+
const origin = resolveAppOrigin(appBaseUrl, "cachedLoaPublicKey");
|
|
1085
|
+
const held = loaKeyCache.get(origin);
|
|
1086
|
+
if (held && now - held.at < LOA_PUBLIC_KEY_CACHE_MS) return held.pem;
|
|
1087
|
+
let pending = loaKeyInFlight.get(origin);
|
|
1088
|
+
if (!pending) {
|
|
1089
|
+
pending = (async () => {
|
|
1090
|
+
const pem = (await fetchLoaPublicKey(origin)).trim();
|
|
1091
|
+
if (!pem.includes("-----BEGIN PUBLIC KEY-----")) {
|
|
1092
|
+
throw new Error("the response is not a PEM public key");
|
|
1093
|
+
}
|
|
1094
|
+
loaKeyCache.set(origin, { pem, at: Date.now() });
|
|
1095
|
+
return pem;
|
|
1096
|
+
})().finally(() => loaKeyInFlight.delete(origin));
|
|
1097
|
+
loaKeyInFlight.set(origin, pending);
|
|
1098
|
+
}
|
|
1099
|
+
try {
|
|
1100
|
+
return await pending;
|
|
1101
|
+
} catch (err) {
|
|
1102
|
+
if (held) return held.pem;
|
|
1103
|
+
throw new LoaPublicKeyUnavailableError(
|
|
1104
|
+
`${origin}/.well-known/oneaddress-loa-key.pem`,
|
|
1105
|
+
err instanceof Error ? err.message : String(err)
|
|
1106
|
+
);
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
function _resetLoaKeyCacheForTests() {
|
|
1110
|
+
loaKeyCache.clear();
|
|
1111
|
+
loaKeyInFlight.clear();
|
|
1112
|
+
}
|
|
891
1113
|
async function verifyLOA(loa, publicKeyPem) {
|
|
892
1114
|
if (loa.algorithm !== "ECDSA-P256") {
|
|
893
1115
|
console.warn(
|
|
@@ -967,6 +1189,91 @@ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId, expec
|
|
|
967
1189
|
);
|
|
968
1190
|
return data;
|
|
969
1191
|
}
|
|
1192
|
+
function hasLoaV2(loa) {
|
|
1193
|
+
return typeof loa.oneaddress_signature_v2 === "string";
|
|
1194
|
+
}
|
|
1195
|
+
function canonicalD5LoaFormV2(loa) {
|
|
1196
|
+
return canonicalLoaV2({
|
|
1197
|
+
consumer_name: loa.consumer_name,
|
|
1198
|
+
authorisation_date: loa.authorisation_date,
|
|
1199
|
+
scope: loa.scope,
|
|
1200
|
+
update_uid: loa.update_uid,
|
|
1201
|
+
partner_id: loa.partner_id,
|
|
1202
|
+
envelope_sha256: loa.envelope_sha256,
|
|
1203
|
+
consumer_typed_aliases: loa.consumer_typed_aliases
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
1206
|
+
function loaEnvelopeSha256(envelope) {
|
|
1207
|
+
return crypto.createHash("sha256").update(loaV2EnvelopeDigestInput(envelope), "utf8").digest("hex");
|
|
1208
|
+
}
|
|
1209
|
+
async function verifyD5LOAv2(loa, publicKeyPem) {
|
|
1210
|
+
if (loa.signature_algorithm !== "ECDSA-P256" || !hasLoaV2(loa)) return false;
|
|
1211
|
+
let text;
|
|
1212
|
+
try {
|
|
1213
|
+
text = canonicalD5LoaFormV2(loa);
|
|
1214
|
+
} catch {
|
|
1215
|
+
return false;
|
|
1216
|
+
}
|
|
1217
|
+
try {
|
|
1218
|
+
const key = await crypto.subtle.importKey(
|
|
1219
|
+
"spki",
|
|
1220
|
+
pemToBuffer(publicKeyPem),
|
|
1221
|
+
{ name: "ECDSA", namedCurve: "P-256" },
|
|
1222
|
+
false,
|
|
1223
|
+
["verify"]
|
|
1224
|
+
);
|
|
1225
|
+
return await crypto.subtle.verify(
|
|
1226
|
+
{ name: "ECDSA", hash: "SHA-256" },
|
|
1227
|
+
key,
|
|
1228
|
+
Buffer.from(loa.oneaddress_signature_v2, "hex"),
|
|
1229
|
+
new TextEncoder().encode(text)
|
|
1230
|
+
);
|
|
1231
|
+
} catch {
|
|
1232
|
+
return false;
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
function typedAliasesOf(loa) {
|
|
1236
|
+
if (!hasLoaV2(loa)) return [];
|
|
1237
|
+
return acceptTypedAliases(loa.consumer_name, loa.consumer_typed_aliases);
|
|
1238
|
+
}
|
|
1239
|
+
function bodyUpdateIdString(v) {
|
|
1240
|
+
if (typeof v === "string") return v;
|
|
1241
|
+
if (typeof v === "number" && Number.isSafeInteger(v)) return String(v);
|
|
1242
|
+
return null;
|
|
1243
|
+
}
|
|
1244
|
+
async function checkLoaV2(loa, ctx) {
|
|
1245
|
+
if (!hasLoaV2(loa) || typeof loa.partner_id !== "string" || typeof loa.envelope_sha256 !== "string") {
|
|
1246
|
+
return "loa_v2_malformed";
|
|
1247
|
+
}
|
|
1248
|
+
try {
|
|
1249
|
+
canonicalD5LoaFormV2(loa);
|
|
1250
|
+
} catch {
|
|
1251
|
+
return "loa_v2_malformed";
|
|
1252
|
+
}
|
|
1253
|
+
if (ctx.publicKeyPem !== void 0 && !await verifyD5LOAv2(loa, ctx.publicKeyPem)) {
|
|
1254
|
+
return "loa_v2_signature_invalid";
|
|
1255
|
+
}
|
|
1256
|
+
if (loa.partner_id !== ctx.partnerId) return "loa_v2_partner_mismatch";
|
|
1257
|
+
if (bodyUpdateIdString(ctx.updateId) !== loa.update_uid) return "loa_v2_update_mismatch";
|
|
1258
|
+
let digest;
|
|
1259
|
+
try {
|
|
1260
|
+
digest = loaEnvelopeSha256(ctx.envelope);
|
|
1261
|
+
} catch {
|
|
1262
|
+
return "loa_v2_envelope_mismatch";
|
|
1263
|
+
}
|
|
1264
|
+
if (digest !== loa.envelope_sha256) return "loa_v2_envelope_mismatch";
|
|
1265
|
+
if (typeof ctx.envelopeVerifiedName !== "string" || !loaNamesMatch(ctx.envelopeVerifiedName, loa.consumer_name)) {
|
|
1266
|
+
return "loa_v2_name_mismatch";
|
|
1267
|
+
}
|
|
1268
|
+
return null;
|
|
1269
|
+
}
|
|
1270
|
+
var LoaV2RefusedError = class extends Error {
|
|
1271
|
+
constructor(code) {
|
|
1272
|
+
super(`[OneAddress SDK] D5 LOA v2 refused (${code}); refusing rather than applying an update the consent record does not cover`);
|
|
1273
|
+
this.code = code;
|
|
1274
|
+
this.name = "LoaV2RefusedError";
|
|
1275
|
+
}
|
|
1276
|
+
};
|
|
970
1277
|
var ADDRESS_REQUIRED_FIELDS = [
|
|
971
1278
|
"street",
|
|
972
1279
|
"suburb",
|
|
@@ -974,19 +1281,60 @@ var ADDRESS_REQUIRED_FIELDS = [
|
|
|
974
1281
|
"postcode",
|
|
975
1282
|
"country"
|
|
976
1283
|
];
|
|
1284
|
+
var MAX_ADDRESS_FIELD_CHARS = 512;
|
|
977
1285
|
function validateAddress(raw) {
|
|
978
|
-
if (typeof raw !== "object" || raw === null) {
|
|
1286
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
979
1287
|
throw new Error("[OneAddress SDK] Decrypted address payload is not an object");
|
|
980
1288
|
}
|
|
981
1289
|
const obj = raw;
|
|
982
1290
|
for (const field of ADDRESS_REQUIRED_FIELDS) {
|
|
983
|
-
|
|
1291
|
+
const value = obj[field];
|
|
1292
|
+
if (typeof value !== "string" || value === "") {
|
|
984
1293
|
throw new Error(
|
|
985
|
-
`[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change
|
|
1294
|
+
`[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change - update @oneaddress/partner-sdk.`
|
|
1295
|
+
);
|
|
1296
|
+
}
|
|
1297
|
+
if (value.length > MAX_ADDRESS_FIELD_CHARS) {
|
|
1298
|
+
throw new Error(
|
|
1299
|
+
`[OneAddress SDK] Decrypted address field "${field}" is ${value.length} characters, over the ${MAX_ADDRESS_FIELD_CHARS} this SDK accepts; refusing rather than truncating`
|
|
986
1300
|
);
|
|
987
1301
|
}
|
|
988
1302
|
}
|
|
989
|
-
|
|
1303
|
+
const rawUpdatedAt = obj.updated_at;
|
|
1304
|
+
let updatedAt;
|
|
1305
|
+
if (rawUpdatedAt === void 0 || rawUpdatedAt === null) updatedAt = "";
|
|
1306
|
+
else if (typeof rawUpdatedAt === "number" && Number.isFinite(rawUpdatedAt)) updatedAt = String(rawUpdatedAt);
|
|
1307
|
+
else if (typeof rawUpdatedAt === "string") updatedAt = rawUpdatedAt;
|
|
1308
|
+
else throw new Error('[OneAddress SDK] Decrypted address field "updated_at" is not a string');
|
|
1309
|
+
if (updatedAt.length > MAX_ADDRESS_FIELD_CHARS) {
|
|
1310
|
+
throw new Error(
|
|
1311
|
+
`[OneAddress SDK] Decrypted address field "updated_at" is over the ${MAX_ADDRESS_FIELD_CHARS} characters this SDK accepts`
|
|
1312
|
+
);
|
|
1313
|
+
}
|
|
1314
|
+
return {
|
|
1315
|
+
street: obj.street,
|
|
1316
|
+
suburb: obj.suburb,
|
|
1317
|
+
state: obj.state,
|
|
1318
|
+
postcode: obj.postcode,
|
|
1319
|
+
country: obj.country,
|
|
1320
|
+
updated_at: updatedAt
|
|
1321
|
+
};
|
|
1322
|
+
}
|
|
1323
|
+
function legacyAddressOf(blob, body) {
|
|
1324
|
+
return validateAddress({
|
|
1325
|
+
street: blob.street,
|
|
1326
|
+
suburb: blob.suburb,
|
|
1327
|
+
state: blob.state,
|
|
1328
|
+
postcode: blob.postcode,
|
|
1329
|
+
country: blob.country,
|
|
1330
|
+
updated_at: typeof blob.updated_at === "string" ? blob.updated_at : body.timestamp ?? ""
|
|
1331
|
+
});
|
|
1332
|
+
}
|
|
1333
|
+
function stringOr(value, fallback) {
|
|
1334
|
+
return typeof value === "string" ? value : fallback;
|
|
1335
|
+
}
|
|
1336
|
+
function stringsOf(value) {
|
|
1337
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
990
1338
|
}
|
|
991
1339
|
var ADDRESS_ALIASES = {
|
|
992
1340
|
line1: ["line1", "address_line1", "street", "streetAddress"],
|
|
@@ -1170,6 +1518,41 @@ function _resetOnceWarningsForTests() {
|
|
|
1170
1518
|
warnedNoIdempotencyStore = false;
|
|
1171
1519
|
}
|
|
1172
1520
|
var MAX_TIMESTAMP_TOLERANCE_SECS = 86400;
|
|
1521
|
+
var DEFAULT_MAX_BODY_BYTES = 1048576;
|
|
1522
|
+
var IN_PROGRESS_RETRY_AFTER_SECS = 30;
|
|
1523
|
+
async function readBodyCapped(req, max) {
|
|
1524
|
+
const declaredLength = req.headers.get("content-length");
|
|
1525
|
+
if (declaredLength !== null && /^\s*\d+\s*$/.test(declaredLength) && Number(declaredLength) > max) {
|
|
1526
|
+
return null;
|
|
1527
|
+
}
|
|
1528
|
+
const stream = req.body;
|
|
1529
|
+
if (stream && typeof stream.getReader === "function") {
|
|
1530
|
+
const reader = stream.getReader();
|
|
1531
|
+
const chunks = [];
|
|
1532
|
+
let total = 0;
|
|
1533
|
+
for (; ; ) {
|
|
1534
|
+
const { done, value } = await reader.read();
|
|
1535
|
+
if (done) break;
|
|
1536
|
+
if (!value) continue;
|
|
1537
|
+
total += value.byteLength;
|
|
1538
|
+
if (total > max) {
|
|
1539
|
+
await reader.cancel().catch(() => void 0);
|
|
1540
|
+
return null;
|
|
1541
|
+
}
|
|
1542
|
+
chunks.push(value);
|
|
1543
|
+
}
|
|
1544
|
+
const joined = new Uint8Array(total);
|
|
1545
|
+
let offset = 0;
|
|
1546
|
+
for (const c of chunks) {
|
|
1547
|
+
joined.set(c, offset);
|
|
1548
|
+
offset += c.byteLength;
|
|
1549
|
+
}
|
|
1550
|
+
return new TextDecoder("utf-8").decode(joined);
|
|
1551
|
+
}
|
|
1552
|
+
const text = await req.text();
|
|
1553
|
+
if (text.length > max || new TextEncoder().encode(text).byteLength > max) return null;
|
|
1554
|
+
return text;
|
|
1555
|
+
}
|
|
1173
1556
|
var XWING_SEED_BYTES = 32;
|
|
1174
1557
|
function assertUsablePrivateKey(privateKeyPem) {
|
|
1175
1558
|
if (typeof privateKeyPem !== "string") {
|
|
@@ -1216,13 +1599,16 @@ function createOneAddressHandler(options) {
|
|
|
1216
1599
|
expectedAlg,
|
|
1217
1600
|
keyId,
|
|
1218
1601
|
loaPublicKeyPem,
|
|
1219
|
-
requireLoa =
|
|
1602
|
+
requireLoa = true,
|
|
1603
|
+
loaPublicKeyBaseUrl,
|
|
1220
1604
|
confirm,
|
|
1605
|
+
partnerId: configuredPartnerId,
|
|
1221
1606
|
onUpdate,
|
|
1222
1607
|
onVerify,
|
|
1223
1608
|
onAccountVerify,
|
|
1224
1609
|
onTest,
|
|
1225
1610
|
timestampToleranceSecs = 300,
|
|
1611
|
+
maxBodyBytes = DEFAULT_MAX_BODY_BYTES,
|
|
1226
1612
|
idempotencyStore,
|
|
1227
1613
|
acceptedUpdateTypes: acceptedUpdateTypesRaw,
|
|
1228
1614
|
allowedCallbackHosts
|
|
@@ -1236,6 +1622,9 @@ function createOneAddressHandler(options) {
|
|
|
1236
1622
|
`[OneAddress SDK] timestampToleranceSecs must be a positive number of seconds up to ${MAX_TIMESTAMP_TOLERANCE_SECS}, got ${String(timestampToleranceSecs)}`
|
|
1237
1623
|
);
|
|
1238
1624
|
}
|
|
1625
|
+
if (typeof maxBodyBytes !== "number" || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes <= 0) {
|
|
1626
|
+
throw new Error(`[OneAddress SDK] maxBodyBytes must be a positive whole number of bytes, got ${String(maxBodyBytes)}`);
|
|
1627
|
+
}
|
|
1239
1628
|
if (webhookSecretGraceUntil !== void 0) {
|
|
1240
1629
|
const until = typeof webhookSecretGraceUntil === "number" ? webhookSecretGraceUntil : Date.parse(webhookSecretGraceUntil);
|
|
1241
1630
|
if (Number.isNaN(until)) {
|
|
@@ -1245,6 +1634,15 @@ function createOneAddressHandler(options) {
|
|
|
1245
1634
|
if (confirm && (!confirm.partnerId || !confirm.confirmSecret)) {
|
|
1246
1635
|
throw new Error("[OneAddress SDK] confirm needs both partnerId and confirmSecret");
|
|
1247
1636
|
}
|
|
1637
|
+
if (typeof requireLoa !== "boolean") {
|
|
1638
|
+
throw new Error(`[OneAddress SDK] requireLoa must be true or false, got ${String(requireLoa)}`);
|
|
1639
|
+
}
|
|
1640
|
+
if (loaPublicKeyBaseUrl !== void 0) resolveAppOrigin(loaPublicKeyBaseUrl, "loaPublicKeyBaseUrl");
|
|
1641
|
+
async function loaVerificationKey() {
|
|
1642
|
+
if (loaPublicKeyPem) return loaPublicKeyPem;
|
|
1643
|
+
if (!requireLoa) return void 0;
|
|
1644
|
+
return cachedLoaPublicKey(loaPublicKeyBaseUrl ?? OA_APP_BASE_URL2);
|
|
1645
|
+
}
|
|
1248
1646
|
function enforceLoaPresence(body) {
|
|
1249
1647
|
const present = !!body.loa_encrypted && typeof body.loa_encrypted === "object";
|
|
1250
1648
|
if (present) return;
|
|
@@ -1257,7 +1655,7 @@ function createOneAddressHandler(options) {
|
|
|
1257
1655
|
warnedConsentUnverified = true;
|
|
1258
1656
|
console.warn(
|
|
1259
1657
|
// NOSONAR - intentional SDK diagnostic, not user-controlled data
|
|
1260
|
-
"[OneAddress SDK] a dispatch arrived with no loa_encrypted and requireLoa is off, so consent for this update is UNVERIFIED.
|
|
1658
|
+
"[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."
|
|
1261
1659
|
);
|
|
1262
1660
|
}
|
|
1263
1661
|
}
|
|
@@ -1292,9 +1690,9 @@ function createOneAddressHandler(options) {
|
|
|
1292
1690
|
const newEmail = updateTypes.includes("email") ? requireContactValue("email", data.new_email) : void 0;
|
|
1293
1691
|
const customer = {
|
|
1294
1692
|
email: "",
|
|
1295
|
-
name: data.verified_name
|
|
1296
|
-
account_number: data.account_number
|
|
1297
|
-
known_names:
|
|
1693
|
+
name: stringOr(data.verified_name, ""),
|
|
1694
|
+
account_number: stringOr(data.account_number, null),
|
|
1695
|
+
known_names: stringsOf(data.known_names)
|
|
1298
1696
|
};
|
|
1299
1697
|
let loa;
|
|
1300
1698
|
let loa_ref;
|
|
@@ -1306,11 +1704,23 @@ function createOneAddressHandler(options) {
|
|
|
1306
1704
|
expectedAlg
|
|
1307
1705
|
);
|
|
1308
1706
|
loa_ref = d5LoaRef(loa);
|
|
1309
|
-
|
|
1310
|
-
|
|
1707
|
+
const loaKey = await loaVerificationKey();
|
|
1708
|
+
if (loaKey) {
|
|
1709
|
+
const valid = await verifyD5LOA(loa, loaKey);
|
|
1311
1710
|
if (!valid) throw new Error("D5 LOA signature verification failed");
|
|
1312
1711
|
}
|
|
1313
1712
|
assertLoaBoundToEnvelope(loa, data.update_uid);
|
|
1713
|
+
if (hasLoaV2(loa)) {
|
|
1714
|
+
const refusal = await checkLoaV2(loa, {
|
|
1715
|
+
partnerId: configuredPartnerId ?? confirm?.partnerId ?? partnerId,
|
|
1716
|
+
updateId: body.update_id,
|
|
1717
|
+
envelope: body.session_envelope,
|
|
1718
|
+
envelopeVerifiedName: data.verified_name,
|
|
1719
|
+
...loaKey ? { publicKeyPem: loaKey } : {}
|
|
1720
|
+
});
|
|
1721
|
+
if (refusal) throw new LoaV2RefusedError(refusal);
|
|
1722
|
+
customer.known_names = typedAliasesOf(loa);
|
|
1723
|
+
}
|
|
1314
1724
|
}
|
|
1315
1725
|
return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
|
|
1316
1726
|
}
|
|
@@ -1326,7 +1736,13 @@ function createOneAddressHandler(options) {
|
|
|
1326
1736
|
return Array.isArray(siblings) && siblings.includes(keyId);
|
|
1327
1737
|
}
|
|
1328
1738
|
return async function handler(req) {
|
|
1329
|
-
const rawBody = await req
|
|
1739
|
+
const rawBody = await readBodyCapped(req, maxBodyBytes);
|
|
1740
|
+
if (rawBody === null) {
|
|
1741
|
+
return new Response(JSON.stringify({ error: "Payload too large" }), {
|
|
1742
|
+
status: 413,
|
|
1743
|
+
headers: { "Content-Type": "application/json" }
|
|
1744
|
+
});
|
|
1745
|
+
}
|
|
1330
1746
|
const sig = req.headers.get("x-oneaddress-signature") ?? "";
|
|
1331
1747
|
const tsHeader = req.headers.get("x-oneaddress-timestamp") ?? "";
|
|
1332
1748
|
if (!isFreshTimestamp(tsHeader, timestampToleranceSecs)) {
|
|
@@ -1363,14 +1779,24 @@ function createOneAddressHandler(options) {
|
|
|
1363
1779
|
}
|
|
1364
1780
|
const partnerId = body.partner_id ?? "";
|
|
1365
1781
|
const tsNum = Number(tsHeader);
|
|
1366
|
-
const
|
|
1782
|
+
const headerDispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
|
|
1783
|
+
const bodyDispatchId = typeof body.dispatch_id === "string" ? body.dispatch_id : "";
|
|
1784
|
+
if (bodyDispatchId && headerDispatchId && bodyDispatchId !== headerDispatchId) {
|
|
1785
|
+
return new Response(JSON.stringify({ error: "dispatch_id_mismatch" }), {
|
|
1786
|
+
status: 400,
|
|
1787
|
+
headers: { "Content-Type": "application/json" }
|
|
1788
|
+
});
|
|
1789
|
+
}
|
|
1790
|
+
const dispatchId = bodyDispatchId || headerDispatchId;
|
|
1367
1791
|
if (isCrossoverSiblingToSkip(body)) {
|
|
1368
1792
|
return declared(200, { ok: true, skipped: true, crossover: true });
|
|
1369
1793
|
}
|
|
1794
|
+
let claimed = false;
|
|
1795
|
+
let completed = false;
|
|
1370
1796
|
if (dispatchId) {
|
|
1371
1797
|
if (!idempotencyStore) {
|
|
1372
1798
|
const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
|
|
1373
|
-
if (nodeEnv === "test") {
|
|
1799
|
+
if (nodeEnv === "test" && headerDispatchId) {
|
|
1374
1800
|
throw new Error(
|
|
1375
1801
|
"[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
|
|
1376
1802
|
);
|
|
@@ -1387,6 +1813,17 @@ function createOneAddressHandler(options) {
|
|
|
1387
1813
|
if (claim === "duplicate") {
|
|
1388
1814
|
return declared(200, { ok: true, duplicate: true });
|
|
1389
1815
|
}
|
|
1816
|
+
if (claim === "in-progress") {
|
|
1817
|
+
return new Response(JSON.stringify({
|
|
1818
|
+
error: "dispatch_in_progress",
|
|
1819
|
+
detail: "Another delivery of this dispatch is being processed. Retry later.",
|
|
1820
|
+
accepted_update_types: acceptedUpdateTypes
|
|
1821
|
+
}), {
|
|
1822
|
+
status: 503,
|
|
1823
|
+
headers: { "Content-Type": "application/json", "Retry-After": String(IN_PROGRESS_RETRY_AFTER_SECS) }
|
|
1824
|
+
});
|
|
1825
|
+
}
|
|
1826
|
+
claimed = true;
|
|
1390
1827
|
} else {
|
|
1391
1828
|
const alreadySeen = await idempotencyStore.has(dispatchId);
|
|
1392
1829
|
if (alreadySeen) {
|
|
@@ -1482,16 +1919,27 @@ function createOneAddressHandler(options) {
|
|
|
1482
1919
|
expectedAlg
|
|
1483
1920
|
);
|
|
1484
1921
|
loa_ref = d5LoaRef(loa);
|
|
1485
|
-
|
|
1922
|
+
const loaKey = await loaVerificationKey();
|
|
1923
|
+
if (loaKey && !await verifyD5LOA(loa, loaKey)) {
|
|
1486
1924
|
throw new Error("D5 LOA signature verification failed");
|
|
1487
1925
|
}
|
|
1488
1926
|
assertLoaBoundToEnvelope(loa, rawAddress.update_uid);
|
|
1927
|
+
if (hasLoaV2(loa)) {
|
|
1928
|
+
const refusal = await checkLoaV2(loa, {
|
|
1929
|
+
partnerId: configuredPartnerId ?? confirm?.partnerId ?? partnerId,
|
|
1930
|
+
updateId: body.update_id,
|
|
1931
|
+
envelope: encrypted,
|
|
1932
|
+
envelopeVerifiedName: rawAddress.fullName,
|
|
1933
|
+
...loaKey ? { publicKeyPem: loaKey } : {}
|
|
1934
|
+
});
|
|
1935
|
+
if (refusal) throw new LoaV2RefusedError(refusal);
|
|
1936
|
+
}
|
|
1489
1937
|
}
|
|
1490
1938
|
const customer = {
|
|
1491
1939
|
email: "",
|
|
1492
|
-
name: rawAddress.fullName
|
|
1493
|
-
account_number: rawAddress.accountReference
|
|
1494
|
-
known_names:
|
|
1940
|
+
name: stringOr(rawAddress.fullName, ""),
|
|
1941
|
+
account_number: stringOr(rawAddress.accountReference, null),
|
|
1942
|
+
known_names: loa && hasLoaV2(loa) ? typedAliasesOf(loa) : stringsOf(rawAddress.knownNames)
|
|
1495
1943
|
};
|
|
1496
1944
|
event = {
|
|
1497
1945
|
event: "address.updated",
|
|
@@ -1503,7 +1951,8 @@ function createOneAddressHandler(options) {
|
|
|
1503
1951
|
customer,
|
|
1504
1952
|
// The legacy blob predates kinds and always carries an address.
|
|
1505
1953
|
update_types: ["address"],
|
|
1506
|
-
|
|
1954
|
+
// Six named fields, never the blob: see validateAddress.
|
|
1955
|
+
address: legacyAddressOf(rawAddress, body),
|
|
1507
1956
|
loa,
|
|
1508
1957
|
loa_ref,
|
|
1509
1958
|
id_verification: body.id_verification,
|
|
@@ -1511,6 +1960,7 @@ function createOneAddressHandler(options) {
|
|
|
1511
1960
|
};
|
|
1512
1961
|
}
|
|
1513
1962
|
const result = await onUpdate(event);
|
|
1963
|
+
completed = true;
|
|
1514
1964
|
if (dispatchId && idempotencyStore) {
|
|
1515
1965
|
const record = idempotencyStore.complete ? idempotencyStore.complete(dispatchId) : idempotencyStore.set(dispatchId);
|
|
1516
1966
|
await record.catch(
|
|
@@ -1527,6 +1977,7 @@ function createOneAddressHandler(options) {
|
|
|
1527
1977
|
status,
|
|
1528
1978
|
loaRef: event.loa_ref,
|
|
1529
1979
|
...confirm.oneAddressApi ? { appBaseUrl: confirm.oneAddressApi } : {},
|
|
1980
|
+
...confirm.allowedHosts ? { allowedHosts: confirm.allowedHosts } : {},
|
|
1530
1981
|
...confirm.fetchImpl ? { fetchImpl: confirm.fetchImpl } : {}
|
|
1531
1982
|
}).then(
|
|
1532
1983
|
(r) => {
|
|
@@ -1563,7 +2014,7 @@ function createOneAddressHandler(options) {
|
|
|
1563
2014
|
user_id: body.user_id ?? "",
|
|
1564
2015
|
customer: body.customer,
|
|
1565
2016
|
customer_match: body.customer_match,
|
|
1566
|
-
address:
|
|
2017
|
+
address: legacyAddressOf(rawAddress, body),
|
|
1567
2018
|
loa: body.loa,
|
|
1568
2019
|
id_verification: body.id_verification,
|
|
1569
2020
|
raw: rawAddress
|
|
@@ -1602,10 +2053,10 @@ function createOneAddressHandler(options) {
|
|
|
1602
2053
|
partnerId
|
|
1603
2054
|
);
|
|
1604
2055
|
customer = {
|
|
1605
|
-
email: raw.email
|
|
1606
|
-
name: raw.name
|
|
1607
|
-
account_number: raw.account_number
|
|
1608
|
-
known_names:
|
|
2056
|
+
email: stringOr(raw.email, ""),
|
|
2057
|
+
name: stringOr(raw.name, ""),
|
|
2058
|
+
account_number: stringOr(raw.account_number, null),
|
|
2059
|
+
known_names: stringsOf(raw.known_names)
|
|
1609
2060
|
};
|
|
1610
2061
|
} else {
|
|
1611
2062
|
customer = body.customer ?? {};
|
|
@@ -1692,6 +2143,13 @@ function createOneAddressHandler(options) {
|
|
|
1692
2143
|
status: 500,
|
|
1693
2144
|
headers: { "Content-Type": "application/json" }
|
|
1694
2145
|
});
|
|
2146
|
+
} finally {
|
|
2147
|
+
if (claimed && !completed && idempotencyStore?.release) {
|
|
2148
|
+
await idempotencyStore.release(dispatchId).catch(
|
|
2149
|
+
(err) => console.error("[OneAddress SDK] idempotency release failed:", err)
|
|
2150
|
+
// NOSONAR
|
|
2151
|
+
);
|
|
2152
|
+
}
|
|
1695
2153
|
}
|
|
1696
2154
|
};
|
|
1697
2155
|
}
|
|
@@ -1765,6 +2223,10 @@ async function buildSignedTestWebhook(opts) {
|
|
|
1765
2223
|
oneaddress_acn: "696 078 869",
|
|
1766
2224
|
oneaddress_signature: "00".repeat(64),
|
|
1767
2225
|
signature_algorithm: "ECDSA-P256",
|
|
2226
|
+
partner_id: opts.partnerId,
|
|
2227
|
+
envelope_sha256: loaEnvelopeSha256(envelope.session_envelope),
|
|
2228
|
+
consumer_typed_aliases: acceptTypedAliases(sessionData.verified_name, sessionData.known_names ?? []),
|
|
2229
|
+
oneaddress_signature_v2: "00".repeat(64),
|
|
1768
2230
|
...opts.loa ?? {}
|
|
1769
2231
|
};
|
|
1770
2232
|
if (opts.loaSigningKeyPem) {
|
|
@@ -1775,12 +2237,19 @@ async function buildSignedTestWebhook(opts) {
|
|
|
1775
2237
|
false,
|
|
1776
2238
|
["sign"]
|
|
1777
2239
|
);
|
|
1778
|
-
const
|
|
2240
|
+
const signHex = async (text) => Buffer.from(await crypto.subtle.sign(
|
|
1779
2241
|
{ name: "ECDSA", hash: "SHA-256" },
|
|
1780
2242
|
key,
|
|
1781
|
-
new TextEncoder().encode(
|
|
1782
|
-
);
|
|
1783
|
-
loa.oneaddress_signature =
|
|
2243
|
+
new TextEncoder().encode(text)
|
|
2244
|
+
)).toString("hex");
|
|
2245
|
+
loa.oneaddress_signature = await signHex(canonicalD5LoaForm(loa));
|
|
2246
|
+
let v2Text;
|
|
2247
|
+
try {
|
|
2248
|
+
v2Text = canonicalD5LoaFormV2(loa);
|
|
2249
|
+
} catch {
|
|
2250
|
+
v2Text = null;
|
|
2251
|
+
}
|
|
2252
|
+
if (hasLoaV2(loa) && v2Text !== null) loa.oneaddress_signature_v2 = await signHex(v2Text);
|
|
1784
2253
|
}
|
|
1785
2254
|
const sealed = await encryptEnvelopeForPartner(loa, partnerKey);
|
|
1786
2255
|
loa_encrypted = { session_envelope: sealed.session_envelope, session_key_share: sealed.session_key_share };
|
|
@@ -1804,7 +2273,6 @@ async function buildSignedTestWebhook(opts) {
|
|
|
1804
2273
|
...loa_encrypted ? { loa_encrypted } : {},
|
|
1805
2274
|
// On the wire with a `null` value when no PaymentIntent backed the update,
|
|
1806
2275
|
// so the KEY is present either way.
|
|
1807
|
-
stripe_session_id: opts.stripeSessionId ?? null,
|
|
1808
2276
|
// `id` and `crossover_key_ids` are crossover-only and therefore NOT emitted
|
|
1809
2277
|
// by default. A test that needs them passes them through `extraBody`, which
|
|
1810
2278
|
// is exactly the circumstance the relay emits them in.
|
|
@@ -1839,6 +2307,15 @@ async function buildSignedTestWebhook(opts) {
|
|
|
1839
2307
|
export {
|
|
1840
2308
|
CURRENT_VERSION,
|
|
1841
2309
|
SUPPORTED_VERSIONS,
|
|
2310
|
+
LOA_MAX_TYPED_ALIASES,
|
|
2311
|
+
normaliseLoaName,
|
|
2312
|
+
loaSurname,
|
|
2313
|
+
loaFirstName,
|
|
2314
|
+
loaNamesMatch,
|
|
2315
|
+
LOA_MIN_SHORT_FORM_LETTERS,
|
|
2316
|
+
isAcceptableAlias,
|
|
2317
|
+
acceptTypedAliases,
|
|
2318
|
+
LOA_V2_REFUSALS,
|
|
1842
2319
|
isEmailLike,
|
|
1843
2320
|
namePoolMatches,
|
|
1844
2321
|
findMatchingStoredName,
|
|
@@ -1848,8 +2325,10 @@ export {
|
|
|
1848
2325
|
createOutboxConsumer,
|
|
1849
2326
|
parsePinnedRegistryRoots,
|
|
1850
2327
|
checkRegistryHead,
|
|
2328
|
+
DEFAULT_IDEMPOTENCY_LEASE_SECS,
|
|
1851
2329
|
createSqlIdempotencyStore,
|
|
1852
2330
|
verifySignature,
|
|
2331
|
+
signPullRequest,
|
|
1853
2332
|
verifyWithGrace,
|
|
1854
2333
|
decryptAddress,
|
|
1855
2334
|
decryptSession,
|
|
@@ -1857,17 +2336,30 @@ export {
|
|
|
1857
2336
|
transformSession,
|
|
1858
2337
|
confirmUpdate,
|
|
1859
2338
|
fetchLoaPublicKey,
|
|
2339
|
+
LOA_PUBLIC_KEY_CACHE_MS,
|
|
2340
|
+
LoaPublicKeyUnavailableError,
|
|
2341
|
+
cachedLoaPublicKey,
|
|
2342
|
+
_resetLoaKeyCacheForTests,
|
|
1860
2343
|
verifyLOA,
|
|
1861
2344
|
canonicalD5LoaForm,
|
|
1862
2345
|
d5LoaRef,
|
|
1863
2346
|
verifyD5LOA,
|
|
1864
2347
|
decryptLoaEncrypted,
|
|
2348
|
+
hasLoaV2,
|
|
2349
|
+
canonicalD5LoaFormV2,
|
|
2350
|
+
loaEnvelopeSha256,
|
|
2351
|
+
verifyD5LOAv2,
|
|
2352
|
+
typedAliasesOf,
|
|
2353
|
+
checkLoaV2,
|
|
2354
|
+
LoaV2RefusedError,
|
|
2355
|
+
MAX_ADDRESS_FIELD_CHARS,
|
|
1865
2356
|
validateAddress,
|
|
1866
2357
|
readAddressParts,
|
|
1867
2358
|
formatAddressParts,
|
|
1868
2359
|
compareAddresses,
|
|
1869
2360
|
sendVerifyResult,
|
|
1870
2361
|
_resetOnceWarningsForTests,
|
|
2362
|
+
DEFAULT_MAX_BODY_BYTES,
|
|
1871
2363
|
createOneAddressHandler,
|
|
1872
2364
|
toExpressHandler,
|
|
1873
2365
|
buildSignedTestWebhook
|