omniqa 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +10 -1
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/cli.js +9 -1
  4. package/dist/cli.js.map +1 -1
  5. package/dist/commands/doctor.d.ts +7 -0
  6. package/dist/commands/doctor.d.ts.map +1 -1
  7. package/dist/commands/doctor.js +77 -5
  8. package/dist/commands/doctor.js.map +1 -1
  9. package/dist/commands/init.d.ts +15 -0
  10. package/dist/commands/init.d.ts.map +1 -1
  11. package/dist/commands/init.js +219 -26
  12. package/dist/commands/init.js.map +1 -1
  13. package/dist/commands/install.d.ts.map +1 -1
  14. package/dist/commands/install.js +20 -3
  15. package/dist/commands/install.js.map +1 -1
  16. package/dist/commands/knowledge.d.ts +23 -0
  17. package/dist/commands/knowledge.d.ts.map +1 -1
  18. package/dist/commands/knowledge.js +215 -39
  19. package/dist/commands/knowledge.js.map +1 -1
  20. package/dist/commands/plan-add.d.ts.map +1 -1
  21. package/dist/commands/plan-add.js +23 -1
  22. package/dist/commands/plan-add.js.map +1 -1
  23. package/dist/commands/plan.d.ts.map +1 -1
  24. package/dist/commands/plan.js +10 -6
  25. package/dist/commands/plan.js.map +1 -1
  26. package/dist/commands/security.d.ts +7 -0
  27. package/dist/commands/security.d.ts.map +1 -0
  28. package/dist/commands/security.js +76 -0
  29. package/dist/commands/security.js.map +1 -0
  30. package/dist/commands/status.d.ts.map +1 -1
  31. package/dist/commands/status.js +2 -2
  32. package/dist/commands/status.js.map +1 -1
  33. package/dist/commands/test.d.ts +10 -0
  34. package/dist/commands/test.d.ts.map +1 -1
  35. package/dist/commands/test.js +61 -7
  36. package/dist/commands/test.js.map +1 -1
  37. package/dist/commands/write.d.ts.map +1 -1
  38. package/dist/commands/write.js +52 -5
  39. package/dist/commands/write.js.map +1 -1
  40. package/dist/coverage-page.d.ts.map +1 -1
  41. package/dist/coverage-page.js +2 -2
  42. package/dist/coverage-page.js.map +1 -1
  43. package/dist/devices.d.ts +4 -2
  44. package/dist/devices.d.ts.map +1 -1
  45. package/dist/devices.js +3 -3
  46. package/dist/devices.js.map +1 -1
  47. package/dist/mcp/tools.d.ts.map +1 -1
  48. package/dist/mcp/tools.js +3 -2
  49. package/dist/mcp/tools.js.map +1 -1
  50. package/dist/planner.d.ts.map +1 -1
  51. package/dist/planner.js +13 -9
  52. package/dist/planner.js.map +1 -1
  53. package/dist/qa.d.ts.map +1 -1
  54. package/dist/qa.js +2 -1
  55. package/dist/qa.js.map +1 -1
  56. package/dist/runner.d.ts +1 -1
  57. package/dist/runner.d.ts.map +1 -1
  58. package/dist/runner.js +64 -56
  59. package/dist/runner.js.map +1 -1
  60. package/dist/security-checks.d.ts +146 -0
  61. package/dist/security-checks.d.ts.map +1 -0
  62. package/dist/security-checks.js +661 -0
  63. package/dist/security-checks.js.map +1 -0
  64. package/dist/security-gates.d.ts +37 -0
  65. package/dist/security-gates.d.ts.map +1 -0
  66. package/dist/security-gates.js +46 -0
  67. package/dist/security-gates.js.map +1 -0
  68. package/dist/security-mask.d.ts +35 -0
  69. package/dist/security-mask.d.ts.map +1 -0
  70. package/dist/security-mask.js +104 -0
  71. package/dist/security-mask.js.map +1 -0
  72. package/dist/security-report.d.ts +93 -0
  73. package/dist/security-report.d.ts.map +1 -0
  74. package/dist/security-report.js +170 -0
  75. package/dist/security-report.js.map +1 -0
  76. package/dist/security-request.d.ts +109 -0
  77. package/dist/security-request.d.ts.map +1 -0
  78. package/dist/security-request.js +254 -0
  79. package/dist/security-request.js.map +1 -0
  80. package/dist/security-research.d.ts +131 -0
  81. package/dist/security-research.d.ts.map +1 -0
  82. package/dist/security-research.js +581 -0
  83. package/dist/security-research.js.map +1 -0
  84. package/dist/security-scan.d.ts +98 -0
  85. package/dist/security-scan.d.ts.map +1 -0
  86. package/dist/security-scan.js +415 -0
  87. package/dist/security-scan.js.map +1 -0
  88. package/dist/security-sources.d.ts +55 -0
  89. package/dist/security-sources.d.ts.map +1 -0
  90. package/dist/security-sources.js +75 -0
  91. package/dist/security-sources.js.map +1 -0
  92. package/dist/security.d.ts +65 -0
  93. package/dist/security.d.ts.map +1 -0
  94. package/dist/security.js +624 -0
  95. package/dist/security.js.map +1 -0
  96. package/dist/sync.d.ts +12 -1
  97. package/dist/sync.d.ts.map +1 -1
  98. package/dist/sync.js +11 -3
  99. package/dist/sync.js.map +1 -1
  100. package/dist/test.d.ts +85 -0
  101. package/dist/test.d.ts.map +1 -1
  102. package/dist/test.js +337 -19
  103. package/dist/test.js.map +1 -1
  104. package/dist/writer.d.ts +5 -1
  105. package/dist/writer.d.ts.map +1 -1
  106. package/dist/writer.js +15 -12
  107. package/dist/writer.js.map +1 -1
  108. package/package.json +7 -7
  109. package/skills/security-research.md +57 -0
  110. package/skills/security-review.md +27 -0
@@ -0,0 +1,661 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { NoAnswer, requestRoute } from "@omniqa/web";
3
+ import { CHECK_REQUESTS } from "./security-gates.js";
4
+ import { ANTI_FORGERY, cookiesOf, headerValues, isJwt, jwtOf, namelessOf, nameOf, parametersOf, setCookies, withCookies, withHeader, withoutHeaders, withParameter } from "./security-request.js";
5
+ /** A reply that does not hold: its message is the sentence, what was sent and why the reply fails it. Any other error is a check that could not say. */
6
+ export class NotHeld extends Error {
7
+ }
8
+ /** A request a gate refused: its message is the gate's sentence, as a run says it. Nothing was sent. */
9
+ export class Refused extends Error {
10
+ }
11
+ /** A path without its trailing slash and without an origin: `/accounts/login/` is the login page `/accounts/login`. */
12
+ const pathOf = (location) => (URL.parse(location)?.pathname ?? location).replace(/(.)\/+$/, "$1");
13
+ /** Refused: a 401, a 403, a 404, or a redirect to the login page. */
14
+ export const refused = (reply, loginPath) => [401, 403, 404].includes(reply.status) || (reply.status >= 300 && reply.status < 400 && reply.location !== undefined && pathOf(reply.location) === pathOf(loginPath));
15
+ /** Turned down in any way a client is: a 4xx, or a redirect to the login page. A forged request is answered so by a product that checks it. */
16
+ const rejected = (reply, loginPath) => (reply.status >= 400 && reply.status < 500) || refused(reply, loginPath);
17
+ /**
18
+ * Whether a request sent without what it needs was turned down. One that only reads is refused or it is not; one that
19
+ * changes state is turned down by any 4xx, since a product answers a POST whose session is gone with a 419 or a 422 as
20
+ * readily as with a 403, and nothing was changed either way.
21
+ */
22
+ export const turnedDown = (method, reply, loginPath) => (["GET", "HEAD"].includes(method.toUpperCase()) ? refused : rejected)(reply, loginPath);
23
+ /**
24
+ * A request the product must turn down. Taken (a 2xx, a redirect elsewhere) is a reply that does not hold; a 5xx is the
25
+ * product failing on it, which is neither a refusal nor a yes: the check cannot say.
26
+ */
27
+ function mustReject(ctx, reply, what, why) {
28
+ if (rejected(reply, ctx.loginPath))
29
+ return;
30
+ if (reply.status >= 500)
31
+ throw new Error(`${ctx.name} ${what} answered ${reply.status}: the product failed on it, which is neither a refusal nor a yes`);
32
+ throw new NotHeld(`${ctx.name} ${what} answered ${reply.status}: ${why}`);
33
+ }
34
+ const SESSION_HEADERS = ["cookie", "authorization"];
35
+ /** What a sign-out control is called: the link or the button `security.signOut()` clicks, and the one the security pass looks for. */
36
+ export const SIGN_OUT = /^\s*(log ?out|sign ?out)\s*$/i;
37
+ /** The origin a forged request comes from: a name nobody owns. */
38
+ export const FOREIGN_ORIGIN = "https://omniqa-origin.example";
39
+ /** The request's anti-forgery token, wherever it rides: every header and every body field named like one (a product takes either), and the request without any of them. */
40
+ function antiForgery(r) {
41
+ const headers = r.headers.filter(([name]) => ANTI_FORGERY.test(name)).map(([name]) => name);
42
+ const fields = parametersOf(r).filter((p) => p.in !== "query" && ANTI_FORGERY.test(p.name));
43
+ if (headers.length === 0 && fields.length === 0)
44
+ return undefined;
45
+ return { names: [...new Set([...headers, ...fields.map((p) => p.name)])], without: fields.reduce((text, field) => withParameter(text, field, undefined), withoutHeaders(r, headers)) };
46
+ }
47
+ /** The body types a form of another site can send; any other needs the browser to ask the product first (a preflight). */
48
+ const FORM_TYPES = ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"];
49
+ const header = (headers, name) => headers.find(([h]) => h.toLowerCase() === name)?.[1];
50
+ async function csrf(ctx) {
51
+ // What a guest is answered as the member was is nothing to forge: a beacon, a search. The request has to need its session.
52
+ const own = await ctx.answered();
53
+ const guest = await ctx.send(withoutHeaders(ctx.request, SESSION_HEADERS), "without its session");
54
+ if (guest.status === own.status && guest.location === own.location)
55
+ return;
56
+ const guard = antiForgery(ctx.request);
57
+ if (guard !== undefined) {
58
+ const what = `without its anti-forgery token (${guard.names.join(", ")})`;
59
+ mustReject(ctx, await ctx.send(guard.without, what), what, "the token is not checked");
60
+ }
61
+ // From another site a browser sends its own Origin, the cookies it lets ride along, and nothing a page there cannot set:
62
+ // no token (it cannot read one), no Authorization, no header of the product's own script.
63
+ const flags = await ctx.cookieFlags();
64
+ const riding = cookiesOf(ctx.request).filter(([name]) => !["lax", "strict"].includes(flags[name]?.sameSite ?? ""));
65
+ if (riding.length === 0)
66
+ return;
67
+ const scripted = (guard?.without ?? ctx.request).headers.filter(([name]) => /^x-/i.test(name) || name.toLowerCase() === "authorization").map(([name]) => name);
68
+ let forged = withCookies(withoutHeaders(guard?.without ?? ctx.request, scripted), riding);
69
+ forged = withHeader(withHeader(forged, "Origin", FOREIGN_ORIGIN), "Referer", `${FOREIGN_ORIGIN}/`);
70
+ if (header(forged.headers, "sec-fetch-site") !== undefined)
71
+ forged = withHeader(forged, "Sec-Fetch-Site", "cross-site");
72
+ const from = `from another site (Origin ${FOREIGN_ORIGIN}, with the cookies that ride along: ${riding.map(([name]) => name).join(", ")})`;
73
+ const why = "a page of another site can make a signed-in visitor's browser send it";
74
+ const type = (header(forged.headers, "content-type") ?? "").toLowerCase();
75
+ if (forged.body === "" || FORM_TYPES.some((form) => type.startsWith(form)))
76
+ return mustReject(ctx, await ctx.send(forged, from), from, why);
77
+ // A body no form can send as it is (JSON). A form can send the same text as text/plain,
78
+ const asText = `${from}, its body as text/plain as a form can send it`;
79
+ mustReject(ctx, await ctx.send(withHeader(forged, "Content-Type", "text/plain"), asText), asText, why);
80
+ // and a script can send it as it is only where the product answers the browser's question first: that site, with credentials.
81
+ const preflight = { ...withoutHeaders(forged, ["cookie", "content-type", "content-length"]), method: "OPTIONS", body: "" };
82
+ const asked = await ctx.send(withHeader(withHeader(preflight, "Access-Control-Request-Method", forged.method), "Access-Control-Request-Headers", "content-type"), "as the question a browser asks before it sends it from another site");
83
+ const allowed = (await asked.read()).headers;
84
+ if (header(allowed, "access-control-allow-origin") !== FOREIGN_ORIGIN || header(allowed, "access-control-allow-credentials") !== "true")
85
+ return;
86
+ mustReject(ctx, await ctx.send(forged, from), from, why);
87
+ }
88
+ const b64 = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
89
+ const unb64 = (part) => JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
90
+ async function token(ctx) {
91
+ const jwt = jwtOf(ctx.request);
92
+ if (jwt === undefined)
93
+ throw new Error(`${ctx.name} carries no JSON Web Token in its Authorization header or a cookie`);
94
+ const bare = await ctx.send(jwt.put(undefined), "without its token");
95
+ if (!rejected(bare, ctx.loginPath))
96
+ throw new Error(`${ctx.name} is answered ${bare.status} without its token: the token is not what lets this request in, so a changed one proves nothing here`);
97
+ const [head = "", payload = "", signature = ""] = jwt.token.split(".");
98
+ const forgeries = [
99
+ ["with its token's algorithm set to none and no signature", `${b64({ ...unb64(head), alg: "none" })}.${payload}.`],
100
+ ["with its token's payload changed under the old signature", `${head}.${b64({ ...unb64(payload), omniqa: 1 })}.${signature}`],
101
+ ["with its token's signature removed", `${head}.${payload}.`],
102
+ ];
103
+ for (const [what, forged] of forgeries)
104
+ mustReject(ctx, await ctx.send(jwt.put(forged), what), what, "a token nobody signed is accepted");
105
+ }
106
+ async function fixation(ctx) {
107
+ const signIn = await ctx.signIn();
108
+ if (signIn === undefined)
109
+ throw new Error("no sign-in was captured in this test: logIn first, so the check knows the cookies the visitor had before it");
110
+ const before = cookiesOf(signIn);
111
+ // A visitor with no cookie before the sign-in had no session to keep.
112
+ if (before.length === 0)
113
+ return;
114
+ const guest = await ctx.send(withoutHeaders(ctx.request, SESSION_HEADERS), "without its session");
115
+ if (!turnedDown(ctx.request.method, guest, ctx.loginPath))
116
+ throw new Error(`${ctx.name} is answered ${guest.status} without a session: fixation is shown on a request a guest is refused`);
117
+ const what = "with the cookies the visitor had before signing in";
118
+ const reply = await ctx.send(withCookies(withoutHeaders(ctx.request, ["authorization"]), before), what);
119
+ if (!turnedDown(ctx.request.method, reply, ctx.loginPath))
120
+ throw new NotHeld(`${ctx.name} ${what} answered ${reply.status}: the session is not renewed at sign-in, so one planted in a visitor's browser becomes a signed-in one`);
121
+ }
122
+ /** A password no account has. */
123
+ const WRONG_PASSWORD = "wrong-password-omniqa";
124
+ /**
125
+ * A user nobody is, in the shape of the real one, and a new one every time: a product that locks an account after wrong
126
+ * passwords locks this one, and the next check's unknown account is not the one the last check got locked.
127
+ */
128
+ function unknownUser(real) {
129
+ const name = `omniqa-unknown-${randomBytes(4).toString("hex")}`;
130
+ return real.includes("@") ? `${name}@omniqa-unknown.example` : name;
131
+ }
132
+ /** The sign-in's two fields, known by what they hold: the password of an account of product.yaml, and that account's email, username, login or user. */
133
+ function signInFields(ctx) {
134
+ const parameters = parametersOf(ctx.request).filter((p) => p.in !== "query");
135
+ for (const fields of Object.values(ctx.accounts)) {
136
+ const password = parameters.find((p) => fields.password !== undefined && p.value === fields.password);
137
+ const name = fields.email ?? fields.username ?? fields.login ?? fields.user;
138
+ const user = parameters.find((p) => name !== undefined && p.value === name);
139
+ if (password !== undefined && user !== undefined)
140
+ return { user, password };
141
+ }
142
+ throw new Error(`${ctx.name} is no sign-in this check knows: none of its fields holds the password of an account of product.yaml (logIn first, then ask for the request it made)`);
143
+ }
144
+ /** The sign-in with these two values in its fields, everything else as the page sent it. */
145
+ const signInAs = (ctx, fields, user, password) => withParameter(withParameter(ctx.request, fields.user, user), fields.password, password);
146
+ async function look(reply) {
147
+ const cookies = setCookies((await reply.read()).headers).map((c) => c.name).toSorted();
148
+ return { status: reply.status, cookies, as: `${reply.status} ${reply.location ?? ""} ${cookies.join(",")}` };
149
+ }
150
+ /**
151
+ * How the page's own sign-in was answered, once the same request sent a second time is answered alike. Where it is not,
152
+ * something it carries is spent (a token of the form, the session of before the sign-in): every other variant would be
153
+ * turned down before a password is looked at, and would prove nothing.
154
+ */
155
+ async function signInWorks(ctx) {
156
+ const works = await look(await ctx.answered());
157
+ const again = await look(await ctx.send(ctx.request, "as the page sent it"));
158
+ if (again.as !== works.as)
159
+ throw new Error(`${ctx.name} sent a second time is answered ${again.status}, not as the page's own sign-in was (${works.status}): something it carries is spent (a token, a session), so no other password would be looked at`);
160
+ return works;
161
+ }
162
+ async function enumeration(ctx) {
163
+ const fields = signInFields(ctx);
164
+ await signInWorks(ctx);
165
+ const users = [fields.user.value, unknownUser(fields.user.value)];
166
+ const looks = [];
167
+ for (const [i, user] of users.entries()) {
168
+ const reply = await ctx.send(signInAs(ctx, fields, user, WRONG_PASSWORD), `with a wrong password for ${i === 0 ? "a real" : "an unknown"} account`);
169
+ // A page that shows the form again with what was typed differs by that much and no more.
170
+ const body = (await reply.read()).body.replaceAll(user, "").replaceAll(encodeURIComponent(user), "");
171
+ looks.push(`${reply.status}${reply.location === undefined ? "" : ` to ${reply.location}`}, ${Buffer.byteLength(body)} bytes`);
172
+ }
173
+ if (looks[0] !== looks[1])
174
+ throw new NotHeld(`${ctx.name} answers a wrong password differently for a real account (${looks[0]}) and for an unknown one (${looks[1]}): the difference tells which accounts exist`);
175
+ }
176
+ /** The wrong passwords in a row a product may take before it reacts. */
177
+ const ATTEMPTS = 10;
178
+ /** ponytail: a throttle is known by a 429, a Retry-After, a status that changes, or these words appearing in the reply; a product that only gets slower, or says it in another language, is missed. Time the replies when one does. */
179
+ const THROTTLED = /too many|rate.?limit|\b(locked|lockout)\b|captcha|try again (later|in )/i;
180
+ async function throttle(ctx) {
181
+ const fields = signInFields(ctx);
182
+ await signInWorks(ctx);
183
+ // An unknown account, so no real one is locked.
184
+ const attempt = signInAs(ctx, fields, unknownUser(fields.user.value), WRONG_PASSWORD);
185
+ // What the first wrong password is answered with is how the product refuses one: a sign is what comes after and differs.
186
+ let first;
187
+ for (let n = 1; n <= ATTEMPTS; n++) {
188
+ const reply = await ctx.send(attempt, `with wrong password ${n} of ${ATTEMPTS} for an unknown account`);
189
+ if (reply.status === 429)
190
+ return;
191
+ const { headers, body } = await reply.read();
192
+ if (header(headers, "retry-after") !== undefined)
193
+ return;
194
+ const said = THROTTLED.test(body);
195
+ if (first === undefined)
196
+ first = { status: reply.status, said };
197
+ else if (reply.status !== first.status || (said && !first.said))
198
+ return;
199
+ }
200
+ throw new NotHeld(`${ctx.name} answered ten wrong passwords in a row for an unknown account alike (${first?.status} each time): nothing slowed, locked or challenged them`);
201
+ }
202
+ /** The pairs every list of default passwords starts with. */
203
+ const DEFAULTS = [["admin", "admin"], ["admin", "password"], ["test", "test"]];
204
+ async function defaultCredentials(ctx) {
205
+ const fields = signInFields(ctx);
206
+ const works = await signInWorks(ctx);
207
+ const fails = await look(await ctx.send(signInAs(ctx, fields, unknownUser(fields.user.value), WRONG_PASSWORD), "with a wrong password for an unknown account"));
208
+ if (works.as === fails.as)
209
+ throw new Error(`${ctx.name} answers a sign-in that works and one that does not alike from outside (${works.status}, the same redirect, the same cookies set): this check cannot tell an accepted password`);
210
+ for (const [user, password] of DEFAULTS) {
211
+ const what = `as ${user} with the password ${password}`;
212
+ const reply = await ctx.send(signInAs(ctx, fields, user, password), what);
213
+ const answer = await look(reply);
214
+ // Let in: not turned down, not answered as a sign-in that fails, and given a cookie the page's own sign-in was given
215
+ // (an admin may land elsewhere than a member does). The session it was given is in no jar and is used for nothing.
216
+ if (reply.status < 400 && answer.as !== fails.as && (works.cookies.length === 0 || answer.cookies.some((name) => works.cookies.includes(name))))
217
+ throw new NotHeld(`${ctx.name} ${what} answered ${reply.status}, not as it answers a sign-in that fails: a default account is open`);
218
+ }
219
+ }
220
+ /** A value long enough to be a credential: a parameter that equals a cookie's value is the session only then (`lang=en` beside a cookie `lang=en` is not). */
221
+ const SECRET_LENGTH = 16;
222
+ const slowed = (ctx, what) => new Error(`${ctx.name} ${what} answered 429: the product is slowing this machine down, and what it answers from here on proves nothing`);
223
+ /** How a sentence says the request a check works on: the page's own, unless the context words it otherwise. */
224
+ const asSent = (ctx) => ctx.sent ?? "as the page sent it";
225
+ /**
226
+ * The request once more as the page sent it, after a check's own requests: a product that has begun to refuse, slow or
227
+ * drop this machine turned every value down for that reason, and what it answered them proves nothing.
228
+ */
229
+ async function stillAnswers(ctx, own) {
230
+ const again = await ctx.send(ctx.request, asSent(ctx)).catch((err) => {
231
+ if (err instanceof NoAnswer)
232
+ throw new Error(`${ctx.name} gets no answer ${asSent(ctx)} by now: the product no longer answers this machine, so what it answered before proves nothing`);
233
+ throw err;
234
+ });
235
+ if (again.status !== own.status)
236
+ throw new Error(`${ctx.name} is answered ${again.status} ${asSent(ctx)} by now, and ${own.status} ${ctx.sent === undefined ? "when the page sent it" : "at first"}: the product no longer answers this machine as it did, so what it answered in between proves nothing`);
237
+ }
238
+ /** A request with one value in each of these parameters. */
239
+ const withValue = (text, fields, value) => fields.reduce((edited, field) => withParameter(edited, field, value), text);
240
+ /** What a sign-in that fails is sent as, in every sentence. */
241
+ const FAILS = "with a wrong password for an unknown account";
242
+ /**
243
+ * The request a check on a parameter works on. The sign-in (it carries an account's password, and the test signed in with
244
+ * it) is asked as a sign-in that fails: an unknown account with a wrong password, and a new account for every request.
245
+ * A wrong password in turn for each field would lock the account the tests sign in as; this way, but for the page's own
246
+ * sign-in sent once more as it was, no request names that account or carries its password, wherever the request holds
247
+ * them (a name in two fields, a password asked twice), and no account a product may lock after a few wrong passwords is
248
+ * tried twice. What the product answers such a sign-in is what the check compares with, and what it asks once more at
249
+ * the end.
250
+ * Any other request that carries the password is handed on as it is, and `sweep` refuses it: one that asks for the
251
+ * password again (a change of email, of the password itself) knows the account by its session, so a wrong password
252
+ * there would be tried on the account itself.
253
+ */
254
+ async function forSignIn(ctx) {
255
+ const all = parametersOf(ctx.request);
256
+ const account = Object.values(ctx.accounts).find((fields) => fields.password !== undefined && all.some((p) => p.in !== "query" && p.value === fields.password));
257
+ if (account === undefined || !(await ctx.signsIn()))
258
+ return ctx;
259
+ const name = account.email ?? account.username ?? account.login ?? account.user;
260
+ const holders = all.filter((p) => p.value === account.password || p.value === name);
261
+ // Which of them hold the password: the ones with its value, and where the name is the same word (demo with demo) the ones named like one, else all but the first.
262
+ const named = holders.filter((p) => /pass|pwd/i.test(p.name));
263
+ const passwords = name !== account.password ? holders.filter((p) => p.value === account.password) : named.length > 0 ? named : holders.slice(1);
264
+ const names = holders.filter((p) => !passwords.includes(p));
265
+ // The password without the account's name: no sign-in this can ask for somebody else.
266
+ if (name === undefined || names.length === 0)
267
+ return ctx;
268
+ await signInWorks(ctx);
269
+ const nobody = unknownUser(name);
270
+ const request = withValue(withValue(ctx.request, names, nobody), passwords, WRONG_PASSWORD);
271
+ // Every place that still holds that first unknown account gets a new one, the same in all of them; a field the check is asking holds its value.
272
+ const send = (text, what) => {
273
+ const held = parametersOf(text);
274
+ const stale = names.filter((field) => held.some((p) => p.name === field.name && p.in === field.in && p.value === nobody));
275
+ return ctx.send(stale.length === 0 ? text : withValue(text, stale, unknownUser(name)), what);
276
+ };
277
+ let failed;
278
+ return { ...ctx, request, sent: FAILS, send, answered: () => (failed ??= send(request, FAILS)) };
279
+ }
280
+ /** A check that asks each parameter of a request: handed the sign-in, it asks it as a sign-in that fails. */
281
+ const onParameters = (check) => async (ctx) => check(await forSignIn(ctx));
282
+ /**
283
+ * Asks each parameter of the request in turn: the request once per parameter and payload, the other parameters as the page
284
+ * sent them, each answer handed to `judge` with what was sent; the judge throws NotHeld for an answer that does not hold,
285
+ * which ends the sweep. A parameter is asked every payload or none: where the test's requests would not cover the next one
286
+ * (with `reserve` kept back for the judge's own second questions, and one for the last request below), the sweep stops and
287
+ * says which parameters it left out, as a line of the test's output.
288
+ * Left alone, and said: a parameter named like an anti-forgery token, one that holds the session, a value with no name. A
289
+ * request that carries an account's password is not asked at all.
290
+ * What proves nothing is not read as an answer: a value the product drops the connection on was turned down; a 429 ends
291
+ * the check; and the request as the page sent it is asked once more at the end, since a product that no longer answers
292
+ * it as it did has stopped answering this machine.
293
+ * A request of any method is asked as it is handed over: one that writes is sent once per parameter and value, each of them
294
+ * that change once more. The gates keep it to an environment that allows mutations, and so do the planning rules.
295
+ */
296
+ export async function sweep(ctx, payloads, judge, reserve = 0) {
297
+ const all = parametersOf(ctx.request).filter((p, i, list) => list.findIndex((other) => other.name === p.name && other.in === p.in) === i);
298
+ const passwords = Object.values(ctx.accounts).flatMap((fields) => (fields.password === undefined ? [] : [fields.password]));
299
+ if (all.some((p) => p.in !== "query" && passwords.includes(p.value)))
300
+ throw new Error(`${ctx.name} carries an account's password: its fields are not asked one by one, since wrong passwords in a row lock the account the tests sign in as`);
301
+ const session = new Set([...cookiesOf(ctx.request).map(([, value]) => value), ...headerValues(ctx.request, "authorization").map((value) => value.split(/\s+/).at(-1) ?? "")].filter((value) => value.length >= SECRET_LENGTH));
302
+ const nameless = namelessOf(ctx.request);
303
+ // A part of a query that is a value with no name (`/confirm?Kq2LmNzT8sVx`) is nobody's parameter, and its text is no name to say.
304
+ const isValue = (p) => p.in !== "json" && nameless.has(p.name);
305
+ const asked = all.filter((p) => !isValue(p) && !ANTI_FORGERY.test(p.name) && !session.has(p.value) && !isJwt(p.value));
306
+ const alone = all.filter((p) => !asked.includes(p));
307
+ const why = "what lets the request in (an anti-forgery token, the session) and a value with no name are not asked";
308
+ if (asked.length === 0)
309
+ throw new Error(`${ctx.name} carries no parameter to ask${all.length === 0 ? "" : `: ${all.length} ${all.length === 1 ? "is" : "are"} left alone, since ${why}`}`);
310
+ const own = await ctx.answered();
311
+ if (own.status >= 500)
312
+ throw new Error(`${ctx.name} is answered ${own.status} ${asSent(ctx)}: a failure a value causes cannot be told from the one it already has`);
313
+ if (own.status === 429)
314
+ throw new Error(`${ctx.name} is answered 429 ${asSent(ctx)}: the product is slowing this machine down, and nothing asked now would prove anything`);
315
+ if (alone.length > 0)
316
+ ctx.note(`${alone.length} of ${all.length} parameters of ${ctx.name} ${alone.length === 1 ? "was" : "were"} left alone (${alone.map((p) => (isValue(p) ? "{value}" : nameOf(p.name))).join(", ")}): ${why}`);
317
+ // What the product already turns down is still asked (its error page is a page, and its refusal may fail), and said: such a test shows less.
318
+ // (A sign-in that fails is turned down by what it is: nothing to say of it.)
319
+ if (own.status >= 400 && ctx.sent === undefined)
320
+ ctx.note(`${ctx.name} is answered ${own.status} as the page sent it: each parameter is asked on a request the product already turns down`);
321
+ for (const [i, p] of asked.entries()) {
322
+ const variants = payloads.flatMap((payload) => {
323
+ const value = payload.list === true && p.in === "json" ? undefined : payload.value(p);
324
+ if (value === undefined)
325
+ return [];
326
+ return [{ value, what: `with ${payload.what} in ${nameOf(p.name)}`, text: payload.list === true ? withParameter(withParameter(ctx.request, p, undefined), { name: `${p.name}[]`, in: p.in }, value) : withParameter(ctx.request, p, value) }];
327
+ });
328
+ if (ctx.left() < variants.length + reserve + 1) {
329
+ const spent = `the test's ${CHECK_REQUESTS} requests were spent`;
330
+ if (i === 0)
331
+ throw new Error(`no parameter of ${ctx.name} was asked: ${spent}`);
332
+ ctx.note(`${asked.length - i} of ${asked.length} parameters of ${ctx.name} were not asked (${asked.slice(i).map((left) => nameOf(left.name)).join(", ")}): ${spent}`);
333
+ break;
334
+ }
335
+ for (const variant of variants) {
336
+ let reply;
337
+ try {
338
+ reply = await ctx.send(variant.text, variant.what);
339
+ }
340
+ catch (err) {
341
+ // A connection dropped on a value (a firewall's way) is that value turned down.
342
+ if (err instanceof NoAnswer)
343
+ continue;
344
+ throw err;
345
+ }
346
+ if (reply.status === 429)
347
+ throw slowed(ctx, variant.what);
348
+ await judge(reply, { what: variant.what, value: variant.value, again: () => ctx.send(variant.text, `${variant.what}, a second time`), other: (value, what) => ctx.send(withParameter(ctx.request, p, value), what) });
349
+ }
350
+ }
351
+ await stillAnswers(ctx, own);
352
+ }
353
+ /** The request with its request line aimed elsewhere, a path of the same host or a whole url (its Host line follows), every other header as the page sent it; what asks whether the page changed aside, since the answer has to be the thing itself. */
354
+ function ask(ctx, target, what) {
355
+ const fresh = withoutHeaders(ctx.request, ["if-none-match", "if-modified-since"]);
356
+ const elsewhere = URL.parse(target);
357
+ return ctx.send({ ...(elsewhere === null ? fresh : withHeader(fresh, "Host", elsewhere.host)), target }, what);
358
+ }
359
+ const has = (pattern) => (body) => pattern.test(body);
360
+ /**
361
+ * Lines of NAME=value: two or more, no line of markup, and most of what the file holds (a key over several lines is not
362
+ * one). A page that happens to hold one such line, or a line of script (`window.location="/"`), is not an environment file.
363
+ */
364
+ function environmentFile(body) {
365
+ const lines = body.split("\n").map((line) => line.trim()).filter((line) => line !== "" && !line.startsWith("#")).slice(0, 50);
366
+ const assignments = lines.filter((line) => /^(export\s+)?[A-Za-z_][A-Za-z0-9_-]*\s*=/.test(line));
367
+ return assignments.length >= 2 && assignments.length * 2 >= lines.length && !lines.some((line) => line.startsWith("<"));
368
+ }
369
+ /**
370
+ * Files and consoles never meant to be served, each with what proves an answer is that file: its own text. A product that
371
+ * answers every path with its own page (a single-page app, a 404 sent as 200) matches none of them.
372
+ * ponytail: a dozen that are text; a backup archive or a heap dump is bytes Interceptor gives no text of, and a list
373
+ * of thousands is a scanner's job.
374
+ */
375
+ const EXPOSED = [
376
+ { path: "/.git/HEAD", is: "a git repository's HEAD", proof: has(/^(ref: refs\/\S+|[0-9a-f]{40})\s*$/) },
377
+ { path: "/.git/config", is: "a git repository's config", proof: has(/^\[core\]\s*$[\s\S]*repositoryformatversion/m) },
378
+ { path: "/.git-credentials", is: "git credentials", proof: has(/^https?:\/\/[^\s:@/]+:[^\s@/]+@\S+\s*$/m) },
379
+ { path: "/.env", is: "an environment file", proof: environmentFile },
380
+ { path: "/.htpasswd", is: "a password file", proof: has(/^[^\s:<>]+:(\$apr1\$|\$2[aby]\$|\$[156]\$|\{SHA\})\S+\s*$/m) },
381
+ { path: "/.aws/credentials", is: "cloud credentials", proof: has(/^\s*aws_access_key_id\s*=/m) },
382
+ { path: "/.npmrc", is: "a registry token", proof: has(/^\S*_authToken\s*=/m) },
383
+ { path: "/id_rsa", is: "a private key", proof: has(/^-----BEGIN [A-Z ]*PRIVATE KEY-----/) },
384
+ { path: "/server-status", is: "Apache's status page", proof: has(/Apache Server Status/) },
385
+ { path: "/phpinfo.php", is: "PHP's configuration page", proof: (body) => body.includes("phpinfo()") && body.includes("PHP Version") },
386
+ { path: "/actuator/env", is: "Spring's environment", proof: has(/"propertySources"\s*:/) },
387
+ { path: "/debug/pprof/", is: "Go's profiler", proof: has(/Types of profiles available|goroutine\?debug=/) },
388
+ ];
389
+ async function exposedFiles(ctx) {
390
+ const served = [];
391
+ let answered = 0;
392
+ let unanswered = 0;
393
+ for (const file of EXPOSED) {
394
+ let reply;
395
+ try {
396
+ reply = await ask(ctx, file.path, `for ${file.path}`);
397
+ }
398
+ catch (err) {
399
+ // A path the environment keeps a test from (its deny list) is not asked, and said; one that gets no answer is not served.
400
+ if (err instanceof Refused)
401
+ ctx.note(err.message.replace(/^omniqa: /, ""));
402
+ else if (err instanceof NoAnswer)
403
+ unanswered++;
404
+ else
405
+ throw err;
406
+ continue;
407
+ }
408
+ if (reply.status === 429)
409
+ throw slowed(ctx, `aimed at ${file.path}`);
410
+ answered++;
411
+ if (reply.status >= 200 && reply.status < 300 && file.proof((await reply.read()).body))
412
+ served.push(`GET ${file.path} answered ${reply.status} with ${file.is}`);
413
+ }
414
+ if (served.length > 0)
415
+ throw new NotHeld(`${served.join("; ")}: served to anyone who asks`);
416
+ if (answered === 0 && unanswered > 0)
417
+ throw new Error(`none of the ${EXPOSED.length} paths was answered: the product stopped answering, or something on the way drops what is asked for them`);
418
+ // "Not served" is said of a product that still serves its page.
419
+ if (answered > 0)
420
+ await stillAnswers(ctx, await ctx.answered());
421
+ }
422
+ /** The text of an answer a sign is looked for in: its start. A pattern is not run over megabytes of one line. */
423
+ const READ = 262_144;
424
+ /** The first of them an answer carries that the page's own answer does not: a page that holds such words whatever is asked says nothing about a value. */
425
+ const fresh = (signs, body, own) => signs.find((sign) => sign.pattern.test(body.slice(0, READ)) && !sign.pattern.test(own.slice(0, READ)));
426
+ /**
427
+ * A failure is the value's when it comes twice and the request as the page sent it is still answered: once is a hiccup
428
+ * of the product or of what stands before it, and a product that has begun to fail, or a firewall that has had enough of
429
+ * this machine, fails whatever the value.
430
+ */
431
+ async function failsOn(ctx, reply, asked, own, why) {
432
+ if (reply.status < 500)
433
+ return;
434
+ if ((await asked.again()).status < 500)
435
+ return;
436
+ const still = await ctx.send(ctx.request, asSent(ctx));
437
+ if (still.status >= 500)
438
+ throw new Error(`${ctx.name} ${asked.what} answered ${reply.status}, and so does the request ${asSent(ctx)} by now (${still.status}): the product is failing or turning this machine away, whatever the value`);
439
+ throw new NotHeld(`${ctx.name} ${asked.what} answered ${reply.status} twice, and ${own.status} ${asSent(ctx)}: ${why}`);
440
+ }
441
+ /** The markup a page must not carry as it was sent: what opens a tag, and what closes an attribute. */
442
+ const MARKUP = `<i>"'`;
443
+ async function reflection(ctx) {
444
+ // A marker of this run's own: what a page carries of it came from this request.
445
+ const marker = `omniqa${[...randomBytes(6)].map((byte) => String.fromCodePoint(97 + (byte % 26))).join("")}${MARKUP}`;
446
+ let pages = 0;
447
+ await sweep(ctx, [{ what: "markup after a marker", value: () => marker }], async (reply, asked) => {
448
+ // A browser renders no redirect's body, and runs nothing in an answer it does not read as a page: a marker in JSON is no script.
449
+ if (reply.status >= 300 && reply.status < 400)
450
+ return;
451
+ const { headers, body } = await reply.read();
452
+ if (!/html/i.test(header(headers, "content-type") ?? ""))
453
+ return;
454
+ pages++;
455
+ if (body.includes(marker))
456
+ throw new NotHeld(`${ctx.name} ${asked.what} answered ${reply.status} with a page that carries it as it was sent: markup a link puts in the parameter becomes part of the page`);
457
+ });
458
+ if (pages === 0)
459
+ throw new Error(`no answer to ${ctx.name} was a page (html): a marker in any other answer runs nothing, so this check has nothing to show on this request`);
460
+ }
461
+ /** What a database says when a query does not parse, by engine. */
462
+ const DATABASE_ERRORS = [
463
+ { is: "a MySQL error", pattern: /You have an error in your SQL syntax|check the manual that corresponds to your (MySQL|MariaDB) server version|MySQLSyntaxErrorException/i },
464
+ { is: "a PostgreSQL error", pattern: /PG::\w*Error|org\.postgresql\.util\.PSQLException|unterminated quoted string at or near|syntax error at or near "|psycopg2?\.errors\./i },
465
+ { is: "a SQLite error", pattern: /SQLITE_ERROR|sqlite3\.OperationalError|unrecognized token: "/i },
466
+ { is: "a SQL Server error", pattern: /Unclosed quotation mark after the character string|Incorrect syntax near '|Microsoft OLE DB Provider for SQL Server|System\.Data\.SqlClient\.SqlException/i },
467
+ { is: "an Oracle error", pattern: /\bORA-\d{5}\b|quoted string not properly terminated/i },
468
+ { is: "a database driver's error", pattern: /SQLSTATE\[\w+\]|java\.sql\.SQL\w*Exception|Sequelize(Database|Base)Error|PrismaClient\w*Error|QueryFailedError|ActiveRecord::StatementInvalid|MongoServerError/ },
469
+ ];
470
+ /**
471
+ * A database's own words in the answer to a quote, and not in the answer to the same quote twice: one quote breaks a
472
+ * query built from the value, two mend it. A page that shows such words (a forum's search, a manual) shows them for both,
473
+ * and a failure with no such words is the errors check's to report.
474
+ * ponytail: what breaks a query, and no more: a value that widens one (`' OR '1'='1`, an operator in a JSON body) widens
475
+ * whatever the query does, a delete included, and is the researcher's to try where it has looked at the request. A query
476
+ * that takes a number fails on two quotes as on one: that one this check cannot tell from a page of such words, and says so.
477
+ */
478
+ async function sql(ctx) {
479
+ const own = (await (await ctx.answered()).read()).body;
480
+ await sweep(ctx, [{ what: "a quote", value: () => "'" }, { what: "a double quote", value: () => '"' }], async (reply, asked) => {
481
+ const error = fresh(DATABASE_ERRORS, (await reply.read()).body, own);
482
+ if (error === undefined)
483
+ return;
484
+ const twice = `${asked.what.replace(" in ", " twice in ")}`;
485
+ const mended = await asked.other(`${asked.value}${asked.value}`, twice);
486
+ if (fresh([error], (await mended.read()).body, own) !== undefined)
487
+ throw new Error(`${ctx.name} carries the same words ${asked.what} and ${twice}: this check cannot tell a query the value breaks from a page that shows such words`);
488
+ throw new NotHeld(`${ctx.name} ${asked.what} answered ${reply.status} with a database error in it (${error.is}), and none ${twice}: the value reaches a query as part of it`);
489
+ }, 1);
490
+ }
491
+ /** Two primes: their product is in no page by chance. */
492
+ const PRODUCT = "62615533";
493
+ async function template(ctx) {
494
+ if ((await (await ctx.answered()).read()).body.includes(PRODUCT))
495
+ throw new Error(`${ctx.name} carries ${PRODUCT} in its answer ${asSent(ctx)}: what an expression evaluates to cannot be told from what is already there`);
496
+ await sweep(ctx, ["{{7919*7907}}", "${7919*7907}", "<%= 7919*7907 %>"].map((expression) => ({ what: `the expression ${expression}`, value: () => expression })), async (reply, asked) => {
497
+ if ((await reply.read()).body.includes(PRODUCT))
498
+ throw new NotHeld(`${ctx.name} ${asked.what} answered ${PRODUCT}: the value is run as a template on the server`);
499
+ });
500
+ }
501
+ const SPLIT_HEADER = "X-Omniqa-Split";
502
+ async function headerSplit(ctx) {
503
+ await sweep(ctx, [{ what: "a line break and a header of its own", value: () => `omniqa\r\n${SPLIT_HEADER}: 1` }], async (reply, asked) => {
504
+ if (header((await reply.read()).headers, SPLIT_HEADER.toLowerCase()) !== undefined)
505
+ throw new NotHeld(`${ctx.name} ${asked.what} answered with that header (${SPLIT_HEADER}): a value adds headers to the answer, and can split it in two`);
506
+ });
507
+ }
508
+ /**
509
+ * What a product prints when it fails in the open, by what it is. Each pattern is bounded: an answer is the product's
510
+ * text, and may be one long line.
511
+ */
512
+ const TRACES = [
513
+ { is: "a Python traceback", pattern: /Traceback \(most recent call last\)/ },
514
+ { is: "a JavaScript stack trace", pattern: /\bat [\w$.<>]{1,120}(?: [\w$.<>]{1,120}){0,3} \((?:node:|file:\/\/|\/)[^)\s]{1,300}:\d+:\d+\)/ },
515
+ { is: "a Java stack trace", pattern: /\bat [\w$.]{1,300}\([\w$]{1,120}\.(?:java|kt|scala):\d+\)/ },
516
+ { is: "a .NET stack trace", pattern: /\bat [\w.<>`]{1,300}\([^()\n]{0,300}\) in [^\n]{1,300}:line \d+/ },
517
+ { is: "a PHP error", pattern: /<b>(?:Fatal error|Warning|Notice)<\/b>: |on line <b>\d+<\/b>/, inline: true },
518
+ { is: "a PHP error", pattern: /Fatal error: Uncaught |Stack trace:\s*#0 / },
519
+ { is: "a Ruby backtrace", pattern: /\.rb:\d+:in [`']/ },
520
+ { is: "a Go panic", pattern: /goroutine \d+ \[running\]/ },
521
+ { is: "a framework's debug page", pattern: /Django Version:|Werkzeug Debugger|Application Trace \| Framework Trace|<title>Whoops! There was an error\.<\/title>|Symfony Exception/ },
522
+ ];
523
+ const NUMBER = /^-?\d+(\.\d+)?$/;
524
+ /**
525
+ * A trace counts in an answer whose status is not the page's own (a listing that shows one for another value is content;
526
+ * PHP's own markup aside, which a failing page prints into a 200). A failure counts when it comes twice.
527
+ */
528
+ async function errors(ctx) {
529
+ const own = await ctx.answered();
530
+ const text = (await own.read()).body;
531
+ const malformed = [
532
+ { what: "a quote", value: () => "'" },
533
+ { what: "4,000 characters", value: () => "A".repeat(4000) },
534
+ { what: "a word where a number was", value: (p) => (NUMBER.test(p.value) ? "omniqa" : undefined) },
535
+ { what: "a list where a value was", value: (p) => (NUMBER.test(p.value) ? undefined : p.value), list: true },
536
+ { what: "no value", value: () => "" },
537
+ ];
538
+ await sweep(ctx, malformed, async (reply, asked) => {
539
+ const trace = fresh(TRACES.filter((sign) => sign.inline === true || reply.status !== own.status), (await reply.read()).body, text);
540
+ if (trace !== undefined)
541
+ throw new NotHeld(`${ctx.name} ${asked.what} answered ${reply.status} with an error trace in it (${trace.is}): the answer shows how the product is built`);
542
+ await failsOn(ctx, reply, asked, own, "the product fails on a value it should turn down");
543
+ }, 2);
544
+ }
545
+ /** A site nobody owns: `.example` is reserved, so nothing is ever fetched from it. */
546
+ const FOREIGN_SITE = "omniqa-redirect.example";
547
+ /** ponytail: a redirect is a 3xx; a page that sends the visitor on by script or by a refresh tag is not read. */
548
+ async function redirect(ctx) {
549
+ const elsewhere = [
550
+ { what: "another site's address", value: () => `https://${FOREIGN_SITE}/` },
551
+ // What gets past a product that only looks for a leading slash.
552
+ { what: "another site's address without its scheme", value: () => `//${FOREIGN_SITE}/` },
553
+ ];
554
+ await sweep(ctx, elsewhere, (reply, asked) => {
555
+ if (reply.status >= 300 && reply.status < 400 && reply.location !== undefined && URL.parse(reply.location)?.hostname === FOREIGN_SITE)
556
+ throw new NotHeld(`${ctx.name} ${asked.what} answered ${reply.status} to that site: a link to this product sends a visitor wherever it names`);
557
+ });
558
+ }
559
+ const CLIMB = "../".repeat(8);
560
+ /** The first line of every passwd file. ponytail: a Unix file; a product on Windows is not asked for one of its own. */
561
+ const PASSWD = /^root:[^:\n]*:0:0:/m;
562
+ async function traversal(ctx) {
563
+ if (PASSWD.test((await (await ctx.answered()).read()).body))
564
+ throw new Error(`${ctx.name} carries the first line of a passwd file in its answer ${asSent(ctx)}: the file cannot be told from what is already there`);
565
+ const paths = [
566
+ { what: "a path that climbs out to etc/passwd", value: () => `${CLIMB}etc/passwd` },
567
+ // Decoded once on the way in, and once more by a product that decodes what it was handed.
568
+ { what: "a path that climbs out to etc/passwd, encoded,", value: () => `${CLIMB.replaceAll("/", "%2f")}etc%2fpasswd` },
569
+ { what: "the path /etc/passwd", value: () => "/etc/passwd" },
570
+ ];
571
+ await sweep(ctx, paths, async (reply, asked) => {
572
+ if (PASSWD.test((await reply.read()).body))
573
+ throw new NotHeld(`${ctx.name} ${asked.what} answered that file: the parameter reads any file the product can`);
574
+ });
575
+ }
576
+ async function origin(ctx) {
577
+ const own = await ctx.answered();
578
+ let foreign = withHeader(ctx.request, "Origin", FOREIGN_ORIGIN);
579
+ if (header(foreign.headers, "sec-fetch-site") !== undefined)
580
+ foreign = withHeader(foreign, "Sec-Fetch-Site", "cross-site");
581
+ const what = `with Origin ${FOREIGN_ORIGIN}`;
582
+ const reply = await ctx.send(foreign, what);
583
+ if (reply.status === 429)
584
+ throw slowed(ctx, what);
585
+ // A refusal is read by nobody, whatever its headers say; it is one of the Origin where the request as the page sent it is still answered.
586
+ if (reply.status >= 400)
587
+ return await stillAnswers(ctx, own);
588
+ const allowed = (await reply.read()).headers;
589
+ // Every origin (`*`) is allowed without credentials only: a browser refuses the two together.
590
+ if (header(allowed, "access-control-allow-origin") !== FOREIGN_ORIGIN || header(allowed, "access-control-allow-credentials") !== "true")
591
+ return;
592
+ // What a page of another site can make a browser send along is a cookie; a request that carried none answered what anyone gets.
593
+ const reads = header(ctx.request.headers, "cookie") === undefined ? "may read what it answers with a visitor's cookies, though this request carried none" : "may read this answer with the visitor's cookies";
594
+ throw new NotHeld(`${ctx.name} ${what} answered ${reply.status} and allows that origin with credentials (Access-Control-Allow-Origin names it, Access-Control-Allow-Credentials is true): the product tells a browser that a page of any site ${reads}`);
595
+ }
596
+ /** The redirects that stay on plain http a visitor is followed through. */
597
+ const HOPS = 5;
598
+ /**
599
+ * ponytail: a port that silently drops what is sent to it (a firewall's way) is "no answer" after the sidecar's ten
600
+ * seconds, and keeps Interceptor's repeater from then on (it sends one request at a time and never gives that one up):
601
+ * a request sent after it fails by name. The planning rules make this the last case of its suite, and a file's sidecar
602
+ * ends with the file; a repeater that drops a connection it cannot make is Interceptor's to gain.
603
+ */
604
+ async function httpsOnly(ctx) {
605
+ const at = new URL(ctx.origin);
606
+ // An https environment on a port of its own: which port would answer plain http for it is not something its url says.
607
+ if (at.protocol === "https:" && at.port !== "")
608
+ throw new Error("the environment's url names a port: what answers plain http for it is not known, so there is nothing to ask");
609
+ // As a new visitor asks: what a browser keeps off plain http (a Secure cookie, a token) does not travel over it here either.
610
+ const visitor = { ...ctx, request: withoutHeaders(ctx.request, SESSION_HEADERS) };
611
+ let target = `http://${at.host}/`;
612
+ for (let hop = 0; hop < HOPS; hop++) {
613
+ const name = `GET ${requestRoute(new URL(target).pathname)} over plain http`;
614
+ let reply;
615
+ try {
616
+ reply = await ask(visitor, target, `over plain http${hop === 0 ? "" : ", where it was sent on"}`);
617
+ }
618
+ catch (err) {
619
+ // Nothing answers plain http: there is nothing to read on the way.
620
+ if (err instanceof NoAnswer)
621
+ return;
622
+ throw err;
623
+ }
624
+ // A refusal or a failure serves no page.
625
+ if (reply.status >= 400)
626
+ return;
627
+ if (reply.status < 300)
628
+ throw new NotHeld(`${name} answered ${reply.status}: the page is served without TLS, where anyone on the way reads and changes it`);
629
+ const to = reply.location === undefined ? null : URL.parse(reply.location, target);
630
+ if (to === null)
631
+ throw new Error(`${name} answered ${reply.status} with no address to go to`);
632
+ if (to.protocol === "https:")
633
+ return;
634
+ target = to.href;
635
+ }
636
+ throw new Error(`GET / over plain http is sent on ${HOPS} times without reaching https or a page`);
637
+ }
638
+ export const CHECKS = [
639
+ { name: "no-session", category: "A01", cwe: ["CWE-306", "CWE-862"], target: "request", title: (o) => `${o.request} is refused without a session`, mutates: "as the request", replay: { without: SESSION_HEADERS }, open: (o) => `${o.request}, a request of ${o.actor}, answered ${o.answer} without a session` },
640
+ { name: "other-account", category: "A01", cwe: ["CWE-639"], target: "request", title: (o) => `${o.request} of ${o.actor} is refused with ${o.with}'s session`, mutates: "always", replay: { as: true }, open: (o) => `${o.request}, a request of ${o.actor}, answered ${o.answer} with ${o.with}'s session` },
641
+ { name: "lower-role", category: "A01", cwe: ["CWE-863", "CWE-284"], target: "request", title: (o) => `${o.request}, which only ${o.actor} asks for, is refused with ${o.with}'s session`, mutates: "always", replay: { as: true }, open: (o) => `${o.request}, a request only ${o.actor} makes, answered ${o.answer} with ${o.with}'s session` },
642
+ { name: "csrf", category: "A01", cwe: ["CWE-352"], target: "request", title: (o) => `${o.request} is refused when another site sends it`, mutates: "as the request", run: csrf },
643
+ { name: "redirect", category: "A01", cwe: ["CWE-601"], target: "request", title: (o) => `${o.request} with another site's address in a parameter does not redirect there`, mutates: "as the request", run: onParameters(redirect) },
644
+ { name: "traversal", category: "A01", cwe: ["CWE-22"], target: "request", title: (o) => `${o.request} with a path that climbs out in a parameter reads no file`, mutates: "as the request", run: onParameters(traversal) },
645
+ { name: "origin", category: "A02", cwe: ["CWE-942"], target: "request", title: (o) => `${o.request} does not let another site read its answer with credentials`, mutates: "as the request", run: origin },
646
+ { name: "exposed-files", category: "A02", cwe: ["CWE-538", "CWE-200"], target: "site", title: (o) => `${o.product} serves none of its repository, credential or server-status files`, mutates: "as the request", run: exposedFiles },
647
+ { name: "token", category: "A04", cwe: ["CWE-347"], target: "request", title: (o) => `${o.request} refuses a token nobody signed`, mutates: "as the request", run: token },
648
+ { name: "https-only", category: "A04", cwe: ["CWE-319"], target: "site", title: (o) => `${o.product} serves no page over plain http`, mutates: "as the request", run: httpsOnly },
649
+ { name: "reflection", category: "A05", cwe: ["CWE-79"], target: "request", title: (o) => `${o.request} with markup in a parameter answers no page that carries it unescaped`, mutates: "as the request", run: onParameters(reflection) },
650
+ { name: "sql", category: "A05", cwe: ["CWE-89"], target: "request", title: (o) => `${o.request} with a quote in a parameter answers no database error`, mutates: "as the request", run: onParameters(sql) },
651
+ { name: "template", category: "A05", cwe: ["CWE-94", "CWE-1336"], target: "request", title: (o) => `${o.request} with a template expression in a parameter does not evaluate it`, mutates: "as the request", run: onParameters(template) },
652
+ { name: "header", category: "A05", cwe: ["CWE-113"], target: "request", title: (o) => `${o.request} with a line break in a parameter gains no header`, mutates: "as the request", run: onParameters(headerSplit) },
653
+ { name: "after-logout", category: "A07", cwe: ["CWE-613"], target: "request", title: (o) => `${o.request} is refused with the session ${o.actor} signed out of`, mutates: "always", replay: { signOut: true }, open: (o) => `${o.request} answered ${o.answer} with the session ${o.actor} had signed out of` },
654
+ { name: "fixation", category: "A07", cwe: ["CWE-384"], target: "request", title: (o) => `Signing in as ${o.actor} does not keep the session the visitor had`, mutates: "always", run: fixation },
655
+ { name: "enumeration", category: "A07", cwe: ["CWE-204"], target: "request", title: () => "The sign-in answers a wrong password alike for a real account and an unknown one", mutates: "always", signIn: true, run: enumeration },
656
+ { name: "throttle", category: "A07", cwe: ["CWE-307", "CWE-770"], target: "request", title: () => "The sign-in slows down wrong passwords in a row", mutates: "always", signIn: true, run: throttle },
657
+ { name: "default-credentials", category: "A07", cwe: ["CWE-1392"], target: "request", title: () => "The sign-in refuses the default passwords", mutates: "always", signIn: true, run: defaultCredentials },
658
+ { name: "errors", category: "A10", cwe: ["CWE-209", "CWE-20"], target: "request", title: (o) => `${o.request} with a malformed parameter is turned down without a failure`, mutates: "as the request", run: onParameters(errors) },
659
+ ];
660
+ export const checkNamed = (name) => CHECKS.find((c) => c.name === name);
661
+ //# sourceMappingURL=security-checks.js.map