@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 +192 -0
- package/dist/chunk-NBUGPU44.mjs +304 -0
- package/dist/edge.d.mts +3 -0
- package/dist/edge.d.ts +3 -0
- package/dist/edge.js +350 -0
- package/dist/edge.mjs +26 -0
- package/dist/index.d.mts +298 -0
- package/dist/index.d.ts +298 -0
- package/dist/index.js +354 -0
- package/dist/index.mjs +29 -0
- package/package.json +38 -0
package/dist/index.d.ts
ADDED
|
@@ -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 };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
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/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
CURRENT_VERSION: () => CURRENT_VERSION,
|
|
34
|
+
DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
|
|
35
|
+
SUPPORTED_VERSIONS: () => SUPPORTED_VERSIONS,
|
|
36
|
+
createOneAddressHandler: () => createOneAddressHandler,
|
|
37
|
+
decrypt: () => decryptAddress,
|
|
38
|
+
decryptAddress: () => decryptAddress,
|
|
39
|
+
fetchLoaPublicKey: () => fetchLoaPublicKey,
|
|
40
|
+
isFreshTimestamp: () => isFreshTimestamp,
|
|
41
|
+
validateAddress: () => validateAddress,
|
|
42
|
+
verify: () => verifySignature,
|
|
43
|
+
verifyGrace: () => verifyWithGrace,
|
|
44
|
+
verifyLOA: () => verifyLOA,
|
|
45
|
+
verifySignature: () => verifySignature,
|
|
46
|
+
verifyWithGrace: () => verifyWithGrace
|
|
47
|
+
});
|
|
48
|
+
module.exports = __toCommonJS(index_exports);
|
|
49
|
+
var import_crypto = __toESM(require("crypto"));
|
|
50
|
+
|
|
51
|
+
// ../crypto/src/replay-window.ts
|
|
52
|
+
var DEFAULT_REPLAY_WINDOW_SECS = 300;
|
|
53
|
+
function isFreshTimestamp(timestampHeader, toleranceSecs = DEFAULT_REPLAY_WINDOW_SECS, nowSecs) {
|
|
54
|
+
if (typeof timestampHeader !== "string" || timestampHeader.length === 0) return false;
|
|
55
|
+
if (!/^\d+$/.test(timestampHeader)) return false;
|
|
56
|
+
const ts = Number(timestampHeader);
|
|
57
|
+
if (!Number.isFinite(ts) || ts < 0) return false;
|
|
58
|
+
const now = typeof nowSecs === "number" ? nowSecs : Math.floor(Date.now() / 1e3);
|
|
59
|
+
return Math.abs(now - ts) <= toleranceSecs;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ../protocol/src/types.ts
|
|
63
|
+
var CURRENT_VERSION = "2026.1";
|
|
64
|
+
var SUPPORTED_VERSIONS = ["2026.1"];
|
|
65
|
+
|
|
66
|
+
// src/index.ts
|
|
67
|
+
function verifySignature(rawBody, signature, timestamp, secret) {
|
|
68
|
+
const sigPayload = `${timestamp}.${rawBody}`;
|
|
69
|
+
const expected = import_crypto.default.createHmac("sha256", secret).update(sigPayload).digest("hex");
|
|
70
|
+
const sigBuffer = Buffer.from(signature, "hex");
|
|
71
|
+
const expBuffer = Buffer.from(expected, "hex");
|
|
72
|
+
if (sigBuffer.length !== expBuffer.length) return false;
|
|
73
|
+
return import_crypto.default.timingSafeEqual(sigBuffer, expBuffer);
|
|
74
|
+
}
|
|
75
|
+
function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousSecret, graceUntil) {
|
|
76
|
+
if (verifySignature(rawBody, signature, timestamp, currentSecret)) return true;
|
|
77
|
+
if (previousSecret && graceUntil) {
|
|
78
|
+
const until = typeof graceUntil === "number" ? graceUntil : Date.parse(graceUntil);
|
|
79
|
+
if (!Number.isNaN(until) && Date.now() < until) {
|
|
80
|
+
return verifySignature(rawBody, signature, timestamp, previousSecret);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
function base64urlToBuffer(b64) {
|
|
86
|
+
return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
87
|
+
}
|
|
88
|
+
function pemToBuffer(pem) {
|
|
89
|
+
return Buffer.from(pem.replace(/-----[^-]+-----/g, "").replace(/\s/g, ""), "base64");
|
|
90
|
+
}
|
|
91
|
+
async function decryptAddress(payload, privateKeyPem, partnerId) {
|
|
92
|
+
const { ephemeralPublicKey, iv, ciphertext, hkdfSalt } = payload;
|
|
93
|
+
const privateKey = await import_crypto.default.subtle.importKey(
|
|
94
|
+
"pkcs8",
|
|
95
|
+
pemToBuffer(privateKeyPem),
|
|
96
|
+
{ name: "ECDH", namedCurve: "P-256" },
|
|
97
|
+
false,
|
|
98
|
+
["deriveBits"]
|
|
99
|
+
);
|
|
100
|
+
const ephemeralKey = await import_crypto.default.subtle.importKey(
|
|
101
|
+
"raw",
|
|
102
|
+
base64urlToBuffer(ephemeralPublicKey),
|
|
103
|
+
{ name: "ECDH", namedCurve: "P-256" },
|
|
104
|
+
false,
|
|
105
|
+
[]
|
|
106
|
+
);
|
|
107
|
+
const sharedBits = await import_crypto.default.subtle.deriveBits(
|
|
108
|
+
{ name: "ECDH", public: ephemeralKey },
|
|
109
|
+
privateKey,
|
|
110
|
+
256
|
|
111
|
+
);
|
|
112
|
+
const hkdfKey = await import_crypto.default.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveBits"]);
|
|
113
|
+
const salt = hkdfSalt ? base64urlToBuffer(hkdfSalt) : new Uint8Array(0);
|
|
114
|
+
const info = new TextEncoder().encode(`oneaddress:${partnerId}`);
|
|
115
|
+
const aesKeyBits = await import_crypto.default.subtle.deriveBits(
|
|
116
|
+
{ name: "HKDF", hash: "SHA-256", salt, info },
|
|
117
|
+
hkdfKey,
|
|
118
|
+
256
|
|
119
|
+
);
|
|
120
|
+
const aesKey = await import_crypto.default.subtle.importKey("raw", aesKeyBits, "AES-GCM", false, ["decrypt"]);
|
|
121
|
+
const plaintext = await import_crypto.default.subtle.decrypt(
|
|
122
|
+
{ name: "AES-GCM", iv: base64urlToBuffer(iv), tagLength: 128 },
|
|
123
|
+
aesKey,
|
|
124
|
+
base64urlToBuffer(ciphertext)
|
|
125
|
+
);
|
|
126
|
+
return JSON.parse(new TextDecoder().decode(plaintext));
|
|
127
|
+
}
|
|
128
|
+
var OA_APP_BASE_URL = "https://app.oneaddress.io";
|
|
129
|
+
var ALLOWED_LOA_HOSTS = /* @__PURE__ */ new Set(["app.oneaddress.io", "localhost", "127.0.0.1"]);
|
|
130
|
+
async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
|
|
131
|
+
let parsedBase;
|
|
132
|
+
try {
|
|
133
|
+
parsedBase = new URL(appBaseUrl);
|
|
134
|
+
} catch {
|
|
135
|
+
throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl is not a valid URL");
|
|
136
|
+
}
|
|
137
|
+
if (!ALLOWED_LOA_HOSTS.has(parsedBase.hostname)) {
|
|
138
|
+
throw new Error(
|
|
139
|
+
`[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...ALLOWED_LOA_HOSTS].join(", ")}`
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
|
|
143
|
+
const res = await fetch(url);
|
|
144
|
+
if (!res.ok) {
|
|
145
|
+
throw new Error(`[OneAddress SDK] Failed to fetch LOA public key: HTTP ${res.status}`);
|
|
146
|
+
}
|
|
147
|
+
return res.text();
|
|
148
|
+
}
|
|
149
|
+
async function verifyLOA(loa, publicKeyPem) {
|
|
150
|
+
if (loa.algorithm !== "ECDSA-P256") {
|
|
151
|
+
console.warn(
|
|
152
|
+
// NOSONAR — intentional SDK diagnostic, not user-controlled data
|
|
153
|
+
"[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."
|
|
154
|
+
);
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
try {
|
|
158
|
+
const key = await import_crypto.default.subtle.importKey(
|
|
159
|
+
"spki",
|
|
160
|
+
pemToBuffer(publicKeyPem),
|
|
161
|
+
{ name: "ECDSA", namedCurve: "P-256" },
|
|
162
|
+
false,
|
|
163
|
+
["verify"]
|
|
164
|
+
);
|
|
165
|
+
const sigBytes = Buffer.from(loa.signature, "hex");
|
|
166
|
+
const textBytes = new TextEncoder().encode(loa.text);
|
|
167
|
+
return await import_crypto.default.subtle.verify(
|
|
168
|
+
{ name: "ECDSA", hash: "SHA-256" },
|
|
169
|
+
key,
|
|
170
|
+
sigBytes,
|
|
171
|
+
textBytes
|
|
172
|
+
);
|
|
173
|
+
} catch {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
var ADDRESS_REQUIRED_FIELDS = [
|
|
178
|
+
"street",
|
|
179
|
+
"suburb",
|
|
180
|
+
"state",
|
|
181
|
+
"postcode",
|
|
182
|
+
"country"
|
|
183
|
+
];
|
|
184
|
+
function validateAddress(raw) {
|
|
185
|
+
if (typeof raw !== "object" || raw === null) {
|
|
186
|
+
throw new Error("[OneAddress SDK] Decrypted address payload is not an object");
|
|
187
|
+
}
|
|
188
|
+
const obj = raw;
|
|
189
|
+
for (const field of ADDRESS_REQUIRED_FIELDS) {
|
|
190
|
+
if (typeof obj[field] !== "string" || obj[field] === "") {
|
|
191
|
+
throw new Error(
|
|
192
|
+
`[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change \u2014 update @oneaddress/partner-sdk.`
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return obj;
|
|
197
|
+
}
|
|
198
|
+
function createOneAddressHandler(options) {
|
|
199
|
+
const {
|
|
200
|
+
webhookSecret,
|
|
201
|
+
previousWebhookSecret,
|
|
202
|
+
webhookSecretGraceUntil,
|
|
203
|
+
privateKeyPem,
|
|
204
|
+
onUpdate,
|
|
205
|
+
onVerify,
|
|
206
|
+
timestampToleranceSecs = 300,
|
|
207
|
+
idempotencyStore
|
|
208
|
+
} = options;
|
|
209
|
+
return async function handler(req) {
|
|
210
|
+
const rawBody = await req.text();
|
|
211
|
+
const sig = req.headers.get("x-oneaddress-signature") ?? "";
|
|
212
|
+
const tsHeader = req.headers.get("x-oneaddress-timestamp") ?? "";
|
|
213
|
+
if (!isFreshTimestamp(tsHeader, timestampToleranceSecs)) {
|
|
214
|
+
return new Response(JSON.stringify({ error: "Request timestamp out of tolerance" }), {
|
|
215
|
+
status: 400,
|
|
216
|
+
headers: { "Content-Type": "application/json" }
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
if (!verifyWithGrace(rawBody, tsHeader, sig, webhookSecret, previousWebhookSecret, webhookSecretGraceUntil)) {
|
|
220
|
+
return new Response(JSON.stringify({ error: "Invalid signature" }), {
|
|
221
|
+
status: 401,
|
|
222
|
+
headers: { "Content-Type": "application/json" }
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
let body;
|
|
226
|
+
try {
|
|
227
|
+
body = JSON.parse(rawBody);
|
|
228
|
+
} catch {
|
|
229
|
+
return new Response(JSON.stringify({ error: "Invalid JSON" }), {
|
|
230
|
+
status: 400,
|
|
231
|
+
headers: { "Content-Type": "application/json" }
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
const payloadVersion = body.oneaddress_version ?? body.version ?? "";
|
|
235
|
+
if (payloadVersion && !SUPPORTED_VERSIONS.includes(payloadVersion)) {
|
|
236
|
+
console.warn(
|
|
237
|
+
// NOSONAR — intentional SDK diagnostic, not user-controlled data
|
|
238
|
+
`[OneAddress SDK] Unrecognised protocol version "${payloadVersion}". Supported: ${SUPPORTED_VERSIONS.join(", ")}. Update @oneaddress/partner-sdk to the latest version.`
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
const partnerId = body.partner_id ?? "";
|
|
242
|
+
const tsNum = Number(tsHeader);
|
|
243
|
+
const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
|
|
244
|
+
if (dispatchId) {
|
|
245
|
+
if (!idempotencyStore) {
|
|
246
|
+
if (process.env.NODE_ENV === "test") {
|
|
247
|
+
throw new Error(
|
|
248
|
+
"[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
} else {
|
|
252
|
+
const alreadySeen = await idempotencyStore.has(dispatchId);
|
|
253
|
+
if (alreadySeen) {
|
|
254
|
+
return new Response(JSON.stringify({ ok: true, duplicate: true }), {
|
|
255
|
+
status: 200,
|
|
256
|
+
headers: { "Content-Type": "application/json" }
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
try {
|
|
262
|
+
if (body.event === "address.updated") {
|
|
263
|
+
if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
|
|
264
|
+
return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
|
|
265
|
+
status: 400,
|
|
266
|
+
headers: { "Content-Type": "application/json" }
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
const encrypted = body.address_encrypted;
|
|
270
|
+
const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
|
|
271
|
+
const event = {
|
|
272
|
+
event: "address.updated",
|
|
273
|
+
version: body.oneaddress_version ?? body.version ?? "1",
|
|
274
|
+
id: body.id ?? "",
|
|
275
|
+
timestamp: tsNum,
|
|
276
|
+
partner_id: partnerId,
|
|
277
|
+
dispatchId,
|
|
278
|
+
customer: body.customer,
|
|
279
|
+
address: validateAddress(rawAddress),
|
|
280
|
+
loa: body.loa,
|
|
281
|
+
raw: rawAddress
|
|
282
|
+
};
|
|
283
|
+
const result = await onUpdate(event);
|
|
284
|
+
if (dispatchId && idempotencyStore) {
|
|
285
|
+
await idempotencyStore.set(dispatchId).catch(
|
|
286
|
+
(err) => console.error("[OneAddress SDK] idempotencyStore.set failed:", err)
|
|
287
|
+
// NOSONAR
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
return new Response(JSON.stringify({ ok: true, ...result }), {
|
|
291
|
+
status: 200,
|
|
292
|
+
headers: { "Content-Type": "application/json" }
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
if (body.event === "address.verify" && onVerify) {
|
|
296
|
+
if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
|
|
297
|
+
return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
|
|
298
|
+
status: 400,
|
|
299
|
+
headers: { "Content-Type": "application/json" }
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
const encrypted = body.address_encrypted;
|
|
303
|
+
const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
|
|
304
|
+
const event = {
|
|
305
|
+
event: "address.verify",
|
|
306
|
+
version: body.oneaddress_version ?? body.version ?? "1",
|
|
307
|
+
id: body.id ?? "",
|
|
308
|
+
timestamp: tsNum,
|
|
309
|
+
partner_id: partnerId,
|
|
310
|
+
dispatchId,
|
|
311
|
+
batch_id: body.batch_id ?? 0,
|
|
312
|
+
user_id: body.user_id ?? "",
|
|
313
|
+
customer: body.customer ?? {},
|
|
314
|
+
address: validateAddress(rawAddress),
|
|
315
|
+
loa: body.loa,
|
|
316
|
+
raw: rawAddress
|
|
317
|
+
};
|
|
318
|
+
const result = await onVerify(event);
|
|
319
|
+
return new Response(JSON.stringify({ ok: true, ...result }), {
|
|
320
|
+
status: 200,
|
|
321
|
+
headers: { "Content-Type": "application/json" }
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
return new Response(JSON.stringify({ ok: true, skipped: true }), {
|
|
325
|
+
status: 200,
|
|
326
|
+
headers: { "Content-Type": "application/json" }
|
|
327
|
+
});
|
|
328
|
+
} catch (err) {
|
|
329
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
330
|
+
console.error("[OneAddress SDK] Handler error:", msg);
|
|
331
|
+
return new Response(JSON.stringify({ error: "Internal handler error" }), {
|
|
332
|
+
status: 500,
|
|
333
|
+
headers: { "Content-Type": "application/json" }
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
339
|
+
0 && (module.exports = {
|
|
340
|
+
CURRENT_VERSION,
|
|
341
|
+
DEFAULT_REPLAY_WINDOW_SECS,
|
|
342
|
+
SUPPORTED_VERSIONS,
|
|
343
|
+
createOneAddressHandler,
|
|
344
|
+
decrypt,
|
|
345
|
+
decryptAddress,
|
|
346
|
+
fetchLoaPublicKey,
|
|
347
|
+
isFreshTimestamp,
|
|
348
|
+
validateAddress,
|
|
349
|
+
verify,
|
|
350
|
+
verifyGrace,
|
|
351
|
+
verifyLOA,
|
|
352
|
+
verifySignature,
|
|
353
|
+
verifyWithGrace
|
|
354
|
+
});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
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 as decrypt,
|
|
20
|
+
decryptAddress,
|
|
21
|
+
fetchLoaPublicKey,
|
|
22
|
+
isFreshTimestamp,
|
|
23
|
+
validateAddress,
|
|
24
|
+
verifySignature as verify,
|
|
25
|
+
verifyWithGrace as verifyGrace,
|
|
26
|
+
verifyLOA,
|
|
27
|
+
verifySignature,
|
|
28
|
+
verifyWithGrace
|
|
29
|
+
};
|