@oneaddress/conformance 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.
Files changed (3) hide show
  1. package/README.md +74 -0
  2. package/dist/index.js +578 -0
  3. package/package.json +27 -0
package/README.md ADDED
@@ -0,0 +1,74 @@
1
+ # `@oneaddress/conformance`
2
+
3
+ CLI tool partners use to verify their webhook integration conforms to the OneAddress protocol. Ships as `oneaddress-conformance` once built.
4
+
5
+ ## What it checks
6
+
7
+ Runs a suite of end-to-end checks against a partner's webhook endpoint, covering:
8
+
9
+ 1. **HTTP basics** — endpoint reachable, responds to POST, returns a parseable body.
10
+ 2. **HMAC signature verification** — rejects tampered bodies, rejects wrong secrets, rejects missing headers.
11
+ 3. **Timestamp replay window** — rejects timestamps older than ±5 minutes (before signature verify).
12
+ 4. **Canonical signing format** — signature covers `${timestamp}.${rawBody}`, not the body alone.
13
+ 5. **Payload decryption** — partner can decrypt the ECDH/HKDF/AES-GCM address payload with their private key.
14
+ 6. **Idempotency guidance** — confirms the partner is reading `dispatchId` from the event (soft check; can't tell if they actually dedup, only that they receive the field).
15
+ 7. **Grace-window key rotation** — when both `currentSecret` and `previousSecret` are provided, verifies the partner accepts signatures from either while the grace window is open.
16
+ 8. **Error responses** — returns 4xx for known bad inputs rather than 5xx.
17
+ 9. **Pull API** (optional, requires `--customer-url`) — partner can fetch pending updates from `/api/dispatch/pull`.
18
+ 10. **Pull API confirm** (optional) — partner correctly acknowledges a pulled update via the confirm callback.
19
+
20
+ Checks 9 and 10 are skipped unless `--customer-url` is provided.
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ npx @oneaddress/conformance test <webhook-url>
26
+ ```
27
+
28
+ No install required — `npx` fetches the latest published version on demand.
29
+
30
+ ## Usage
31
+
32
+ ```bash
33
+ # Against your local dev server using built-in test credentials
34
+ oneaddress-conformance test http://localhost:3001/webhook
35
+
36
+ # Against a staging deployment with real credentials
37
+ oneaddress-conformance test https://api.mycompany.com/oneaddress \
38
+ --secret whsec_real_xxx \
39
+ --partner-id 123e4567-e89b-12d3-a456-426614174000 \
40
+ --public-key <base64-SPKI-of-your-ECDH-public-key>
41
+
42
+ # Include the pull-API checks (9 and 10)
43
+ oneaddress-conformance test https://api.mycompany.com/oneaddress \
44
+ --secret whsec_xxx \
45
+ --partner-id aaa... \
46
+ --customer-url https://app.oneaddress.io
47
+ ```
48
+
49
+ ### Flags
50
+
51
+ | Flag | Default | Purpose |
52
+ |------|---------|---------|
53
+ | `--secret` | Built-in synthetic test secret (used when partner is testing the wizard scaffold) | Your HMAC webhook secret |
54
+ | `--partner-id` | Built-in test UUID | Your partner UUID |
55
+ | `--public-key` | Built-in test ECDH SPKI | Your ECDH P-256 public key, base64 SPKI |
56
+ | `--customer-url` | — | Customer-app base URL; when set, adds pull-API checks |
57
+
58
+ ## Exit codes
59
+
60
+ - `0` — all checks passed
61
+ - `1` — one or more checks failed (individual check output indicates which)
62
+ - `2` — CLI usage error (bad args, missing required flag)
63
+
64
+ ## Why it exists
65
+
66
+ - Gives partners a self-service way to validate their integration before go-live.
67
+ - Protects OneAddress against a partner that silently starts replying "200 OK" without actually verifying signatures — these checks deliberately send tampered bodies and expect a 4xx response.
68
+ - Locks the canonical signing format. If anyone ever changes it, this tool breaks, and that's the intended early-warning.
69
+
70
+ ## Related
71
+
72
+ - **`@oneaddress/partner-sdk`** — the TypeScript SDK that implements the partner side of these checks.
73
+ - **`packages/protocol`** — shared test vectors this CLI uses as ground truth.
74
+ - **Partner SDK README** — step-by-step integration guide (`packages/partner-sdk/README.md`).
package/dist/index.js ADDED
@@ -0,0 +1,578 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/checks.ts
27
+ var import_node_crypto = __toESM(require("crypto"));
28
+
29
+ // ../crypto/src/index.ts
30
+ function b64ToBytes(b64) {
31
+ const binary = atob(b64);
32
+ const bytes = new Uint8Array(binary.length);
33
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.codePointAt(i) ?? 0;
34
+ return bytes;
35
+ }
36
+ function bytesToB64(bytes) {
37
+ return btoa(String.fromCharCode(...bytes));
38
+ }
39
+ var subtle = () => globalThis.crypto.subtle;
40
+ var AU_STATE_FULL = {
41
+ "new south wales": "NSW",
42
+ "victoria": "VIC",
43
+ "queensland": "QLD",
44
+ "south australia": "SA",
45
+ "western australia": "WA",
46
+ "tasmania": "TAS",
47
+ "northern territory": "NT",
48
+ "australian capital territory": "ACT",
49
+ // Common shorthands people type
50
+ "act": "ACT",
51
+ "nsw": "NSW",
52
+ "vic": "VIC",
53
+ "qld": "QLD",
54
+ "sa": "SA",
55
+ "wa": "WA",
56
+ "tas": "TAS",
57
+ "nt": "NT"
58
+ };
59
+ function toTitleCase(s) {
60
+ return s.trim().replace(
61
+ /\S+/g,
62
+ (w) => /^\d/.test(w) ? w : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()
63
+ );
64
+ }
65
+ function normaliseAddress(addr) {
66
+ const rawState = (addr.state ?? "").trim();
67
+ const stateKey = rawState.toLowerCase();
68
+ const normState = AU_STATE_FULL[stateKey] ?? rawState.toUpperCase();
69
+ const rawCountry = (addr.country ?? "").trim();
70
+ const normCountry = rawCountry.toLowerCase() === "australia" ? "AU" : rawCountry.toUpperCase();
71
+ return {
72
+ ...addr,
73
+ street: toTitleCase(addr.street ?? ""),
74
+ suburb: toTitleCase(addr.suburb ?? ""),
75
+ state: normState,
76
+ postcode: (addr.postcode ?? "").trim(),
77
+ country: normCountry
78
+ };
79
+ }
80
+ async function encryptAddressForPartner(address, partner) {
81
+ const address_ = normaliseAddress(address);
82
+ const partnerPubKey = await subtle().importKey(
83
+ "spki",
84
+ b64ToBytes(partner.publicKeyB64),
85
+ { name: "ECDH", namedCurve: "P-256" },
86
+ false,
87
+ []
88
+ // public key — no usages
89
+ );
90
+ const ephemeral = await subtle().generateKey(
91
+ { name: "ECDH", namedCurve: "P-256" },
92
+ true,
93
+ ["deriveBits"]
94
+ );
95
+ const hkdfSaltBytes = globalThis.crypto.getRandomValues(new Uint8Array(32));
96
+ const ecdhBits = await subtle().deriveBits(
97
+ { name: "ECDH", public: partnerPubKey },
98
+ ephemeral.privateKey,
99
+ 256
100
+ );
101
+ const hkdfKey = await subtle().importKey("raw", ecdhBits, "HKDF", false, ["deriveBits"]);
102
+ const aesRaw = await subtle().deriveBits(
103
+ {
104
+ name: "HKDF",
105
+ hash: "SHA-256",
106
+ salt: hkdfSaltBytes,
107
+ info: new TextEncoder().encode(`oneaddress:${partner.partnerId}`)
108
+ },
109
+ hkdfKey,
110
+ 256
111
+ );
112
+ const aesKey = await subtle().importKey(
113
+ "raw",
114
+ aesRaw,
115
+ { name: "AES-GCM" },
116
+ false,
117
+ ["encrypt"]
118
+ );
119
+ const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
120
+ const plaintext = new TextEncoder().encode(JSON.stringify(address_));
121
+ const ciphertextBuf = await subtle().encrypt(
122
+ { name: "AES-GCM", iv },
123
+ aesKey,
124
+ plaintext
125
+ );
126
+ const ephPubRaw = await subtle().exportKey("raw", ephemeral.publicKey);
127
+ return {
128
+ ciphertext: bytesToB64(new Uint8Array(ciphertextBuf)),
129
+ iv: bytesToB64(iv),
130
+ ephemeralPublicKey: bytesToB64(new Uint8Array(ephPubRaw)),
131
+ partnerId: partner.partnerId,
132
+ encryptedAt: (/* @__PURE__ */ new Date()).toISOString(),
133
+ hkdfSalt: bytesToB64(hkdfSaltBytes)
134
+ };
135
+ }
136
+
137
+ // ../protocol/src/types.ts
138
+ var CURRENT_VERSION = "2026.1";
139
+
140
+ // src/credentials.ts
141
+ var TEST_WEBHOOK_SECRET = (
142
+ // NOSONAR — intentional test credential, not a real secret
143
+ "whsec_test_conformance_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
144
+ );
145
+ var TEST_PARTNER_ID = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
146
+ var TEST_PARTNER_PUBLIC_KEY_SPKI_B64 = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEqFmYg3ct73DoAR3WHO5pUr/bVtaKUlLb9bd+g0KwJGZkgUhGop6JhSzQZw08zuvLbvkJXZnz0BHfsXy4MfeTjg==";
147
+
148
+ // src/checks.ts
149
+ function sign(body, timestamp, secret) {
150
+ return import_node_crypto.default.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
151
+ }
152
+ function buildHeaders(partnerId, timestamp, signature, dispatchId, event = "address.updated") {
153
+ return {
154
+ "Content-Type": "application/json",
155
+ "X-OneAddress-Event": event,
156
+ "X-OneAddress-Partner": partnerId,
157
+ "X-OneAddress-Version": CURRENT_VERSION,
158
+ "X-OneAddress-Timestamp": timestamp,
159
+ "X-OneAddress-Signature": signature,
160
+ "X-OneAddress-Dispatch": dispatchId
161
+ };
162
+ }
163
+ async function buildBody(partnerId, publicKeyB64, extraFields) {
164
+ const encrypted = await encryptAddressForPartner(
165
+ {
166
+ street: "42 Collins Street",
167
+ suburb: "Melbourne",
168
+ state: "VIC",
169
+ postcode: "3000",
170
+ country: "AU"
171
+ },
172
+ { partnerId, publicKeyB64 }
173
+ );
174
+ return JSON.stringify({
175
+ event: "address.updated",
176
+ oneaddress_version: CURRENT_VERSION,
177
+ version: CURRENT_VERSION,
178
+ id: import_node_crypto.default.randomUUID(),
179
+ timestamp: String(Math.floor(Date.now() / 1e3)),
180
+ partner_id: partnerId,
181
+ customer: { email: "conformance@test.oneaddress.io", name: "Conformance Test" },
182
+ address_encrypted: encrypted,
183
+ encryption_status: "encrypted",
184
+ ...extraFields
185
+ });
186
+ }
187
+ async function post(url, body, headers, timeoutMs = 12e3) {
188
+ const controller = new AbortController();
189
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
190
+ const start = Date.now();
191
+ try {
192
+ const res = await fetch(url, {
193
+ method: "POST",
194
+ headers,
195
+ body,
196
+ signal: controller.signal,
197
+ redirect: "error"
198
+ });
199
+ return { status: res.status, durationMs: Date.now() - start };
200
+ } catch (err) {
201
+ return { status: 0, durationMs: Date.now() - start, error: String(err) };
202
+ } finally {
203
+ clearTimeout(timer);
204
+ }
205
+ }
206
+ function signGet(timestamp, secret) {
207
+ return import_node_crypto.default.createHmac("sha256", secret).update(`${timestamp}.`).digest("hex");
208
+ }
209
+ async function get(url, headers, timeoutMs = 12e3) {
210
+ const controller = new AbortController();
211
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
212
+ const start = Date.now();
213
+ try {
214
+ const res = await fetch(url, {
215
+ method: "GET",
216
+ headers,
217
+ signal: controller.signal,
218
+ redirect: "error"
219
+ });
220
+ const body = await res.text();
221
+ const resHdrs = /* @__PURE__ */ new Map();
222
+ res.headers.forEach((v, k) => resHdrs.set(k.toLowerCase(), v));
223
+ return { status: res.status, headers: resHdrs, body, durationMs: Date.now() - start };
224
+ } catch (err) {
225
+ return { status: 0, headers: /* @__PURE__ */ new Map(), body: "", durationMs: Date.now() - start, error: String(err) };
226
+ } finally {
227
+ clearTimeout(timer);
228
+ }
229
+ }
230
+ async function runChecks(urlOrOptions, secret = TEST_WEBHOOK_SECRET, partnerId = TEST_PARTNER_ID, publicKeyB64 = TEST_PARTNER_PUBLIC_KEY_SPKI_B64) {
231
+ let targetUrl;
232
+ let customerUrl;
233
+ if (typeof urlOrOptions === "object") {
234
+ targetUrl = urlOrOptions.targetUrl;
235
+ secret = urlOrOptions.secret ?? TEST_WEBHOOK_SECRET;
236
+ partnerId = urlOrOptions.partnerId ?? TEST_PARTNER_ID;
237
+ publicKeyB64 = urlOrOptions.publicKeyB64 ?? TEST_PARTNER_PUBLIC_KEY_SPKI_B64;
238
+ customerUrl = urlOrOptions.customerUrl;
239
+ } else {
240
+ targetUrl = urlOrOptions;
241
+ }
242
+ const results = [];
243
+ const sharedBody = await buildBody(partnerId, publicKeyB64);
244
+ {
245
+ const ts = String(Math.floor(Date.now() / 1e3));
246
+ const sig = sign(sharedBody, ts, secret);
247
+ const { status, error } = await post(targetUrl, sharedBody, buildHeaders(partnerId, ts, sig, "1"));
248
+ const passed = !error && status >= 200 && status < 300;
249
+ results.push({
250
+ id: "check-1",
251
+ label: "Accepts correctly signed webhook",
252
+ passed,
253
+ detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 2xx`
254
+ });
255
+ }
256
+ {
257
+ const ts = String(Math.floor(Date.now() / 1e3));
258
+ const sig = sign(sharedBody, ts, secret);
259
+ const badSig = sig.slice(0, -1) + (sig.endsWith("a") ? "b" : "a");
260
+ const { status, error } = await post(targetUrl, sharedBody, buildHeaders(partnerId, ts, badSig, "2"));
261
+ const passed = !error && status >= 400 && status < 500;
262
+ results.push({
263
+ id: "check-2",
264
+ label: "Rejects invalid signature",
265
+ passed,
266
+ detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 4xx`
267
+ });
268
+ }
269
+ {
270
+ const staleTs = String(Math.floor(Date.now() / 1e3) - 600);
271
+ const staleSig = sign(sharedBody, staleTs, secret);
272
+ const { status, error } = await post(targetUrl, sharedBody, buildHeaders(partnerId, staleTs, staleSig, "3"));
273
+ const passed = !error && status >= 400 && status < 500;
274
+ results.push({
275
+ id: "check-3",
276
+ label: "Rejects stale timestamp (replay protection)",
277
+ passed,
278
+ detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 4xx`
279
+ });
280
+ }
281
+ {
282
+ const futureTs = String(Math.floor(Date.now() / 1e3) + 600);
283
+ const futureSig = sign(sharedBody, futureTs, secret);
284
+ const { status, error } = await post(targetUrl, sharedBody, buildHeaders(partnerId, futureTs, futureSig, "4"));
285
+ const passed = !error && status >= 400 && status < 500;
286
+ results.push({
287
+ id: "check-4",
288
+ label: "Rejects future timestamp (\xB1300s window)",
289
+ passed,
290
+ detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 4xx`
291
+ });
292
+ }
293
+ {
294
+ const ts = String(Math.floor(Date.now() / 1e3));
295
+ const sig = sign(sharedBody, ts, secret);
296
+ const { durationMs, error } = await post(targetUrl, sharedBody, buildHeaders(partnerId, ts, sig, "5"));
297
+ const passed = !error && durationMs < 1e4;
298
+ results.push({
299
+ id: "check-5",
300
+ label: "Responds within 10 seconds",
301
+ passed,
302
+ detail: error ? `Network error: ${error}` : `${durationMs}ms \u2014 limit is 10 000ms`
303
+ });
304
+ }
305
+ {
306
+ const futureBody = await buildBody(partnerId, publicKeyB64, { future_field: "ignored", future_object: { x: 1 } });
307
+ const ts = String(Math.floor(Date.now() / 1e3));
308
+ const sig = sign(futureBody, ts, secret);
309
+ const { status, error } = await post(targetUrl, futureBody, buildHeaders(partnerId, ts, sig, "6"));
310
+ const passed = !error && status >= 200 && status < 300;
311
+ results.push({
312
+ id: "check-6",
313
+ label: "Handles unknown fields gracefully (forward compat)",
314
+ passed,
315
+ detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 2xx`
316
+ });
317
+ }
318
+ {
319
+ const unknownBody = JSON.stringify({
320
+ event: "address.future_event",
321
+ oneaddress_version: CURRENT_VERSION,
322
+ version: CURRENT_VERSION,
323
+ id: import_node_crypto.default.randomUUID(),
324
+ timestamp: String(Math.floor(Date.now() / 1e3)),
325
+ partner_id: partnerId
326
+ });
327
+ const ts = String(Math.floor(Date.now() / 1e3));
328
+ const sig = sign(unknownBody, ts, secret);
329
+ const { status, error } = await post(
330
+ targetUrl,
331
+ unknownBody,
332
+ buildHeaders(partnerId, ts, sig, "7", "address.future_event")
333
+ );
334
+ const passed = !error && status >= 200 && status < 300;
335
+ results.push({
336
+ id: "check-7",
337
+ label: "Accepts unknown event type gracefully",
338
+ passed,
339
+ detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 2xx (acknowledge, do not error on new event types)`
340
+ });
341
+ }
342
+ {
343
+ const ts1 = String(Math.floor(Date.now() / 1e3));
344
+ const sig1 = sign(sharedBody, ts1, secret);
345
+ const dedupId = import_node_crypto.default.randomUUID().slice(0, 8);
346
+ const { status: s1, error: e1 } = await post(
347
+ targetUrl,
348
+ sharedBody,
349
+ buildHeaders(partnerId, ts1, sig1, `dedup-${dedupId}`)
350
+ );
351
+ await new Promise((r) => setTimeout(r, 200));
352
+ const ts2 = String(Math.floor(Date.now() / 1e3));
353
+ const sig2 = sign(sharedBody, ts2, secret);
354
+ const res2 = await fetch(targetUrl, {
355
+ method: "POST",
356
+ headers: buildHeaders(partnerId, ts2, sig2, `dedup-${dedupId}`),
357
+ body: sharedBody
358
+ }).catch(() => null);
359
+ const s2 = res2?.status ?? 0;
360
+ const body2Text = res2 ? await res2.text().catch(() => "") : "";
361
+ let body2 = {};
362
+ try {
363
+ body2 = JSON.parse(body2Text);
364
+ } catch {
365
+ }
366
+ const bothOk = !e1 && s1 >= 200 && s1 < 300 && s2 >= 200 && s2 < 300;
367
+ const hasDupe = body2.duplicate === true;
368
+ const passed = bothOk && hasDupe;
369
+ results.push({
370
+ id: "check-8",
371
+ label: "Idempotent: duplicate dispatch_id \u2192 200 + { duplicate: true }",
372
+ passed,
373
+ detail: e1 ? `Network error: ${e1}` : !bothOk ? `First: HTTP ${s1}, Second: HTTP ${s2} \u2014 both expected 2xx` : !hasDupe ? `Both returned 2xx but second response body missing { duplicate: true } \u2014 idempotency store not wired` : `First: HTTP ${s1}, Second: HTTP ${s2} with duplicate:true`
374
+ });
375
+ }
376
+ {
377
+ const badBody = "this is not { valid json";
378
+ const ts = String(Math.floor(Date.now() / 1e3));
379
+ const sig = sign(badBody, ts, secret);
380
+ const { status, error } = await post(targetUrl, badBody, buildHeaders(partnerId, ts, sig, "bad-json"));
381
+ const passed = !error && status >= 400 && status < 500;
382
+ results.push({
383
+ id: "check-9",
384
+ label: "Rejects malformed JSON body with 4xx",
385
+ passed,
386
+ detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 4xx`
387
+ });
388
+ }
389
+ {
390
+ const nearEdgeTs = String(Math.floor(Date.now() / 1e3) - 295);
391
+ const nearEdgeSig = sign(sharedBody, nearEdgeTs, secret);
392
+ const { status, error } = await post(
393
+ targetUrl,
394
+ sharedBody,
395
+ buildHeaders(partnerId, nearEdgeTs, nearEdgeSig, "near-edge")
396
+ );
397
+ const passed = !error && status >= 200 && status < 300;
398
+ results.push({
399
+ id: "check-10",
400
+ label: "Accepts timestamp near replay-window edge (4m55s old)",
401
+ passed,
402
+ detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 2xx (timestamp is within the \xB1300s window)`
403
+ });
404
+ }
405
+ if (customerUrl) {
406
+ const pullBase = customerUrl.replace(/\/$/, "");
407
+ {
408
+ const ts = String(Math.floor(Date.now() / 1e3));
409
+ const sig = signGet(ts, secret);
410
+ const url = `${pullBase}/api/partners/${partnerId}/updates`;
411
+ const { status, error } = await get(url, {
412
+ "X-OneAddress-Timestamp": ts,
413
+ "X-OneAddress-Signature": sig
414
+ });
415
+ const passed = !error && status === 200;
416
+ results.push({
417
+ id: "check-11",
418
+ label: "Pull /updates \u2014 authenticated GET returns 200",
419
+ passed,
420
+ detail: error ? `Network error: ${error}` : `HTTP ${status} \u2014 expected 200`
421
+ });
422
+ }
423
+ {
424
+ const ts = String(Math.floor(Date.now() / 1e3));
425
+ const sig = signGet(ts, secret);
426
+ const url = `${pullBase}/api/partners/${partnerId}/audit`;
427
+ const { status, headers: resHdrs, body: resBody, error } = await get(url, {
428
+ "X-OneAddress-Timestamp": ts,
429
+ "X-OneAddress-Signature": sig
430
+ });
431
+ let passed = false;
432
+ let detail = "";
433
+ if (error) {
434
+ detail = `Network error: ${error}`;
435
+ } else if (status !== 200) {
436
+ detail = `HTTP ${status} \u2014 expected 200`;
437
+ } else {
438
+ const resSig = resHdrs.get("x-oneaddress-signature");
439
+ const resTs = resHdrs.get("x-oneaddress-timestamp");
440
+ if (!resSig || !resTs) {
441
+ detail = `Response missing X-OneAddress-Signature or X-OneAddress-Timestamp headers`;
442
+ } else {
443
+ const expected = import_node_crypto.default.createHmac("sha256", secret).update(`${resTs}.${resBody}`).digest("hex");
444
+ if (resSig === expected) {
445
+ passed = true;
446
+ detail = `HTTP 200, response signature verified`;
447
+ } else {
448
+ detail = `HTTP 200 but response signature mismatch`;
449
+ }
450
+ }
451
+ }
452
+ results.push({
453
+ id: "check-12",
454
+ label: "Pull /audit \u2014 response is correctly signed",
455
+ passed,
456
+ detail
457
+ });
458
+ }
459
+ }
460
+ return results;
461
+ }
462
+
463
+ // src/report.ts
464
+ var PASS = "\u2705";
465
+ var FAIL = "\u274C";
466
+ function printReport(results) {
467
+ const width = 50;
468
+ console.log("\n" + "\u2500".repeat(width));
469
+ console.log(" OneAddress Conformance Report");
470
+ console.log("\u2500".repeat(width));
471
+ for (const r of results) {
472
+ const icon = r.passed ? PASS : FAIL;
473
+ const status = r.passed ? "PASSED" : "FAILED";
474
+ const label = r.label.padEnd(40);
475
+ console.log(` ${icon} ${label} ${status}`);
476
+ if (!r.passed) {
477
+ console.log(` \u21B3 ${r.detail}`);
478
+ }
479
+ }
480
+ const passed = results.filter((r) => r.passed).length;
481
+ const total = results.length;
482
+ console.log("\u2500".repeat(width));
483
+ if (passed === total) {
484
+ console.log(`
485
+ ${PASS} ${passed}/${total} checks passed. Your integration is ready.`);
486
+ console.log(" Replace credentials in .env with your real portal keys to go live.\n");
487
+ } else {
488
+ console.log(`
489
+ ${FAIL} ${passed}/${total} checks passed. See failures above.
490
+ `);
491
+ console.log(" Docs: https://docs.oneaddress.io/integration/SPEC.md\n");
492
+ }
493
+ }
494
+ function exitCode(results) {
495
+ return results.every((r) => r.passed) ? 0 : 1;
496
+ }
497
+
498
+ // src/index.ts
499
+ var USAGE = `
500
+ Usage: oneaddress-conformance test <webhook-url>
501
+
502
+ Options:
503
+ --secret <webhook_secret> Webhook secret from the OneAddress Partner Portal (default: built-in test secret)
504
+ --partner-id <uuid> Partner UUID (default: built-in test ID)
505
+ --public-key <b64> Partner ECDH public key SPKI Base64 (default: built-in test key)
506
+ --customer-url <url> Customer app URL for pull API checks (adds checks 9 + 10)
507
+
508
+ Example:
509
+ oneaddress-conformance test http://localhost:3001/webhook
510
+ oneaddress-conformance test https://api.mycompany.com/oneaddress --secret whsec_real_xxx
511
+ oneaddress-conformance test https://api.mycompany.com/oneaddress \\
512
+ --secret whsec_xxx --partner-id aaa... --customer-url https://app.oneaddress.io
513
+ `.trim();
514
+ async function main() {
515
+ const args = process.argv.slice(2);
516
+ if (args[0] !== "test" || !args[1] || args[1].startsWith("--")) {
517
+ console.log(USAGE);
518
+ process.exit(1);
519
+ }
520
+ const targetUrl = args[1];
521
+ const getFlag = (flag) => {
522
+ const idx = args.indexOf(flag);
523
+ return idx !== -1 ? args[idx + 1] : void 0;
524
+ };
525
+ const secret = getFlag("--secret");
526
+ const partnerId = getFlag("--partner-id");
527
+ const publicKey = getFlag("--public-key");
528
+ const customerUrl = getFlag("--customer-url");
529
+ try {
530
+ new URL(targetUrl);
531
+ } catch {
532
+ console.error(`Error: "${targetUrl}" is not a valid URL.`);
533
+ process.exit(1);
534
+ }
535
+ if (customerUrl) {
536
+ try {
537
+ new URL(customerUrl);
538
+ } catch {
539
+ console.error(`Error: --customer-url "${customerUrl}" is not a valid URL.`);
540
+ process.exit(1);
541
+ }
542
+ }
543
+ const parsedTarget = new URL(targetUrl);
544
+ const isLocalhost = ["localhost", "127.0.0.1", "::1"].includes(parsedTarget.hostname);
545
+ if (parsedTarget.protocol === "http:" && !isLocalhost) {
546
+ console.error("");
547
+ console.error(" \u2717 HTTPS REQUIRED");
548
+ console.error(" Your webhook endpoint uses HTTP, not HTTPS.");
549
+ console.error(" Production endpoints must use TLS (https://) to protect");
550
+ console.error(" the webhook secret and address payload in transit.");
551
+ console.error(" Obtain a certificate (Let's Encrypt is free) before going live.");
552
+ console.error("");
553
+ process.exit(1);
554
+ }
555
+ if (parsedTarget.protocol === "http:" && isLocalhost) {
556
+ console.warn("\n \u26A0 HTTP detected \u2014 acceptable for local testing only.\n");
557
+ }
558
+ console.log(`
559
+ Running conformance checks against: ${targetUrl}`);
560
+ if (customerUrl) console.log(`Pull API checks against: ${customerUrl}`);
561
+ console.log("");
562
+ const results = await runChecks({
563
+ targetUrl,
564
+ secret,
565
+ partnerId,
566
+ publicKeyB64: publicKey,
567
+ customerUrl
568
+ });
569
+ printReport(results);
570
+ const code = exitCode(results);
571
+ process.exitCode = code;
572
+ setTimeout(() => process.exit(code), 50).unref();
573
+ }
574
+ main().catch((err) => {
575
+ console.error("Unexpected error:", err instanceof Error ? err.message : String(err));
576
+ process.exitCode = 1;
577
+ setTimeout(() => process.exit(1), 50).unref();
578
+ });
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "@oneaddress/conformance",
3
+ "version": "1.0.0",
4
+ "description": "Conformance test tool for OneAddress partner integrations",
5
+ "license": "UNLICENSED",
6
+ "bin": {
7
+ "oneaddress-conformance": "./dist/index.js"
8
+ },
9
+ "files": ["dist", "README.md"],
10
+ "scripts": {
11
+ "build": "tsup",
12
+ "prepare": "tsup",
13
+ "type-check": "tsc --noEmit"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "devDependencies": {
19
+ "@oneaddress/crypto": "*",
20
+ "@oneaddress/protocol": "*",
21
+ "tsup": "^8.0.0",
22
+ "typescript": "^5.0.0"
23
+ },
24
+ "engines": {
25
+ "node": ">=18"
26
+ }
27
+ }