@tokenoftrust/cli 7.14.1 → 7.14.2
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/cli",
|
|
3
|
-
"version": "7.14.
|
|
3
|
+
"version": "7.14.2",
|
|
4
4
|
"description": "Token of Trust developer CLI — clone a tenant store, run it locally with save→reload, and submit it for preview. Installs the `tot` command.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Token of Trust",
|
|
@@ -0,0 +1,683 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Bucket 3 conformance archetypes: marketing-esp, accounting-gl, affiliate-s2s and bi-export.
|
|
5
|
+
* Each archetype is a fixed checklist of signed deliveries plus a mock platform API served on
|
|
6
|
+
* the conformance listener, so the connector's platform API base is MOCK_ORIGIN. Payloads and
|
|
7
|
+
* API responses follow docs/private-apps/contract/{asyncapi,openapi}.yaml exactly.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const MOCK_ORIGIN = "http://127.0.0.1:37891";
|
|
11
|
+
export const BUCKET3_ARCHETYPES = ["marketing-esp", "accounting-gl", "affiliate-s2s", "bi-export"];
|
|
12
|
+
|
|
13
|
+
const API_PREFIX = "/api/apps/v1/";
|
|
14
|
+
const DOWNLOAD_PREFIX = "/_conformance/exports/";
|
|
15
|
+
const MAX_MOCK_BODY_BYTES = 65_536;
|
|
16
|
+
const CURRENCY = "USD";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @typedef {{ method: string, path: string, idempotencyKey: string | null, body: string }} MockRequest
|
|
20
|
+
* @typedef {{ status: number, headers: Record<string, string>, body: string }} MockResponse
|
|
21
|
+
* @typedef {{ log: MockRequest[], mark: number }} StepContext
|
|
22
|
+
* @typedef {{
|
|
23
|
+
* label: string,
|
|
24
|
+
* body: string,
|
|
25
|
+
* acknowledgment?: "initial" | "replay",
|
|
26
|
+
* tamper?: boolean,
|
|
27
|
+
* expect?: (ack: any, context: StepContext) => string | undefined,
|
|
28
|
+
* rejected?: (status: number) => string,
|
|
29
|
+
* refusal?: string,
|
|
30
|
+
* }} Step
|
|
31
|
+
* @typedef {{ label: string, detail: string, evaluate: (log: MockRequest[]) => string | undefined }} FinalCheck
|
|
32
|
+
* @typedef {{ steps: Step[], finalChecks: FinalCheck[], log: MockRequest[], owns: (url: string) => boolean, serve: (request: { method: string, url: string, headers: Record<string, string | string[] | undefined>, body: string }) => MockResponse }} ArchetypePlan
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/** @param {number} minute */
|
|
36
|
+
const fixtureTime = (minute) => new Date(Date.UTC(2026, 0, 1, 12, minute)).toISOString();
|
|
37
|
+
const EXPORT_EXPIRES_AT = new Date(Date.UTC(2026, 0, 2, 12, 10)).toISOString();
|
|
38
|
+
|
|
39
|
+
/** @param {string} value */
|
|
40
|
+
const sha256Hex = (value) => createHash("sha256").update(value).digest("hex");
|
|
41
|
+
|
|
42
|
+
/** A synthetic per-install customer hash: 64 lowercase hex, never a contact value. @param {string} label */
|
|
43
|
+
const customerHash = (label) => sha256Hex(`conformance-customer-${label}`);
|
|
44
|
+
|
|
45
|
+
/** @param {number} status @param {unknown} body @returns {MockResponse} */
|
|
46
|
+
function json(status, body) {
|
|
47
|
+
return { status, headers: { "content-type": "application/json", "cache-control": "no-store" }, body: JSON.stringify(body) };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Contract `Error` shape. @param {number} status @param {string} code @param {string} message */
|
|
51
|
+
const error = (status, code, message) => json(status, { code, message });
|
|
52
|
+
/** Contract `CustomerRefusal` / `ExportRefusal` shape. @param {number} status @param {string} code @param {string} message */
|
|
53
|
+
const refusal = (status, code, message) => json(status, { code, error: message });
|
|
54
|
+
const NO_ROUTE = error(404, "not_found", "No conformance mock route");
|
|
55
|
+
|
|
56
|
+
/** @param {unknown} key @param {number} min */
|
|
57
|
+
const validKey = (key, min) => typeof key === "string" && key.length >= min && key.length <= 128 && /^[\x21-\x7e]+$/.test(key);
|
|
58
|
+
|
|
59
|
+
/** Parse a closed JSON object body: every required key present and no other key. @param {string} text @param {string[]} required @param {string[]} [optional] */
|
|
60
|
+
function closedBody(text, required, optional = []) {
|
|
61
|
+
let body;
|
|
62
|
+
try {
|
|
63
|
+
body = JSON.parse(text);
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (error instanceof SyntaxError) return null;
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) return null;
|
|
69
|
+
const allowed = new Set([...required, ...optional]);
|
|
70
|
+
if (!required.every((key) => key in body) || !Object.keys(body).every((key) => allowed.has(key))) return null;
|
|
71
|
+
return body;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** @param {string} id @param {string} topic @param {unknown} data @param {number} minute @param {boolean} replay */
|
|
75
|
+
function cloudEvent(id, topic, data, minute, replay) {
|
|
76
|
+
return JSON.stringify({
|
|
77
|
+
specversion: "1.0",
|
|
78
|
+
id: `conformance-${id}`,
|
|
79
|
+
source: "/tenants/conformance/storefront",
|
|
80
|
+
type: `com.tokenoftrust.storefront.${topic}`,
|
|
81
|
+
time: fixtureTime(minute),
|
|
82
|
+
datacontenttype: "application/json",
|
|
83
|
+
dataschemaversion: "1",
|
|
84
|
+
tenantid: "conformance",
|
|
85
|
+
appinstallid: "conformance-install",
|
|
86
|
+
retrycount: replay ? 1 : 0,
|
|
87
|
+
data,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* @param {string} label
|
|
93
|
+
* @param {{ id: string, topic: string, data: unknown, minute: number } & Omit<Step, "label" | "body">} spec
|
|
94
|
+
* @returns {Step}
|
|
95
|
+
*/
|
|
96
|
+
function step(label, { id, topic, data, minute, ...rest }) {
|
|
97
|
+
return { label, ...rest, body: cloudEvent(id, topic, data, minute, rest.acknowledgment === "replay") };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A refused read must not be retried within one delivery. @param {MockRequest[]} requests @param {string[]} paths */
|
|
101
|
+
function retriedRead(requests, paths) {
|
|
102
|
+
for (const path of paths) {
|
|
103
|
+
const count = requests.filter((request) => request.path === path).length;
|
|
104
|
+
if (count > 1) return `refused ${path} read ${count} times in one delivery`;
|
|
105
|
+
}
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** @param {MockRequest[]} log @param {(request: MockRequest) => boolean} predicate */
|
|
110
|
+
const requestsWhere = (log, predicate) => log.filter(predicate);
|
|
111
|
+
|
|
112
|
+
// ---------------------------------------------------------------------------------------------
|
|
113
|
+
// marketing-esp
|
|
114
|
+
|
|
115
|
+
function marketingEsp() {
|
|
116
|
+
const subscribed = customerHash("subscribed");
|
|
117
|
+
const revoked = customerHash("revoked");
|
|
118
|
+
/** @type {Map<string, { email: string, sms: string }>} */
|
|
119
|
+
const consent = new Map([
|
|
120
|
+
[subscribed, { email: "subscribed", sms: "subscribed" }],
|
|
121
|
+
[revoked, { email: "unsubscribed", sms: "unsubscribed" }],
|
|
122
|
+
]);
|
|
123
|
+
/** @type {Map<string, string>} */
|
|
124
|
+
const optOutKeys = new Map();
|
|
125
|
+
const consentState = (/** @type {string} */ hash) => {
|
|
126
|
+
const state = consent.get(hash);
|
|
127
|
+
return { customerHash: hash, emailConsent: state?.email, smsConsent: state?.sms, updatedAt: fixtureTime(hash === subscribed ? 3 : 4) };
|
|
128
|
+
};
|
|
129
|
+
const contactPath = (/** @type {string} */ hash) => `${API_PREFIX}customers/${hash}/marketing-contact`;
|
|
130
|
+
|
|
131
|
+
/** @param {MockRequest} request @returns {MockResponse} */
|
|
132
|
+
function route(request) {
|
|
133
|
+
const match = /^\/api\/apps\/v1\/customers\/([^/]+)\/(marketing-contact|consent|marketing-opt-out)$/.exec(request.path);
|
|
134
|
+
if (!match) return request.path.startsWith(`${API_PREFIX}customers`) ? refusal(404, "not_found", "Unknown customer route") : NO_ROUTE;
|
|
135
|
+
const [, hash, operation] = match;
|
|
136
|
+
const state = consent.get(hash);
|
|
137
|
+
if (operation === "marketing-opt-out") {
|
|
138
|
+
if (request.method !== "POST") return refusal(404, "not_found", "Unknown customer route");
|
|
139
|
+
if (!validKey(request.idempotencyKey, 8)) return refusal(400, "malformed", "Idempotency-Key is required (8-128 characters)");
|
|
140
|
+
const body = closedBody(request.body, ["channel", "reason", "occurredAt"]);
|
|
141
|
+
if (!body || !["email", "sms", "all"].includes(body.channel)
|
|
142
|
+
|| !["unsubscribe", "hard_bounce", "spam_complaint", "carrier_stop"].includes(body.reason)
|
|
143
|
+
|| typeof body.occurredAt !== "string" || Number.isNaN(Date.parse(body.occurredAt))) {
|
|
144
|
+
return refusal(400, "malformed", "Body outside the closed opt-out schema");
|
|
145
|
+
}
|
|
146
|
+
if (!state) return refusal(404, "not_found", "Unknown customer");
|
|
147
|
+
const binding = `${hash}\n${body.channel}\n${body.reason}\n${body.occurredAt}`;
|
|
148
|
+
const prior = optOutKeys.get(/** @type {string} */ (request.idempotencyKey));
|
|
149
|
+
if (prior !== undefined && prior !== binding) return refusal(409, "idempotency_conflict", "Idempotency-Key reused with a different body");
|
|
150
|
+
optOutKeys.set(/** @type {string} */ (request.idempotencyKey), binding);
|
|
151
|
+
if (body.channel !== "sms" && state.email === "subscribed") state.email = "unsubscribed";
|
|
152
|
+
if (body.channel !== "email" && state.sms === "subscribed") state.sms = "unsubscribed";
|
|
153
|
+
return json(200, consentState(hash));
|
|
154
|
+
}
|
|
155
|
+
if (request.method !== "GET") return refusal(404, "not_found", "Unknown customer route");
|
|
156
|
+
if (!state) return refusal(404, "not_found", "Unknown customer");
|
|
157
|
+
if (operation === "consent") return json(200, consentState(hash));
|
|
158
|
+
if (state.email !== "subscribed" && state.sms !== "subscribed") {
|
|
159
|
+
return refusal(403, "customer_not_opted_in", "The customer holds no active marketing opt-in");
|
|
160
|
+
}
|
|
161
|
+
return json(200, {
|
|
162
|
+
customerHash: hash,
|
|
163
|
+
...(state.email === "subscribed" ? { email: "conformance-subscriber@example.com" } : {}),
|
|
164
|
+
...(state.sms === "subscribed" ? { phoneE164: "+15550100001" } : {}),
|
|
165
|
+
emailConsent: state.email,
|
|
166
|
+
smsConsent: state.sms,
|
|
167
|
+
...(state.email === "subscribed" ? { emailOptInAt: fixtureTime(0) } : {}),
|
|
168
|
+
...(state.sms === "subscribed" ? { smsOptInAt: fixtureTime(0) } : {}),
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const abandoned = { checkoutId: "conformance-checkout", currency: CURRENCY, subtotalMinor: 4599, lineCount: 2, abandonedAt: fixtureTime(1) };
|
|
173
|
+
const steps = [
|
|
174
|
+
step("Signature tamper refused", {
|
|
175
|
+
id: "checkout-tampered", topic: "checkout.abandoned", minute: 0, tamper: true,
|
|
176
|
+
data: { checkoutId: "conformance-checkout-tampered", currency: CURRENCY, subtotalMinor: 2599, lineCount: 1, abandonedAt: fixtureTime(0) },
|
|
177
|
+
}),
|
|
178
|
+
step("Checkout abandoned", { id: "checkout-abandoned", topic: "checkout.abandoned", data: abandoned, minute: 1, acknowledgment: "initial" }),
|
|
179
|
+
step("Checkout abandoned replay", { id: "checkout-abandoned", topic: "checkout.abandoned", data: abandoned, minute: 2, acknowledgment: "replay" }),
|
|
180
|
+
step("Consent subscribed", {
|
|
181
|
+
id: "consent-subscribed", topic: "customer.marketing_consent.updated", minute: 3,
|
|
182
|
+
data: { customerHash: subscribed, marketingConsent: true, updatedAt: fixtureTime(3) },
|
|
183
|
+
}),
|
|
184
|
+
step("Consent revoked", {
|
|
185
|
+
id: "consent-revoked", topic: "customer.marketing_consent.updated", minute: 4,
|
|
186
|
+
data: { customerHash: revoked, marketingConsent: false, updatedAt: fixtureTime(4) },
|
|
187
|
+
rejected: (status) => `HTTP ${status} revocation refused; answer 2xx so the platform does not retry`,
|
|
188
|
+
expect: (_ack, { log, mark }) => retriedRead(log.slice(mark), [contactPath(revoked)]),
|
|
189
|
+
}),
|
|
190
|
+
];
|
|
191
|
+
/** @type {FinalCheck[]} */
|
|
192
|
+
const finalChecks = [
|
|
193
|
+
{
|
|
194
|
+
label: "Contact pull-only",
|
|
195
|
+
detail: "no contact push observed",
|
|
196
|
+
evaluate(log) {
|
|
197
|
+
const push = log.find((request) => request.path.startsWith(`${API_PREFIX}customers`) && request.method !== "GET"
|
|
198
|
+
&& !(request.method === "POST" && request.path.endsWith("/marketing-opt-out")));
|
|
199
|
+
return push && `contact push refused: ${push.method} ${push.path}`;
|
|
200
|
+
},
|
|
201
|
+
},
|
|
202
|
+
{
|
|
203
|
+
label: "Opt-out write-back idempotent",
|
|
204
|
+
detail: "every opt-out write carries a stable Idempotency-Key",
|
|
205
|
+
evaluate(log) {
|
|
206
|
+
const writes = requestsWhere(log, (request) => request.method === "POST" && request.path.endsWith("/marketing-opt-out"));
|
|
207
|
+
/** @type {Map<string, string>} */
|
|
208
|
+
const keys = new Map();
|
|
209
|
+
for (const write of writes) {
|
|
210
|
+
if (!validKey(write.idempotencyKey, 8)) return "opt-out written without an Idempotency-Key of 8-128 characters";
|
|
211
|
+
const repeat = `${write.path}\n${write.body}`;
|
|
212
|
+
const prior = keys.get(repeat);
|
|
213
|
+
if (prior !== undefined && prior !== write.idempotencyKey) return "opt-out repeated for one customer under a new Idempotency-Key";
|
|
214
|
+
keys.set(repeat, /** @type {string} */ (write.idempotencyKey));
|
|
215
|
+
}
|
|
216
|
+
return undefined;
|
|
217
|
+
},
|
|
218
|
+
},
|
|
219
|
+
];
|
|
220
|
+
return { steps, finalChecks, route };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ---------------------------------------------------------------------------------------------
|
|
224
|
+
// accounting-gl
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* One processor settlement batch with a 2.9% + 30-cent processing fee and a 10% rolling-reserve
|
|
228
|
+
* holdback. `feeMinor` is everything withheld, so grossMinor - feeMinor = netMinor.
|
|
229
|
+
* Returns the closed seven-key settlement.recorded shape.
|
|
230
|
+
* @param {number} n @param {number} grossMinor @param {number} minute
|
|
231
|
+
*/
|
|
232
|
+
function settlementBatch(n, grossMinor, minute) {
|
|
233
|
+
const feeMinor = Math.round(grossMinor * 0.029) + 30 + reserveHeld(grossMinor);
|
|
234
|
+
return {
|
|
235
|
+
settlementId: `conformance-settlement-${n}`, currency: CURRENCY, grossMinor, feeMinor, netMinor: grossMinor - feeMinor,
|
|
236
|
+
entryCount: n, settledAt: fixtureTime(minute),
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** The 10% rolling reserve withheld from a batch. @param {number} grossMinor */
|
|
241
|
+
const reserveHeld = (grossMinor) => Math.round(grossMinor / 10);
|
|
242
|
+
|
|
243
|
+
/** @param {{ code: string, amountMinor: number }[]} lines */
|
|
244
|
+
const sum = (lines) => lines.reduce((total, line) => total + line.amountMinor, 0);
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* One sub-ledger entry, balanced to the cent:
|
|
248
|
+
* netMerchandiseMinor + shippingMinor + Σ complianceFees + Σ salesTaxLines + Σ exciseTaxLines = totalMinor.
|
|
249
|
+
* @param {{ entryId: string, entryKind: string, orderId: string, refundId?: string, disputeId?: string, net: number, shipping: number,
|
|
250
|
+
* fees: { code: string, amountMinor: number }[], salesTax: { code: string, amountMinor: number }[], excise: { code: string, amountMinor: number }[], minute: number }} spec
|
|
251
|
+
*/
|
|
252
|
+
function ledgerEntry({ entryId, entryKind, orderId, refundId, disputeId, net, shipping, fees, salesTax, excise, minute }) {
|
|
253
|
+
return {
|
|
254
|
+
entryId,
|
|
255
|
+
entryKind,
|
|
256
|
+
orderId,
|
|
257
|
+
...(refundId ? { refundId } : {}),
|
|
258
|
+
...(disputeId ? { disputeId } : {}),
|
|
259
|
+
currency: CURRENCY,
|
|
260
|
+
netMerchandiseMinor: net,
|
|
261
|
+
shippingMinor: shipping,
|
|
262
|
+
complianceFeesMinor: sum(fees),
|
|
263
|
+
salesTaxMinor: sum(salesTax),
|
|
264
|
+
exciseTaxMinor: sum(excise),
|
|
265
|
+
totalMinor: net + shipping + sum(fees) + sum(salesTax) + sum(excise),
|
|
266
|
+
complianceFees: fees,
|
|
267
|
+
salesTaxLines: salesTax,
|
|
268
|
+
exciseTaxLines: excise,
|
|
269
|
+
balancingCheckPassed: true,
|
|
270
|
+
occurredAt: fixtureTime(minute),
|
|
271
|
+
recordedAt: fixtureTime(minute),
|
|
272
|
+
postedStatus: "unposted",
|
|
273
|
+
externalAccountingRef: /** @type {string | null} */ (null),
|
|
274
|
+
targetSystem: /** @type {string | null} */ (null),
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function accountingGl() {
|
|
279
|
+
const orderId = "conformance-order-gl";
|
|
280
|
+
// state-a includes excise in the sales-tax base: 6% of (6000 + 2400 excise) = 504.
|
|
281
|
+
// state-b excludes it: 7% of 4000 = 280, with its 10% excise of 400 outside the base.
|
|
282
|
+
const fee = "age-verification-fee";
|
|
283
|
+
const entries = [
|
|
284
|
+
ledgerEntry({
|
|
285
|
+
entryId: "conformance-entry-sale", entryKind: "sale", orderId, net: 10000, shipping: 1000, minute: 0,
|
|
286
|
+
fees: [{ code: fee, amountMinor: 150 }],
|
|
287
|
+
salesTax: [{ code: "state-a", amountMinor: 504 }, { code: "state-b", amountMinor: 280 }],
|
|
288
|
+
excise: [{ code: "state-a", amountMinor: 2400 }, { code: "state-b", amountMinor: 400 }],
|
|
289
|
+
}),
|
|
290
|
+
// Partial refund of the state-b line: a contra entry, every amount negative.
|
|
291
|
+
ledgerEntry({
|
|
292
|
+
entryId: "conformance-entry-refund", entryKind: "refund", orderId, refundId: "conformance-refund-1", net: -4000, shipping: 0, minute: 1,
|
|
293
|
+
fees: [], salesTax: [{ code: "state-b", amountMinor: -280 }], excise: [{ code: "state-b", amountMinor: -400 }],
|
|
294
|
+
}),
|
|
295
|
+
// An opened dispute over the remainder: a contra entry.
|
|
296
|
+
ledgerEntry({
|
|
297
|
+
entryId: "conformance-entry-dispute", entryKind: "dispute", orderId, disputeId: "conformance-dispute-1", net: -6000, shipping: -1000, minute: 2,
|
|
298
|
+
fees: [{ code: fee, amountMinor: -150 }], salesTax: [{ code: "state-a", amountMinor: -504 }], excise: [{ code: "state-a", amountMinor: -2400 }],
|
|
299
|
+
}),
|
|
300
|
+
];
|
|
301
|
+
const [sale, refund, dispute] = entries;
|
|
302
|
+
const byId = new Map(entries.map((entry) => [entry.entryId, entry]));
|
|
303
|
+
const settlement = settlementBatch(1, sale.totalMinor, 3);
|
|
304
|
+
/** @type {Map<string, string>} */
|
|
305
|
+
const refKeys = new Map();
|
|
306
|
+
const refPath = /^\/api\/apps\/v1\/accounting\/entries\/([^/]+)\/external-ref$/;
|
|
307
|
+
|
|
308
|
+
/** @param {MockRequest} request @param {URL} url @returns {MockResponse} */
|
|
309
|
+
function route(request, url) {
|
|
310
|
+
const write = refPath.exec(request.path);
|
|
311
|
+
if (write) {
|
|
312
|
+
if (request.method !== "POST") return NO_ROUTE;
|
|
313
|
+
if (!validKey(request.idempotencyKey, 8)) return error(400, "bad_request", "Idempotency-Key is required (8-128 characters)");
|
|
314
|
+
const body = closedBody(request.body, ["externalAccountingRef", "targetSystem"]);
|
|
315
|
+
if (!body || typeof body.externalAccountingRef !== "string" || !/^[A-Za-z0-9._:-]{1,128}$/.test(body.externalAccountingRef)
|
|
316
|
+
|| !["qbo", "xero", "netsuite", "other"].includes(body.targetSystem)) {
|
|
317
|
+
return error(400, "bad_request", "Body outside the closed external-ref schema");
|
|
318
|
+
}
|
|
319
|
+
const entry = byId.get(write[1]);
|
|
320
|
+
if (!entry) return error(404, "not_found", "Unknown entry");
|
|
321
|
+
const binding = `${entry.entryId}\n${body.externalAccountingRef}\n${body.targetSystem}`;
|
|
322
|
+
const prior = refKeys.get(/** @type {string} */ (request.idempotencyKey));
|
|
323
|
+
if (prior !== undefined && prior !== binding) return error(409, "idempotency_conflict", "Idempotency-Key reused with a different entry or body");
|
|
324
|
+
if (entry.externalAccountingRef !== null
|
|
325
|
+
&& (entry.externalAccountingRef !== body.externalAccountingRef || entry.targetSystem !== body.targetSystem)) {
|
|
326
|
+
return error(409, "accounting_ref_conflict", "A different external reference is already recorded on the entry");
|
|
327
|
+
}
|
|
328
|
+
refKeys.set(/** @type {string} */ (request.idempotencyKey), binding);
|
|
329
|
+
entry.externalAccountingRef = body.externalAccountingRef;
|
|
330
|
+
entry.targetSystem = body.targetSystem;
|
|
331
|
+
entry.postedStatus = "posted";
|
|
332
|
+
return json(200, { entryId: entry.entryId, externalAccountingRef: body.externalAccountingRef, targetSystem: body.targetSystem, recordedAt: fixtureTime(20) });
|
|
333
|
+
}
|
|
334
|
+
if (request.method !== "GET") return NO_ROUTE;
|
|
335
|
+
const limit = Number(url.searchParams.get("limit") ?? 50);
|
|
336
|
+
if (request.path === `${API_PREFIX}accounting/entries`) {
|
|
337
|
+
const kind = url.searchParams.get("entryType");
|
|
338
|
+
const posted = url.searchParams.get("postedStatus");
|
|
339
|
+
const page = entries.filter((entry) => (!kind || entry.entryKind === kind || (kind === "dispute" && entry.entryKind === "dispute_reversal"))
|
|
340
|
+
&& (!posted || entry.postedStatus === posted));
|
|
341
|
+
return json(200, { entries: page, page: { limit, nextCursor: null } });
|
|
342
|
+
}
|
|
343
|
+
if (request.path === `${API_PREFIX}accounting/settlements`) {
|
|
344
|
+
return json(200, { settlements: [{ ...settlement, updatedAt: settlement.settledAt }], page: { limit, nextCursor: null } });
|
|
345
|
+
}
|
|
346
|
+
if (request.path === `${API_PREFIX}orders/${orderId}/financial-breakdown`) {
|
|
347
|
+
const total = (/** @type {"netMerchandiseMinor" | "shippingMinor" | "complianceFeesMinor" | "salesTaxMinor" | "exciseTaxMinor" | "totalMinor"} */ key) => entries.reduce((acc, entry) => acc + entry[key], 0);
|
|
348
|
+
return json(200, {
|
|
349
|
+
orderId, currency: CURRENCY, netMerchandiseMinor: total("netMerchandiseMinor"), shippingMinor: total("shippingMinor"),
|
|
350
|
+
complianceFeesMinor: total("complianceFeesMinor"), salesTaxMinor: total("salesTaxMinor"), exciseTaxMinor: total("exciseTaxMinor"),
|
|
351
|
+
totalMinor: total("totalMinor"), refundedMinor: -refund.totalMinor, balancingCheckPassed: true, entries,
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
return NO_ROUTE;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
const isRefWrite = (/** @type {MockRequest} */ request) => request.method === "POST" && refPath.test(request.path);
|
|
358
|
+
const steps = [
|
|
359
|
+
step("Signature tamper refused", {
|
|
360
|
+
id: "settlement-tampered", topic: "settlement.recorded", minute: 3, tamper: true,
|
|
361
|
+
data: { ...settlement, settlementId: "conformance-settlement-tampered" },
|
|
362
|
+
}),
|
|
363
|
+
step("Refund contra entry", {
|
|
364
|
+
id: "order-refunded", topic: "order.refunded", minute: 1,
|
|
365
|
+
data: { orderId, refundId: refund.refundId, currency: CURRENCY, amountMinor: -refund.totalMinor, occurredAt: refund.occurredAt },
|
|
366
|
+
}),
|
|
367
|
+
step("Dispute contra entry", {
|
|
368
|
+
id: "order-disputed", topic: "order.disputed", minute: 2,
|
|
369
|
+
data: { orderId, disputeId: dispute.disputeId, status: "opened", currency: CURRENCY, amountMinor: -dispute.totalMinor, occurredAt: dispute.occurredAt },
|
|
370
|
+
}),
|
|
371
|
+
step("Settlement journal", {
|
|
372
|
+
id: "settlement-recorded", topic: "settlement.recorded", data: settlement, minute: 3, acknowledgment: "initial",
|
|
373
|
+
expect(ack) {
|
|
374
|
+
const debit = ack?.journal?.debitMinor;
|
|
375
|
+
const credit = ack?.journal?.creditMinor;
|
|
376
|
+
const balanced = Number.isSafeInteger(debit) && Number.isSafeInteger(credit) && debit === credit && debit > 0;
|
|
377
|
+
return balanced ? undefined : `unbalanced journal (debitMinor ${JSON.stringify(debit) ?? "missing"}, creditMinor ${JSON.stringify(credit) ?? "missing"})`;
|
|
378
|
+
},
|
|
379
|
+
}),
|
|
380
|
+
step("Settlement replay", {
|
|
381
|
+
id: "settlement-recorded", topic: "settlement.recorded", data: settlement, minute: 4, acknowledgment: "replay",
|
|
382
|
+
expect(_ack, { log, mark }) {
|
|
383
|
+
const writes = log.slice(mark).filter(isRefWrite).length;
|
|
384
|
+
return writes > 0 ? `replay wrote ${writes} external-ref(s); a duplicate must not post again` : undefined;
|
|
385
|
+
},
|
|
386
|
+
}),
|
|
387
|
+
];
|
|
388
|
+
/** @type {FinalCheck[]} */
|
|
389
|
+
const finalChecks = [{
|
|
390
|
+
label: "External ref insert-once",
|
|
391
|
+
detail: "no entry's external ref rewritten",
|
|
392
|
+
evaluate(log) {
|
|
393
|
+
/** @type {Map<string, string>} */
|
|
394
|
+
const recorded = new Map();
|
|
395
|
+
for (const write of log.filter(isRefWrite)) {
|
|
396
|
+
if (!validKey(write.idempotencyKey, 8)) return "external-ref written without an Idempotency-Key of 8-128 characters";
|
|
397
|
+
const body = closedBody(write.body, ["externalAccountingRef", "targetSystem"]);
|
|
398
|
+
if (!body) continue;
|
|
399
|
+
const ref = `${body.externalAccountingRef}\n${body.targetSystem}`;
|
|
400
|
+
const prior = recorded.get(write.path);
|
|
401
|
+
if (prior !== undefined && prior !== ref) return `external-ref rewritten on ${refPath.exec(write.path)?.[1]}`;
|
|
402
|
+
recorded.set(write.path, ref);
|
|
403
|
+
}
|
|
404
|
+
return undefined;
|
|
405
|
+
},
|
|
406
|
+
}];
|
|
407
|
+
return { steps, finalChecks, route };
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// ---------------------------------------------------------------------------------------------
|
|
411
|
+
// affiliate-s2s
|
|
412
|
+
|
|
413
|
+
function affiliateS2s() {
|
|
414
|
+
const orderId = "conformance-order-aff";
|
|
415
|
+
const context = {
|
|
416
|
+
orderId,
|
|
417
|
+
status: "paid",
|
|
418
|
+
currency: CURRENCY,
|
|
419
|
+
customerHash: customerHash("affiliate"),
|
|
420
|
+
isFirstOrderForInstall: true,
|
|
421
|
+
commissionableSubtotalMinor: 8000,
|
|
422
|
+
excludedExciseMinor: 2400,
|
|
423
|
+
excludedSalesTaxMinor: 624,
|
|
424
|
+
excludedShippingAndFeesMinor: 1150,
|
|
425
|
+
lineItems: [
|
|
426
|
+
{ sku: "CONFORMANCE-SKU-1", quantity: 2, commissionableLineMinor: 5000 },
|
|
427
|
+
{ sku: "CONFORMANCE-SKU-2", quantity: 1, commissionableLineMinor: 3000 },
|
|
428
|
+
],
|
|
429
|
+
click: { clickId: "conformance-click-1", affiliateRef: "conformance-affiliate", sub1: "conformance-sub", sub2: null },
|
|
430
|
+
paidAt: fixtureTime(0),
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
/** @param {MockRequest} request @returns {MockResponse} */
|
|
434
|
+
function route(request) {
|
|
435
|
+
const match = /^\/api\/apps\/v1\/orders\/([^/]+)\/attribution-context$/.exec(request.path);
|
|
436
|
+
if (!match || request.method !== "GET") return NO_ROUTE;
|
|
437
|
+
return match[1] === orderId ? json(200, context) : error(404, "not_found", "Unknown order");
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
const finalized = { attributionId: "conformance-attribution-1", orderId, campaign: "conformance-campaign" };
|
|
441
|
+
const clawback = (/** @type {any} */ ack) => ack?.clawback === true ? undefined : "clawback missing (acknowledge with {\"clawback\":true})";
|
|
442
|
+
const steps = [
|
|
443
|
+
step("Signature tamper refused", {
|
|
444
|
+
id: "attribution-tampered", topic: "attribution.finalized", minute: 0, tamper: true,
|
|
445
|
+
data: { ...finalized, attributionId: "conformance-attribution-tampered" },
|
|
446
|
+
}),
|
|
447
|
+
step("Attribution commission base", {
|
|
448
|
+
id: "attribution-finalized", topic: "attribution.finalized", data: finalized, minute: 1, acknowledgment: "initial",
|
|
449
|
+
expect(ack) {
|
|
450
|
+
const base = ack?.commission?.baseMinor;
|
|
451
|
+
if (!Number.isSafeInteger(base)) return "acknowledgment carries no commission.baseMinor";
|
|
452
|
+
return base === context.commissionableSubtotalMinor
|
|
453
|
+
? undefined
|
|
454
|
+
: `excise or tax leaked into commission base (baseMinor ${base}, commissionableSubtotalMinor ${context.commissionableSubtotalMinor})`;
|
|
455
|
+
},
|
|
456
|
+
}),
|
|
457
|
+
step("Attribution replay", { id: "attribution-finalized", topic: "attribution.finalized", data: finalized, minute: 2, acknowledgment: "replay" }),
|
|
458
|
+
step("Refund clawback", {
|
|
459
|
+
id: "affiliate-refunded", topic: "order.refunded", minute: 3, expect: clawback,
|
|
460
|
+
data: { orderId, refundId: "conformance-refund-aff", currency: CURRENCY, amountMinor: 4000, occurredAt: fixtureTime(3) },
|
|
461
|
+
}),
|
|
462
|
+
step("Dispute clawback", {
|
|
463
|
+
id: "affiliate-disputed", topic: "order.disputed", minute: 4, expect: clawback,
|
|
464
|
+
data: { orderId, disputeId: "conformance-dispute-aff", status: "opened", currency: CURRENCY, amountMinor: 8174, occurredAt: fixtureTime(4) },
|
|
465
|
+
}),
|
|
466
|
+
];
|
|
467
|
+
return { steps, finalChecks: [], route };
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// ---------------------------------------------------------------------------------------------
|
|
471
|
+
// bi-export
|
|
472
|
+
|
|
473
|
+
/** @param {string} tag alphanumeric, at most 24 characters */
|
|
474
|
+
const exportId = (tag) => `exp_${tag.padEnd(24, "0")}`;
|
|
475
|
+
|
|
476
|
+
/** @param {Record<string, unknown>[]} rows */
|
|
477
|
+
const ndjson = (rows) => rows.map((row) => `${JSON.stringify(row)}\n`).join("");
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* @param {{ id: string, dataset: string, bytes: string, rowCount: number, advertisedDigest?: string, watermark: string, scopeDenied?: boolean }} spec
|
|
481
|
+
*/
|
|
482
|
+
function exportFixture({ id, dataset, bytes, rowCount, advertisedDigest, watermark, scopeDenied = false }) {
|
|
483
|
+
const byteSize = Buffer.byteLength(bytes);
|
|
484
|
+
const sha256Digest = advertisedDigest ?? sha256Hex(bytes);
|
|
485
|
+
return {
|
|
486
|
+
id, bytes, scopeDenied,
|
|
487
|
+
event: {
|
|
488
|
+
exportId: id, dataset, format: "ndjson", schemaVersion: "1", rowCount, byteSize, sha256Digest,
|
|
489
|
+
watermarkMaxUpdatedAt: watermark, partCount: 1, expiresAt: EXPORT_EXPIRES_AT, completedAt: fixtureTime(10),
|
|
490
|
+
},
|
|
491
|
+
job: {
|
|
492
|
+
exportId: id, dataset, format: "ndjson", compression: "none", status: "completed", schemaVersion: "1",
|
|
493
|
+
from: null, to: null, updatedSince: null, createdAt: fixtureTime(7), startedAt: fixtureTime(8), completedAt: fixtureTime(10),
|
|
494
|
+
expiresAt: EXPORT_EXPIRES_AT, rowCount, byteSize, sha256Digest, watermarkMaxUpdatedAt: watermark, errorCode: null,
|
|
495
|
+
parts: [{ part: 0, byteSize, sha256Digest }],
|
|
496
|
+
},
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
const EXPORT_DATASETS = ["orders_financial", "order_lines", "refunds", "settlements", "catalog_products", "inventory_movements",
|
|
501
|
+
"stocktakes", "purchase_orders", "attributions", "compliance_audit_events"];
|
|
502
|
+
|
|
503
|
+
function biExport() {
|
|
504
|
+
// A settlements export row: the settlement.recorded shape plus the rolling reserve withheld and updatedAt.
|
|
505
|
+
const settlementRow = (/** @type {number} */ n, /** @type {number} */ gross, /** @type {number} */ minute) => {
|
|
506
|
+
const { entryCount, settledAt, ...batch } = settlementBatch(n, gross, minute - 1);
|
|
507
|
+
return { ...batch, reserveHeldMinor: reserveHeld(gross), entryCount, settledAt, updatedAt: fixtureTime(minute) };
|
|
508
|
+
};
|
|
509
|
+
const verified = exportFixture({
|
|
510
|
+
id: exportId("conformanceVerified"), dataset: "settlements", rowCount: 2, watermark: fixtureTime(6),
|
|
511
|
+
bytes: ndjson([settlementRow(1, 14734, 4), settlementRow(2, 20000, 6)]),
|
|
512
|
+
});
|
|
513
|
+
const mismatchBytes = ndjson([settlementRow(3, 9900, 9)]);
|
|
514
|
+
const mismatch = exportFixture({
|
|
515
|
+
id: exportId("conformanceMismatch"), dataset: "settlements", rowCount: 1, watermark: fixtureTime(9),
|
|
516
|
+
bytes: mismatchBytes, advertisedDigest: sha256Hex(`${mismatchBytes}stale`),
|
|
517
|
+
});
|
|
518
|
+
const scopeDenied = exportFixture({
|
|
519
|
+
id: exportId("conformanceScopeDenied"), dataset: "compliance_audit_events", rowCount: 1, watermark: fixtureTime(9),
|
|
520
|
+
bytes: ndjson([{ conformance: true }]), scopeDenied: true,
|
|
521
|
+
});
|
|
522
|
+
const tampered = exportFixture({
|
|
523
|
+
id: exportId("conformanceTampered"), dataset: "settlements", rowCount: 1, watermark: fixtureTime(9), bytes: mismatchBytes,
|
|
524
|
+
});
|
|
525
|
+
const jobs = new Map([verified, mismatch, scopeDenied].map((fixture) => [fixture.id, fixture]));
|
|
526
|
+
/** @type {Map<string, { binding: string, accepted: Record<string, unknown> }>} */
|
|
527
|
+
const created = new Map();
|
|
528
|
+
|
|
529
|
+
/** @param {MockRequest} request @param {URL} url @returns {MockResponse} */
|
|
530
|
+
function route(request, url) {
|
|
531
|
+
const part = /^\/_conformance\/exports\/([^/]+)\/0$/.exec(request.path);
|
|
532
|
+
if (part) {
|
|
533
|
+
const fixture = jobs.get(part[1]);
|
|
534
|
+
if (request.method !== "GET" || !fixture || fixture.scopeDenied) return NO_ROUTE;
|
|
535
|
+
return { status: 200, headers: { "content-type": "application/x-ndjson", "cache-control": "no-store" }, body: fixture.bytes };
|
|
536
|
+
}
|
|
537
|
+
if (request.path === `${API_PREFIX}exports`) {
|
|
538
|
+
if (request.method === "GET") return json(200, { exports: [...jobs.values()].map((fixture) => fixture.job) });
|
|
539
|
+
if (request.method !== "POST") return NO_ROUTE;
|
|
540
|
+
if (!validKey(request.idempotencyKey, 1)) return refusal(400, "bad_request", "Idempotency-Key is required (1-128 characters)");
|
|
541
|
+
const body = closedBody(request.body, ["dataset", "format"], ["compression", "from", "to", "updatedSince"]);
|
|
542
|
+
if (!body || !EXPORT_DATASETS.includes(body.dataset) || !["ndjson", "csv"].includes(body.format)) {
|
|
543
|
+
return refusal(400, "bad_request", "Body outside the closed export schema");
|
|
544
|
+
}
|
|
545
|
+
if (body.dataset === "compliance_audit_events") return refusal(403, "scope_denied", "The install does not hold the dataset's scope");
|
|
546
|
+
const key = /** @type {string} */ (request.idempotencyKey);
|
|
547
|
+
const prior = created.get(key);
|
|
548
|
+
if (prior) return prior.binding === request.body ? json(202, prior.accepted) : refusal(409, "idempotency_conflict", "Idempotency-Key reused with a different body");
|
|
549
|
+
const accepted = {
|
|
550
|
+
exportId: exportId(`conformanceCreated${created.size + 1}`), dataset: body.dataset, format: body.format,
|
|
551
|
+
status: "queued", schemaVersion: "1", createdAt: fixtureTime(7),
|
|
552
|
+
};
|
|
553
|
+
created.set(key, { binding: request.body, accepted });
|
|
554
|
+
return json(202, accepted);
|
|
555
|
+
}
|
|
556
|
+
const match = /^\/api\/apps\/v1\/exports\/([^/]+)(\/download)?$/.exec(request.path);
|
|
557
|
+
if (!match || request.method !== "GET") return NO_ROUTE;
|
|
558
|
+
const fixture = jobs.get(match[1]);
|
|
559
|
+
if (!fixture) return refusal(404, "not_found", "Unknown export");
|
|
560
|
+
if (!match[2]) return fixture.scopeDenied ? error(403, "scope_denied", "The install no longer holds the dataset's scope") : json(200, fixture.job);
|
|
561
|
+
if (fixture.scopeDenied) return refusal(403, "scope_denied", "The install no longer holds the dataset's scope");
|
|
562
|
+
if ((url.searchParams.get("part") ?? "0") !== "0") return refusal(400, "bad_request", "Unknown part");
|
|
563
|
+
return json(200, { url: `${MOCK_ORIGIN}${DOWNLOAD_PREFIX}${fixture.id}/0`, expiresAt: fixtureTime(25), sha256Digest: fixture.job.sha256Digest });
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
const statusPath = `${API_PREFIX}exports/${scopeDenied.id}`;
|
|
567
|
+
const steps = [
|
|
568
|
+
step("Signature tamper refused", { id: "export-tampered", topic: "export.completed", data: tampered.event, minute: 10, tamper: true }),
|
|
569
|
+
step("Export verified", {
|
|
570
|
+
id: "export-verified", topic: "export.completed", data: verified.event, minute: 11, acknowledgment: "initial",
|
|
571
|
+
expect(ack) {
|
|
572
|
+
if (ack?.verified !== true) return "export not verified (acknowledge {\"verified\":true} after the bytes match sha256Digest)";
|
|
573
|
+
return ack?.watermark === verified.event.watermarkMaxUpdatedAt
|
|
574
|
+
? undefined
|
|
575
|
+
: `watermark not echoed (expected ${verified.event.watermarkMaxUpdatedAt})`;
|
|
576
|
+
},
|
|
577
|
+
}),
|
|
578
|
+
step("Export replay", { id: "export-verified", topic: "export.completed", data: verified.event, minute: 12, acknowledgment: "replay" }),
|
|
579
|
+
step("Digest mismatch refused", {
|
|
580
|
+
id: "export-mismatch", topic: "export.completed", data: mismatch.event, minute: 13, refusal: "digest mismatch refused",
|
|
581
|
+
expect(ack) {
|
|
582
|
+
if (ack?.verified === true) return "digest mismatch accepted";
|
|
583
|
+
return ack?.verified === false ? undefined : "acknowledgment carries no verified:false for a digest mismatch";
|
|
584
|
+
},
|
|
585
|
+
}),
|
|
586
|
+
step("Scope-denied export handled", {
|
|
587
|
+
id: "export-scope-denied", topic: "export.completed", data: scopeDenied.event, minute: 14,
|
|
588
|
+
rejected: (status) => `HTTP ${status} scope_denied refusal not handled; answer 2xx with {"verified":false} so the platform does not retry`,
|
|
589
|
+
expect(ack, { log, mark }) {
|
|
590
|
+
if (ack?.verified !== false) return "scope-denied export loaded (acknowledge {\"verified\":false})";
|
|
591
|
+
return retriedRead(log.slice(mark), [statusPath, `${statusPath}/download`]);
|
|
592
|
+
},
|
|
593
|
+
}),
|
|
594
|
+
];
|
|
595
|
+
return { steps, finalChecks: [], route };
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
const BUILDERS = { "marketing-esp": marketingEsp, "accounting-gl": accountingGl, "affiliate-s2s": affiliateS2s, "bi-export": biExport };
|
|
599
|
+
|
|
600
|
+
/** @param {string} archetype @returns {ArchetypePlan | undefined} */
|
|
601
|
+
export function createArchetypePlan(archetype) {
|
|
602
|
+
const build = BUILDERS[/** @type {keyof typeof BUILDERS} */ (archetype)];
|
|
603
|
+
if (!build) return undefined;
|
|
604
|
+
const { steps, finalChecks, route } = build();
|
|
605
|
+
/** @type {MockRequest[]} */
|
|
606
|
+
const log = [];
|
|
607
|
+
return {
|
|
608
|
+
steps,
|
|
609
|
+
finalChecks,
|
|
610
|
+
log,
|
|
611
|
+
owns: (url) => url.startsWith(API_PREFIX) || url.startsWith(DOWNLOAD_PREFIX),
|
|
612
|
+
serve({ method, url, headers, body }) {
|
|
613
|
+
const parsed = new URL(url, MOCK_ORIGIN);
|
|
614
|
+
const key = headers["idempotency-key"];
|
|
615
|
+
/** @type {MockRequest} */
|
|
616
|
+
const request = { method, path: parsed.pathname, idempotencyKey: typeof key === "string" ? key : null, body };
|
|
617
|
+
log.push(request);
|
|
618
|
+
return route(request, parsed);
|
|
619
|
+
},
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* Serve one mock platform API request on the conformance listener.
|
|
625
|
+
* @param {ArchetypePlan} plan
|
|
626
|
+
* @param {import("node:http").IncomingMessage} req
|
|
627
|
+
* @param {import("node:http").ServerResponse} res
|
|
628
|
+
*/
|
|
629
|
+
export async function serveMockRequest(plan, req, res) {
|
|
630
|
+
const chunks = [];
|
|
631
|
+
let total = 0;
|
|
632
|
+
try {
|
|
633
|
+
for await (const chunk of req) {
|
|
634
|
+
total += chunk.length;
|
|
635
|
+
if (total > MAX_MOCK_BODY_BYTES) {
|
|
636
|
+
res.writeHead(413).end();
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
chunks.push(chunk);
|
|
640
|
+
}
|
|
641
|
+
} catch {
|
|
642
|
+
res.writeHead(400).end();
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
const response = plan.serve({
|
|
646
|
+
method: req.method ?? "GET",
|
|
647
|
+
url: req.url ?? "/",
|
|
648
|
+
headers: req.headers ?? {},
|
|
649
|
+
body: Buffer.concat(chunks).toString("utf8"),
|
|
650
|
+
});
|
|
651
|
+
res.writeHead(response.status, response.headers);
|
|
652
|
+
res.end(response.body);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/**
|
|
656
|
+
* Judge one delivery's response against its step.
|
|
657
|
+
* @param {Step} step
|
|
658
|
+
* @param {{ status: number, ack: any, initialAccepted: boolean, log: MockRequest[], mark: number }} outcome
|
|
659
|
+
* @returns {{ finding: string, initial: boolean } | { detail: string, initial: boolean }}
|
|
660
|
+
*/
|
|
661
|
+
export function judgeDelivery(step, { status, ack, initialAccepted, log, mark }) {
|
|
662
|
+
const success = status >= 200 && status < 300;
|
|
663
|
+
if (step.tamper) {
|
|
664
|
+
if (success) return { finding: `HTTP ${status} unsigned delivery accepted`, initial: false };
|
|
665
|
+
if (status >= 300 && status < 400) return { finding: `HTTP ${status} redirect refused`, initial: false };
|
|
666
|
+
if (status >= 400 && status < 500) return { detail: "tampered signature refused", initial: false };
|
|
667
|
+
return { finding: `HTTP ${status} tampered delivery not refused with 4xx`, initial: false };
|
|
668
|
+
}
|
|
669
|
+
if (status >= 300 && status < 400) return { finding: `HTTP ${status} redirect refused`, initial: false };
|
|
670
|
+
if (!success) {
|
|
671
|
+
if (step.refusal && status >= 400 && status < 500) return { detail: step.refusal, initial: false };
|
|
672
|
+
return { finding: step.rejected ? step.rejected(status) : `HTTP ${status} delivery rejected`, initial: false };
|
|
673
|
+
}
|
|
674
|
+
const duplicate = ack?.accepted === true && ack?.duplicate === true;
|
|
675
|
+
const replay = step.acknowledgment === "replay";
|
|
676
|
+
if (step.acknowledgment === "initial" && duplicate) return { finding: `HTTP ${status} initial delivery already known. Use clean local state.`, initial: false };
|
|
677
|
+
if (replay && !duplicate) return { finding: `HTTP ${status} delivery acknowledged without duplicate confirmation`, initial: false };
|
|
678
|
+
if (replay && !initialAccepted) return { finding: `HTTP ${status} duplicate reported without a successful initial delivery`, initial: false };
|
|
679
|
+
const initial = step.acknowledgment === "initial";
|
|
680
|
+
const finding = step.expect?.(ack, { log, mark });
|
|
681
|
+
if (finding) return { finding: `HTTP ${status} ${finding}`, initial };
|
|
682
|
+
return { detail: replay ? "duplicate acknowledged" : "delivery acknowledged", initial };
|
|
683
|
+
}
|
|
@@ -18,12 +18,13 @@ import {
|
|
|
18
18
|
computeContentDigestSha256,
|
|
19
19
|
} from "../../vendor/private-apps-devkit.mjs";
|
|
20
20
|
import { createSign } from "node:crypto";
|
|
21
|
+
import { BUCKET3_ARCHETYPES, MOCK_ORIGIN, createArchetypePlan, judgeDelivery, serveMockRequest } from "./conformance-archetypes.mjs";
|
|
21
22
|
|
|
22
23
|
const METADATA_HOST = "127.0.0.1";
|
|
23
24
|
const METADATA_PORT = 37891;
|
|
24
25
|
const METADATA_PATH = "/.well-known/tot-app-authorization-metadata";
|
|
25
26
|
const METADATA_URL = `http://${METADATA_HOST}:${METADATA_PORT}${METADATA_PATH}`;
|
|
26
|
-
const ARCHETYPES = ["label-station", "dropship", "inventory-sync"];
|
|
27
|
+
const ARCHETYPES = ["label-station", "dropship", "inventory-sync", ...BUCKET3_ARCHETYPES];
|
|
27
28
|
const REQUEST_TIMEOUT_MS = 5000;
|
|
28
29
|
const STAFF_SESSION_TIMEOUT_MS = 30_000;
|
|
29
30
|
const MAX_ACK_BYTES = 4096;
|
|
@@ -52,6 +53,33 @@ For replay, return a 2xx JSON response with {"accepted":true,"duplicate":true}
|
|
|
52
53
|
when the same CloudEvent ID is received again. Check connector state separately
|
|
53
54
|
to confirm idempotent side effects and handling of stale inventory.
|
|
54
55
|
|
|
56
|
+
marketing-esp, accounting-gl, affiliate-s2s and bi-export also serve a mock
|
|
57
|
+
platform API on the same listener: set the connector's platform API base to
|
|
58
|
+
${MOCK_ORIGIN} (routes under /api/apps/v1/, any bearer accepted). Each checklist
|
|
59
|
+
opens with a delivery whose signature bytes are wrong; answer it with 4xx. Make
|
|
60
|
+
platform API calls before answering a delivery: each check judges the requests
|
|
61
|
+
seen by the time its answer returns. A refused (403) read must not be retried
|
|
62
|
+
within one delivery. Acknowledgment bodies are 2xx JSON:
|
|
63
|
+
|
|
64
|
+
marketing-esp Any 2xx. customer.marketing_consent.updated with
|
|
65
|
+
marketingConsent:false still answers 2xx even though its
|
|
66
|
+
marketing-contact read answers 403 customer_not_opted_in.
|
|
67
|
+
Contacts are pull-only: the only write under /customers/ is
|
|
68
|
+
POST .../marketing-opt-out, carrying an Idempotency-Key of
|
|
69
|
+
8-128 characters that a repeat of the same opt-out reuses.
|
|
70
|
+
accounting-gl settlement.recorded answers
|
|
71
|
+
{"journal":{"debitMinor":<int>,"creditMinor":<int>}}, equal and
|
|
72
|
+
above zero. A replay posts no external-ref, and an entry's
|
|
73
|
+
external ref is never rewritten.
|
|
74
|
+
affiliate-s2s attribution.finalized answers
|
|
75
|
+
{"commission":{"baseMinor":<commissionableSubtotalMinor>}};
|
|
76
|
+
order.refunded and order.disputed answer {"clawback":true}.
|
|
77
|
+
bi-export export.completed answers
|
|
78
|
+
{"verified":true,"watermark":"<watermarkMaxUpdatedAt>"} once the
|
|
79
|
+
downloaded bytes match sha256Digest, {"verified":false} (or a
|
|
80
|
+
4xx) when they do not, and a 2xx {"verified":false} when the
|
|
81
|
+
export answers 403 scope_denied.
|
|
82
|
+
|
|
55
83
|
Conformance certification:
|
|
56
84
|
tot app conformance --url <webhookUrl> --archetype <name> --certify --app-id <id>
|
|
57
85
|
[--receipt <path>] [--actor <id>] [--api-base ${DEFAULT_STOREFRONT_ORIGIN}]
|
|
@@ -149,31 +177,36 @@ function close(server) {
|
|
|
149
177
|
});
|
|
150
178
|
}
|
|
151
179
|
|
|
152
|
-
/** @param {import("node:http").IncomingMessage} response */
|
|
153
|
-
async function
|
|
180
|
+
/** @param {import("node:http").IncomingMessage} response @returns {Promise<any>} */
|
|
181
|
+
async function readAcknowledgment(response) {
|
|
154
182
|
const chunks = [];
|
|
155
183
|
let total = 0;
|
|
156
184
|
for await (const chunk of response) {
|
|
157
185
|
total += chunk.length;
|
|
158
|
-
if (total > MAX_ACK_BYTES) return
|
|
186
|
+
if (total > MAX_ACK_BYTES) return undefined;
|
|
159
187
|
chunks.push(chunk);
|
|
160
188
|
}
|
|
161
189
|
try {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
190
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
191
|
+
} catch (error) {
|
|
192
|
+
if (error instanceof SyntaxError) return undefined;
|
|
193
|
+
throw error;
|
|
166
194
|
}
|
|
167
195
|
}
|
|
168
196
|
|
|
197
|
+
/** @param {any} ack */
|
|
198
|
+
const isDuplicate = (ack) => ack?.accepted === true && ack?.duplicate === true;
|
|
199
|
+
|
|
169
200
|
/** @param {URL} target @param {import("node:https").RequestOptions} options @param {(response: import("node:http").IncomingMessage) => void} callback */
|
|
170
201
|
function directRequest(target, options, callback) {
|
|
171
202
|
const request = target.protocol === "https:" ? requestHttps : requestHttp;
|
|
172
203
|
return request(target, options, callback);
|
|
173
204
|
}
|
|
174
205
|
|
|
175
|
-
/** @param {URL} target @param {string} body @param {Record<string, string>} headers @param {boolean}
|
|
176
|
-
|
|
206
|
+
/** @param {URL} target @param {string} body @param {Record<string, string>} headers @param {boolean} readAck @param {typeof directRequest} request
|
|
207
|
+
* @returns {Promise<{ status: number, ack: any }>}
|
|
208
|
+
*/
|
|
209
|
+
function post(target, body, headers, readAck, request) {
|
|
177
210
|
const localhost = target.hostname === "localhost";
|
|
178
211
|
return new Promise((resolve, reject) => {
|
|
179
212
|
const req = request(target, {
|
|
@@ -186,11 +219,11 @@ function post(target, body, headers, checkDuplicate, request) {
|
|
|
186
219
|
headers: { ...headers, host: target.host, "content-length": String(Buffer.byteLength(body)) },
|
|
187
220
|
}, (response) => {
|
|
188
221
|
const status = response.statusCode ?? 0;
|
|
189
|
-
if (
|
|
190
|
-
void
|
|
222
|
+
if (readAck && status >= 200 && status < 300) {
|
|
223
|
+
void readAcknowledgment(response).then((ack) => resolve({ status, ack }), reject);
|
|
191
224
|
} else {
|
|
192
225
|
response.destroy();
|
|
193
|
-
resolve({ status,
|
|
226
|
+
resolve({ status, ack: undefined });
|
|
194
227
|
}
|
|
195
228
|
});
|
|
196
229
|
req.once("error", reject);
|
|
@@ -325,14 +358,35 @@ export async function runAppConformance(argv, {
|
|
|
325
358
|
const kid = `conformance-${randomUUID()}`;
|
|
326
359
|
const jwk = { ...publicKey.export({ format: "jwk" }), kid, alg: "RS256", use: "sig" };
|
|
327
360
|
const metadata = JSON.stringify({ webhook_signing_keys: { keys: [jwk] } });
|
|
361
|
+
const plan = archetype === undefined ? undefined : createArchetypePlan(archetype);
|
|
328
362
|
const server = makeServer((req, res) => {
|
|
329
363
|
if (req.method === "GET" && req.url === METADATA_PATH) {
|
|
330
364
|
res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store, max-age=0" });
|
|
331
365
|
res.end(metadata);
|
|
366
|
+
} else if (plan && plan.owns(req.url ?? "")) {
|
|
367
|
+
void serveMockRequest(plan, req, res);
|
|
332
368
|
} else {
|
|
333
369
|
res.writeHead(404).end();
|
|
334
370
|
}
|
|
335
371
|
});
|
|
372
|
+
|
|
373
|
+
/** @param {string} body @param {boolean} [tamper] */
|
|
374
|
+
async function signedHeaders(body, tamper = false) {
|
|
375
|
+
const digest = await computeContentDigestSha256(body);
|
|
376
|
+
const params = buildSignatureParamsValue(WEBHOOK_SIGNATURE_COVERED_COMPONENTS, {
|
|
377
|
+
created: Math.floor(now() / 1000), keyid: kid, alg: WEBHOOK_SIGNING_HTTPSIG_ALG,
|
|
378
|
+
});
|
|
379
|
+
const base = buildSignatureBase([["@method", "POST"], ["@target-uri", /** @type {URL} */ (target).href], ["content-digest", digest]], params);
|
|
380
|
+
const signature = createSign("RSA-SHA256").update(base).sign(privateKey);
|
|
381
|
+
// Well-formed header, wrong bytes: the receiver must refuse it on verification.
|
|
382
|
+
if (tamper) signature[signature.length - 1] ^= 0x01;
|
|
383
|
+
return {
|
|
384
|
+
"content-type": "application/cloudevents+json",
|
|
385
|
+
"content-digest": digest,
|
|
386
|
+
"signature-input": `${SIGNATURE_LABEL}=${params}`,
|
|
387
|
+
signature: `${SIGNATURE_LABEL}=:${signature.toString("base64")}:`,
|
|
388
|
+
};
|
|
389
|
+
}
|
|
336
390
|
try {
|
|
337
391
|
await listen(server);
|
|
338
392
|
} catch {
|
|
@@ -345,23 +399,43 @@ export async function runAppConformance(argv, {
|
|
|
345
399
|
const checks = [];
|
|
346
400
|
let passed = true;
|
|
347
401
|
let initialAccepted = false;
|
|
348
|
-
|
|
402
|
+
const mockLog = plan?.log ?? [];
|
|
403
|
+
for (const step of plan?.steps ?? []) {
|
|
404
|
+
const { label, body } = step;
|
|
405
|
+
const mark = mockLog.length;
|
|
406
|
+
let finding;
|
|
407
|
+
try {
|
|
408
|
+
const { status, ack } = await post(target, body, await signedHeaders(body, step.tamper), true, request);
|
|
409
|
+
const verdict = judgeDelivery(step, { status, ack, initialAccepted, log: mockLog, mark });
|
|
410
|
+
if (verdict.initial) initialAccepted = true;
|
|
411
|
+
if ("detail" in verdict) {
|
|
412
|
+
checks.push({ label, passed: true, status });
|
|
413
|
+
if (!certify) log(`PASS ${label} — HTTP ${status} ${verdict.detail}`);
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
finding = verdict.finding;
|
|
417
|
+
} catch {
|
|
418
|
+
finding = "request failed or timed out";
|
|
419
|
+
}
|
|
420
|
+
(certify ? error : log)(`FAIL ${label} — ${finding}`);
|
|
421
|
+
passed = false;
|
|
422
|
+
}
|
|
423
|
+
for (const { label, detail, evaluate } of plan?.finalChecks ?? []) {
|
|
424
|
+
const finding = evaluate(mockLog);
|
|
425
|
+
if (finding) {
|
|
426
|
+
(certify ? error : log)(`FAIL ${label} — ${finding}`);
|
|
427
|
+
passed = false;
|
|
428
|
+
} else {
|
|
429
|
+
checks.push({ label, passed: true });
|
|
430
|
+
if (!certify) log(`PASS ${label} — ${detail}`);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
for (const { label, acknowledgment, body } of plan ? [] : fixtures(archetype)) {
|
|
349
434
|
const replay = acknowledgment === "replay";
|
|
350
|
-
const digest = await computeContentDigestSha256(body);
|
|
351
|
-
const params = buildSignatureParamsValue(WEBHOOK_SIGNATURE_COVERED_COMPONENTS, {
|
|
352
|
-
created: Math.floor(now() / 1000), keyid: kid, alg: WEBHOOK_SIGNING_HTTPSIG_ALG,
|
|
353
|
-
});
|
|
354
|
-
const base = buildSignatureBase([["@method", "POST"], ["@target-uri", target.href], ["content-digest", digest]], params);
|
|
355
|
-
const sig = createSign("RSA-SHA256").update(base).sign(privateKey).toString("base64");
|
|
356
|
-
const headers = {
|
|
357
|
-
"content-type": "application/cloudevents+json",
|
|
358
|
-
"content-digest": digest,
|
|
359
|
-
"signature-input": `${SIGNATURE_LABEL}=${params}`,
|
|
360
|
-
signature: `${SIGNATURE_LABEL}=:${sig}:`,
|
|
361
|
-
};
|
|
362
435
|
let finding;
|
|
363
436
|
try {
|
|
364
|
-
const { status,
|
|
437
|
+
const { status, ack } = await post(target, body, await signedHeaders(body), Boolean(acknowledgment), request);
|
|
438
|
+
const duplicate = isDuplicate(ack);
|
|
365
439
|
if (status >= 300 && status < 400) finding = `HTTP ${status} redirect refused`;
|
|
366
440
|
else if (status < 200 || status >= 300) finding = `HTTP ${status} delivery rejected`;
|
|
367
441
|
else if (acknowledgment === "initial" && duplicate) finding = `HTTP ${status} initial delivery already known. Use clean local state.`;
|