@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/README.md ADDED
@@ -0,0 +1,192 @@
1
+ # @oneaddress/partner-sdk
2
+
3
+ Official Node.js SDK for OneAddress partner webhook integrations.
4
+
5
+ Handles signature verification, replay-window enforcement, ECDH address decryption, and secret-rotation grace windows in a single call.
6
+
7
+ ---
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @oneaddress/partner-sdk
13
+ ```
14
+
15
+ ---
16
+
17
+ ## Quick start
18
+
19
+ ```typescript
20
+ import { createOneAddressHandler } from '@oneaddress/partner-sdk';
21
+
22
+ export const handler = createOneAddressHandler({
23
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
24
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
25
+
26
+ async onUpdate(event) {
27
+ // event.address is already decrypted
28
+ console.log(`Address updated for ${event.customer.email}:`, event.address);
29
+ await db.updateAddress({ email: event.customer.email, ...event.address });
30
+ },
31
+ });
32
+
33
+ // Next.js App Router
34
+ export { handler as POST };
35
+
36
+ // Express (requires express.raw middleware on this route)
37
+ // app.post('/webhook/oneaddress', express.raw({ type: 'application/json' }), handler);
38
+ ```
39
+
40
+ ---
41
+
42
+ ## Idempotency — handling retries
43
+
44
+ If your handler takes longer than ~10 seconds OneAddress will time out and retry the webhook. Your `onUpdate` can be called more than once for the same address change. Use `event.dispatchId` (from the `X-OneAddress-Dispatch` header) as an idempotency key:
45
+
46
+ ```typescript
47
+ async onUpdate(event) {
48
+ if (event.dispatchId) {
49
+ const seen = await db.dispatches.exists({ dispatchId: event.dispatchId });
50
+ if (seen) return; // idempotent no-op
51
+ }
52
+
53
+ await db.updateAddress({ email: event.customer.email, ...event.address });
54
+
55
+ if (event.dispatchId) {
56
+ await db.dispatches.insert({ dispatchId: event.dispatchId });
57
+ }
58
+ }
59
+ ```
60
+
61
+ `dispatchId` falls back to `''` (empty string) if the header is absent — always guard before using it as a key.
62
+
63
+ ---
64
+
65
+ ## Secret rotation grace window
66
+
67
+ After rotating your webhook secret in the Partner Portal, OneAddress keeps dispatching webhooks signed with the **old** secret for up to 24 hours to cover in-flight requests. Pass both secrets to the handler during the transition:
68
+
69
+ ```typescript
70
+ export const handler = createOneAddressHandler({
71
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
72
+ previousWebhookSecret: process.env.OA_PREVIOUS_WEBHOOK_SECRET,
73
+ webhookSecretGraceUntil: process.env.OA_WEBHOOK_SECRET_GRACE_UNTIL, // ISO-8601
74
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
75
+ async onUpdate(event) { /* ... */ },
76
+ });
77
+ ```
78
+
79
+ Once `webhookSecretGraceUntil` passes, the previous secret is ignored automatically. You can then remove those two env vars.
80
+
81
+ ### Standalone `verifyWithGrace`
82
+
83
+ If you're not using the handler factory, use `verifyWithGrace` directly instead of calling `verifySignature` twice:
84
+
85
+ ```typescript
86
+ import { verifyWithGrace, isFreshTimestamp } from '@oneaddress/partner-sdk';
87
+
88
+ // Replay check first — before signature verify
89
+ if (!isFreshTimestamp(req.headers['x-oneaddress-timestamp'])) {
90
+ return res.status(400).json({ error: 'Stale timestamp' });
91
+ }
92
+
93
+ const ok = verifyWithGrace(
94
+ rawBody,
95
+ req.headers['x-oneaddress-timestamp'],
96
+ req.headers['x-oneaddress-signature'],
97
+ process.env.OA_WEBHOOK_SECRET!,
98
+ process.env.OA_PREVIOUS_WEBHOOK_SECRET,
99
+ process.env.OA_WEBHOOK_SECRET_GRACE_UNTIL,
100
+ );
101
+ if (!ok) return res.status(401).json({ error: 'Invalid signature' });
102
+ ```
103
+
104
+ ---
105
+
106
+ ## Address verification events
107
+
108
+ Implement `onVerify` to respond to consumer address-match checks:
109
+
110
+ ```typescript
111
+ export const handler = createOneAddressHandler({
112
+ webhookSecret: process.env.OA_WEBHOOK_SECRET!,
113
+ privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
114
+
115
+ async onUpdate(event) { /* ... */ },
116
+
117
+ async onVerify(event) {
118
+ const stored = await db.getAddress({ email: event.customer.email });
119
+ const match = stored?.street === event.address.street &&
120
+ stored?.postcode === event.address.postcode;
121
+ return { match, note: match ? undefined : 'Address does not match our records' };
122
+ },
123
+ });
124
+ ```
125
+
126
+ ---
127
+
128
+ ## Edge runtime (Cloudflare Workers, Next.js Edge)
129
+
130
+ ```typescript
131
+ import { createOneAddressHandler } from '@oneaddress/partner-sdk/edge';
132
+ ```
133
+
134
+ All exports are available on the `/edge` path. No Node.js-specific APIs are used.
135
+
136
+ ---
137
+
138
+ ## Standalone utilities
139
+
140
+ ```typescript
141
+ import {
142
+ verifySignature, // single-secret HMAC verify
143
+ verifyWithGrace, // two-secret grace-window verify
144
+ decryptAddress, // ECDH + HKDF + AES-GCM decryption
145
+ isFreshTimestamp, // ±5-minute replay-window check
146
+ CURRENT_VERSION, // '2026.1'
147
+ SUPPORTED_VERSIONS, // ['2026.1']
148
+ } from '@oneaddress/partner-sdk';
149
+ ```
150
+
151
+ ### `verifySignature(rawBody, signature, timestamp, secret)`
152
+
153
+ Returns `true` if the HMAC-SHA256 signature is valid. Signing formula: `HMAC-SHA256("${timestamp}.${rawBody}")`.
154
+
155
+ ### `isFreshTimestamp(timestamp, toleranceSecs?)`
156
+
157
+ Returns `true` if `timestamp` (Unix seconds string) is within `toleranceSecs` of now. Default tolerance: 300 seconds (±5 minutes). **Always check freshness before signature** — a stale-timestamp check is cheap; a signature verify is not.
158
+
159
+ ### `decryptAddress(payload, privateKeyPem, partnerId)`
160
+
161
+ Decrypts the `address_encrypted` blob using your PKCS#8 ECDH P-256 private key.
162
+
163
+ ---
164
+
165
+ ## Protocol versioning
166
+
167
+ The SDK warns (but does not reject) if it receives a protocol version it doesn't recognise:
168
+
169
+ ```
170
+ [OneAddress SDK] Unrecognised protocol version "2027.1".
171
+ Supported: 2026.1. Update @oneaddress/partner-sdk to the latest version.
172
+ ```
173
+
174
+ This ensures you keep receiving events while updating your SDK. See `SUPPORTED_VERSIONS` to check which versions the installed SDK build supports.
175
+
176
+ ---
177
+
178
+ ## Testing your integration
179
+
180
+ **Quick smoke test** — send a single test webhook from the Partner Portal (Profile → Test Webhook).
181
+
182
+ **Full conformance suite** — run 10 checks against your endpoint using real crypto, no mocks:
183
+
184
+ ```bash
185
+ # Against a live endpoint
186
+ npx @oneaddress/conformance test https://your-endpoint.com/webhook --secret whsec_...
187
+
188
+ # Against a local server (run from the machine where the server is running)
189
+ npx @oneaddress/conformance test http://localhost:3001/webhook
190
+ ```
191
+
192
+ Or use the **Integration Conformance** card in the Partner Portal to run the same checks against your configured webhook URL from within the portal.
@@ -0,0 +1,304 @@
1
+ // src/index.ts
2
+ import crypto from "crypto";
3
+
4
+ // ../crypto/src/replay-window.ts
5
+ var DEFAULT_REPLAY_WINDOW_SECS = 300;
6
+ function isFreshTimestamp(timestampHeader, toleranceSecs = DEFAULT_REPLAY_WINDOW_SECS, nowSecs) {
7
+ if (typeof timestampHeader !== "string" || timestampHeader.length === 0) return false;
8
+ if (!/^\d+$/.test(timestampHeader)) return false;
9
+ const ts = Number(timestampHeader);
10
+ if (!Number.isFinite(ts) || ts < 0) return false;
11
+ const now = typeof nowSecs === "number" ? nowSecs : Math.floor(Date.now() / 1e3);
12
+ return Math.abs(now - ts) <= toleranceSecs;
13
+ }
14
+
15
+ // ../protocol/src/types.ts
16
+ var CURRENT_VERSION = "2026.1";
17
+ var SUPPORTED_VERSIONS = ["2026.1"];
18
+
19
+ // src/index.ts
20
+ function verifySignature(rawBody, signature, timestamp, secret) {
21
+ const sigPayload = `${timestamp}.${rawBody}`;
22
+ const expected = crypto.createHmac("sha256", secret).update(sigPayload).digest("hex");
23
+ const sigBuffer = Buffer.from(signature, "hex");
24
+ const expBuffer = Buffer.from(expected, "hex");
25
+ if (sigBuffer.length !== expBuffer.length) return false;
26
+ return crypto.timingSafeEqual(sigBuffer, expBuffer);
27
+ }
28
+ function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousSecret, graceUntil) {
29
+ if (verifySignature(rawBody, signature, timestamp, currentSecret)) return true;
30
+ if (previousSecret && graceUntil) {
31
+ const until = typeof graceUntil === "number" ? graceUntil : Date.parse(graceUntil);
32
+ if (!Number.isNaN(until) && Date.now() < until) {
33
+ return verifySignature(rawBody, signature, timestamp, previousSecret);
34
+ }
35
+ }
36
+ return false;
37
+ }
38
+ function base64urlToBuffer(b64) {
39
+ return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
40
+ }
41
+ function pemToBuffer(pem) {
42
+ return Buffer.from(pem.replace(/-----[^-]+-----/g, "").replace(/\s/g, ""), "base64");
43
+ }
44
+ async function decryptAddress(payload, privateKeyPem, partnerId) {
45
+ const { ephemeralPublicKey, iv, ciphertext, hkdfSalt } = payload;
46
+ const privateKey = await crypto.subtle.importKey(
47
+ "pkcs8",
48
+ pemToBuffer(privateKeyPem),
49
+ { name: "ECDH", namedCurve: "P-256" },
50
+ false,
51
+ ["deriveBits"]
52
+ );
53
+ const ephemeralKey = await crypto.subtle.importKey(
54
+ "raw",
55
+ base64urlToBuffer(ephemeralPublicKey),
56
+ { name: "ECDH", namedCurve: "P-256" },
57
+ false,
58
+ []
59
+ );
60
+ const sharedBits = await crypto.subtle.deriveBits(
61
+ { name: "ECDH", public: ephemeralKey },
62
+ privateKey,
63
+ 256
64
+ );
65
+ const hkdfKey = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
66
+ const salt = hkdfSalt ? base64urlToBuffer(hkdfSalt) : new Uint8Array(0);
67
+ const info = new TextEncoder().encode(`oneaddress:${partnerId}`);
68
+ const aesKeyBits = await crypto.subtle.deriveBits(
69
+ { name: "HKDF", hash: "SHA-256", salt, info },
70
+ hkdfKey,
71
+ 256
72
+ );
73
+ const aesKey = await crypto.subtle.importKey("raw", aesKeyBits, "AES-GCM", false, ["decrypt"]);
74
+ const plaintext = await crypto.subtle.decrypt(
75
+ { name: "AES-GCM", iv: base64urlToBuffer(iv), tagLength: 128 },
76
+ aesKey,
77
+ base64urlToBuffer(ciphertext)
78
+ );
79
+ return JSON.parse(new TextDecoder().decode(plaintext));
80
+ }
81
+ var OA_APP_BASE_URL = "https://app.oneaddress.io";
82
+ var ALLOWED_LOA_HOSTS = /* @__PURE__ */ new Set(["app.oneaddress.io", "localhost", "127.0.0.1"]);
83
+ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
84
+ let parsedBase;
85
+ try {
86
+ parsedBase = new URL(appBaseUrl);
87
+ } catch {
88
+ throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl is not a valid URL");
89
+ }
90
+ if (!ALLOWED_LOA_HOSTS.has(parsedBase.hostname)) {
91
+ throw new Error(
92
+ `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...ALLOWED_LOA_HOSTS].join(", ")}`
93
+ );
94
+ }
95
+ const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
96
+ const res = await fetch(url);
97
+ if (!res.ok) {
98
+ throw new Error(`[OneAddress SDK] Failed to fetch LOA public key: HTTP ${res.status}`);
99
+ }
100
+ return res.text();
101
+ }
102
+ async function verifyLOA(loa, publicKeyPem) {
103
+ if (loa.algorithm !== "ECDSA-P256") {
104
+ console.warn(
105
+ // NOSONAR — intentional SDK diagnostic, not user-controlled data
106
+ "[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."
107
+ );
108
+ return false;
109
+ }
110
+ try {
111
+ const key = await crypto.subtle.importKey(
112
+ "spki",
113
+ pemToBuffer(publicKeyPem),
114
+ { name: "ECDSA", namedCurve: "P-256" },
115
+ false,
116
+ ["verify"]
117
+ );
118
+ const sigBytes = Buffer.from(loa.signature, "hex");
119
+ const textBytes = new TextEncoder().encode(loa.text);
120
+ return await crypto.subtle.verify(
121
+ { name: "ECDSA", hash: "SHA-256" },
122
+ key,
123
+ sigBytes,
124
+ textBytes
125
+ );
126
+ } catch {
127
+ return false;
128
+ }
129
+ }
130
+ var ADDRESS_REQUIRED_FIELDS = [
131
+ "street",
132
+ "suburb",
133
+ "state",
134
+ "postcode",
135
+ "country"
136
+ ];
137
+ function validateAddress(raw) {
138
+ if (typeof raw !== "object" || raw === null) {
139
+ throw new Error("[OneAddress SDK] Decrypted address payload is not an object");
140
+ }
141
+ const obj = raw;
142
+ for (const field of ADDRESS_REQUIRED_FIELDS) {
143
+ if (typeof obj[field] !== "string" || obj[field] === "") {
144
+ throw new Error(
145
+ `[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change \u2014 update @oneaddress/partner-sdk.`
146
+ );
147
+ }
148
+ }
149
+ return obj;
150
+ }
151
+ function createOneAddressHandler(options) {
152
+ const {
153
+ webhookSecret,
154
+ previousWebhookSecret,
155
+ webhookSecretGraceUntil,
156
+ privateKeyPem,
157
+ onUpdate,
158
+ onVerify,
159
+ timestampToleranceSecs = 300,
160
+ idempotencyStore
161
+ } = options;
162
+ return async function handler(req) {
163
+ const rawBody = await req.text();
164
+ const sig = req.headers.get("x-oneaddress-signature") ?? "";
165
+ const tsHeader = req.headers.get("x-oneaddress-timestamp") ?? "";
166
+ if (!isFreshTimestamp(tsHeader, timestampToleranceSecs)) {
167
+ return new Response(JSON.stringify({ error: "Request timestamp out of tolerance" }), {
168
+ status: 400,
169
+ headers: { "Content-Type": "application/json" }
170
+ });
171
+ }
172
+ if (!verifyWithGrace(rawBody, tsHeader, sig, webhookSecret, previousWebhookSecret, webhookSecretGraceUntil)) {
173
+ return new Response(JSON.stringify({ error: "Invalid signature" }), {
174
+ status: 401,
175
+ headers: { "Content-Type": "application/json" }
176
+ });
177
+ }
178
+ let body;
179
+ try {
180
+ body = JSON.parse(rawBody);
181
+ } catch {
182
+ return new Response(JSON.stringify({ error: "Invalid JSON" }), {
183
+ status: 400,
184
+ headers: { "Content-Type": "application/json" }
185
+ });
186
+ }
187
+ const payloadVersion = body.oneaddress_version ?? body.version ?? "";
188
+ if (payloadVersion && !SUPPORTED_VERSIONS.includes(payloadVersion)) {
189
+ console.warn(
190
+ // NOSONAR — intentional SDK diagnostic, not user-controlled data
191
+ `[OneAddress SDK] Unrecognised protocol version "${payloadVersion}". Supported: ${SUPPORTED_VERSIONS.join(", ")}. Update @oneaddress/partner-sdk to the latest version.`
192
+ );
193
+ }
194
+ const partnerId = body.partner_id ?? "";
195
+ const tsNum = Number(tsHeader);
196
+ const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
197
+ if (dispatchId) {
198
+ if (!idempotencyStore) {
199
+ if (process.env.NODE_ENV === "test") {
200
+ throw new Error(
201
+ "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
202
+ );
203
+ }
204
+ } else {
205
+ const alreadySeen = await idempotencyStore.has(dispatchId);
206
+ if (alreadySeen) {
207
+ return new Response(JSON.stringify({ ok: true, duplicate: true }), {
208
+ status: 200,
209
+ headers: { "Content-Type": "application/json" }
210
+ });
211
+ }
212
+ }
213
+ }
214
+ try {
215
+ if (body.event === "address.updated") {
216
+ if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
217
+ return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
218
+ status: 400,
219
+ headers: { "Content-Type": "application/json" }
220
+ });
221
+ }
222
+ const encrypted = body.address_encrypted;
223
+ const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
224
+ const event = {
225
+ event: "address.updated",
226
+ version: body.oneaddress_version ?? body.version ?? "1",
227
+ id: body.id ?? "",
228
+ timestamp: tsNum,
229
+ partner_id: partnerId,
230
+ dispatchId,
231
+ customer: body.customer,
232
+ address: validateAddress(rawAddress),
233
+ loa: body.loa,
234
+ raw: rawAddress
235
+ };
236
+ const result = await onUpdate(event);
237
+ if (dispatchId && idempotencyStore) {
238
+ await idempotencyStore.set(dispatchId).catch(
239
+ (err) => console.error("[OneAddress SDK] idempotencyStore.set failed:", err)
240
+ // NOSONAR
241
+ );
242
+ }
243
+ return new Response(JSON.stringify({ ok: true, ...result }), {
244
+ status: 200,
245
+ headers: { "Content-Type": "application/json" }
246
+ });
247
+ }
248
+ if (body.event === "address.verify" && onVerify) {
249
+ if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
250
+ return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
251
+ status: 400,
252
+ headers: { "Content-Type": "application/json" }
253
+ });
254
+ }
255
+ const encrypted = body.address_encrypted;
256
+ const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
257
+ const event = {
258
+ event: "address.verify",
259
+ version: body.oneaddress_version ?? body.version ?? "1",
260
+ id: body.id ?? "",
261
+ timestamp: tsNum,
262
+ partner_id: partnerId,
263
+ dispatchId,
264
+ batch_id: body.batch_id ?? 0,
265
+ user_id: body.user_id ?? "",
266
+ customer: body.customer ?? {},
267
+ address: validateAddress(rawAddress),
268
+ loa: body.loa,
269
+ raw: rawAddress
270
+ };
271
+ const result = await onVerify(event);
272
+ return new Response(JSON.stringify({ ok: true, ...result }), {
273
+ status: 200,
274
+ headers: { "Content-Type": "application/json" }
275
+ });
276
+ }
277
+ return new Response(JSON.stringify({ ok: true, skipped: true }), {
278
+ status: 200,
279
+ headers: { "Content-Type": "application/json" }
280
+ });
281
+ } catch (err) {
282
+ const msg = err instanceof Error ? err.message : String(err);
283
+ console.error("[OneAddress SDK] Handler error:", msg);
284
+ return new Response(JSON.stringify({ error: "Internal handler error" }), {
285
+ status: 500,
286
+ headers: { "Content-Type": "application/json" }
287
+ });
288
+ }
289
+ };
290
+ }
291
+
292
+ export {
293
+ DEFAULT_REPLAY_WINDOW_SECS,
294
+ isFreshTimestamp,
295
+ CURRENT_VERSION,
296
+ SUPPORTED_VERSIONS,
297
+ verifySignature,
298
+ verifyWithGrace,
299
+ decryptAddress,
300
+ fetchLoaPublicKey,
301
+ verifyLOA,
302
+ validateAddress,
303
+ createOneAddressHandler
304
+ };
@@ -0,0 +1,3 @@
1
+ export { EncryptedPayload, OneAddressAddress, OneAddressCustomer, OneAddressHandlerOptions, OneAddressLOA, OneAddressUpdateEvent, OneAddressVerifyEvent, createOneAddressHandler, decrypt as decryptAddress, fetchLoaPublicKey, validateAddress, verifyLOA, verify as verifySignature, verifyGrace as verifyWithGrace } from './index.mjs';
2
+ export { CURRENT_VERSION, SUPPORTED_VERSIONS } from '@oneaddress/protocol';
3
+ export { DEFAULT_REPLAY_WINDOW_SECS, isFreshTimestamp } from '@oneaddress/crypto';
package/dist/edge.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { EncryptedPayload, OneAddressAddress, OneAddressCustomer, OneAddressHandlerOptions, OneAddressLOA, OneAddressUpdateEvent, OneAddressVerifyEvent, createOneAddressHandler, decrypt as decryptAddress, fetchLoaPublicKey, validateAddress, verifyLOA, verify as verifySignature, verifyGrace as verifyWithGrace } from './index.js';
2
+ export { CURRENT_VERSION, SUPPORTED_VERSIONS } from '@oneaddress/protocol';
3
+ export { DEFAULT_REPLAY_WINDOW_SECS, isFreshTimestamp } from '@oneaddress/crypto';