badday 0.1.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/LICENSE +21 -0
- package/README.md +270 -0
- package/dist/cli.js +4633 -0
- package/package.json +51 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,4633 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli/main.ts
|
|
4
|
+
import { readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "node:fs";
|
|
5
|
+
import { resolve as resolve5 } from "node:path";
|
|
6
|
+
import { createInterface as createInterface3 } from "node:readline/promises";
|
|
7
|
+
|
|
8
|
+
// fixtures/shop/server.ts
|
|
9
|
+
import http from "node:http";
|
|
10
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
11
|
+
|
|
12
|
+
// fixtures/shop/openapi.ts
|
|
13
|
+
var order = {
|
|
14
|
+
type: "object",
|
|
15
|
+
properties: {
|
|
16
|
+
id: { type: "string" },
|
|
17
|
+
userId: { type: "string" },
|
|
18
|
+
item: { type: "string" },
|
|
19
|
+
qty: { type: "integer" },
|
|
20
|
+
total: { type: "integer" },
|
|
21
|
+
status: { type: "string", enum: ["pending", "paid"] },
|
|
22
|
+
note: { type: "string" },
|
|
23
|
+
createdAt: { type: "string", format: "date-time" }
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
var orderInput = {
|
|
27
|
+
type: "object",
|
|
28
|
+
required: ["item", "qty"],
|
|
29
|
+
properties: { item: { type: "string", example: "pizza" }, qty: { type: "integer", minimum: 1, maximum: 100 }, note: { type: "string" } }
|
|
30
|
+
};
|
|
31
|
+
var id = { name: "id", in: "path", required: true, schema: { type: "string" } };
|
|
32
|
+
var json = (schema) => ({ content: { "application/json": { schema } } });
|
|
33
|
+
var openapi = {
|
|
34
|
+
openapi: "3.0.3",
|
|
35
|
+
info: { title: "badday demo shop", version: "1.0.0" },
|
|
36
|
+
security: [{ bearer: [] }],
|
|
37
|
+
components: { securitySchemes: { bearer: { type: "http", scheme: "bearer" } }, schemas: { Order: order, OrderInput: orderInput } },
|
|
38
|
+
paths: {
|
|
39
|
+
"/orders": {
|
|
40
|
+
get: {
|
|
41
|
+
parameters: [{ name: "limit", in: "query", schema: { type: "integer" } }, { name: "cursor", in: "query", schema: { type: "string" } }],
|
|
42
|
+
responses: { 200: json({ type: "object", properties: { data: { type: "array", items: { $ref: "#/components/schemas/Order" } }, nextCursor: { type: "string", nullable: true } } }) }
|
|
43
|
+
},
|
|
44
|
+
post: {
|
|
45
|
+
parameters: [{ name: "Idempotency-Key", in: "header", schema: { type: "string" } }],
|
|
46
|
+
requestBody: json({ $ref: "#/components/schemas/OrderInput" }),
|
|
47
|
+
responses: { 201: json({ $ref: "#/components/schemas/Order" }) }
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
"/orders/{id}": {
|
|
51
|
+
parameters: [id],
|
|
52
|
+
get: { responses: { 200: json({ $ref: "#/components/schemas/Order" }) } },
|
|
53
|
+
patch: { requestBody: json({ type: "object", properties: { qty: { type: "integer", example: 2 } } }), responses: { 200: json({ $ref: "#/components/schemas/Order" }) } },
|
|
54
|
+
delete: { responses: { 204: { description: "deleted" } } }
|
|
55
|
+
},
|
|
56
|
+
"/payments": { get: { responses: { 200: json({ type: "object" }) } } },
|
|
57
|
+
"/webhooks/payment": { post: { security: [], responses: { 200: json({ type: "object" }) } } }
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// fixtures/shop/server.ts
|
|
62
|
+
var DEFECTS = [
|
|
63
|
+
"idempotency-race",
|
|
64
|
+
// looks the key up, does the slow insert, and only then stores the key
|
|
65
|
+
"idempotency-ttl",
|
|
66
|
+
// forgets a key after half a second
|
|
67
|
+
"idempotency-no-fingerprint",
|
|
68
|
+
// a used key with a new body returns the old response
|
|
69
|
+
"idempotency-global-keys",
|
|
70
|
+
// one key store for every user and every route
|
|
71
|
+
"abandoned-forgets-key",
|
|
72
|
+
// the client hangs up, the insert lands, the key is never stored
|
|
73
|
+
"no-keyless-dedupe",
|
|
74
|
+
// two identical orders with no key, moments apart, are two orders
|
|
75
|
+
"no-auth-on-read",
|
|
76
|
+
// a GET with no credentials runs as a guest
|
|
77
|
+
"any-token",
|
|
78
|
+
// an unknown token runs as a guest
|
|
79
|
+
"no-owner-check-read",
|
|
80
|
+
"no-owner-check-update",
|
|
81
|
+
"no-owner-check-delete",
|
|
82
|
+
"no-owner-check-list",
|
|
83
|
+
"mass-assignment",
|
|
84
|
+
// the request body can set userId, total and status
|
|
85
|
+
"cursor-crash",
|
|
86
|
+
// a bad cursor throws
|
|
87
|
+
"cursor-trusts-user",
|
|
88
|
+
// the cursor names the user, and the list believes it
|
|
89
|
+
"no-limit-cap",
|
|
90
|
+
"limit-crash",
|
|
91
|
+
// limit=-1 or limit=abc throws
|
|
92
|
+
"offset-pagination",
|
|
93
|
+
// newest first, by offset, so new rows shift every page
|
|
94
|
+
"no-body-limit",
|
|
95
|
+
"json-crash",
|
|
96
|
+
// broken JSON throws
|
|
97
|
+
"stack-traces",
|
|
98
|
+
// a 500 carries the stack
|
|
99
|
+
"webhook-no-dedupe",
|
|
100
|
+
"webhook-dedupe-race",
|
|
101
|
+
"webhook-no-verify",
|
|
102
|
+
// a wrong signature is accepted
|
|
103
|
+
"webhook-missing-signature-ok",
|
|
104
|
+
"webhook-no-tolerance",
|
|
105
|
+
// an old timestamp is accepted
|
|
106
|
+
"webhook-unknown-crash"
|
|
107
|
+
// an unknown event type throws
|
|
108
|
+
];
|
|
109
|
+
var WEBHOOK_SECRET = "whsec_test";
|
|
110
|
+
var TOKENS = { "alice-token": "usr_alice", "bob-token": "usr_bob" };
|
|
111
|
+
var UNIT_PRICE = 1200;
|
|
112
|
+
var BODY_LIMIT = 1e5;
|
|
113
|
+
var PAGE_DEFAULT = 20;
|
|
114
|
+
var PAGE_MAX = 100;
|
|
115
|
+
var DB_MS = 5;
|
|
116
|
+
var SLOW_MS = 300;
|
|
117
|
+
var TOLERANCE_S = 300;
|
|
118
|
+
var DEDUPE_MS = 2e3;
|
|
119
|
+
var HttpError = class extends Error {
|
|
120
|
+
status;
|
|
121
|
+
constructor(status, message) {
|
|
122
|
+
super(message);
|
|
123
|
+
this.status = status;
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
127
|
+
var newId = (prefix) => prefix + "_" + randomBytes(6).toString("hex");
|
|
128
|
+
function createShop(defectList = [], dialect = "flat") {
|
|
129
|
+
const defects = new Set(defectList);
|
|
130
|
+
const has = (d) => defects.has(d);
|
|
131
|
+
const wrapped = dialect === "wrapped";
|
|
132
|
+
const one = (table) => table.slice(0, -1);
|
|
133
|
+
const wrap2 = (table, doc) => wrapped ? { [one(table)]: doc } : doc;
|
|
134
|
+
const fieldsOf = (table, body2) => {
|
|
135
|
+
if (!wrapped) return body2;
|
|
136
|
+
const inner = body2[one(table)];
|
|
137
|
+
if (!inner || typeof inner !== "object" || Array.isArray(inner)) throw new HttpError(400, `the body must hold the ${one(table)} as { "${one(table)}": { ... } }`);
|
|
138
|
+
return inner;
|
|
139
|
+
};
|
|
140
|
+
const keyOf = (req, fields2) => wrapped ? typeof fields2.request_id === "string" ? fields2.request_id : void 0 : req.headers["idempotency-key"];
|
|
141
|
+
let seq = 0;
|
|
142
|
+
const tables = { orders: /* @__PURE__ */ new Map(), refunds: /* @__PURE__ */ new Map(), payments: /* @__PURE__ */ new Map() };
|
|
143
|
+
const keys = /* @__PURE__ */ new Map();
|
|
144
|
+
const seenEvents = /* @__PURE__ */ new Set();
|
|
145
|
+
const recent = /* @__PURE__ */ new Map();
|
|
146
|
+
const insert = (table, doc) => {
|
|
147
|
+
tables[table].set(doc.id, { seq: ++seq, doc });
|
|
148
|
+
return doc;
|
|
149
|
+
};
|
|
150
|
+
function auth(req) {
|
|
151
|
+
const header = req.headers.authorization;
|
|
152
|
+
if (!header) {
|
|
153
|
+
if (has("no-auth-on-read") && req.method === "GET") return "usr_guest";
|
|
154
|
+
throw new HttpError(401, "credentials are missing");
|
|
155
|
+
}
|
|
156
|
+
const user = TOKENS[header.replace(/^Bearer /, "")];
|
|
157
|
+
if (user) return user;
|
|
158
|
+
if (has("any-token")) return "usr_guest";
|
|
159
|
+
throw new HttpError(401, "the token is not valid");
|
|
160
|
+
}
|
|
161
|
+
function readBody(req) {
|
|
162
|
+
return new Promise((resolve6, reject) => {
|
|
163
|
+
const chunks = [];
|
|
164
|
+
let size = 0;
|
|
165
|
+
req.on("data", (chunk) => {
|
|
166
|
+
size += chunk.length;
|
|
167
|
+
if (size <= BODY_LIMIT || has("no-body-limit")) chunks.push(chunk);
|
|
168
|
+
else chunks.length = 0;
|
|
169
|
+
});
|
|
170
|
+
req.on("end", () => {
|
|
171
|
+
if (size > BODY_LIMIT && !has("no-body-limit")) reject(new HttpError(413, "the body is larger than 100 kB"));
|
|
172
|
+
else resolve6(Buffer.concat(chunks));
|
|
173
|
+
});
|
|
174
|
+
req.on("error", reject);
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
function parseJson(raw) {
|
|
178
|
+
if (has("json-crash")) return JSON.parse(raw.toString());
|
|
179
|
+
try {
|
|
180
|
+
const value = JSON.parse(raw.toString());
|
|
181
|
+
if (value && typeof value === "object" && !Array.isArray(value)) return value;
|
|
182
|
+
} catch {
|
|
183
|
+
}
|
|
184
|
+
throw new HttpError(400, "the body is not a JSON object");
|
|
185
|
+
}
|
|
186
|
+
async function idempotent(key, req, user, action, body2, make) {
|
|
187
|
+
if (!key) return make();
|
|
188
|
+
const scope = has("idempotency-global-keys") ? key : user + "|" + action + "|" + key;
|
|
189
|
+
const fingerprint = JSON.stringify(body2);
|
|
190
|
+
const hit = keys.get(scope);
|
|
191
|
+
if (hit) {
|
|
192
|
+
if (hit.fingerprint !== fingerprint && !has("idempotency-no-fingerprint")) {
|
|
193
|
+
throw new HttpError(422, "this idempotency key was used with a different body");
|
|
194
|
+
}
|
|
195
|
+
return hit.reply;
|
|
196
|
+
}
|
|
197
|
+
const forget = () => {
|
|
198
|
+
if (has("idempotency-ttl")) setTimeout(() => keys.delete(scope), 500).unref();
|
|
199
|
+
};
|
|
200
|
+
if (has("idempotency-race")) {
|
|
201
|
+
const reply2 = await make();
|
|
202
|
+
if (has("abandoned-forgets-key") && req.socket.destroyed) return reply2;
|
|
203
|
+
keys.set(scope, { fingerprint, reply: Promise.resolve(reply2) });
|
|
204
|
+
forget();
|
|
205
|
+
return reply2;
|
|
206
|
+
}
|
|
207
|
+
const reply = make();
|
|
208
|
+
keys.set(scope, { fingerprint, reply });
|
|
209
|
+
reply.catch(() => keys.delete(scope));
|
|
210
|
+
forget();
|
|
211
|
+
return reply;
|
|
212
|
+
}
|
|
213
|
+
function orderFrom(user, body2) {
|
|
214
|
+
const { item, qty } = body2;
|
|
215
|
+
if (typeof item !== "string" || !item) throw new HttpError(400, "item must be a string");
|
|
216
|
+
if (typeof qty !== "number" || !Number.isInteger(qty) || qty < 1 || qty > 100) throw new HttpError(400, "qty must be a whole number from 1 to 100");
|
|
217
|
+
const doc = {
|
|
218
|
+
id: newId("ord"),
|
|
219
|
+
userId: user,
|
|
220
|
+
item,
|
|
221
|
+
qty,
|
|
222
|
+
total: qty * UNIT_PRICE,
|
|
223
|
+
status: "pending",
|
|
224
|
+
note: typeof body2.note === "string" ? body2.note : "",
|
|
225
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
226
|
+
};
|
|
227
|
+
return has("mass-assignment") ? { ...doc, ...body2, id: doc.id } : doc;
|
|
228
|
+
}
|
|
229
|
+
function refundFrom(user, body2) {
|
|
230
|
+
if (typeof body2.orderId !== "string") throw new HttpError(400, "orderId must be a string");
|
|
231
|
+
return { id: newId("ref"), userId: user, orderId: body2.orderId, note: typeof body2.note === "string" ? body2.note : "", createdAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
232
|
+
}
|
|
233
|
+
async function create(user, table, req) {
|
|
234
|
+
const body2 = fieldsOf(table, parseJson(await readBody(req)));
|
|
235
|
+
const key = keyOf(req, body2);
|
|
236
|
+
const doc = table === "orders" ? orderFrom(user, body2) : refundFrom(user, body2);
|
|
237
|
+
const make = async () => {
|
|
238
|
+
await sleep(body2.item === "slow-pizza" ? SLOW_MS : DB_MS);
|
|
239
|
+
return { status: 201, body: wrap2(table, insert(table, doc)) };
|
|
240
|
+
};
|
|
241
|
+
if (key || has("no-keyless-dedupe")) return idempotent(key, req, user, "create " + table, body2, make);
|
|
242
|
+
const print = user + "|" + table + "|" + JSON.stringify(body2);
|
|
243
|
+
const twin = recent.get(print);
|
|
244
|
+
if (twin && Date.now() - twin.at < DEDUPE_MS) return { ...await twin.reply, status: 200 };
|
|
245
|
+
const reply = make();
|
|
246
|
+
recent.set(print, { at: Date.now(), reply });
|
|
247
|
+
return reply;
|
|
248
|
+
}
|
|
249
|
+
function owned(user, table, id2, skipOwnerCheck) {
|
|
250
|
+
const row = tables[table].get(id2);
|
|
251
|
+
if (!row || row.doc.userId !== user && !skipOwnerCheck) throw new HttpError(404, "not found");
|
|
252
|
+
return row;
|
|
253
|
+
}
|
|
254
|
+
async function update(user, id2, req) {
|
|
255
|
+
const body2 = fieldsOf("orders", parseJson(await readBody(req)));
|
|
256
|
+
return idempotent(keyOf(req, body2), req, user, "update orders", body2, async () => ({ status: 200, body: wrap2("orders", applyUpdate(user, id2, body2)) }));
|
|
257
|
+
}
|
|
258
|
+
function applyUpdate(user, id2, body2) {
|
|
259
|
+
const { doc } = owned(user, "orders", id2, has("no-owner-check-update"));
|
|
260
|
+
if (has("mass-assignment")) Object.assign(doc, body2, { id: doc.id });
|
|
261
|
+
else {
|
|
262
|
+
if (typeof body2.item === "string" && body2.item) doc.item = body2.item;
|
|
263
|
+
if (typeof body2.note === "string") doc.note = body2.note;
|
|
264
|
+
if (body2.qty !== void 0) {
|
|
265
|
+
if (typeof body2.qty !== "number" || !Number.isInteger(body2.qty) || body2.qty < 1 || body2.qty > 100) throw new HttpError(400, "qty must be a whole number from 1 to 100");
|
|
266
|
+
doc.qty = body2.qty;
|
|
267
|
+
doc.total = body2.qty * UNIT_PRICE;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return doc;
|
|
271
|
+
}
|
|
272
|
+
function list2(user, table, query) {
|
|
273
|
+
let limit = PAGE_DEFAULT;
|
|
274
|
+
const rawLimit = query.get(wrapped ? "per_page" : "limit");
|
|
275
|
+
if (rawLimit !== null) {
|
|
276
|
+
limit = Number(rawLimit);
|
|
277
|
+
if (has("limit-crash")) new Array(limit);
|
|
278
|
+
else if (!Number.isInteger(limit) || limit < 1) throw new HttpError(400, "limit must be a whole number above 0");
|
|
279
|
+
if (!has("no-limit-cap")) limit = Math.min(limit, PAGE_MAX);
|
|
280
|
+
}
|
|
281
|
+
if (wrapped) {
|
|
282
|
+
let page2 = 1;
|
|
283
|
+
const rawPage = query.get("page");
|
|
284
|
+
if (rawPage !== null) {
|
|
285
|
+
page2 = Number(rawPage);
|
|
286
|
+
if (!Number.isInteger(page2) || page2 < 1) throw new HttpError(400, "page must be a whole number above 0");
|
|
287
|
+
}
|
|
288
|
+
let rows2 = [...tables[table].values()];
|
|
289
|
+
if (!(has("no-owner-check-list") && table === "orders")) rows2 = rows2.filter((r) => r.doc.userId === user);
|
|
290
|
+
rows2.sort((a, b) => has("offset-pagination") ? b.seq - a.seq : a.seq - b.seq);
|
|
291
|
+
const start = (page2 - 1) * limit;
|
|
292
|
+
return { status: 200, body: { [table]: rows2.slice(start, start + limit).map((r) => r.doc), total: rows2.length } };
|
|
293
|
+
}
|
|
294
|
+
let cursor = {};
|
|
295
|
+
const rawCursor = query.get("cursor");
|
|
296
|
+
if (rawCursor !== null) {
|
|
297
|
+
if (has("cursor-crash")) cursor = JSON.parse(Buffer.from(rawCursor, "base64url").toString());
|
|
298
|
+
else {
|
|
299
|
+
try {
|
|
300
|
+
cursor = JSON.parse(Buffer.from(rawCursor, "base64url").toString());
|
|
301
|
+
} catch {
|
|
302
|
+
throw new HttpError(400, "the cursor is not valid");
|
|
303
|
+
}
|
|
304
|
+
const position = has("offset-pagination") ? cursor?.off : cursor?.after;
|
|
305
|
+
if (!Number.isInteger(position)) throw new HttpError(400, "the cursor is not valid");
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
const reader = has("cursor-trusts-user") && cursor.u ? cursor.u : user;
|
|
309
|
+
let rows = [...tables[table].values()];
|
|
310
|
+
if (!(has("no-owner-check-list") && table === "orders")) rows = rows.filter((r) => r.doc.userId === reader);
|
|
311
|
+
const encode = (c) => Buffer.from(JSON.stringify(has("cursor-trusts-user") ? { ...c, u: reader } : c)).toString("base64url");
|
|
312
|
+
if (has("offset-pagination")) {
|
|
313
|
+
rows.sort((a, b) => b.seq - a.seq);
|
|
314
|
+
const off = cursor.off ?? 0;
|
|
315
|
+
const page2 = rows.slice(off, off + limit);
|
|
316
|
+
return { status: 200, body: { data: page2.map((r) => r.doc), nextCursor: off + limit < rows.length ? encode({ off: off + limit }) : null } };
|
|
317
|
+
}
|
|
318
|
+
rows = rows.filter((r) => r.seq > (cursor.after ?? 0)).sort((a, b) => a.seq - b.seq);
|
|
319
|
+
const page = rows.slice(0, limit);
|
|
320
|
+
return { status: 200, body: { data: page.map((r) => r.doc), nextCursor: rows.length > limit ? encode({ after: page[page.length - 1].seq }) : null } };
|
|
321
|
+
}
|
|
322
|
+
function verify(header, raw) {
|
|
323
|
+
if (!header) {
|
|
324
|
+
if (has("webhook-missing-signature-ok")) return;
|
|
325
|
+
throw new HttpError(401, "the signature is missing");
|
|
326
|
+
}
|
|
327
|
+
const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
|
|
328
|
+
const expected = createHmac("sha256", WEBHOOK_SECRET).update(parts.t + "." + raw.toString()).digest("hex");
|
|
329
|
+
const given = Buffer.from(parts.v1 ?? "");
|
|
330
|
+
const match = given.length === expected.length && timingSafeEqual(given, Buffer.from(expected));
|
|
331
|
+
if (!match && !has("webhook-no-verify")) throw new HttpError(401, "the signature does not match");
|
|
332
|
+
const age = Math.abs(Date.now() / 1e3 - Number(parts.t));
|
|
333
|
+
if (!(age <= TOLERANCE_S) && !has("webhook-no-tolerance")) throw new HttpError(401, "the timestamp is too old");
|
|
334
|
+
}
|
|
335
|
+
const handlers = {
|
|
336
|
+
"payment.succeeded": async (event) => {
|
|
337
|
+
const id2 = String(event.id);
|
|
338
|
+
if (!has("webhook-no-dedupe")) {
|
|
339
|
+
if (seenEvents.has(id2)) return;
|
|
340
|
+
if (!has("webhook-dedupe-race")) seenEvents.add(id2);
|
|
341
|
+
}
|
|
342
|
+
await sleep(DB_MS);
|
|
343
|
+
const row = tables.orders.get(String(event.data?.orderId));
|
|
344
|
+
if (row) {
|
|
345
|
+
row.doc.status = "paid";
|
|
346
|
+
insert("payments", { id: newId("pay"), userId: row.doc.userId, orderId: row.doc.id, eventId: id2, amount: row.doc.total });
|
|
347
|
+
}
|
|
348
|
+
seenEvents.add(id2);
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
async function webhook(req) {
|
|
352
|
+
const raw = await readBody(req);
|
|
353
|
+
verify(req.headers["stripe-signature"], raw);
|
|
354
|
+
const event = parseJson(raw);
|
|
355
|
+
const handler = handlers[String(event.type)];
|
|
356
|
+
if (!handler && !has("webhook-unknown-crash")) return { status: 200, body: { received: true, ignored: true } };
|
|
357
|
+
await handler(event);
|
|
358
|
+
return { status: 200, body: { received: true } };
|
|
359
|
+
}
|
|
360
|
+
async function route3(req) {
|
|
361
|
+
const url = new URL(req.url ?? "/", "http://shop");
|
|
362
|
+
const method = req.method ?? "GET";
|
|
363
|
+
if (url.pathname === "/") return { status: 200, body: { name: "badday demo shop" } };
|
|
364
|
+
if (url.pathname === "/openapi.json") return { status: 200, body: openapi };
|
|
365
|
+
if (url.pathname === "/webhooks/payment") {
|
|
366
|
+
if (method !== "POST") throw new HttpError(405, "method not allowed");
|
|
367
|
+
return webhook(req);
|
|
368
|
+
}
|
|
369
|
+
const match = url.pathname.match(/^\/(orders|refunds|payments)(?:\/([^/]+))?$/);
|
|
370
|
+
if (!match) throw new HttpError(404, "not found");
|
|
371
|
+
const [, table, id2] = match;
|
|
372
|
+
const user = auth(req);
|
|
373
|
+
if (!id2) {
|
|
374
|
+
if (method === "GET") return list2(user, table, url.searchParams);
|
|
375
|
+
if (method === "POST" && table !== "payments") return create(user, table, req);
|
|
376
|
+
} else {
|
|
377
|
+
if (method === "GET") return { status: 200, body: wrap2(table, owned(user, table, id2, has("no-owner-check-read")).doc) };
|
|
378
|
+
if (method === "PATCH" && table === "orders") return update(user, id2, req);
|
|
379
|
+
if (method === "DELETE" && table === "orders") {
|
|
380
|
+
owned(user, table, id2, has("no-owner-check-delete"));
|
|
381
|
+
tables[table].delete(id2);
|
|
382
|
+
return { status: 204, body: null };
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
throw new HttpError(405, "method not allowed");
|
|
386
|
+
}
|
|
387
|
+
function send(res, reply, close = false) {
|
|
388
|
+
const text2 = reply.body === null ? "" : JSON.stringify(reply.body);
|
|
389
|
+
const headers = { "Content-Length": String(Buffer.byteLength(text2)) };
|
|
390
|
+
if (text2) headers["Content-Type"] = "application/json";
|
|
391
|
+
if (close) headers.Connection = "close";
|
|
392
|
+
res.writeHead(reply.status, headers).end(text2);
|
|
393
|
+
}
|
|
394
|
+
return http.createServer((req, res) => {
|
|
395
|
+
route3(req).then(
|
|
396
|
+
(reply) => send(res, reply),
|
|
397
|
+
(err) => {
|
|
398
|
+
if (err instanceof HttpError) return send(res, { status: err.status, body: { error: err.message } }, err.status === 413);
|
|
399
|
+
send(res, { status: 500, body: has("stack-traces") ? { error: err.message, stack: err.stack } : { error: "internal error" } });
|
|
400
|
+
}
|
|
401
|
+
);
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
function startShop(defects = [], port = 0, dialect = "flat") {
|
|
405
|
+
const server = createShop(defects, dialect);
|
|
406
|
+
return new Promise((resolve6, reject) => {
|
|
407
|
+
server.once("error", reject);
|
|
408
|
+
server.listen(port, "127.0.0.1", () => {
|
|
409
|
+
const { port: bound } = server.address();
|
|
410
|
+
resolve6({
|
|
411
|
+
url: "http://127.0.0.1:" + bound,
|
|
412
|
+
close: () => new Promise((done) => {
|
|
413
|
+
server.closeAllConnections();
|
|
414
|
+
server.close(() => done());
|
|
415
|
+
})
|
|
416
|
+
});
|
|
417
|
+
});
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// fixtures/shop-broken/index.ts
|
|
422
|
+
var startBrokenShop = (port = 0, dialect = "flat") => startShop(DEFECTS, port, dialect);
|
|
423
|
+
|
|
424
|
+
// fixtures/shop-fixed/index.ts
|
|
425
|
+
var startFixedShop = (port = 0, dialect = "flat") => startShop([], port, dialect);
|
|
426
|
+
|
|
427
|
+
// fixtures/shop/config.ts
|
|
428
|
+
var actors = {
|
|
429
|
+
alice: { headers: { Authorization: "Bearer alice-token" } },
|
|
430
|
+
bob: { headers: { Authorization: "Bearer bob-token" } }
|
|
431
|
+
};
|
|
432
|
+
var webhooks = [{
|
|
433
|
+
path: "/webhooks/payment",
|
|
434
|
+
signing: { scheme: "stripe", secret: WEBHOOK_SECRET },
|
|
435
|
+
event: { type: "payment.succeeded", data: { orderId: "$orders.id" } },
|
|
436
|
+
effect: { list: "/payments" }
|
|
437
|
+
}];
|
|
438
|
+
function shopConfig(baseUrl, dialect = "flat") {
|
|
439
|
+
if (dialect === "wrapped") {
|
|
440
|
+
return {
|
|
441
|
+
baseUrl,
|
|
442
|
+
actors,
|
|
443
|
+
webhooks: [{ ...webhooks[0], effect: { list: { path: "/payments", limitParam: "per_page", pageParam: "page" } } }],
|
|
444
|
+
resources: [{
|
|
445
|
+
name: "orders",
|
|
446
|
+
envelope: "order",
|
|
447
|
+
create: { method: "POST", path: "/orders", body: { order: { item: "pizza", qty: 1 } }, slow: { body: { item: "slow-pizza" }, ms: 300 } },
|
|
448
|
+
get: "/orders/:id",
|
|
449
|
+
list: { path: "/orders", limitParam: "per_page", pageParam: "page", maxLimit: 100 },
|
|
450
|
+
update: { method: "PATCH", path: "/orders/:id", body: { order: { qty: 2 } } },
|
|
451
|
+
remove: { method: "DELETE", path: "/orders/:id" },
|
|
452
|
+
idempotencyField: "request_id",
|
|
453
|
+
duplicates: "forbidden",
|
|
454
|
+
protectedFields: ["userId", "total", "status"],
|
|
455
|
+
markerField: "note"
|
|
456
|
+
}]
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
return {
|
|
460
|
+
baseUrl,
|
|
461
|
+
actors,
|
|
462
|
+
webhooks,
|
|
463
|
+
resources: [{
|
|
464
|
+
name: "orders",
|
|
465
|
+
create: { method: "POST", path: "/orders", body: { item: "pizza", qty: 1 }, slow: { body: { item: "slow-pizza" }, ms: 300 } },
|
|
466
|
+
get: "/orders/:id",
|
|
467
|
+
list: { path: "/orders", limitParam: "limit", maxLimit: 100 },
|
|
468
|
+
update: { method: "PATCH", path: "/orders/:id", body: { qty: 2 } },
|
|
469
|
+
remove: { method: "DELETE", path: "/orders/:id" },
|
|
470
|
+
idempotencyHeader: "Idempotency-Key",
|
|
471
|
+
duplicates: "forbidden",
|
|
472
|
+
protectedFields: ["userId", "total", "status"],
|
|
473
|
+
markerField: "note"
|
|
474
|
+
}]
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// src/engine/resource.ts
|
|
479
|
+
var ITEM_FIELDS = ["data", "items", "results"];
|
|
480
|
+
var CURSOR_FIELDS = ["nextCursor", "next_cursor", "next"];
|
|
481
|
+
var MAX_PAGES = 200;
|
|
482
|
+
var BATCH = 20;
|
|
483
|
+
var counter = 0;
|
|
484
|
+
var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
485
|
+
var cap = (text2) => text2[0].toUpperCase() + text2.slice(1);
|
|
486
|
+
var an = (noun) => (/^[aeiou]/i.test(noun) ? "an " : "a ") + noun;
|
|
487
|
+
var withId = (path2, id2) => path2.replace(":id", encodeURIComponent(id2));
|
|
488
|
+
var statusOf = (exchange) => String(exchange.response?.status ?? "no answer");
|
|
489
|
+
var ok = (exchange) => !!exchange.response && exchange.response.status >= 200 && exchange.response.status < 300;
|
|
490
|
+
var crashed = (exchange) => !exchange.response || exchange.response.status >= 500;
|
|
491
|
+
var WRAPPERS = ["data", "item", "result", "record"];
|
|
492
|
+
var isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
493
|
+
function withFields(resource, body2, fields2) {
|
|
494
|
+
const copy = { ...body2 };
|
|
495
|
+
const { envelope } = resource;
|
|
496
|
+
if (!envelope) return Object.assign(copy, fields2);
|
|
497
|
+
copy[envelope] = { ...isObject(copy[envelope]) ? copy[envelope] : {}, ...fields2 };
|
|
498
|
+
return copy;
|
|
499
|
+
}
|
|
500
|
+
var sentRecord = (resource, body2) => {
|
|
501
|
+
const root = resource.envelope && isObject(body2) ? body2[resource.envelope] : body2;
|
|
502
|
+
return isObject(root) ? root : null;
|
|
503
|
+
};
|
|
504
|
+
var recordFields = (resource, body2) => sentRecord(resource, body2) ?? {};
|
|
505
|
+
function createReq(ctx, actor, extra = {}) {
|
|
506
|
+
const { create, markerField } = ctx.resource;
|
|
507
|
+
if (!create) throw new Error(`the ${ctx.resource.name} resource has no create route`);
|
|
508
|
+
const body2 = markerField ? withFields(ctx.resource, create.body, { [markerField]: ctx.marker + "-" + ++counter }) : { ...create.body };
|
|
509
|
+
return { actor, method: create.method, path: create.path, body: body2, ...extra };
|
|
510
|
+
}
|
|
511
|
+
var keyName = (resource) => resource.idempotencyHeader ? `${resource.idempotencyHeader} header` : `${resource.idempotencyField} field`;
|
|
512
|
+
function keyed(resource, req, key) {
|
|
513
|
+
if (resource.idempotencyHeader) return { ...req, headers: { ...req.headers, [resource.idempotencyHeader]: key } };
|
|
514
|
+
return { ...req, body: withFields(resource, req.body, { [resource.idempotencyField]: key }) };
|
|
515
|
+
}
|
|
516
|
+
function recordOf(ctx, doc) {
|
|
517
|
+
if (!isObject(doc)) return null;
|
|
518
|
+
const { idField, envelope, singular: singular2, name } = ctx.resource;
|
|
519
|
+
const holdsId = (value) => isObject(value) && (typeof value[idField] === "string" || typeof value[idField] === "number");
|
|
520
|
+
if (envelope && holdsId(doc[envelope])) return doc[envelope];
|
|
521
|
+
if (holdsId(doc)) return doc;
|
|
522
|
+
for (const key of [...WRAPPERS, singular2, name]) if (holdsId(doc[key])) return doc[key];
|
|
523
|
+
const inner = Object.values(doc).filter(holdsId);
|
|
524
|
+
return inner.length === 1 ? inner[0] : null;
|
|
525
|
+
}
|
|
526
|
+
function idOf(ctx, doc) {
|
|
527
|
+
const record2 = recordOf(ctx, doc);
|
|
528
|
+
return record2 ? String(record2[ctx.resource.idField]) : null;
|
|
529
|
+
}
|
|
530
|
+
function createdId(ctx, exchange, opts = {}) {
|
|
531
|
+
if (!ok(exchange)) return null;
|
|
532
|
+
const fromResponse = idOf(ctx, exchange.response.body);
|
|
533
|
+
if (fromResponse) return fromResponse;
|
|
534
|
+
const bare = exchange.response.body;
|
|
535
|
+
if (typeof bare === "number" || typeof bare === "string" && /^[\w.~-]{1,100}$/.test(bare) && /json/i.test(exchange.response.headers["content-type"] ?? "")) return String(bare);
|
|
536
|
+
const { idField, markerField } = ctx.resource;
|
|
537
|
+
const sent = markerField === idField ? sentRecord(ctx.resource, exchange.request.body)?.[idField] : null;
|
|
538
|
+
if (typeof sent === "string" || typeof sent === "number") return String(sent);
|
|
539
|
+
if (!opts.lookup) ctx.unidentified();
|
|
540
|
+
return null;
|
|
541
|
+
}
|
|
542
|
+
async function idsByMarker(ctx, actor, exchanges) {
|
|
543
|
+
const found = /* @__PURE__ */ new Map();
|
|
544
|
+
const { markerField, list: list2 } = ctx.resource;
|
|
545
|
+
if (!markerField || !list2) return found;
|
|
546
|
+
const byMarker = /* @__PURE__ */ new Map();
|
|
547
|
+
for (const [id2, row] of await listAll(ctx, actor, { quiet: true })) byMarker.set(String(row[markerField]), id2);
|
|
548
|
+
for (const exchange of exchanges) {
|
|
549
|
+
const id2 = byMarker.get(String(sentRecord(ctx.resource, exchange.request.body)?.[markerField]));
|
|
550
|
+
if (id2) found.set(exchange, id2);
|
|
551
|
+
}
|
|
552
|
+
return found;
|
|
553
|
+
}
|
|
554
|
+
var noId = (ctx, exchange) => {
|
|
555
|
+
const { idField, name, envelope } = ctx.resource;
|
|
556
|
+
return `Your app answered ${statusOf(exchange)} to a create request, and badday found no "${idField}" field in the answer, so it cannot tell which of the ${name} it made. The answer starts: ${exchange.response.text.slice(0, 120)}. Name the field that holds the id in idField${envelope ? "" : ", or the field that wraps the record in envelope"}`;
|
|
557
|
+
};
|
|
558
|
+
async function createOne(ctx, actor, opts = {}) {
|
|
559
|
+
const req = createReq(ctx, actor, { quiet: opts.quiet });
|
|
560
|
+
if (opts.body) req.body = withFields(ctx.resource, req.body, opts.body);
|
|
561
|
+
const exchange = await ctx.client.send(req);
|
|
562
|
+
if (!exchange.response) throw new Error(`Your app gave no answer to a plain create request as ${actor}, so this check could not start`);
|
|
563
|
+
if (!ok(exchange)) throw new Error(`Your app answered ${statusOf(exchange)} to a plain create request as ${actor}, so this check could not start. Check the create route and its body in the config`);
|
|
564
|
+
const id2 = createdId(ctx, exchange, { lookup: true }) ?? (await idsByMarker(ctx, actor, [exchange])).get(exchange);
|
|
565
|
+
if (!id2) {
|
|
566
|
+
ctx.unidentified();
|
|
567
|
+
throw new Error(noId(ctx, exchange));
|
|
568
|
+
}
|
|
569
|
+
ctx.track(actor, id2);
|
|
570
|
+
exchange.note = opts.note ?? `${actor} created ${id2}`;
|
|
571
|
+
return { id: id2, exchange, doc: recordOf(ctx, exchange.response.body) ?? {} };
|
|
572
|
+
}
|
|
573
|
+
async function createMany(ctx, actor, count) {
|
|
574
|
+
const ids = [];
|
|
575
|
+
for (let done = 0; done < count; done += BATCH) {
|
|
576
|
+
const batch = await ctx.client.burst(Array.from({ length: Math.min(BATCH, count - done) }, () => createReq(ctx, actor, { quiet: true })));
|
|
577
|
+
const refused = batch.find((exchange) => !ok(exchange));
|
|
578
|
+
if (refused) {
|
|
579
|
+
const silent = batch.filter((exchange) => !exchange.response).length;
|
|
580
|
+
throw new Error(silent ? `We sent ${batch.length} plain create requests at once, and your app gave no answer to ${silent} of them, so this check could not finish` : `Your app answered ${statusOf(refused)} to a plain create request, after ${ids.length} of ${count} records, so this check could not finish`);
|
|
581
|
+
}
|
|
582
|
+
let looked = null;
|
|
583
|
+
for (const exchange of batch) {
|
|
584
|
+
const id2 = createdId(ctx, exchange, { lookup: true }) ?? (looked ??= await idsByMarker(ctx, actor, batch)).get(exchange);
|
|
585
|
+
if (!id2) {
|
|
586
|
+
ctx.unidentified();
|
|
587
|
+
throw new Error(noId(ctx, exchange));
|
|
588
|
+
}
|
|
589
|
+
ctx.track(actor, id2);
|
|
590
|
+
ids.push(id2);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
return ids;
|
|
594
|
+
}
|
|
595
|
+
function listPath(spec, params = {}) {
|
|
596
|
+
const query = new URLSearchParams(params).toString();
|
|
597
|
+
return spec.path + (query ? (spec.path.includes("?") ? "&" : "?") + query : "");
|
|
598
|
+
}
|
|
599
|
+
function pageOf(exchange, spec, name) {
|
|
600
|
+
if (!ok(exchange)) return null;
|
|
601
|
+
const body2 = exchange.response.body;
|
|
602
|
+
const field = spec.items ?? [...ITEM_FIELDS, name].find((f) => Array.isArray(body2?.[f]));
|
|
603
|
+
const rows = Array.isArray(body2) ? body2 : field ? body2?.[field] : null;
|
|
604
|
+
if (!Array.isArray(rows)) return null;
|
|
605
|
+
const next = Array.isArray(body2) ? null : body2[spec.nextCursor ?? CURSOR_FIELDS.find((f) => body2[f]) ?? ""];
|
|
606
|
+
return { rows, next: typeof next === "string" && next ? next : null };
|
|
607
|
+
}
|
|
608
|
+
function pager(spec, size) {
|
|
609
|
+
let cursor = null;
|
|
610
|
+
let page = 1;
|
|
611
|
+
let offset = 0;
|
|
612
|
+
let last = "";
|
|
613
|
+
return {
|
|
614
|
+
params() {
|
|
615
|
+
const params = {};
|
|
616
|
+
if (spec.limitParam && size) params[spec.limitParam] = String(size);
|
|
617
|
+
if (spec.pageParam) params[spec.pageParam] = String(page);
|
|
618
|
+
else if (spec.offsetParam) params[spec.offsetParam] = String(offset);
|
|
619
|
+
else if (cursor) params[spec.cursorParam ?? "cursor"] = cursor;
|
|
620
|
+
return params;
|
|
621
|
+
},
|
|
622
|
+
/** Moves to the next page. False when the list has ended. */
|
|
623
|
+
advance(got) {
|
|
624
|
+
if (spec.pageParam || spec.offsetParam) {
|
|
625
|
+
const print = JSON.stringify(got.rows[0] ?? null) + got.rows.length;
|
|
626
|
+
if (!got.rows.length || print === last) return false;
|
|
627
|
+
last = print;
|
|
628
|
+
page++;
|
|
629
|
+
offset += got.rows.length;
|
|
630
|
+
return true;
|
|
631
|
+
}
|
|
632
|
+
if (!got.next || got.next === cursor) return false;
|
|
633
|
+
cursor = got.next;
|
|
634
|
+
return true;
|
|
635
|
+
}
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
var pagesByNumber = (spec) => !!(spec?.pageParam || spec?.offsetParam);
|
|
639
|
+
function totalOf(body2) {
|
|
640
|
+
if (!isObject(body2)) return null;
|
|
641
|
+
for (const holder of [body2, body2.meta, body2.pagination]) {
|
|
642
|
+
if (!isObject(holder)) continue;
|
|
643
|
+
for (const [key, value] of Object.entries(holder)) {
|
|
644
|
+
if (typeof value === "number" && /^(total|count)$|(_total|_count|Total|Count)$|^total_?(items|count|results|records)$/.test(key)) return value;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
return null;
|
|
648
|
+
}
|
|
649
|
+
async function walk(ctx, actor, spec, name, opts = {}) {
|
|
650
|
+
const all = [];
|
|
651
|
+
let total = null;
|
|
652
|
+
const pages = pager(spec, spec.maxLimit ?? 100);
|
|
653
|
+
for (let i = 0; i < MAX_PAGES; i++) {
|
|
654
|
+
const path2 = listPath(spec, pages.params());
|
|
655
|
+
const exchange = await ctx.client.send({ actor, method: "GET", path: path2, quiet: opts.quiet, note: opts.note });
|
|
656
|
+
if (!ok(exchange)) throw new Error(`GET ${path2} answered ${statusOf(exchange)}, so badday could not read the ${name}`);
|
|
657
|
+
const page = pageOf(exchange, spec, name);
|
|
658
|
+
if (!page) throw new Error(`badday could not find the ${name} in the response of GET ${spec.path}. Name the field in list.items`);
|
|
659
|
+
all.push(...page.rows);
|
|
660
|
+
total ??= totalOf(exchange.response.body);
|
|
661
|
+
if (!pages.advance(page)) break;
|
|
662
|
+
}
|
|
663
|
+
if (total !== null && total > all.length) {
|
|
664
|
+
throw new Error(`GET ${spec.path} says it holds ${total} ${name}, and badday could read only ${all.length} of them. The list pages in a way the config does not describe. Name list.pageParam or list.offsetParam, and list.limitParam`);
|
|
665
|
+
}
|
|
666
|
+
return all;
|
|
667
|
+
}
|
|
668
|
+
async function listAll(ctx, actor, opts = {}) {
|
|
669
|
+
const spec = ctx.resource.list;
|
|
670
|
+
if (!spec) throw new Error(`the ${ctx.resource.name} resource has no list route`);
|
|
671
|
+
const found = /* @__PURE__ */ new Map();
|
|
672
|
+
for (const row of await walk(ctx, actor, spec, ctx.resource.name, opts)) {
|
|
673
|
+
const id2 = idOf(ctx, row);
|
|
674
|
+
if (id2) found.set(id2, row);
|
|
675
|
+
}
|
|
676
|
+
return found;
|
|
677
|
+
}
|
|
678
|
+
var snapshot = (ctx, actor) => ctx.resource.list ? listAll(ctx, actor, { quiet: true }) : Promise.resolve(null);
|
|
679
|
+
function createdBy(ctx, before, after) {
|
|
680
|
+
const { markerField } = ctx.resource;
|
|
681
|
+
return [...after].filter(([id2, row]) => !before.has(id2) && (!markerField || String(row[markerField] ?? "").startsWith(ctx.marker + "-"))).map(([id2]) => id2);
|
|
682
|
+
}
|
|
683
|
+
async function newRecords(ctx, actor, before, returned) {
|
|
684
|
+
const named2 = [...new Set(returned)].filter((id2) => !!id2);
|
|
685
|
+
const created = before ? createdBy(ctx, before, await listAll(ctx, actor, { note: "the count after" })) : named2;
|
|
686
|
+
for (const id2 of /* @__PURE__ */ new Set([...created, ...named2])) ctx.track(actor, id2);
|
|
687
|
+
return created;
|
|
688
|
+
}
|
|
689
|
+
async function realCursor(ctx, actor) {
|
|
690
|
+
const spec = ctx.resource.list;
|
|
691
|
+
const ids = await createMany(ctx, actor, 3);
|
|
692
|
+
const exchange = await ctx.client.send({ actor, method: "GET", path: listPath(spec, spec.limitParam ? { [spec.limitParam]: "2" } : {}), note: `${actor} reads the first page, to get a real cursor` });
|
|
693
|
+
const cursor = pageOf(exchange, spec, ctx.resource.name)?.next;
|
|
694
|
+
return cursor ? { cursor, ids } : null;
|
|
695
|
+
}
|
|
696
|
+
var NO_CURSOR = "The first page of your list came with no cursor for a second page, so badday has no real cursor to work with. Name list.limitParam in the config, so badday can ask for a small page.";
|
|
697
|
+
function needsList(resource) {
|
|
698
|
+
if (!resource.list) return `Your config gives the ${resource.name} resource no list route. Add one and this check runs.`;
|
|
699
|
+
return null;
|
|
700
|
+
}
|
|
701
|
+
function needsCreateAndList(resource) {
|
|
702
|
+
if (!resource.create) return `Your config gives the ${resource.name} resource no create route. Add one and this check runs.`;
|
|
703
|
+
return needsList(resource);
|
|
704
|
+
}
|
|
705
|
+
function needsCursor(resource) {
|
|
706
|
+
const reason = needsCreateAndList(resource);
|
|
707
|
+
if (reason) return reason;
|
|
708
|
+
if (pagesByNumber(resource.list)) return `Your ${resource.name} list pages by ${resource.list.pageParam ? "page number" : "offset"}, so it has no cursor to attack.`;
|
|
709
|
+
return null;
|
|
710
|
+
}
|
|
711
|
+
function needsKeyedCreate(resource) {
|
|
712
|
+
if (!resource.create) return `Your config gives the ${resource.name} resource no create route. Add one and this check runs.`;
|
|
713
|
+
if (!resource.idempotencyHeader && !resource.idempotencyField) {
|
|
714
|
+
return `Your config names no idempotency key for ${resource.name}. If your create route takes one, add idempotencyHeader, such as "Idempotency-Key", or idempotencyField for a key in the body, and this check runs.`;
|
|
715
|
+
}
|
|
716
|
+
return null;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// src/checks/replay/abandoned-retry.ts
|
|
720
|
+
function needsSlowCreate(resource) {
|
|
721
|
+
const reason = needsKeyedCreate(resource);
|
|
722
|
+
if (reason) return reason;
|
|
723
|
+
if (!resource.create.slow) {
|
|
724
|
+
return `badday has to cut in while a create request runs, and it cannot tell how to make yours slow. Give the create route of ${resource.name} a slow body, with the time it takes.`;
|
|
725
|
+
}
|
|
726
|
+
return null;
|
|
727
|
+
}
|
|
728
|
+
var abandonedRetry = {
|
|
729
|
+
name: "abandoned-retry",
|
|
730
|
+
pack: "replay",
|
|
731
|
+
creates: 2,
|
|
732
|
+
promise: "A customer whose connection drops mid-payment and who tries again is charged once.",
|
|
733
|
+
consequence: "A customer whose connection drops mid-payment and who tries again is charged twice.",
|
|
734
|
+
question: "if a dropped connection and a retry charge a customer twice",
|
|
735
|
+
needs: needsSlowCreate,
|
|
736
|
+
async run(ctx) {
|
|
737
|
+
const { resource, owner, client } = ctx;
|
|
738
|
+
const { name, singular: singular2 } = resource;
|
|
739
|
+
const slow = resource.create.slow;
|
|
740
|
+
const cutAt = Math.round(slow.ms / 3);
|
|
741
|
+
const before = await snapshot(ctx, owner);
|
|
742
|
+
const req = keyed(resource, createReq(ctx, owner), ctx.marker + "-dropped");
|
|
743
|
+
req.body = withFields(resource, req.body, slow.body);
|
|
744
|
+
const dropped = await client.send({ ...req, abortAfterMs: cutAt });
|
|
745
|
+
if (dropped.response) {
|
|
746
|
+
return { verdict: "warning", summary: `Your app answered the slow create request in under ${cutAt} ms, before badday could cut the connection. Correct the slow body or its time in the config.` };
|
|
747
|
+
}
|
|
748
|
+
await sleep2(slow.ms + 150);
|
|
749
|
+
const retry = await client.send({ ...req });
|
|
750
|
+
const retryId = createdId(ctx, retry);
|
|
751
|
+
retry.note = retryId ? `the retry got ${retryId}` : `the retry was refused with ${retry.response?.status ?? "no answer"}`;
|
|
752
|
+
const created = await newRecords(ctx, owner, before, [retryId]);
|
|
753
|
+
const story = `We cut the connection ${cutAt} ms into a create request, let your app finish, and sent the request again with the same key.`;
|
|
754
|
+
const facts = [{ label: `${cap(name)} created by a dropped request and its retry`, expected: "1", actual: String(created.length) }];
|
|
755
|
+
if (created.length > 1) {
|
|
756
|
+
return {
|
|
757
|
+
verdict: "fail",
|
|
758
|
+
facts,
|
|
759
|
+
summary: `${story} Your app created ${created.length} ${name}.`,
|
|
760
|
+
fixPrompt: `My backend creates a second ${singular2} when a client disconnects during a request and then retries. A test sent ${resource.create.method} ${resource.create.path} with the ${keyName(resource)}, closed the connection while the request ran, and sent it again with the same key. The backend created ${created.length} ${name}. It must create 1.
|
|
761
|
+
|
|
762
|
+
The first request still finished its insert after the client left, and its key was never saved. Save the key in the same transaction as the ${singular2}, before any slow work and before the response is written. Do not tie the save to a successful response.`
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
if (created.length === 0) return { verdict: "warning", facts, summary: `${story} No new ${singular2} shows in the list. badday cannot tell what happened.` };
|
|
766
|
+
if (!ok(retry)) return { verdict: "warning", facts, title: "A retry after a dropped connection gets an error, though the payment went through.", summary: `${story} Your app created 1 ${singular2} and answered the retry with ${retry.response?.status ?? "no answer"}.` };
|
|
767
|
+
return { verdict: "pass", facts, summary: `${story} 1 ${singular2} exists.` };
|
|
768
|
+
}
|
|
769
|
+
};
|
|
770
|
+
|
|
771
|
+
// src/checks/replay/duplicate-submit.ts
|
|
772
|
+
var COPIES = 20;
|
|
773
|
+
var duplicateSubmit = {
|
|
774
|
+
name: "duplicate-submit",
|
|
775
|
+
pack: "replay",
|
|
776
|
+
creates: COPIES,
|
|
777
|
+
promise: 'A customer who double-clicks "Pay" is charged once.',
|
|
778
|
+
consequence: 'A customer who double-clicks "Pay" is charged twice.',
|
|
779
|
+
question: "if a double-click charges a customer twice",
|
|
780
|
+
needs: needsKeyedCreate,
|
|
781
|
+
async run(ctx) {
|
|
782
|
+
const { resource, owner, client } = ctx;
|
|
783
|
+
const { name, singular: singular2 } = resource;
|
|
784
|
+
const before = await snapshot(ctx, owner);
|
|
785
|
+
const req = keyed(resource, createReq(ctx, owner), ctx.marker + "-dup");
|
|
786
|
+
const sent = await client.burst(Array.from({ length: COPIES }, () => ({ ...req })));
|
|
787
|
+
const accepted = sent.filter(ok);
|
|
788
|
+
const returned = /* @__PURE__ */ new Set();
|
|
789
|
+
for (const exchange of sent) {
|
|
790
|
+
const status = exchange.response?.status;
|
|
791
|
+
const id2 = createdId(ctx, exchange);
|
|
792
|
+
if (id2) {
|
|
793
|
+
exchange.note = returned.size === 0 ? `created ${id2}` : returned.has(id2) ? `returned ${id2} again` : `created ${id2}, a new ${singular2}`;
|
|
794
|
+
returned.add(id2);
|
|
795
|
+
} else if (status) exchange.note = `refused with ${status}`;
|
|
796
|
+
}
|
|
797
|
+
const created = await newRecords(ctx, owner, before, returned);
|
|
798
|
+
const copies = `We sent the same ${singular2} ${COPIES} times at once, with one idempotency key.`;
|
|
799
|
+
const facts = [{ label: `${cap(name)} created by ${COPIES} copies of one request`, expected: "1", actual: String(created.length) }];
|
|
800
|
+
if (!accepted.length) {
|
|
801
|
+
const statuses = [...new Set(sent.map((x) => x.response?.status ?? "no response"))].join(", ");
|
|
802
|
+
return { verdict: "warning", facts, summary: `${copies} Your app accepted none of them (${statuses}), so this check proves nothing. Check the create route and its body in the config.` };
|
|
803
|
+
}
|
|
804
|
+
if (created.length > 1) {
|
|
805
|
+
const { method, path: path2 } = resource.create;
|
|
806
|
+
return {
|
|
807
|
+
verdict: "fail",
|
|
808
|
+
facts,
|
|
809
|
+
summary: `${copies} Your app created ${created.length} ${name}.`,
|
|
810
|
+
fixPrompt: `My backend creates duplicate ${name} when the same request arrives more than once at the same time. A test sent ${method} ${path2} ${COPIES} times in the same instant with the same ${keyName(resource)}, and the backend created ${created.length} ${name}. It must create 1 ${singular2} and return that ${singular2} to all ${COPIES} requests.
|
|
811
|
+
|
|
812
|
+
The likely cause is a check-then-insert race. The code looks up the key, finds nothing, then inserts, and all ${COPIES} requests pass the lookup before any insert lands.
|
|
813
|
+
|
|
814
|
+
Store the idempotency key in a column with a unique constraint, and insert the key and the ${singular2} in one transaction. When the insert hits the constraint, read the stored ${singular2} and return it with the original status code. Do not use an in-memory lock, because that fails as soon as two server processes run.`
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
if (created.length === 0) {
|
|
818
|
+
return { verdict: "warning", facts, summary: `${copies} Your app answered with success, and no new ${singular2} shows in the list. badday cannot tell what happened.` };
|
|
819
|
+
}
|
|
820
|
+
const crashed2 = sent.filter((x) => !x.response || x.response.status >= 500).length;
|
|
821
|
+
if (crashed2) {
|
|
822
|
+
return { verdict: "warning", facts, title: "A double-click creates one order, and some of the copies get a server error.", summary: `${copies} Your app created 1 ${singular2}, and ${crashed2} of the copies got a server error or no answer.` };
|
|
823
|
+
}
|
|
824
|
+
if (returned.size > 1) {
|
|
825
|
+
return { verdict: "warning", facts, summary: `${copies} The list shows 1 new ${singular2}, and the responses name ${returned.size} different ids. badday cannot tell what happened.` };
|
|
826
|
+
}
|
|
827
|
+
const refused = COPIES - accepted.length;
|
|
828
|
+
return {
|
|
829
|
+
verdict: "pass",
|
|
830
|
+
facts,
|
|
831
|
+
summary: refused ? `${copies} Your app created 1 ${singular2}. ${accepted.length} copies got it back and ${refused} were refused.` : `${copies} Your app created 1 ${singular2}, and all ${COPIES} responses name it.`
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
};
|
|
835
|
+
|
|
836
|
+
// src/checks/replay/key-cross-route.ts
|
|
837
|
+
var keyCrossRoute = {
|
|
838
|
+
name: "key-cross-route",
|
|
839
|
+
pack: "replay",
|
|
840
|
+
creates: 2,
|
|
841
|
+
promise: "A key used on one route means nothing on another.",
|
|
842
|
+
consequence: "An update can come back with the saved answer of an older, unrelated request, and change nothing.",
|
|
843
|
+
question: "if a key from one route leaks into another",
|
|
844
|
+
needs(resource) {
|
|
845
|
+
const reason = needsKeyedCreate(resource);
|
|
846
|
+
if (reason) return reason;
|
|
847
|
+
if (!resource.update) return `This check sends the key to a second route. Give the ${resource.name} resource an update route and it runs.`;
|
|
848
|
+
return null;
|
|
849
|
+
},
|
|
850
|
+
async run(ctx) {
|
|
851
|
+
const { resource, owner, client } = ctx;
|
|
852
|
+
const { singular: singular2 } = resource;
|
|
853
|
+
const update = resource.update;
|
|
854
|
+
const before = await snapshot(ctx, owner);
|
|
855
|
+
const key = ctx.marker + "-route";
|
|
856
|
+
const first = await client.send(keyed(resource, createReq(ctx, owner), key));
|
|
857
|
+
const keyedId = createdId(ctx, first);
|
|
858
|
+
first.note = keyedId ? `created ${keyedId} with the key` : "the keyed create";
|
|
859
|
+
const plain = await client.send(createReq(ctx, owner));
|
|
860
|
+
const plainId = createdId(ctx, plain);
|
|
861
|
+
plain.note = plainId ? `created ${plainId} with no key` : "the second create";
|
|
862
|
+
await newRecords(ctx, owner, before, [keyedId, plainId]);
|
|
863
|
+
if (!keyedId || !plainId) return { verdict: "warning", summary: "Your app refused a create request, so this check proves nothing." };
|
|
864
|
+
const patch = await client.send(keyed(resource, { actor: owner, method: update.method, path: update.path.replace(":id", encodeURIComponent(plainId)), body: update.body ?? {} }, key));
|
|
865
|
+
const answeredId = ok(patch) ? idOf(ctx, patch.response.body) : null;
|
|
866
|
+
const leaked = answeredId === keyedId;
|
|
867
|
+
patch.note = leaked ? `answered with ${keyedId}, the saved response of the create` : `answered ${patch.response?.status ?? "nothing"}`;
|
|
868
|
+
const story = `We created one ${singular2} with a key, then sent that key with an update of a different ${singular2}.`;
|
|
869
|
+
const facts = [{ label: "The record in the answer to the update", expected: plainId, actual: answeredId ?? String(patch.response?.status ?? "no answer") }];
|
|
870
|
+
if (leaked) {
|
|
871
|
+
return {
|
|
872
|
+
verdict: "fail",
|
|
873
|
+
facts,
|
|
874
|
+
summary: `${story} Your app answered the update with the first ${singular2}.`,
|
|
875
|
+
fixPrompt: `My backend shares idempotency keys across routes. A test sent ${resource.create.method} ${resource.create.path} with the ${keyName(resource)}, then sent ${update.method} ${update.path} for a different ${singular2} with the same key. The backend answered the update with the saved response of the create.
|
|
876
|
+
|
|
877
|
+
Make the key lookup the user id, the HTTP method and the route together with the key. A key saved for one route must never match a request to another route.`
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
return { verdict: "pass", facts, summary: `${story} Your app did not return the first ${singular2}.` };
|
|
881
|
+
}
|
|
882
|
+
};
|
|
883
|
+
|
|
884
|
+
// src/checks/replay/key-cross-user.ts
|
|
885
|
+
var keyCrossUser = {
|
|
886
|
+
name: "key-cross-user",
|
|
887
|
+
pack: "replay",
|
|
888
|
+
creates: 2,
|
|
889
|
+
promise: "One user's key never returns another user's response.",
|
|
890
|
+
consequence: "A user who sends another user's key gets that user's order back.",
|
|
891
|
+
question: "if one user's key returns another user's response",
|
|
892
|
+
needs(resource, model) {
|
|
893
|
+
if (!model.other) return "This check needs two users. Add a second actor to the config.";
|
|
894
|
+
return needsKeyedCreate(resource);
|
|
895
|
+
},
|
|
896
|
+
async run(ctx) {
|
|
897
|
+
const { resource, owner, client } = ctx;
|
|
898
|
+
const other = ctx.other;
|
|
899
|
+
const { singular: singular2 } = resource;
|
|
900
|
+
const before = await snapshot(ctx, owner);
|
|
901
|
+
const req = keyed(resource, createReq(ctx, owner), ctx.marker + "-shared");
|
|
902
|
+
const mine = await client.send({ ...req });
|
|
903
|
+
const myId = createdId(ctx, mine);
|
|
904
|
+
mine.note = myId ? `${owner} created ${myId}` : "the first request";
|
|
905
|
+
const theirs = await client.send({ ...req, actor: other });
|
|
906
|
+
const theirId = createdId(ctx, theirs);
|
|
907
|
+
const leaked = !!myId && theirId === myId;
|
|
908
|
+
theirs.note = !ok(theirs) ? `refused with ${theirs.response?.status ?? "no answer"}` : leaked ? `${other} got ${myId}, the ${singular2} of ${owner}` : `${other} created ${theirId}, their own ${singular2}`;
|
|
909
|
+
await newRecords(ctx, owner, before, [myId]);
|
|
910
|
+
if (theirId && !leaked) ctx.track(other, theirId);
|
|
911
|
+
const story = `${cap(owner)} sent one ${singular2} with a key. ${cap(other)} sent the same request with the same key.`;
|
|
912
|
+
const facts = [{ label: `What ${other} gets back`, expected: `${an(singular2)} of their own, or a refusal`, actual: leaked ? `${myId}, which belongs to ${owner}` : theirId ?? String(theirs.response?.status ?? "no answer") }];
|
|
913
|
+
if (!myId) return { verdict: "warning", facts, summary: `Your app refused the first create request with ${mine.response?.status ?? "no answer"}, so this check proves nothing.` };
|
|
914
|
+
if (leaked) {
|
|
915
|
+
return {
|
|
916
|
+
verdict: "fail",
|
|
917
|
+
facts,
|
|
918
|
+
summary: `${story} Your app answered ${other} with the ${singular2} of ${owner}.`,
|
|
919
|
+
fixPrompt: `My backend returns one user's saved response to a different user who sends the same idempotency key. A test created ${an(singular2)} as one user with the ${keyName(resource)}, then sent the same request and key as a second user. The second user got the first user's ${singular2} back.
|
|
920
|
+
|
|
921
|
+
The key store uses the key alone as its lookup. Make the lookup the user id together with the key, with the user id taken from the verified session. Two users who send the same key must get two separate entries.`
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
return { verdict: "pass", facts, summary: `${story} ${cap(other)} ${theirId ? `got a new ${singular2} of their own` : `was refused with ${theirs.response?.status ?? "no answer"}`}, and saw nothing of ${owner}.` };
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
|
|
928
|
+
// src/checks/replay/key-reuse.ts
|
|
929
|
+
var keyReuse = {
|
|
930
|
+
name: "key-reuse",
|
|
931
|
+
pack: "replay",
|
|
932
|
+
creates: 2,
|
|
933
|
+
promise: "A used key cannot carry a different order.",
|
|
934
|
+
consequence: "A customer who changes their order and submits again is told it worked, and gets the old order.",
|
|
935
|
+
question: "if a used key can carry a different order",
|
|
936
|
+
needs(resource) {
|
|
937
|
+
const reason = needsKeyedCreate(resource);
|
|
938
|
+
if (reason) return reason;
|
|
939
|
+
if (!resource.markerField && !resource.update?.body) {
|
|
940
|
+
return `badday needs a way to make a second, different ${resource.singular}. Name a markerField for ${resource.name}, or give the update route a body.`;
|
|
941
|
+
}
|
|
942
|
+
return null;
|
|
943
|
+
},
|
|
944
|
+
async run(ctx) {
|
|
945
|
+
const { resource, owner, client } = ctx;
|
|
946
|
+
const { name, singular: singular2 } = resource;
|
|
947
|
+
const before = await snapshot(ctx, owner);
|
|
948
|
+
const key = ctx.marker + "-reuse";
|
|
949
|
+
const first = await client.send(keyed(resource, createReq(ctx, owner), key));
|
|
950
|
+
const firstId = createdId(ctx, first);
|
|
951
|
+
first.note = firstId ? `created ${firstId}` : "the first request";
|
|
952
|
+
const changed = createReq(ctx, owner);
|
|
953
|
+
changed.body = withFields(resource, changed.body, recordFields(resource, resource.update?.body));
|
|
954
|
+
const second = await client.send(keyed(resource, changed, key));
|
|
955
|
+
const secondId = createdId(ctx, second);
|
|
956
|
+
second.note = !ok(second) ? `refused with ${second.response?.status ?? "no answer"}` : secondId === firstId ? `answered ${second.response.status} with ${firstId}, the first ${singular2}` : `created ${secondId}, a new ${singular2}`;
|
|
957
|
+
const created = await newRecords(ctx, owner, before, [firstId, secondId]);
|
|
958
|
+
const story = `We sent one ${singular2}, then a different ${singular2} under the same key.`;
|
|
959
|
+
const facts = [
|
|
960
|
+
{ label: "The answer to a used key with a different body", expected: "a 4xx refusal", actual: String(second.response?.status ?? "no answer") },
|
|
961
|
+
{ label: `${cap(name)} created`, expected: "1", actual: String(created.length) }
|
|
962
|
+
];
|
|
963
|
+
if (!ok(first)) return { verdict: "warning", facts, summary: `Your app refused the first create request with ${first.response?.status ?? "no answer"}, so this check proves nothing.` };
|
|
964
|
+
if (ok(second)) {
|
|
965
|
+
return {
|
|
966
|
+
verdict: "fail",
|
|
967
|
+
facts,
|
|
968
|
+
summary: secondId === firstId ? `${story} Your app answered ${second.response.status} with the first ${singular2}. The client believes its new ${singular2} went through, and it did not.` : `${story} Your app created a second ${singular2} under the used key.`,
|
|
969
|
+
fixPrompt: `My backend accepts a reused idempotency key with a different request body. A test sent ${resource.create.method} ${resource.create.path} with the ${keyName(resource)}, then sent a different body with the same key. The backend answered ${second.response.status}. It must refuse the second request with 422 and create nothing.
|
|
970
|
+
|
|
971
|
+
Store a hash of the request body next to the key. When a request arrives with a known key, compare the hashes. If they are equal, return the saved response. If they differ, answer 422 with a message that says the key was used with a different request.`
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
if (!second.response || second.response.status >= 500) {
|
|
975
|
+
return { verdict: "warning", facts, title: "A used key with a different order gets a server error.", summary: `${story} Your app answered ${second.response?.status ?? "nothing"}. It created nothing new, and a 4xx with a clear message is the right answer.` };
|
|
976
|
+
}
|
|
977
|
+
if (created.length !== 1) return { verdict: "warning", facts, summary: `${story} Your app refused the second one, and the list shows ${created.length} new ${name}. badday cannot tell what happened.` };
|
|
978
|
+
return { verdict: "pass", facts, summary: `${story} Your app answered ${second.response.status} and created nothing new.` };
|
|
979
|
+
}
|
|
980
|
+
};
|
|
981
|
+
|
|
982
|
+
// src/checks/replay/keyless-duplicate.ts
|
|
983
|
+
var GAP_MS = 50;
|
|
984
|
+
var keylessDuplicate = {
|
|
985
|
+
name: "keyless-duplicate",
|
|
986
|
+
pack: "replay",
|
|
987
|
+
creates: 2,
|
|
988
|
+
promise: "Two identical orders with no key, moments apart, are handled as your config says.",
|
|
989
|
+
consequence: "A request that is sent twice with no key creates two orders, and your config says duplicates are not allowed.",
|
|
990
|
+
question: "if two identical requests with no key create two records",
|
|
991
|
+
needs(resource) {
|
|
992
|
+
return resource.create ? null : `Your config gives the ${resource.name} resource no create route. Add one and this check runs.`;
|
|
993
|
+
},
|
|
994
|
+
async run(ctx) {
|
|
995
|
+
const { resource, owner, client } = ctx;
|
|
996
|
+
const { name, singular: singular2 } = resource;
|
|
997
|
+
const before = await snapshot(ctx, owner);
|
|
998
|
+
const req = createReq(ctx, owner);
|
|
999
|
+
const firstSent = client.send({ ...req });
|
|
1000
|
+
await sleep2(GAP_MS);
|
|
1001
|
+
const sent = [await firstSent, await client.send({ ...req })];
|
|
1002
|
+
const ids = sent.map((x) => createdId(ctx, x));
|
|
1003
|
+
sent.forEach((x, i) => {
|
|
1004
|
+
x.note = !ok(x) ? `refused with ${x.response?.status ?? "no answer"}` : i && ids[1] === ids[0] ? `returned ${ids[1]} again` : `created ${ids[i]}`;
|
|
1005
|
+
});
|
|
1006
|
+
const created = await newRecords(ctx, owner, before, ids);
|
|
1007
|
+
const story = `We sent 2 identical ${name} ${GAP_MS} ms apart with no idempotency key.`;
|
|
1008
|
+
const rule = resource.duplicates;
|
|
1009
|
+
const facts = [{
|
|
1010
|
+
label: `${cap(name)} created by 2 identical requests with no key`,
|
|
1011
|
+
expected: rule === "forbidden" ? "1" : rule === "allowed" ? "1 or 2" : "the config does not say",
|
|
1012
|
+
actual: String(created.length)
|
|
1013
|
+
}];
|
|
1014
|
+
if (!sent.some(ok)) return { verdict: "warning", facts, summary: `${story} Your app refused both, so this check proves nothing.` };
|
|
1015
|
+
if (created.length < 2) return { verdict: "pass", facts, title: "Two identical orders with no key, moments apart, create one order.", summary: `${story} Your app created ${created.length}.` };
|
|
1016
|
+
if (rule === "allowed") return { verdict: "pass", facts, summary: `${story} Your app created 2, and your config says duplicates are legal.` };
|
|
1017
|
+
if (rule === "forbidden") {
|
|
1018
|
+
return {
|
|
1019
|
+
verdict: "fail",
|
|
1020
|
+
facts,
|
|
1021
|
+
summary: `${story} Your app created 2.`,
|
|
1022
|
+
fixPrompt: `My backend creates two ${name} when a client sends the same request twice within ${GAP_MS} ms and sends no idempotency key. Duplicates are not legal for ${name}.
|
|
1023
|
+
|
|
1024
|
+
Reject or merge a repeat on the server. Either require an idempotency key on ${resource.create.method} ${resource.create.path} and answer 400 when it is missing, or treat the same body from the same user within a few seconds as a retry and return the first ${singular2}.`
|
|
1025
|
+
};
|
|
1026
|
+
}
|
|
1027
|
+
return {
|
|
1028
|
+
verdict: "warning",
|
|
1029
|
+
facts,
|
|
1030
|
+
title: "Two identical orders with no key both went through.",
|
|
1031
|
+
summary: `${story} Your app created 2. That is right if a user can make the same thing twice on purpose, and wrong if the second request was a retry. Set duplicates to "allowed" or "forbidden" for ${name} in the config, and this becomes a pass or a fail.`
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
};
|
|
1035
|
+
|
|
1036
|
+
// src/checks/replay/retry-in-flight.ts
|
|
1037
|
+
var retryInFlight = {
|
|
1038
|
+
name: "retry-in-flight",
|
|
1039
|
+
pack: "replay",
|
|
1040
|
+
creates: 2,
|
|
1041
|
+
promise: "A retry that arrives while the first request still runs creates no second order.",
|
|
1042
|
+
consequence: "An impatient retry, sent while the first request still runs, charges the customer twice.",
|
|
1043
|
+
question: "if a retry during a running request charges a customer twice",
|
|
1044
|
+
needs: needsSlowCreate,
|
|
1045
|
+
async run(ctx) {
|
|
1046
|
+
const { resource, owner, client } = ctx;
|
|
1047
|
+
const { name, singular: singular2 } = resource;
|
|
1048
|
+
const slow = resource.create.slow;
|
|
1049
|
+
const gap = Math.round(slow.ms / 3);
|
|
1050
|
+
const before = await snapshot(ctx, owner);
|
|
1051
|
+
const req = keyed(resource, createReq(ctx, owner), ctx.marker + "-flight");
|
|
1052
|
+
req.body = withFields(resource, req.body, slow.body);
|
|
1053
|
+
const running = client.send({ ...req });
|
|
1054
|
+
await sleep2(gap);
|
|
1055
|
+
const sent = [await client.send({ ...req }), await running].reverse();
|
|
1056
|
+
const ids = sent.map((x) => createdId(ctx, x));
|
|
1057
|
+
sent.forEach((x, i) => {
|
|
1058
|
+
const who = i ? "the retry" : "the first request";
|
|
1059
|
+
x.note = ok(x) ? `${who} got ${ids[i]}` : `${who} was refused with ${x.response?.status ?? "no answer"}`;
|
|
1060
|
+
});
|
|
1061
|
+
const created = await newRecords(ctx, owner, before, ids);
|
|
1062
|
+
const story = `We sent a create request and, ${gap} ms later while it still ran, the same request with the same key.`;
|
|
1063
|
+
const facts = [{ label: `${cap(name)} created by a request and its early retry`, expected: "1", actual: String(created.length) }];
|
|
1064
|
+
if (created.length > 1) {
|
|
1065
|
+
return {
|
|
1066
|
+
verdict: "fail",
|
|
1067
|
+
facts,
|
|
1068
|
+
summary: `${story} Your app created ${created.length} ${name}.`,
|
|
1069
|
+
fixPrompt: `My backend creates a second ${singular2} when a retry arrives while the first request is still running. A test sent ${resource.create.method} ${resource.create.path} with the ${keyName(resource)} and sent it again ${gap} ms later with the same key. The backend created ${created.length} ${name}. It must create 1.
|
|
1070
|
+
|
|
1071
|
+
The key is saved only after the work is done, so the retry finds no key. Insert the key first, in a column with a unique constraint, with the state "in progress". A second request that hits the constraint must answer 409, or wait for the first one and return its response.`
|
|
1072
|
+
};
|
|
1073
|
+
}
|
|
1074
|
+
if (created.length === 0) return { verdict: "warning", facts, summary: `${story} No new ${singular2} shows in the list. badday cannot tell what happened.` };
|
|
1075
|
+
if (sent.some((x) => !x.response || x.response.status >= 500)) return { verdict: "warning", facts, title: "A retry during a running request gets a server error.", summary: `${story} Your app created 1 ${singular2}, and one of the two requests got a server error or no answer.` };
|
|
1076
|
+
return { verdict: "pass", facts, summary: `${story} Your app created 1 ${singular2}. The retry got ${sent[1].response.status}.` };
|
|
1077
|
+
}
|
|
1078
|
+
};
|
|
1079
|
+
|
|
1080
|
+
// src/checks/replay/retry-later.ts
|
|
1081
|
+
var WAIT_MS = 1e3;
|
|
1082
|
+
var retryLater = {
|
|
1083
|
+
name: "retry-later",
|
|
1084
|
+
pack: "replay",
|
|
1085
|
+
creates: 2,
|
|
1086
|
+
promise: "A retry of a finished request gets the first answer back.",
|
|
1087
|
+
consequence: "A customer whose app retries a payment a second later is charged again.",
|
|
1088
|
+
question: "if a late retry charges a customer again",
|
|
1089
|
+
needs: needsKeyedCreate,
|
|
1090
|
+
async run(ctx) {
|
|
1091
|
+
const { resource, owner, client } = ctx;
|
|
1092
|
+
const { name, singular: singular2 } = resource;
|
|
1093
|
+
const before = await snapshot(ctx, owner);
|
|
1094
|
+
const req = keyed(resource, createReq(ctx, owner), ctx.marker + "-later");
|
|
1095
|
+
const first = await client.send({ ...req });
|
|
1096
|
+
const firstId = createdId(ctx, first);
|
|
1097
|
+
first.note = firstId ? `created ${firstId}` : "the first request";
|
|
1098
|
+
await sleep2(WAIT_MS);
|
|
1099
|
+
const second = await client.send({ ...req });
|
|
1100
|
+
const secondId = createdId(ctx, second);
|
|
1101
|
+
second.note = !ok(second) ? `refused with ${second.response?.status ?? "no answer"}` : secondId === firstId ? `returned ${secondId} again` : `created ${secondId}, a new ${singular2}`;
|
|
1102
|
+
const created = await newRecords(ctx, owner, before, [firstId, secondId]);
|
|
1103
|
+
const story = `We sent one ${singular2}, waited ${WAIT_MS / 1e3} second and sent it again with the same key.`;
|
|
1104
|
+
const facts = [{ label: `${cap(name)} created by one request and its retry`, expected: "1", actual: String(created.length) }];
|
|
1105
|
+
if (!ok(first)) return { verdict: "warning", facts, summary: `Your app refused the first create request with ${first.response?.status ?? "no answer"}, so this check proves nothing. Check the create route and its body in the config.` };
|
|
1106
|
+
if (created.length > 1) {
|
|
1107
|
+
return {
|
|
1108
|
+
verdict: "fail",
|
|
1109
|
+
facts,
|
|
1110
|
+
summary: `${story} Your app created ${created.length} ${name}.`,
|
|
1111
|
+
fixPrompt: `My backend creates a second ${singular2} when a client retries a request that already finished. A test sent ${resource.create.method} ${resource.create.path} with the ${keyName(resource)}, waited ${WAIT_MS / 1e3} second and sent the same request with the same key. The backend created ${created.length} ${name}. It must create 1 and answer the retry with the first response.
|
|
1112
|
+
|
|
1113
|
+
The likely cause is a key store that forgets too soon, such as a cache with a short expiry, or a key that is never saved after the insert.
|
|
1114
|
+
|
|
1115
|
+
Save the key in the database in the same transaction as the ${singular2}, with the response status and body. Keep keys for at least 24 hours. On a retry, look the key up first and return the saved response.`
|
|
1116
|
+
};
|
|
1117
|
+
}
|
|
1118
|
+
if (!ok(second)) {
|
|
1119
|
+
return { verdict: "warning", facts, title: "A retry of a finished request gets an error, though the first request worked.", summary: `${story} Your app created 1 ${singular2} and answered the retry with ${second.response?.status ?? "no answer"}. A client that retries then reports a failure for a payment that went through.` };
|
|
1120
|
+
}
|
|
1121
|
+
if (created.length !== 1 || secondId !== firstId) {
|
|
1122
|
+
return { verdict: "warning", facts, summary: `${story} The list shows ${created.length} new ${name} and the retry named ${secondId ?? "no id"}, not ${firstId}. badday cannot tell what happened.` };
|
|
1123
|
+
}
|
|
1124
|
+
return { verdict: "pass", facts, summary: `${story} 1 ${singular2} exists, and both responses name it.` };
|
|
1125
|
+
}
|
|
1126
|
+
};
|
|
1127
|
+
|
|
1128
|
+
// src/engine/webhook.ts
|
|
1129
|
+
import { createHmac as createHmac2 } from "node:crypto";
|
|
1130
|
+
var counter2 = 0;
|
|
1131
|
+
function effectList(model, webhook) {
|
|
1132
|
+
const { list: list2, resource } = webhook.effect ?? {};
|
|
1133
|
+
if (list2) {
|
|
1134
|
+
const spec = typeof list2 === "string" ? { path: list2 } : list2;
|
|
1135
|
+
return { spec, name: resource ?? spec.path.split("?")[0].split("/").filter(Boolean).pop() ?? "effects" };
|
|
1136
|
+
}
|
|
1137
|
+
const named2 = model.resources.find((r) => r.name === resource);
|
|
1138
|
+
return named2?.list ? { spec: named2.list, name: named2.name } : null;
|
|
1139
|
+
}
|
|
1140
|
+
function needsWebhook(resource, model, webhook) {
|
|
1141
|
+
if (!webhook) return "Your config describes no webhook. Add one under webhooks and this check runs.";
|
|
1142
|
+
if (!resource.create) return `The webhook event points at the ${resource.name} resource, which has no create route in your config. Add one and this check runs.`;
|
|
1143
|
+
if (!effectList(model, webhook)) return 'badday counts what an event did by reading a list. Give the webhook an effect with a list route, such as { list: "/payments" }.';
|
|
1144
|
+
return null;
|
|
1145
|
+
}
|
|
1146
|
+
function effectName(ctx) {
|
|
1147
|
+
const { name } = effectList(ctx.model, ctx.webhook);
|
|
1148
|
+
return name.endsWith("s") ? name.slice(0, -1) : name;
|
|
1149
|
+
}
|
|
1150
|
+
function eventFor(ctx, recordId, change = {}) {
|
|
1151
|
+
const fill = (value) => {
|
|
1152
|
+
if (typeof value === "string") return /^\$\w+\.id$/.test(value) ? recordId : value;
|
|
1153
|
+
if (Array.isArray(value)) return value.map(fill);
|
|
1154
|
+
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, fill(v)]));
|
|
1155
|
+
return value;
|
|
1156
|
+
};
|
|
1157
|
+
return { id: `evt_${ctx.marker}_${++counter2}`, ...fill(ctx.webhook.event), ...change };
|
|
1158
|
+
}
|
|
1159
|
+
function sign(webhook, raw, opts = {}) {
|
|
1160
|
+
const { scheme, header } = webhook.signing;
|
|
1161
|
+
const secret = opts.secret ?? webhook.signing.secret;
|
|
1162
|
+
if (scheme === "stripe") {
|
|
1163
|
+
const t = opts.timestamp ?? Math.floor(Date.now() / 1e3);
|
|
1164
|
+
return { [header ?? "Stripe-Signature"]: `t=${t},v1=${createHmac2("sha256", secret).update(t + "." + raw).digest("hex")}` };
|
|
1165
|
+
}
|
|
1166
|
+
return { [header ?? "X-Signature"]: createHmac2("sha256", secret).update(raw).digest("hex") };
|
|
1167
|
+
}
|
|
1168
|
+
var delivery = (ctx, raw, headers, note) => ({ actor: null, method: "POST", path: ctx.webhook.path, rawBody: raw, headers: { "Content-Type": "application/json", ...headers }, note });
|
|
1169
|
+
var deliver = (ctx, raw, headers, note) => ctx.client.send(delivery(ctx, raw, headers, note));
|
|
1170
|
+
async function effects(ctx, recordId, note) {
|
|
1171
|
+
const { spec, name } = effectList(ctx.model, ctx.webhook);
|
|
1172
|
+
if (ctx.webhook.effect.settleMs) await sleep2(ctx.webhook.effect.settleMs);
|
|
1173
|
+
const rows = await walk(ctx, ctx.owner, spec, name, { note });
|
|
1174
|
+
return rows.filter((row) => JSON.stringify(row).includes(JSON.stringify(recordId))).length;
|
|
1175
|
+
}
|
|
1176
|
+
function rejectionCheck(spec) {
|
|
1177
|
+
return {
|
|
1178
|
+
name: spec.name,
|
|
1179
|
+
pack: "webhooks",
|
|
1180
|
+
scope: "webhook",
|
|
1181
|
+
creates: 2,
|
|
1182
|
+
promise: spec.promise,
|
|
1183
|
+
consequence: spec.consequence,
|
|
1184
|
+
question: spec.question,
|
|
1185
|
+
needs(resource, model, webhook) {
|
|
1186
|
+
const reason = needsWebhook(resource, model, webhook);
|
|
1187
|
+
if (reason) return reason;
|
|
1188
|
+
if (spec.stripeOnly && webhook.signing.scheme !== "stripe") {
|
|
1189
|
+
return "The webhook in your config uses plain HMAC signing, which carries no timestamp. This check needs the Stripe signing scheme.";
|
|
1190
|
+
}
|
|
1191
|
+
return null;
|
|
1192
|
+
},
|
|
1193
|
+
async run(ctx) {
|
|
1194
|
+
const webhook = ctx.webhook;
|
|
1195
|
+
const thing = effectName(ctx);
|
|
1196
|
+
const target = await createOne(ctx, ctx.owner, { quiet: true });
|
|
1197
|
+
const control = await createOne(ctx, ctx.owner, { quiet: true });
|
|
1198
|
+
const forged = spec.forge(webhook, eventFor(ctx, target.id));
|
|
1199
|
+
const bad = await deliver(ctx, forged.raw, forged.headers, spec.what);
|
|
1200
|
+
const applied = await effects(ctx, target.id, `the ${thing}s for ${target.id}`);
|
|
1201
|
+
bad.note = `${spec.what}, ${ok(bad) ? "accepted" : "refused"} with ${statusOf(bad)}`;
|
|
1202
|
+
const raw = JSON.stringify(eventFor(ctx, control.id));
|
|
1203
|
+
const good = await deliver(ctx, raw, sign(webhook, raw), "a correct event for a second record, as the control");
|
|
1204
|
+
const controlApplied = await effects(ctx, control.id, `the ${thing}s for ${control.id}`);
|
|
1205
|
+
const facts = [
|
|
1206
|
+
{ label: `The answer to ${spec.what}`, expected: "a refusal", actual: statusOf(bad) },
|
|
1207
|
+
{ label: `${thing[0].toUpperCase() + thing.slice(1)}s it caused`, expected: "0", actual: String(applied) }
|
|
1208
|
+
];
|
|
1209
|
+
if (!ok(good) || controlApplied === 0) {
|
|
1210
|
+
return { verdict: "warning", facts, summary: `Your app also turned away a correctly signed event (${statusOf(good)}, ${controlApplied} ${thing}s), so its answer to ${spec.what} proves nothing. Check the signing scheme and the secret in the config.` };
|
|
1211
|
+
}
|
|
1212
|
+
if (applied > 0) {
|
|
1213
|
+
return {
|
|
1214
|
+
verdict: "fail",
|
|
1215
|
+
facts,
|
|
1216
|
+
summary: `We sent ${spec.what}. Your app answered ${statusOf(bad)} and recorded ${applied === 1 ? `${an(thing)}` : `${applied} ${thing}s`}.`,
|
|
1217
|
+
fixPrompt: `My webhook route POST ${webhook.path} accepts ${spec.what}. A test sent one and the backend recorded ${an(thing)} for it. It must answer 400 or 401 and change nothing.
|
|
1218
|
+
|
|
1219
|
+
${spec.remedy}`
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
if (ok(bad)) {
|
|
1223
|
+
return { verdict: "warning", facts, title: `The webhook answers with success to ${spec.what}.`, summary: `We sent ${spec.what}. Your app answered ${statusOf(bad)} and recorded no ${thing}. A refusal with 400 or 401 is the right answer, so the sender learns the event was not accepted.` };
|
|
1224
|
+
}
|
|
1225
|
+
return { verdict: "pass", facts, summary: `We sent ${spec.what}. Your app answered ${statusOf(bad)} and recorded no ${thing}.` };
|
|
1226
|
+
}
|
|
1227
|
+
};
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
// src/checks/webhooks/webhook-bad-signature.ts
|
|
1231
|
+
var webhookBadSignature = rejectionCheck({
|
|
1232
|
+
name: "webhook-bad-signature",
|
|
1233
|
+
promise: "An event with a wrong signature is rejected.",
|
|
1234
|
+
consequence: "Anyone who knows the webhook address can send a fake payment event, and your app believes it.",
|
|
1235
|
+
question: "if an event with a wrong signature is accepted",
|
|
1236
|
+
what: "an event with a wrong signature",
|
|
1237
|
+
forge(webhook, event) {
|
|
1238
|
+
const raw = JSON.stringify(event);
|
|
1239
|
+
return { raw, headers: sign(webhook, raw, { secret: "not-the-secret" }) };
|
|
1240
|
+
},
|
|
1241
|
+
remedy: "Verify the signature before any other work. Compute the HMAC of the raw request body with the webhook secret, compare it to the signature header with a constant-time comparison, and refuse the request when they differ. Use the raw bytes of the body, not a parsed and re-serialised copy."
|
|
1242
|
+
});
|
|
1243
|
+
|
|
1244
|
+
// src/checks/webhooks/webhook-burst.ts
|
|
1245
|
+
var COPIES2 = 5;
|
|
1246
|
+
var webhookBurst = {
|
|
1247
|
+
name: "webhook-burst",
|
|
1248
|
+
pack: "webhooks",
|
|
1249
|
+
scope: "webhook",
|
|
1250
|
+
creates: 1,
|
|
1251
|
+
promise: "5 copies of one event at the same instant are applied once.",
|
|
1252
|
+
consequence: "Copies of one event that arrive at the same instant are each recorded as a payment.",
|
|
1253
|
+
question: "if copies of one event that arrive together are all applied",
|
|
1254
|
+
needs: needsWebhook,
|
|
1255
|
+
async run(ctx) {
|
|
1256
|
+
const webhook = ctx.webhook;
|
|
1257
|
+
const thing = effectName(ctx);
|
|
1258
|
+
const record2 = await createOne(ctx, ctx.owner, { quiet: true });
|
|
1259
|
+
const raw = JSON.stringify(eventFor(ctx, record2.id));
|
|
1260
|
+
const request = delivery(ctx, raw, sign(webhook, raw));
|
|
1261
|
+
const sent = await ctx.client.burst(Array.from({ length: COPIES2 }, () => ({ ...request })));
|
|
1262
|
+
sent.forEach((x, i) => {
|
|
1263
|
+
x.note = `delivery ${i + 1} of ${COPIES2}, answered ${statusOf(x)}`;
|
|
1264
|
+
});
|
|
1265
|
+
const applied = await effects(ctx, record2.id, `the ${thing}s for ${record2.id}`);
|
|
1266
|
+
const story = `We delivered ${COPIES2} copies of one signed event at the same instant.`;
|
|
1267
|
+
const facts = [{ label: `${cap(thing)}s recorded for one event, delivered ${COPIES2} times`, expected: "1", actual: String(applied) }];
|
|
1268
|
+
if (applied > 1) {
|
|
1269
|
+
return {
|
|
1270
|
+
verdict: "fail",
|
|
1271
|
+
facts,
|
|
1272
|
+
summary: `${story} Your app recorded ${applied} ${thing}s.`,
|
|
1273
|
+
fixPrompt: `My webhook route POST ${webhook.path} applies the same event more than once. A test delivered one signed event ${COPIES2} times webhook-burst0, and the backend recorded ${applied} ${thing}s. It must record 1. Payment providers deliver an event again whenever they are not sure the first delivery arrived.
|
|
1274
|
+
|
|
1275
|
+
Save the id of each event in a table with a unique constraint, in the same transaction as the work the event causes. If the insert of the id hits the constraint, answer 200 and do nothing else. A lookup followed by an insert is not enough, because two deliveries can pass the lookup together.`
|
|
1276
|
+
};
|
|
1277
|
+
}
|
|
1278
|
+
if (applied === 0) {
|
|
1279
|
+
return { verdict: "warning", facts, summary: `${story} Your app recorded no ${thing} at all (${[...new Set(sent.map(statusOf))].join(", ")}), so this check proves nothing. Check the signing scheme, the secret and the event in the config.` };
|
|
1280
|
+
}
|
|
1281
|
+
if (sent.some(crashed)) {
|
|
1282
|
+
return { verdict: "warning", facts, title: "A repeated webhook event is applied once, and a delivery gets a server error.", summary: `${story} Your app recorded 1 ${thing}, and ${sent.filter(crashed).length} of the deliveries got a server error. The sender will keep retrying those.` };
|
|
1283
|
+
}
|
|
1284
|
+
return { verdict: "pass", facts, summary: `${story} Your app recorded 1 ${thing}${sent.every(ok) ? " and answered every delivery with success" : ""}.` };
|
|
1285
|
+
}
|
|
1286
|
+
};
|
|
1287
|
+
|
|
1288
|
+
// src/checks/webhooks/webhook-no-signature.ts
|
|
1289
|
+
var webhookNoSignature = rejectionCheck({
|
|
1290
|
+
name: "webhook-no-signature",
|
|
1291
|
+
promise: "An event with no signature is rejected.",
|
|
1292
|
+
consequence: "An event with no signature at all is accepted as a real payment.",
|
|
1293
|
+
question: "if an event with no signature is accepted",
|
|
1294
|
+
what: "an event with no signature",
|
|
1295
|
+
forge: (_webhook, event) => ({ raw: JSON.stringify(event), headers: {} }),
|
|
1296
|
+
remedy: "The code skips verification when the signature header is absent. Treat a missing header as a failed verification and refuse the request."
|
|
1297
|
+
});
|
|
1298
|
+
|
|
1299
|
+
// src/checks/webhooks/webhook-redelivery.ts
|
|
1300
|
+
var COPIES3 = 3;
|
|
1301
|
+
var webhookRedelivery = {
|
|
1302
|
+
name: "webhook-redelivery",
|
|
1303
|
+
pack: "webhooks",
|
|
1304
|
+
scope: "webhook",
|
|
1305
|
+
creates: 1,
|
|
1306
|
+
promise: "An event delivered 3 times is applied once.",
|
|
1307
|
+
consequence: "When your payment provider delivers an event again, the payment is recorded again.",
|
|
1308
|
+
question: "if a redelivered event is applied again",
|
|
1309
|
+
needs: needsWebhook,
|
|
1310
|
+
async run(ctx) {
|
|
1311
|
+
const webhook = ctx.webhook;
|
|
1312
|
+
const thing = effectName(ctx);
|
|
1313
|
+
const record2 = await createOne(ctx, ctx.owner, { quiet: true });
|
|
1314
|
+
const raw = JSON.stringify(eventFor(ctx, record2.id));
|
|
1315
|
+
const request = delivery(ctx, raw, sign(webhook, raw));
|
|
1316
|
+
const sent = [];
|
|
1317
|
+
for (let i = 0; i < COPIES3; i++) sent.push(await ctx.client.send({ ...request }));
|
|
1318
|
+
sent.forEach((x, i) => {
|
|
1319
|
+
x.note = `delivery ${i + 1} of ${COPIES3}, answered ${statusOf(x)}`;
|
|
1320
|
+
});
|
|
1321
|
+
const applied = await effects(ctx, record2.id, `the ${thing}s for ${record2.id}`);
|
|
1322
|
+
const story = `We delivered one signed event ${COPIES3} times in a row.`;
|
|
1323
|
+
const facts = [{ label: `${cap(thing)}s recorded for one event, delivered ${COPIES3} times`, expected: "1", actual: String(applied) }];
|
|
1324
|
+
if (applied > 1) {
|
|
1325
|
+
return {
|
|
1326
|
+
verdict: "fail",
|
|
1327
|
+
facts,
|
|
1328
|
+
summary: `${story} Your app recorded ${applied} ${thing}s.`,
|
|
1329
|
+
fixPrompt: `My webhook route POST ${webhook.path} applies the same event more than once. A test delivered one signed event ${COPIES3} times webhook-redelivery0, and the backend recorded ${applied} ${thing}s. It must record 1. Payment providers deliver an event again whenever they are not sure the first delivery arrived.
|
|
1330
|
+
|
|
1331
|
+
Save the id of each event in a table with a unique constraint, in the same transaction as the work the event causes. If the insert of the id hits the constraint, answer 200 and do nothing else. A lookup followed by an insert is not enough, because two deliveries can pass the lookup together.`
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
if (applied === 0) {
|
|
1335
|
+
return { verdict: "warning", facts, summary: `${story} Your app recorded no ${thing} at all (${[...new Set(sent.map(statusOf))].join(", ")}), so this check proves nothing. Check the signing scheme, the secret and the event in the config.` };
|
|
1336
|
+
}
|
|
1337
|
+
if (sent.some(crashed)) {
|
|
1338
|
+
return { verdict: "warning", facts, title: "A repeated webhook event is applied once, and a delivery gets a server error.", summary: `${story} Your app recorded 1 ${thing}, and ${sent.filter(crashed).length} of the deliveries got a server error. The sender will keep retrying those.` };
|
|
1339
|
+
}
|
|
1340
|
+
return { verdict: "pass", facts, summary: `${story} Your app recorded 1 ${thing}${sent.every(ok) ? " and answered every delivery with success" : ""}.` };
|
|
1341
|
+
}
|
|
1342
|
+
};
|
|
1343
|
+
|
|
1344
|
+
// src/checks/webhooks/webhook-stale-timestamp.ts
|
|
1345
|
+
var AGE_S = 3600;
|
|
1346
|
+
var webhookStaleTimestamp = rejectionCheck({
|
|
1347
|
+
name: "webhook-stale-timestamp",
|
|
1348
|
+
promise: "A correctly signed event that is an hour old is rejected.",
|
|
1349
|
+
consequence: "Someone who captures one real event can replay it an hour later, and your app accepts it.",
|
|
1350
|
+
question: "if an old event can be replayed an hour later",
|
|
1351
|
+
what: "a correctly signed event with a timestamp 1 hour old",
|
|
1352
|
+
stripeOnly: true,
|
|
1353
|
+
forge(webhook, event) {
|
|
1354
|
+
const raw = JSON.stringify(event);
|
|
1355
|
+
return { raw, headers: sign(webhook, raw, { timestamp: Math.floor(Date.now() / 1e3) - AGE_S }) };
|
|
1356
|
+
},
|
|
1357
|
+
remedy: "The signature is valid, so the code must also read the timestamp in the signature header. Refuse any event whose timestamp is more than 5 minutes from the current time."
|
|
1358
|
+
});
|
|
1359
|
+
|
|
1360
|
+
// src/checks/webhooks/webhook-tampered-body.ts
|
|
1361
|
+
var webhookTamperedBody = rejectionCheck({
|
|
1362
|
+
name: "webhook-tampered-body",
|
|
1363
|
+
promise: "An event whose body changed after signing is rejected.",
|
|
1364
|
+
consequence: "Someone can change the content of a real event, such as its amount, and your app still accepts it.",
|
|
1365
|
+
question: "if an event that was changed after signing is accepted",
|
|
1366
|
+
what: "a signed event whose body was changed after signing",
|
|
1367
|
+
forge(webhook, event) {
|
|
1368
|
+
const headers = sign(webhook, JSON.stringify(event));
|
|
1369
|
+
return { raw: JSON.stringify({ ...event, changedAfterSigning: true }), headers };
|
|
1370
|
+
},
|
|
1371
|
+
remedy: "The signature must cover the exact bytes of the request body. Compute the HMAC over the raw body as it arrived, and refuse the request when it does not match the header."
|
|
1372
|
+
});
|
|
1373
|
+
|
|
1374
|
+
// src/checks/webhooks/webhook-unknown-type.ts
|
|
1375
|
+
var UNKNOWN = "badday.unknown";
|
|
1376
|
+
var webhookUnknownType = {
|
|
1377
|
+
name: "webhook-unknown-type",
|
|
1378
|
+
pack: "webhooks",
|
|
1379
|
+
scope: "webhook",
|
|
1380
|
+
creates: 1,
|
|
1381
|
+
promise: "An event of an unknown type gets a 2xx and changes nothing.",
|
|
1382
|
+
consequence: "An event of a type your app does not know makes the webhook fail, and the provider retries it for days.",
|
|
1383
|
+
question: "if an event of an unknown type breaks the webhook",
|
|
1384
|
+
needs(resource, model, webhook) {
|
|
1385
|
+
const reason = needsWebhook(resource, model, webhook);
|
|
1386
|
+
if (reason) return reason;
|
|
1387
|
+
return typeof webhook.event.type === "string" ? null : "The event in your config has no type field, so badday cannot send one of an unknown type.";
|
|
1388
|
+
},
|
|
1389
|
+
async run(ctx) {
|
|
1390
|
+
const webhook = ctx.webhook;
|
|
1391
|
+
const thing = effectName(ctx);
|
|
1392
|
+
const record2 = await createOne(ctx, ctx.owner, { quiet: true });
|
|
1393
|
+
const raw = JSON.stringify(eventFor(ctx, record2.id, { type: UNKNOWN }));
|
|
1394
|
+
const sent = await deliver(ctx, raw, sign(webhook, raw), `a signed event of the type ${UNKNOWN}`);
|
|
1395
|
+
const applied = await effects(ctx, record2.id, `the ${thing}s for ${record2.id}`);
|
|
1396
|
+
const story = `We sent a correctly signed event of the type ${UNKNOWN}.`;
|
|
1397
|
+
const facts = [
|
|
1398
|
+
{ label: "The answer to an event of an unknown type", expected: "2xx", actual: statusOf(sent) },
|
|
1399
|
+
{ label: `${cap(thing)}s it caused`, expected: "0", actual: String(applied) }
|
|
1400
|
+
];
|
|
1401
|
+
if (crashed(sent) || applied > 0) {
|
|
1402
|
+
return {
|
|
1403
|
+
verdict: "fail",
|
|
1404
|
+
facts,
|
|
1405
|
+
title: applied > 0 && !crashed(sent) ? `An event of an unknown type is applied as if it were ${an(thing)}.` : void 0,
|
|
1406
|
+
summary: `${story} Your app answered ${statusOf(sent)} and recorded ${applied} ${thing}s.`,
|
|
1407
|
+
fixPrompt: `My webhook route POST ${webhook.path} does not handle an event type it does not know. A test sent a correctly signed event of the type "${UNKNOWN}" and the backend answered ${statusOf(sent)}. Providers add event types over time, and they retry every delivery that does not get a 2xx.
|
|
1408
|
+
|
|
1409
|
+
Verify the signature first. Then look the event type up in the set of types the code handles. For any other type, answer 200 and do nothing.`
|
|
1410
|
+
};
|
|
1411
|
+
}
|
|
1412
|
+
if (!ok(sent)) {
|
|
1413
|
+
return { verdict: "warning", facts, title: "An event of an unknown type is refused, so the provider will keep sending it.", summary: `${story} Your app answered ${statusOf(sent)} and changed nothing. Answer 200 for types you do not handle, or the provider retries the event and may disable the webhook.` };
|
|
1414
|
+
}
|
|
1415
|
+
return { verdict: "pass", facts, summary: `${story} Your app answered ${statusOf(sent)} and recorded nothing.` };
|
|
1416
|
+
}
|
|
1417
|
+
};
|
|
1418
|
+
|
|
1419
|
+
// src/checks/input/body-too-large.ts
|
|
1420
|
+
var SIZE = 10 * 1024 * 1024;
|
|
1421
|
+
var bodyTooLarge = {
|
|
1422
|
+
name: "body-too-large",
|
|
1423
|
+
pack: "input",
|
|
1424
|
+
creates: 2,
|
|
1425
|
+
promise: "A 10 MB body is refused, and the server stays up.",
|
|
1426
|
+
consequence: "Your app reads a 10 MB request body into memory, so a few large requests can take it down.",
|
|
1427
|
+
question: "if a 10 MB body is accepted",
|
|
1428
|
+
needs(resource) {
|
|
1429
|
+
return resource.create ? null : `Your config gives the ${resource.name} resource no create route. Add one and this check runs.`;
|
|
1430
|
+
},
|
|
1431
|
+
async run(ctx) {
|
|
1432
|
+
const { resource, owner, client } = ctx;
|
|
1433
|
+
const big = createReq(ctx, owner, { note: "a create request with 10 MB of padding", timeoutMs: 3e4 });
|
|
1434
|
+
big.rawBody = JSON.stringify(withFields(resource, big.body, { padding: "x".repeat(SIZE) }));
|
|
1435
|
+
big.headers = { ...big.headers, "Content-Type": "application/json" };
|
|
1436
|
+
delete big.body;
|
|
1437
|
+
const sent = await client.send(big);
|
|
1438
|
+
const bigId = createdId(ctx, sent);
|
|
1439
|
+
if (bigId) ctx.track(owner, bigId);
|
|
1440
|
+
const after = await client.send(createReq(ctx, owner, { note: "a normal request, to see if the server is still up" }));
|
|
1441
|
+
const afterId = createdId(ctx, after);
|
|
1442
|
+
if (afterId) ctx.track(owner, afterId);
|
|
1443
|
+
const facts = [
|
|
1444
|
+
{ label: "The answer to a 10 MB body", expected: "413", actual: statusOf(sent) },
|
|
1445
|
+
{ label: "A normal request afterwards", expected: "works", actual: ok(after) ? "works" : statusOf(after) }
|
|
1446
|
+
];
|
|
1447
|
+
const remedy = `Set a limit on the request body, at the web server or in the body parser, and answer 413 above it. Pick the limit from the largest body a real client sends to ${resource.create.method} ${resource.create.path}, with some room. 100 kB is plenty for most JSON routes.`;
|
|
1448
|
+
if (!ok(after)) {
|
|
1449
|
+
return { verdict: "fail", facts, title: "One 10 MB request stops your app from answering.", summary: `We sent a create request with a 10 MB body. Your app answered ${statusOf(sent)}, and a normal request right after it got ${statusOf(after)}.`, fixPrompt: `My backend stops answering after one request with a 10 MB body.
|
|
1450
|
+
|
|
1451
|
+
${remedy}` };
|
|
1452
|
+
}
|
|
1453
|
+
if (!sent.response && !/no response in/.test(sent.error ?? "")) {
|
|
1454
|
+
return { verdict: "pass", facts, summary: "We sent a create request with a 10 MB body. Your app closed the connection without reading it, and a normal request right after it worked. An answer of 413 tells the client more." };
|
|
1455
|
+
}
|
|
1456
|
+
if (ok(sent) || crashed(sent)) {
|
|
1457
|
+
return {
|
|
1458
|
+
verdict: "fail",
|
|
1459
|
+
facts,
|
|
1460
|
+
summary: `We sent a create request with a 10 MB body. Your app ${ok(sent) ? `accepted it with ${statusOf(sent)}` : `read all of it and answered ${statusOf(sent)}`}.`,
|
|
1461
|
+
fixPrompt: `My backend accepts a request body of any size. A test sent ${resource.create.method} ${resource.create.path} with a 10 MB body and the backend answered ${statusOf(sent)}. It must answer 413 and keep none of the body in memory.
|
|
1462
|
+
|
|
1463
|
+
${remedy}`
|
|
1464
|
+
};
|
|
1465
|
+
}
|
|
1466
|
+
if (sent.response.status !== 413) {
|
|
1467
|
+
const slow = sent.response.ms > 1e3 ? ` It took ${Math.round(sent.response.ms)} ms to answer, which suggests it read the whole body first.` : "";
|
|
1468
|
+
return {
|
|
1469
|
+
verdict: "warning",
|
|
1470
|
+
facts,
|
|
1471
|
+
title: "A 10 MB body is refused, but not for its size.",
|
|
1472
|
+
summary: `We sent a create request with a 10 MB JSON body. Your app refused it with ${statusOf(sent)} and kept answering. That status does not say the body was too large, so badday cannot tell if your app has a size limit or read all 10 MB and then rejected a field.${slow} A backend with a limit answers 413.`
|
|
1473
|
+
};
|
|
1474
|
+
}
|
|
1475
|
+
return { verdict: "pass", facts, summary: "We sent a create request with a 10 MB body. Your app answered 413, and a normal request right after it worked." };
|
|
1476
|
+
}
|
|
1477
|
+
};
|
|
1478
|
+
|
|
1479
|
+
// src/checks/input/broken-json.ts
|
|
1480
|
+
var brokenJson = {
|
|
1481
|
+
name: "broken-json",
|
|
1482
|
+
pack: "input",
|
|
1483
|
+
creates: 0,
|
|
1484
|
+
promise: "Broken JSON gets a 400, not a 500.",
|
|
1485
|
+
consequence: "A request with broken JSON crashes the route with a server error.",
|
|
1486
|
+
question: "if broken JSON crashes a route",
|
|
1487
|
+
needs(resource) {
|
|
1488
|
+
return resource.create ? null : `Your config gives the ${resource.name} resource no create route. Add one and this check runs.`;
|
|
1489
|
+
},
|
|
1490
|
+
async run(ctx) {
|
|
1491
|
+
const { create } = ctx.resource;
|
|
1492
|
+
const raw = JSON.stringify(create.body ?? {}).slice(0, -1) + ', "cut": ';
|
|
1493
|
+
const sent = await ctx.client.send({ actor: ctx.owner, method: create.method, path: create.path, rawBody: raw, headers: { "Content-Type": "application/json" }, note: "a JSON body that breaks off in the middle" });
|
|
1494
|
+
const id2 = createdId(ctx, sent);
|
|
1495
|
+
if (id2) ctx.track(ctx.owner, id2);
|
|
1496
|
+
const facts = [{ label: "The answer to broken JSON", expected: "400", actual: statusOf(sent) }];
|
|
1497
|
+
const story = "We sent a create request whose JSON breaks off in the middle.";
|
|
1498
|
+
if (crashed(sent)) {
|
|
1499
|
+
return {
|
|
1500
|
+
verdict: "fail",
|
|
1501
|
+
facts,
|
|
1502
|
+
summary: `${story} Your app answered ${statusOf(sent)}.`,
|
|
1503
|
+
fixPrompt: `My backend answers ${statusOf(sent)} when a request body is not valid JSON. A test sent ${create.method} ${create.path} with a body that breaks off in the middle. It must answer 400.
|
|
1504
|
+
|
|
1505
|
+
Catch the parse error of the body, in the body parser or in an error handler that runs for every route, and answer 400 with a short message. A 500 must mean a fault in the server, never a fault in the request.`
|
|
1506
|
+
};
|
|
1507
|
+
}
|
|
1508
|
+
if (ok(sent)) return { verdict: "warning", facts, title: "Broken JSON is accepted as if it were a valid request.", summary: `${story} Your app answered ${statusOf(sent)}. badday cannot tell what it stored.` };
|
|
1509
|
+
return { verdict: "pass", facts, summary: `${story} Your app answered ${statusOf(sent)}.` };
|
|
1510
|
+
}
|
|
1511
|
+
};
|
|
1512
|
+
|
|
1513
|
+
// src/engine/access.ts
|
|
1514
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
1515
|
+
function needsTwoUsers(resource, model, route3) {
|
|
1516
|
+
if (!model.other) return "This check needs two users. Add a second actor to the config.";
|
|
1517
|
+
if (!resource.create) return `Your config gives the ${resource.name} resource no create route. Add one and this check runs.`;
|
|
1518
|
+
if (!resource[route3]) return `Your config gives the ${resource.name} resource no ${route3} route. Add one and this check runs.`;
|
|
1519
|
+
if (route3 === "get" || route3 === "list") return sharedByDesign(resource, route3);
|
|
1520
|
+
return null;
|
|
1521
|
+
}
|
|
1522
|
+
function sharedByDesign(resource, route3) {
|
|
1523
|
+
if (!resource.shared.includes(route3)) return null;
|
|
1524
|
+
const who = resource.public.includes(route3) ? "anyone" : "every logged-in user";
|
|
1525
|
+
return `Your config says ${who} may ${route3 === "list" ? `list all ${resource.name}` : `read any ${resource.singular} by its id`}, so one user seeing the ${resource.name} of another is not a defect here.`;
|
|
1526
|
+
}
|
|
1527
|
+
async function readAs(ctx, actor, id2, note) {
|
|
1528
|
+
const sent = await ctx.client.send({ actor, method: "GET", path: withId(ctx.resource.get, id2), note });
|
|
1529
|
+
return ok(sent) ? recordOf(ctx, sent.response.body) ?? sent.response.body : null;
|
|
1530
|
+
}
|
|
1531
|
+
function lockedRoutesCheck(spec) {
|
|
1532
|
+
return {
|
|
1533
|
+
name: spec.name,
|
|
1534
|
+
pack: "access",
|
|
1535
|
+
creates: 2,
|
|
1536
|
+
promise: spec.promise,
|
|
1537
|
+
consequence: spec.consequence,
|
|
1538
|
+
question: spec.question,
|
|
1539
|
+
needs: (resource) => {
|
|
1540
|
+
const guarded = ["list", "get"].filter((r) => resource[r] && !resource.public.includes(r));
|
|
1541
|
+
if (guarded.length || resource.create || resource.update || resource.remove) return null;
|
|
1542
|
+
return `Your config says every route of ${resource.name} is public, so no route is left that must refuse.`;
|
|
1543
|
+
},
|
|
1544
|
+
async run(ctx) {
|
|
1545
|
+
const { resource, owner, client } = ctx;
|
|
1546
|
+
const headers = spec.headers(ctx.model);
|
|
1547
|
+
const record2 = resource.create ? await createOne(ctx, owner, { quiet: true }) : null;
|
|
1548
|
+
const probes = [];
|
|
1549
|
+
if (resource.list && !resource.public.includes("list")) probes.push({ method: "GET", path: resource.list.path });
|
|
1550
|
+
if (resource.get && record2 && !resource.public.includes("get")) probes.push({ method: "GET", path: withId(resource.get, record2.id) });
|
|
1551
|
+
if (resource.create) probes.push({ ...createReq(ctx, null), actor: null });
|
|
1552
|
+
if (resource.update && record2) probes.push({ method: resource.update.method, path: withId(resource.update.path, record2.id), body: resource.update.body ?? {} });
|
|
1553
|
+
if (resource.remove && record2) probes.push({ method: resource.remove.method, path: withId(resource.remove.path, record2.id) });
|
|
1554
|
+
const open = [];
|
|
1555
|
+
const broke = [];
|
|
1556
|
+
for (const probe2 of probes) {
|
|
1557
|
+
const sent = await client.send({ ...probe2, actor: null, headers });
|
|
1558
|
+
const label = `${probe2.method} ${probe2.path.replace(record2?.id ?? "\0", ":id")}`;
|
|
1559
|
+
sent.note = ok(sent) ? `answered ${statusOf(sent)} with ${spec.what}` : `refused with ${statusOf(sent)}`;
|
|
1560
|
+
if (ok(sent)) open.push(label);
|
|
1561
|
+
else if (crashed(sent)) broke.push(label);
|
|
1562
|
+
const strayId = probe2.method === resource.create?.method && probe2.path === resource.create?.path ? createdId(ctx, sent) : null;
|
|
1563
|
+
if (strayId) ctx.track(owner, strayId);
|
|
1564
|
+
}
|
|
1565
|
+
const facts = [{ label: `Routes that answer a request with ${spec.what}, of ${probes.length}`, expected: "0", actual: String(open.length) }];
|
|
1566
|
+
const story = `We called the ${probes.length} configured routes of ${resource.name} with ${spec.what}.`;
|
|
1567
|
+
if (open.length) {
|
|
1568
|
+
return {
|
|
1569
|
+
verdict: "fail",
|
|
1570
|
+
facts,
|
|
1571
|
+
summary: `${story} ${open.length} answered with success: ${open.join(", ")}.`,
|
|
1572
|
+
fixPrompt: `My backend answers requests that carry ${spec.what}. A test called every route of ${resource.name}, and these answered with success: ${open.join(", ")}. Each one must answer 401.
|
|
1573
|
+
|
|
1574
|
+
${spec.remedy}`
|
|
1575
|
+
};
|
|
1576
|
+
}
|
|
1577
|
+
if (broke.length) return { verdict: "warning", facts, title: `A request with ${spec.what} gets a server error.`, summary: `${story} None answered with success, and ${broke.join(", ")} answered with a server error. 401 is the right answer.` };
|
|
1578
|
+
return { verdict: "pass", facts, summary: `${story} Every one refused.` };
|
|
1579
|
+
}
|
|
1580
|
+
};
|
|
1581
|
+
}
|
|
1582
|
+
function garbageHeaders(model) {
|
|
1583
|
+
const fake = "badday-" + randomBytes2(12).toString("hex");
|
|
1584
|
+
return Object.fromEntries(Object.entries(model.actors[model.owner].headers).map(([name, value]) => {
|
|
1585
|
+
const scheme = value.match(/^(\w+) /);
|
|
1586
|
+
return [name, scheme ? scheme[1] + " " + fake : fake];
|
|
1587
|
+
}));
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
// src/checks/input/cursor-cross-user.ts
|
|
1591
|
+
var cursorCrossUser = {
|
|
1592
|
+
name: "cursor-cross-user",
|
|
1593
|
+
pack: "input",
|
|
1594
|
+
creates: 3,
|
|
1595
|
+
promise: "One user cannot page through another user's records with that user's cursor.",
|
|
1596
|
+
consequence: "A user who gets hold of another user's page cursor can read that user's records with it.",
|
|
1597
|
+
question: "if one user's cursor shows their records to another user",
|
|
1598
|
+
needs(resource, model) {
|
|
1599
|
+
if (!model.other) return "This check needs two users. Add a second actor to the config.";
|
|
1600
|
+
return needsCursor(resource) ?? sharedByDesign(resource, "list");
|
|
1601
|
+
},
|
|
1602
|
+
async run(ctx) {
|
|
1603
|
+
const { resource, owner } = ctx;
|
|
1604
|
+
const other = ctx.other;
|
|
1605
|
+
const spec = resource.list;
|
|
1606
|
+
const real = await realCursor(ctx, owner);
|
|
1607
|
+
if (!real) return { verdict: "not-configured", summary: NO_CURSOR };
|
|
1608
|
+
const params = { [spec.cursorParam ?? "cursor"]: real.cursor, ...spec.limitParam ? { [spec.limitParam]: String(spec.maxLimit ?? 100) } : {} };
|
|
1609
|
+
const sent = await ctx.client.send({ actor: other, method: "GET", path: listPath(spec, params) });
|
|
1610
|
+
const rows = pageOf(sent, spec, resource.name)?.rows ?? [];
|
|
1611
|
+
const leaked = rows.map((row) => idOf(ctx, row)).filter((id2) => id2 && real.ids.includes(id2));
|
|
1612
|
+
sent.note = leaked.length ? `${other} sends the cursor of ${owner} and gets ${leaked.join(", ")}` : `${other} sends the cursor of ${owner}, answered ${statusOf(sent)}`;
|
|
1613
|
+
const story = `${cap(owner)} created 3 ${resource.name} and read a page, which came with a cursor. ${cap(other)} sent that cursor.`;
|
|
1614
|
+
const facts = [{ label: `Records of ${owner} in the page ${other} got`, expected: "0", actual: String(leaked.length) }];
|
|
1615
|
+
if (leaked.length) {
|
|
1616
|
+
return {
|
|
1617
|
+
verdict: "fail",
|
|
1618
|
+
facts,
|
|
1619
|
+
summary: `${story} The page held ${leaked.length} of the ${resource.name} of ${owner}.`,
|
|
1620
|
+
fixPrompt: `My list route GET ${spec.path} trusts what is inside the page cursor. A test took a cursor from one user and sent it as a second user, and the page held the first user's ${resource.name}.
|
|
1621
|
+
|
|
1622
|
+
The cursor must hold a position only, such as the last id or timestamp. Filter every page by the user id of the verified session, never by anything inside the cursor. If the cursor must carry more, sign it and reject one whose signature fails.`
|
|
1623
|
+
};
|
|
1624
|
+
}
|
|
1625
|
+
return { verdict: "pass", facts, summary: `${story} The page held none of the ${resource.name} of ${owner}.` };
|
|
1626
|
+
}
|
|
1627
|
+
};
|
|
1628
|
+
|
|
1629
|
+
// src/checks/input/cursor-garbage.ts
|
|
1630
|
+
import { randomBytes as randomBytes3 } from "node:crypto";
|
|
1631
|
+
var cursorGarbage = {
|
|
1632
|
+
name: "cursor-garbage",
|
|
1633
|
+
pack: "input",
|
|
1634
|
+
creates: 3,
|
|
1635
|
+
promise: "A cursor of random bytes gets a 400, not a crash.",
|
|
1636
|
+
consequence: "A made-up page cursor crashes your list route.",
|
|
1637
|
+
question: "if a made-up cursor crashes the list",
|
|
1638
|
+
needs: needsCursor,
|
|
1639
|
+
async run(ctx) {
|
|
1640
|
+
const spec = ctx.resource.list;
|
|
1641
|
+
if (!await realCursor(ctx, ctx.owner)) return { verdict: "not-configured", summary: NO_CURSOR };
|
|
1642
|
+
const garbage = randomBytes3(24).toString("base64url");
|
|
1643
|
+
const sent = await ctx.client.send({ actor: ctx.owner, method: "GET", path: listPath(spec, { [spec.cursorParam ?? "cursor"]: garbage }), note: "a cursor of 24 random bytes" });
|
|
1644
|
+
const facts = [{ label: "The answer to a cursor of random bytes", expected: "400", actual: statusOf(sent) }];
|
|
1645
|
+
if (crashed(sent)) {
|
|
1646
|
+
return {
|
|
1647
|
+
verdict: "fail",
|
|
1648
|
+
facts,
|
|
1649
|
+
summary: `We asked for the list with a cursor of random bytes. Your app answered ${statusOf(sent)}.`,
|
|
1650
|
+
fixPrompt: `My list route GET ${spec.path} crashes on a bad cursor. A test sent a cursor of random bytes and the backend answered ${statusOf(sent)}. It must answer 400.
|
|
1651
|
+
|
|
1652
|
+
Wrap the decoding of the cursor in error handling. If the cursor does not decode, or does not hold the fields the code expects with the right types, answer 400 with a short message. Never pass a decoded cursor to the database before it is validated.`
|
|
1653
|
+
};
|
|
1654
|
+
}
|
|
1655
|
+
if (ok(sent)) return { verdict: "warning", facts, title: "A cursor of random bytes is accepted without an error.", summary: `We asked for the list with a cursor of random bytes. Your app answered ${statusOf(sent)} with a page. A client with a damaged cursor then reads the wrong page and never learns it.` };
|
|
1656
|
+
return { verdict: "pass", facts, summary: `We asked for the list with a cursor of random bytes. Your app answered ${statusOf(sent)}.` };
|
|
1657
|
+
}
|
|
1658
|
+
};
|
|
1659
|
+
|
|
1660
|
+
// src/checks/input/cursor-truncated.ts
|
|
1661
|
+
var cursorTruncated = {
|
|
1662
|
+
name: "cursor-truncated",
|
|
1663
|
+
pack: "input",
|
|
1664
|
+
creates: 3,
|
|
1665
|
+
promise: "A damaged cursor gets a 400.",
|
|
1666
|
+
consequence: "A page cursor that lost its last characters, as happens with a cut-off link, crashes your list route.",
|
|
1667
|
+
question: "if a damaged cursor crashes the list",
|
|
1668
|
+
needs: needsCursor,
|
|
1669
|
+
async run(ctx) {
|
|
1670
|
+
const spec = ctx.resource.list;
|
|
1671
|
+
const real = await realCursor(ctx, ctx.owner);
|
|
1672
|
+
if (!real) return { verdict: "not-configured", summary: NO_CURSOR };
|
|
1673
|
+
const sent = await ctx.client.send({ actor: ctx.owner, method: "GET", path: listPath(spec, { [spec.cursorParam ?? "cursor"]: real.cursor.slice(0, -4) }), note: "the real cursor with its last 4 characters removed" });
|
|
1674
|
+
const story = "We took a real cursor, removed its last 4 characters and asked for that page.";
|
|
1675
|
+
const facts = [{ label: "The answer to a cursor with 4 characters missing", expected: "400", actual: statusOf(sent) }];
|
|
1676
|
+
if (crashed(sent)) {
|
|
1677
|
+
return {
|
|
1678
|
+
verdict: "fail",
|
|
1679
|
+
facts,
|
|
1680
|
+
summary: `${story} Your app answered ${statusOf(sent)}.`,
|
|
1681
|
+
fixPrompt: `My list route GET ${spec.path} crashes on a damaged cursor. A test removed the last 4 characters of a real cursor and the backend answered ${statusOf(sent)}. It must answer 400.
|
|
1682
|
+
|
|
1683
|
+
Wrap the decoding of the cursor in error handling and validate the decoded value. Answer 400 when the cursor does not decode or a field is missing.`
|
|
1684
|
+
};
|
|
1685
|
+
}
|
|
1686
|
+
if (ok(sent)) return { verdict: "warning", facts, title: "A damaged cursor is accepted without an error.", summary: `${story} Your app answered ${statusOf(sent)} with a page, and the client cannot know it is the wrong one.` };
|
|
1687
|
+
return { verdict: "pass", facts, summary: `${story} Your app answered ${statusOf(sent)}.` };
|
|
1688
|
+
}
|
|
1689
|
+
};
|
|
1690
|
+
|
|
1691
|
+
// src/checks/input/error-leak.ts
|
|
1692
|
+
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
1693
|
+
var LEAKS = [
|
|
1694
|
+
["a stack trace", /\bat [\w$.<> ]+ \(?[^\s()]+:\d+:\d+\)?|Traceback \(most recent call last\)|\.(java|kt|go|rb|php|cs):\d+\b|goroutine \d+ \[/],
|
|
1695
|
+
["a file path", /(?:\/(?:home|usr|var|app|srv|opt|workspace|Users)\/[\w.@-]+\/[\w./@-]+)|(?:[A-Z]:\\\\?[\w.-]+\\\\?[\w\\.-]+)|node_modules\//],
|
|
1696
|
+
["SQL text", /\b(?:SELECT\b.{1,200}\bFROM|INSERT INTO|UPDATE\b.{1,100}\bSET|DELETE FROM)\b|syntax error at or near|SQLSTATE|ORA-\d{5}|sqlite3?\.|psycopg|PG::/i]
|
|
1697
|
+
];
|
|
1698
|
+
var errorLeak = {
|
|
1699
|
+
name: "error-leak",
|
|
1700
|
+
pack: "input",
|
|
1701
|
+
creates: 0,
|
|
1702
|
+
promise: "Error responses carry no stack trace, SQL or file path.",
|
|
1703
|
+
consequence: "Your error responses show the inside of your server, such as stack traces and file paths, to anyone who sends a bad request.",
|
|
1704
|
+
question: "if error responses show the inside of your server",
|
|
1705
|
+
needs(resource) {
|
|
1706
|
+
return resource.create || resource.list ? null : `Your config gives the ${resource.name} resource no create route and no list route, so badday has nothing to provoke an error with.`;
|
|
1707
|
+
},
|
|
1708
|
+
async run(ctx) {
|
|
1709
|
+
const { create, list: list2, get: get2 } = ctx.resource;
|
|
1710
|
+
const actor = ctx.owner;
|
|
1711
|
+
const probes = [];
|
|
1712
|
+
if (create) {
|
|
1713
|
+
probes.push(
|
|
1714
|
+
{ actor, method: create.method, path: create.path, rawBody: '{"cut": ', headers: { "Content-Type": "application/json" }, note: "broken JSON" },
|
|
1715
|
+
{ actor, method: create.method, path: create.path, rawBody: "[]", headers: { "Content-Type": "application/json" }, note: "an array where an object belongs" },
|
|
1716
|
+
{ actor, method: create.method, path: create.path, body: Object.fromEntries(Object.keys(create.body ?? {}).map((k) => [k, { nested: [null] }])), note: "every field with the wrong type" }
|
|
1717
|
+
);
|
|
1718
|
+
}
|
|
1719
|
+
if (list2) {
|
|
1720
|
+
probes.push({ actor, method: "GET", path: listPath(list2, { [list2.cursorParam ?? "cursor"]: randomBytes4(18).toString("base64url") }), note: "a cursor of random bytes" });
|
|
1721
|
+
if (list2.limitParam) probes.push({ actor, method: "GET", path: listPath(list2, { [list2.limitParam]: "abc" }), note: "a page size that is not a number" });
|
|
1722
|
+
}
|
|
1723
|
+
if (get2) probes.push({ actor, method: "GET", path: get2.replace(":id", "%27%22%3B--%00"), note: "an id made of quote characters" });
|
|
1724
|
+
const found = [];
|
|
1725
|
+
let errors = 0;
|
|
1726
|
+
let leaking = 0;
|
|
1727
|
+
for (const probe2 of probes) {
|
|
1728
|
+
const sent = await ctx.client.send(probe2);
|
|
1729
|
+
if (!sent.response || ok(sent)) continue;
|
|
1730
|
+
errors++;
|
|
1731
|
+
const kinds3 = LEAKS.filter(([, pattern]) => pattern.test(sent.response.text)).map(([kind]) => kind);
|
|
1732
|
+
if (kinds3.length) {
|
|
1733
|
+
sent.note += `. The ${sent.response.status} response holds ${kinds3.join(" and ")}`;
|
|
1734
|
+
found.push(...kinds3);
|
|
1735
|
+
leaking++;
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
const kinds2 = [...new Set(found)];
|
|
1739
|
+
const facts = [{ label: `Error responses that show server internals, of ${errors}`, expected: "0", actual: String(leaking) }];
|
|
1740
|
+
if (!errors) return { verdict: "warning", facts, summary: `We sent ${probes.length} bad requests and your app answered none of them with an error, so there was no error response to read.` };
|
|
1741
|
+
if (kinds2.length) {
|
|
1742
|
+
return {
|
|
1743
|
+
verdict: "fail",
|
|
1744
|
+
facts,
|
|
1745
|
+
summary: `We sent ${probes.length} bad requests and read the ${errors} error responses. They hold ${kinds2.join(" and ")}.`,
|
|
1746
|
+
fixPrompt: `My backend sends internal details to the client in its error responses. A test sent ${probes.length} bad requests, and the error responses held ${kinds2.join(" and ")}.
|
|
1747
|
+
|
|
1748
|
+
Add one error handler that every route passes through. It logs the full error on the server and sends the client a short fixed message with a status code, and an error id to quote in a support request. Turn off the debug or development error page of the framework in production.`
|
|
1749
|
+
};
|
|
1750
|
+
}
|
|
1751
|
+
return { verdict: "pass", facts, summary: `We sent ${probes.length} bad requests and read the ${errors} error responses. None held a stack trace, SQL text or a file path.` };
|
|
1752
|
+
}
|
|
1753
|
+
};
|
|
1754
|
+
|
|
1755
|
+
// src/checks/input/limit-huge.ts
|
|
1756
|
+
var DEFAULT_MAX = 100;
|
|
1757
|
+
var EXTRA = 20;
|
|
1758
|
+
var HUGE = "100000";
|
|
1759
|
+
var SMALL = 2;
|
|
1760
|
+
var SLACK = 8;
|
|
1761
|
+
var limitHuge = {
|
|
1762
|
+
name: "limit-huge",
|
|
1763
|
+
pack: "input",
|
|
1764
|
+
creates: DEFAULT_MAX + EXTRA,
|
|
1765
|
+
promise: "A request for a huge page gets a capped page.",
|
|
1766
|
+
consequence: "One request can pull your whole table in a single response.",
|
|
1767
|
+
question: "if one request can pull a whole table",
|
|
1768
|
+
needs(resource) {
|
|
1769
|
+
const reason = needsCreateAndList(resource);
|
|
1770
|
+
if (reason) return reason;
|
|
1771
|
+
return resource.list.limitParam ? null : `Your config names no limit parameter for the ${resource.name} list. Add list.limitParam, such as "limit", and this check runs.`;
|
|
1772
|
+
},
|
|
1773
|
+
async run(ctx) {
|
|
1774
|
+
const { resource, owner } = ctx;
|
|
1775
|
+
const spec = resource.list;
|
|
1776
|
+
const max = spec.maxLimit ?? DEFAULT_MAX;
|
|
1777
|
+
const count = max + EXTRA;
|
|
1778
|
+
await createMany(ctx, owner, count);
|
|
1779
|
+
const small = await ctx.client.send({ actor: owner, method: "GET", path: listPath(spec, { [spec.limitParam]: String(SMALL) }), note: `a page of ${SMALL}, to see if the list takes a page size` });
|
|
1780
|
+
const smallPage = pageOf(small, spec, resource.name);
|
|
1781
|
+
if (smallPage && smallPage.rows.length > SMALL + SLACK) {
|
|
1782
|
+
return {
|
|
1783
|
+
verdict: "warning",
|
|
1784
|
+
title: "Your list returns every record in one response.",
|
|
1785
|
+
facts: [{ label: `${cap(resource.name)} returned for ${spec.limitParam}=${SMALL}`, expected: `${SMALL}`, actual: String(smallPage.rows.length) }],
|
|
1786
|
+
summary: `We created ${count} ${resource.name} and asked for ${spec.limitParam}=${SMALL}. Your app returned ${smallPage.rows.length}, so the list does not page. That is fine for a list that stays short, and a problem for one that grows with your users. If the list pages by a different parameter, correct list.limitParam in the config.`
|
|
1787
|
+
};
|
|
1788
|
+
}
|
|
1789
|
+
const sent = await ctx.client.send({ actor: owner, method: "GET", path: listPath(spec, { [spec.limitParam]: HUGE }) });
|
|
1790
|
+
const page = pageOf(sent, spec, resource.name);
|
|
1791
|
+
if (!page) return { verdict: "warning", summary: `We created ${count} ${resource.name} and asked for ${spec.limitParam}=${HUGE}. Your app answered ${statusOf(sent)} with no list, so badday cannot tell if the page is capped.` };
|
|
1792
|
+
sent.note = `one page with ${page.rows.length} ${resource.name}`;
|
|
1793
|
+
const story = `We created ${count} ${resource.name} and asked for ${spec.limitParam}=${HUGE}.`;
|
|
1794
|
+
const facts = [{ label: `${cap(resource.name)} in one page`, expected: `${max} at most`, actual: String(page.rows.length) }];
|
|
1795
|
+
if (page.rows.length > max) {
|
|
1796
|
+
return {
|
|
1797
|
+
verdict: "fail",
|
|
1798
|
+
facts,
|
|
1799
|
+
summary: `${story} Your app returned ${page.rows.length} in one response.`,
|
|
1800
|
+
fixPrompt: `My list route GET ${spec.path} lets the client choose any page size. A test asked for ${spec.limitParam}=${HUGE} and the backend returned ${page.rows.length} ${resource.name} in one response. On a real table that is one slow query and one very large response per request, and anyone can send it.
|
|
1801
|
+
|
|
1802
|
+
Cap the page size on the server at ${max}. If the client asks for more, use ${max}. Keep returning the cursor of the next page, so a client can still read everything page by page.`
|
|
1803
|
+
};
|
|
1804
|
+
}
|
|
1805
|
+
return { verdict: "pass", facts, summary: `${story} Your app returned ${page.rows.length} in one page.` };
|
|
1806
|
+
}
|
|
1807
|
+
};
|
|
1808
|
+
|
|
1809
|
+
// src/checks/input/limit-invalid.ts
|
|
1810
|
+
var VALUES = ["-1", "0", "abc"];
|
|
1811
|
+
var limitInvalid = {
|
|
1812
|
+
name: "limit-invalid",
|
|
1813
|
+
pack: "input",
|
|
1814
|
+
creates: 0,
|
|
1815
|
+
promise: "A limit of -1, 0 or abc does not crash the list.",
|
|
1816
|
+
consequence: "A page size that is not a sensible number crashes your list route.",
|
|
1817
|
+
question: "if a bad page size crashes the list",
|
|
1818
|
+
needs(resource) {
|
|
1819
|
+
const reason = needsList(resource);
|
|
1820
|
+
if (reason) return reason;
|
|
1821
|
+
return resource.list.limitParam ? null : `Your config names no limit parameter for the ${resource.name} list. Add list.limitParam, such as "limit", and this check runs.`;
|
|
1822
|
+
},
|
|
1823
|
+
async run(ctx) {
|
|
1824
|
+
const spec = ctx.resource.list;
|
|
1825
|
+
const param = spec.limitParam;
|
|
1826
|
+
const sent = [];
|
|
1827
|
+
for (const value of VALUES) sent.push(await ctx.client.send({ actor: ctx.owner, method: "GET", path: listPath(spec, { [param]: value }), note: `${param}=${value}` }));
|
|
1828
|
+
const answers2 = sent.map((x, i) => `${param}=${VALUES[i]} got ${statusOf(x)}`).join(", ");
|
|
1829
|
+
const bad = sent.filter(crashed);
|
|
1830
|
+
const facts = sent.map((x, i) => ({ label: `The answer to ${param}=${VALUES[i]}`, expected: "400, or a normal page", actual: statusOf(x) }));
|
|
1831
|
+
if (bad.length) {
|
|
1832
|
+
return {
|
|
1833
|
+
verdict: "fail",
|
|
1834
|
+
facts,
|
|
1835
|
+
summary: `We asked for the list with three bad page sizes: ${answers2}.`,
|
|
1836
|
+
fixPrompt: `My list route GET ${spec.path} crashes on a bad ${param} parameter. A test sent ${VALUES.map((v) => param + "=" + v).join(", ")} and got: ${answers2}. None of them may answer 500.
|
|
1837
|
+
|
|
1838
|
+
Parse ${param} as a whole number before any other work. If it is not a whole number above 0, answer 400 with a short message, or use the default page size.`
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
return { verdict: "pass", facts, summary: `We asked for the list with three bad page sizes: ${answers2}.` };
|
|
1842
|
+
}
|
|
1843
|
+
};
|
|
1844
|
+
|
|
1845
|
+
// src/checks/input/list-walk-under-writes.ts
|
|
1846
|
+
var START = 30;
|
|
1847
|
+
var PAGE = 10;
|
|
1848
|
+
var PER_PAGE_WRITES = 2;
|
|
1849
|
+
var MAX_WRITES = 10;
|
|
1850
|
+
var MAX_PAGES2 = 60;
|
|
1851
|
+
var listWalkUnderWrites = {
|
|
1852
|
+
name: "list-walk-under-writes",
|
|
1853
|
+
pack: "input",
|
|
1854
|
+
creates: START + MAX_WRITES,
|
|
1855
|
+
promise: "Paging through the list while records arrive shows each record once and skips none.",
|
|
1856
|
+
consequence: "A client that pages through your list while new records arrive sees some records twice.",
|
|
1857
|
+
question: "if paging goes wrong while new records arrive",
|
|
1858
|
+
needs(resource) {
|
|
1859
|
+
const reason = needsCreateAndList(resource);
|
|
1860
|
+
if (reason) return reason;
|
|
1861
|
+
return resource.list.limitParam ? null : `Your config names no limit parameter for the ${resource.name} list, so badday cannot ask for small pages. Add list.limitParam and this check runs.`;
|
|
1862
|
+
},
|
|
1863
|
+
async run(ctx) {
|
|
1864
|
+
const { resource, owner } = ctx;
|
|
1865
|
+
const spec = resource.list;
|
|
1866
|
+
const initial = await createMany(ctx, owner, START);
|
|
1867
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1868
|
+
const step = pager(spec, PAGE);
|
|
1869
|
+
let pages = 0;
|
|
1870
|
+
let written = 0;
|
|
1871
|
+
for (; pages < MAX_PAGES2; pages++) {
|
|
1872
|
+
const sent = await ctx.client.send({ actor: owner, method: "GET", path: listPath(spec, step.params()) });
|
|
1873
|
+
const page = pageOf(sent, spec, resource.name);
|
|
1874
|
+
if (!page) throw new Error(`Page ${pages + 1} of the list answered ${statusOf(sent)}, so badday could not finish the walk`);
|
|
1875
|
+
for (const row of page.rows) {
|
|
1876
|
+
const id2 = idOf(ctx, row);
|
|
1877
|
+
if (id2) seen.set(id2, (seen.get(id2) ?? 0) + 1);
|
|
1878
|
+
}
|
|
1879
|
+
sent.note = `page ${pages + 1}, ${page.rows.length} ${resource.name}`;
|
|
1880
|
+
if (pages === 0 && page.rows.length > PAGE * 2) {
|
|
1881
|
+
return { verdict: "not-configured", summary: `Your list returned ${page.rows.length} ${resource.name} when badday asked for pages of ${PAGE}, so it does not page, and there is no paging to test. If the list pages by a different parameter, correct list.limitParam in the config.` };
|
|
1882
|
+
}
|
|
1883
|
+
if (!step.advance(page)) {
|
|
1884
|
+
pages++;
|
|
1885
|
+
break;
|
|
1886
|
+
}
|
|
1887
|
+
if (written < MAX_WRITES) {
|
|
1888
|
+
await createMany(ctx, owner, PER_PAGE_WRITES);
|
|
1889
|
+
written += PER_PAGE_WRITES;
|
|
1890
|
+
sent.note += `. Then ${PER_PAGE_WRITES} new ${resource.name} arrive`;
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
const twice = [...seen].filter(([, n]) => n > 1).map(([id2]) => id2);
|
|
1894
|
+
const skipped = initial.filter((id2) => !seen.has(id2));
|
|
1895
|
+
const story = `We created ${START} ${resource.name} and read the list in pages of ${PAGE}, while ${written} more arrived.`;
|
|
1896
|
+
const facts = [
|
|
1897
|
+
{ label: `${cap(resource.name)} that came back twice`, expected: "0", actual: String(twice.length) },
|
|
1898
|
+
{ label: `Of the first ${START}, never returned`, expected: "0", actual: String(skipped.length) }
|
|
1899
|
+
];
|
|
1900
|
+
if (pages < 2) return { verdict: "not-configured", facts, summary: `Your list returned everything in one page, though badday asked for pages of ${PAGE}. With one page there is no paging to test.` };
|
|
1901
|
+
if ((twice.length || skipped.length) && pagesByNumber(spec)) {
|
|
1902
|
+
return {
|
|
1903
|
+
verdict: "warning",
|
|
1904
|
+
facts,
|
|
1905
|
+
title: "Your list pages by number, so its pages shift while new records arrive.",
|
|
1906
|
+
summary: `${story} ${twice.length} came back twice and ${skipped.length} of the first ${START} never came back. Every list that pages by ${spec.pageParam ? "page number" : "offset"} does this when it shows the newest record first. It matters if a client must see each record once, such as an export or a sync.`
|
|
1907
|
+
};
|
|
1908
|
+
}
|
|
1909
|
+
if (twice.length || skipped.length) {
|
|
1910
|
+
return {
|
|
1911
|
+
verdict: "fail",
|
|
1912
|
+
facts,
|
|
1913
|
+
title: twice.length ? void 0 : "A client that pages through your list while new records arrive never sees some of the records.",
|
|
1914
|
+
summary: `${story} ${twice.length} came back twice and ${skipped.length} of the first ${START} never came back.`,
|
|
1915
|
+
fixPrompt: `My list route GET ${spec.path} pages by offset, so its pages shift when new ${resource.name} arrive. A test read the list page by page while new records were created. ${twice.length} records came back twice and ${skipped.length} were never returned.
|
|
1916
|
+
|
|
1917
|
+
Use keyset pagination. Sort by a column that never changes and is unique, such as the id or the creation time together with the id. The cursor holds the last value of that column on the page, and the next page is every row after it. Do not use OFFSET.`
|
|
1918
|
+
};
|
|
1919
|
+
}
|
|
1920
|
+
return { verdict: "pass", facts, summary: `${story} No record came back twice, and none of the first ${START} was missing.` };
|
|
1921
|
+
}
|
|
1922
|
+
};
|
|
1923
|
+
|
|
1924
|
+
// src/checks/access/cross-user-delete.ts
|
|
1925
|
+
var crossUserDelete = {
|
|
1926
|
+
name: "cross-user-delete",
|
|
1927
|
+
pack: "access",
|
|
1928
|
+
creates: 1,
|
|
1929
|
+
promise: "One user cannot delete another user's records.",
|
|
1930
|
+
consequence: "Any logged-in user can delete another user's records.",
|
|
1931
|
+
question: "if one user can delete another user's records",
|
|
1932
|
+
needs: (resource, model) => needsTwoUsers(resource, model, "remove"),
|
|
1933
|
+
async run(ctx) {
|
|
1934
|
+
const { resource, owner } = ctx;
|
|
1935
|
+
const other = ctx.other;
|
|
1936
|
+
const remove = resource.remove;
|
|
1937
|
+
const record2 = await createOne(ctx, owner);
|
|
1938
|
+
const sent = await ctx.client.send({ actor: other, method: remove.method, path: withId(remove.path, record2.id) });
|
|
1939
|
+
sent.note = ok(sent) ? `${other} deletes the ${resource.singular} of ${owner}` : `${other} is refused with ${statusOf(sent)}`;
|
|
1940
|
+
const gone = resource.get ? !await readAs(ctx, owner, record2.id, `${owner} looks for it afterwards`) : false;
|
|
1941
|
+
const story = `${cap(owner)} created ${an(resource.singular)}. ${cap(other)} sent a delete for it.`;
|
|
1942
|
+
const facts = [
|
|
1943
|
+
{ label: `The answer to the delete by ${other}`, expected: "403 or 404", actual: statusOf(sent) },
|
|
1944
|
+
...resource.get ? [{ label: `The ${resource.singular}, when ${owner} looks for it afterwards`, expected: "still there", actual: gone ? "gone" : "still there" }] : []
|
|
1945
|
+
];
|
|
1946
|
+
if (ok(sent) || gone) {
|
|
1947
|
+
return {
|
|
1948
|
+
verdict: "fail",
|
|
1949
|
+
facts,
|
|
1950
|
+
summary: `${story} Your app answered ${statusOf(sent)}${gone ? `, and the ${resource.singular} is gone` : ""}.`,
|
|
1951
|
+
fixPrompt: `My backend lets one user delete another user's ${resource.singular}. A test created ${an(resource.singular)} as one user, then sent ${remove.method} ${remove.path} as a second user. The backend answered ${statusOf(sent)}. It must answer 404 and delete nothing.
|
|
1952
|
+
|
|
1953
|
+
Add the owner to the query of the delete, so it matches the record by its id and by the user id of the caller. If no row matches, answer 404.`
|
|
1954
|
+
};
|
|
1955
|
+
}
|
|
1956
|
+
return { verdict: "pass", facts, summary: `${story} Your app answered ${statusOf(sent)}${resource.get ? `, and the ${resource.singular} was still there afterwards` : ""}.` };
|
|
1957
|
+
}
|
|
1958
|
+
};
|
|
1959
|
+
|
|
1960
|
+
// src/checks/access/cross-user-list.ts
|
|
1961
|
+
var COUNT = 3;
|
|
1962
|
+
var crossUserList = {
|
|
1963
|
+
name: "cross-user-list",
|
|
1964
|
+
pack: "access",
|
|
1965
|
+
creates: COUNT,
|
|
1966
|
+
promise: "One user's list shows none of another user's records.",
|
|
1967
|
+
consequence: "The list shows every user's records to any logged-in user.",
|
|
1968
|
+
question: "if the list shows one user's records to another user",
|
|
1969
|
+
needs: (resource, model) => needsTwoUsers(resource, model, "list"),
|
|
1970
|
+
async run(ctx) {
|
|
1971
|
+
const { resource, owner } = ctx;
|
|
1972
|
+
const other = ctx.other;
|
|
1973
|
+
const mine = await createMany(ctx, owner, COUNT);
|
|
1974
|
+
const listed = await listAll(ctx, other, { note: `${other} reads the list` });
|
|
1975
|
+
const leaked = mine.filter((id2) => listed.has(id2));
|
|
1976
|
+
const story = `${cap(owner)} created ${COUNT} ${resource.name}. ${cap(other)} read the whole list.`;
|
|
1977
|
+
const facts = [{ label: `${cap(resource.name)} of ${owner} in the list of ${other}`, expected: "0", actual: String(leaked.length) }];
|
|
1978
|
+
if (leaked.length) {
|
|
1979
|
+
return {
|
|
1980
|
+
verdict: "fail",
|
|
1981
|
+
facts,
|
|
1982
|
+
summary: `${story} It held ${leaked.length} of the ${COUNT}.`,
|
|
1983
|
+
fixPrompt: `My list route GET ${resource.list.path} returns records of every user. A test created ${COUNT} ${resource.name} as one user and read the list as a second user, and the list held ${leaked.length} of them.
|
|
1984
|
+
|
|
1985
|
+
Filter the list query by the user id of the caller. Take the user id from the verified session, never from a query parameter.`
|
|
1986
|
+
};
|
|
1987
|
+
}
|
|
1988
|
+
return { verdict: "pass", facts, summary: `${story} It held none of them.` };
|
|
1989
|
+
}
|
|
1990
|
+
};
|
|
1991
|
+
|
|
1992
|
+
// src/checks/access/cross-user-read.ts
|
|
1993
|
+
var crossUserRead = {
|
|
1994
|
+
name: "cross-user-read",
|
|
1995
|
+
pack: "access",
|
|
1996
|
+
creates: 1,
|
|
1997
|
+
promise: "One user cannot read another user's records.",
|
|
1998
|
+
consequence: "Any logged-in user can read another user's records by their id.",
|
|
1999
|
+
question: "if one user can read another user's records",
|
|
2000
|
+
needs: (resource, model) => needsTwoUsers(resource, model, "get"),
|
|
2001
|
+
async run(ctx) {
|
|
2002
|
+
const { resource, owner } = ctx;
|
|
2003
|
+
const other = ctx.other;
|
|
2004
|
+
const record2 = await createOne(ctx, owner);
|
|
2005
|
+
const sent = await ctx.client.send({ actor: other, method: "GET", path: withId(resource.get, record2.id) });
|
|
2006
|
+
sent.note = ok(sent) ? `${other} reads the ${resource.singular} of ${owner}` : `${other} is refused with ${statusOf(sent)}`;
|
|
2007
|
+
const story = `${cap(owner)} created ${an(resource.singular)}. ${cap(other)} asked for it by its id.`;
|
|
2008
|
+
const facts = [{ label: `${cap(other)} reads ${an(resource.singular)} of ${owner}`, expected: "403 or 404", actual: ok(sent) ? `${statusOf(sent)}, with the ${resource.singular}` : statusOf(sent) }];
|
|
2009
|
+
if (ok(sent)) {
|
|
2010
|
+
return {
|
|
2011
|
+
verdict: "fail",
|
|
2012
|
+
facts,
|
|
2013
|
+
summary: `${story} Your app answered ${statusOf(sent)} with the ${resource.singular}.`,
|
|
2014
|
+
fixPrompt: `My backend lets one user read another user's ${resource.singular}. A test created ${an(resource.singular)} as one user, then sent GET ${resource.get} as a second user with the first user's id. The backend answered ${statusOf(sent)} with the record. It must answer 404.
|
|
2015
|
+
|
|
2016
|
+
The likely cause is a lookup by id alone. Add the owner to the query, so the route looks the record up by its id and by the user id of the caller, and answers 404 when nothing matches. Take the user id from the verified session or token, never from the request. Check the update, delete and list routes for the same defect.`
|
|
2017
|
+
};
|
|
2018
|
+
}
|
|
2019
|
+
return { verdict: "pass", facts, summary: `${story} Your app answered ${statusOf(sent)}.` };
|
|
2020
|
+
}
|
|
2021
|
+
};
|
|
2022
|
+
|
|
2023
|
+
// src/checks/access/cross-user-update.ts
|
|
2024
|
+
var crossUserUpdate = {
|
|
2025
|
+
name: "cross-user-update",
|
|
2026
|
+
pack: "access",
|
|
2027
|
+
creates: 1,
|
|
2028
|
+
promise: "One user cannot change another user's records.",
|
|
2029
|
+
consequence: "Any logged-in user can change another user's records.",
|
|
2030
|
+
question: "if one user can change another user's records",
|
|
2031
|
+
needs: (resource, model) => needsTwoUsers(resource, model, "update"),
|
|
2032
|
+
async run(ctx) {
|
|
2033
|
+
const { resource, owner } = ctx;
|
|
2034
|
+
const other = ctx.other;
|
|
2035
|
+
const update = resource.update;
|
|
2036
|
+
const record2 = await createOne(ctx, owner);
|
|
2037
|
+
const before = resource.get ? await readAs(ctx, owner, record2.id, `${owner} reads it before`) : null;
|
|
2038
|
+
const sent = await ctx.client.send({ actor: other, method: update.method, path: withId(update.path, record2.id), body: update.body ?? {} });
|
|
2039
|
+
sent.note = ok(sent) ? `${other} updates the ${resource.singular} of ${owner}` : `${other} is refused with ${statusOf(sent)}`;
|
|
2040
|
+
const after = resource.get ? await readAs(ctx, owner, record2.id, `${owner} reads it after`) : null;
|
|
2041
|
+
const changed = !!before && JSON.stringify(before) !== JSON.stringify(after);
|
|
2042
|
+
const story = `${cap(owner)} created ${an(resource.singular)}. ${cap(other)} sent an update for it.`;
|
|
2043
|
+
const facts = [
|
|
2044
|
+
{ label: `The answer to the update by ${other}`, expected: "403 or 404", actual: statusOf(sent) },
|
|
2045
|
+
...before ? [{ label: `The ${resource.singular}, when ${owner} reads it afterwards`, expected: "unchanged", actual: changed ? "changed" : "unchanged" }] : []
|
|
2046
|
+
];
|
|
2047
|
+
if (ok(sent) || changed) {
|
|
2048
|
+
return {
|
|
2049
|
+
verdict: "fail",
|
|
2050
|
+
facts,
|
|
2051
|
+
summary: `${story} Your app answered ${statusOf(sent)}${changed ? `, and the ${resource.singular} changed` : ""}.`,
|
|
2052
|
+
fixPrompt: `My backend lets one user change another user's ${resource.singular}. A test created ${an(resource.singular)} as one user, then sent ${update.method} ${update.path} as a second user. The backend answered ${statusOf(sent)}. It must answer 404 and change nothing.
|
|
2053
|
+
|
|
2054
|
+
Add the owner to the query of the update, so it matches the record by its id and by the user id of the caller. If no row matches, answer 404. Take the user id from the verified session, never from the request.`
|
|
2055
|
+
};
|
|
2056
|
+
}
|
|
2057
|
+
return { verdict: "pass", facts, summary: `${story} Your app answered ${statusOf(sent)}${before ? `, and the ${resource.singular} was unchanged when ${owner} read it afterwards` : ""}.` };
|
|
2058
|
+
}
|
|
2059
|
+
};
|
|
2060
|
+
|
|
2061
|
+
// src/checks/access/garbage-token.ts
|
|
2062
|
+
var garbageToken = lockedRoutesCheck({
|
|
2063
|
+
name: "garbage-token",
|
|
2064
|
+
promise: "Every route refuses a made-up token.",
|
|
2065
|
+
consequence: "Your app accepts a token that nobody issued.",
|
|
2066
|
+
question: "if a made-up token gets through",
|
|
2067
|
+
what: "a made-up token",
|
|
2068
|
+
headers: garbageHeaders,
|
|
2069
|
+
remedy: "The code treats an unknown token as a guest or an anonymous user. Verify the token first. If the signature fails or no session matches, answer 401 and stop. Do not fall back to a default user."
|
|
2070
|
+
});
|
|
2071
|
+
|
|
2072
|
+
// src/checks/access/no-credentials.ts
|
|
2073
|
+
var noCredentials = lockedRoutesCheck({
|
|
2074
|
+
name: "no-credentials",
|
|
2075
|
+
promise: "Every route refuses a request with no credentials.",
|
|
2076
|
+
consequence: "Someone who is not logged in can use parts of your app.",
|
|
2077
|
+
question: "if a request with no credentials gets through",
|
|
2078
|
+
what: "no credentials",
|
|
2079
|
+
headers: () => ({}),
|
|
2080
|
+
remedy: "Put the authentication check in one place that every route passes through, such as a middleware on the whole router, and name the few public routes there. A route must not decide by itself to check for a user."
|
|
2081
|
+
});
|
|
2082
|
+
|
|
2083
|
+
// src/checks/access/protected-fields.ts
|
|
2084
|
+
function hostile(honest, marker) {
|
|
2085
|
+
if (typeof honest === "number") return honest + 987654;
|
|
2086
|
+
if (typeof honest === "boolean") return !honest;
|
|
2087
|
+
return "badday-" + marker;
|
|
2088
|
+
}
|
|
2089
|
+
var protectedFields = {
|
|
2090
|
+
name: "protected-fields",
|
|
2091
|
+
pack: "access",
|
|
2092
|
+
creates: 2,
|
|
2093
|
+
promise: "A user cannot set the protected fields of their own record.",
|
|
2094
|
+
consequence: "A user can set fields that only your server may set, such as the owner or the price of an order.",
|
|
2095
|
+
question: "if a user can set protected fields",
|
|
2096
|
+
needs(resource) {
|
|
2097
|
+
if (!resource.create) return `Your config gives the ${resource.name} resource no create route. Add one and this check runs.`;
|
|
2098
|
+
if (!resource.protectedFields.length) return `Your config names no protected fields for ${resource.name}. Add protectedFields, such as ["userId", "total"], and this check runs.`;
|
|
2099
|
+
return null;
|
|
2100
|
+
},
|
|
2101
|
+
async run(ctx) {
|
|
2102
|
+
const { resource, owner, client } = ctx;
|
|
2103
|
+
const fields2 = resource.protectedFields;
|
|
2104
|
+
const honest = await createOne(ctx, owner, { note: "an honest create, to learn the values the server sets" });
|
|
2105
|
+
const attack = Object.fromEntries(fields2.map((f) => [f, hostile(honest.doc[f], ctx.marker)]));
|
|
2106
|
+
const taken = (doc) => fields2.filter((f) => doc && typeof doc === "object" && JSON.stringify(doc[f]) === JSON.stringify(attack[f]));
|
|
2107
|
+
const req = createReq(ctx, owner);
|
|
2108
|
+
req.body = withFields(resource, req.body, attack);
|
|
2109
|
+
const created = await client.send(req);
|
|
2110
|
+
const madeId = createdId(ctx, created);
|
|
2111
|
+
if (madeId) ctx.track(owner, madeId);
|
|
2112
|
+
const onCreate = ok(created) ? taken(recordOf(ctx, created.response.body)) : [];
|
|
2113
|
+
created.note = onCreate.length ? `the create set ${onCreate.join(", ")}` : ok(created) ? "the create ignored the protected fields" : `the create was refused with ${statusOf(created)}`;
|
|
2114
|
+
let onUpdate = [];
|
|
2115
|
+
if (resource.update) {
|
|
2116
|
+
const updated = await client.send({ actor: owner, method: resource.update.method, path: withId(resource.update.path, honest.id), body: withFields(resource, resource.update.body, attack) });
|
|
2117
|
+
let doc = ok(updated) ? recordOf(ctx, updated.response.body) : null;
|
|
2118
|
+
if (resource.get) {
|
|
2119
|
+
const read = await client.send({ actor: owner, method: "GET", path: withId(resource.get, honest.id), note: `${owner} reads the record after the update` });
|
|
2120
|
+
doc = ok(read) ? recordOf(ctx, read.response.body) : doc;
|
|
2121
|
+
}
|
|
2122
|
+
onUpdate = taken(doc);
|
|
2123
|
+
updated.note = onUpdate.length ? `the update set ${onUpdate.join(", ")}` : ok(updated) ? "the update ignored the protected fields" : `the update was refused with ${statusOf(updated)}`;
|
|
2124
|
+
}
|
|
2125
|
+
const set = [.../* @__PURE__ */ new Set([...onCreate, ...onUpdate])];
|
|
2126
|
+
const story = `${cap(owner)} sent ${fields2.join(", ")} in a create${resource.update ? " and in an update" : ""}, with values of their own.`;
|
|
2127
|
+
const facts = [{ label: `Protected fields the request could set, of ${fields2.length}`, expected: "0", actual: set.length ? `${set.length} (${set.join(", ")})` : "0" }];
|
|
2128
|
+
if (set.length) {
|
|
2129
|
+
return {
|
|
2130
|
+
verdict: "fail",
|
|
2131
|
+
facts,
|
|
2132
|
+
summary: `${story} Your app stored ${set.join(", ")} as sent.`,
|
|
2133
|
+
fixPrompt: `My backend copies fields from the request body into the record without a filter. A test sent ${fields2.join(", ")} in the body of ${resource.create.method} ${resource.create.path}${resource.update ? ` and ${resource.update.method} ${resource.update.path}` : ""}, and the backend stored ${set.join(", ")} as sent. Only the server may set those fields.
|
|
2134
|
+
|
|
2135
|
+
Do not spread or assign the request body into the record. Name the fields a client may set, copy only those, and compute the rest on the server. Validate the body against a schema that rejects or strips unknown fields.`
|
|
2136
|
+
};
|
|
2137
|
+
}
|
|
2138
|
+
return { verdict: "pass", facts, summary: `${story} Your app kept its own values.` };
|
|
2139
|
+
}
|
|
2140
|
+
};
|
|
2141
|
+
|
|
2142
|
+
// src/checks/index.ts
|
|
2143
|
+
var checks = [
|
|
2144
|
+
duplicateSubmit,
|
|
2145
|
+
retryLater,
|
|
2146
|
+
keyReuse,
|
|
2147
|
+
keyCrossUser,
|
|
2148
|
+
keyCrossRoute,
|
|
2149
|
+
keylessDuplicate,
|
|
2150
|
+
abandonedRetry,
|
|
2151
|
+
retryInFlight,
|
|
2152
|
+
webhookRedelivery,
|
|
2153
|
+
webhookBurst,
|
|
2154
|
+
webhookBadSignature,
|
|
2155
|
+
webhookNoSignature,
|
|
2156
|
+
webhookStaleTimestamp,
|
|
2157
|
+
webhookTamperedBody,
|
|
2158
|
+
webhookUnknownType,
|
|
2159
|
+
cursorGarbage,
|
|
2160
|
+
cursorTruncated,
|
|
2161
|
+
cursorCrossUser,
|
|
2162
|
+
limitHuge,
|
|
2163
|
+
limitInvalid,
|
|
2164
|
+
listWalkUnderWrites,
|
|
2165
|
+
bodyTooLarge,
|
|
2166
|
+
brokenJson,
|
|
2167
|
+
errorLeak,
|
|
2168
|
+
noCredentials,
|
|
2169
|
+
garbageToken,
|
|
2170
|
+
crossUserRead,
|
|
2171
|
+
crossUserUpdate,
|
|
2172
|
+
crossUserDelete,
|
|
2173
|
+
crossUserList,
|
|
2174
|
+
protectedFields
|
|
2175
|
+
];
|
|
2176
|
+
|
|
2177
|
+
// src/engine/client.ts
|
|
2178
|
+
import http2 from "node:http";
|
|
2179
|
+
import net from "node:net";
|
|
2180
|
+
import tls from "node:tls";
|
|
2181
|
+
var SECRET_HEADER = /^(authorization|cookie|x-api-key|proxy-authorization)$/i;
|
|
2182
|
+
var DEFAULT_TIMEOUT_MS = 15e3;
|
|
2183
|
+
function redact(value) {
|
|
2184
|
+
const scheme = value.match(/^(Bearer|Basic|Token) /i);
|
|
2185
|
+
return scheme ? scheme[1] + " [redacted]" : "[redacted]";
|
|
2186
|
+
}
|
|
2187
|
+
var Client = class {
|
|
2188
|
+
exchanges = [];
|
|
2189
|
+
model;
|
|
2190
|
+
t0 = performance.now();
|
|
2191
|
+
constructor(model) {
|
|
2192
|
+
this.model = model;
|
|
2193
|
+
}
|
|
2194
|
+
send(req) {
|
|
2195
|
+
return this.dispatch(req, null, null);
|
|
2196
|
+
}
|
|
2197
|
+
/**
|
|
2198
|
+
* Sends every request at the same instant. It opens one connection per request and waits
|
|
2199
|
+
* until all of them are up. Only then does it write the requests, in one tick, so no request
|
|
2200
|
+
* waits behind another for a socket.
|
|
2201
|
+
*/
|
|
2202
|
+
async burst(reqs) {
|
|
2203
|
+
const sockets = await Promise.all(reqs.map(() => this.open()));
|
|
2204
|
+
const at = this.elapsed();
|
|
2205
|
+
return Promise.all(reqs.map((req, i) => this.dispatch(req, sockets[i], at)));
|
|
2206
|
+
}
|
|
2207
|
+
elapsed() {
|
|
2208
|
+
return performance.now() - this.t0;
|
|
2209
|
+
}
|
|
2210
|
+
open() {
|
|
2211
|
+
const { base } = this.model;
|
|
2212
|
+
const host = base.hostname.replace(/^\[|\]$/g, "");
|
|
2213
|
+
const secure = base.protocol === "https:";
|
|
2214
|
+
const port = Number(base.port) || (secure ? 443 : 80);
|
|
2215
|
+
return new Promise((resolve6, reject) => {
|
|
2216
|
+
const socket = secure ? tls.connect({ host, port, servername: net.isIP(host) ? void 0 : host }) : net.connect({ host, port });
|
|
2217
|
+
socket.setNoDelay(true);
|
|
2218
|
+
socket.once("error", reject);
|
|
2219
|
+
socket.once(secure ? "secureConnect" : "connect", () => {
|
|
2220
|
+
socket.off("error", reject);
|
|
2221
|
+
resolve6(socket);
|
|
2222
|
+
});
|
|
2223
|
+
});
|
|
2224
|
+
}
|
|
2225
|
+
async dispatch(req, ready, burstAt) {
|
|
2226
|
+
const actorHeaders = req.actor ? this.model.actors[req.actor]?.headers ?? {} : {};
|
|
2227
|
+
const headers = { ...actorHeaders, ...req.headers };
|
|
2228
|
+
let payload = null;
|
|
2229
|
+
if (req.rawBody !== void 0) payload = Buffer.from(req.rawBody);
|
|
2230
|
+
else if (req.body !== void 0) {
|
|
2231
|
+
payload = Buffer.from(JSON.stringify(req.body));
|
|
2232
|
+
if (!Object.keys(headers).some((k) => k.toLowerCase() === "content-type")) headers["Content-Type"] = "application/json";
|
|
2233
|
+
}
|
|
2234
|
+
const shown = {};
|
|
2235
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
2236
|
+
shown[name] = name in actorHeaders || SECRET_HEADER.test(name) ? redact(value) : value;
|
|
2237
|
+
}
|
|
2238
|
+
const exchange = {
|
|
2239
|
+
at: burstAt ?? this.elapsed(),
|
|
2240
|
+
actor: req.actor ?? null,
|
|
2241
|
+
request: {
|
|
2242
|
+
method: req.method,
|
|
2243
|
+
path: req.path,
|
|
2244
|
+
headers: shown,
|
|
2245
|
+
body: req.rawBody !== void 0 ? rawPreview(payload) : req.body
|
|
2246
|
+
},
|
|
2247
|
+
response: null,
|
|
2248
|
+
note: req.note,
|
|
2249
|
+
quiet: req.quiet
|
|
2250
|
+
};
|
|
2251
|
+
this.exchanges.push(exchange);
|
|
2252
|
+
let socket;
|
|
2253
|
+
try {
|
|
2254
|
+
socket = ready ?? await this.open();
|
|
2255
|
+
} catch (err) {
|
|
2256
|
+
exchange.error = "could not connect, " + err.message;
|
|
2257
|
+
return exchange;
|
|
2258
|
+
}
|
|
2259
|
+
const base = this.model.base;
|
|
2260
|
+
const started = performance.now();
|
|
2261
|
+
await new Promise((done) => {
|
|
2262
|
+
let settled = false;
|
|
2263
|
+
let answered = false;
|
|
2264
|
+
const finish = (error) => {
|
|
2265
|
+
if (settled) return;
|
|
2266
|
+
settled = true;
|
|
2267
|
+
clearTimeout(timer);
|
|
2268
|
+
clearTimeout(abortTimer);
|
|
2269
|
+
if (error) exchange.error = error;
|
|
2270
|
+
socket.destroy();
|
|
2271
|
+
done();
|
|
2272
|
+
};
|
|
2273
|
+
const agent = new http2.Agent({ keepAlive: false });
|
|
2274
|
+
agent.createConnection = () => socket;
|
|
2275
|
+
const request = http2.request({
|
|
2276
|
+
agent,
|
|
2277
|
+
host: base.hostname.replace(/^\[|\]$/g, ""),
|
|
2278
|
+
port: base.port || void 0,
|
|
2279
|
+
method: req.method,
|
|
2280
|
+
path: base.pathname.replace(/\/$/, "") + req.path,
|
|
2281
|
+
headers: { ...headers, Connection: "close", ...payload ? { "Content-Length": String(payload.length) } : {} }
|
|
2282
|
+
});
|
|
2283
|
+
const limit = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
2284
|
+
const timer = setTimeout(() => finish(`no response in ${limit / 1e3} s`), limit);
|
|
2285
|
+
const abortTimer = req.abortAfterMs === void 0 ? void 0 : setTimeout(() => finish(`badday cut the connection after ${req.abortAfterMs} ms`), req.abortAfterMs);
|
|
2286
|
+
request.on("response", (res) => {
|
|
2287
|
+
answered = true;
|
|
2288
|
+
const chunks = [];
|
|
2289
|
+
res.on("data", (chunk) => chunks.push(chunk));
|
|
2290
|
+
const record2 = () => {
|
|
2291
|
+
if (settled) return;
|
|
2292
|
+
const text2 = Buffer.concat(chunks).toString("utf8");
|
|
2293
|
+
const flat = {};
|
|
2294
|
+
for (const [name, value] of Object.entries(res.headers)) {
|
|
2295
|
+
if (value !== void 0) flat[name] = Array.isArray(value) ? value.join(", ") : value;
|
|
2296
|
+
}
|
|
2297
|
+
let body2 = text2;
|
|
2298
|
+
if (/json/i.test(flat["content-type"] ?? "")) {
|
|
2299
|
+
try {
|
|
2300
|
+
body2 = JSON.parse(text2);
|
|
2301
|
+
} catch {
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
exchange.response = { status: res.statusCode ?? 0, headers: flat, body: body2, text: text2, ms: performance.now() - started };
|
|
2305
|
+
finish();
|
|
2306
|
+
};
|
|
2307
|
+
res.on("end", record2);
|
|
2308
|
+
res.on("error", record2);
|
|
2309
|
+
res.on("close", record2);
|
|
2310
|
+
});
|
|
2311
|
+
request.on("error", (err) => {
|
|
2312
|
+
if (!answered) setTimeout(() => finish(err.message), 150);
|
|
2313
|
+
});
|
|
2314
|
+
request.end(payload ?? void 0);
|
|
2315
|
+
});
|
|
2316
|
+
return exchange;
|
|
2317
|
+
}
|
|
2318
|
+
};
|
|
2319
|
+
function rawPreview(payload) {
|
|
2320
|
+
if (payload.length <= 400) return payload.toString("utf8");
|
|
2321
|
+
return payload.subarray(0, 200).toString("utf8") + `
|
|
2322
|
+
[${payload.length} bytes in total]`;
|
|
2323
|
+
}
|
|
2324
|
+
|
|
2325
|
+
// src/engine/config.ts
|
|
2326
|
+
import { isIP } from "node:net";
|
|
2327
|
+
var UsageError = class extends Error {
|
|
2328
|
+
};
|
|
2329
|
+
var route = (spec, method) => {
|
|
2330
|
+
if (!spec) return void 0;
|
|
2331
|
+
if (typeof spec === "string") return { method, path: spec };
|
|
2332
|
+
return { method: (spec.method ?? method).toUpperCase(), path: spec.path, body: spec.body, slow: spec.slow };
|
|
2333
|
+
};
|
|
2334
|
+
function buildModel(config) {
|
|
2335
|
+
let base;
|
|
2336
|
+
try {
|
|
2337
|
+
base = new URL(config.baseUrl);
|
|
2338
|
+
} catch {
|
|
2339
|
+
throw new UsageError(`baseUrl is "${config.baseUrl}", which is not a URL. Write it like http://localhost:3000.`);
|
|
2340
|
+
}
|
|
2341
|
+
if (base.protocol !== "http:" && base.protocol !== "https:") {
|
|
2342
|
+
throw new UsageError(`baseUrl must start with http:// or https://. It starts with ${base.protocol}`);
|
|
2343
|
+
}
|
|
2344
|
+
const names2 = Object.keys(config.actors ?? {});
|
|
2345
|
+
if (!names2.length) throw new UsageError("The config has no actors. Add one actor with the headers of a test user.");
|
|
2346
|
+
const resources = (config.resources ?? []).map((r) => {
|
|
2347
|
+
const list2 = typeof r.list === "string" ? { path: r.list } : r.list;
|
|
2348
|
+
return {
|
|
2349
|
+
name: r.name,
|
|
2350
|
+
singular: r.name.endsWith("s") ? r.name.slice(0, -1) : r.name,
|
|
2351
|
+
idField: r.idField ?? "id",
|
|
2352
|
+
envelope: r.envelope,
|
|
2353
|
+
create: route(r.create, "POST"),
|
|
2354
|
+
get: r.get,
|
|
2355
|
+
list: list2,
|
|
2356
|
+
update: route(r.update, "PATCH"),
|
|
2357
|
+
remove: route(r.remove, "DELETE"),
|
|
2358
|
+
idempotencyHeader: r.idempotencyHeader,
|
|
2359
|
+
idempotencyField: r.idempotencyField,
|
|
2360
|
+
duplicates: r.duplicates,
|
|
2361
|
+
protectedFields: r.protectedFields ?? [],
|
|
2362
|
+
markerField: r.markerField,
|
|
2363
|
+
public: r.public ?? [],
|
|
2364
|
+
shared: [.../* @__PURE__ */ new Set([...r.shared ?? [], ...r.public ?? []])]
|
|
2365
|
+
};
|
|
2366
|
+
});
|
|
2367
|
+
return { base, actors: config.actors, owner: names2[0], other: names2[1] ?? null, resources, webhooks: config.webhooks ?? [] };
|
|
2368
|
+
}
|
|
2369
|
+
function isLocalHost(hostname) {
|
|
2370
|
+
const host = hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
2371
|
+
if (host === "localhost" || host.endsWith(".localhost")) return true;
|
|
2372
|
+
if (isIP(host) === 6) return host === "::1" || /^f[cd]/.test(host) || host.startsWith("fe80:");
|
|
2373
|
+
if (isIP(host) !== 4) return false;
|
|
2374
|
+
const [a, b] = host.split(".").map(Number);
|
|
2375
|
+
return a === 127 || a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 169 && b === 254;
|
|
2376
|
+
}
|
|
2377
|
+
|
|
2378
|
+
// src/engine/load.ts
|
|
2379
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2380
|
+
import { resolve } from "node:path";
|
|
2381
|
+
import { pathToFileURL } from "node:url";
|
|
2382
|
+
var CONFIG_NAMES = ["badday.config.json", "badday.config.mjs", "badday.config.js", "badday.config.ts"];
|
|
2383
|
+
function findConfig(named2, cwd = process.cwd()) {
|
|
2384
|
+
if (named2) {
|
|
2385
|
+
const file = resolve(cwd, named2);
|
|
2386
|
+
if (!existsSync(file)) throw new UsageError(`No file exists at ${file}. Correct the path after --config.`);
|
|
2387
|
+
return file;
|
|
2388
|
+
}
|
|
2389
|
+
return CONFIG_NAMES.map((n) => resolve(cwd, n)).find(existsSync) ?? null;
|
|
2390
|
+
}
|
|
2391
|
+
async function loadConfig(file) {
|
|
2392
|
+
if (file.endsWith(".json")) {
|
|
2393
|
+
try {
|
|
2394
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
2395
|
+
} catch (err) {
|
|
2396
|
+
throw new UsageError(`${file} is not valid JSON: ${err.message}. Correct the file, or let "badday init --agent" guide an AI tool to write it.`);
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
try {
|
|
2400
|
+
const loaded = await import(pathToFileURL(file).href);
|
|
2401
|
+
return loaded.default ?? loaded.config;
|
|
2402
|
+
} catch (err) {
|
|
2403
|
+
const hint = file.endsWith(".ts") ? " A .ts config needs Node 22.18 or later. Use badday.config.json or badday.config.mjs on older versions." : "";
|
|
2404
|
+
throw new UsageError(`badday could not load ${file}: ${err.message}.${hint}`);
|
|
2405
|
+
}
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2408
|
+
// src/engine/openapi.ts
|
|
2409
|
+
var LIMIT_PARAMS = ["limit", "per_page", "page_size", "pageSize", "perPage", "size", "take", "first"];
|
|
2410
|
+
var CURSOR_PARAMS = ["cursor", "after", "starting_after", "page_token", "pageToken", "next", "next_token"];
|
|
2411
|
+
var MARKER_FIELDS = ["note", "notes", "description", "comment", "memo", "reference"];
|
|
2412
|
+
var PROTECTED = /^(user_?id|owner(_?id)?|account_?id|tenant_?id|total|amount|price|status|role|is_?admin|paid|balance)$/i;
|
|
2413
|
+
var SKIP = /\/(login|logout|auth|signup|register|token|webhooks?|health)(\/|$)/i;
|
|
2414
|
+
function draftFromOpenApi(doc, baseUrl) {
|
|
2415
|
+
const questions = [];
|
|
2416
|
+
const found = [];
|
|
2417
|
+
const resolve6 = (node, depth = 0) => {
|
|
2418
|
+
if (!node || depth > 8) return node;
|
|
2419
|
+
if (typeof node.$ref === "string") return resolve6(node.$ref.replace(/^#\//, "").split("/").reduce((at, key) => at?.[key], doc), depth + 1);
|
|
2420
|
+
if (Array.isArray(node.allOf)) return node.allOf.map((s) => resolve6(s, depth + 1)).reduce((all, s) => ({ ...all, ...s, properties: { ...all.properties, ...s?.properties }, required: [...all.required ?? [], ...s?.required ?? []] }), {});
|
|
2421
|
+
return node;
|
|
2422
|
+
};
|
|
2423
|
+
const sample = (schemaNode, depth = 0) => {
|
|
2424
|
+
const schema = resolve6(schemaNode);
|
|
2425
|
+
if (!schema || depth > 4) return void 0;
|
|
2426
|
+
if (schema.example !== void 0) return schema.example;
|
|
2427
|
+
if (schema.default !== void 0) return schema.default;
|
|
2428
|
+
if (schema.enum) return schema.enum[0];
|
|
2429
|
+
if (schema.type === "object" || schema.properties) {
|
|
2430
|
+
const required = schema.required ?? [];
|
|
2431
|
+
const keys = Object.keys(schema.properties ?? {}).filter((k) => !resolve6(schema.properties[k])?.readOnly && (!required.length || required.includes(k)));
|
|
2432
|
+
return Object.fromEntries(keys.map((k) => [k, sample(schema.properties[k], depth + 1)]).filter(([, v]) => v !== void 0));
|
|
2433
|
+
}
|
|
2434
|
+
if (schema.type === "array") return [sample(schema.items, depth + 1)].filter((v) => v !== void 0);
|
|
2435
|
+
if (schema.type === "integer" || schema.type === "number") return schema.minimum ?? 1;
|
|
2436
|
+
if (schema.type === "boolean") return true;
|
|
2437
|
+
if (schema.format === "email") return "badday@example.com";
|
|
2438
|
+
if (schema.format === "date-time") return "2026-01-01T00:00:00Z";
|
|
2439
|
+
if (schema.format === "date") return "2026-01-01";
|
|
2440
|
+
if (schema.format === "uuid") return "00000000-0000-4000-8000-000000000000";
|
|
2441
|
+
return "test";
|
|
2442
|
+
};
|
|
2443
|
+
const jsonSchema = (holder) => {
|
|
2444
|
+
const content = resolve6(holder)?.content ?? {};
|
|
2445
|
+
const media = content["application/json"] ?? Object.entries(content).find(([type]) => type.includes("json"))?.[1];
|
|
2446
|
+
return media?.example !== void 0 ? { example: media.example } : resolve6(media?.schema);
|
|
2447
|
+
};
|
|
2448
|
+
const success = (operation) => {
|
|
2449
|
+
const code = Object.keys(operation.responses ?? {}).find((c) => /^2/.test(c));
|
|
2450
|
+
return code ? jsonSchema(operation.responses[code]) : void 0;
|
|
2451
|
+
};
|
|
2452
|
+
const params = (operation, pathItem) => [...pathItem.parameters ?? [], ...operation.parameters ?? []].map((p) => resolve6(p)).filter(Boolean);
|
|
2453
|
+
const prefix = (() => {
|
|
2454
|
+
try {
|
|
2455
|
+
return new URL(doc.servers?.[0]?.url ?? "", baseUrl).pathname.replace(/\/$/, "");
|
|
2456
|
+
} catch {
|
|
2457
|
+
return "";
|
|
2458
|
+
}
|
|
2459
|
+
})();
|
|
2460
|
+
const paths = doc.paths ?? {};
|
|
2461
|
+
const resources = [];
|
|
2462
|
+
for (const [path2, item] of Object.entries(paths)) {
|
|
2463
|
+
if (path2.includes("{") || SKIP.test(path2) || !item.post) continue;
|
|
2464
|
+
const name = path2.split("/").filter(Boolean).pop();
|
|
2465
|
+
const full = prefix + path2;
|
|
2466
|
+
const resource = { name };
|
|
2467
|
+
const requestSchema = jsonSchema(item.post.requestBody);
|
|
2468
|
+
const body2 = sample(requestSchema);
|
|
2469
|
+
if (body2 && typeof body2 === "object" && !Array.isArray(body2)) resource.create = { method: "POST", path: full, body: body2 };
|
|
2470
|
+
else {
|
|
2471
|
+
resource.create = { method: "POST", path: full, body: {} };
|
|
2472
|
+
questions.push(`POST ${path2} has no JSON body in the description. Write a body the backend accepts in resources "${name}", create.body.`);
|
|
2473
|
+
}
|
|
2474
|
+
const key = params(item.post, item).find((p) => p.in === "header" && /idempoten/i.test(p.name));
|
|
2475
|
+
if (key) resource.idempotencyHeader = key.name;
|
|
2476
|
+
const marker = MARKER_FIELDS.find((f) => resolve6(requestSchema?.properties?.[f])?.type === "string");
|
|
2477
|
+
if (marker) resource.markerField = marker;
|
|
2478
|
+
if (item.get) {
|
|
2479
|
+
const query = params(item.get, item).filter((p) => p.in === "query").map((p) => p.name);
|
|
2480
|
+
const list2 = { path: full };
|
|
2481
|
+
const limit = LIMIT_PARAMS.find((p) => query.includes(p));
|
|
2482
|
+
const cursor = CURSOR_PARAMS.find((p) => query.includes(p));
|
|
2483
|
+
if (limit) list2.limitParam = limit;
|
|
2484
|
+
if (cursor && cursor !== "cursor") list2.cursorParam = cursor;
|
|
2485
|
+
resource.list = limit || list2.cursorParam ? list2 : full;
|
|
2486
|
+
}
|
|
2487
|
+
const single = Object.entries(paths).find(([p]) => new RegExp(`^${path2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/\\{[^/}]+\\}$`).test(p));
|
|
2488
|
+
if (single) {
|
|
2489
|
+
const withId2 = prefix + single[0].replace(/\{[^}]+\}$/, ":id");
|
|
2490
|
+
if (single[1].get) resource.get = withId2;
|
|
2491
|
+
const update = single[1].patch ? "PATCH" : single[1].put ? "PUT" : null;
|
|
2492
|
+
if (update) {
|
|
2493
|
+
const updateBody = sample(jsonSchema(single[1][update.toLowerCase()].requestBody));
|
|
2494
|
+
resource.update = { method: update, path: withId2, body: updateBody && typeof updateBody === "object" && !Array.isArray(updateBody) ? updateBody : {} };
|
|
2495
|
+
if (!Object.keys(resource.update.body).length) questions.push(`${update} ${single[0]} has no JSON body in the description. Write one field to change in resources "${name}", update.body.`);
|
|
2496
|
+
}
|
|
2497
|
+
if (single[1].delete) resource.remove = { method: "DELETE", path: withId2 };
|
|
2498
|
+
}
|
|
2499
|
+
const record2 = success(item.post);
|
|
2500
|
+
const fieldsOf = Object.keys(record2?.properties ?? (record2?.example && typeof record2.example === "object" ? record2.example : {}));
|
|
2501
|
+
if (fieldsOf.length && !fieldsOf.includes("id")) {
|
|
2502
|
+
const ids = fieldsOf.filter((f) => /(^|_)id$|Id$|^uuid$/.test(f));
|
|
2503
|
+
if (ids.length === 1) resource.idField = ids[0];
|
|
2504
|
+
else questions.push(`badday cannot tell which field of ${name} is the id. The response of POST ${path2} has: ${fieldsOf.join(", ")}. Set idField in resources "${name}".`);
|
|
2505
|
+
}
|
|
2506
|
+
const sent = Object.keys(requestSchema?.properties ?? {});
|
|
2507
|
+
const guarded = fieldsOf.filter((f) => PROTECTED.test(f) && (!sent.includes(f) || resolve6(record2?.properties?.[f])?.readOnly));
|
|
2508
|
+
if (guarded.length) resource.protectedFields = guarded;
|
|
2509
|
+
found.push(`${name}: ${["create", "get", "list", "update", "remove"].filter((k) => resource[k]).join(", ")}`);
|
|
2510
|
+
resources.push(resource);
|
|
2511
|
+
}
|
|
2512
|
+
if (!resources.length) questions.push("The description has no path with a POST that creates a record, so badday found no resource. Write the resources by hand.");
|
|
2513
|
+
const scheme = Object.values(doc.components?.securitySchemes ?? {}).map((s) => resolve6(s))[0];
|
|
2514
|
+
const header = scheme?.type === "apiKey" && scheme.in === "header" ? scheme.name : scheme?.type === "apiKey" && scheme.in === "cookie" ? "Cookie" : "Authorization";
|
|
2515
|
+
const value = header === "Authorization" ? "Bearer <token of test user N>" : header === "Cookie" ? `${scheme.name}=<session of test user N>` : "<key of test user N>";
|
|
2516
|
+
questions.push("Fill in the credentials of two different test users under actors.");
|
|
2517
|
+
if (Object.keys(paths).some((p) => /webhook/i.test(p))) questions.push("The description has a webhook path. badday cannot learn the signing scheme or the secret from it. Add a webhooks entry by hand.");
|
|
2518
|
+
return {
|
|
2519
|
+
found,
|
|
2520
|
+
questions,
|
|
2521
|
+
config: {
|
|
2522
|
+
baseUrl,
|
|
2523
|
+
actors: { alice: { headers: { [header]: value.replace("N", "1") } }, bob: { headers: { [header]: value.replace("N", "2") } } },
|
|
2524
|
+
resources
|
|
2525
|
+
}
|
|
2526
|
+
};
|
|
2527
|
+
}
|
|
2528
|
+
|
|
2529
|
+
// src/engine/runner.ts
|
|
2530
|
+
import { randomBytes as randomBytes5 } from "node:crypto";
|
|
2531
|
+
|
|
2532
|
+
// src/engine/standards.ts
|
|
2533
|
+
var MAPPING_LABEL = "Draft mapping, written by developers. Not a compliance assessment.";
|
|
2534
|
+
var packs = [
|
|
2535
|
+
{ id: "replay", title: "Replay", about: "The same request, sent again" },
|
|
2536
|
+
{ id: "webhooks", title: "Webhooks", about: "Events from a payment provider" },
|
|
2537
|
+
{ id: "input", title: "Pagination and input", about: "Bad cursors, limits and bodies" },
|
|
2538
|
+
{ id: "access", title: "Access", about: "One user against another's data" }
|
|
2539
|
+
];
|
|
2540
|
+
var standards = [
|
|
2541
|
+
{ id: "hipaa", short: "HIPAA", title: "HIPAA Security Rule, 45 CFR", controls: [
|
|
2542
|
+
{ id: "164.312(a)(1)", title: "Access control" },
|
|
2543
|
+
{ id: "164.312(c)(1)", title: "Integrity" },
|
|
2544
|
+
{ id: "164.312(c)(2)", title: "Mechanism to authenticate data" },
|
|
2545
|
+
{ id: "164.312(d)", title: "Person or entity authentication" },
|
|
2546
|
+
{ id: "164.312(e)(1)", title: "Transmission security" }
|
|
2547
|
+
] },
|
|
2548
|
+
{ id: "gdpr", short: "GDPR", title: "GDPR", controls: [
|
|
2549
|
+
{ id: "Art. 5(1)(d)", title: "Accuracy" },
|
|
2550
|
+
{ id: "Art. 5(1)(f)", title: "Integrity and confidentiality" },
|
|
2551
|
+
{ id: "Art. 25", title: "Data protection by design and by default" },
|
|
2552
|
+
{ id: "Art. 32", title: "Security of processing" }
|
|
2553
|
+
] },
|
|
2554
|
+
{ id: "pci", short: "PCI DSS", title: "PCI DSS 4.0", controls: [
|
|
2555
|
+
{ id: "6.2.4", title: "Software is protected from common attacks" },
|
|
2556
|
+
{ id: "7.2", title: "Access to data is defined and assigned" },
|
|
2557
|
+
{ id: "8.3", title: "Strong authentication for users" }
|
|
2558
|
+
] },
|
|
2559
|
+
{ id: "soc2", short: "SOC 2", title: "SOC 2 trust services criteria", controls: [
|
|
2560
|
+
{ id: "CC6.1", title: "Logical access security" },
|
|
2561
|
+
{ id: "CC6.6", title: "Protection against threats from outside the system" },
|
|
2562
|
+
{ id: "CC6.7", title: "Transmission and movement of information" },
|
|
2563
|
+
{ id: "PI1", title: "Processing integrity" },
|
|
2564
|
+
{ id: "A1", title: "Availability" }
|
|
2565
|
+
] },
|
|
2566
|
+
{ id: "owasp", short: "OWASP API", title: "OWASP API Security Top 10, 2023", controls: [
|
|
2567
|
+
{ id: "API1", title: "Broken object level authorization" },
|
|
2568
|
+
{ id: "API2", title: "Broken authentication" },
|
|
2569
|
+
{ id: "API3", title: "Broken object property level authorization" },
|
|
2570
|
+
{ id: "API4", title: "Unrestricted resource consumption" },
|
|
2571
|
+
{ id: "API8", title: "Security misconfiguration" },
|
|
2572
|
+
{ id: "API10", title: "Unsafe consumption of APIs" }
|
|
2573
|
+
] }
|
|
2574
|
+
];
|
|
2575
|
+
var mapping = [
|
|
2576
|
+
{
|
|
2577
|
+
checks: ["no-credentials", "garbage-token"],
|
|
2578
|
+
controls: { hipaa: ["164.312(d)"], gdpr: ["Art. 32"], pci: ["8.3"], soc2: ["CC6.1"], owasp: ["API2"] }
|
|
2579
|
+
},
|
|
2580
|
+
{
|
|
2581
|
+
checks: ["cross-user-read", "cross-user-update", "cross-user-delete", "cross-user-list", "cursor-cross-user", "key-cross-user"],
|
|
2582
|
+
controls: { hipaa: ["164.312(a)(1)"], gdpr: ["Art. 5(1)(f)", "Art. 32"], pci: ["7.2"], soc2: ["CC6.1"], owasp: ["API1"] }
|
|
2583
|
+
},
|
|
2584
|
+
{
|
|
2585
|
+
checks: ["protected-fields"],
|
|
2586
|
+
controls: { hipaa: ["164.312(c)(1)"], gdpr: ["Art. 25"], pci: ["6.2.4"], soc2: ["CC6.1"], owasp: ["API3"] }
|
|
2587
|
+
},
|
|
2588
|
+
{
|
|
2589
|
+
checks: ["error-leak"],
|
|
2590
|
+
controls: { hipaa: ["164.312(e)(1)"], gdpr: ["Art. 5(1)(f)"], pci: ["6.2.4"], soc2: ["CC6.7"], owasp: ["API8"] }
|
|
2591
|
+
},
|
|
2592
|
+
{
|
|
2593
|
+
checks: [
|
|
2594
|
+
"duplicate-submit",
|
|
2595
|
+
"retry-later",
|
|
2596
|
+
"key-reuse",
|
|
2597
|
+
"key-cross-user",
|
|
2598
|
+
"key-cross-route",
|
|
2599
|
+
"keyless-duplicate",
|
|
2600
|
+
"abandoned-retry",
|
|
2601
|
+
"retry-in-flight",
|
|
2602
|
+
"webhook-redelivery",
|
|
2603
|
+
"webhook-burst"
|
|
2604
|
+
],
|
|
2605
|
+
controls: { hipaa: ["164.312(c)(1)"], gdpr: ["Art. 5(1)(d)"], soc2: ["PI1"] }
|
|
2606
|
+
},
|
|
2607
|
+
{
|
|
2608
|
+
checks: ["webhook-bad-signature", "webhook-no-signature", "webhook-stale-timestamp", "webhook-tampered-body"],
|
|
2609
|
+
controls: { hipaa: ["164.312(c)(2)"], gdpr: ["Art. 32"], soc2: ["CC6.6"], owasp: ["API10"] }
|
|
2610
|
+
},
|
|
2611
|
+
{
|
|
2612
|
+
checks: ["limit-huge", "body-too-large"],
|
|
2613
|
+
controls: { soc2: ["A1"], owasp: ["API4"] }
|
|
2614
|
+
}
|
|
2615
|
+
];
|
|
2616
|
+
var needsPerson = [
|
|
2617
|
+
"Encryption of stored data",
|
|
2618
|
+
"Backups and restore",
|
|
2619
|
+
"Key management",
|
|
2620
|
+
"Log retention",
|
|
2621
|
+
"Staff access to the database",
|
|
2622
|
+
"Vendor contracts, such as a HIPAA business associate agreement",
|
|
2623
|
+
"Breach notification",
|
|
2624
|
+
"Data retention schedules"
|
|
2625
|
+
];
|
|
2626
|
+
function controlsOf(name) {
|
|
2627
|
+
const tags = [];
|
|
2628
|
+
for (const group of mapping) {
|
|
2629
|
+
if (!group.checks.includes(name)) continue;
|
|
2630
|
+
for (const [standard, ids] of Object.entries(group.controls)) {
|
|
2631
|
+
for (const id2 of ids) {
|
|
2632
|
+
if (!tags.some((t) => t.standard === standard && t.id === id2)) tags.push({ standard, id: id2 });
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
}
|
|
2636
|
+
return tags;
|
|
2637
|
+
}
|
|
2638
|
+
|
|
2639
|
+
// src/engine/runner.ts
|
|
2640
|
+
var VERSION = "0.1.0";
|
|
2641
|
+
var BODY_LIMIT2 = 2e3;
|
|
2642
|
+
var PROBE_TIMEOUT_MS = 4e3;
|
|
2643
|
+
var STALL_LIMIT_MS = 9e4;
|
|
2644
|
+
var DROPPED_HEADERS = /^(date|connection|keep-alive|transfer-encoding|content-length)$/i;
|
|
2645
|
+
function toEvidence(exchanges) {
|
|
2646
|
+
return exchanges.filter((x) => !x.quiet).map((x) => {
|
|
2647
|
+
const note = [x.note, x.error].filter(Boolean).join(". ") || void 0;
|
|
2648
|
+
if (!x.response) return { at: Math.round(x.at), actor: x.actor, request: x.request, response: null, note };
|
|
2649
|
+
const headers = {};
|
|
2650
|
+
for (const [name, value] of Object.entries(x.response.headers)) {
|
|
2651
|
+
if (!DROPPED_HEADERS.test(name)) headers[name] = /^set-cookie$/i.test(name) ? redact(value) : value;
|
|
2652
|
+
}
|
|
2653
|
+
const long = x.response.text.length > BODY_LIMIT2;
|
|
2654
|
+
return {
|
|
2655
|
+
at: Math.round(x.at),
|
|
2656
|
+
actor: x.actor,
|
|
2657
|
+
request: x.request,
|
|
2658
|
+
note,
|
|
2659
|
+
response: {
|
|
2660
|
+
status: x.response.status,
|
|
2661
|
+
ms: Math.round(x.response.ms),
|
|
2662
|
+
headers,
|
|
2663
|
+
body: long ? x.response.text.slice(0, BODY_LIMIT2) : x.response.body,
|
|
2664
|
+
bodyNote: long ? `(body shortened, ${Math.round(x.response.text.length / 1e3)} kB)` : void 0
|
|
2665
|
+
}
|
|
2666
|
+
};
|
|
2667
|
+
});
|
|
2668
|
+
}
|
|
2669
|
+
function named(title, resource) {
|
|
2670
|
+
if (resource.name === "orders") return title;
|
|
2671
|
+
const one = resource.singular;
|
|
2672
|
+
return title.replace(/\ban order\b/g, (/^[aeiou]/i.test(one) ? "an " : "a ") + one).replace(/\borders\b/g, resource.name).replace(/\border\b/g, one);
|
|
2673
|
+
}
|
|
2674
|
+
function resourceOf(webhook, model) {
|
|
2675
|
+
const named2 = JSON.stringify(webhook?.event ?? {}).match(/"\$(\w+)\.id"/)?.[1];
|
|
2676
|
+
return model.resources.find((r) => r.name === named2) ?? model.resources[0];
|
|
2677
|
+
}
|
|
2678
|
+
async function runOne({ check, resource, webhook }, model, marker, records) {
|
|
2679
|
+
const id2 = model.resources.length > 1 && check.scope !== "webhook" ? `${check.name}@${resource.name}` : check.name;
|
|
2680
|
+
const base = { id: id2, name: check.name, pack: check.pack, resource: resource.name, controls: controlsOf(check.name) };
|
|
2681
|
+
const reason = check.needs(resource, model, webhook);
|
|
2682
|
+
if (reason) return { ...base, verdict: "not-configured", title: `We could not test ${check.question}.`, summary: reason };
|
|
2683
|
+
const client = new Client(model);
|
|
2684
|
+
const tracked = /* @__PURE__ */ new Map();
|
|
2685
|
+
const ctx = {
|
|
2686
|
+
model,
|
|
2687
|
+
resource,
|
|
2688
|
+
webhook,
|
|
2689
|
+
client,
|
|
2690
|
+
marker,
|
|
2691
|
+
owner: model.owner,
|
|
2692
|
+
other: model.other,
|
|
2693
|
+
track: (actor, id3) => {
|
|
2694
|
+
tracked.set(id3, { actor, id: id3 });
|
|
2695
|
+
},
|
|
2696
|
+
unidentified: () => {
|
|
2697
|
+
records.unidentified++;
|
|
2698
|
+
}
|
|
2699
|
+
};
|
|
2700
|
+
let result;
|
|
2701
|
+
try {
|
|
2702
|
+
const outcome = await check.run(ctx);
|
|
2703
|
+
const title = outcome.title ?? (outcome.verdict === "pass" ? check.promise : outcome.verdict === "fail" ? check.consequence : outcome.verdict === "warning" ? `We could not tell ${check.question}.` : `We could not test ${check.question}.`);
|
|
2704
|
+
result = {
|
|
2705
|
+
...base,
|
|
2706
|
+
verdict: outcome.verdict,
|
|
2707
|
+
title: named(title, resource),
|
|
2708
|
+
summary: outcome.summary,
|
|
2709
|
+
fixPrompt: outcome.fixPrompt,
|
|
2710
|
+
evidence: { facts: outcome.facts ?? [], exchanges: toEvidence(client.exchanges) }
|
|
2711
|
+
};
|
|
2712
|
+
} catch (err) {
|
|
2713
|
+
result = {
|
|
2714
|
+
...base,
|
|
2715
|
+
verdict: "warning",
|
|
2716
|
+
title: `We could not finish testing ${check.question}.`,
|
|
2717
|
+
summary: err.message + ".",
|
|
2718
|
+
evidence: { facts: [], exchanges: toEvidence(client.exchanges) }
|
|
2719
|
+
};
|
|
2720
|
+
}
|
|
2721
|
+
records.created += tracked.size;
|
|
2722
|
+
if (resource.remove) {
|
|
2723
|
+
const cleaner = new Client(model);
|
|
2724
|
+
for (const { actor, id: id3 } of tracked.values()) {
|
|
2725
|
+
const gone = await cleaner.send({ actor, method: resource.remove.method, path: resource.remove.path.replace(":id", encodeURIComponent(id3)), quiet: true });
|
|
2726
|
+
if (gone.response && (gone.response.status < 300 || gone.response.status === 404)) records.deleted++;
|
|
2727
|
+
}
|
|
2728
|
+
}
|
|
2729
|
+
return result;
|
|
2730
|
+
}
|
|
2731
|
+
async function answers(model, resource) {
|
|
2732
|
+
const path2 = resource.list?.path ?? "/";
|
|
2733
|
+
const probe2 = await new Client(model).send({ actor: resource.list ? model.owner : null, method: "GET", path: path2, quiet: true, timeoutMs: PROBE_TIMEOUT_MS });
|
|
2734
|
+
return !!probe2.response;
|
|
2735
|
+
}
|
|
2736
|
+
async function stallAfterCheck(model, resource) {
|
|
2737
|
+
if (await answers(model, resource)) return 0;
|
|
2738
|
+
const since = performance.now();
|
|
2739
|
+
while (performance.now() - since < STALL_LIMIT_MS) {
|
|
2740
|
+
await new Promise((r) => setTimeout(r, 1e3));
|
|
2741
|
+
if (await answers(model, resource)) return Math.round(performance.now() - since) + PROBE_TIMEOUT_MS;
|
|
2742
|
+
}
|
|
2743
|
+
return null;
|
|
2744
|
+
}
|
|
2745
|
+
function withStall(result, ms) {
|
|
2746
|
+
const time = ms === null ? `more than ${STALL_LIMIT_MS / 1e3} seconds` : `about ${Math.round(ms / 1e3)} seconds`;
|
|
2747
|
+
const facts = [...result.evidence?.facts ?? [], { label: "Time your app answered nothing after this check", expected: "0 seconds", actual: time }];
|
|
2748
|
+
return {
|
|
2749
|
+
...result,
|
|
2750
|
+
verdict: "fail",
|
|
2751
|
+
title: `These requests left your app unable to answer anyone for ${time}.`,
|
|
2752
|
+
summary: `${result.summary} After the last request of this check, your app answered nothing for ${time}, not even a plain read of the list.`,
|
|
2753
|
+
fixPrompt: result.fixPrompt ?? `My backend stopped answering every request for ${time} after a test sent it the requests of the "${result.name}" check. The requests and their answers are in the evidence. Find what they exhaust: a database connection pool held by open transactions, a blocked event loop, or a worker that died. A burst of requests must slow the backend down, not stop it.`,
|
|
2754
|
+
evidence: { facts, exchanges: result.evidence?.exchanges ?? [] }
|
|
2755
|
+
};
|
|
2756
|
+
}
|
|
2757
|
+
async function run(config, opts) {
|
|
2758
|
+
const model = buildModel(config);
|
|
2759
|
+
if (!isLocalHost(model.base.hostname) && !opts.allowRemote) {
|
|
2760
|
+
throw new UsageError(
|
|
2761
|
+
`${model.base.host} is not a local address. badday creates records and sends hostile input, and running it against a server you do not own can be illegal. If this server is yours, pass --i-own-this-server.`
|
|
2762
|
+
);
|
|
2763
|
+
}
|
|
2764
|
+
const reach = await new Client(model).send({ method: "GET", path: "/", quiet: true, timeoutMs: 5e3 });
|
|
2765
|
+
if (!reach.response) {
|
|
2766
|
+
throw new UsageError(`Nothing answers at ${config.baseUrl} (${reach.error}). Start your app, or correct baseUrl in the config.`);
|
|
2767
|
+
}
|
|
2768
|
+
if (!model.resources.length) throw new UsageError("The config has no resources. Describe one resource, with its create and list routes.");
|
|
2769
|
+
const known = new Set(opts.checks.flatMap((c) => [c.name, c.pack]));
|
|
2770
|
+
const unknown = [...opts.only ?? [], ...opts.skip ?? []].filter((n) => !known.has(n));
|
|
2771
|
+
if (unknown.length) throw new UsageError(`No check or pack is named ${unknown.join(", ")}. The packs are ${[...new Set(opts.checks.map((c) => c.pack))].join(", ")}. "badday list" prints every check.`);
|
|
2772
|
+
const picked = opts.checks.filter((c) => (!opts.only?.length || opts.only.includes(c.name) || opts.only.includes(c.pack)) && !opts.skip?.includes(c.name) && !opts.skip?.includes(c.pack));
|
|
2773
|
+
const jobs = picked.flatMap((check) => check.scope === "webhook" ? (model.webhooks.length ? model.webhooks : [void 0]).map((webhook) => ({ check, webhook, resource: resourceOf(webhook, model) })) : model.resources.map((resource) => ({ check, resource })));
|
|
2774
|
+
opts.onPlan?.({
|
|
2775
|
+
checks: jobs.length,
|
|
2776
|
+
records: jobs.reduce((sum, j) => sum + (j.check.needs(j.resource, model, j.webhook) ? 0 : j.check.creates), 0)
|
|
2777
|
+
});
|
|
2778
|
+
const startedAt = /* @__PURE__ */ new Date();
|
|
2779
|
+
const started = performance.now();
|
|
2780
|
+
const runId = "bd-" + randomBytes5(3).toString("hex");
|
|
2781
|
+
const records = { created: 0, deleted: 0, left: 0, unidentified: 0 };
|
|
2782
|
+
const checks2 = [];
|
|
2783
|
+
let dead = null;
|
|
2784
|
+
for (const [i, job] of jobs.entries()) {
|
|
2785
|
+
if (dead) {
|
|
2786
|
+
const reason = `Your app stopped answering during the ${dead} check and did not come back, so badday stopped there. Restart your app and run this check alone with --only ${job.check.name}.`;
|
|
2787
|
+
checks2.push({ ...await runOne({ ...job, check: { ...job.check, needs: () => reason } }, model, runId + "-" + i, records) });
|
|
2788
|
+
continue;
|
|
2789
|
+
}
|
|
2790
|
+
let result = await runOne(job, model, runId + "-" + i, records);
|
|
2791
|
+
if (result.verdict !== "not-configured") {
|
|
2792
|
+
const stall = await stallAfterCheck(model, job.resource);
|
|
2793
|
+
if (stall !== 0) result = withStall(result, stall);
|
|
2794
|
+
if (stall === null) dead = job.check.name;
|
|
2795
|
+
}
|
|
2796
|
+
checks2.push(result);
|
|
2797
|
+
}
|
|
2798
|
+
records.left = records.created - records.deleted;
|
|
2799
|
+
return {
|
|
2800
|
+
tool: { name: "badday", version: VERSION },
|
|
2801
|
+
target: config.baseUrl,
|
|
2802
|
+
startedAt: startedAt.toISOString(),
|
|
2803
|
+
durationMs: Math.round(performance.now() - started),
|
|
2804
|
+
records,
|
|
2805
|
+
mappingLabel: MAPPING_LABEL,
|
|
2806
|
+
packs: packs.filter((p) => checks2.some((c) => c.pack === p.id)),
|
|
2807
|
+
standards,
|
|
2808
|
+
needsPerson,
|
|
2809
|
+
checks: checks2
|
|
2810
|
+
};
|
|
2811
|
+
}
|
|
2812
|
+
|
|
2813
|
+
// src/engine/schema.ts
|
|
2814
|
+
var path = { type: "string", description: 'A path that starts with "/", such as "/orders".' };
|
|
2815
|
+
var idPath = { type: "string", description: 'A path with ":id" where the id of a record goes, such as "/orders/:id".' };
|
|
2816
|
+
var body = { type: "object", description: "A JSON body the backend accepts for this route.", additionalProperties: true };
|
|
2817
|
+
var route2 = (what, method, pathSchema) => ({
|
|
2818
|
+
type: "object",
|
|
2819
|
+
description: `The route that ${what}, as { "method": "${method}", "path": "..." }.`,
|
|
2820
|
+
required: ["path"],
|
|
2821
|
+
additionalProperties: false,
|
|
2822
|
+
properties: {
|
|
2823
|
+
method: { type: "string", enum: ["GET", "POST", "PUT", "PATCH", "DELETE"], description: `The HTTP method. ${method} if absent.` },
|
|
2824
|
+
path: pathSchema,
|
|
2825
|
+
body,
|
|
2826
|
+
slow: {
|
|
2827
|
+
type: "object",
|
|
2828
|
+
description: "A variant of the request that the backend takes a known time to answer. Two replay checks need it, to cut in while a request runs.",
|
|
2829
|
+
required: ["body", "ms"],
|
|
2830
|
+
additionalProperties: false,
|
|
2831
|
+
properties: {
|
|
2832
|
+
body: { type: "object", description: "Fields to merge into the body that make the request slow.", additionalProperties: true },
|
|
2833
|
+
ms: { type: "number", description: "How long the slow request takes, in milliseconds. 300 or more works well." }
|
|
2834
|
+
}
|
|
2835
|
+
}
|
|
2836
|
+
}
|
|
2837
|
+
});
|
|
2838
|
+
var listSpec = {
|
|
2839
|
+
type: "object",
|
|
2840
|
+
description: 'The route that lists records, as { "path": "/orders" }, with the names of its paging parameters.',
|
|
2841
|
+
required: ["path"],
|
|
2842
|
+
additionalProperties: false,
|
|
2843
|
+
properties: {
|
|
2844
|
+
path,
|
|
2845
|
+
items: { type: "string", description: 'The field of the response that holds the records. badday tries "data", "items" and "results" if absent.' },
|
|
2846
|
+
nextCursor: { type: "string", description: 'The field of the response that holds the cursor of the next page. badday tries "nextCursor", "next_cursor" and "next" if absent.' },
|
|
2847
|
+
cursorParam: { type: "string", description: 'The query parameter that takes a cursor. "cursor" if absent.' },
|
|
2848
|
+
pageParam: { type: "string", description: 'The query parameter that takes a page number, such as "page". Set it for a list that pages by number and has no cursor.' },
|
|
2849
|
+
offsetParam: { type: "string", description: 'The query parameter that takes an offset, such as "offset". Set it for a list that pages by offset and has no cursor.' },
|
|
2850
|
+
limitParam: { type: "string", description: 'The query parameter that sets the page size, such as "limit". Four checks need it.' },
|
|
2851
|
+
maxLimit: { type: "number", description: "The largest page the backend may return. 100 if absent." }
|
|
2852
|
+
}
|
|
2853
|
+
};
|
|
2854
|
+
var configSchema = {
|
|
2855
|
+
type: "object",
|
|
2856
|
+
description: "The badday config. It describes a running backend: where it is, who can log in, and which routes create, read, list, update and delete each resource.",
|
|
2857
|
+
required: ["baseUrl", "actors", "resources"],
|
|
2858
|
+
additionalProperties: false,
|
|
2859
|
+
properties: {
|
|
2860
|
+
$schema: { type: "string", description: "Ignored by badday. Editors use it." },
|
|
2861
|
+
baseUrl: { type: "string", description: 'Where the backend runs, such as "http://localhost:3000".' },
|
|
2862
|
+
actors: {
|
|
2863
|
+
type: "object",
|
|
2864
|
+
description: "The test users, by name. The first one owns the records badday creates. The second one tries to reach them, and the access checks need it.",
|
|
2865
|
+
minProperties: 1,
|
|
2866
|
+
additionalProperties: {
|
|
2867
|
+
type: "object",
|
|
2868
|
+
description: 'One test user, as { "headers": { "Authorization": "Bearer <token>" } }.',
|
|
2869
|
+
required: ["headers"],
|
|
2870
|
+
additionalProperties: false,
|
|
2871
|
+
properties: {
|
|
2872
|
+
headers: { type: "object", description: "The headers that log this user in, such as Authorization or Cookie.", additionalProperties: { type: "string", description: "A header value." } }
|
|
2873
|
+
}
|
|
2874
|
+
}
|
|
2875
|
+
},
|
|
2876
|
+
resources: {
|
|
2877
|
+
type: "array",
|
|
2878
|
+
description: "The resources to test. One resource with create and list routes is enough to start.",
|
|
2879
|
+
minItems: 1,
|
|
2880
|
+
items: {
|
|
2881
|
+
type: "object",
|
|
2882
|
+
description: "One resource, such as orders.",
|
|
2883
|
+
required: ["name"],
|
|
2884
|
+
additionalProperties: false,
|
|
2885
|
+
properties: {
|
|
2886
|
+
name: { type: "string", description: 'The plural name of the resource, such as "orders". Reports use it.' },
|
|
2887
|
+
create: route2("creates a record", "POST", path),
|
|
2888
|
+
get: idPath,
|
|
2889
|
+
list: { description: "The route that lists records. A path, or an object that also names the paging parameters.", oneOf: [path, listSpec] },
|
|
2890
|
+
update: route2("updates a record", "PATCH", idPath),
|
|
2891
|
+
remove: { description: "The route that deletes a record. badday uses it to delete what it created.", oneOf: [idPath, route2("deletes a record", "DELETE", idPath)] },
|
|
2892
|
+
idField: { type: "string", description: 'The field of a record that holds its id, or the key the get route looks records up by, such as "slug". "id" if absent.' },
|
|
2893
|
+
envelope: { type: "string", description: 'The field that wraps the record in request and response bodies, such as "article" for { "article": {...} }. badday then writes the marker and reads the id inside it. Leave it out if only responses are wrapped: badday finds a record under "data" or the resource name by itself.' },
|
|
2894
|
+
idempotencyHeader: { type: "string", description: 'The request header that carries an idempotency key, such as "Idempotency-Key". The replay checks need it, or idempotencyField.' },
|
|
2895
|
+
idempotencyField: { type: "string", description: 'A field of the create body that carries the idempotency key, such as "transaction_id". Use it if the backend takes the key in the body and not in a header.' },
|
|
2896
|
+
duplicates: { type: "string", enum: ["allowed", "forbidden"], description: "Says if two identical creates with no idempotency key are two legal records." },
|
|
2897
|
+
protectedFields: { type: "array", description: 'Fields only the server may set, such as ["userId", "total", "status"].', items: { type: "string", description: "A field name." } },
|
|
2898
|
+
public: { type: "array", description: 'The read routes that need no login, by design: ["list"], ["get"] or both. badday then does not report them as open, and does not report that one user can read the records of another there.', items: { type: "string", enum: ["list", "get"], description: '"list" or "get".' } },
|
|
2899
|
+
shared: { type: "array", description: 'The read routes where every logged-in user sees the records of every user, by design, such as a public feed: ["list"], ["get"] or both.', items: { type: "string", enum: ["list", "get"], description: '"list" or "get".' } },
|
|
2900
|
+
markerField: { type: "string", description: 'A free-text field of the record in the create body, such as "note" or "title". badday writes a marker there, to count only its own records. It can be the same field as idField, for a backend that looks records up by a name the client picks.' }
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
},
|
|
2904
|
+
webhooks: {
|
|
2905
|
+
type: "array",
|
|
2906
|
+
description: "The webhook routes to test.",
|
|
2907
|
+
items: {
|
|
2908
|
+
type: "object",
|
|
2909
|
+
description: "One webhook route.",
|
|
2910
|
+
required: ["path", "signing", "event", "effect"],
|
|
2911
|
+
additionalProperties: false,
|
|
2912
|
+
properties: {
|
|
2913
|
+
path,
|
|
2914
|
+
signing: {
|
|
2915
|
+
type: "object",
|
|
2916
|
+
description: 'How the sender signs an event, as { "scheme": "stripe", "secret": "whsec_..." }.',
|
|
2917
|
+
required: ["scheme", "secret"],
|
|
2918
|
+
additionalProperties: false,
|
|
2919
|
+
properties: {
|
|
2920
|
+
scheme: { type: "string", enum: ["stripe", "hmac"], description: '"stripe" for the Stripe-Signature format with a timestamp. "hmac" for a hex HMAC-SHA256 of the body in one header.' },
|
|
2921
|
+
secret: { type: "string", description: "The signing secret of the test environment." },
|
|
2922
|
+
header: { type: "string", description: 'The header that carries the signature. "Stripe-Signature" or "X-Signature" if absent.' }
|
|
2923
|
+
}
|
|
2924
|
+
},
|
|
2925
|
+
event: { type: "object", description: 'An event the backend acts on. Write "$orders.id" where the id of a record of the orders resource goes.', additionalProperties: true },
|
|
2926
|
+
effect: {
|
|
2927
|
+
type: "object",
|
|
2928
|
+
description: 'Where badday can read what the event did, as { "list": "/payments" }. badday counts the rows that mention the record.',
|
|
2929
|
+
additionalProperties: false,
|
|
2930
|
+
properties: {
|
|
2931
|
+
list: { description: "A list route that shows what events caused.", oneOf: [path, listSpec] },
|
|
2932
|
+
resource: { type: "string", description: "The name of a resource in this config whose list shows what events caused." },
|
|
2933
|
+
settleMs: { type: "number", description: "How long to wait after a delivery before badday reads the effect, in milliseconds. Set it if the backend answers first and handles the event in a queue." }
|
|
2934
|
+
}
|
|
2935
|
+
}
|
|
2936
|
+
}
|
|
2937
|
+
}
|
|
2938
|
+
}
|
|
2939
|
+
}
|
|
2940
|
+
};
|
|
2941
|
+
var typeOf = (value) => value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
|
|
2942
|
+
function distance(a, b) {
|
|
2943
|
+
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
2944
|
+
for (let i = 1; i <= a.length; i++) {
|
|
2945
|
+
let prev = row[0];
|
|
2946
|
+
row[0] = i;
|
|
2947
|
+
for (let j = 1; j <= b.length; j++) {
|
|
2948
|
+
const next = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
2949
|
+
prev = row[j];
|
|
2950
|
+
row[j] = next;
|
|
2951
|
+
}
|
|
2952
|
+
}
|
|
2953
|
+
return row[b.length];
|
|
2954
|
+
}
|
|
2955
|
+
function walk2(value, schema, at, out) {
|
|
2956
|
+
const fix = schema.description ?? "";
|
|
2957
|
+
if (schema.oneOf) {
|
|
2958
|
+
const match = schema.oneOf.find((s) => s.type === typeOf(value));
|
|
2959
|
+
if (!match) {
|
|
2960
|
+
out.push({ path: at, problem: `is ${typeOf(value)}, and must be ${schema.oneOf.map((s) => s.type).join(" or ")}`, fix });
|
|
2961
|
+
return;
|
|
2962
|
+
}
|
|
2963
|
+
return walk2(value, match, at, out);
|
|
2964
|
+
}
|
|
2965
|
+
if (schema.type && typeOf(value) !== schema.type) {
|
|
2966
|
+
out.push({ path: at, problem: `is ${typeOf(value)}, and must be ${schema.type}`, fix });
|
|
2967
|
+
return;
|
|
2968
|
+
}
|
|
2969
|
+
if (schema.enum && !schema.enum.includes(value)) {
|
|
2970
|
+
out.push({ path: at, problem: `is "${value}", which is not one of the values badday knows`, fix: `Use one of: ${schema.enum.join(", ")}.` });
|
|
2971
|
+
}
|
|
2972
|
+
if (schema.type === "array") {
|
|
2973
|
+
const list2 = value;
|
|
2974
|
+
if (schema.minItems && list2.length < schema.minItems) out.push({ path: at, problem: "is empty", fix });
|
|
2975
|
+
if (schema.items) list2.forEach((item, i) => walk2(item, schema.items, `${at}[${i}]`, out));
|
|
2976
|
+
}
|
|
2977
|
+
if (schema.type === "object") {
|
|
2978
|
+
const object = value;
|
|
2979
|
+
const known = schema.properties ?? {};
|
|
2980
|
+
const sub = (key) => at ? `${at}.${key}` : key;
|
|
2981
|
+
for (const key of schema.required ?? []) {
|
|
2982
|
+
if (object[key] === void 0) out.push({ path: sub(key), problem: "is missing", fix: `Add it. ${known[key]?.description ?? ""}`.trim() });
|
|
2983
|
+
}
|
|
2984
|
+
if (schema.minProperties && Object.keys(object).length < schema.minProperties) out.push({ path: at, problem: "is empty", fix });
|
|
2985
|
+
for (const [key, child] of Object.entries(object)) {
|
|
2986
|
+
if (child === void 0) continue;
|
|
2987
|
+
if (known[key]) walk2(child, known[key], sub(key), out);
|
|
2988
|
+
else if (typeof schema.additionalProperties === "object") walk2(child, schema.additionalProperties, sub(key), out);
|
|
2989
|
+
else if (schema.additionalProperties === false) {
|
|
2990
|
+
const near = Object.keys(known).find((k) => distance(k.toLowerCase(), key.toLowerCase()) <= 2);
|
|
2991
|
+
out.push({ path: sub(key), problem: "is not a key badday knows", fix: near ? `Did you mean "${near}"? Rename the key.` : `Remove it. The keys here are: ${Object.keys(known).filter((k) => k !== "$schema").join(", ")}.` });
|
|
2992
|
+
}
|
|
2993
|
+
}
|
|
2994
|
+
}
|
|
2995
|
+
}
|
|
2996
|
+
function validateConfig(value) {
|
|
2997
|
+
const out = [];
|
|
2998
|
+
walk2(value, configSchema, "", out);
|
|
2999
|
+
if (out.length) return out;
|
|
3000
|
+
const config = value;
|
|
3001
|
+
try {
|
|
3002
|
+
const url = new URL(config.baseUrl);
|
|
3003
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error();
|
|
3004
|
+
} catch {
|
|
3005
|
+
out.push({ path: "baseUrl", problem: `is "${config.baseUrl}", which is not an http or https URL`, fix: 'Write it like "http://localhost:3000".' });
|
|
3006
|
+
}
|
|
3007
|
+
const slash = (at, p) => {
|
|
3008
|
+
if (p !== void 0 && !p.startsWith("/")) out.push({ path: at, problem: `is "${p}", which does not start with "/"`, fix: `Write it as "/${p}". badday adds it to baseUrl.` });
|
|
3009
|
+
};
|
|
3010
|
+
const withId2 = (at, p) => {
|
|
3011
|
+
slash(at, p);
|
|
3012
|
+
if (p !== void 0 && !p.includes(":id")) out.push({ path: at, problem: `is "${p}", which has no ":id"`, fix: 'Write ":id" where the id of a record goes, such as "/orders/:id".' });
|
|
3013
|
+
};
|
|
3014
|
+
config.resources.forEach((r, i) => {
|
|
3015
|
+
const at = `resources[${i}]`;
|
|
3016
|
+
slash(`${at}.create.path`, r.create?.path);
|
|
3017
|
+
slash(typeof r.list === "string" ? `${at}.list` : `${at}.list.path`, typeof r.list === "string" ? r.list : r.list?.path);
|
|
3018
|
+
withId2(`${at}.get`, r.get);
|
|
3019
|
+
withId2(`${at}.update.path`, r.update?.path);
|
|
3020
|
+
withId2(typeof r.remove === "string" ? `${at}.remove` : `${at}.remove.path`, typeof r.remove === "string" ? r.remove : r.remove?.path);
|
|
3021
|
+
if (!r.create && !r.list) out.push({ path: at, problem: "has no create route and no list route", fix: "Add create, list or both. With neither, no check can run against this resource." });
|
|
3022
|
+
const record2 = r.envelope ? r.create?.body?.[r.envelope] : r.create?.body;
|
|
3023
|
+
if (r.envelope && r.create?.body && typeof record2 !== "object") {
|
|
3024
|
+
out.push({ path: `${at}.envelope`, problem: `names "${r.envelope}", and the create body has no object in that field`, fix: `Write the create body as { "${r.envelope}": { ... } }, or remove envelope if the backend takes the fields at the top level.` });
|
|
3025
|
+
}
|
|
3026
|
+
if (r.idempotencyHeader && r.idempotencyField) out.push({ path: `${at}.idempotencyField`, problem: "is set together with idempotencyHeader", fix: "Keep the one your backend reads, and remove the other." });
|
|
3027
|
+
if (r.markerField && record2 && typeof record2[r.markerField] === "object") {
|
|
3028
|
+
out.push({ path: `${at}.markerField`, problem: `names "${r.markerField}", which is not a text field in the create body`, fix: "Name a field that takes free text, such as a note or a description." });
|
|
3029
|
+
}
|
|
3030
|
+
});
|
|
3031
|
+
(config.webhooks ?? []).forEach((w, i) => {
|
|
3032
|
+
const at = `webhooks[${i}]`;
|
|
3033
|
+
slash(`${at}.path`, w.path);
|
|
3034
|
+
if (!w.effect.list && !w.effect.resource) out.push({ path: `${at}.effect`, problem: "has no list and no resource", fix: 'Add "list" with a route that shows what an event caused, such as "/payments".' });
|
|
3035
|
+
if (w.effect.resource && !w.effect.list && !config.resources.some((r) => r.name === w.effect.resource && r.list)) {
|
|
3036
|
+
out.push({ path: `${at}.effect.resource`, problem: `is "${w.effect.resource}", and no resource of that name with a list route exists in this config`, fix: `Use one of: ${config.resources.filter((r) => r.list).map((r) => r.name).join(", ") || "none exist yet"}. Or set effect.list to a route.` });
|
|
3037
|
+
}
|
|
3038
|
+
});
|
|
3039
|
+
return out;
|
|
3040
|
+
}
|
|
3041
|
+
|
|
3042
|
+
// src/report/html.ts
|
|
3043
|
+
var template = () => true ? `<!doctype html>
|
|
3044
|
+
<html lang="en">
|
|
3045
|
+
<head>
|
|
3046
|
+
<meta charset="utf-8">
|
|
3047
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
3048
|
+
<title>badday report</title>
|
|
3049
|
+
<script>
|
|
3050
|
+
(function () {
|
|
3051
|
+
var t
|
|
3052
|
+
try { t = localStorage.getItem('badday-theme') } catch (e) {}
|
|
3053
|
+
if (t !== 'light' && t !== 'dark') {
|
|
3054
|
+
t = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
|
|
3055
|
+
}
|
|
3056
|
+
document.documentElement.dataset.theme = t
|
|
3057
|
+
})()
|
|
3058
|
+
</script>
|
|
3059
|
+
<style>
|
|
3060
|
+
:root {
|
|
3061
|
+
--bg: #f6f5f1; --panel: #ffffff; --ink: #1b1a17; --muted: #6b675e; --line: #e2dfd6;
|
|
3062
|
+
--code-bg: #f1efe9;
|
|
3063
|
+
--fail: #b92d1b; --fail-bg: #fbeae6;
|
|
3064
|
+
--pass: #1c7448; --pass-bg: #e4f2e9;
|
|
3065
|
+
--warning: #8f5a00; --warning-bg: #faefd6;
|
|
3066
|
+
--skip: #6b675e; --skip-bg: #eceae4;
|
|
3067
|
+
--serif: "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, "Times New Roman", serif;
|
|
3068
|
+
--sans: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
|
3069
|
+
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
|
|
3070
|
+
}
|
|
3071
|
+
:root[data-theme="dark"] {
|
|
3072
|
+
--bg: #141412; --panel: #1d1c19; --ink: #ecebe6; --muted: #a09b8f; --line: #33312b;
|
|
3073
|
+
--code-bg: #171614;
|
|
3074
|
+
--fail: #ff806c; --fail-bg: #3a1b16;
|
|
3075
|
+
--pass: #62cf96; --pass-bg: #15301f;
|
|
3076
|
+
--warning: #f0b64a; --warning-bg: #3a2c10;
|
|
3077
|
+
--skip: #a09b8f; --skip-bg: #2a2925;
|
|
3078
|
+
}
|
|
3079
|
+
* { box-sizing: border-box; }
|
|
3080
|
+
html { -webkit-text-size-adjust: 100%; }
|
|
3081
|
+
body {
|
|
3082
|
+
margin: 0; background: var(--bg); color: var(--ink);
|
|
3083
|
+
font: 15px/1.55 var(--sans);
|
|
3084
|
+
}
|
|
3085
|
+
button { font: inherit; color: inherit; cursor: pointer; }
|
|
3086
|
+
code, pre { font-family: var(--mono); font-size: 12.5px; }
|
|
3087
|
+
.wrap { max-width: 1040px; margin: 0 auto; padding: 0 20px; }
|
|
3088
|
+
|
|
3089
|
+
.top { display: flex; align-items: center; gap: 16px; padding: 18px 0; border-bottom: 1px solid var(--line); flex-wrap: wrap; }
|
|
3090
|
+
.brand { font: 700 17px var(--mono); letter-spacing: -0.02em; }
|
|
3091
|
+
.brand i { font-style: normal; color: var(--fail); }
|
|
3092
|
+
.meta { color: var(--muted); font-size: 13px; flex: 1; min-width: 220px; }
|
|
3093
|
+
.meta code { color: var(--ink); }
|
|
3094
|
+
.theme { background: none; border: 1px solid var(--line); border-radius: 6px; padding: 4px 10px; font-size: 13px; color: var(--muted); }
|
|
3095
|
+
.theme:hover { color: var(--ink); border-color: var(--muted); }
|
|
3096
|
+
|
|
3097
|
+
.sample { margin: 18px 0 0; padding: 8px 12px; border: 1px dashed var(--warning); border-radius: 6px; color: var(--warning); background: var(--warning-bg); font-size: 13px; }
|
|
3098
|
+
|
|
3099
|
+
h1 { font: 400 clamp(28px, 5vw, 44px)/1.15 var(--serif); letter-spacing: -0.01em; margin: 36px 0 28px; }
|
|
3100
|
+
h1 .fail { color: var(--fail); } h1 .pass { color: var(--pass); }
|
|
3101
|
+
h1 .warning { color: var(--warning); } h1 .not-configured { color: var(--skip); }
|
|
3102
|
+
|
|
3103
|
+
.tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--line); overflow-x: auto; }
|
|
3104
|
+
.tabs button { background: none; border: 0; border-bottom: 2px solid transparent; padding: 9px 14px; margin-bottom: -1px; color: var(--muted); white-space: nowrap; }
|
|
3105
|
+
.tabs button:hover { color: var(--ink); }
|
|
3106
|
+
.tabs button[aria-selected="true"] { color: var(--ink); border-bottom-color: var(--ink); font-weight: 600; }
|
|
3107
|
+
|
|
3108
|
+
.packs { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 12px; margin: 24px 0 8px; }
|
|
3109
|
+
.pack { text-align: left; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 14px 16px; }
|
|
3110
|
+
.pack:hover { border-color: var(--muted); }
|
|
3111
|
+
.pack[aria-pressed="true"] { border-color: var(--ink); box-shadow: 0 0 0 1px var(--ink); }
|
|
3112
|
+
.pack b { display: block; font-size: 15px; }
|
|
3113
|
+
.pack small { color: var(--muted); font-size: 12.5px; }
|
|
3114
|
+
.bar { display: flex; height: 6px; border-radius: 3px; overflow: hidden; margin: 12px 0 10px; gap: 2px; }
|
|
3115
|
+
.bar span { display: block; }
|
|
3116
|
+
.bar .fail { background: var(--fail); } .bar .pass { background: var(--pass); }
|
|
3117
|
+
.bar .warning { background: var(--warning); } .bar .not-configured { background: var(--skip); opacity: .5; }
|
|
3118
|
+
.pack .counts { font-size: 13px; }
|
|
3119
|
+
.pack .counts span { margin-right: 10px; white-space: nowrap; }
|
|
3120
|
+
.filter-note { color: var(--muted); font-size: 13px; margin: 6px 0 0; }
|
|
3121
|
+
.filter-note button { background: none; border: 0; padding: 0; text-decoration: underline; color: var(--ink); }
|
|
3122
|
+
|
|
3123
|
+
h2 { font: 600 13px var(--sans); text-transform: uppercase; letter-spacing: .08em; color: var(--muted); margin: 36px 0 12px; }
|
|
3124
|
+
h3 { font: 600 13px var(--sans); color: var(--muted); margin: 18px 0 6px; }
|
|
3125
|
+
|
|
3126
|
+
.fail { --v: var(--fail); --v-bg: var(--fail-bg); }
|
|
3127
|
+
.pass { --v: var(--pass); --v-bg: var(--pass-bg); }
|
|
3128
|
+
.warning { --v: var(--warning); --v-bg: var(--warning-bg); }
|
|
3129
|
+
.not-configured { --v: var(--skip); --v-bg: var(--skip-bg); }
|
|
3130
|
+
.badge { display: inline-block; font: 700 11px var(--sans); letter-spacing: .07em; text-transform: uppercase; color: var(--v); background: var(--v-bg); border-radius: 4px; padding: 3px 7px; white-space: nowrap; }
|
|
3131
|
+
|
|
3132
|
+
details > summary { list-style: none; cursor: pointer; }
|
|
3133
|
+
details > summary::-webkit-details-marker { display: none; }
|
|
3134
|
+
|
|
3135
|
+
.check { background: var(--panel); border: 1px solid var(--line); border-left: 3px solid var(--v); border-radius: 10px; margin: 0 0 12px; }
|
|
3136
|
+
.check > summary { display: grid; grid-template-columns: 96px 1fr 20px; gap: 4px 14px; padding: 16px 18px; align-items: start; }
|
|
3137
|
+
.check > summary .badge { justify-self: start; margin-top: 4px; }
|
|
3138
|
+
.check .title { font: 400 21px/1.3 var(--serif); }
|
|
3139
|
+
.check .sum { grid-column: 2; color: var(--muted); }
|
|
3140
|
+
.check .tags { grid-column: 2; font-size: 12.5px; color: var(--muted); margin-top: 2px; }
|
|
3141
|
+
.check .tags code { color: var(--ink); }
|
|
3142
|
+
.chev { grid-column: 3; grid-row: 1; color: var(--muted); transition: transform .15s; justify-self: end; margin-top: 4px; }
|
|
3143
|
+
details[open] > summary .chev { transform: rotate(90deg); }
|
|
3144
|
+
.check .body { padding: 4px 18px 18px 128px; }
|
|
3145
|
+
.check.target { box-shadow: 0 0 0 2px var(--v); }
|
|
3146
|
+
|
|
3147
|
+
.check.compact { margin: 0; border-radius: 0; border-width: 0 0 1px 0; border-left: 0; background: none; }
|
|
3148
|
+
.check.compact > summary { padding: 9px 4px; grid-template-columns: 96px 1fr auto 20px; align-items: center; }
|
|
3149
|
+
.check.compact .title { font: 15px/1.4 var(--sans); }
|
|
3150
|
+
.check.compact .name { font-size: 12px; color: var(--muted); }
|
|
3151
|
+
.check.compact .chev { grid-column: 4; margin-top: 0; }
|
|
3152
|
+
.check.compact .badge { margin-top: 0; }
|
|
3153
|
+
.check.compact .body { padding: 0 4px 14px 114px; }
|
|
3154
|
+
.check.compact .body .sum { color: var(--muted); margin: 0 0 8px; }
|
|
3155
|
+
.group { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 2px 14px; }
|
|
3156
|
+
.group .check.compact:last-child { border-bottom: 0; }
|
|
3157
|
+
|
|
3158
|
+
.facts { border-collapse: collapse; margin: 0 0 16px; font-size: 14px; }
|
|
3159
|
+
.facts th { text-align: left; font-weight: 400; color: var(--muted); padding: 3px 24px 3px 0; font-size: 12.5px; }
|
|
3160
|
+
.facts td { padding: 3px 24px 3px 0; }
|
|
3161
|
+
.facts td.got { color: var(--v); font-weight: 600; }
|
|
3162
|
+
|
|
3163
|
+
.timeline { border: 1px solid var(--line); border-radius: 8px; overflow: hidden; margin: 0 0 16px; }
|
|
3164
|
+
.ex { border-bottom: 1px solid var(--line); }
|
|
3165
|
+
.ex:last-of-type { border-bottom: 0; }
|
|
3166
|
+
.ex > summary { display: grid; grid-template-columns: 70px 56px minmax(120px, 1.2fr) 44px 2fr; gap: 10px; padding: 7px 12px; font: 12.5px var(--mono); align-items: baseline; }
|
|
3167
|
+
.ex > summary:hover { background: var(--code-bg); }
|
|
3168
|
+
.ex .at, .ex .actor { color: var(--muted); }
|
|
3169
|
+
.ex .status { font-weight: 700; }
|
|
3170
|
+
.ex .note { font-family: var(--sans); color: var(--muted); }
|
|
3171
|
+
.ex .raw { display: grid; grid-template-columns: 1fr 1fr; gap: 1px; background: var(--line); border-top: 1px solid var(--line); }
|
|
3172
|
+
.ex .raw > div { background: var(--code-bg); padding: 10px 12px; min-width: 0; }
|
|
3173
|
+
.ex .raw b { font: 600 11px var(--sans); text-transform: uppercase; letter-spacing: .07em; color: var(--muted); }
|
|
3174
|
+
pre { margin: 6px 0 0; white-space: pre-wrap; word-break: break-word; }
|
|
3175
|
+
.more { display: block; width: 100%; background: var(--code-bg); border: 0; border-top: 1px solid var(--line); padding: 7px; font-size: 13px; color: var(--muted); }
|
|
3176
|
+
.more:hover { color: var(--ink); }
|
|
3177
|
+
|
|
3178
|
+
.fix { background: var(--code-bg); border-radius: 8px; padding: 12px 14px; margin: 0 0 14px; }
|
|
3179
|
+
.fix-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
|
|
3180
|
+
.fix-head b { font-size: 13px; }
|
|
3181
|
+
.fix p { margin: 8px 0 0; font-size: 14px; white-space: pre-wrap; }
|
|
3182
|
+
.btn { background: var(--ink); color: var(--bg); border: 0; border-radius: 6px; padding: 6px 12px; font-size: 13px; font-weight: 600; }
|
|
3183
|
+
.btn:hover { opacity: .85; }
|
|
3184
|
+
|
|
3185
|
+
.chips { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; font-size: 12.5px; color: var(--muted); }
|
|
3186
|
+
.chip { background: none; border: 1px solid var(--line); border-radius: 999px; padding: 2px 9px; font-size: 12px; color: var(--muted); }
|
|
3187
|
+
.chip:hover { color: var(--ink); border-color: var(--muted); }
|
|
3188
|
+
|
|
3189
|
+
.draft { margin: 24px 0 0; padding: 10px 14px; border: 1px solid var(--warning); border-radius: 8px; background: var(--warning-bg); color: var(--warning); font-weight: 600; font-size: 14px; }
|
|
3190
|
+
.lede { font: 400 22px/1.4 var(--serif); margin: 20px 0 8px; max-width: 46em; }
|
|
3191
|
+
.control { background: var(--panel); border: 1px solid var(--line); border-left: 3px solid var(--v); border-radius: 10px; margin: 0 0 12px; padding: 14px 18px; }
|
|
3192
|
+
.control-head { display: flex; gap: 12px; align-items: baseline; flex-wrap: wrap; }
|
|
3193
|
+
.control-head code { font-size: 14px; font-weight: 700; }
|
|
3194
|
+
.control-head .ctitle { flex: 1; min-width: 180px; }
|
|
3195
|
+
.rows { margin: 10px 0 0; border-top: 1px solid var(--line); }
|
|
3196
|
+
.row { display: grid; grid-template-columns: 96px 1fr auto; gap: 14px; width: 100%; text-align: left; background: none; border: 0; border-bottom: 1px solid var(--line); padding: 7px 0; align-items: center; }
|
|
3197
|
+
.row:last-child { border-bottom: 0; padding-bottom: 0; }
|
|
3198
|
+
.row:hover .rt { text-decoration: underline; }
|
|
3199
|
+
.row code { color: var(--muted); font-size: 12px; }
|
|
3200
|
+
.person { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 14px 18px 14px 36px; margin: 0; columns: 2 280px; }
|
|
3201
|
+
.person li { margin: 2px 0; break-inside: avoid; }
|
|
3202
|
+
.hint { color: var(--muted); font-size: 13.5px; margin: 0 0 10px; max-width: 52em; }
|
|
3203
|
+
|
|
3204
|
+
footer { color: var(--muted); font-size: 13px; border-top: 1px solid var(--line); margin-top: 48px; padding: 18px 0 40px; }
|
|
3205
|
+
|
|
3206
|
+
@media (max-width: 640px) {
|
|
3207
|
+
.check > summary, .check.compact > summary { grid-template-columns: 1fr 20px; }
|
|
3208
|
+
.check .sum, .check .tags { grid-column: 1 / -1; }
|
|
3209
|
+
.check .title { grid-column: 1; }
|
|
3210
|
+
.chev, .check.compact .chev { grid-column: 2; grid-row: 1; }
|
|
3211
|
+
.check.compact .name { grid-column: 1; }
|
|
3212
|
+
.check .body, .check.compact .body { padding-left: 18px; }
|
|
3213
|
+
.check.compact .body { padding-left: 4px; }
|
|
3214
|
+
.ex > summary { grid-template-columns: 60px 1fr 40px; }
|
|
3215
|
+
.ex .actor, .ex .note { display: none; }
|
|
3216
|
+
.ex .raw { grid-template-columns: 1fr; }
|
|
3217
|
+
.row { grid-template-columns: 1fr; gap: 2px; }
|
|
3218
|
+
}
|
|
3219
|
+
@media print {
|
|
3220
|
+
.theme, .tabs, .btn, .more, .chev { display: none; }
|
|
3221
|
+
body { background: #fff; }
|
|
3222
|
+
}
|
|
3223
|
+
</style>
|
|
3224
|
+
</head>
|
|
3225
|
+
<body>
|
|
3226
|
+
<div class="wrap">
|
|
3227
|
+
<header class="top">
|
|
3228
|
+
<div class="brand">bad<i>day</i></div>
|
|
3229
|
+
<div class="meta" id="meta"></div>
|
|
3230
|
+
<button class="theme" id="theme" type="button"></button>
|
|
3231
|
+
</header>
|
|
3232
|
+
<noscript><p>This report needs JavaScript to draw its results. The data is in the page source, in the element with the id badday-result.</p></noscript>
|
|
3233
|
+
<p class="sample" id="sample" hidden>Sample report. Every result on this page is invented to show the layout.</p>
|
|
3234
|
+
<h1 id="headline"></h1>
|
|
3235
|
+
<nav class="tabs" id="tabs" role="tablist"></nav>
|
|
3236
|
+
<main id="view"></main>
|
|
3237
|
+
<footer id="foot"></footer>
|
|
3238
|
+
</div>
|
|
3239
|
+
|
|
3240
|
+
<script type="application/json" id="badday-result">__BADDAY_RESULT__</script>
|
|
3241
|
+
<script>
|
|
3242
|
+
const R = JSON.parse(document.getElementById('badday-result').textContent)
|
|
3243
|
+
|
|
3244
|
+
const VERDICTS = {
|
|
3245
|
+
'fail': { label: 'Broken', heading: 'Broken promises', one: 'broken' },
|
|
3246
|
+
'warning': { label: 'Warning', heading: 'Warnings', one: 'warning' },
|
|
3247
|
+
'not-configured': { label: 'Not tested', heading: 'Not tested', one: 'not tested' },
|
|
3248
|
+
'pass': { label: 'Kept', heading: 'Kept promises', one: 'kept' },
|
|
3249
|
+
}
|
|
3250
|
+
const ORDER = ['fail', 'warning', 'not-configured', 'pass']
|
|
3251
|
+
const CONTROL_LABEL = { 'fail': 'Failing evidence', 'warning': 'Warning', 'not-configured': 'Not tested', 'pass': 'Passing evidence' }
|
|
3252
|
+
|
|
3253
|
+
const state = { tab: 'results', pack: null }
|
|
3254
|
+
const packTitle = Object.fromEntries(R.packs.map(p => [p.id, p.title]))
|
|
3255
|
+
const standardById = Object.fromEntries(R.standards.map(s => [s.id, s]))
|
|
3256
|
+
|
|
3257
|
+
// Every value from the result document goes into the page as a text node.
|
|
3258
|
+
// A response body is hostile input, so nothing here sets innerHTML.
|
|
3259
|
+
function h(tag, attrs, ...kids) {
|
|
3260
|
+
const el = document.createElement(tag)
|
|
3261
|
+
for (const [k, v] of Object.entries(attrs || {})) {
|
|
3262
|
+
if (v == null || v === false) continue
|
|
3263
|
+
if (k === 'class') el.className = v
|
|
3264
|
+
else if (k.startsWith('on')) el.addEventListener(k.slice(2), v)
|
|
3265
|
+
else el.setAttribute(k, v === true ? '' : v)
|
|
3266
|
+
}
|
|
3267
|
+
for (const kid of kids.flat(3)) {
|
|
3268
|
+
if (kid == null || kid === false) continue
|
|
3269
|
+
el.append(kid.nodeType ? kid : document.createTextNode(String(kid)))
|
|
3270
|
+
}
|
|
3271
|
+
return el
|
|
3272
|
+
}
|
|
3273
|
+
|
|
3274
|
+
function count(checks) {
|
|
3275
|
+
const c = { 'fail': 0, 'warning': 0, 'not-configured': 0, 'pass': 0 }
|
|
3276
|
+
for (const k of checks) c[k.verdict]++
|
|
3277
|
+
return c
|
|
3278
|
+
}
|
|
3279
|
+
|
|
3280
|
+
function drawTop() {
|
|
3281
|
+
const when = new Date(R.startedAt)
|
|
3282
|
+
const meta = document.getElementById('meta')
|
|
3283
|
+
meta.append(
|
|
3284
|
+
h('code', {}, R.target), ' \xB7 ',
|
|
3285
|
+
when.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }), ' \xB7 ',
|
|
3286
|
+
(R.durationMs / 1000).toFixed(1) + ' s \xB7 ',
|
|
3287
|
+
'created ' + R.records.created + ' records, deleted ' + R.records.deleted,
|
|
3288
|
+
R.records.left ? ', left ' + R.records.left + ' behind' : '',
|
|
3289
|
+
R.records.unidentified ? ', and ' + R.records.unidentified + ' more creates succeeded without naming a record' : '',
|
|
3290
|
+
)
|
|
3291
|
+
document.title = 'badday report, ' + R.target
|
|
3292
|
+
document.getElementById('sample').hidden = !R.sample
|
|
3293
|
+
|
|
3294
|
+
const c = count(R.checks)
|
|
3295
|
+
const parts = [c.fail
|
|
3296
|
+
? [c.fail + (c.fail === 1 ? ' promise broken' : ' promises broken'), 'fail']
|
|
3297
|
+
: ['No promises broken', 'pass']]
|
|
3298
|
+
parts.push([c.pass + ' kept', 'pass'])
|
|
3299
|
+
if (c.warning) parts.push([c.warning + (c.warning === 1 ? ' warning' : ' warnings'), 'warning'])
|
|
3300
|
+
if (c['not-configured']) parts.push([c['not-configured'] + ' not tested', 'not-configured'])
|
|
3301
|
+
const h1 = document.getElementById('headline')
|
|
3302
|
+
parts.forEach(([text, cls], i) => h1.append(h('span', { class: cls }, text), i < parts.length - 1 ? ', ' : '.'))
|
|
3303
|
+
|
|
3304
|
+
document.getElementById('foot').append(
|
|
3305
|
+
'Made by ' + R.tool.name + ' ' + R.tool.version + '. ',
|
|
3306
|
+
'This report shows evidence for the controls a tool can test over HTTP. It says nothing about the rest of an organisation.',
|
|
3307
|
+
)
|
|
3308
|
+
|
|
3309
|
+
const btn = document.getElementById('theme')
|
|
3310
|
+
const label = () => { btn.textContent = document.documentElement.dataset.theme === 'dark' ? 'Light theme' : 'Dark theme' }
|
|
3311
|
+
btn.addEventListener('click', () => {
|
|
3312
|
+
const next = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark'
|
|
3313
|
+
document.documentElement.dataset.theme = next
|
|
3314
|
+
try { localStorage.setItem('badday-theme', next) } catch (e) {}
|
|
3315
|
+
label()
|
|
3316
|
+
})
|
|
3317
|
+
label()
|
|
3318
|
+
}
|
|
3319
|
+
|
|
3320
|
+
function drawTabs() {
|
|
3321
|
+
const tabs = document.getElementById('tabs')
|
|
3322
|
+
tabs.replaceChildren(...[{ id: 'results', short: 'Results' }, ...R.standards].map(t =>
|
|
3323
|
+
h('button', {
|
|
3324
|
+
type: 'button', role: 'tab', 'aria-selected': String(state.tab === t.id),
|
|
3325
|
+
onclick: () => { state.tab = t.id; draw() },
|
|
3326
|
+
}, t.short)))
|
|
3327
|
+
}
|
|
3328
|
+
|
|
3329
|
+
function facts(c) {
|
|
3330
|
+
const f = c.evidence && c.evidence.facts
|
|
3331
|
+
if (!f || !f.length) return null
|
|
3332
|
+
return h('table', { class: 'facts' },
|
|
3333
|
+
h('tr', {}, h('th', {}), h('th', {}, 'A correct backend'), h('th', {}, 'Your backend')),
|
|
3334
|
+
f.map(x => h('tr', {}, h('td', {}, x.label), h('td', {}, x.expected), h('td', { class: 'got' }, x.actual))))
|
|
3335
|
+
}
|
|
3336
|
+
|
|
3337
|
+
function bodyText(b) {
|
|
3338
|
+
if (b == null || b === '') return ''
|
|
3339
|
+
return typeof b === 'string' ? b : JSON.stringify(b, null, 2)
|
|
3340
|
+
}
|
|
3341
|
+
|
|
3342
|
+
function raw(first, msg, tail) {
|
|
3343
|
+
const head = Object.entries(msg.headers || {}).map(([k, v]) => k + ': ' + v).join('\\n')
|
|
3344
|
+
const body = bodyText(msg.body)
|
|
3345
|
+
return [first, head, body ? '\\n' + body : '', tail ? '\\n' + tail : ''].filter(Boolean).join('\\n')
|
|
3346
|
+
}
|
|
3347
|
+
|
|
3348
|
+
function timeline(c) {
|
|
3349
|
+
const ex = c.evidence && c.evidence.exchanges
|
|
3350
|
+
if (!ex || !ex.length) return null
|
|
3351
|
+
const LIMIT = 6
|
|
3352
|
+
const rows = ex.map((x, i) => h('details', { class: 'ex', hidden: i >= LIMIT && ex.length > LIMIT + 1 },
|
|
3353
|
+
h('summary', {},
|
|
3354
|
+
h('span', { class: 'at' }, '+' + x.at + ' ms'),
|
|
3355
|
+
h('span', { class: 'actor' }, x.actor || ''),
|
|
3356
|
+
h('span', { class: 'req' }, x.request.method + ' ' + x.request.path),
|
|
3357
|
+
h('span', { class: 'status' }, x.response ? x.response.status : 'none'),
|
|
3358
|
+
h('span', { class: 'note' }, x.note || '')),
|
|
3359
|
+
h('div', { class: 'raw' },
|
|
3360
|
+
h('div', {}, h('b', {}, 'Request, as ' + (x.actor || 'nobody')),
|
|
3361
|
+
h('pre', {}, raw(x.request.method + ' ' + x.request.path, x.request))),
|
|
3362
|
+
h('div', {}, h('b', {}, x.response ? 'Response, after ' + x.response.ms + ' ms' : 'No response'),
|
|
3363
|
+
h('pre', {}, x.response ? raw('HTTP ' + x.response.status, x.response, x.response.bodyNote) : (x.note || ''))))))
|
|
3364
|
+
const box = h('div', { class: 'timeline' }, rows)
|
|
3365
|
+
const hiddenRows = rows.filter(r => r.hidden)
|
|
3366
|
+
if (hiddenRows.length) {
|
|
3367
|
+
const more = h('button', { class: 'more', type: 'button', onclick: () => { hiddenRows.forEach(r => { r.hidden = false }); more.remove() } },
|
|
3368
|
+
'Show all ' + ex.length + ' requests')
|
|
3369
|
+
box.append(more)
|
|
3370
|
+
}
|
|
3371
|
+
return box
|
|
3372
|
+
}
|
|
3373
|
+
|
|
3374
|
+
function fix(c) {
|
|
3375
|
+
if (!c.fixPrompt) return null
|
|
3376
|
+
const btn = h('button', { class: 'btn', type: 'button' }, 'Copy fix prompt')
|
|
3377
|
+
btn.addEventListener('click', async () => {
|
|
3378
|
+
try { await navigator.clipboard.writeText(c.fixPrompt) } catch (e) {
|
|
3379
|
+
const ta = h('textarea', { style: 'position:fixed;opacity:0' })
|
|
3380
|
+
ta.value = c.fixPrompt
|
|
3381
|
+
document.body.append(ta); ta.select(); document.execCommand('copy'); ta.remove()
|
|
3382
|
+
}
|
|
3383
|
+
btn.textContent = 'Copied'
|
|
3384
|
+
setTimeout(() => { btn.textContent = 'Copy fix prompt' }, 1500)
|
|
3385
|
+
})
|
|
3386
|
+
return h('div', { class: 'fix' },
|
|
3387
|
+
h('div', { class: 'fix-head' }, h('b', {}, 'Fix prompt, to paste into your AI coding tool'), btn),
|
|
3388
|
+
h('p', {}, c.fixPrompt))
|
|
3389
|
+
}
|
|
3390
|
+
|
|
3391
|
+
function chips(c) {
|
|
3392
|
+
if (!c.controls || !c.controls.length) return null
|
|
3393
|
+
return h('div', { class: 'chips' }, 'Evidence for',
|
|
3394
|
+
c.controls.map(k => h('button', {
|
|
3395
|
+
class: 'chip', type: 'button',
|
|
3396
|
+
onclick: () => { state.tab = k.standard; draw(); scrollTo(0, 0) },
|
|
3397
|
+
}, standardById[k.standard].short + ' ' + k.id)))
|
|
3398
|
+
}
|
|
3399
|
+
|
|
3400
|
+
function checkCard(c, compact) {
|
|
3401
|
+
const v = VERDICTS[c.verdict]
|
|
3402
|
+
const chev = h('span', { class: 'chev', 'aria-hidden': 'true' }, '\u203A')
|
|
3403
|
+
const summary = compact
|
|
3404
|
+
? h('summary', {}, h('span', { class: 'badge' }, v.label), h('span', { class: 'title' }, c.title),
|
|
3405
|
+
h('code', { class: 'name' }, c.name), chev)
|
|
3406
|
+
: h('summary', {}, h('span', { class: 'badge' }, v.label), h('span', { class: 'title' }, c.title), chev,
|
|
3407
|
+
h('span', { class: 'sum' }, c.summary),
|
|
3408
|
+
h('span', { class: 'tags' }, h('code', {}, c.id || c.name), ' \xB7 ' + packTitle[c.pack]))
|
|
3409
|
+
return h('details', { class: 'check ' + c.verdict + (compact ? ' compact' : ''), id: 'check-' + (c.id || c.name) },
|
|
3410
|
+
summary,
|
|
3411
|
+
h('div', { class: 'body' }, compact && h('p', { class: 'sum' }, c.summary), facts(c), timeline(c), fix(c), chips(c)))
|
|
3412
|
+
}
|
|
3413
|
+
|
|
3414
|
+
function drawResults(view) {
|
|
3415
|
+
view.append(h('div', { class: 'packs' }, R.packs.map(p => {
|
|
3416
|
+
const mine = R.checks.filter(c => c.pack === p.id)
|
|
3417
|
+
const c = count(mine)
|
|
3418
|
+
return h('button', {
|
|
3419
|
+
class: 'pack', type: 'button', 'aria-pressed': String(state.pack === p.id),
|
|
3420
|
+
onclick: () => { state.pack = state.pack === p.id ? null : p.id; draw() },
|
|
3421
|
+
},
|
|
3422
|
+
h('b', {}, p.title), h('small', {}, p.about),
|
|
3423
|
+
h('div', { class: 'bar' }, ORDER.filter(k => c[k]).map(k => h('span', { class: k, style: 'flex:' + c[k] }))),
|
|
3424
|
+
h('div', { class: 'counts' }, ORDER.filter(k => c[k]).map(k => h('span', {}, c[k] + ' ' + VERDICTS[k].one))))
|
|
3425
|
+
})))
|
|
3426
|
+
|
|
3427
|
+
if (state.pack) {
|
|
3428
|
+
view.append(h('p', { class: 'filter-note' }, 'Showing the ' + packTitle[state.pack].toLowerCase() + ' pack only. ',
|
|
3429
|
+
h('button', { type: 'button', onclick: () => { state.pack = null; draw() } }, 'Show every pack')))
|
|
3430
|
+
}
|
|
3431
|
+
|
|
3432
|
+
const shown = R.checks.filter(c => !state.pack || c.pack === state.pack)
|
|
3433
|
+
for (const verdict of ORDER) {
|
|
3434
|
+
const list = shown.filter(c => c.verdict === verdict)
|
|
3435
|
+
if (!list.length) continue
|
|
3436
|
+
view.append(h('h2', {}, VERDICTS[verdict].heading + ', ' + list.length))
|
|
3437
|
+
if (verdict !== 'pass') { view.append(...list.map(c => checkCard(c, false))); continue }
|
|
3438
|
+
for (const p of R.packs) {
|
|
3439
|
+
const inPack = list.filter(c => c.pack === p.id)
|
|
3440
|
+
if (!inPack.length) continue
|
|
3441
|
+
view.append(h('h3', {}, p.title), h('div', { class: 'group' }, inPack.map(c => checkCard(c, true))))
|
|
3442
|
+
}
|
|
3443
|
+
}
|
|
3444
|
+
}
|
|
3445
|
+
|
|
3446
|
+
function controlVerdict(checks) {
|
|
3447
|
+
for (const v of ['fail', 'warning', 'pass']) if (checks.some(c => c.verdict === v)) return v
|
|
3448
|
+
return 'not-configured'
|
|
3449
|
+
}
|
|
3450
|
+
|
|
3451
|
+
function goToCheck(name) {
|
|
3452
|
+
state.tab = 'results'; state.pack = null; draw()
|
|
3453
|
+
const el = document.getElementById('check-' + name)
|
|
3454
|
+
if (!el) return
|
|
3455
|
+
el.open = true
|
|
3456
|
+
el.classList.add('target')
|
|
3457
|
+
el.scrollIntoView({ block: 'center' })
|
|
3458
|
+
setTimeout(() => el.classList.remove('target'), 1600)
|
|
3459
|
+
}
|
|
3460
|
+
|
|
3461
|
+
function drawStandard(view, s) {
|
|
3462
|
+
const controls = s.controls.map(k => {
|
|
3463
|
+
const checks = R.checks.filter(c => (c.controls || []).some(x => x.standard === s.id && x.id === k.id))
|
|
3464
|
+
return { ...k, checks, verdict: controlVerdict(checks) }
|
|
3465
|
+
}).filter(k => k.checks.length)
|
|
3466
|
+
const n = v => controls.filter(k => k.verdict === v).length
|
|
3467
|
+
const tested = controls.length - n('not-configured')
|
|
3468
|
+
const lede = [n('pass') + ' of ' + tested + ' testable controls have passing evidence.']
|
|
3469
|
+
if (n('fail')) lede.push(n('fail') + ' failed.')
|
|
3470
|
+
if (n('warning')) lede.push(n('warning') + (n('warning') === 1 ? ' carries a warning.' : ' carry a warning.'))
|
|
3471
|
+
if (n('not-configured')) lede.push(n('not-configured') + ' could not be tested with this config.')
|
|
3472
|
+
lede.push(R.needsPerson.length + ' areas of this standard cannot be tested from outside and are listed below.')
|
|
3473
|
+
|
|
3474
|
+
view.append(
|
|
3475
|
+
h('p', { class: 'draft' }, R.mappingLabel),
|
|
3476
|
+
h('p', { class: 'lede' }, lede.join(' ')),
|
|
3477
|
+
h('h2', {}, s.title + ', controls with evidence'))
|
|
3478
|
+
|
|
3479
|
+
const rank = { 'fail': 0, 'warning': 1, 'not-configured': 2, 'pass': 3 }
|
|
3480
|
+
controls.sort((a, b) => rank[a.verdict] - rank[b.verdict])
|
|
3481
|
+
for (const k of controls) {
|
|
3482
|
+
view.append(h('section', { class: 'control ' + k.verdict },
|
|
3483
|
+
h('div', { class: 'control-head' },
|
|
3484
|
+
h('code', {}, k.id), h('span', { class: 'ctitle' }, k.title),
|
|
3485
|
+
h('span', { class: 'badge' }, CONTROL_LABEL[k.verdict])),
|
|
3486
|
+
h('div', { class: 'rows' }, k.checks
|
|
3487
|
+
.slice().sort((a, b) => rank[a.verdict] - rank[b.verdict])
|
|
3488
|
+
.map(c => h('button', { class: 'row ' + c.verdict, type: 'button', onclick: () => goToCheck(c.id || c.name) },
|
|
3489
|
+
h('span', {}, h('span', { class: 'badge' }, VERDICTS[c.verdict].label)),
|
|
3490
|
+
h('span', { class: 'rt' }, c.title),
|
|
3491
|
+
h('code', {}, c.name))))))
|
|
3492
|
+
}
|
|
3493
|
+
|
|
3494
|
+
view.append(
|
|
3495
|
+
h('h2', {}, 'Needs a person'),
|
|
3496
|
+
h('p', { class: 'hint' }, 'A tool that sends HTTP requests cannot see these. Nothing on this page is evidence for them, in either direction.'),
|
|
3497
|
+
h('ul', { class: 'person' }, R.needsPerson.map(x => h('li', {}, x))))
|
|
3498
|
+
}
|
|
3499
|
+
|
|
3500
|
+
function draw() {
|
|
3501
|
+
drawTabs()
|
|
3502
|
+
const view = document.getElementById('view')
|
|
3503
|
+
view.replaceChildren()
|
|
3504
|
+
if (state.tab === 'results') drawResults(view)
|
|
3505
|
+
else drawStandard(view, standardById[state.tab])
|
|
3506
|
+
}
|
|
3507
|
+
|
|
3508
|
+
drawTop()
|
|
3509
|
+
draw()
|
|
3510
|
+
|
|
3511
|
+
// A link can point at a standard, as #hipaa, or at one check, as #check-duplicate-submit.
|
|
3512
|
+
const hash = decodeURIComponent(location.hash.slice(1))
|
|
3513
|
+
if (standardById[hash]) { state.tab = hash; draw() }
|
|
3514
|
+
else if (hash.startsWith('check-')) goToCheck(hash.slice(6))
|
|
3515
|
+
</script>
|
|
3516
|
+
</body>
|
|
3517
|
+
</html>
|
|
3518
|
+
` : readFileSync(new URL("./html/template.html", import.meta.url), "utf8");
|
|
3519
|
+
function renderHtml(result) {
|
|
3520
|
+
const data = JSON.stringify(result).replace(/</g, "\\u003c");
|
|
3521
|
+
return template().replace("__BADDAY_RESULT__", () => data);
|
|
3522
|
+
}
|
|
3523
|
+
|
|
3524
|
+
// src/report/terminal.ts
|
|
3525
|
+
var LABEL = { "fail": "BROKEN", "warning": "WARNING", "not-configured": "NOT TESTED", "pass": "KEPT" };
|
|
3526
|
+
var WORD = { "fail": "broken", "warning": "warning", "not-configured": "not tested", "pass": "kept" };
|
|
3527
|
+
var COLOR = { "fail": 31, "warning": 33, "not-configured": 90, "pass": 32 };
|
|
3528
|
+
var ORDER = ["fail", "warning", "not-configured", "pass"];
|
|
3529
|
+
var SHOWN_EXCHANGES = 6;
|
|
3530
|
+
var PAD = " ".repeat(12);
|
|
3531
|
+
function headline(checks2) {
|
|
3532
|
+
const n = (v) => checks2.filter((c) => c.verdict === v).length;
|
|
3533
|
+
const parts = [n("fail") ? `${n("fail")} ${n("fail") === 1 ? "promise" : "promises"} broken` : "No promises broken", `${n("pass")} kept`];
|
|
3534
|
+
if (n("warning")) parts.push(`${n("warning")} ${n("warning") === 1 ? "warning" : "warnings"}`);
|
|
3535
|
+
if (n("not-configured")) parts.push(`${n("not-configured")} not tested`);
|
|
3536
|
+
return parts.join(", ") + ".";
|
|
3537
|
+
}
|
|
3538
|
+
function wrap(text2, width) {
|
|
3539
|
+
const lines = [];
|
|
3540
|
+
for (const paragraph of text2.split("\n")) {
|
|
3541
|
+
let line = "";
|
|
3542
|
+
for (const word of paragraph.split(" ")) {
|
|
3543
|
+
if (line && line.length + word.length + 1 > width) {
|
|
3544
|
+
lines.push(line);
|
|
3545
|
+
line = word;
|
|
3546
|
+
} else line = line ? line + " " + word : word;
|
|
3547
|
+
}
|
|
3548
|
+
lines.push(line);
|
|
3549
|
+
}
|
|
3550
|
+
return lines;
|
|
3551
|
+
}
|
|
3552
|
+
function renderTerminal(result, opts = {}) {
|
|
3553
|
+
const failures = result.checks.filter((c) => c.verdict === "fail").length;
|
|
3554
|
+
const prompts = opts.detail || failures <= 3;
|
|
3555
|
+
const paint = (code, text2) => opts.color ? `\x1B[${code}m${text2}\x1B[0m` : text2;
|
|
3556
|
+
const width = Math.min(opts.width && opts.width >= 60 ? opts.width : 100, 110) - PAD.length;
|
|
3557
|
+
const out = [];
|
|
3558
|
+
out.push(paint(1, "badday " + result.tool.version) + " " + result.target, "", paint(1, headline(result.checks)), "");
|
|
3559
|
+
for (const verdict of ORDER.slice(0, 3)) {
|
|
3560
|
+
for (const check of result.checks.filter((c) => c.verdict === verdict)) {
|
|
3561
|
+
const [first, ...rest] = wrap(check.title, width);
|
|
3562
|
+
out.push(paint(COLOR[verdict], paint(1, LABEL[verdict].padEnd(PAD.length))) + paint(1, first), ...rest.map((l) => PAD + paint(1, l)));
|
|
3563
|
+
out.push(...wrap(check.summary, width).map((l) => PAD + l));
|
|
3564
|
+
out.push(PAD + paint(90, `${check.id}, ${check.pack} pack`));
|
|
3565
|
+
for (const fact of check.evidence?.facts ?? []) {
|
|
3566
|
+
out.push("", PAD + fact.label, PAD + ` a correct backend ${fact.expected}`, PAD + " your backend " + paint(COLOR[verdict], fact.actual));
|
|
3567
|
+
}
|
|
3568
|
+
const exchanges = opts.detail ? check.evidence?.exchanges ?? [] : [];
|
|
3569
|
+
if (exchanges.length) out.push("");
|
|
3570
|
+
for (const x of exchanges.slice(0, SHOWN_EXCHANGES)) {
|
|
3571
|
+
const status = x.response ? String(x.response.status) : "none";
|
|
3572
|
+
out.push(PAD + paint(90, `+${x.at} ms`.padEnd(9) + (x.actor ?? "").padEnd(7)) + `${x.request.method} ${x.request.path}`.padEnd(24) + " " + status.padEnd(5) + paint(90, x.note ?? ""));
|
|
3573
|
+
}
|
|
3574
|
+
if (exchanges.length > SHOWN_EXCHANGES) out.push(PAD + paint(90, `and ${exchanges.length - SHOWN_EXCHANGES} more requests, in the JSON and HTML reports`));
|
|
3575
|
+
if (check.fixPrompt && prompts) out.push("", PAD + "Fix prompt, to paste into your AI coding tool:", ...wrap(check.fixPrompt, width - 2).map((l) => PAD + " " + paint(90, l)));
|
|
3576
|
+
out.push("");
|
|
3577
|
+
}
|
|
3578
|
+
}
|
|
3579
|
+
for (const pack of result.packs) {
|
|
3580
|
+
const mine = result.checks.filter((c) => c.pack === pack.id);
|
|
3581
|
+
const counts = ORDER.map((v) => [v, mine.filter((c) => c.verdict === v).length]).filter(([, n]) => n);
|
|
3582
|
+
out.push(pack.title.padEnd(24) + counts.map(([v, n]) => paint(COLOR[v], `${n} ${WORD[v]}`)).join(" "));
|
|
3583
|
+
}
|
|
3584
|
+
const { created, deleted, left, unidentified } = result.records;
|
|
3585
|
+
const unnamed = unidentified ? ` ${unidentified} more create ${unidentified === 1 ? "request" : "requests"} succeeded without naming a record, so badday could not delete what they made.` : "";
|
|
3586
|
+
out.push("", paint(90, `Created ${created} records, deleted ${deleted}${left ? `, left ${left} behind` : ""}.${unnamed} Took ${(result.durationMs / 1e3).toFixed(1)} s.`));
|
|
3587
|
+
return out.join("\n") + "\n";
|
|
3588
|
+
}
|
|
3589
|
+
|
|
3590
|
+
// src/cli/brief.ts
|
|
3591
|
+
function fields(schema, at, out) {
|
|
3592
|
+
for (const alt of schema.oneOf ?? []) if (alt.type === "object") fields(alt, at, out);
|
|
3593
|
+
if (schema.type === "array" && schema.items) fields(schema.items, at + "[]", out);
|
|
3594
|
+
for (const [key, child] of Object.entries(schema.properties ?? {})) {
|
|
3595
|
+
if (key === "$schema") continue;
|
|
3596
|
+
const path2 = at ? `${at}.${key}` : key;
|
|
3597
|
+
const required = schema.required?.includes(key) ? "required" : "optional";
|
|
3598
|
+
const type = child.enum ? child.enum.map((v) => `"${v}"`).join(" | ") : child.type ?? child.oneOf?.map((s) => s.type).join(" | ");
|
|
3599
|
+
out.push(`- \`${path2}\` (${type}, ${required}). ${child.description ?? ""}`);
|
|
3600
|
+
fields(child, path2, out);
|
|
3601
|
+
}
|
|
3602
|
+
if (typeof schema.additionalProperties === "object" && schema.additionalProperties.type === "object") fields(schema.additionalProperties, at + ".<name>", out);
|
|
3603
|
+
return out;
|
|
3604
|
+
}
|
|
3605
|
+
var EXAMPLE = {
|
|
3606
|
+
baseUrl: "http://localhost:3000",
|
|
3607
|
+
actors: {
|
|
3608
|
+
alice: { headers: { Authorization: "Bearer <token of test user 1>" } },
|
|
3609
|
+
bob: { headers: { Authorization: "Bearer <token of test user 2>" } }
|
|
3610
|
+
},
|
|
3611
|
+
resources: [{
|
|
3612
|
+
name: "orders",
|
|
3613
|
+
create: { method: "POST", path: "/orders", body: { item: "pizza", qty: 1 } },
|
|
3614
|
+
get: "/orders/:id",
|
|
3615
|
+
list: { path: "/orders", limitParam: "limit" },
|
|
3616
|
+
update: { method: "PATCH", path: "/orders/:id", body: { qty: 2 } },
|
|
3617
|
+
remove: { method: "DELETE", path: "/orders/:id" },
|
|
3618
|
+
idempotencyHeader: "Idempotency-Key",
|
|
3619
|
+
protectedFields: ["userId", "total", "status"],
|
|
3620
|
+
markerField: "note"
|
|
3621
|
+
}]
|
|
3622
|
+
};
|
|
3623
|
+
function agentBrief() {
|
|
3624
|
+
return `# badday, a brief for a coding agent
|
|
3625
|
+
|
|
3626
|
+
badday tests a running HTTP backend for broken promises: duplicate charges, replayed webhooks, data of one user shown to another, and crashes on bad input. It sends real requests and never reads the code of the backend. You write one file, \`badday.config.json\`. badday does the rest.
|
|
3627
|
+
|
|
3628
|
+
If a person can use the app in a browser or an API client, \`npx badday record --target <address>\` writes the config from their traffic, and you can skip to step 3. Read the config it wrote and correct what it lists as open.
|
|
3629
|
+
|
|
3630
|
+
## The loop
|
|
3631
|
+
|
|
3632
|
+
1. Find the routes and the authentication of the backend in this repository.
|
|
3633
|
+
2. Write \`badday.config.json\` in the project root.
|
|
3634
|
+
3. Run \`npx badday validate\`. Each problem it prints has a path, a problem and a fix. Correct the file and run the command again, until it prints no problem.
|
|
3635
|
+
4. Start the backend, if it does not run.
|
|
3636
|
+
5. Run \`npx badday run --json\`.
|
|
3637
|
+
6. For each check with the verdict \`fail\`, read its \`summary\`, \`evidence\` and \`fixPrompt\`. Fix the backend. Run step 5 again.
|
|
3638
|
+
|
|
3639
|
+
## Where to look
|
|
3640
|
+
|
|
3641
|
+
- Routes. Look in the router files, the controllers, and an OpenAPI file if one exists. For each resource, find the route that creates a record, the route that reads one record by id, the route that lists records, the route that updates and the route that deletes.
|
|
3642
|
+
- Authentication. Find how a request proves who sends it: a bearer token, a cookie or an API key header.
|
|
3643
|
+
- Test users. badday needs the credentials of two different users. Look in seed scripts, test fixtures and \`.env.example\`. If the repository has none, create two users through the signup route of the running backend.
|
|
3644
|
+
- Webhooks. Find the route that receives events, the code that verifies the signature, and the name of the secret.
|
|
3645
|
+
|
|
3646
|
+
Do not guess a value. If the repository does not show a value, ask the person.
|
|
3647
|
+
|
|
3648
|
+
## The config
|
|
3649
|
+
|
|
3650
|
+
A small example:
|
|
3651
|
+
|
|
3652
|
+
\`\`\`json
|
|
3653
|
+
${JSON.stringify(EXAMPLE, null, 2)}
|
|
3654
|
+
\`\`\`
|
|
3655
|
+
|
|
3656
|
+
Every field:
|
|
3657
|
+
|
|
3658
|
+
${fields(configSchema, "", []).join("\n")}
|
|
3659
|
+
|
|
3660
|
+
\`npx badday schema\` prints the same as a JSON Schema.
|
|
3661
|
+
|
|
3662
|
+
Rules for a config that tests the most:
|
|
3663
|
+
|
|
3664
|
+
- Give two actors. With one actor, the access checks report "not tested".
|
|
3665
|
+
- Give \`remove\`, so badday can delete the records it creates.
|
|
3666
|
+
- Give \`list\` with \`limitParam\`, so badday can count records and ask for small pages.
|
|
3667
|
+
- Give \`markerField\` if the create body has a free-text field.
|
|
3668
|
+
- Leave out what the backend does not have. A check whose input is missing reports "not tested". It never reports a pass.
|
|
3669
|
+
|
|
3670
|
+
Describe the backend as it is. Read one real create response and one real list response before you write the config:
|
|
3671
|
+
|
|
3672
|
+
- If request and response bodies wrap the record, as \`{ "article": { ... } }\`, set \`envelope\` to that field. If only responses wrap it, under \`data\` or the name of the resource, set nothing. badday finds it.
|
|
3673
|
+
- If records are looked up by a slug or a name and not an id, set \`idField\` to that field. If the client picks that name, set \`markerField\` to the same field.
|
|
3674
|
+
- If the list pages by page number or offset, set \`list.pageParam\` or \`list.offsetParam\`. If it takes no page size at all, leave \`limitParam\` out.
|
|
3675
|
+
- If a read route is public or shared by design, such as a blog feed, name it in \`public\` or \`shared\`. Without that, badday reports it as a leak.
|
|
3676
|
+
- Set \`idempotencyHeader\` or \`idempotencyField\` only if the code reads one. Most backends have neither, and the replay checks then report "not tested".
|
|
3677
|
+
- If tokens expire or come from a login route, write \`badday.config.mjs\` in place of the JSON file. It can log in with \`fetch\` and top-level \`await\`, then \`export default\` the config. \`npx badday validate\` reads it the same way.
|
|
3678
|
+
|
|
3679
|
+
## The result of \`run --json\`
|
|
3680
|
+
|
|
3681
|
+
One JSON document on stdout. \`checks\` is a list. Each check has:
|
|
3682
|
+
|
|
3683
|
+
- \`id\`, \`name\` and \`pack\`
|
|
3684
|
+
- \`verdict\`: \`pass\`, \`fail\`, \`warning\` or \`not-configured\`
|
|
3685
|
+
- \`title\`: the result in one sentence
|
|
3686
|
+
- \`summary\`: what badday sent and what the backend did
|
|
3687
|
+
- \`evidence.facts\`: what a correct backend does, against what this one did
|
|
3688
|
+
- \`evidence.exchanges\`: each request and its response, with credentials replaced by \`[redacted]\`
|
|
3689
|
+
- \`fixPrompt\`: on a failure, the defect and the standard remedy
|
|
3690
|
+
- \`controls\`: the controls of HIPAA, GDPR, PCI DSS, SOC 2 and the OWASP API Top 10 that the check gives evidence for. This mapping is a draft, written by developers. It is not a compliance assessment.
|
|
3691
|
+
|
|
3692
|
+
A \`not-configured\` check did not run. Its \`summary\` says what to add to the config.
|
|
3693
|
+
|
|
3694
|
+
## Exit codes
|
|
3695
|
+
|
|
3696
|
+
- 0: no check failed.
|
|
3697
|
+
- 1: one check or more failed.
|
|
3698
|
+
- 2: badday could not run. The config is not valid, or nothing answers at \`baseUrl\`. The message on stderr names the fix.
|
|
3699
|
+
|
|
3700
|
+
## Safety
|
|
3701
|
+
|
|
3702
|
+
- badday creates records and sends hostile input. Run it against a local or a test backend.
|
|
3703
|
+
- badday refuses a host that is not local. The flag \`--i-own-this-server <hostname>\` lifts that. Use it only if the person tells you to.
|
|
3704
|
+
- Before it starts, badday prints the most records it can create. If the config has \`remove\`, badday deletes what it created.
|
|
3705
|
+
|
|
3706
|
+
## Other commands
|
|
3707
|
+
|
|
3708
|
+
- \`npx badday list\` prints every check with the promise it tests.
|
|
3709
|
+
- \`npx badday run --only replay,cross-user-read\` runs some packs or checks. \`--skip\` leaves some out.
|
|
3710
|
+
- \`npx badday run --detail\` prints the requests of each failure in the terminal.
|
|
3711
|
+
- \`npx badday init --from <OpenAPI file or URL>\` drafts a config from an OpenAPI description in JSON. Check the draft before you use it.
|
|
3712
|
+
- \`npx badday demo\` runs every check against a small bundled shop that has every defect.
|
|
3713
|
+
`;
|
|
3714
|
+
}
|
|
3715
|
+
var PASTE_PROMPT = `Set up badday for this project. Run "npx badday init --agent" and follow the brief it prints. Write badday.config.json in the project root, then run "npx badday validate" until it reports no problem. Do not guess a route or a token. Ask me if the repository does not show one. When the config is valid, tell me to run "npx badday".`;
|
|
3716
|
+
|
|
3717
|
+
// src/cli/record.ts
|
|
3718
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync } from "node:fs";
|
|
3719
|
+
import { resolve as resolve2 } from "node:path";
|
|
3720
|
+
import { createInterface } from "node:readline/promises";
|
|
3721
|
+
|
|
3722
|
+
// src/learn/infer.ts
|
|
3723
|
+
var isObj = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
3724
|
+
var ok2 = (seen) => seen.status >= 200 && seen.status < 300;
|
|
3725
|
+
var STATIC = /\.(js|mjs|css|png|jpe?g|gif|svg|ico|map|woff2?|ttf|html?|txt|webmanifest)$/i;
|
|
3726
|
+
var ACTION = /(^|\/)(login|logout|signin|signup|sign-in|sign-up|register|token|tokens|auth|oauth|session|sessions|refresh|password|verify|otp|me|health|healthcheck|ping)(\/|$)/i;
|
|
3727
|
+
var ID_SHAPE = /^(\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{12,}|[0-9A-HJKMNP-TV-Z]{26})$/i;
|
|
3728
|
+
var WRAPPERS2 = ["data", "item", "result", "record"];
|
|
3729
|
+
var ARRAY_FIELDS = ["data", "items", "results"];
|
|
3730
|
+
var MARKER_NAMES = ["note", "notes", "description", "comment", "title", "name", "subject", "text", "body", "content", "label", "summary", "message"];
|
|
3731
|
+
var LIMIT_NAMES = ["limit", "per_page", "perpage", "page_size", "pagesize", "size", "take", "count"];
|
|
3732
|
+
var PAGE_NAMES = ["page", "p", "page_number", "pagenumber"];
|
|
3733
|
+
var OFFSET_NAMES = ["offset", "skip", "start"];
|
|
3734
|
+
var CURSOR_NAMES = ["cursor", "after", "page_token", "pagetoken", "starting_after", "next"];
|
|
3735
|
+
var SERVER_OWNED = /^(user_?id|owner(_?id)?|account_?id|author(_?id)?|tenant_?id|org(anization)?_?id|created_?by(_?id)?|role|is_?admin|admin|is_?superuser|total|balance|verified|is_?verified)$/i;
|
|
3736
|
+
var KEY_FIELD = /^(idempotency_?key|request_?id|transaction_?id|client_?(request_?)?token)$/i;
|
|
3737
|
+
var CREDENTIALS = ["authorization", "x-api-key", "x-auth-token", "cookie"];
|
|
3738
|
+
var singular = (name) => name.endsWith("ies") ? name.slice(0, -3) + "y" : name.endsWith("s") ? name.slice(0, -1) : name;
|
|
3739
|
+
function recordIn(body2, prefer) {
|
|
3740
|
+
if (!isObj(body2)) return null;
|
|
3741
|
+
if (prefer && isObj(body2[prefer])) return { record: body2[prefer], wrapper: prefer };
|
|
3742
|
+
for (const key of WRAPPERS2) if (isObj(body2[key])) return { record: body2[key], wrapper: key };
|
|
3743
|
+
const inner = Object.entries(body2).filter(([, value]) => isObj(value));
|
|
3744
|
+
const scalars = Object.values(body2).filter((value) => !isObj(value) && !Array.isArray(value)).length;
|
|
3745
|
+
if (inner.length === 1 && scalars === 0) return { record: inner[0][1], wrapper: inner[0][0] };
|
|
3746
|
+
return { record: body2, wrapper: null };
|
|
3747
|
+
}
|
|
3748
|
+
function rowsIn(body2) {
|
|
3749
|
+
if (Array.isArray(body2)) return { rows: body2.filter(isObj), field: null };
|
|
3750
|
+
if (!isObj(body2)) return null;
|
|
3751
|
+
const fields2 = Object.entries(body2).filter(([, value]) => Array.isArray(value));
|
|
3752
|
+
const named2 = ARRAY_FIELDS.map((name) => fields2.find(([key]) => key === name)).find(Boolean) ?? fields2[0];
|
|
3753
|
+
return named2 ? { rows: named2[1].filter(isObj), field: named2[0] } : null;
|
|
3754
|
+
}
|
|
3755
|
+
function actorOf(seen) {
|
|
3756
|
+
for (const name of CREDENTIALS) {
|
|
3757
|
+
const last = [...seen].reverse().find((s) => s.headers[name]);
|
|
3758
|
+
if (!last) continue;
|
|
3759
|
+
const headers = { [name === "authorization" ? "Authorization" : name === "cookie" ? "Cookie" : name]: last.headers[name] };
|
|
3760
|
+
if (name === "cookie") {
|
|
3761
|
+
for (const extra of ["x-csrf-token", "x-xsrf-token"]) if (last.headers[extra]) headers[extra] = last.headers[extra];
|
|
3762
|
+
}
|
|
3763
|
+
return { headers };
|
|
3764
|
+
}
|
|
3765
|
+
return null;
|
|
3766
|
+
}
|
|
3767
|
+
function learn(seen, baseUrl) {
|
|
3768
|
+
const notes = [];
|
|
3769
|
+
const open = [];
|
|
3770
|
+
const calls = seen.filter((s) => s.method !== "OPTIONS" && s.method !== "HEAD" && !STATIC.test(s.path));
|
|
3771
|
+
const actorNames = [...new Set(calls.map((s) => s.actor))];
|
|
3772
|
+
const actors2 = {};
|
|
3773
|
+
for (const name of actorNames) {
|
|
3774
|
+
const actor = actorOf(calls.filter((s) => s.actor === name));
|
|
3775
|
+
if (actor) actors2[name] = actor;
|
|
3776
|
+
else open.push(`The requests of ${name} carried no Authorization header, cookie or API key, so badday has no credentials for that user.`);
|
|
3777
|
+
}
|
|
3778
|
+
const [first, second] = Object.keys(actors2);
|
|
3779
|
+
if (first) notes.push(`${Object.keys(actors2).join(" and ")} log in with the ${Object.keys(actors2[first].headers)[0]} header.`);
|
|
3780
|
+
if (!second) open.push("Only one user was recorded. The access checks need two. Record again and log in as a second user in the second step.");
|
|
3781
|
+
const values = /* @__PURE__ */ new Set();
|
|
3782
|
+
const collect = (value, depth = 0) => {
|
|
3783
|
+
if (depth > 6) return;
|
|
3784
|
+
if (typeof value === "string" && value.length > 0 && value.length <= 120) values.add(value);
|
|
3785
|
+
else if (typeof value === "number") values.add(String(value));
|
|
3786
|
+
else if (Array.isArray(value)) value.slice(0, 200).forEach((v) => collect(v, depth + 1));
|
|
3787
|
+
else if (isObj(value)) Object.values(value).forEach((v) => collect(v, depth + 1));
|
|
3788
|
+
};
|
|
3789
|
+
for (const call of calls) if (ok2(call)) collect(call.resBody);
|
|
3790
|
+
const bare = (path2) => path2.length > 1 ? path2.replace(/\/+$/, "") : path2;
|
|
3791
|
+
const collections = new Set(calls.filter((s) => ok2(s) && (s.method === "POST" || s.method === "PUT" || s.method === "GET" && rowsIn(s.resBody))).map((s) => bare(s.path)));
|
|
3792
|
+
const groups = /* @__PURE__ */ new Map();
|
|
3793
|
+
const group = (path2) => groups.get(path2) ?? groups.set(path2, { path: path2, creates: [], lists: [], gets: [], updates: [], removes: [], ids: /* @__PURE__ */ new Set() }).get(path2);
|
|
3794
|
+
for (const call of calls) {
|
|
3795
|
+
if (!ok2(call)) continue;
|
|
3796
|
+
const path2 = bare(call.path);
|
|
3797
|
+
const cut = path2.lastIndexOf("/");
|
|
3798
|
+
const parent = path2.slice(0, cut);
|
|
3799
|
+
const last = decodeURIComponent(path2.slice(cut + 1));
|
|
3800
|
+
const isItem = cut > 0 && last !== "" && (ID_SHAPE.test(last) || values.has(last) && collections.has(parent));
|
|
3801
|
+
if (isItem && !ACTION.test(parent)) {
|
|
3802
|
+
const g = group(parent);
|
|
3803
|
+
g.ids.add(last);
|
|
3804
|
+
if (call.method === "GET") g.gets.push(call);
|
|
3805
|
+
else if (call.method === "DELETE") g.removes.push(call);
|
|
3806
|
+
else g.updates.push(call);
|
|
3807
|
+
} else if (!ACTION.test(call.path)) {
|
|
3808
|
+
if ((call.method === "POST" || call.method === "PUT") && isObj(call.body)) group(path2).creates.push(call);
|
|
3809
|
+
else if (call.method === "GET" && rowsIn(call.resBody)) group(path2).lists.push(call);
|
|
3810
|
+
}
|
|
3811
|
+
}
|
|
3812
|
+
const resources = [];
|
|
3813
|
+
const usable = [...groups.values()].filter((g) => g.creates.length && (g.lists.length || g.gets.length || g.updates.length || g.removes.length) || g.lists.length && g.gets.length).sort((a, b) => kinds(b) - kinds(a));
|
|
3814
|
+
for (const g of usable) {
|
|
3815
|
+
const name = (g.path.split("/").filter((part) => part && !/^v\d+$/i.test(part)).pop() ?? "").replace(/[^\w-]/g, "");
|
|
3816
|
+
if (!name || resources.some((r) => r.name === name)) continue;
|
|
3817
|
+
const resource = { name };
|
|
3818
|
+
const about = [];
|
|
3819
|
+
const mine = (list3) => [...list3].reverse().find((s) => s.actor === first) ?? list3[list3.length - 1];
|
|
3820
|
+
const create = mine(g.creates);
|
|
3821
|
+
let envelope;
|
|
3822
|
+
let sentRecord2 = null;
|
|
3823
|
+
let gotRecord = null;
|
|
3824
|
+
if (create) {
|
|
3825
|
+
const sent = recordIn(create.body);
|
|
3826
|
+
const got = recordIn(create.resBody, sent.wrapper ?? void 0);
|
|
3827
|
+
if (sent.wrapper && (got?.wrapper === sent.wrapper || sent.wrapper === singular(name) || sent.wrapper === name)) {
|
|
3828
|
+
envelope = resource.envelope = sent.wrapper;
|
|
3829
|
+
about.push(`bodies wrap the record in "${envelope}"`);
|
|
3830
|
+
}
|
|
3831
|
+
sentRecord2 = envelope ? sent.record : create.body;
|
|
3832
|
+
gotRecord = got?.record ?? null;
|
|
3833
|
+
const keyField = Object.keys(sentRecord2).find((field) => KEY_FIELD.test(field) && typeof sentRecord2[field] === "string");
|
|
3834
|
+
let body2 = create.body;
|
|
3835
|
+
if (keyField) {
|
|
3836
|
+
const { [keyField]: _key, ...rest } = sentRecord2;
|
|
3837
|
+
sentRecord2 = rest;
|
|
3838
|
+
body2 = envelope ? { ...body2, [envelope]: rest } : rest;
|
|
3839
|
+
resource.idempotencyField = keyField;
|
|
3840
|
+
about.push(`the create body carries an idempotency key in "${keyField}"`);
|
|
3841
|
+
}
|
|
3842
|
+
resource.create = { method: create.method, path: create.path, body: body2 };
|
|
3843
|
+
const key = Object.keys(create.headers).find((h) => /idempot/i.test(h));
|
|
3844
|
+
if (key) {
|
|
3845
|
+
resource.idempotencyHeader = key.replace(/(^|-)([a-z])/g, (_, dash, c) => dash + c.toUpperCase());
|
|
3846
|
+
about.push(`the create request carries a ${resource.idempotencyHeader} header`);
|
|
3847
|
+
}
|
|
3848
|
+
}
|
|
3849
|
+
const list2 = mine(g.lists);
|
|
3850
|
+
let rows = [];
|
|
3851
|
+
if (list2) {
|
|
3852
|
+
const found = rowsIn(list2.resBody);
|
|
3853
|
+
rows = found.rows;
|
|
3854
|
+
const spec = { path: list2.path };
|
|
3855
|
+
if (found.field && !ARRAY_FIELDS.includes(found.field) && found.field !== name) spec.items = found.field;
|
|
3856
|
+
const params = new Set(g.lists.flatMap((s) => s.query.map(([key]) => key)));
|
|
3857
|
+
const pick = (names2) => [...params].find((p) => names2.includes(p.toLowerCase()));
|
|
3858
|
+
const limit = pick(LIMIT_NAMES), page = pick(PAGE_NAMES), offset = pick(OFFSET_NAMES), cursor = pick(CURSOR_NAMES);
|
|
3859
|
+
if (limit) spec.limitParam = limit;
|
|
3860
|
+
if (cursor) {
|
|
3861
|
+
if (cursor !== "cursor") spec.cursorParam = cursor;
|
|
3862
|
+
} else if (page) spec.pageParam = page;
|
|
3863
|
+
else if (offset) spec.offsetParam = offset;
|
|
3864
|
+
resource.list = Object.keys(spec).length > 1 ? spec : list2.path;
|
|
3865
|
+
}
|
|
3866
|
+
const samples = [gotRecord, ...rows].filter(isObj);
|
|
3867
|
+
let idField = [...new Set(samples.flatMap(Object.keys))].find((field) => samples.some((row) => {
|
|
3868
|
+
const value = row[field];
|
|
3869
|
+
return (typeof value === "string" || typeof value === "number") && g.ids.has(String(value));
|
|
3870
|
+
}));
|
|
3871
|
+
if (!idField && samples.some((row) => "id" in row)) idField = "id";
|
|
3872
|
+
if (!idField) idField = ["_id", "uuid", "slug", "key"].find((field) => samples.some((row) => field in row));
|
|
3873
|
+
if (idField && idField !== "id") {
|
|
3874
|
+
resource.idField = idField;
|
|
3875
|
+
about.push(`a record is found by its "${idField}"`);
|
|
3876
|
+
}
|
|
3877
|
+
if (!idField) open.push(`badday could not tell which field of ${name} holds the id. Open one record in the app while badday records, or name the field in idField.`);
|
|
3878
|
+
if (sentRecord2) {
|
|
3879
|
+
const answerNamesRecord = !!gotRecord && !!idField && idField in gotRecord;
|
|
3880
|
+
if (idField && !answerNamesRecord && typeof sentRecord2[idField] === "string") {
|
|
3881
|
+
resource.markerField = idField;
|
|
3882
|
+
about.push(`the create answer names no record, and the client picks the "${idField}"`);
|
|
3883
|
+
} else {
|
|
3884
|
+
const typed = Object.entries(sentRecord2).filter(([, value]) => typeof value === "string" && /\s/.test(value) && !/@|^\d{4}-\d\d-\d\d|^https?:/.test(value)).sort((a, b) => b[1].length - a[1].length)[0]?.[0];
|
|
3885
|
+
const marker = MARKER_NAMES.find((field) => typeof sentRecord2[field] === "string") ?? typed;
|
|
3886
|
+
if (marker) resource.markerField = marker;
|
|
3887
|
+
else open.push(`badday found no free-text field in the create body of ${name}, so it cannot stamp its own records. Name one in markerField if there is one.`);
|
|
3888
|
+
}
|
|
3889
|
+
const owned = Object.keys(gotRecord ?? rows[0] ?? {}).filter((field) => SERVER_OWNED.test(field) && !(field in sentRecord2) && field !== idField);
|
|
3890
|
+
if (owned.length) resource.protectedFields = owned;
|
|
3891
|
+
}
|
|
3892
|
+
const item = g.path + "/:id";
|
|
3893
|
+
if (g.gets.length) resource.get = item;
|
|
3894
|
+
const update = mine(g.updates);
|
|
3895
|
+
if (update) resource.update = { method: update.method, path: item, ...isObj(update.body) ? { body: update.body } : {} };
|
|
3896
|
+
if (g.removes.length) resource.remove = { method: "DELETE", path: item };
|
|
3897
|
+
const anonymous = (list3) => list3.some((s) => !CREDENTIALS.some((name2) => s.headers[name2]));
|
|
3898
|
+
const open_ = [];
|
|
3899
|
+
if (anonymous(g.lists)) open_.push("list");
|
|
3900
|
+
if (anonymous(g.gets)) open_.push("get");
|
|
3901
|
+
if (open_.length) {
|
|
3902
|
+
resource.public = open_;
|
|
3903
|
+
about.push(`the app reads the ${open_.join(" and the ")} route with no login, so badday treats it as public`);
|
|
3904
|
+
}
|
|
3905
|
+
const routes = [resource.create && "create", resource.list && "list", resource.get && "read", resource.update && "update", resource.remove && "delete"].filter(Boolean);
|
|
3906
|
+
notes.push(`${name}: ${routes.join(", ")} at ${g.path}${about.length ? ". " + about.join(", ") : ""}.`);
|
|
3907
|
+
for (const [route3, what] of [["get", "opened one"], ["update", "changed one"], ["remove", "deleted one"], ["list", "listed them"]]) {
|
|
3908
|
+
if (!resource[route3]) open.push(`Nobody ${what} of the ${name} during the recording, so badday knows no ${route3 === "remove" ? "delete" : route3} route for them.`);
|
|
3909
|
+
}
|
|
3910
|
+
if (second && !resource.public?.includes("list")) {
|
|
3911
|
+
const made = new Set(g.creates.filter((s) => s.actor === first).map((s) => String(recordIn(s.resBody, envelope)?.record[idField ?? "id"] ?? "")).filter(Boolean));
|
|
3912
|
+
const shown = g.lists.filter((s) => s.actor === second).some((s) => rowsIn(s.resBody).rows.some((row) => made.has(String(row[idField ?? "id"]))));
|
|
3913
|
+
if (shown) open.push(`The list of ${name} showed ${second} the records of ${first}. If every user is meant to see every record, add "shared": ["list"] to ${name}. If not, badday will report it.`);
|
|
3914
|
+
}
|
|
3915
|
+
resources.push(resource);
|
|
3916
|
+
}
|
|
3917
|
+
if (!resources.length) open.push("badday saw no request that creates a record. Create one in the app while badday records.");
|
|
3918
|
+
return { config: { baseUrl, actors: actors2, resources }, notes, open };
|
|
3919
|
+
}
|
|
3920
|
+
var kinds = (g) => [g.creates, g.lists, g.gets, g.updates, g.removes].filter((list2) => list2.length).length;
|
|
3921
|
+
|
|
3922
|
+
// src/learn/probe.ts
|
|
3923
|
+
import { randomBytes as randomBytes6 } from "node:crypto";
|
|
3924
|
+
var LIMITS = ["limit", "per_page", "page_size", "pageSize", "perPage", "size", "take"];
|
|
3925
|
+
var CURSORS = ["cursor", "after", "page_token", "starting_after"];
|
|
3926
|
+
var PAGES = ["page"];
|
|
3927
|
+
var OFFSETS = ["offset", "skip"];
|
|
3928
|
+
var unique = (list2) => [...new Set(list2.filter((x) => !!x))];
|
|
3929
|
+
async function probe(config) {
|
|
3930
|
+
const notes = [];
|
|
3931
|
+
const open = [];
|
|
3932
|
+
for (const [index, spec] of config.resources.entries()) {
|
|
3933
|
+
if (!spec.create) continue;
|
|
3934
|
+
let model = buildModel(config);
|
|
3935
|
+
const client = new Client(model);
|
|
3936
|
+
const made = [];
|
|
3937
|
+
const ctxOf = () => ({
|
|
3938
|
+
model,
|
|
3939
|
+
resource: model.resources[index],
|
|
3940
|
+
client,
|
|
3941
|
+
owner: model.owner,
|
|
3942
|
+
other: model.other,
|
|
3943
|
+
marker: "bd-probe-" + randomBytes6(3).toString("hex"),
|
|
3944
|
+
track: (_actor, id2) => {
|
|
3945
|
+
made.push(id2);
|
|
3946
|
+
},
|
|
3947
|
+
unidentified: () => {
|
|
3948
|
+
}
|
|
3949
|
+
});
|
|
3950
|
+
let ctx = ctxOf();
|
|
3951
|
+
const { name } = spec;
|
|
3952
|
+
const send = (path2) => client.send({ actor: model.owner, method: "GET", path: path2, quiet: true });
|
|
3953
|
+
const create = async () => {
|
|
3954
|
+
const exchange = await client.send(createReq(ctx, model.owner, { quiet: true }));
|
|
3955
|
+
const id2 = ok(exchange) ? createdId(ctx, exchange, { lookup: true }) ?? (await idsByMarker(ctx, model.owner, [exchange]).catch(() => /* @__PURE__ */ new Map())).get(exchange) ?? null : null;
|
|
3956
|
+
if (id2) made.push(id2);
|
|
3957
|
+
return { exchange, id: id2 };
|
|
3958
|
+
};
|
|
3959
|
+
let first = await create();
|
|
3960
|
+
if (!ok(first.exchange) && spec.markerField) {
|
|
3961
|
+
const marker = spec.markerField;
|
|
3962
|
+
delete spec.markerField;
|
|
3963
|
+
model = buildModel(config);
|
|
3964
|
+
ctx = ctxOf();
|
|
3965
|
+
const plain = await create();
|
|
3966
|
+
if (ok(plain.exchange)) {
|
|
3967
|
+
first = plain;
|
|
3968
|
+
open.push(`${name}: the create route refused a marker in "${marker}", so badday stamps no marker. Name a free-text field in markerField if there is one.`);
|
|
3969
|
+
} else spec.markerField = marker;
|
|
3970
|
+
}
|
|
3971
|
+
if (!ok(first.exchange)) {
|
|
3972
|
+
open.push(`${name}: the create route answered ${statusOf(first.exchange)} to the recorded body, sent again. The body may hold a value that works only once, such as a unique name. Correct create.body in the config.`);
|
|
3973
|
+
continue;
|
|
3974
|
+
}
|
|
3975
|
+
if (!first.id) {
|
|
3976
|
+
open.push(`${name}: the create route works, and badday found no "${spec.idField ?? "id"}" in its answer or in the list. Name the field that holds the id in idField.`);
|
|
3977
|
+
continue;
|
|
3978
|
+
}
|
|
3979
|
+
await create();
|
|
3980
|
+
if (spec.list) {
|
|
3981
|
+
const list2 = typeof spec.list === "string" ? { path: spec.list } : spec.list;
|
|
3982
|
+
const whole = pageOf(await send(listPath(list2)), list2, name);
|
|
3983
|
+
if (!whole) open.push(`${name}: badday could not find the rows in the answer of the list. Name the field in list.items.`);
|
|
3984
|
+
else if (whole.rows.length < 2) notes.push(`${name}: the list showed fewer than 2 records after badday created 2, so badday could not test its paging.`);
|
|
3985
|
+
else {
|
|
3986
|
+
let limit;
|
|
3987
|
+
for (const param of unique([list2.limitParam, ...LIMITS])) {
|
|
3988
|
+
const page = pageOf(await send(listPath(list2, { [param]: "1" })), list2, name);
|
|
3989
|
+
if (page && page.rows.length >= 1 && page.rows.length < whole.rows.length) {
|
|
3990
|
+
limit = param;
|
|
3991
|
+
break;
|
|
3992
|
+
}
|
|
3993
|
+
}
|
|
3994
|
+
delete list2.cursorParam;
|
|
3995
|
+
delete list2.pageParam;
|
|
3996
|
+
delete list2.offsetParam;
|
|
3997
|
+
if (!limit) {
|
|
3998
|
+
delete list2.limitParam;
|
|
3999
|
+
notes.push(`${name}: the list takes no page size. It returns every record in one answer.`);
|
|
4000
|
+
} else {
|
|
4001
|
+
list2.limitParam = limit;
|
|
4002
|
+
const one = pageOf(await send(listPath(list2, { [limit]: "1" })), list2, name);
|
|
4003
|
+
const firstId = idOf(ctx, one.rows[0]);
|
|
4004
|
+
const moves = async (params) => {
|
|
4005
|
+
const page = pageOf(await send(listPath(list2, { [limit]: "1", ...params })), list2, name);
|
|
4006
|
+
return !!page && page.rows.length >= 1 && idOf(ctx, page.rows[0]) !== firstId;
|
|
4007
|
+
};
|
|
4008
|
+
let how = "";
|
|
4009
|
+
if (one.next) {
|
|
4010
|
+
for (const param of CURSORS) if (await moves({ [param]: one.next })) {
|
|
4011
|
+
if (param !== "cursor") list2.cursorParam = param;
|
|
4012
|
+
how = `a cursor in "${param}"`;
|
|
4013
|
+
break;
|
|
4014
|
+
}
|
|
4015
|
+
}
|
|
4016
|
+
if (!how) {
|
|
4017
|
+
for (const param of PAGES) if (await moves({ [param]: "2" })) {
|
|
4018
|
+
list2.pageParam = param;
|
|
4019
|
+
how = `a page number in "${param}"`;
|
|
4020
|
+
break;
|
|
4021
|
+
}
|
|
4022
|
+
}
|
|
4023
|
+
if (!how) {
|
|
4024
|
+
for (const param of OFFSETS) if (await moves({ [param]: "1" })) {
|
|
4025
|
+
list2.offsetParam = param;
|
|
4026
|
+
how = `an offset in "${param}"`;
|
|
4027
|
+
break;
|
|
4028
|
+
}
|
|
4029
|
+
}
|
|
4030
|
+
notes.push(how ? `${name}: the list takes a page size in "${limit}" and pages by ${how}.` : `${name}: the list takes a page size in "${limit}", and badday found no way to ask for a second page.`);
|
|
4031
|
+
}
|
|
4032
|
+
}
|
|
4033
|
+
spec.list = Object.keys(list2).length > 1 ? list2 : list2.path;
|
|
4034
|
+
}
|
|
4035
|
+
if (spec.get) {
|
|
4036
|
+
const read = await send(withId(spec.get, first.id));
|
|
4037
|
+
if (!ok(read) || idOf(ctx, read.response.body) !== first.id) {
|
|
4038
|
+
open.push(`${name}: GET ${spec.get} answered ${statusOf(read)} for a record badday had just created with the id ${first.id}. Check get and idField.`);
|
|
4039
|
+
}
|
|
4040
|
+
}
|
|
4041
|
+
const remove = model.resources[index].remove;
|
|
4042
|
+
if (remove) for (const id2 of new Set(made)) await client.send({ actor: model.owner, method: remove.method, path: withId(remove.path, id2), quiet: true });
|
|
4043
|
+
else notes.push(`${name}: badday left ${new Set(made).size} test records behind, because it knows no delete route.`);
|
|
4044
|
+
}
|
|
4045
|
+
return { notes, open };
|
|
4046
|
+
}
|
|
4047
|
+
|
|
4048
|
+
// src/learn/record.ts
|
|
4049
|
+
import http3 from "node:http";
|
|
4050
|
+
var BODY_CAP = 2e6;
|
|
4051
|
+
var CONTROL = "/__badday/";
|
|
4052
|
+
function parse(text2, type) {
|
|
4053
|
+
if (!text2) return void 0;
|
|
4054
|
+
if (type && !/json/i.test(type)) return text2.length > 2e3 ? void 0 : text2;
|
|
4055
|
+
try {
|
|
4056
|
+
return JSON.parse(text2);
|
|
4057
|
+
} catch {
|
|
4058
|
+
return text2.length > 2e3 ? void 0 : text2;
|
|
4059
|
+
}
|
|
4060
|
+
}
|
|
4061
|
+
var splitUrl = (url) => {
|
|
4062
|
+
const parsed = new URL(url, "http://x");
|
|
4063
|
+
return { path: parsed.pathname, query: [...parsed.searchParams] };
|
|
4064
|
+
};
|
|
4065
|
+
function startRecorder(target, port = 0, firstActor = "alice") {
|
|
4066
|
+
const upstream = new URL(target);
|
|
4067
|
+
const seen = [];
|
|
4068
|
+
let actor = firstActor;
|
|
4069
|
+
let finish = () => {
|
|
4070
|
+
};
|
|
4071
|
+
const done = new Promise((resolve6) => {
|
|
4072
|
+
finish = resolve6;
|
|
4073
|
+
});
|
|
4074
|
+
const server = http3.createServer((req, res) => {
|
|
4075
|
+
const url = req.url ?? "/";
|
|
4076
|
+
if (url.startsWith(CONTROL)) {
|
|
4077
|
+
const [command, name] = url.slice(CONTROL.length).split("/");
|
|
4078
|
+
if (command === "next" && name) actor = decodeURIComponent(name);
|
|
4079
|
+
if (command === "done") finish();
|
|
4080
|
+
res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify({ actor, requests: seen.length }));
|
|
4081
|
+
return;
|
|
4082
|
+
}
|
|
4083
|
+
const who = actor;
|
|
4084
|
+
const chunks = [];
|
|
4085
|
+
let size = 0;
|
|
4086
|
+
req.on("data", (chunk) => {
|
|
4087
|
+
size += chunk.length;
|
|
4088
|
+
chunks.push(chunk);
|
|
4089
|
+
});
|
|
4090
|
+
req.on("end", () => {
|
|
4091
|
+
const body2 = Buffer.concat(chunks);
|
|
4092
|
+
const headers = { ...req.headers, host: upstream.host, "accept-encoding": "identity" };
|
|
4093
|
+
const out = http3.request({
|
|
4094
|
+
host: upstream.hostname,
|
|
4095
|
+
port: upstream.port || 80,
|
|
4096
|
+
method: req.method,
|
|
4097
|
+
path: upstream.pathname.replace(/\/$/, "") + url,
|
|
4098
|
+
headers
|
|
4099
|
+
}, (answer) => {
|
|
4100
|
+
const parts = [];
|
|
4101
|
+
let got = 0;
|
|
4102
|
+
answer.on("data", (chunk) => {
|
|
4103
|
+
got += chunk.length;
|
|
4104
|
+
if (got <= BODY_CAP) parts.push(chunk);
|
|
4105
|
+
});
|
|
4106
|
+
answer.on("end", () => {
|
|
4107
|
+
const flat = {};
|
|
4108
|
+
for (const [name, value] of Object.entries(req.headers)) if (value !== void 0) flat[name] = Array.isArray(value) ? value.join(", ") : value;
|
|
4109
|
+
seen.push({
|
|
4110
|
+
actor: who,
|
|
4111
|
+
method: req.method ?? "GET",
|
|
4112
|
+
...splitUrl(url),
|
|
4113
|
+
headers: flat,
|
|
4114
|
+
body: size <= BODY_CAP ? parse(body2.toString("utf8"), flat["content-type"]) : void 0,
|
|
4115
|
+
status: answer.statusCode ?? 0,
|
|
4116
|
+
resBody: got <= BODY_CAP ? parse(Buffer.concat(parts).toString("utf8"), String(answer.headers["content-type"] ?? "")) : void 0
|
|
4117
|
+
});
|
|
4118
|
+
});
|
|
4119
|
+
res.writeHead(answer.statusCode ?? 502, answer.headers);
|
|
4120
|
+
answer.pipe(res);
|
|
4121
|
+
});
|
|
4122
|
+
out.on("error", (err) => {
|
|
4123
|
+
if (!res.headersSent) res.writeHead(502, { "Content-Type": "text/plain" });
|
|
4124
|
+
res.end(`badday could not reach ${target}: ${err.message}`);
|
|
4125
|
+
});
|
|
4126
|
+
out.end(body2);
|
|
4127
|
+
});
|
|
4128
|
+
});
|
|
4129
|
+
return new Promise((resolve6, reject) => {
|
|
4130
|
+
server.once("error", reject);
|
|
4131
|
+
server.listen(port, "127.0.0.1", () => {
|
|
4132
|
+
resolve6({
|
|
4133
|
+
url: "http://localhost:" + server.address().port,
|
|
4134
|
+
next: (name) => {
|
|
4135
|
+
actor = name;
|
|
4136
|
+
},
|
|
4137
|
+
count: (name) => name ? seen.filter((s) => s.actor === name).length : seen.length,
|
|
4138
|
+
done,
|
|
4139
|
+
stop: () => new Promise((closed) => {
|
|
4140
|
+
server.closeAllConnections();
|
|
4141
|
+
server.close(() => closed(seen));
|
|
4142
|
+
})
|
|
4143
|
+
});
|
|
4144
|
+
});
|
|
4145
|
+
});
|
|
4146
|
+
}
|
|
4147
|
+
function readHar(doc, actor, origin) {
|
|
4148
|
+
const entries = doc?.log?.entries;
|
|
4149
|
+
if (!Array.isArray(entries)) throw new Error("the file has no log.entries, so it is not a HAR file");
|
|
4150
|
+
const seen = [];
|
|
4151
|
+
for (const entry of entries) {
|
|
4152
|
+
let url;
|
|
4153
|
+
try {
|
|
4154
|
+
url = new URL(entry.request.url);
|
|
4155
|
+
} catch {
|
|
4156
|
+
continue;
|
|
4157
|
+
}
|
|
4158
|
+
if (url.origin !== origin) continue;
|
|
4159
|
+
const headers = {};
|
|
4160
|
+
for (const { name, value } of entry.request.headers ?? []) headers[name.toLowerCase()] = value;
|
|
4161
|
+
const content = entry.response.content;
|
|
4162
|
+
const text2 = content?.encoding === "base64" ? Buffer.from(content.text ?? "", "base64").toString("utf8") : content?.text ?? "";
|
|
4163
|
+
seen.push({
|
|
4164
|
+
actor,
|
|
4165
|
+
method: entry.request.method,
|
|
4166
|
+
path: url.pathname,
|
|
4167
|
+
query: [...url.searchParams],
|
|
4168
|
+
headers,
|
|
4169
|
+
body: parse(entry.request.postData?.text ?? "", entry.request.postData?.mimeType ?? headers["content-type"]),
|
|
4170
|
+
status: entry.response.status,
|
|
4171
|
+
resBody: parse(text2, content?.mimeType)
|
|
4172
|
+
});
|
|
4173
|
+
}
|
|
4174
|
+
return seen;
|
|
4175
|
+
}
|
|
4176
|
+
function mainOrigin(doc) {
|
|
4177
|
+
const counts = /* @__PURE__ */ new Map();
|
|
4178
|
+
for (const entry of doc?.log?.entries ?? []) {
|
|
4179
|
+
if (!/json/i.test(entry.response?.content?.mimeType ?? "")) continue;
|
|
4180
|
+
try {
|
|
4181
|
+
const { origin } = new URL(entry.request.url);
|
|
4182
|
+
counts.set(origin, (counts.get(origin) ?? 0) + 1);
|
|
4183
|
+
} catch {
|
|
4184
|
+
}
|
|
4185
|
+
}
|
|
4186
|
+
return [...counts].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
|
|
4187
|
+
}
|
|
4188
|
+
|
|
4189
|
+
// src/cli/record.ts
|
|
4190
|
+
var USERS = ["alice", "bob"];
|
|
4191
|
+
var STEPS = "Log in, create one record, open it, change it, look at the list, and delete one if the app lets you.";
|
|
4192
|
+
async function reachable(target) {
|
|
4193
|
+
const model = buildModel({ baseUrl: target, actors: { nobody: { headers: {} } }, resources: [] });
|
|
4194
|
+
return !!(await new Client(model).send({ method: "GET", path: "/", quiet: true, timeoutMs: 3e3 })).response;
|
|
4195
|
+
}
|
|
4196
|
+
function local(target) {
|
|
4197
|
+
let url;
|
|
4198
|
+
try {
|
|
4199
|
+
url = new URL(target);
|
|
4200
|
+
} catch {
|
|
4201
|
+
throw new UsageError(`"${target}" is not an address. Write it like http://localhost:3000.`);
|
|
4202
|
+
}
|
|
4203
|
+
if (!isLocalHost(url.hostname)) throw new UsageError(`${url.hostname} is not a local address. badday records and tests an app on this machine only.`);
|
|
4204
|
+
return target.replace(/\/$/, "");
|
|
4205
|
+
}
|
|
4206
|
+
async function record(opts, out = console.log) {
|
|
4207
|
+
const file = resolve2(opts.out ?? "badday.config.json");
|
|
4208
|
+
if (existsSync2(file) && !opts.force) throw new UsageError(`${file} exists already. Pass --force to replace it, or --out <file> to write somewhere else.`);
|
|
4209
|
+
let seen = [];
|
|
4210
|
+
let target;
|
|
4211
|
+
if (opts.har?.length) {
|
|
4212
|
+
const docs = opts.har.map((name) => {
|
|
4213
|
+
try {
|
|
4214
|
+
return JSON.parse(readFileSync2(resolve2(name), "utf8"));
|
|
4215
|
+
} catch (err) {
|
|
4216
|
+
throw new UsageError(`badday could not read ${resolve2(name)} as a HAR file: ${err.message}.`);
|
|
4217
|
+
}
|
|
4218
|
+
});
|
|
4219
|
+
const origin = opts.target ? new URL(local(opts.target)).origin : mainOrigin(docs[0]);
|
|
4220
|
+
if (!origin) throw new UsageError("The HAR file holds no JSON answer, so badday cannot tell where the backend is. Pass --target <address of the backend>.");
|
|
4221
|
+
target = local(origin);
|
|
4222
|
+
docs.forEach((doc, i) => {
|
|
4223
|
+
try {
|
|
4224
|
+
seen.push(...readHar(doc, USERS[i] ?? "user" + (i + 1), origin));
|
|
4225
|
+
} catch (err) {
|
|
4226
|
+
throw new UsageError(`${opts.har[i]}: ${err.message}.`);
|
|
4227
|
+
}
|
|
4228
|
+
});
|
|
4229
|
+
out(`Read ${seen.length} requests to ${origin} from ${opts.har.length} HAR ${opts.har.length === 1 ? "file" : "files"}.`);
|
|
4230
|
+
if (!seen.some((s) => s.headers.authorization || s.headers.cookie)) {
|
|
4231
|
+
out('None of them carries a login. Browsers leave credentials out of a HAR export unless you allow it: in Chrome, turn on "Allow to generate HAR with sensitive data" in the DevTools settings, then export again.');
|
|
4232
|
+
}
|
|
4233
|
+
} else {
|
|
4234
|
+
if (!opts.target) throw new UsageError("Tell badday where your backend runs, as: badday record --target http://localhost:3000");
|
|
4235
|
+
target = local(opts.target);
|
|
4236
|
+
if (!await reachable(target)) throw new UsageError(`Nothing answers at ${target}. Start your app, then run badday record again.`);
|
|
4237
|
+
const recorder = await startRecorder(target, opts.port ?? 4010);
|
|
4238
|
+
out(`badday listens at ${recorder.url} and passes every request on to ${target}.`);
|
|
4239
|
+
out(`Point your frontend or your API client at ${recorder.url} in place of ${target}.
|
|
4240
|
+
`);
|
|
4241
|
+
if (process.stdin.isTTY) {
|
|
4242
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
4243
|
+
try {
|
|
4244
|
+
await rl.question(`Step 1. Use the app as your first test user. ${STEPS}
|
|
4245
|
+
Press Enter when you are done. `);
|
|
4246
|
+
out(` ${recorder.count("alice")} requests recorded.`);
|
|
4247
|
+
recorder.next("bob");
|
|
4248
|
+
await rl.question("\nStep 2. Log out, log in as a second test user, and do the same.\nPress Enter when you are done, or right away if you have one user only. ");
|
|
4249
|
+
out(` ${recorder.count("bob")} requests recorded.
|
|
4250
|
+
`);
|
|
4251
|
+
} finally {
|
|
4252
|
+
rl.close();
|
|
4253
|
+
}
|
|
4254
|
+
} else {
|
|
4255
|
+
out(`No terminal is attached, so drive the recording over HTTP:`);
|
|
4256
|
+
out(` the first user sends their requests through ${recorder.url}`);
|
|
4257
|
+
out(` POST ${recorder.url}/__badday/next/bob starts the second user`);
|
|
4258
|
+
out(` POST ${recorder.url}/__badday/done ends the recording
|
|
4259
|
+
`);
|
|
4260
|
+
await recorder.done;
|
|
4261
|
+
}
|
|
4262
|
+
seen = await recorder.stop();
|
|
4263
|
+
}
|
|
4264
|
+
const learned = learn(seen, target);
|
|
4265
|
+
const open = [...learned.open];
|
|
4266
|
+
if (!learned.config.resources.length || !Object.keys(learned.config.actors).length) {
|
|
4267
|
+
out("badday could not write a config from this recording:");
|
|
4268
|
+
for (const line of open) out(" - " + line);
|
|
4269
|
+
return 2;
|
|
4270
|
+
}
|
|
4271
|
+
out("What badday learned:");
|
|
4272
|
+
for (const line of learned.notes) out(" - " + line);
|
|
4273
|
+
if (opts.probe !== false && await reachable(target)) {
|
|
4274
|
+
out("\nChecking it against the running backend, with 2 test records per resource:");
|
|
4275
|
+
const probed = await probe(learned.config);
|
|
4276
|
+
for (const line of probed.notes) out(" - " + line);
|
|
4277
|
+
open.push(...probed.open);
|
|
4278
|
+
}
|
|
4279
|
+
const problems = validateConfig(learned.config);
|
|
4280
|
+
for (const p of problems) open.push(`${p.path}: ${p.problem}. ${p.fix}`);
|
|
4281
|
+
writeFileSync(file, JSON.stringify(learned.config, null, 2) + "\n");
|
|
4282
|
+
out(`
|
|
4283
|
+
Wrote ${file}. It holds the credentials of your test users, so keep it out of git.`);
|
|
4284
|
+
if (open.length) {
|
|
4285
|
+
out("\nStill open:");
|
|
4286
|
+
for (const line of open) out(" - " + line);
|
|
4287
|
+
}
|
|
4288
|
+
out(`
|
|
4289
|
+
Run the checks with: npx badday run${opts.out ? " --config " + opts.out : ""}`);
|
|
4290
|
+
return problems.length ? 2 : 0;
|
|
4291
|
+
}
|
|
4292
|
+
|
|
4293
|
+
// src/cli/skill.ts
|
|
4294
|
+
import { existsSync as existsSync3, mkdirSync, writeFileSync as writeFileSync2 } from "node:fs";
|
|
4295
|
+
import { dirname, relative, resolve as resolve3 } from "node:path";
|
|
4296
|
+
var skillText = () => true ? "---\nname: badday\ndescription: Test a live HTTP backend for broken promises with the badday CLI. Use when the user asks to check a backend for duplicate charges, replayed webhooks, cross-user data leaks or crashes on bad input, or asks to set up or run badday.\n---\n\n# badday\n\nbadday sends requests to a live backend and reports the promises that the backend broke. badday does not read the code of the backend.\n\n## Procedure\n\n1. Run `npx badday init --agent`. Read the brief it prints. The brief holds every config field.\n2. Find the routes, the authentication and two test users in the repository. Do not guess a value. If the repository does not show a value, ask the user.\n3. Write `badday.config.json` in the project root.\n4. Run `npx badday validate`. If it prints a problem, apply the fix it names and run the command again.\n5. Start the backend, if it does not run.\n6. Run `npx badday run --json`.\n7. For each check with the verdict `fail`, read `summary`, `evidence` and `fixPrompt`. Fix the backend.\n8. Run step 6 again, until no check has the verdict `fail`.\n9. Tell the user which checks have the verdict `not-configured`, and what each one needs.\n\n## Rules\n\n- A `not-configured` check did not run. Do not report it as a pass.\n- Do not change the config to make a check pass. Fix the backend.\n- Do not pass `--i-own-this-server`, unless the user tells you to.\n- The file `badday.config.json` can hold real tokens. Do not commit it, unless the user tells you to.\n- The standards tabs of the report show a draft. Do not tell the user that the backend meets a standard.\n\n## Exit codes\n\n- 0: no check failed.\n- 1: one check or more failed.\n- 2: the config or the target is not usable. The message names the fix.\n" : readFileSync3(new URL("../../agents/skill/badday/SKILL.md", import.meta.url), "utf8");
|
|
4297
|
+
function writeSkill(force) {
|
|
4298
|
+
const file = resolve3(".claude/skills/badday/SKILL.md");
|
|
4299
|
+
if (existsSync3(file) && !force) throw new UsageError(`${relative(process.cwd(), file)} exists. Pass --force to replace it.`);
|
|
4300
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
4301
|
+
writeFileSync2(file, skillText());
|
|
4302
|
+
console.log(`Wrote ${relative(process.cwd(), file)}. Claude Code now runs badday when you ask it to test this backend.`);
|
|
4303
|
+
return 0;
|
|
4304
|
+
}
|
|
4305
|
+
|
|
4306
|
+
// src/cli/wizard.ts
|
|
4307
|
+
import { writeFileSync as writeFileSync3 } from "node:fs";
|
|
4308
|
+
import { resolve as resolve4 } from "node:path";
|
|
4309
|
+
import { createInterface as createInterface2 } from "node:readline/promises";
|
|
4310
|
+
var PORTS = [3e3, 8e3, 8080, 5173, 4e3, 5e3];
|
|
4311
|
+
var DESCRIPTIONS = ["/openapi.json", "/swagger.json", "/api-docs", "/docs", "/v3/api-docs", "/api/openapi.json"];
|
|
4312
|
+
async function get(baseUrl, path2) {
|
|
4313
|
+
const model = buildModel({ baseUrl, actors: { nobody: { headers: {} } }, resources: [] });
|
|
4314
|
+
return new Client(model).send({ method: "GET", path: path2, timeoutMs: 1500, quiet: true });
|
|
4315
|
+
}
|
|
4316
|
+
async function findDescription(baseUrl) {
|
|
4317
|
+
for (const path2 of DESCRIPTIONS) {
|
|
4318
|
+
const { response } = await get(baseUrl, path2);
|
|
4319
|
+
const doc = response?.body;
|
|
4320
|
+
if (response?.status === 200 && doc && typeof doc === "object" && (doc.openapi || doc.swagger) && doc.paths) return { path: path2, doc };
|
|
4321
|
+
}
|
|
4322
|
+
return null;
|
|
4323
|
+
}
|
|
4324
|
+
async function wizard(cwd, out = console.log) {
|
|
4325
|
+
const rl = createInterface2({ input: process.stdin, output: process.stdout });
|
|
4326
|
+
const ask = async (question, fallback = "") => (await rl.question(fallback ? `${question} [${fallback}] ` : question + " ")).trim() || fallback;
|
|
4327
|
+
try {
|
|
4328
|
+
out("No badday config exists in this folder yet. A few questions, then badday writes one.");
|
|
4329
|
+
out("To see badday work first, with no app of your own, stop here and run: npx badday demo\n");
|
|
4330
|
+
const answering = [];
|
|
4331
|
+
for (const port of PORTS) {
|
|
4332
|
+
if ((await get(`http://localhost:${port}`, "/")).response) answering.push(`http://localhost:${port}`);
|
|
4333
|
+
}
|
|
4334
|
+
if (answering.length) out(`Something answers at ${answering.join(" and at ")}.`);
|
|
4335
|
+
else out("Nothing answers on the usual local ports. Start your app first, or type its address.");
|
|
4336
|
+
let baseUrl = "";
|
|
4337
|
+
while (!baseUrl) {
|
|
4338
|
+
const typed = await ask("Where is your app running?", answering[0]);
|
|
4339
|
+
const candidate = /^https?:\/\//.test(typed) ? typed : "http://" + typed;
|
|
4340
|
+
let host = "";
|
|
4341
|
+
try {
|
|
4342
|
+
host = new URL(candidate).hostname;
|
|
4343
|
+
} catch {
|
|
4344
|
+
}
|
|
4345
|
+
if (!typed || !host) out("That is not an address. Type one like localhost:3000.");
|
|
4346
|
+
else if (!isLocalHost(host)) out(`${host} is not a local address. The wizard only sets up an app on this machine. badday creates records and sends hostile input, and running it against a server you do not own can be illegal.`);
|
|
4347
|
+
else if (!(await get(candidate, "/")).response) out(`Nothing answers at ${candidate}. Start your app, then type the address again.`);
|
|
4348
|
+
else baseUrl = candidate.replace(/\/$/, "");
|
|
4349
|
+
}
|
|
4350
|
+
const description = await findDescription(baseUrl);
|
|
4351
|
+
if (!description) {
|
|
4352
|
+
out(`
|
|
4353
|
+
Your app publishes no API description at ${DESCRIPTIONS.slice(0, 4).join(", ")}, so badday cannot learn its routes by itself.`);
|
|
4354
|
+
out("\nbadday can learn them by watching. Run this, then use your app as two test users:\n");
|
|
4355
|
+
out(` npx badday record --target ${baseUrl}
|
|
4356
|
+
`);
|
|
4357
|
+
out("Or your AI coding tool can write the config. Paste this into Cursor, Claude Code or Lovable:\n");
|
|
4358
|
+
out(" " + PASTE_PROMPT + "\n");
|
|
4359
|
+
out("Then run npx badday again.");
|
|
4360
|
+
return null;
|
|
4361
|
+
}
|
|
4362
|
+
const draft = draftFromOpenApi(description.doc, baseUrl);
|
|
4363
|
+
out(`
|
|
4364
|
+
Found an API description at ${description.path}.`);
|
|
4365
|
+
if (!draft.config.resources.length) {
|
|
4366
|
+
out("It has no route that creates a record, so badday found nothing to test. Paste this into your AI coding tool:\n");
|
|
4367
|
+
out(" " + PASTE_PROMPT);
|
|
4368
|
+
return null;
|
|
4369
|
+
}
|
|
4370
|
+
for (const line of draft.found) out(" " + line);
|
|
4371
|
+
const header = Object.keys(draft.config.actors.alice.headers)[0];
|
|
4372
|
+
out(`
|
|
4373
|
+
badday needs to act as a test user. It sends the ${header} header on every request.`);
|
|
4374
|
+
out(header === "Authorization" ? 'Log in to your app as a test user and copy the token. Paste it with or without "Bearer".' : `Log in to your app as a test user and copy the value of the ${header} header.`);
|
|
4375
|
+
const credential = (label, optional) => ask(`${label}${optional ? ", or press Enter to skip" : ""}:`);
|
|
4376
|
+
const format = (value) => header === "Authorization" && !/^\w+ /.test(value) ? "Bearer " + value : value;
|
|
4377
|
+
let first = "";
|
|
4378
|
+
while (!first) first = await credential("Token of the first test user", false);
|
|
4379
|
+
out('\nA second user lets badday test if one user can reach the data of another. Without one, those checks report "not tested".');
|
|
4380
|
+
const second = await credential("Token of a second, different test user", true);
|
|
4381
|
+
draft.config.actors = { alice: { headers: { [header]: format(first) } }, ...second ? { bob: { headers: { [header]: format(second) } } } : {} };
|
|
4382
|
+
out("\nChecking the draft against your running app, with 2 test records per resource:");
|
|
4383
|
+
const probed = await probe(draft.config);
|
|
4384
|
+
for (const line of probed.notes) out(" - " + line);
|
|
4385
|
+
draft.questions.push(...probed.open);
|
|
4386
|
+
const file = resolve4(cwd, "badday.config.json");
|
|
4387
|
+
writeFileSync3(file, JSON.stringify(draft.config, null, 2) + "\n");
|
|
4388
|
+
out(`
|
|
4389
|
+
Wrote ${file}. It holds the tokens you pasted, so keep it out of git.`);
|
|
4390
|
+
const open = draft.questions.filter((q) => !q.startsWith("Fill in the credentials"));
|
|
4391
|
+
if (open.length) {
|
|
4392
|
+
out("badday could not work out everything from the description:");
|
|
4393
|
+
for (const question of open) out(" - " + question);
|
|
4394
|
+
}
|
|
4395
|
+
return file;
|
|
4396
|
+
} catch (err) {
|
|
4397
|
+
if (err instanceof UsageError) throw err;
|
|
4398
|
+
throw new UsageError("The setup stopped before it finished. Run npx badday again, or run npx badday init --agent to let an AI tool write the config.");
|
|
4399
|
+
} finally {
|
|
4400
|
+
rl.close();
|
|
4401
|
+
}
|
|
4402
|
+
}
|
|
4403
|
+
|
|
4404
|
+
// src/cli/main.ts
|
|
4405
|
+
var HELP = `badday ${VERSION}, give your backend a bad day before production does.
|
|
4406
|
+
|
|
4407
|
+
badday run the checks. With no config in this folder, ask a few questions and write one
|
|
4408
|
+
badday demo run every check against a small bundled shop that has every defect
|
|
4409
|
+
badday demo --fixed run them against the same shop with the defects fixed
|
|
4410
|
+
badday run run the checks against the backend in badday.config.json
|
|
4411
|
+
badday record --target <url>
|
|
4412
|
+
watch two test users use your app through a local proxy, then write the config
|
|
4413
|
+
badday record --har <a.har,b.har>
|
|
4414
|
+
write the config from HAR files exported from the browser, one per user
|
|
4415
|
+
badday validate check the config, and name the path, the problem and the fix for each error
|
|
4416
|
+
badday schema print the JSON Schema of the config
|
|
4417
|
+
badday list print every check and the promise it tests
|
|
4418
|
+
badday init --agent print a brief for a coding agent that writes the config
|
|
4419
|
+
badday init --skill write the Claude Code skill to .claude/skills/badday. --force replaces one
|
|
4420
|
+
badday init --from <f> draft a config from an OpenAPI file or URL, in JSON
|
|
4421
|
+
|
|
4422
|
+
Options for record:
|
|
4423
|
+
--port <n> the port of the proxy. 4010 if absent
|
|
4424
|
+
--out <file> where to write the config. badday.config.json if absent
|
|
4425
|
+
--force replace a config that exists
|
|
4426
|
+
--no-probe do not send test requests to check what was learned
|
|
4427
|
+
|
|
4428
|
+
Options for run and demo:
|
|
4429
|
+
--config <file> the config file, if it is not badday.config.json
|
|
4430
|
+
--only <names> run only these checks or packs, separated by commas
|
|
4431
|
+
--skip <names> leave these checks or packs out
|
|
4432
|
+
--detail print the requests and responses of each failure
|
|
4433
|
+
--json print the result as one JSON document
|
|
4434
|
+
--html <file> where to write the HTML report. badday-report.html if absent
|
|
4435
|
+
--no-html write no HTML report
|
|
4436
|
+
--i-own-this-server <hostname>
|
|
4437
|
+
allow a host that is not local. badday creates records and sends
|
|
4438
|
+
hostile input. Running it against a server you do not own can be illegal
|
|
4439
|
+
|
|
4440
|
+
Exit codes: 0 no check failed, 1 a check failed, 2 the config or the target is not usable.
|
|
4441
|
+
`;
|
|
4442
|
+
var VALUE_FLAGS = ["--config", "--only", "--skip", "--html", "--from", "--i-own-this-server", "--base-url", "--target", "--port", "--har", "--out"];
|
|
4443
|
+
function parse2(argv) {
|
|
4444
|
+
const flags = {};
|
|
4445
|
+
let command;
|
|
4446
|
+
for (let i = 0; i < argv.length; i++) {
|
|
4447
|
+
const arg = argv[i];
|
|
4448
|
+
if (!arg.startsWith("--")) {
|
|
4449
|
+
if (command) throw new UsageError(`badday does not know what to do with "${arg}". Run badday help.`);
|
|
4450
|
+
command = arg;
|
|
4451
|
+
continue;
|
|
4452
|
+
}
|
|
4453
|
+
const [name, inline] = arg.split(/=(.*)/s);
|
|
4454
|
+
if (inline !== void 0) flags[name] = inline;
|
|
4455
|
+
else if (VALUE_FLAGS.includes(name) && argv[i + 1] !== void 0 && !argv[i + 1].startsWith("--")) flags[name] = argv[++i];
|
|
4456
|
+
else flags[name] = true;
|
|
4457
|
+
}
|
|
4458
|
+
return { command, flags };
|
|
4459
|
+
}
|
|
4460
|
+
var text = (flags, name) => typeof flags[name] === "string" ? flags[name] : void 0;
|
|
4461
|
+
var names = (flags, name) => text(flags, name)?.split(",").map((n) => n.trim()).filter(Boolean);
|
|
4462
|
+
function printProblems(file, problems) {
|
|
4463
|
+
console.error(`${file} has ${problems.length} ${problems.length === 1 ? "problem" : "problems"}.
|
|
4464
|
+
`);
|
|
4465
|
+
for (const p of problems) console.error(`${p.path || "the config"}
|
|
4466
|
+
problem ${p.problem}
|
|
4467
|
+
fix ${p.fix}
|
|
4468
|
+
`);
|
|
4469
|
+
}
|
|
4470
|
+
async function readValidConfig(flags) {
|
|
4471
|
+
const file = findConfig(text(flags, "--config"));
|
|
4472
|
+
if (!file) return null;
|
|
4473
|
+
const config = await loadConfig(file);
|
|
4474
|
+
const problems = validateConfig(config);
|
|
4475
|
+
if (problems.length) {
|
|
4476
|
+
printProblems(file, problems);
|
|
4477
|
+
throw new UsageError('Correct the config and run badday again. "badday validate" checks it without a run.');
|
|
4478
|
+
}
|
|
4479
|
+
return { file, config };
|
|
4480
|
+
}
|
|
4481
|
+
async function confirmRemote(config, flags) {
|
|
4482
|
+
const flag = flags["--i-own-this-server"];
|
|
4483
|
+
if (!flag) return false;
|
|
4484
|
+
const host = buildModel(config).base.hostname;
|
|
4485
|
+
if (flag === host) return true;
|
|
4486
|
+
if (!process.stdin.isTTY) throw new UsageError(`Pass the hostname with the flag, as --i-own-this-server ${host}, to confirm that this server is yours.`);
|
|
4487
|
+
const rl = createInterface3({ input: process.stdin, output: process.stdout });
|
|
4488
|
+
const typed = await rl.question(`badday will create records on ${host} and send it hostile input. Type the hostname to confirm that this server is yours: `);
|
|
4489
|
+
rl.close();
|
|
4490
|
+
if (typed.trim() !== host) throw new UsageError("The hostname does not match. badday did not run.");
|
|
4491
|
+
return true;
|
|
4492
|
+
}
|
|
4493
|
+
async function execute(config, flags, target, allowRemote) {
|
|
4494
|
+
const json2 = !!flags["--json"];
|
|
4495
|
+
const result = await run(config, {
|
|
4496
|
+
checks,
|
|
4497
|
+
allowRemote,
|
|
4498
|
+
only: names(flags, "--only"),
|
|
4499
|
+
skip: names(flags, "--skip"),
|
|
4500
|
+
onPlan: (plan) => {
|
|
4501
|
+
if (!json2) console.log(`Running ${plan.checks} ${plan.checks === 1 ? "check" : "checks"} against ${target}. They create at most ${plan.records} records.
|
|
4502
|
+
`);
|
|
4503
|
+
}
|
|
4504
|
+
});
|
|
4505
|
+
const htmlFile = flags["--no-html"] || json2 && !flags["--html"] ? null : resolve5(text(flags, "--html") ?? "badday-report.html");
|
|
4506
|
+
if (htmlFile) writeFileSync4(htmlFile, renderHtml(result));
|
|
4507
|
+
if (json2) console.log(JSON.stringify(result, null, 2));
|
|
4508
|
+
else {
|
|
4509
|
+
process.stdout.write(renderTerminal(result, { color: process.stdout.isTTY && !process.env.NO_COLOR, width: process.stdout.columns, detail: !!flags["--detail"] }));
|
|
4510
|
+
if (htmlFile) console.log(`
|
|
4511
|
+
The full report, with every request and a fix prompt for each failure: ${htmlFile}`);
|
|
4512
|
+
}
|
|
4513
|
+
return result.checks.some((c) => c.verdict === "fail") ? 1 : 0;
|
|
4514
|
+
}
|
|
4515
|
+
async function demo(flags) {
|
|
4516
|
+
const shop = await (flags["--fixed"] ? startFixedShop() : startBrokenShop());
|
|
4517
|
+
try {
|
|
4518
|
+
return await execute(shopConfig(shop.url), flags, flags["--fixed"] ? "the demo shop, with its defects fixed" : "the demo shop, which has every defect", false);
|
|
4519
|
+
} finally {
|
|
4520
|
+
await shop.close();
|
|
4521
|
+
}
|
|
4522
|
+
}
|
|
4523
|
+
async function runCommand(flags, canAsk) {
|
|
4524
|
+
let loaded = await readValidConfig(flags);
|
|
4525
|
+
if (!loaded) {
|
|
4526
|
+
if (!canAsk || !process.stdin.isTTY) {
|
|
4527
|
+
throw new UsageError('No badday.config.json exists in this folder. Run "npx badday record --target <address of your backend>" to let badday learn it from your app in use, "npx badday" in a terminal for the questions, "npx badday init --agent" to let a coding agent write it, or "npx badday demo" to see badday work with no setup.');
|
|
4528
|
+
}
|
|
4529
|
+
if (!await wizard(process.cwd())) return 2;
|
|
4530
|
+
console.log();
|
|
4531
|
+
loaded = await readValidConfig(flags);
|
|
4532
|
+
}
|
|
4533
|
+
return execute(loaded.config, flags, loaded.config.baseUrl, await confirmRemote(loaded.config, flags));
|
|
4534
|
+
}
|
|
4535
|
+
async function validate(flags) {
|
|
4536
|
+
const file = findConfig(text(flags, "--config"));
|
|
4537
|
+
if (!file) throw new UsageError("No badday.config.json exists in this folder. Write one, or pass --config <file>.");
|
|
4538
|
+
const problems = validateConfig(await loadConfig(file));
|
|
4539
|
+
if (flags["--json"]) console.log(JSON.stringify({ file, valid: !problems.length, problems }, null, 2));
|
|
4540
|
+
else if (problems.length) printProblems(file, problems);
|
|
4541
|
+
else console.log(`${file} is valid. Run badday to test the backend.`);
|
|
4542
|
+
return problems.length ? 2 : 0;
|
|
4543
|
+
}
|
|
4544
|
+
async function init(flags) {
|
|
4545
|
+
if (flags["--agent"]) {
|
|
4546
|
+
process.stdout.write(agentBrief());
|
|
4547
|
+
return 0;
|
|
4548
|
+
}
|
|
4549
|
+
if (flags["--skill"]) return writeSkill(!!flags["--force"]);
|
|
4550
|
+
const from = text(flags, "--from");
|
|
4551
|
+
if (!from) throw new UsageError('Run "badday init --agent" for the brief, "badday init --skill" for the Claude Code skill, or "badday init --from <OpenAPI file or URL>" for a draft config.');
|
|
4552
|
+
const baseUrl = text(flags, "--base-url") ?? (/^https?:\/\//.test(from) ? new URL(from).origin : "http://localhost:3000");
|
|
4553
|
+
let raw;
|
|
4554
|
+
if (/^https?:\/\//.test(from)) {
|
|
4555
|
+
const url = new URL(from);
|
|
4556
|
+
const model = buildModel({ baseUrl: url.origin, actors: { nobody: { headers: {} } }, resources: [] });
|
|
4557
|
+
const sent = await new Client(model).send({ method: "GET", path: url.pathname + url.search });
|
|
4558
|
+
if (sent.response?.status !== 200) throw new UsageError(`GET ${from} answered ${sent.response?.status ?? sent.error}. Check the address of the OpenAPI description.`);
|
|
4559
|
+
raw = sent.response.text;
|
|
4560
|
+
} else {
|
|
4561
|
+
try {
|
|
4562
|
+
raw = readFileSync4(resolve5(from), "utf8");
|
|
4563
|
+
} catch {
|
|
4564
|
+
throw new UsageError(`No file exists at ${resolve5(from)}.`);
|
|
4565
|
+
}
|
|
4566
|
+
}
|
|
4567
|
+
let doc;
|
|
4568
|
+
try {
|
|
4569
|
+
doc = JSON.parse(raw);
|
|
4570
|
+
} catch {
|
|
4571
|
+
throw new UsageError(`${from} is not JSON. badday reads OpenAPI in JSON only. Convert a YAML file to JSON first.`);
|
|
4572
|
+
}
|
|
4573
|
+
const draft = draftFromOpenApi(doc, baseUrl);
|
|
4574
|
+
console.log(JSON.stringify(draft.config, null, 2));
|
|
4575
|
+
console.error(`
|
|
4576
|
+
This is a draft. Save it as badday.config.json, then finish it:`);
|
|
4577
|
+
for (const question of draft.questions) console.error(" - " + question);
|
|
4578
|
+
console.error('Then run "badday validate".');
|
|
4579
|
+
return 0;
|
|
4580
|
+
}
|
|
4581
|
+
function list() {
|
|
4582
|
+
let pack = "";
|
|
4583
|
+
for (const check of checks) {
|
|
4584
|
+
if (check.pack !== pack) {
|
|
4585
|
+
pack = check.pack;
|
|
4586
|
+
console.log(`
|
|
4587
|
+
${pack}`);
|
|
4588
|
+
}
|
|
4589
|
+
console.log(` ${check.name.padEnd(26)}${check.promise}`);
|
|
4590
|
+
}
|
|
4591
|
+
return 0;
|
|
4592
|
+
}
|
|
4593
|
+
async function main() {
|
|
4594
|
+
const { command, flags } = parse2(process.argv.slice(2));
|
|
4595
|
+
if (flags["--version"]) {
|
|
4596
|
+
console.log(VERSION);
|
|
4597
|
+
return 0;
|
|
4598
|
+
}
|
|
4599
|
+
if (flags["--help"] || command === "help") {
|
|
4600
|
+
process.stdout.write(HELP);
|
|
4601
|
+
return 0;
|
|
4602
|
+
}
|
|
4603
|
+
switch (command) {
|
|
4604
|
+
case void 0:
|
|
4605
|
+
return runCommand(flags, true);
|
|
4606
|
+
case "run":
|
|
4607
|
+
return runCommand(flags, false);
|
|
4608
|
+
case "demo":
|
|
4609
|
+
return demo(flags);
|
|
4610
|
+
case "validate":
|
|
4611
|
+
return validate(flags);
|
|
4612
|
+
case "schema":
|
|
4613
|
+
console.log(JSON.stringify({ $schema: "http://json-schema.org/draft-07/schema#", title: "badday config", ...configSchema }, null, 2));
|
|
4614
|
+
return 0;
|
|
4615
|
+
case "list":
|
|
4616
|
+
return list();
|
|
4617
|
+
case "init":
|
|
4618
|
+
return init(flags);
|
|
4619
|
+
case "record":
|
|
4620
|
+
return record({ target: text(flags, "--target"), port: text(flags, "--port") ? Number(text(flags, "--port")) : void 0, har: names(flags, "--har"), out: text(flags, "--out"), force: !!flags["--force"], probe: !flags["--no-probe"] });
|
|
4621
|
+
default:
|
|
4622
|
+
throw new UsageError(`badday has no command "${command}". Run badday help.`);
|
|
4623
|
+
}
|
|
4624
|
+
}
|
|
4625
|
+
main().then(
|
|
4626
|
+
(code) => {
|
|
4627
|
+
process.exitCode = code;
|
|
4628
|
+
},
|
|
4629
|
+
(err) => {
|
|
4630
|
+
console.error(err instanceof UsageError ? err.message : err);
|
|
4631
|
+
process.exitCode = 2;
|
|
4632
|
+
}
|
|
4633
|
+
);
|