@oneaddress/partner-sdk 1.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.
package/dist/edge.js ADDED
@@ -0,0 +1,350 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/edge.ts
31
+ var edge_exports = {};
32
+ __export(edge_exports, {
33
+ CURRENT_VERSION: () => CURRENT_VERSION,
34
+ DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
35
+ SUPPORTED_VERSIONS: () => SUPPORTED_VERSIONS,
36
+ createOneAddressHandler: () => createOneAddressHandler,
37
+ decryptAddress: () => decryptAddress,
38
+ fetchLoaPublicKey: () => fetchLoaPublicKey,
39
+ isFreshTimestamp: () => isFreshTimestamp,
40
+ validateAddress: () => validateAddress,
41
+ verifyLOA: () => verifyLOA,
42
+ verifySignature: () => verifySignature,
43
+ verifyWithGrace: () => verifyWithGrace
44
+ });
45
+ module.exports = __toCommonJS(edge_exports);
46
+
47
+ // src/index.ts
48
+ var import_crypto = __toESM(require("crypto"));
49
+
50
+ // ../crypto/src/replay-window.ts
51
+ var DEFAULT_REPLAY_WINDOW_SECS = 300;
52
+ function isFreshTimestamp(timestampHeader, toleranceSecs = DEFAULT_REPLAY_WINDOW_SECS, nowSecs) {
53
+ if (typeof timestampHeader !== "string" || timestampHeader.length === 0) return false;
54
+ if (!/^\d+$/.test(timestampHeader)) return false;
55
+ const ts = Number(timestampHeader);
56
+ if (!Number.isFinite(ts) || ts < 0) return false;
57
+ const now = typeof nowSecs === "number" ? nowSecs : Math.floor(Date.now() / 1e3);
58
+ return Math.abs(now - ts) <= toleranceSecs;
59
+ }
60
+
61
+ // ../protocol/src/types.ts
62
+ var CURRENT_VERSION = "2026.1";
63
+ var SUPPORTED_VERSIONS = ["2026.1"];
64
+
65
+ // src/index.ts
66
+ function verifySignature(rawBody, signature, timestamp, secret) {
67
+ const sigPayload = `${timestamp}.${rawBody}`;
68
+ const expected = import_crypto.default.createHmac("sha256", secret).update(sigPayload).digest("hex");
69
+ const sigBuffer = Buffer.from(signature, "hex");
70
+ const expBuffer = Buffer.from(expected, "hex");
71
+ if (sigBuffer.length !== expBuffer.length) return false;
72
+ return import_crypto.default.timingSafeEqual(sigBuffer, expBuffer);
73
+ }
74
+ function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousSecret, graceUntil) {
75
+ if (verifySignature(rawBody, signature, timestamp, currentSecret)) return true;
76
+ if (previousSecret && graceUntil) {
77
+ const until = typeof graceUntil === "number" ? graceUntil : Date.parse(graceUntil);
78
+ if (!Number.isNaN(until) && Date.now() < until) {
79
+ return verifySignature(rawBody, signature, timestamp, previousSecret);
80
+ }
81
+ }
82
+ return false;
83
+ }
84
+ function base64urlToBuffer(b64) {
85
+ return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
86
+ }
87
+ function pemToBuffer(pem) {
88
+ return Buffer.from(pem.replace(/-----[^-]+-----/g, "").replace(/\s/g, ""), "base64");
89
+ }
90
+ async function decryptAddress(payload, privateKeyPem, partnerId) {
91
+ const { ephemeralPublicKey, iv, ciphertext, hkdfSalt } = payload;
92
+ const privateKey = await import_crypto.default.subtle.importKey(
93
+ "pkcs8",
94
+ pemToBuffer(privateKeyPem),
95
+ { name: "ECDH", namedCurve: "P-256" },
96
+ false,
97
+ ["deriveBits"]
98
+ );
99
+ const ephemeralKey = await import_crypto.default.subtle.importKey(
100
+ "raw",
101
+ base64urlToBuffer(ephemeralPublicKey),
102
+ { name: "ECDH", namedCurve: "P-256" },
103
+ false,
104
+ []
105
+ );
106
+ const sharedBits = await import_crypto.default.subtle.deriveBits(
107
+ { name: "ECDH", public: ephemeralKey },
108
+ privateKey,
109
+ 256
110
+ );
111
+ const hkdfKey = await import_crypto.default.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
112
+ const salt = hkdfSalt ? base64urlToBuffer(hkdfSalt) : new Uint8Array(0);
113
+ const info = new TextEncoder().encode(`oneaddress:${partnerId}`);
114
+ const aesKeyBits = await import_crypto.default.subtle.deriveBits(
115
+ { name: "HKDF", hash: "SHA-256", salt, info },
116
+ hkdfKey,
117
+ 256
118
+ );
119
+ const aesKey = await import_crypto.default.subtle.importKey("raw", aesKeyBits, "AES-GCM", false, ["decrypt"]);
120
+ const plaintext = await import_crypto.default.subtle.decrypt(
121
+ { name: "AES-GCM", iv: base64urlToBuffer(iv), tagLength: 128 },
122
+ aesKey,
123
+ base64urlToBuffer(ciphertext)
124
+ );
125
+ return JSON.parse(new TextDecoder().decode(plaintext));
126
+ }
127
+ var OA_APP_BASE_URL = "https://app.oneaddress.io";
128
+ var ALLOWED_LOA_HOSTS = /* @__PURE__ */ new Set(["app.oneaddress.io", "localhost", "127.0.0.1"]);
129
+ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
130
+ let parsedBase;
131
+ try {
132
+ parsedBase = new URL(appBaseUrl);
133
+ } catch {
134
+ throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl is not a valid URL");
135
+ }
136
+ if (!ALLOWED_LOA_HOSTS.has(parsedBase.hostname)) {
137
+ throw new Error(
138
+ `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...ALLOWED_LOA_HOSTS].join(", ")}`
139
+ );
140
+ }
141
+ const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
142
+ const res = await fetch(url);
143
+ if (!res.ok) {
144
+ throw new Error(`[OneAddress SDK] Failed to fetch LOA public key: HTTP ${res.status}`);
145
+ }
146
+ return res.text();
147
+ }
148
+ async function verifyLOA(loa, publicKeyPem) {
149
+ if (loa.algorithm !== "ECDSA-P256") {
150
+ console.warn(
151
+ // NOSONAR — intentional SDK diagnostic, not user-controlled data
152
+ "[OneAddress SDK] LOA algorithm is HMAC-SHA256 (deprecated). Verification is not possible without the OneAddress HMAC key. Contact support@oneaddress.io if you are seeing this on recent webhooks."
153
+ );
154
+ return false;
155
+ }
156
+ try {
157
+ const key = await import_crypto.default.subtle.importKey(
158
+ "spki",
159
+ pemToBuffer(publicKeyPem),
160
+ { name: "ECDSA", namedCurve: "P-256" },
161
+ false,
162
+ ["verify"]
163
+ );
164
+ const sigBytes = Buffer.from(loa.signature, "hex");
165
+ const textBytes = new TextEncoder().encode(loa.text);
166
+ return await import_crypto.default.subtle.verify(
167
+ { name: "ECDSA", hash: "SHA-256" },
168
+ key,
169
+ sigBytes,
170
+ textBytes
171
+ );
172
+ } catch {
173
+ return false;
174
+ }
175
+ }
176
+ var ADDRESS_REQUIRED_FIELDS = [
177
+ "street",
178
+ "suburb",
179
+ "state",
180
+ "postcode",
181
+ "country"
182
+ ];
183
+ function validateAddress(raw) {
184
+ if (typeof raw !== "object" || raw === null) {
185
+ throw new Error("[OneAddress SDK] Decrypted address payload is not an object");
186
+ }
187
+ const obj = raw;
188
+ for (const field of ADDRESS_REQUIRED_FIELDS) {
189
+ if (typeof obj[field] !== "string" || obj[field] === "") {
190
+ throw new Error(
191
+ `[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change \u2014 update @oneaddress/partner-sdk.`
192
+ );
193
+ }
194
+ }
195
+ return obj;
196
+ }
197
+ function createOneAddressHandler(options) {
198
+ const {
199
+ webhookSecret,
200
+ previousWebhookSecret,
201
+ webhookSecretGraceUntil,
202
+ privateKeyPem,
203
+ onUpdate,
204
+ onVerify,
205
+ timestampToleranceSecs = 300,
206
+ idempotencyStore
207
+ } = options;
208
+ return async function handler(req) {
209
+ const rawBody = await req.text();
210
+ const sig = req.headers.get("x-oneaddress-signature") ?? "";
211
+ const tsHeader = req.headers.get("x-oneaddress-timestamp") ?? "";
212
+ if (!isFreshTimestamp(tsHeader, timestampToleranceSecs)) {
213
+ return new Response(JSON.stringify({ error: "Request timestamp out of tolerance" }), {
214
+ status: 400,
215
+ headers: { "Content-Type": "application/json" }
216
+ });
217
+ }
218
+ if (!verifyWithGrace(rawBody, tsHeader, sig, webhookSecret, previousWebhookSecret, webhookSecretGraceUntil)) {
219
+ return new Response(JSON.stringify({ error: "Invalid signature" }), {
220
+ status: 401,
221
+ headers: { "Content-Type": "application/json" }
222
+ });
223
+ }
224
+ let body;
225
+ try {
226
+ body = JSON.parse(rawBody);
227
+ } catch {
228
+ return new Response(JSON.stringify({ error: "Invalid JSON" }), {
229
+ status: 400,
230
+ headers: { "Content-Type": "application/json" }
231
+ });
232
+ }
233
+ const payloadVersion = body.oneaddress_version ?? body.version ?? "";
234
+ if (payloadVersion && !SUPPORTED_VERSIONS.includes(payloadVersion)) {
235
+ console.warn(
236
+ // NOSONAR — intentional SDK diagnostic, not user-controlled data
237
+ `[OneAddress SDK] Unrecognised protocol version "${payloadVersion}". Supported: ${SUPPORTED_VERSIONS.join(", ")}. Update @oneaddress/partner-sdk to the latest version.`
238
+ );
239
+ }
240
+ const partnerId = body.partner_id ?? "";
241
+ const tsNum = Number(tsHeader);
242
+ const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
243
+ if (dispatchId) {
244
+ if (!idempotencyStore) {
245
+ if (process.env.NODE_ENV === "test") {
246
+ throw new Error(
247
+ "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
248
+ );
249
+ }
250
+ } else {
251
+ const alreadySeen = await idempotencyStore.has(dispatchId);
252
+ if (alreadySeen) {
253
+ return new Response(JSON.stringify({ ok: true, duplicate: true }), {
254
+ status: 200,
255
+ headers: { "Content-Type": "application/json" }
256
+ });
257
+ }
258
+ }
259
+ }
260
+ try {
261
+ if (body.event === "address.updated") {
262
+ if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
263
+ return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
264
+ status: 400,
265
+ headers: { "Content-Type": "application/json" }
266
+ });
267
+ }
268
+ const encrypted = body.address_encrypted;
269
+ const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
270
+ const event = {
271
+ event: "address.updated",
272
+ version: body.oneaddress_version ?? body.version ?? "1",
273
+ id: body.id ?? "",
274
+ timestamp: tsNum,
275
+ partner_id: partnerId,
276
+ dispatchId,
277
+ customer: body.customer,
278
+ address: validateAddress(rawAddress),
279
+ loa: body.loa,
280
+ raw: rawAddress
281
+ };
282
+ const result = await onUpdate(event);
283
+ if (dispatchId && idempotencyStore) {
284
+ await idempotencyStore.set(dispatchId).catch(
285
+ (err) => console.error("[OneAddress SDK] idempotencyStore.set failed:", err)
286
+ // NOSONAR
287
+ );
288
+ }
289
+ return new Response(JSON.stringify({ ok: true, ...result }), {
290
+ status: 200,
291
+ headers: { "Content-Type": "application/json" }
292
+ });
293
+ }
294
+ if (body.event === "address.verify" && onVerify) {
295
+ if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
296
+ return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
297
+ status: 400,
298
+ headers: { "Content-Type": "application/json" }
299
+ });
300
+ }
301
+ const encrypted = body.address_encrypted;
302
+ const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
303
+ const event = {
304
+ event: "address.verify",
305
+ version: body.oneaddress_version ?? body.version ?? "1",
306
+ id: body.id ?? "",
307
+ timestamp: tsNum,
308
+ partner_id: partnerId,
309
+ dispatchId,
310
+ batch_id: body.batch_id ?? 0,
311
+ user_id: body.user_id ?? "",
312
+ customer: body.customer ?? {},
313
+ address: validateAddress(rawAddress),
314
+ loa: body.loa,
315
+ raw: rawAddress
316
+ };
317
+ const result = await onVerify(event);
318
+ return new Response(JSON.stringify({ ok: true, ...result }), {
319
+ status: 200,
320
+ headers: { "Content-Type": "application/json" }
321
+ });
322
+ }
323
+ return new Response(JSON.stringify({ ok: true, skipped: true }), {
324
+ status: 200,
325
+ headers: { "Content-Type": "application/json" }
326
+ });
327
+ } catch (err) {
328
+ const msg = err instanceof Error ? err.message : String(err);
329
+ console.error("[OneAddress SDK] Handler error:", msg);
330
+ return new Response(JSON.stringify({ error: "Internal handler error" }), {
331
+ status: 500,
332
+ headers: { "Content-Type": "application/json" }
333
+ });
334
+ }
335
+ };
336
+ }
337
+ // Annotate the CommonJS export names for ESM import in node:
338
+ 0 && (module.exports = {
339
+ CURRENT_VERSION,
340
+ DEFAULT_REPLAY_WINDOW_SECS,
341
+ SUPPORTED_VERSIONS,
342
+ createOneAddressHandler,
343
+ decryptAddress,
344
+ fetchLoaPublicKey,
345
+ isFreshTimestamp,
346
+ validateAddress,
347
+ verifyLOA,
348
+ verifySignature,
349
+ verifyWithGrace
350
+ });
package/dist/edge.mjs ADDED
@@ -0,0 +1,26 @@
1
+ import {
2
+ CURRENT_VERSION,
3
+ DEFAULT_REPLAY_WINDOW_SECS,
4
+ SUPPORTED_VERSIONS,
5
+ createOneAddressHandler,
6
+ decryptAddress,
7
+ fetchLoaPublicKey,
8
+ isFreshTimestamp,
9
+ validateAddress,
10
+ verifyLOA,
11
+ verifySignature,
12
+ verifyWithGrace
13
+ } from "./chunk-NBUGPU44.mjs";
14
+ export {
15
+ CURRENT_VERSION,
16
+ DEFAULT_REPLAY_WINDOW_SECS,
17
+ SUPPORTED_VERSIONS,
18
+ createOneAddressHandler,
19
+ decryptAddress,
20
+ fetchLoaPublicKey,
21
+ isFreshTimestamp,
22
+ validateAddress,
23
+ verifyLOA,
24
+ verifySignature,
25
+ verifyWithGrace
26
+ };
@@ -0,0 +1,298 @@
1
+ export { DEFAULT_REPLAY_WINDOW_SECS, isFreshTimestamp } from '@oneaddress/crypto';
2
+ export { CURRENT_VERSION, SUPPORTED_VERSIONS } from '@oneaddress/protocol';
3
+
4
+ /**
5
+ * @oneaddress/partner-sdk
6
+ *
7
+ * Official Node.js SDK for OneAddress partner integrations.
8
+ *
9
+ * Usage:
10
+ * import { createOneAddressHandler } from '@oneaddress/partner-sdk';
11
+ *
12
+ * export const handler = createOneAddressHandler({
13
+ * webhookSecret: process.env.OA_WEBHOOK_SECRET!,
14
+ * privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
15
+ * async onUpdate(event) {
16
+ * await db.updateAddress({ email: event.customer.email, ...event.address });
17
+ * },
18
+ * });
19
+ *
20
+ * // Express: app.post('/webhook/oneaddress', express.raw({ type: 'application/json' }), handler);
21
+ * // Next.js: export { handler as POST };
22
+ */
23
+
24
+ interface OneAddressAddress {
25
+ street: string;
26
+ suburb: string;
27
+ state: string;
28
+ postcode: string;
29
+ country: string;
30
+ updated_at: string;
31
+ }
32
+ interface OneAddressCustomer {
33
+ email: string;
34
+ name: string;
35
+ }
36
+ interface OneAddressLOA {
37
+ reference: string;
38
+ type: string;
39
+ generatedAt: string;
40
+ text: string;
41
+ signature: string;
42
+ algorithm: string;
43
+ }
44
+ interface OneAddressUpdateEvent {
45
+ event: 'address.updated';
46
+ version: string;
47
+ id: string;
48
+ timestamp: number;
49
+ partner_id: string;
50
+ /**
51
+ * Unique identifier for this specific dispatch attempt, taken from the
52
+ * `X-OneAddress-Dispatch` request header.
53
+ *
54
+ * **Important:** falls back to `''` (empty string) if the header is absent —
55
+ * guard against this when using it as an idempotency key:
56
+ * ```ts
57
+ * if (event.dispatchId) {
58
+ * const seen = await db.dispatches.exists({ dispatchId: event.dispatchId });
59
+ * if (seen) return; // idempotent no-op
60
+ * }
61
+ * ```
62
+ *
63
+ * Use this to implement idempotency: if your handler takes longer than
64
+ * ~10 seconds OneAddress will time out and retry the webhook, which means
65
+ * your `onUpdate` may be called more than once for the same address update.
66
+ * Deduplicating on `(partner_id, dispatchId)` prevents double-processing.
67
+ */
68
+ dispatchId: string;
69
+ customer: OneAddressCustomer;
70
+ address: OneAddressAddress;
71
+ loa?: OneAddressLOA;
72
+ /** Raw decrypted + parsed payload (in case fields are extended) */
73
+ raw: Record<string, unknown>;
74
+ }
75
+ interface OneAddressVerifyEvent {
76
+ event: 'address.verify';
77
+ version: string;
78
+ id: string;
79
+ timestamp: number;
80
+ partner_id: string;
81
+ /** Unique dispatch ID from `X-OneAddress-Dispatch`. Falls back to `''` if header is absent — guard before using as idempotency key. */
82
+ dispatchId: string;
83
+ batch_id: number;
84
+ user_id: string;
85
+ customer: OneAddressCustomer;
86
+ address: OneAddressAddress;
87
+ loa?: OneAddressLOA;
88
+ raw: Record<string, unknown>;
89
+ }
90
+ interface EncryptedPayload {
91
+ /** Base64-encoded ECDH P-256 ephemeral public key (uncompressed, 65 bytes) */
92
+ ephemeralPublicKey: string;
93
+ /** Base64-encoded 12-byte AES-GCM IV */
94
+ iv: string;
95
+ /** Base64-encoded AES-256-GCM ciphertext with auth tag appended */
96
+ ciphertext: string;
97
+ /**
98
+ * Base64-encoded 32-byte random HKDF salt (added v2).
99
+ * Absent on legacy blobs — decryptAddress falls back to all-zeros salt
100
+ * for backward compatibility with pre-v2 payloads.
101
+ */
102
+ hkdfSalt?: string;
103
+ }
104
+ interface OneAddressHandlerOptions {
105
+ /** HMAC-SHA256 webhook secret — shown in the OneAddress Partner Portal */
106
+ webhookSecret: string;
107
+ /**
108
+ * Previous webhook secret, valid during the 24-hour grace window after a
109
+ * secret rotation. Set this alongside `webhookSecretGraceUntil` so the
110
+ * handler accepts webhooks signed with either the old or new secret during
111
+ * the transition. Once `webhookSecretGraceUntil` passes, this is ignored.
112
+ */
113
+ previousWebhookSecret?: string;
114
+ /**
115
+ * ISO-8601 date string or ms-epoch timestamp until which `previousWebhookSecret`
116
+ * is accepted. Obtain this value from the Partner Portal after rotating your
117
+ * webhook secret — it will be exactly 24 hours after the rotation time.
118
+ */
119
+ webhookSecretGraceUntil?: string | number;
120
+ /** PKCS#8 PEM-encoded ECDH P-256 private key for address decryption */
121
+ privateKeyPem: string;
122
+ /**
123
+ * Called when a consumer dispatches an address update to you.
124
+ * Return an object with optional `status` and `reference` for the confirmation callback.
125
+ */
126
+ onUpdate: (event: OneAddressUpdateEvent) => Promise<{
127
+ status?: string;
128
+ reference?: string;
129
+ } | void>;
130
+ /**
131
+ * Called when a consumer runs an address verification check.
132
+ * Return `{ match: true }` if the address matches your records, `{ match: false }` otherwise.
133
+ */
134
+ onVerify?: (event: OneAddressVerifyEvent) => Promise<{
135
+ match: boolean;
136
+ note?: string;
137
+ } | void>;
138
+ /**
139
+ * Timestamp tolerance in seconds (default: 300 = 5 minutes).
140
+ * Requests with timestamps outside this window are rejected as potential replays.
141
+ */
142
+ timestampToleranceSecs?: number;
143
+ /**
144
+ * Idempotency store for deduplicating repeated webhook deliveries.
145
+ *
146
+ * OneAddress retries failed deliveries and may deliver the same `dispatch_id`
147
+ * more than once. Without deduplication your `onUpdate` handler will process
148
+ * the same address update multiple times.
149
+ *
150
+ * Implement two methods:
151
+ * `has(dispatchId)` — return `true` if this dispatch was already processed.
152
+ * `set(dispatchId)` — record that this dispatch has been processed.
153
+ *
154
+ * **Required in test mode** (`NODE_ENV=test`): if a request with a non-empty
155
+ * `X-OneAddress-Dispatch` header arrives and `idempotencyStore` is not wired,
156
+ * the handler throws immediately so the oversight is caught at development time,
157
+ * not in production.
158
+ *
159
+ * @example
160
+ * const seen = new Set<string>();
161
+ * const handler = createOneAddressHandler({
162
+ * webhookSecret: process.env.OA_WEBHOOK_SECRET!,
163
+ * privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
164
+ * idempotencyStore: {
165
+ * has: async (id) => seen.has(id),
166
+ * set: async (id) => { seen.add(id); },
167
+ * },
168
+ * async onUpdate(event) { ... },
169
+ * });
170
+ */
171
+ idempotencyStore?: {
172
+ has(dispatchId: string): Promise<boolean>;
173
+ set(dispatchId: string): Promise<void>;
174
+ };
175
+ }
176
+ /**
177
+ * Verify the HMAC-SHA256 webhook signature.
178
+ * OneAddress signs: `${timestamp}.${rawBody}` with the webhook secret.
179
+ * The signature is sent in X-OneAddress-Signature header.
180
+ */
181
+ declare function verifySignature(rawBody: string, signature: string, timestamp: string, secret: string): boolean;
182
+ /**
183
+ * Verify a webhook signature with grace-window fallback for secret rotations.
184
+ *
185
+ * OneAddress supports a 24-hour grace window after a webhook-secret rotation:
186
+ * webhooks signed with the previous secret are still valid until `graceUntil`.
187
+ * This helper encapsulates the two-step verify so you don't have to call
188
+ * `verifySignature` twice yourself.
189
+ *
190
+ * Algorithm:
191
+ * 1. Try the current secret — if it passes, return true immediately.
192
+ * 2. If `previousSecret` is provided and `graceUntil` is in the future,
193
+ * try the previous secret and return that result.
194
+ * 3. Otherwise return false.
195
+ *
196
+ * @param rawBody - Raw request body string (before JSON.parse)
197
+ * @param timestamp - Value of the X-OneAddress-Timestamp header
198
+ * @param signature - Value of the X-OneAddress-Signature header
199
+ * @param currentSecret - Your current webhook secret from the Partner Portal
200
+ * @param previousSecret - Your previous webhook secret (optional)
201
+ * @param graceUntil - ISO-8601 date string or ms-epoch until which the
202
+ * previous secret is still accepted (optional)
203
+ *
204
+ * @example
205
+ * const ok = verifyWithGrace(
206
+ * rawBody, timestamp, signature,
207
+ * process.env.OA_WEBHOOK_SECRET!,
208
+ * process.env.OA_PREVIOUS_WEBHOOK_SECRET,
209
+ * process.env.OA_WEBHOOK_SECRET_GRACE_UNTIL,
210
+ * );
211
+ * if (!ok) return res.status(401).end();
212
+ */
213
+ declare function verifyWithGrace(rawBody: string, timestamp: string, signature: string, currentSecret: string, previousSecret?: string, graceUntil?: string | number): boolean;
214
+ /**
215
+ * Decrypt an ECDH P-256 + HKDF-SHA256 + AES-256-GCM encrypted address payload.
216
+ *
217
+ * @param payload - The `address_encrypted` object from the webhook body
218
+ * @param privateKeyPem - PKCS#8 PEM private key
219
+ * @param partnerId - Your partner UUID (used as HKDF info string)
220
+ */
221
+ declare function decryptAddress(payload: EncryptedPayload, privateKeyPem: string, partnerId: string): Promise<Record<string, unknown>>;
222
+ /**
223
+ * Fetch OneAddress's ECDSA P-256 LOA signing public key from the well-known endpoint.
224
+ *
225
+ * Cache the result — the key only changes during a planned key rotation, which is
226
+ * announced in advance. Calling this on every request adds unnecessary latency.
227
+ *
228
+ * @param appBaseUrl Override the consumer-app base URL (default: https://app.oneaddress.io)
229
+ *
230
+ * @example
231
+ * const publicKeyPem = await fetchLoaPublicKey();
232
+ * // Cache it: loaPublicKey = publicKeyPem;
233
+ * const ok = await verifyLOA(event.loa, loaPublicKey);
234
+ */
235
+ declare function fetchLoaPublicKey(appBaseUrl?: string): Promise<string>;
236
+ /**
237
+ * Verify the ECDSA P-256 signature on a OneAddress Letter of Authority.
238
+ *
239
+ * OneAddress signs the `loa.text` field with its ECDSA P-256 private key when
240
+ * generating the LOA. Partners can verify this signature to prove the LOA was
241
+ * issued by OneAddress and has not been tampered with — providing cryptographic
242
+ * proof of consumer consent that stands up in an audit.
243
+ *
244
+ * The signing public key is served at:
245
+ * https://app.oneaddress.io/.well-known/oneaddress-loa-key.pem
246
+ *
247
+ * Fetch it once and cache it (it only changes during a planned key rotation):
248
+ * ```ts
249
+ * const loaPublicKey = await fetchLoaPublicKey();
250
+ *
251
+ * handler = createOneAddressHandler({
252
+ * ...
253
+ * async onUpdate(event) {
254
+ * if (event.loa) {
255
+ * const valid = await verifyLOA(event.loa, loaPublicKey);
256
+ * if (!valid) throw new Error('LOA signature invalid — possible tampering');
257
+ * }
258
+ * await db.updateAddress(event.address);
259
+ * },
260
+ * });
261
+ * ```
262
+ *
263
+ * @param loa - The `loa` field from a `OneAddressUpdateEvent` or `OneAddressVerifyEvent`
264
+ * @param publicKeyPem - OneAddress's ECDSA P-256 public key in SPKI PEM format
265
+ * @returns `true` if the signature is valid; `false` if invalid or unrecognised algorithm
266
+ */
267
+ declare function verifyLOA(loa: OneAddressLOA, publicKeyPem: string): Promise<boolean>;
268
+ /**
269
+ * Validate and narrow the decrypted address payload to `OneAddressAddress`.
270
+ *
271
+ * Throws a descriptive `Error` if any required field is absent or not a string.
272
+ * Call this after `decryptAddress()` when you want explicit failure rather than
273
+ * silently receiving `undefined` for a missing field.
274
+ *
275
+ * `createOneAddressHandler` runs this automatically before calling `onUpdate`
276
+ * and `onVerify`, so SDK users get validation for free.
277
+ *
278
+ * @example
279
+ * const raw = await decryptAddress(payload, privateKeyPem, partnerId);
280
+ * const address = validateAddress(raw); // throws if malformed
281
+ * await db.updateAddress(address);
282
+ */
283
+ declare function validateAddress(raw: unknown): OneAddressAddress;
284
+ type HandlerRequest = {
285
+ text(): Promise<string>;
286
+ headers: {
287
+ get(name: string): string | null;
288
+ };
289
+ };
290
+ type HandlerResponse = Response;
291
+ /**
292
+ * Create a framework-agnostic OneAddress webhook handler.
293
+ * Returns a function compatible with Next.js App Router route handlers,
294
+ * Express (with raw body middleware), and Cloudflare Workers.
295
+ */
296
+ declare function createOneAddressHandler(options: OneAddressHandlerOptions): (req: HandlerRequest) => Promise<HandlerResponse>;
297
+
298
+ export { type EncryptedPayload, type OneAddressAddress, type OneAddressCustomer, type OneAddressHandlerOptions, type OneAddressLOA, type OneAddressUpdateEvent, type OneAddressVerifyEvent, createOneAddressHandler, decryptAddress as decrypt, decryptAddress, fetchLoaPublicKey, validateAddress, verifySignature as verify, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };