kryptheon 0.1.55 → 0.1.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -0
- package/bin/kryptheon.js +143 -1
- package/kryptheon-api.js +896 -0
- package/kryptheon-dashboard-page.js +1 -1
- package/kryptheon-dashboard.js +61 -6
- package/kryptheon-look.js +8 -0
- package/kryptheon-map.js +2910 -0
- package/kryptheon-roles.js +85 -10
- package/package.json +8 -4
package/kryptheon-map.js
ADDED
|
@@ -0,0 +1,2910 @@
|
|
|
1
|
+
// The backend map: what an app's server answers, and what stands in front of
|
|
2
|
+
// each answer - read from its code, never by running it.
|
|
3
|
+
//
|
|
4
|
+
// For every route it finds it says:
|
|
5
|
+
// - the method and the full path, with every router prefix it is mounted under;
|
|
6
|
+
// - the middleware in front of it, inherited ones included, each with the file
|
|
7
|
+
// and line it is defined on;
|
|
8
|
+
// - three guards, each as guard_detected | not_detected | unknown:
|
|
9
|
+
// auth a check that turns away someone who is not signed in
|
|
10
|
+
// (a session, a token, an API key);
|
|
11
|
+
// role a check that turns away a signed-in person whose role is not
|
|
12
|
+
// allowed, for every request to the route;
|
|
13
|
+
// signature for webhooks: a check that turns away a body the provider
|
|
14
|
+
// did not sign;
|
|
15
|
+
// not_detected is said only when every function in front of the route was
|
|
16
|
+
// found and read; when one could not be followed the answer is unknown, and
|
|
17
|
+
// the reason is said;
|
|
18
|
+
// - every database statement its handler makes (SQL through pg or a wrapper
|
|
19
|
+
// of it, sql`` templates, supabase .from(), prisma), with the table, the
|
|
20
|
+
// operation, and whether the rows are limited to the signed-in person's
|
|
21
|
+
// organisation - read from the WHERE clause, the inserted columns, and
|
|
22
|
+
// where each value comes from (the session, the request, a row read
|
|
23
|
+
// earlier). Row level security, a table with no schema, or SQL built at
|
|
24
|
+
// run time make that answer unknown, never "not limited".
|
|
25
|
+
//
|
|
26
|
+
// What it never does: run the app, send a request, change a file of the app,
|
|
27
|
+
// or print a secret - every line of code it quotes passes through the same
|
|
28
|
+
// key finder the code check uses, and a key in it is masked.
|
|
29
|
+
//
|
|
30
|
+
// Everything here is a reading of code. A route with no check found is a place
|
|
31
|
+
// to look, never a proven hole: the report says "to check", and only a later
|
|
32
|
+
// runtime check (roles, edge) can say CONFIRMED.
|
|
33
|
+
//
|
|
34
|
+
// Patterns it cannot read are listed, with their file and line, as
|
|
35
|
+
// "not read" - never skipped in silence.
|
|
36
|
+
|
|
37
|
+
const fs = require('fs');
|
|
38
|
+
const path = require('path');
|
|
39
|
+
const keys = require('./kryptheon-keys.js');
|
|
40
|
+
const code = require('./kryptheon-code.js');
|
|
41
|
+
|
|
42
|
+
const SKIP_DIRS = new Set([
|
|
43
|
+
'node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt', '.svelte-kit',
|
|
44
|
+
'coverage', 'vendor', '.vercel', '.netlify', '.turbo', '.cache', 'test-results',
|
|
45
|
+
]);
|
|
46
|
+
const STATIC_DIRS = new Set(['public', 'static', 'assets']);
|
|
47
|
+
const CODE_EXT = /\.(js|mjs|cjs|ts|mts|cts|jsx|tsx)$/i;
|
|
48
|
+
const MAX_BYTES = 800 * 1024;
|
|
49
|
+
const METHODS = ['get', 'post', 'put', 'patch', 'delete', 'del', 'all', 'options', 'head'];
|
|
50
|
+
const STATUS = { DETECTED: 'guard_detected', NOT: 'not_detected', UNKNOWN: 'unknown' };
|
|
51
|
+
|
|
52
|
+
// Middleware from packages that is known not to turn anyone away.
|
|
53
|
+
const NOT_GUARDS = /^(express\.(json|urlencoded|raw|text|static)|bodyParser(\.\w+)?|json|urlencoded|cors|helmet|morgan|compression|cookieParser|cookie-parser|session|expressSession|cookieSession|csurf|multer(\.\w+)?|upload(\.\w+)?|rateLimit|limiter|serveStatic|favicon|methodOverride|express\.Router)$/;
|
|
54
|
+
// Middleware from packages that is known to turn away whoever is not signed in.
|
|
55
|
+
const PACKAGE_AUTH = /^(passport\.authenticate|expressjwt|jwt|requiresAuth|ClerkExpressRequireAuth|requireAuth|withAuth|ensureLoggedIn|ensureAuthenticated|checkJwt|auth)$/;
|
|
56
|
+
const PACKAGE_AUTH_SOURCES = /^(passport|express-jwt|express-openid-connect|@clerk\/|connect-ensure-login|express-oauth2-jwt-bearer|@auth0\/)/;
|
|
57
|
+
// Frameworks this map does not read yet: their routes are said to be not read.
|
|
58
|
+
const OTHER_FRAMEWORKS = /^(fastify|koa|@koa\/router|koa-router|hono|@hono\/hono|oak|@oak\/oak|@nestjs\/\w+|@hapi\/hapi|hapi|restify|polka|@adonisjs\/\w+|sails|elysia)$/;
|
|
59
|
+
|
|
60
|
+
// Where the signed-in person lives on a request, in the apps this was built on.
|
|
61
|
+
const IDENTITY_SEGS = /^(user|users|session|auth|actor|account|member|currentUser|identity|principal|claims|userId|user_id|uid|sub|me|profile|viewer|isAuthenticated|isLoggedIn|token|kauth|apiKey|api_key|tenant|org|workspace)$/;
|
|
62
|
+
const IDENTITY_NAMES = /^(user|currentUser|current_user|me|actor|member|account|profile|viewer|identity|principal|session|sessionUser|authUser|auth|claims)$/i;
|
|
63
|
+
const ROLE_SEGS = /^(role|roles|isAdmin|is_admin|isOwner|is_owner|admin|permissions|perms|scopes|scope|capabilities|access|accessLevel|access_level|level)$/;
|
|
64
|
+
const SIGNATURE_CALLS = /^(createHmac|timingSafeEqual|validateWebhookSignature|constructEvent|constructEventAsync|verifyWebhook|verifySignature|validateSignature|verify)$/;
|
|
65
|
+
const SIGNATURE_NAMES = /sign|hmac|webhook|valid/i;
|
|
66
|
+
const APIKEY_HEADER = /^(x-api-key|x-api-token|api-key|apikey|x-auth-token)$/i;
|
|
67
|
+
// A local that holds who is calling, from a lookup named as one (deps.userIdFrom(jwt), getCurrentUser(token)).
|
|
68
|
+
const IDENTITY_LOOKUP_LOCAL = /^(user|userId|user_id|uid|caller|callerId|me|viewer|account|accountId|session|identity|actor|actorId|profile)$/i;
|
|
69
|
+
const IDENTITY_LOOKUP_CALL = /^(userFrom|userIdFrom|getUser|getUserId|getUserFrom\w*|currentUser|getCurrentUser|getSession|getCaller|callerFrom|whoami|whoAmI|authenticate|verifyUser|requireUser|identify|userFromToken|userFromJwt)$/;
|
|
70
|
+
const TOKEN_LOCAL = /^(token|apiKey|api_key|bearer|bearerToken|jwt|accessToken|projectToken|key)$/i;
|
|
71
|
+
|
|
72
|
+
/** Every source file worth reading, skipping what is not the app's own code. */
|
|
73
|
+
function listFiles(root) {
|
|
74
|
+
const out = [];
|
|
75
|
+
(function walk(dir) {
|
|
76
|
+
let entries;
|
|
77
|
+
try {
|
|
78
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
79
|
+
} catch (err) {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
for (const entry of entries) {
|
|
83
|
+
if (entry.name.startsWith('.')) continue;
|
|
84
|
+
const full = path.join(dir, entry.name);
|
|
85
|
+
if (entry.isDirectory()) {
|
|
86
|
+
// public/, static/ and assets/ at the top hold what the browser downloads; deeper (pages/api/public) they are routes
|
|
87
|
+
const top = dir === root;
|
|
88
|
+
if (!SKIP_DIRS.has(entry.name) && !(top && STATIC_DIRS.has(entry.name)) && entry.name !== 'tests' && entry.name !== '__tests__') walk(full);
|
|
89
|
+
} else if (CODE_EXT.test(entry.name) && !/\.(min|d)\.[cm]?[jt]s$/i.test(entry.name) && !/\.(test|spec)\.[cm]?[jt]sx?$/i.test(entry.name)) {
|
|
90
|
+
out.push(full);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
})(root);
|
|
94
|
+
return out.sort();
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** A line of code fit to print: trimmed, short, and with any key in it masked. */
|
|
98
|
+
function snippet(mod, line) {
|
|
99
|
+
let text = (mod.lines[line - 1] || '').trim();
|
|
100
|
+
try {
|
|
101
|
+
for (const k of keys.secretsIn(mod.rel, text, new Map())) if (k && k.value) text = text.split(k.value).join(keys.masked(k.value));
|
|
102
|
+
} catch (err) {
|
|
103
|
+
/* the finder never decides whether a line is shown - masking below still runs */
|
|
104
|
+
}
|
|
105
|
+
// anything long and random enough to be a key is masked whatever it is called
|
|
106
|
+
text = text.replace(/(['"`])([A-Za-z0-9_\-+/=.]{28,})\1/g, (m, q, v) => (/[0-9]/.test(v) && /[A-Za-z]/.test(v) && !/[/.]{2}|^https?/.test(v) ? q + keys.masked(v) + q : m));
|
|
107
|
+
return text.length > 160 ? text.slice(0, 157) + '...' : text;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function makeContext(root, parser) {
|
|
111
|
+
const t = parser.types;
|
|
112
|
+
const ctx = { root, parser, t, modules: new Map(), unreadable: [], notRead: [], files: [] };
|
|
113
|
+
const relOf = (full) => path.relative(root, full).split(path.sep).join('/');
|
|
114
|
+
|
|
115
|
+
ctx.load = function load(abs) {
|
|
116
|
+
if (ctx.modules.has(abs)) return ctx.modules.get(abs);
|
|
117
|
+
let source;
|
|
118
|
+
try {
|
|
119
|
+
if (fs.statSync(abs).size > MAX_BYTES) throw new Error('larger than ' + Math.round(MAX_BYTES / 1024) + ' KB');
|
|
120
|
+
source = fs.readFileSync(abs, 'utf8');
|
|
121
|
+
} catch (err) {
|
|
122
|
+
ctx.modules.set(abs, null);
|
|
123
|
+
ctx.unreadable.push({ file: relOf(abs), why: err.message });
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
let ast;
|
|
127
|
+
try {
|
|
128
|
+
ast = parser.babelParse(source, abs, true);
|
|
129
|
+
} catch (err) {
|
|
130
|
+
try {
|
|
131
|
+
ast = parser.babelParse(source, abs, false);
|
|
132
|
+
} catch (err2) {
|
|
133
|
+
ctx.modules.set(abs, null);
|
|
134
|
+
ctx.unreadable.push({ file: relOf(abs), why: 'could not be parsed: ' + String(err.message).split('\n')[0] });
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
const mod = { abs, rel: relOf(abs), source, lines: source.split(/\r?\n/), ast, program: null, imports: new Map(), exportsNamed: new Map(), exportDefault: null, cjsExports: null, calls: [] };
|
|
139
|
+
ctx.modules.set(abs, mod);
|
|
140
|
+
parser.traverse(ast, {
|
|
141
|
+
Program(p) {
|
|
142
|
+
mod.program = p;
|
|
143
|
+
},
|
|
144
|
+
ImportDeclaration(p) {
|
|
145
|
+
const source = p.node.source.value;
|
|
146
|
+
for (const s of p.node.specifiers) {
|
|
147
|
+
const imported = t.isImportDefaultSpecifier(s) ? 'default' : t.isImportNamespaceSpecifier(s) ? '*' : (s.imported.name || s.imported.value);
|
|
148
|
+
mod.imports.set(s.local.name, { source, imported, line: p.node.loc.start.line });
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
ExportNamedDeclaration(p) {
|
|
152
|
+
const d = p.get('declaration');
|
|
153
|
+
if (d.node) {
|
|
154
|
+
if (d.isFunctionDeclaration() || d.isClassDeclaration()) mod.exportsNamed.set(d.node.id.name, d);
|
|
155
|
+
else if (d.isVariableDeclaration()) for (const dec of d.get('declarations')) if (t.isIdentifier(dec.node.id)) mod.exportsNamed.set(dec.node.id.name, dec.get('init'));
|
|
156
|
+
}
|
|
157
|
+
for (const s of p.get('specifiers')) {
|
|
158
|
+
const exported = s.node.exported.name || s.node.exported.value;
|
|
159
|
+
if (p.node.source) mod.exportsNamed.set(exported, { reexport: p.node.source.value, name: s.node.local ? s.node.local.name : 'default' });
|
|
160
|
+
else if (s.node.local) mod.exportsNamed.set(exported, { local: s.node.local.name, at: s });
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
ExportDefaultDeclaration(p) {
|
|
164
|
+
mod.exportDefault = p.get('declaration');
|
|
165
|
+
},
|
|
166
|
+
AssignmentExpression(p) {
|
|
167
|
+
const left = p.node.left;
|
|
168
|
+
// module.exports = x / module.exports.name = x / exports.name = x
|
|
169
|
+
if (t.isMemberExpression(left)) {
|
|
170
|
+
const chain = memberChain(left);
|
|
171
|
+
if (chain && chain[0] === 'module' && chain[1] === 'exports' && chain.length === 2) mod.cjsExports = p.get('right');
|
|
172
|
+
else if (chain && ((chain[0] === 'module' && chain[1] === 'exports' && chain.length === 3) || (chain[0] === 'exports' && chain.length === 2))) {
|
|
173
|
+
mod.exportsNamed.set(chain[chain.length - 1], p.get('right'));
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
CallExpression(p) {
|
|
178
|
+
mod.calls.push(p);
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
return mod;
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
/** A module path an import names, as a file of this project - or null for a package. */
|
|
185
|
+
ctx.resolveModule = function resolveModule(fromAbs, spec) {
|
|
186
|
+
if (typeof spec !== 'string' || !/^\.{1,2}(\/|$)|^\//.test(spec)) return null;
|
|
187
|
+
const base = path.resolve(path.dirname(fromAbs), spec);
|
|
188
|
+
const stem = base.replace(/\.(js|mjs|cjs|jsx)$/i, '');
|
|
189
|
+
const tries = [base, stem + '.ts', stem + '.tsx', stem + '.mts', stem + '.cts', stem + '.js', stem + '.mjs', stem + '.cjs', stem + '.jsx',
|
|
190
|
+
path.join(base, 'index.ts'), path.join(base, 'index.js'), path.join(base, 'index.tsx'), path.join(base, 'index.mjs')];
|
|
191
|
+
for (const f of tries) {
|
|
192
|
+
try {
|
|
193
|
+
if (fs.statSync(f).isFile()) return f;
|
|
194
|
+
} catch (err) {
|
|
195
|
+
/* next */
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return undefined; // a local path that is not there
|
|
199
|
+
};
|
|
200
|
+
return ctx;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** ['req', 'session', 'user'] for req.session.user; null when any part is computed and not a fixed text. */
|
|
204
|
+
function memberChain(node) {
|
|
205
|
+
const out = [];
|
|
206
|
+
let n = node;
|
|
207
|
+
while (n) {
|
|
208
|
+
if (n.type === 'MemberExpression' || n.type === 'OptionalMemberExpression') {
|
|
209
|
+
if (!n.computed && n.property.type === 'Identifier') out.unshift(n.property.name);
|
|
210
|
+
else if (n.computed && n.property.type === 'StringLiteral') out.unshift(n.property.value);
|
|
211
|
+
else return null;
|
|
212
|
+
n = n.object;
|
|
213
|
+
} else if (n.type === 'Identifier') {
|
|
214
|
+
out.unshift(n.name);
|
|
215
|
+
return out;
|
|
216
|
+
} else if (n.type === 'ThisExpression') {
|
|
217
|
+
out.unshift('this');
|
|
218
|
+
return out;
|
|
219
|
+
} else if (n.type === 'TSNonNullExpression' || n.type === 'TSAsExpression' || n.type === 'ParenthesizedExpression') {
|
|
220
|
+
n = n.expression;
|
|
221
|
+
} else {
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const unwrapTs = (p) => {
|
|
229
|
+
while (p && p.node && (p.isTSAsExpression() || p.isTSNonNullExpression() || p.isParenthesizedExpression() || p.isTSSatisfiesExpression && p.isTSSatisfiesExpression() || p.isAwaitExpression())) p = p.get('expression');
|
|
230
|
+
return p;
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* What a reference in the code is, followed through bindings and imports:
|
|
235
|
+
* { kind: 'fn', path, mod, via } a function of the app's own code
|
|
236
|
+
* { kind: 'container', container } an express app or router
|
|
237
|
+
* { kind: 'pkg', name, source } something from a package (express.json(), passport.authenticate('jwt'))
|
|
238
|
+
* { kind: 'value', path, mod } an expression that is none of these (an object, a string)
|
|
239
|
+
* { kind: 'unknown', why } could not be followed
|
|
240
|
+
*/
|
|
241
|
+
function resolveRef(ctx, mod, p, depth = 0, seen = new Set()) {
|
|
242
|
+
const t = ctx.t;
|
|
243
|
+
p = unwrapTs(p);
|
|
244
|
+
if (!p || !p.node) return { kind: 'unknown', why: 'nothing there' };
|
|
245
|
+
if (depth > 12) return { kind: 'unknown', why: 'followed too far' };
|
|
246
|
+
if (p.isFunction()) return { kind: 'fn', path: p, mod };
|
|
247
|
+
const c = ctx.containerAt(p);
|
|
248
|
+
if (c) return { kind: 'container', container: c };
|
|
249
|
+
if (p.isIdentifier()) {
|
|
250
|
+
const name = p.node.name;
|
|
251
|
+
const binding = p.scope.getBinding(name);
|
|
252
|
+
if (!binding) {
|
|
253
|
+
return { kind: 'unknown', why: name + ' is not defined in this file' };
|
|
254
|
+
}
|
|
255
|
+
const key = mod.abs + ':' + binding.identifier.start;
|
|
256
|
+
if (seen.has(key)) return { kind: 'unknown', why: 'refers back to itself' };
|
|
257
|
+
seen.add(key);
|
|
258
|
+
const bp = binding.path;
|
|
259
|
+
if (ctx.containerOfBinding(binding)) return { kind: 'container', container: ctx.containerOfBinding(binding) };
|
|
260
|
+
if (bp.isFunctionDeclaration() || bp.isClassDeclaration()) return bp.isFunctionDeclaration() ? { kind: 'fn', path: bp, mod } : { kind: 'value', path: bp, mod };
|
|
261
|
+
if (bp.isVariableDeclarator()) {
|
|
262
|
+
const id = bp.node.id;
|
|
263
|
+
const init = bp.get('init');
|
|
264
|
+
if (t.isIdentifier(id)) {
|
|
265
|
+
if (!init.node) return { kind: 'unknown', why: name + ' has no value where it is declared' };
|
|
266
|
+
const req = requireOf(t, init.node);
|
|
267
|
+
if (req) return fromModule(ctx, mod, req, 'default', depth, seen, name);
|
|
268
|
+
// a value assigned later (let x; x = ...) is not followed
|
|
269
|
+
if (binding.constantViolations.length) return { kind: 'unknown', why: name + ' is assigned more than once' };
|
|
270
|
+
return resolveRef(ctx, mod, init, depth + 1, seen);
|
|
271
|
+
}
|
|
272
|
+
if (t.isObjectPattern(id) && init.node) {
|
|
273
|
+
const req = requireOf(t, init.node);
|
|
274
|
+
const prop = id.properties.find((q) => t.isObjectProperty(q) && t.isIdentifier(q.value) && q.value.name === name);
|
|
275
|
+
const key2 = prop && (prop.key.name || prop.key.value);
|
|
276
|
+
if (req && key2) return fromModule(ctx, mod, req, key2, depth, seen, name);
|
|
277
|
+
if (key2) {
|
|
278
|
+
const obj = resolveRef(ctx, mod, init, depth + 1, seen);
|
|
279
|
+
if (obj.kind === 'pkg') return { kind: 'pkg', name: obj.name + '.' + key2, source: obj.source };
|
|
280
|
+
if (obj.kind === 'value' && obj.path.isObjectExpression()) return propertyOf(ctx, obj.mod, obj.path, key2, depth, seen);
|
|
281
|
+
}
|
|
282
|
+
return { kind: 'unknown', why: name + ' comes out of a destructured value that could not be followed' };
|
|
283
|
+
}
|
|
284
|
+
return { kind: 'unknown', why: name + ' comes out of a pattern that could not be followed' };
|
|
285
|
+
}
|
|
286
|
+
if (bp.isImportSpecifier() || bp.isImportDefaultSpecifier() || bp.isImportNamespaceSpecifier()) {
|
|
287
|
+
const imp = mod.imports.get(name);
|
|
288
|
+
if (imp) return fromModule(ctx, mod, imp.source, imp.imported, depth, seen, name);
|
|
289
|
+
}
|
|
290
|
+
if (binding.kind === 'param') return { kind: 'unknown', why: name + ' is a parameter', param: true, binding };
|
|
291
|
+
return { kind: 'unknown', why: name + ' could not be followed' };
|
|
292
|
+
}
|
|
293
|
+
if (p.isMemberExpression() || p.isOptionalMemberExpression()) {
|
|
294
|
+
const prop = p.node.computed ? (t.isStringLiteral(p.node.property) ? p.node.property.value : null) : p.node.property.name;
|
|
295
|
+
if (!prop) return { kind: 'unknown', why: 'a property chosen at run time' };
|
|
296
|
+
const obj = resolveRef(ctx, mod, p.get('object'), depth + 1, seen);
|
|
297
|
+
if (obj.kind === 'pkg') return { kind: 'pkg', name: obj.name + '.' + prop, source: obj.source };
|
|
298
|
+
if (obj.kind === 'module') return fromModule(ctx, obj.mod, obj.spec || './', prop, depth, seen, prop, obj.target);
|
|
299
|
+
if (obj.kind === 'value' && obj.path.isObjectExpression()) return propertyOf(ctx, obj.mod, obj.path, prop, depth, seen);
|
|
300
|
+
if (obj.kind === 'value' && obj.path.isClassDeclaration()) {
|
|
301
|
+
const m = obj.path.get('body.body').find((q) => (q.isClassMethod() || q.isClassProperty()) && q.node.static && q.node.key && q.node.key.name === prop);
|
|
302
|
+
if (m) return m.isClassMethod() ? { kind: 'fn', path: m, mod: obj.mod } : resolveRef(ctx, obj.mod, m.get('value'), depth + 1, seen);
|
|
303
|
+
}
|
|
304
|
+
return { kind: 'unknown', why: 'could not follow ' + (memberChain(p.node) || [prop]).join('.') };
|
|
305
|
+
}
|
|
306
|
+
if (p.isCallExpression() && requireOf(t, p.node)) return fromModule(ctx, mod, requireOf(t, p.node), 'default', depth, seen);
|
|
307
|
+
if (p.isCallExpression()) {
|
|
308
|
+
const callee = resolveRef(ctx, mod, p.get('callee'), depth + 1, seen);
|
|
309
|
+
if (callee.kind === 'pkg') return { kind: 'pkg', name: callee.name, source: callee.source, call: p, mod };
|
|
310
|
+
if (callee.kind === 'fn') {
|
|
311
|
+
// a factory: allow('owner') returns the middleware; asyncRoute(fn) wraps one
|
|
312
|
+
const wrapped = wrappedFunction(ctx, mod, p, callee);
|
|
313
|
+
if (wrapped) return wrapped;
|
|
314
|
+
const ret = returnedFunction(ctx, callee.mod, callee.path, depth, seen);
|
|
315
|
+
// the factory is the function the returned one is written inside: its parameters are this call's arguments
|
|
316
|
+
if (ret && ret.factory && ret.path.getFunctionParent && ret.path.getFunctionParent() !== callee.path && ret.path.findParent((x) => x === callee.path) === null) return ret;
|
|
317
|
+
if (ret) return Object.assign(ret, { factory: { path: callee.path, mod: callee.mod, args: p.node.arguments.map((a) => (t.isStringLiteral(a) ? a.value : null)), callArgs: p.get('arguments'), callMod: mod } });
|
|
318
|
+
return { kind: 'unknown', why: 'the result of ' + calleeText(p) + '() could not be followed' };
|
|
319
|
+
}
|
|
320
|
+
return { kind: 'unknown', why: 'the result of ' + calleeText(p) + '() could not be followed' + (callee.why ? ' (' + callee.why + ')' : '') };
|
|
321
|
+
}
|
|
322
|
+
if (p.isObjectExpression() || p.isClassDeclaration() || p.isClassExpression() || p.isStringLiteral() || p.isTemplateLiteral() || p.isArrayExpression()) return { kind: 'value', path: p, mod };
|
|
323
|
+
if (p.isNewExpression()) return { kind: 'value', path: p, mod };
|
|
324
|
+
return { kind: 'unknown', why: 'a ' + p.node.type + ' could not be followed' };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** What a binding names, as a path resolveRef can follow: a declaration's value, an import's local name, a function. */
|
|
328
|
+
const bindingTarget = (b) => (b.path.isVariableDeclarator() ? b.path.get('init') : b.path.isImportSpecifier() || b.path.isImportDefaultSpecifier() || b.path.isImportNamespaceSpecifier() ? b.path.get('local') : b.path);
|
|
329
|
+
|
|
330
|
+
const calleeText = (p) => (memberChain(p.node.callee) || ['(call)']).join('.');
|
|
331
|
+
|
|
332
|
+
/** The module a require('x') names, or null. */
|
|
333
|
+
function requireOf(t, node) {
|
|
334
|
+
if (t.isCallExpression(node) && t.isIdentifier(node.callee, { name: 'require' }) && t.isStringLiteral(node.arguments[0])) return node.arguments[0].value;
|
|
335
|
+
if (t.isAwaitExpression(node)) return requireOf(t, node.argument);
|
|
336
|
+
if (t.isMemberExpression(node) && !node.computed && requireOf(t, node.object) && node.property.name === 'default') return requireOf(t, node.object);
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function fromModule(ctx, mod, spec, name, depth, seen, local, target) {
|
|
341
|
+
const abs = target || ctx.resolveModule(mod.abs, spec);
|
|
342
|
+
if (abs === null) {
|
|
343
|
+
if (name === 'default' || name === '*') return { kind: 'pkg', name: local || spec, source: spec };
|
|
344
|
+
return { kind: 'pkg', name: (local && local !== name ? local : spec.replace(/^.*\//, '') + '.' + name), source: spec, importedName: name };
|
|
345
|
+
}
|
|
346
|
+
if (abs === undefined) return { kind: 'unknown', why: 'the file ' + spec + ' is not there' };
|
|
347
|
+
const other = ctx.load(abs);
|
|
348
|
+
if (!other) return { kind: 'unknown', why: spec + ' could not be read' };
|
|
349
|
+
if (name === '*') return { kind: 'module', mod: other, target: abs, spec };
|
|
350
|
+
return exportOf(ctx, other, name, depth + 1, seen);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function exportOf(ctx, mod, name, depth, seen) {
|
|
354
|
+
if (depth > 12) return { kind: 'unknown', why: 'followed too far' };
|
|
355
|
+
if (name === 'default') {
|
|
356
|
+
if (mod.exportDefault) return resolveRef(ctx, mod, mod.exportDefault, depth + 1, seen);
|
|
357
|
+
if (mod.cjsExports) return resolveRef(ctx, mod, mod.cjsExports, depth + 1, seen);
|
|
358
|
+
if (mod.exportsNamed.size) return { kind: 'module', mod, target: mod.abs };
|
|
359
|
+
return { kind: 'unknown', why: mod.rel + ' exports nothing that could be followed' };
|
|
360
|
+
}
|
|
361
|
+
const e = mod.exportsNamed.get(name);
|
|
362
|
+
if (e && e.reexport) return fromModule(ctx, mod, e.reexport, e.name, depth, seen);
|
|
363
|
+
if (e && e.local) {
|
|
364
|
+
const b = mod.program.scope.getBinding(e.local);
|
|
365
|
+
if (b) return resolveRef(ctx, mod, bindingTarget(b), depth + 1, seen);
|
|
366
|
+
}
|
|
367
|
+
if (e) return resolveRef(ctx, mod, e, depth + 1, seen);
|
|
368
|
+
if (mod.cjsExports) {
|
|
369
|
+
const obj = resolveRef(ctx, mod, mod.cjsExports, depth + 1, seen);
|
|
370
|
+
if (obj.kind === 'value' && obj.path.isObjectExpression()) return propertyOf(ctx, obj.mod, obj.path, name, depth, seen);
|
|
371
|
+
}
|
|
372
|
+
return { kind: 'unknown', why: mod.rel + ' has no export named ' + name };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function propertyOf(ctx, mod, objPath, name, depth, seen) {
|
|
376
|
+
for (const prop of objPath.get('properties')) {
|
|
377
|
+
const key = prop.node.key && (prop.node.key.name || prop.node.key.value);
|
|
378
|
+
if (key !== name) continue;
|
|
379
|
+
if (prop.isObjectMethod()) return { kind: 'fn', path: prop, mod };
|
|
380
|
+
if (prop.isObjectProperty()) return resolveRef(ctx, mod, prop.get('value'), depth + 1, seen);
|
|
381
|
+
}
|
|
382
|
+
return { kind: 'unknown', why: 'no property ' + name };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** The function a factory returns: (...roles) => (req, res, next) => ... */
|
|
386
|
+
function returnedFunction(ctx, mod, fnPath, depth, seen) {
|
|
387
|
+
const body = fnPath.get('body');
|
|
388
|
+
if (!body.isBlockStatement()) {
|
|
389
|
+
const r = resolveRef(ctx, mod, body, depth + 1, seen);
|
|
390
|
+
return r.kind === 'fn' ? r : null;
|
|
391
|
+
}
|
|
392
|
+
let found = null;
|
|
393
|
+
body.traverse({
|
|
394
|
+
Function(q) {
|
|
395
|
+
q.skip();
|
|
396
|
+
},
|
|
397
|
+
ReturnStatement(q) {
|
|
398
|
+
if (found || !q.node.argument) return;
|
|
399
|
+
const r = resolveRef(ctx, mod, q.get('argument'), depth + 1, seen);
|
|
400
|
+
if (r.kind === 'fn') found = r;
|
|
401
|
+
},
|
|
402
|
+
});
|
|
403
|
+
return found;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** asyncRoute(async (req, res) => ...): the call wraps the function it is given. */
|
|
407
|
+
function wrappedFunction(ctx, mod, callPath, callee) {
|
|
408
|
+
const args = callPath.get('arguments');
|
|
409
|
+
if (args.length !== 1) return null;
|
|
410
|
+
const inner = resolveRef(ctx, mod, args[0]);
|
|
411
|
+
if (inner.kind !== 'fn') return null;
|
|
412
|
+
// the wrapper must call its parameter with the request: fn(req, res, next)
|
|
413
|
+
const params = callee.path.node.params;
|
|
414
|
+
if (!params.length || params[0].type !== 'Identifier') return null;
|
|
415
|
+
const pname = params[0].name;
|
|
416
|
+
let calls = false;
|
|
417
|
+
callee.path.traverse({
|
|
418
|
+
CallExpression(q) {
|
|
419
|
+
if (ctx.t.isIdentifier(q.node.callee, { name: pname })) calls = true;
|
|
420
|
+
},
|
|
421
|
+
});
|
|
422
|
+
return calls ? Object.assign({}, inner, { wrappedBy: { path: callee.path, mod: callee.mod } }) : null;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// --- express apps and routers -----------------------------------------------
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Every express app and router in the project, with what is registered on it
|
|
429
|
+
* in the order it is registered.
|
|
430
|
+
*/
|
|
431
|
+
function findContainers(ctx) {
|
|
432
|
+
const t = ctx.t;
|
|
433
|
+
const containers = [];
|
|
434
|
+
const byBinding = new Map();
|
|
435
|
+
const byNode = new Map();
|
|
436
|
+
ctx.containerOfBinding = (b) => byBinding.get(b) || null;
|
|
437
|
+
ctx.containerAt = (p) => byNode.get(p.node) || null;
|
|
438
|
+
|
|
439
|
+
const isExpressFactory = (mod, calleePath) => {
|
|
440
|
+
const r = resolveRef(ctx, mod, calleePath);
|
|
441
|
+
return r.kind === 'pkg' && packageName(r.source) === 'express' && (/^express$|^[A-Za-z_$]+$/.test(r.name) && !r.importedName ? 'app' : /(^|\.)Router$/.test(r.name) || r.importedName === 'Router' ? 'router' : null);
|
|
442
|
+
};
|
|
443
|
+
for (const mod of ctx.modules.values()) {
|
|
444
|
+
if (!mod) continue;
|
|
445
|
+
for (const call of mod.calls) {
|
|
446
|
+
const callee = call.get('callee');
|
|
447
|
+
if (!(callee.isIdentifier() || callee.isMemberExpression())) continue;
|
|
448
|
+
const chain = memberChain(callee.node);
|
|
449
|
+
if (!chain) continue;
|
|
450
|
+
const last = chain[chain.length - 1];
|
|
451
|
+
if (!(chain.length === 1 || last === 'Router')) continue;
|
|
452
|
+
const kind = isExpressFactory(mod, callee);
|
|
453
|
+
if (!kind) continue;
|
|
454
|
+
const c = { id: containers.length, kind, mod, line: call.node.loc.start.line, name: null, items: [], mounted: [] };
|
|
455
|
+
const parent = call.parentPath;
|
|
456
|
+
if (parent.isVariableDeclarator() && t.isIdentifier(parent.node.id)) {
|
|
457
|
+
c.name = parent.node.id.name;
|
|
458
|
+
const b = parent.scope.getBinding(c.name);
|
|
459
|
+
if (b) byBinding.set(b, c);
|
|
460
|
+
} else if (parent.isAssignmentExpression() && t.isIdentifier(parent.node.left)) {
|
|
461
|
+
c.name = parent.node.left.name;
|
|
462
|
+
const b = parent.scope.getBinding(c.name);
|
|
463
|
+
if (b) byBinding.set(b, c);
|
|
464
|
+
}
|
|
465
|
+
byNode.set(call.node, c);
|
|
466
|
+
containers.push(c);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
return containers;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** The container a call is made on (app.get -> app), following app.route('/x').get(...) chains. */
|
|
473
|
+
function registrationTarget(ctx, mod, calleePath) {
|
|
474
|
+
const obj = calleePath.get('object');
|
|
475
|
+
if (obj.isCallExpression() && obj.get('callee').isMemberExpression()) {
|
|
476
|
+
const prop = obj.node.callee.property.name;
|
|
477
|
+
if (prop === 'route') {
|
|
478
|
+
const target = registrationTarget(ctx, mod, obj.get('callee'));
|
|
479
|
+
return target && { container: target.container, routePath: obj.get('arguments')[0], via: 'route', param: target.param };
|
|
480
|
+
}
|
|
481
|
+
if (METHODS.includes(prop) || prop === 'all') {
|
|
482
|
+
const inner = registrationTarget(ctx, mod, obj.get('callee'));
|
|
483
|
+
if (inner && inner.via === 'route') return inner;
|
|
484
|
+
}
|
|
485
|
+
return null;
|
|
486
|
+
}
|
|
487
|
+
const r = resolveRef(ctx, mod, obj);
|
|
488
|
+
if (r.kind === 'container') return { container: r.container };
|
|
489
|
+
if (r.kind === 'unknown' && r.param) return { param: r.binding };
|
|
490
|
+
return null;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function collectRegistrations(ctx, containers) {
|
|
494
|
+
const t = ctx.t;
|
|
495
|
+
const pending = []; // registrations on a parameter: function(app) { app.get(...) }
|
|
496
|
+
for (const mod of ctx.modules.values()) {
|
|
497
|
+
if (!mod) continue;
|
|
498
|
+
for (const call of mod.calls) {
|
|
499
|
+
const callee = call.get('callee');
|
|
500
|
+
if (!callee.isMemberExpression() || callee.node.computed) continue;
|
|
501
|
+
const method = callee.node.property.name;
|
|
502
|
+
if (!(METHODS.includes(method) || method === 'use')) continue;
|
|
503
|
+
const target = registrationTarget(ctx, mod, callee);
|
|
504
|
+
if (!target) continue;
|
|
505
|
+
let args = call.get('arguments');
|
|
506
|
+
let routePath = null;
|
|
507
|
+
if (target.via === 'route') {
|
|
508
|
+
routePath = target.routePath;
|
|
509
|
+
} else if (method !== 'use') {
|
|
510
|
+
// app.get('name') with one text argument reads a setting
|
|
511
|
+
if (args.length < 2) continue;
|
|
512
|
+
routePath = args[0];
|
|
513
|
+
args = args.slice(1);
|
|
514
|
+
} else if (args.length && (args[0].isStringLiteral() || args[0].isTemplateLiteral() || args[0].isArrayExpression() || (args[0].isIdentifier() && isTextValue(ctx, mod, args[0])))) {
|
|
515
|
+
routePath = args[0];
|
|
516
|
+
args = args.slice(1);
|
|
517
|
+
}
|
|
518
|
+
const item = {
|
|
519
|
+
type: method === 'use' ? 'use' : 'route',
|
|
520
|
+
method: method === 'del' ? 'DELETE' : method.toUpperCase(),
|
|
521
|
+
path: routePath ? pathText(ctx, mod, routePath) : (method === 'use' ? { text: '/' } : { text: null }),
|
|
522
|
+
handlers: flattenHandlers(ctx, mod, args),
|
|
523
|
+
mod,
|
|
524
|
+
line: call.node.loc.start.line,
|
|
525
|
+
start: call.node.start,
|
|
526
|
+
};
|
|
527
|
+
if (target.container) target.container.items.push(item);
|
|
528
|
+
else if (target.param) pending.push({ item, binding: target.param });
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
// function registerRoutes(app) { app.get(...) } called as registerRoutes(app)
|
|
532
|
+
for (const pend of pending) {
|
|
533
|
+
const fnPath = pend.binding.path.getFunctionParent ? pend.binding.path.getFunctionParent() : null;
|
|
534
|
+
const fn = pend.binding.path.parentPath && pend.binding.path.parentPath.isFunction() ? pend.binding.path.parentPath : pend.binding.scope.path;
|
|
535
|
+
const index = fn && fn.node.params ? fn.node.params.findIndex((q) => q.type === 'Identifier' && q.name === pend.binding.identifier.name) : -1;
|
|
536
|
+
let attached = false;
|
|
537
|
+
if (index >= 0) {
|
|
538
|
+
for (const mod of ctx.modules.values()) {
|
|
539
|
+
if (!mod) continue;
|
|
540
|
+
for (const call of mod.calls) {
|
|
541
|
+
const r = resolveRef(ctx, mod, call.get('callee'));
|
|
542
|
+
if (r.kind !== 'fn' || r.path.node !== fn.node) continue;
|
|
543
|
+
const arg = call.get('arguments')[index];
|
|
544
|
+
const a = arg && resolveRef(ctx, mod, arg);
|
|
545
|
+
if (a && a.kind === 'container') {
|
|
546
|
+
a.container.items.push(Object.assign({}, pend.item, { order: { mod, start: call.node.start, line: call.node.loc.start.line } }));
|
|
547
|
+
attached = true;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
if (!attached && !pend.item.mod.otherFramework && !hasFrameworkType(pend.binding)) {
|
|
553
|
+
ctx.notRead.push({ file: pend.item.mod.rel, line: pend.item.line, what: 'a route registered on a parameter (' + pend.binding.identifier.name + ') whose app or router could not be found', pattern: 'registration-on-parameter' });
|
|
554
|
+
}
|
|
555
|
+
void fnPath;
|
|
556
|
+
}
|
|
557
|
+
for (const c of containers) {
|
|
558
|
+
// the order express runs them: by where they are registered, a call site standing for what it registers
|
|
559
|
+
c.items.sort((a, b) => orderOf(c, a) - orderOf(c, b) || (a.order ? a.start - b.start : 0));
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/** A parameter typed as another framework's app (app: FastifyInstance) is that framework's, not express's. */
|
|
564
|
+
function hasFrameworkType(binding) {
|
|
565
|
+
const ann = binding.identifier.typeAnnotation;
|
|
566
|
+
const text = ann && ann.typeAnnotation && ann.typeAnnotation.typeName ? (ann.typeAnnotation.typeName.name || '') : '';
|
|
567
|
+
return /^(Fastify\w*|Koa|Hono)$/.test(text);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
function orderOf(c, item) {
|
|
571
|
+
const o = item.order || item;
|
|
572
|
+
return o.mod === c.mod ? o.start : Number.MAX_SAFE_INTEGER / 2 + o.start;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** Whether an identifier holds a fixed text: const PREFIX = '/api'. */
|
|
576
|
+
function isTextValue(ctx, mod, p) {
|
|
577
|
+
const r = resolveRef(ctx, mod, p);
|
|
578
|
+
return r.kind === 'value' && (r.path.isStringLiteral() || r.path.isTemplateLiteral());
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/** A route path as text: '/api/x', `${BASE}/x` with BASE fixed, or { text: null, why }. */
|
|
582
|
+
function pathText(ctx, mod, p) {
|
|
583
|
+
p = unwrapTs(p);
|
|
584
|
+
if (p.isStringLiteral()) return { text: p.node.value };
|
|
585
|
+
if (p.isTemplateLiteral()) {
|
|
586
|
+
let out = '';
|
|
587
|
+
const quasis = p.node.quasis;
|
|
588
|
+
const exprs = p.get('expressions');
|
|
589
|
+
for (let i = 0; i < quasis.length; i++) {
|
|
590
|
+
out += quasis[i].value.cooked;
|
|
591
|
+
if (i < exprs.length) {
|
|
592
|
+
const v = pathText(ctx, mod, exprs[i]);
|
|
593
|
+
if (v.text === null) return { text: null, why: 'part of the path is chosen at run time' };
|
|
594
|
+
out += v.text;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
return { text: out };
|
|
598
|
+
}
|
|
599
|
+
if (p.isIdentifier() || p.isMemberExpression()) {
|
|
600
|
+
const r = resolveRef(ctx, mod, p);
|
|
601
|
+
if (r.kind === 'value' && (r.path.isStringLiteral() || r.path.isTemplateLiteral())) return pathText(ctx, r.mod, r.path);
|
|
602
|
+
return { text: null, why: 'the path is the value of ' + (memberChain(p.node) || ['?']).join('.') + ', which could not be read' };
|
|
603
|
+
}
|
|
604
|
+
if (p.isArrayExpression()) {
|
|
605
|
+
const parts = p.get('elements').map((e) => pathText(ctx, mod, e));
|
|
606
|
+
if (parts.every((x) => x.text !== null)) return { text: parts[0].text, also: parts.slice(1).map((x) => x.text) };
|
|
607
|
+
return { text: null, why: 'a list of paths that could not all be read' };
|
|
608
|
+
}
|
|
609
|
+
if (p.isRegExpLiteral()) return { text: null, why: 'the path is a pattern (' + p.node.pattern + ')', regex: true };
|
|
610
|
+
return { text: null, why: 'the path is a ' + p.node.type };
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
function flattenHandlers(ctx, mod, args) {
|
|
614
|
+
const out = [];
|
|
615
|
+
for (const a of args) {
|
|
616
|
+
const u = unwrapTs(a);
|
|
617
|
+
if (u.isArrayExpression()) {
|
|
618
|
+
out.push(...flattenHandlers(ctx, mod, u.get('elements')));
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
if (u.isSpreadElement()) {
|
|
622
|
+
out.push({ ref: { kind: 'unknown', why: 'a spread list of handlers' }, mod, line: u.node.loc.start.line, text: '...' });
|
|
623
|
+
continue;
|
|
624
|
+
}
|
|
625
|
+
out.push({ ref: resolveRef(ctx, mod, u), mod, line: u.node.loc.start.line, text: refText(u) });
|
|
626
|
+
}
|
|
627
|
+
return out;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function refText(p) {
|
|
631
|
+
const n = p.node;
|
|
632
|
+
if (p.isFunction()) return n.id ? n.id.name : '(inline function)';
|
|
633
|
+
if (p.isCallExpression()) {
|
|
634
|
+
const chain = memberChain(n.callee);
|
|
635
|
+
const args = n.arguments.map((a) => (a.type === 'StringLiteral' ? "'" + a.value + "'" : a.type === 'Identifier' ? a.name : a.type === 'ArrowFunctionExpression' || a.type === 'FunctionExpression' ? 'fn' : '...'));
|
|
636
|
+
return (chain ? chain.join('.') : '(call)') + '(' + args.join(', ') + ')';
|
|
637
|
+
}
|
|
638
|
+
const chain = memberChain(n);
|
|
639
|
+
return chain ? chain.join('.') : '(' + n.type + ')';
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/** '/api' + '/x/' -> '/api/x' */
|
|
643
|
+
function joinPath(a, b) {
|
|
644
|
+
const x = (a || '').replace(/\/+$/, '');
|
|
645
|
+
const y = (b || '/').startsWith('/') ? b || '/' : '/' + b;
|
|
646
|
+
const out = (x + (y === '/' ? '' : y)) || '/';
|
|
647
|
+
return out.replace(/\/{2,}/g, '/');
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** Whether middleware used at `prefix` runs for a request to `full`. */
|
|
651
|
+
function covers(prefix, full) {
|
|
652
|
+
if (!prefix || prefix === '/') return true;
|
|
653
|
+
const p = prefix.replace(/\/+$/, '');
|
|
654
|
+
return full === p || full.startsWith(p + '/');
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* Walks the apps from the top: every route with its full path, and the
|
|
659
|
+
* middleware that runs before it, in order. Routers mounted with use() are
|
|
660
|
+
* walked under their prefix, carrying what was used before them.
|
|
661
|
+
*/
|
|
662
|
+
function flatten(ctx, containers) {
|
|
663
|
+
const routes = [];
|
|
664
|
+
const mountedIds = new Set();
|
|
665
|
+
// which containers are mounted where
|
|
666
|
+
for (const c of containers) {
|
|
667
|
+
for (const item of c.items) {
|
|
668
|
+
if (item.type !== 'use') continue;
|
|
669
|
+
for (const h of item.handlers) if (h.ref.kind === 'container' && h.ref.container !== c) {
|
|
670
|
+
mountedIds.add(h.ref.container.id);
|
|
671
|
+
h.ref.container.mounted.push({ into: c, item });
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
const roots = containers.filter((c) => c.kind === 'app' && !mountedIds.has(c.id));
|
|
676
|
+
const walk = (c, prefix, inherited, stack) => {
|
|
677
|
+
if (stack.includes(c.id)) return;
|
|
678
|
+
const active = inherited.slice();
|
|
679
|
+
for (const item of c.items) {
|
|
680
|
+
const here = item.path.text === null ? null : joinPath(prefix, item.path.text);
|
|
681
|
+
if (item.type === 'use') {
|
|
682
|
+
const subs = item.handlers.filter((h) => h.ref.kind === 'container');
|
|
683
|
+
const fns = item.handlers.filter((h) => h.ref.kind !== 'container');
|
|
684
|
+
if (here === null) {
|
|
685
|
+
ctx.notRead.push({ file: item.mod.rel, line: item.line, what: 'use() with a path that could not be read (' + item.path.why + ') - what it guards is unknown', pattern: 'use-path' });
|
|
686
|
+
for (const f of fns) active.push({ prefix: '/', handler: f, unknownPath: true, from: item });
|
|
687
|
+
} else {
|
|
688
|
+
for (const f of fns) active.push({ prefix: here, handler: f, from: item });
|
|
689
|
+
}
|
|
690
|
+
for (const s of subs) walk(s.ref.container, here === null ? prefix : here, active.slice(), stack.concat(c.id));
|
|
691
|
+
continue;
|
|
692
|
+
}
|
|
693
|
+
const paths = here === null ? [null] : [here].concat((item.path.also || []).map((x) => joinPath(prefix, x)));
|
|
694
|
+
for (const full of paths) {
|
|
695
|
+
// a path that could not be read: only what runs for every path is known to be in front of it
|
|
696
|
+
const chain = active.filter((m) => m.unknownPath || (full === null ? !m.prefix || m.prefix === '/' : covers(m.prefix, full))).map((m) => Object.assign({ inherited: true }, m.handler, { usedAt: m.from }));
|
|
697
|
+
const maybe = full === null ? active.filter((m) => m.prefix && m.prefix !== '/').map((m) => m.handler.text + ' (used at ' + m.prefix + ')') : [];
|
|
698
|
+
routes.push({
|
|
699
|
+
method: item.method === 'ALL' ? 'ALL' : item.method,
|
|
700
|
+
path: full,
|
|
701
|
+
pathWhy: full === null ? item.path.why : null,
|
|
702
|
+
file: item.mod.rel,
|
|
703
|
+
line: item.line,
|
|
704
|
+
container: c,
|
|
705
|
+
chain: chain.concat(item.handlers.map((h) => Object.assign({ inherited: false }, h))),
|
|
706
|
+
crossFileOrder: !!(item.order && item.order.mod !== c.mod) || item.mod !== c.mod,
|
|
707
|
+
maybe,
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
for (const r of roots) walk(r, '', [], []);
|
|
713
|
+
// routers nobody mounts: their routes are listed, and said to be unreachable as far as the code shows
|
|
714
|
+
const unmounted = [];
|
|
715
|
+
for (const c of containers) {
|
|
716
|
+
if (c.kind === 'router' && !mountedIds.has(c.id) && c.items.some((i) => i.type === 'route')) {
|
|
717
|
+
unmounted.push(c);
|
|
718
|
+
ctx.notRead.push({ file: c.mod.rel, line: c.line, what: 'a router' + (c.name ? ' (' + c.name + ')' : '') + ' with ' + c.items.filter((i) => i.type === 'route').length + ' route(s) that no app mounts in the code read - its routes are listed under "not mounted"', pattern: 'router-not-mounted' });
|
|
719
|
+
const before = routes.length;
|
|
720
|
+
walk(c, '', [], []);
|
|
721
|
+
for (let i = before; i < routes.length; i++) routes[i].unmounted = true;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
return routes;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
// --- guards -------------------------------------------------------------------
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* What one function in front of a route checks, read from its code:
|
|
731
|
+
* { auth, role, apiKey, signature: evidence | null, partial: [...], blocks: bool }
|
|
732
|
+
* evidence = { file, line, code, how }
|
|
733
|
+
*/
|
|
734
|
+
function readGuardFn(ctx, ref, opts = {}) {
|
|
735
|
+
const t = ctx.t;
|
|
736
|
+
const fn = ref.path;
|
|
737
|
+
const mod = ref.mod;
|
|
738
|
+
const out = { auth: null, role: null, apiKey: null, signature: null, signatureSkippable: false, partial: [], rejects: false };
|
|
739
|
+
const params = fn.node.params;
|
|
740
|
+
const reqName = opts.asHelper ? opts.reqName : params[0] && params[0].type === 'Identifier' ? params[0].name : null;
|
|
741
|
+
const resName = opts.asHelper ? opts.resName : params[1] && params[1].type === 'Identifier' ? params[1].name : null;
|
|
742
|
+
const nextName = opts.asHelper ? null : params[2] && params[2].type === 'Identifier' ? params[2].name : null;
|
|
743
|
+
const roleList = ref.factory ? ref.factory.args.filter((x) => typeof x === 'string') : [];
|
|
744
|
+
const factoryParams = ref.factory ? ref.factory.path.node.params.map((q) => (q.type === 'RestElement' ? q.argument.name : q.name)) : [];
|
|
745
|
+
// local names that hold the signed-in person: const user = req.session.user / await currentUser(req) / rows[0] of a lookup by the session id
|
|
746
|
+
const identityLocals = new Set();
|
|
747
|
+
const roleLocals = new Set();
|
|
748
|
+
const sigHeaderLocals = new Set();
|
|
749
|
+
const computedLocals = new Set();
|
|
750
|
+
const verifyLocals = new Set();
|
|
751
|
+
const apiKeyLocals = new Set();
|
|
752
|
+
const isReq = (n) => reqName && t.isIdentifier(n, { name: reqName });
|
|
753
|
+
|
|
754
|
+
const refersTo = (node, test) => {
|
|
755
|
+
let hit = false;
|
|
756
|
+
const visit = (n) => {
|
|
757
|
+
if (!n || hit || typeof n !== 'object') return;
|
|
758
|
+
if (Array.isArray(n)) return n.forEach(visit);
|
|
759
|
+
if (test(n)) {
|
|
760
|
+
hit = true;
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
if (n.type === 'ArrowFunctionExpression' || n.type === 'FunctionExpression') return;
|
|
764
|
+
for (const k of Object.keys(n)) if (k !== 'loc' && k !== 'start' && k !== 'end' && k !== 'leadingComments' && k !== 'trailingComments' && k !== 'extra') visit(n[k]);
|
|
765
|
+
};
|
|
766
|
+
visit(node);
|
|
767
|
+
return hit;
|
|
768
|
+
};
|
|
769
|
+
const helperReturns = (callNode, test) => {
|
|
770
|
+
// role(req) where const role = req => req.session.user?.role
|
|
771
|
+
if (!t.isIdentifier(callNode.callee)) return false;
|
|
772
|
+
const b = fn.scope.getBinding(callNode.callee.name);
|
|
773
|
+
if (!b) return false;
|
|
774
|
+
const r = resolveRef(ctx, mod, bindingTarget(b));
|
|
775
|
+
if (r.kind !== 'fn') return false;
|
|
776
|
+
const body = r.path.node.body;
|
|
777
|
+
return refersTo(body, test);
|
|
778
|
+
};
|
|
779
|
+
const identityChain = (n) => {
|
|
780
|
+
const chain = memberChain(n);
|
|
781
|
+
if (!chain) return false;
|
|
782
|
+
if (reqName && chain[0] === reqName && chain.length > 1 && IDENTITY_SEGS.test(chain[1])) return true;
|
|
783
|
+
if (chain[0] === 'res' && chain[1] === 'locals' && chain[2] && IDENTITY_SEGS.test(chain[2])) return true;
|
|
784
|
+
if (identityLocals.has(chain[0])) return true;
|
|
785
|
+
return false;
|
|
786
|
+
};
|
|
787
|
+
const isIdentityNode = (n) => {
|
|
788
|
+
if (n.type === 'MemberExpression' || n.type === 'OptionalMemberExpression') return identityChain(n);
|
|
789
|
+
if (n.type === 'Identifier') return identityLocals.has(n.name);
|
|
790
|
+
if (n.type === 'CallExpression' || n.type === 'OptionalCallExpression') {
|
|
791
|
+
const chain = memberChain(n.callee);
|
|
792
|
+
if (chain && reqName && chain[0] === reqName && /^(isAuthenticated|isLoggedIn|isUnauthenticated)$/.test(chain[chain.length - 1])) return true;
|
|
793
|
+
if (n.arguments.some((a) => isReq(a)) && helperReturns(n, (x) => (x.type === 'MemberExpression' || x.type === 'OptionalMemberExpression') && (() => { const c = memberChain(x); return c && c.length > 1 && IDENTITY_SEGS.test(c[1]); })())) return true;
|
|
794
|
+
}
|
|
795
|
+
return false;
|
|
796
|
+
};
|
|
797
|
+
const isRoleNode = (n) => {
|
|
798
|
+
if (n.type === 'MemberExpression' || n.type === 'OptionalMemberExpression') {
|
|
799
|
+
const chain = memberChain(n);
|
|
800
|
+
if (chain && ROLE_SEGS.test(chain[chain.length - 1]) && (identityChain(n.object) || identityLocals.has(chain[0]))) return true;
|
|
801
|
+
}
|
|
802
|
+
if (n.type === 'Identifier' && roleLocals.has(n.name)) return true;
|
|
803
|
+
if (n.type === 'CallExpression' || n.type === 'OptionalCallExpression') {
|
|
804
|
+
if (n.arguments.some((a) => isReq(a)) && helperReturns(n, (x) => (x.type === 'MemberExpression' || x.type === 'OptionalMemberExpression') && ROLE_SEGS.test((memberChain(x) || ['']).slice(-1)[0]))) return true;
|
|
805
|
+
// roles.includes(...) where roles is the factory's list
|
|
806
|
+
const chain = memberChain(n.callee);
|
|
807
|
+
if (chain && chain.length === 2 && factoryParams.includes(chain[0]) && /^(includes|indexOf|some|has)$/.test(chain[1])) return true;
|
|
808
|
+
}
|
|
809
|
+
return false;
|
|
810
|
+
};
|
|
811
|
+
// what a helper of the app does: 'verifies' (compares a signature), 'computes' (makes one), or null
|
|
812
|
+
const helperKind = (name, depth = 0) => {
|
|
813
|
+
if (depth > 2) return null;
|
|
814
|
+
const b = fn.scope.getBinding(name);
|
|
815
|
+
if (!b) return null;
|
|
816
|
+
const r = resolveRef(ctx, mod, bindingTarget(b));
|
|
817
|
+
if (r.kind !== 'fn') return null;
|
|
818
|
+
const body = r.path.node.body;
|
|
819
|
+
const calls = (re) => refersTo(body, (x) => x.type === 'CallExpression' && (re.test((memberChain(x.callee) || ['']).slice(-1)[0]) ||
|
|
820
|
+
(t.isIdentifier(x.callee) && x.callee.name !== name && helperKind(x.callee.name, depth + 1) === (re === VERIFIES ? 'verifies' : 'computes'))));
|
|
821
|
+
if (calls(VERIFIES)) return 'verifies';
|
|
822
|
+
if (calls(COMPUTES)) return 'computes';
|
|
823
|
+
return null;
|
|
824
|
+
};
|
|
825
|
+
const VERIFIES = /^(timingSafeEqual|validateWebhookSignature|constructEvent|constructEventAsync|verifyWebhook|verifySignature|validateSignature|verifyHeader)$/;
|
|
826
|
+
const COMPUTES = /^(createHmac|digest|sign)$/;
|
|
827
|
+
// a function of the app's that builds an error answer from a status it is given: reply(status, body)
|
|
828
|
+
const buildsResponse = (name) => {
|
|
829
|
+
const b = fn.scope.getBinding(name);
|
|
830
|
+
if (!b) return false;
|
|
831
|
+
const r = resolveRef(ctx, mod, bindingTarget(b));
|
|
832
|
+
if (r.kind !== 'fn') return false;
|
|
833
|
+
return refersTo(r.path.node.body, (x) => (x.type === 'NewExpression' && x.callee.type === 'Identifier' && /^(Response|NextResponse)$/.test(x.callee.name)) ||
|
|
834
|
+
(x.type === 'CallExpression' && /^(Response|NextResponse)$/.test(((memberChain(x.callee) || [])[0]) || '') && calledName(x) === 'json'));
|
|
835
|
+
};
|
|
836
|
+
const isSigHeader = (n) => {
|
|
837
|
+
if (n.type === 'Identifier' && sigHeaderLocals.has(n.name)) return true;
|
|
838
|
+
const h = headerName(n);
|
|
839
|
+
return !!(h && /signature|x-hub|svix|webhook-sign/i.test(h));
|
|
840
|
+
};
|
|
841
|
+
const isComputed = (n) => {
|
|
842
|
+
if (n.type === 'Identifier' && computedLocals.has(n.name)) return true;
|
|
843
|
+
if (n.type === 'CallExpression' || n.type === 'OptionalCallExpression') {
|
|
844
|
+
const last = (memberChain(n.callee) || ['']).slice(-1)[0];
|
|
845
|
+
if (COMPUTES.test(last)) return true;
|
|
846
|
+
if (t.isIdentifier(n.callee) && helperKind(n.callee.name) === 'computes') return true;
|
|
847
|
+
}
|
|
848
|
+
return false;
|
|
849
|
+
};
|
|
850
|
+
const isVerify = (n) => {
|
|
851
|
+
if (n.type === 'Identifier' && verifyLocals.has(n.name)) return true;
|
|
852
|
+
if (n.type === 'CallExpression' || n.type === 'OptionalCallExpression') {
|
|
853
|
+
const chain = memberChain(n.callee) || [];
|
|
854
|
+
const last = chain[chain.length - 1] || '';
|
|
855
|
+
if (VERIFIES.test(last)) return true;
|
|
856
|
+
if (last === 'verify' && chain.length > 1 && /webhook|signature|hmac|svix/i.test(chain.join('.'))) return true;
|
|
857
|
+
if (chain.length === 1 && helperKind(last) === 'verifies') return true;
|
|
858
|
+
}
|
|
859
|
+
// sameText(signature, await sign(secret, body)): a compare of the app's own, given what was sent and what the secret makes
|
|
860
|
+
if ((n.type === 'CallExpression' || n.type === 'OptionalCallExpression') && n.arguments.length >= 2 &&
|
|
861
|
+
n.arguments.some((a) => refersTo(a, isSigHeader)) && n.arguments.some((a) => refersTo(a, isComputed))) return true;
|
|
862
|
+
// signature === expected: what was sent against what the secret makes
|
|
863
|
+
if (n.type === 'BinaryExpression' && /^[!=]==?$/.test(n.operator)) {
|
|
864
|
+
const l = refersTo(n.left, isSigHeader), r = refersTo(n.right, isSigHeader);
|
|
865
|
+
const lc = refersTo(n.left, isComputed), rc = refersTo(n.right, isComputed);
|
|
866
|
+
if ((l && rc) || (r && lc)) return true;
|
|
867
|
+
}
|
|
868
|
+
return false;
|
|
869
|
+
};
|
|
870
|
+
const isSigNode = (n) => isVerify(n) || isSigHeader(n);
|
|
871
|
+
const isApiKeyNode = (n) => {
|
|
872
|
+
if (n.type === 'Identifier' && apiKeyLocals.has(n.name)) return true;
|
|
873
|
+
const h = headerName(n);
|
|
874
|
+
return !!(h && (APIKEY_HEADER.test(h) || /^authorization$/i.test(h)));
|
|
875
|
+
};
|
|
876
|
+
function headerName(n) {
|
|
877
|
+
// req.get('x-api-key') / req.header('x') / req.headers['x-api-key'] / req.headers.authorization
|
|
878
|
+
if ((n.type === 'CallExpression' || n.type === 'OptionalCallExpression') && n.arguments[0] && n.arguments[0].type === 'StringLiteral') {
|
|
879
|
+
const chain = memberChain(n.callee);
|
|
880
|
+
if (chain && reqName && chain[0] === reqName && /^(get|header)$/.test(chain[chain.length - 1])) return n.arguments[0].value;
|
|
881
|
+
if (chain && chain.slice(-2).join('.') === 'headers.get') return n.arguments[0].value;
|
|
882
|
+
}
|
|
883
|
+
if (n.type === 'MemberExpression' || n.type === 'OptionalMemberExpression') {
|
|
884
|
+
const chain = memberChain(n);
|
|
885
|
+
if (chain && reqName && chain[0] === reqName && chain[1] === 'headers' && chain[2]) return chain[2];
|
|
886
|
+
}
|
|
887
|
+
return null;
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// first pass: local names
|
|
891
|
+
const readsClient = reqName && refersTo(fn.node.body, (x) => {
|
|
892
|
+
const c = (x.type === 'MemberExpression' || x.type === 'OptionalMemberExpression') && memberChain(x);
|
|
893
|
+
return !!(c && c[0] === reqName && /^(body|query|params)$/.test(c[1] || ''));
|
|
894
|
+
});
|
|
895
|
+
// a local that mixes a role with something else (owner || instructor || enrolled) is a partial check
|
|
896
|
+
const roleMixedLocals = new Set();
|
|
897
|
+
const errorLocals = new Set();
|
|
898
|
+
const learn = (id, init) => {
|
|
899
|
+
const names = patternNames(id);
|
|
900
|
+
for (const name of names) {
|
|
901
|
+
if (refersTo(init, isVerify)) verifyLocals.add(name);
|
|
902
|
+
else if (refersTo(init, isComputed)) computedLocals.add(name);
|
|
903
|
+
else if (refersTo(init, isSigHeader)) sigHeaderLocals.add(name);
|
|
904
|
+
if (refersTo(init, (x) => isApiKeyNode(x))) apiKeyLocals.add(name);
|
|
905
|
+
if (refersTo(init, (x) => isRoleNode(x))) {
|
|
906
|
+
const terms = [];
|
|
907
|
+
const split = (n) => (n.type === 'LogicalExpression' ? (split(n.left), split(n.right)) : terms.push(n));
|
|
908
|
+
split(init.type === 'AwaitExpression' ? init.argument : init);
|
|
909
|
+
const bare = (x) => isIdentityNode(x.type === 'UnaryExpression' ? x.argument : x);
|
|
910
|
+
if (terms.length > 1 && terms.some((x) => !refersTo(x, isRoleNode) && !bare(x))) roleMixedLocals.add(name);
|
|
911
|
+
else roleLocals.add(name);
|
|
912
|
+
}
|
|
913
|
+
// const { data: { user }, error } = await supabase.auth.getUser(token): the person, or the reason there is none
|
|
914
|
+
// const userId = jwt ? await deps.userIdFrom(jwt) : null: an injected lookup of who is calling, named as one
|
|
915
|
+
else if (IDENTITY_LOOKUP_LOCAL.test(name) && refersTo(init, (x) => (x.type === 'CallExpression' || x.type === 'OptionalCallExpression') && IDENTITY_LOOKUP_CALL.test(calledName(x)))) identityLocals.add(name);
|
|
916
|
+
// const token = bearer(request): a helper that reads the token the request carries
|
|
917
|
+
else if (TOKEN_LOCAL.test(name) && refersTo(init, (x) => x.type === 'CallExpression' && /bearer|token|apikey|authheader|authorization/i.test(calledName(x)) && x.arguments.some((a) => isReq(a)))) apiKeyLocals.add(name);
|
|
918
|
+
else if (refersTo(init, isSessionLookup)) {
|
|
919
|
+
if (/^(error|err|authError|userError|e)$/i.test(name)) errorLocals.add(name);
|
|
920
|
+
identityLocals.add(name);
|
|
921
|
+
}
|
|
922
|
+
else if (refersTo(init, (x) => isIdentityNode(x)) || (IDENTITY_NAMES.test(name) && !readsClient && refersTo(init, (x) => (x.type === 'MemberExpression' || x.type === 'Identifier') && /^(rows|user|users|data|result|session)$/.test(x.type === 'Identifier' ? x.name : (memberChain(x) || [''])[0])))) identityLocals.add(name);
|
|
923
|
+
}
|
|
924
|
+
};
|
|
925
|
+
fn.traverse({
|
|
926
|
+
VariableDeclarator(q) {
|
|
927
|
+
if (q.node.init) learn(q.node.id, q.node.init);
|
|
928
|
+
},
|
|
929
|
+
AssignmentExpression(q) {
|
|
930
|
+
if (t.isIdentifier(q.node.left) && q.node.operator === '=') learn(q.node.left, q.node.right);
|
|
931
|
+
},
|
|
932
|
+
});
|
|
933
|
+
|
|
934
|
+
// second pass: every place that turns the request away
|
|
935
|
+
const responds = (node) => refersTo(node, (x) => {
|
|
936
|
+
if (x.type === 'ThrowStatement') return true;
|
|
937
|
+
// a Fetch-style answer (an edge function, a Next route): new Response(..., { status: 401 }) / Response.json(..., { status: 403 })
|
|
938
|
+
if (isErrorResponse(x)) return true;
|
|
939
|
+
// reply(401, {...}): a helper of the app that builds an error Response from its first argument
|
|
940
|
+
if (x.type === 'CallExpression' && t.isIdentifier(x.callee) && x.arguments[0] && x.arguments[0].type === 'NumericLiteral' && x.arguments[0].value >= 400 && buildsResponse(x.callee.name)) return true;
|
|
941
|
+
if (x.type !== 'CallExpression' && x.type !== 'OptionalCallExpression') return false;
|
|
942
|
+
const chain = memberChain(x.callee);
|
|
943
|
+
if (chain && resName && chain[0] === resName) return /^(status|sendStatus|redirect|json|send|end|render|type|set|writeHead)$/.test(chain[1] || '');
|
|
944
|
+
// res.status(401).json(...) - the callee's object is itself a call on res
|
|
945
|
+
let c = x.callee;
|
|
946
|
+
while (c && (c.type === 'MemberExpression' || c.type === 'OptionalMemberExpression')) c = c.object;
|
|
947
|
+
if (c && (c.type === 'CallExpression' || c.type === 'OptionalCallExpression')) {
|
|
948
|
+
const inner = memberChain(c.callee);
|
|
949
|
+
if (inner && resName && inner[0] === resName) return true;
|
|
950
|
+
}
|
|
951
|
+
if (nextName && t.isIdentifier(x.callee, { name: nextName }) && x.arguments.length) return true;
|
|
952
|
+
if (t.isIdentifier(x.callee) && /^(reject|deny|forbid|unauthori[sz]ed|forbidden|notFound|fail)$/i.test(x.callee.name)) return true;
|
|
953
|
+
return false;
|
|
954
|
+
});
|
|
955
|
+
const passes = (node) => !node || refersTo(node, (x) => (x.type === 'CallExpression' && nextName && t.isIdentifier(x.callee, { name: nextName }) && !x.arguments.length)) || !responds(node);
|
|
956
|
+
|
|
957
|
+
const polarity = (n, isX) => {
|
|
958
|
+
if (!n) return 0;
|
|
959
|
+
if (n.type === 'UnaryExpression' && n.operator === '!') return -polarity(n.argument, isX);
|
|
960
|
+
if (n.type === 'TSNonNullExpression' || n.type === 'ParenthesizedExpression' || n.type === 'AwaitExpression') return polarity(n.expression || n.argument, isX);
|
|
961
|
+
if (n.type === 'BinaryExpression' && /^[!=]==?$/.test(n.operator)) {
|
|
962
|
+
const neg = n.operator[0] === '!';
|
|
963
|
+
const nullish = (x) => x.type === 'NullLiteral' || (x.type === 'Identifier' && x.name === 'undefined');
|
|
964
|
+
if (nullish(n.right) || nullish(n.left)) return (neg ? 1 : -1) * Math.abs(polarity(nullish(n.right) ? n.left : n.right, isX) || 1);
|
|
965
|
+
if (n.right.type === 'UnaryExpression' && n.right.operator === '-') return neg ? 1 : -1; // indexOf(x) === -1
|
|
966
|
+
return neg ? -1 : 1;
|
|
967
|
+
}
|
|
968
|
+
if (n.type === 'BinaryExpression' && /^[<>]=?$/.test(n.operator)) return 0;
|
|
969
|
+
if (n.type === 'CallExpression' || n.type === 'OptionalCallExpression' || n.type === 'MemberExpression' || n.type === 'OptionalMemberExpression' || n.type === 'Identifier') return 1;
|
|
970
|
+
return 0;
|
|
971
|
+
};
|
|
972
|
+
const consider = (testNode, rejectWhenTrue, at) => {
|
|
973
|
+
// the test, read as "turn away when": split into its || parts (for a true-rejection) or && parts (false-rejection)
|
|
974
|
+
const parts = [];
|
|
975
|
+
const split = (n, op) => {
|
|
976
|
+
if (n.type === 'LogicalExpression' && n.operator === op) {
|
|
977
|
+
split(n.left, op);
|
|
978
|
+
split(n.right, op);
|
|
979
|
+
} else parts.push(n);
|
|
980
|
+
};
|
|
981
|
+
split(testNode, rejectWhenTrue ? '||' : '&&');
|
|
982
|
+
const line = at.loc.start.line;
|
|
983
|
+
const ev = (how) => ({ file: mod.rel, line, code: snippet(mod, line), how });
|
|
984
|
+
let anyIdentity = false;
|
|
985
|
+
let anyRole = false;
|
|
986
|
+
let anyOther = false;
|
|
987
|
+
let sig = false;
|
|
988
|
+
let sigSkippable = false;
|
|
989
|
+
let apiKey = false;
|
|
990
|
+
for (const part of parts) {
|
|
991
|
+
const id = refersTo(part, isIdentityNode);
|
|
992
|
+
const role = refersTo(part, isRoleNode);
|
|
993
|
+
const s = refersTo(part, isVerify);
|
|
994
|
+
const present = !s && refersTo(part, isSigHeader);
|
|
995
|
+
const k = refersTo(part, isApiKeyNode);
|
|
996
|
+
// a part that also asks about something else (a record's owner, a body field) makes the check depend on it
|
|
997
|
+
const mixed = part.type === 'LogicalExpression' && part.operator === (rejectWhenTrue ? '&&' : '||');
|
|
998
|
+
if (s) {
|
|
999
|
+
sig = true;
|
|
1000
|
+
// if (signature && !valid(...)) reject - a request without the header walks past
|
|
1001
|
+
if (mixed && [part.left, part.right].some((side) => refersTo(side, isSigHeader) && !refersTo(side, isVerify))) sigSkippable = true;
|
|
1002
|
+
} else if (present) {
|
|
1003
|
+
out.sigPresenceOnly = out.sigPresenceOnly || ev('checks only that a signature header is there - never that it matches');
|
|
1004
|
+
}
|
|
1005
|
+
if (k) apiKey = true;
|
|
1006
|
+
// the part must turn away the right people: nobody signed in / a role not allowed - not the other way round
|
|
1007
|
+
const want = rejectWhenTrue ? -1 : 1;
|
|
1008
|
+
const rolePart = role && !mixed && !refersTo(part, (x) => x.type === 'Identifier' && roleMixedLocals.has(x.name));
|
|
1009
|
+
const rp = rolePart ? polarity(part, isRoleNode) : 0;
|
|
1010
|
+
// `error` from a session lookup is there when the person is not: its polarity is the other way round
|
|
1011
|
+
const onlyError = id && refersTo(part, (x) => x.type === 'Identifier' && errorLocals.has(x.name)) && !refersTo(part, (x) => x.type === 'Identifier' && identityLocals.has(x.name) && !errorLocals.has(x.name));
|
|
1012
|
+
const ip = id ? (onlyError ? -1 : 1) * polarity(part, isIdentityNode) : 0;
|
|
1013
|
+
if (rolePart && (rp === want || rp === 0)) anyRole = true;
|
|
1014
|
+
else if (role || refersTo(part, (x) => x.type === 'Identifier' && roleMixedLocals.has(x.name))) out.partial.push(ev('a role check that applies only in some cases'));
|
|
1015
|
+
else if (id && !mixed && (ip === want || ip === 0)) anyIdentity = true;
|
|
1016
|
+
else if (id && !mixed) out.turnsAwaySignedIn = true;
|
|
1017
|
+
else if (id && mixed) out.authPartial = out.authPartial || ev('a sign-in check that applies only in some cases');
|
|
1018
|
+
else if (!s && !k && !present) anyOther = true;
|
|
1019
|
+
}
|
|
1020
|
+
if (anyRole) out.role = out.role || Object.assign(ev('turns away a role that is not allowed'), { roles: roleList.length ? roleList : rolesIn(t, testNode) });
|
|
1021
|
+
if (anyIdentity || (anyRole && !out.auth)) {
|
|
1022
|
+
if (anyIdentity) out.auth = out.auth || ev('turns away a request with nobody signed in');
|
|
1023
|
+
}
|
|
1024
|
+
if (apiKey && !anyOther) out.apiKey = out.apiKey || ev('turns away a request without a valid API key');
|
|
1025
|
+
if (sig) {
|
|
1026
|
+
out.signature = out.signature || ev(sigSkippable ? 'checks the signature only when one is sent' : 'turns away a body whose signature does not match');
|
|
1027
|
+
if (sigSkippable) out.signatureSkippable = true;
|
|
1028
|
+
}
|
|
1029
|
+
if (anyIdentity || anyRole || apiKey || sig) out.rejects = true;
|
|
1030
|
+
};
|
|
1031
|
+
|
|
1032
|
+
fn.traverse({
|
|
1033
|
+
Function(q) {
|
|
1034
|
+
// callbacks inside the function (a promise's then) still run for this request; named inner functions do not
|
|
1035
|
+
if (q.isFunctionDeclaration()) q.skip();
|
|
1036
|
+
},
|
|
1037
|
+
IfStatement(q) {
|
|
1038
|
+
const cons = q.node.consequent;
|
|
1039
|
+
const alt = q.node.alternate;
|
|
1040
|
+
if (responds(cons) && !refersTo(cons, (x) => x.type === 'CallExpression' && nextName && t.isIdentifier(x.callee, { name: nextName }) && !x.arguments.length)) consider(q.node.test, true, q.node);
|
|
1041
|
+
else if (alt && responds(alt) && passes(cons)) consider(q.node.test, false, q.node);
|
|
1042
|
+
},
|
|
1043
|
+
ConditionalExpression(q) {
|
|
1044
|
+
const { test, consequent, alternate } = q.node;
|
|
1045
|
+
if (responds(alternate) && !responds(consequent)) consider(test, false, q.node);
|
|
1046
|
+
else if (responds(consequent) && !responds(alternate)) consider(test, true, q.node);
|
|
1047
|
+
},
|
|
1048
|
+
LogicalExpression(q) {
|
|
1049
|
+
// cond || res.status(401)... / cond && next()
|
|
1050
|
+
if (q.node.operator === '||' && responds(q.node.right) && q.parentPath.isExpressionStatement()) consider(q.node.left, false, q.node);
|
|
1051
|
+
},
|
|
1052
|
+
// try { event = stripe.webhooks.constructEvent(...) } catch { return 400 }: the verification throws on a bad signature
|
|
1053
|
+
TryStatement(q) {
|
|
1054
|
+
if (!q.node.handler || !responds(q.node.handler.body)) return;
|
|
1055
|
+
let at = null;
|
|
1056
|
+
q.get('block').traverse({
|
|
1057
|
+
CallExpression(c) {
|
|
1058
|
+
if (!at && isVerify(c.node)) at = c.node;
|
|
1059
|
+
},
|
|
1060
|
+
});
|
|
1061
|
+
if (!at) return;
|
|
1062
|
+
const line = at.loc.start.line;
|
|
1063
|
+
out.signature = out.signature || { file: mod.rel, line, code: snippet(mod, line), how: 'turns away a body whose signature does not match (the verification throws and the catch answers with an error)' };
|
|
1064
|
+
out.rejects = true;
|
|
1065
|
+
},
|
|
1066
|
+
});
|
|
1067
|
+
// the request handed on: requireAdmin(req), handlePlan(request, deps), or handle(request) where handle is
|
|
1068
|
+
// what a wrapper was given (guarded('plan', (request) => handlePlan(request, ...))). Each is read the same
|
|
1069
|
+
// way; one that cannot be followed makes "no check found" unknown, never not_detected.
|
|
1070
|
+
out.delegates = out.delegates || [];
|
|
1071
|
+
// the methods it answers: if (req.method !== 'POST') return 405 - read here and in every function the request is handed to
|
|
1072
|
+
out.methods = new Set();
|
|
1073
|
+
if (reqName) {
|
|
1074
|
+
fn.traverse({
|
|
1075
|
+
Function(q) {
|
|
1076
|
+
if (q.isFunctionDeclaration()) q.skip();
|
|
1077
|
+
},
|
|
1078
|
+
BinaryExpression(q) {
|
|
1079
|
+
const sides = [q.node.left, q.node.right];
|
|
1080
|
+
const isMethod = sides.some((s) => (memberChain(s) || []).join('.') === reqName + '.method');
|
|
1081
|
+
const lit = sides.find((s) => s.type === 'StringLiteral');
|
|
1082
|
+
if (isMethod && lit && /^[A-Z]+$/.test(lit.value) && lit.value !== 'OPTIONS') out.methods.add(lit.value);
|
|
1083
|
+
},
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
const depth = opts.depth || 0;
|
|
1087
|
+
if (reqName && depth < 5) {
|
|
1088
|
+
const calls = [];
|
|
1089
|
+
fn.traverse({
|
|
1090
|
+
Function(q) {
|
|
1091
|
+
if (q.isFunctionDeclaration()) q.skip();
|
|
1092
|
+
},
|
|
1093
|
+
CallExpression(q) {
|
|
1094
|
+
if (q.node.arguments.some((a) => t.isIdentifier(a, { name: reqName }))) calls.push(q);
|
|
1095
|
+
},
|
|
1096
|
+
});
|
|
1097
|
+
for (const call of calls) {
|
|
1098
|
+
const callee = call.get('callee');
|
|
1099
|
+
const chain = memberChain(call.node.callee) || [];
|
|
1100
|
+
if (chain[0] === reqName || (resName && chain[0] === resName)) continue;
|
|
1101
|
+
if (nextName && chain[0] === nextName) continue;
|
|
1102
|
+
let r = null;
|
|
1103
|
+
if (callee.isIdentifier()) {
|
|
1104
|
+
const b = call.scope.getBinding(callee.node.name);
|
|
1105
|
+
if (!b) continue; // a global: console.log(req), fetch(req) - not the app's code
|
|
1106
|
+
if (b.kind === 'param' && ref.factory) {
|
|
1107
|
+
const params2 = ref.factory.path.node.params;
|
|
1108
|
+
const at2 = params2.findIndex((q) => (q.type === 'RestElement' ? q.argument.name : q.name) === callee.node.name);
|
|
1109
|
+
const arg = at2 >= 0 && ref.factory.callArgs && ref.factory.callArgs[at2];
|
|
1110
|
+
r = arg ? resolveRef(ctx, ref.factory.callMod, arg) : { kind: 'unknown', why: callee.node.name + ' is a parameter of ' + (ref.factory.path.node.id ? ref.factory.path.node.id.name : 'a wrapper') + ' with no argument for it' };
|
|
1111
|
+
} else if (b.kind === 'param') {
|
|
1112
|
+
r = { kind: 'unknown', why: callee.node.name + ' is a parameter' };
|
|
1113
|
+
} else {
|
|
1114
|
+
r = resolveRef(ctx, mod, bindingTarget(b));
|
|
1115
|
+
}
|
|
1116
|
+
} else {
|
|
1117
|
+
r = resolveRef(ctx, mod, callee);
|
|
1118
|
+
if (r.kind === 'pkg' && NOT_GUARDS.test(r.name)) continue;
|
|
1119
|
+
}
|
|
1120
|
+
const line = call.node.loc.start.line;
|
|
1121
|
+
if (r.kind !== 'fn') {
|
|
1122
|
+
out.delegates.push({ name: (chain.join('.') || 'a function') + '()', file: mod.rel, line, why: r.why || (r.kind === 'pkg' ? 'comes from the package ' + r.source : 'could not be followed') });
|
|
1123
|
+
continue;
|
|
1124
|
+
}
|
|
1125
|
+
if (r.path.node === fn.node) continue;
|
|
1126
|
+
const idx = call.node.arguments.findIndex((a) => t.isIdentifier(a, { name: reqName }));
|
|
1127
|
+
const p = r.path.node.params[idx];
|
|
1128
|
+
if (!p || p.type !== 'Identifier') {
|
|
1129
|
+
out.delegates.push({ name: (chain.join('.') || 'a function') + '()', file: mod.rel, line, why: 'takes the request in a pattern that is not read' });
|
|
1130
|
+
continue;
|
|
1131
|
+
}
|
|
1132
|
+
const resIdx = call.node.arguments.findIndex((a) => resName && t.isIdentifier(a, { name: resName }));
|
|
1133
|
+
const g = readGuardFn(ctx, r, { reqName: p.name, resName: resIdx >= 0 && r.path.node.params[resIdx] ? r.path.node.params[resIdx].name : null, asHelper: true, depth: depth + 1 });
|
|
1134
|
+
const where = ' (in ' + (chain.join('.') || 'a function') + '(), called at ' + mod.rel + ':' + line + ')';
|
|
1135
|
+
for (const k of ['auth', 'role', 'apiKey', 'signature', 'authPartial', 'sigPresenceOnly']) if (g[k] && !out[k]) out[k] = Object.assign({}, g[k], { how: g[k].how + where });
|
|
1136
|
+
if (g.signatureSkippable) out.signatureSkippable = true;
|
|
1137
|
+
out.partial.push(...g.partial);
|
|
1138
|
+
out.delegates.push(...g.delegates);
|
|
1139
|
+
for (const m of g.methods) out.methods.add(m);
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
// a role check implies a signed-in one: nobody signed in has no role to pass
|
|
1143
|
+
if (out.role && !out.auth) out.auth = Object.assign({}, out.role, { how: 'turns away anyone without an allowed role, which nobody signed out has' });
|
|
1144
|
+
if (out.apiKey && !out.auth) out.auth = Object.assign({}, out.apiKey, { how: 'turns away a request without a valid API key', kind: 'api-key' });
|
|
1145
|
+
return out;
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
/** Every name a declaration binds: user, or data and user and error in { data: { user }, error }. */
|
|
1149
|
+
function patternNames(id) {
|
|
1150
|
+
if (!id) return [];
|
|
1151
|
+
if (id.type === 'Identifier') return [id.name];
|
|
1152
|
+
if (id.type === 'ObjectPattern') return id.properties.flatMap((p) => (p.type === 'RestElement' ? patternNames(p.argument) : patternNames(p.value)));
|
|
1153
|
+
if (id.type === 'ArrayPattern') return id.elements.flatMap((e) => patternNames(e));
|
|
1154
|
+
if (id.type === 'AssignmentPattern') return patternNames(id.left);
|
|
1155
|
+
return [];
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
/** supabase.auth.getUser(), getClaims(), getSession(), jwt.verify(), jose's jwtVerify(): who the token belongs to. */
|
|
1159
|
+
function isSessionLookup(n) {
|
|
1160
|
+
if (n.type !== 'CallExpression' && n.type !== 'OptionalCallExpression') return false;
|
|
1161
|
+
const chain = memberChain(n.callee) || [];
|
|
1162
|
+
const last = chain[chain.length - 1] || '';
|
|
1163
|
+
if (chain.includes('auth') && /^(getUser|getClaims|getSession)$/.test(last)) return true;
|
|
1164
|
+
if (/^(jwtVerify|verifyToken|verifyIdToken|getServerSession|currentUser|getToken|getAuth|getIronSession)$/.test(last)) return true;
|
|
1165
|
+
// next-auth v5 and Clerk: await auth() / const { userId } = auth()
|
|
1166
|
+
if (chain.length === 1 && last === 'auth') return true;
|
|
1167
|
+
// cookies().get('session') from next/headers: a session cookie, read on the server
|
|
1168
|
+
if (last === 'get' && n.callee.type === 'MemberExpression' && n.callee.object.type === 'CallExpression' && n.callee.object.callee.type === 'Identifier' && n.callee.object.callee.name === 'cookies') return true;
|
|
1169
|
+
return last === 'verify' && /^(jwt|jsonwebtoken|jose)$/i.test(chain[0] || '');
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
/** new Response(body, { status: 401 }), Response.json(body, { status: 403 }), NextResponse.json(..., { status: 400 }), NextResponse.redirect(). */
|
|
1173
|
+
function isErrorResponse(n) {
|
|
1174
|
+
const statusOf = (opts) => {
|
|
1175
|
+
if (!opts || opts.type !== 'ObjectExpression') return null;
|
|
1176
|
+
const s = opts.properties.find((p) => p.key && (p.key.name || p.key.value) === 'status');
|
|
1177
|
+
return s && s.value.type === 'NumericLiteral' ? s.value.value : null;
|
|
1178
|
+
};
|
|
1179
|
+
if (n.type === 'NewExpression' && n.callee.type === 'Identifier' && /^(Response|NextResponse)$/.test(n.callee.name)) {
|
|
1180
|
+
const s = statusOf(n.arguments[1]);
|
|
1181
|
+
return s !== null && s >= 400;
|
|
1182
|
+
}
|
|
1183
|
+
if (n.type === 'CallExpression') {
|
|
1184
|
+
const chain = memberChain(n.callee) || [];
|
|
1185
|
+
if (/^(Response|NextResponse)$/.test(chain[0] || '') && chain[1] === 'json') {
|
|
1186
|
+
const s = statusOf(n.arguments[1]);
|
|
1187
|
+
return s !== null && s >= 400;
|
|
1188
|
+
}
|
|
1189
|
+
if (/^(NextResponse)$/.test(chain[0] || '') && chain[1] === 'redirect') return true;
|
|
1190
|
+
if (chain.length === 1 && /^(redirect|notFound|unauthorized|forbidden)$/.test(chain[0])) return true;
|
|
1191
|
+
}
|
|
1192
|
+
return false;
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
function rolesIn(t, node) {
|
|
1196
|
+
const out = [];
|
|
1197
|
+
const visit = (n) => {
|
|
1198
|
+
if (!n || typeof n !== 'object') return;
|
|
1199
|
+
if (Array.isArray(n)) return n.forEach(visit);
|
|
1200
|
+
if (n.type === 'StringLiteral' && /^[a-z][a-z_:-]{1,30}$/i.test(n.value)) out.push(n.value);
|
|
1201
|
+
for (const k of Object.keys(n)) if (k !== 'loc') visit(n[k]);
|
|
1202
|
+
};
|
|
1203
|
+
visit(node);
|
|
1204
|
+
return Array.from(new Set(out));
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
/** What one element in front of a route is, and what it checks. */
|
|
1208
|
+
function readElement(ctx, h) {
|
|
1209
|
+
const ref = h.ref;
|
|
1210
|
+
const base = { text: h.text, usedFile: h.mod.rel, usedLine: h.line, inherited: !!h.inherited };
|
|
1211
|
+
if (h.usedAt) Object.assign(base, { usedFile: h.usedAt.mod.rel, usedLine: h.usedAt.line });
|
|
1212
|
+
if (ref.kind === 'fn') {
|
|
1213
|
+
const g = readGuardFn(ctx, ref);
|
|
1214
|
+
const defLine = ref.path.node.loc.start.line;
|
|
1215
|
+
return Object.assign(base, { kind: 'code', file: ref.mod.rel, line: defLine, guards: g, wrappedBy: ref.wrappedBy ? ref.wrappedBy.mod.rel + ':' + ref.wrappedBy.path.node.loc.start.line : null });
|
|
1216
|
+
}
|
|
1217
|
+
if (ref.kind === 'pkg') {
|
|
1218
|
+
const name = ref.name;
|
|
1219
|
+
if (NOT_GUARDS.test(name) || (packageName(ref.source) === 'express' && /^(json|urlencoded|raw|text|static)$/.test(name.split('.').pop()))) return Object.assign(base, { kind: 'package', source: ref.source, guards: { none: true } });
|
|
1220
|
+
if (PACKAGE_AUTH.test(name.split('.').slice(-2).join('.')) || PACKAGE_AUTH.test(name.split('.').pop()) && PACKAGE_AUTH_SOURCES.test(ref.source)) {
|
|
1221
|
+
return Object.assign(base, { kind: 'package', source: ref.source, guards: { auth: { file: h.mod.rel, line: h.line, code: snippet(h.mod, h.line), how: 'sign-in middleware from ' + ref.source } } });
|
|
1222
|
+
}
|
|
1223
|
+
return Object.assign(base, { kind: 'package', source: ref.source, guards: null, why: 'comes from the package ' + ref.source + ', whose code is not read' });
|
|
1224
|
+
}
|
|
1225
|
+
if (ref.kind === 'container') return Object.assign(base, { kind: 'router', guards: { none: true } });
|
|
1226
|
+
return Object.assign(base, { kind: 'unknown', guards: null, why: ref.why });
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
/** The three guards of one route, from everything in front of it. */
|
|
1230
|
+
function judge(route, elements) {
|
|
1231
|
+
const unknowns = elements.filter((e) => e.guards === null);
|
|
1232
|
+
// the request handed to code that could not be followed: a check may be there
|
|
1233
|
+
const handedOn = [];
|
|
1234
|
+
for (const e of elements) for (const d of (e.guards && e.guards.delegates) || []) handedOn.push(e.text + ' hands the request to ' + d.name + ' at ' + d.file + ':' + d.line + ', which could not be followed (' + d.why + ')');
|
|
1235
|
+
const verdict = (key) => {
|
|
1236
|
+
const hit = elements.find((e) => e.guards && e.guards[key]);
|
|
1237
|
+
if (hit) return { status: STATUS.DETECTED, evidence: hit.guards[key], by: hit.text };
|
|
1238
|
+
if (unknowns.length || handedOn.length) return { status: STATUS.UNKNOWN, why: unknowns.map((u) => u.text + ': ' + u.why).concat(handedOn) };
|
|
1239
|
+
return { status: STATUS.NOT };
|
|
1240
|
+
};
|
|
1241
|
+
const out = { auth: verdict('auth'), role: verdict('role'), signature: verdict('signature') };
|
|
1242
|
+
const authPartial = elements.find((e) => e.guards && e.guards.authPartial);
|
|
1243
|
+
if (authPartial && out.auth.status === STATUS.NOT) out.auth = { status: STATUS.UNKNOWN, why: [authPartial.text + ': ' + authPartial.guards.authPartial.how + ' (' + authPartial.guards.authPartial.file + ':' + authPartial.guards.authPartial.line + ')'] };
|
|
1244
|
+
const skippable = elements.find((e) => e.guards && e.guards.signatureSkippable);
|
|
1245
|
+
if (skippable && out.signature.status === STATUS.DETECTED) out.signature.skippable = true;
|
|
1246
|
+
const presence = elements.find((e) => e.guards && e.guards.sigPresenceOnly);
|
|
1247
|
+
if (presence && out.signature.status !== STATUS.DETECTED) out.signature.presenceOnly = presence.guards.sigPresenceOnly;
|
|
1248
|
+
const partial = [];
|
|
1249
|
+
for (const e of elements) if (e.guards && e.guards.partial) partial.push(...e.guards.partial);
|
|
1250
|
+
out.partial = partial;
|
|
1251
|
+
const roleEv = out.role.evidence;
|
|
1252
|
+
if (roleEv && roleEv.roles) out.role.roles = roleEv.roles;
|
|
1253
|
+
return out;
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
// --- the database: what each route reads and writes, and whose rows ----------------
|
|
1257
|
+
|
|
1258
|
+
// A column that says which organisation a row belongs to, and one that says which person.
|
|
1259
|
+
const TENANT_COLS = /^(org_id|orgid|organization_id|organisation_id|organizationid|workspace_id|workspaceid|tenant_id|tenantid|team_id|teamid|account_id|accountid|company_id|companyid|business_id|clinic_id|school_id|store_id|shop_id)$/i;
|
|
1260
|
+
const OWNER_COLS = /^(user_id|userid|owner_id|ownerid|created_by|createdby|author_id|authorid|customer_id|customerid|member_id|memberid|student_id|studentid|profile_id|profileid|requester_id|requesterid|actor_id)$/i;
|
|
1261
|
+
// A table that is the organisation itself: its own id is the tenant.
|
|
1262
|
+
const TENANT_TABLES = /^(organizations|organisations|orgs|workspaces|tenants|teams|accounts|companies|businesses)$/i;
|
|
1263
|
+
const SQL_CALLS = /^(query|execute|any|one|oneOrNone|many|manyOrNone|none|result|unsafe|raw)$/;
|
|
1264
|
+
const SUPABASE_OPS = { select: 'SELECT', insert: 'INSERT', update: 'UPDATE', upsert: 'UPSERT', delete: 'DELETE' };
|
|
1265
|
+
const PRISMA_OPS = { findMany: 'SELECT', findFirst: 'SELECT', findUnique: 'SELECT', findFirstOrThrow: 'SELECT', findUniqueOrThrow: 'SELECT', count: 'SELECT', aggregate: 'SELECT', groupBy: 'SELECT',
|
|
1266
|
+
create: 'INSERT', createMany: 'INSERT', update: 'UPDATE', updateMany: 'UPDATE', upsert: 'UPSERT', delete: 'DELETE', deleteMany: 'DELETE' };
|
|
1267
|
+
// Database libraries whose calls this map does not read: said once per file.
|
|
1268
|
+
const OTHER_DB = /^(knex|sequelize|typeorm|drizzle-orm|mongoose|mongodb|kysely|objection|@mikro-orm\/)/;
|
|
1269
|
+
|
|
1270
|
+
/** Tables and their columns, from CREATE TABLE / ALTER TABLE in .sql files and in SQL strings in the code. */
|
|
1271
|
+
function readSchema(ctx, root) {
|
|
1272
|
+
const tables = new Map();
|
|
1273
|
+
const rlsTables = new Set();
|
|
1274
|
+
const texts = [];
|
|
1275
|
+
(function walk(dir, depth) {
|
|
1276
|
+
if (depth > 6) return;
|
|
1277
|
+
let entries;
|
|
1278
|
+
try {
|
|
1279
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
1280
|
+
} catch (err) {
|
|
1281
|
+
return;
|
|
1282
|
+
}
|
|
1283
|
+
for (const e of entries) {
|
|
1284
|
+
if (e.name.startsWith('.') || e.name === 'node_modules') continue;
|
|
1285
|
+
const full = path.join(dir, e.name);
|
|
1286
|
+
if (e.isDirectory()) walk(full, depth + 1);
|
|
1287
|
+
else if (/\.sql$/i.test(e.name)) {
|
|
1288
|
+
try {
|
|
1289
|
+
if (fs.statSync(full).size <= MAX_BYTES * 4) texts.push(fs.readFileSync(full, 'utf8'));
|
|
1290
|
+
} catch (err) {
|
|
1291
|
+
/* an unreadable .sql file only means fewer known columns */
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
})(root, 0);
|
|
1296
|
+
for (const mod of ctx.modules.values()) if (mod && /create\s+table/i.test(mod.source)) texts.push(mod.source);
|
|
1297
|
+
const bare = (n) => n.replace(/["`]/g, '').split('.').pop().toLowerCase();
|
|
1298
|
+
for (const text of texts) {
|
|
1299
|
+
const re = /create\s+table\s+(?:if\s+not\s+exists\s+)?([\w."`]+)\s*\(/gi;
|
|
1300
|
+
let m;
|
|
1301
|
+
while ((m = re.exec(text))) {
|
|
1302
|
+
let i = re.lastIndex, d = 1;
|
|
1303
|
+
const start = i;
|
|
1304
|
+
while (i < text.length && d > 0) {
|
|
1305
|
+
if (text[i] === '(') d++;
|
|
1306
|
+
else if (text[i] === ')') d--;
|
|
1307
|
+
i++;
|
|
1308
|
+
}
|
|
1309
|
+
const body = text.slice(start, i - 1);
|
|
1310
|
+
const cols = new Set(tables.get(bare(m[1])) || []);
|
|
1311
|
+
let depth = 0, cur = '';
|
|
1312
|
+
const parts = [];
|
|
1313
|
+
for (const ch of body) {
|
|
1314
|
+
if (ch === '(') depth++;
|
|
1315
|
+
if (ch === ')') depth--;
|
|
1316
|
+
if (ch === ',' && depth === 0) {
|
|
1317
|
+
parts.push(cur);
|
|
1318
|
+
cur = '';
|
|
1319
|
+
} else cur += ch;
|
|
1320
|
+
}
|
|
1321
|
+
parts.push(cur);
|
|
1322
|
+
for (const p of parts) {
|
|
1323
|
+
const w = p.trim().split(/\s+/)[0];
|
|
1324
|
+
if (w && !/^(constraint|primary|foreign|unique|check|exclude|like|index|key)$/i.test(w)) cols.add(w.replace(/["`]/g, '').toLowerCase());
|
|
1325
|
+
}
|
|
1326
|
+
tables.set(bare(m[1]), cols);
|
|
1327
|
+
}
|
|
1328
|
+
const alter = /alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?([\w."`]+)\s+add\s+(?:column\s+)?(?:if\s+not\s+exists\s+)?([\w"`]+)/gi;
|
|
1329
|
+
while ((m = alter.exec(text))) {
|
|
1330
|
+
const t = bare(m[1]);
|
|
1331
|
+
if (!tables.has(t)) tables.set(t, new Set());
|
|
1332
|
+
tables.get(t).add(m[2].replace(/["`]/g, '').toLowerCase());
|
|
1333
|
+
}
|
|
1334
|
+
// tables whose rows the database itself limits: row level security
|
|
1335
|
+
const rls = /alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?([\w."`]+)\s+(?:force\s+)?enable\s+row\s+level\s+security/gi;
|
|
1336
|
+
while ((m = rls.exec(text))) rlsTables.add(bare(m[1]));
|
|
1337
|
+
}
|
|
1338
|
+
tables.rls = rlsTables;
|
|
1339
|
+
return tables;
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
/** The SQL a call sends, as text with $1.. kept, or null; several when it is one of two texts. */
|
|
1343
|
+
function sqlTexts(ctx, mod, p, depth = 0) {
|
|
1344
|
+
p = unwrapTs(p);
|
|
1345
|
+
if (!p || !p.node || depth > 6) return null;
|
|
1346
|
+
if (p.isStringLiteral()) return [{ text: p.node.value, dynamic: false }];
|
|
1347
|
+
if (p.isTemplateLiteral()) {
|
|
1348
|
+
let out = '';
|
|
1349
|
+
let dynamic = false;
|
|
1350
|
+
const exprs = p.get('expressions');
|
|
1351
|
+
p.node.quasis.forEach((q, i) => {
|
|
1352
|
+
out += q.value.cooked;
|
|
1353
|
+
if (i < exprs.length) {
|
|
1354
|
+
const inner = sqlTexts(ctx, mod, exprs[i], depth + 1);
|
|
1355
|
+
if (inner && inner.length === 1 && !inner[0].dynamic) out += inner[0].text;
|
|
1356
|
+
else {
|
|
1357
|
+
dynamic = true;
|
|
1358
|
+
out += ' ${...} ';
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
});
|
|
1362
|
+
return [{ text: out, dynamic }];
|
|
1363
|
+
}
|
|
1364
|
+
if (p.isConditionalExpression()) {
|
|
1365
|
+
const a = sqlTexts(ctx, mod, p.get('consequent'), depth + 1);
|
|
1366
|
+
const b = sqlTexts(ctx, mod, p.get('alternate'), depth + 1);
|
|
1367
|
+
return a && b ? a.concat(b) : null;
|
|
1368
|
+
}
|
|
1369
|
+
if (p.isBinaryExpression({ operator: '+' })) {
|
|
1370
|
+
const a = sqlTexts(ctx, mod, p.get('left'), depth + 1);
|
|
1371
|
+
const b = sqlTexts(ctx, mod, p.get('right'), depth + 1);
|
|
1372
|
+
if (a && b && a.length === 1 && b.length === 1) return [{ text: a[0].text + b[0].text, dynamic: a[0].dynamic || b[0].dynamic }];
|
|
1373
|
+
return [{ text: (a && a.length === 1 ? a[0].text : ' ${...} ') + (b && b.length === 1 ? b[0].text : ' ${...} '), dynamic: true }];
|
|
1374
|
+
}
|
|
1375
|
+
if (p.isIdentifier()) {
|
|
1376
|
+
const b = p.scope.getBinding(p.node.name);
|
|
1377
|
+
if (b && b.path.isVariableDeclarator() && b.path.get('init').node) {
|
|
1378
|
+
// let sql = '...'; sql += ' AND x' - built up in pieces: read the first piece, say it is dynamic
|
|
1379
|
+
const first = sqlTexts(ctx, mod, b.path.get('init'), depth + 1);
|
|
1380
|
+
if (!first) return null;
|
|
1381
|
+
if (b.constantViolations.length) return first.map((x) => Object.assign({}, x, { dynamic: true, text: x.text + ' ${...} ' }));
|
|
1382
|
+
return first;
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
return null;
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
/** What one SQL statement does: [{ op, table, where, insertCols }] for each table it writes or reads. */
|
|
1389
|
+
function parseSql(text) {
|
|
1390
|
+
const sql = text.replace(/--[^\n]*/g, ' ').replace(/\/\*[\s\S]*?\*\//g, ' ');
|
|
1391
|
+
const out = [];
|
|
1392
|
+
const name = '((?:"?\\w+"?\\.)?"?[A-Za-z_]\\w*"?)';
|
|
1393
|
+
const clean = (n) => n.replace(/"/g, '').split('.').pop().toLowerCase();
|
|
1394
|
+
const writes = new Set();
|
|
1395
|
+
let m;
|
|
1396
|
+
const ins = new RegExp('insert\\s+into\\s+' + name + '\\s*(\\(([^)]*)\\))?', 'gi');
|
|
1397
|
+
while ((m = ins.exec(sql))) {
|
|
1398
|
+
const cols = m[3] ? m[3].split(',').map((c) => c.trim().replace(/"/g, '').toLowerCase()) : [];
|
|
1399
|
+
const values = sql.slice(ins.lastIndex).match(/^\s*values\s*\(([\s\S]*?)\)\s*(on\s+conflict|returning|;|$)/i);
|
|
1400
|
+
const vals = values ? splitTop(values[1]) : [];
|
|
1401
|
+
out.push({ op: /on\s+conflict[\s\S]*do\s+update/i.test(sql) ? 'UPSERT' : 'INSERT', table: clean(m[1]), insertCols: cols, insertVals: vals, where: '' });
|
|
1402
|
+
writes.add(clean(m[1]));
|
|
1403
|
+
}
|
|
1404
|
+
const upd = new RegExp('update\\s+(?:only\\s+)?' + name + '(?:\\s+(?:as\\s+)?(\\w+))?\\s+set\\b', 'gi');
|
|
1405
|
+
while ((m = upd.exec(sql))) {
|
|
1406
|
+
out.push({ op: 'UPDATE', table: clean(m[1]), alias: m[2] && m[2].toLowerCase(), where: whereAfter(sql, upd.lastIndex) });
|
|
1407
|
+
writes.add(clean(m[1]));
|
|
1408
|
+
}
|
|
1409
|
+
const del = new RegExp('delete\\s+from\\s+(?:only\\s+)?' + name + '(?:\\s+(?:as\\s+)?(?!where\\b|using\\b|returning\\b)(\\w+))?', 'gi');
|
|
1410
|
+
while ((m = del.exec(sql))) {
|
|
1411
|
+
out.push({ op: 'DELETE', table: clean(m[1]), alias: m[2] && m[2].toLowerCase(), where: whereAfter(sql, del.lastIndex) });
|
|
1412
|
+
writes.add(clean(m[1]));
|
|
1413
|
+
}
|
|
1414
|
+
// reads: FROM and JOIN that are not the table being written
|
|
1415
|
+
const from = new RegExp('\\b(from|join)\\s+' + name + '(?:\\s+(?:as\\s+)?(?!where|join|on|left|right|inner|outer|full|cross|group|order|limit|returning|set|using|natural|lateral)(\\w+))?', 'gi');
|
|
1416
|
+
const isSelect = /^\s*(with\b[\s\S]*?\)\s*)?select\b/i.test(sql) || /\bselect\b/i.test(sql);
|
|
1417
|
+
const seen = new Set();
|
|
1418
|
+
while ((m = from.exec(sql))) {
|
|
1419
|
+
const before = sql.slice(Math.max(0, m.index - 12), m.index);
|
|
1420
|
+
if (/delete\s*$/i.test(before)) continue;
|
|
1421
|
+
const t = clean(m[2]);
|
|
1422
|
+
if (/^(unnest|generate_series|json_\w+|jsonb_\w+|lateral|select|values)$/.test(t)) continue;
|
|
1423
|
+
if (writes.has(t) && !isSelect) continue;
|
|
1424
|
+
if (seen.has(t)) continue;
|
|
1425
|
+
seen.add(t);
|
|
1426
|
+
const firstRead = out.find((x) => x.op === 'SELECT' && !x.joinedTo);
|
|
1427
|
+
out.push({ op: 'SELECT', table: t, alias: m[3] && m[3].toLowerCase(), where: whereAfter(sql, from.lastIndex), joinedTo: /^join$/i.test(m[1]) && firstRead ? firstRead.table : undefined });
|
|
1428
|
+
}
|
|
1429
|
+
return out;
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
function whereAfter(sql, from) {
|
|
1433
|
+
const rest = sql.slice(from);
|
|
1434
|
+
const w = rest.search(/\bwhere\b/i);
|
|
1435
|
+
if (w < 0) return '';
|
|
1436
|
+
const tail = rest.slice(w + 5);
|
|
1437
|
+
const end = tail.search(/\b(group\s+by|order\s+by|limit|returning|union|having|for\s+update)\b/i);
|
|
1438
|
+
return end < 0 ? tail : tail.slice(0, end);
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
function splitTop(s) {
|
|
1442
|
+
const out = [];
|
|
1443
|
+
let d = 0, cur = '';
|
|
1444
|
+
for (const ch of s) {
|
|
1445
|
+
if (ch === '(') d++;
|
|
1446
|
+
if (ch === ')') d--;
|
|
1447
|
+
if (ch === ',' && d === 0) {
|
|
1448
|
+
out.push(cur.trim());
|
|
1449
|
+
cur = '';
|
|
1450
|
+
} else cur += ch;
|
|
1451
|
+
}
|
|
1452
|
+
if (cur.trim()) out.push(cur.trim());
|
|
1453
|
+
return out;
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
/**
|
|
1457
|
+
* Where a value in the request's code comes from:
|
|
1458
|
+
* 'identity' the signed-in person (req.user, req.session, a helper of it, the database's auth.uid())
|
|
1459
|
+
* 'client' what the request sends (req.body, req.query, req.params)
|
|
1460
|
+
* 'record' a row the code read (shipment.org_id) - whose row it is depends on how it was read
|
|
1461
|
+
* 'unknown'
|
|
1462
|
+
*/
|
|
1463
|
+
function sourceReader(ctx, fnRef, env) {
|
|
1464
|
+
const t = ctx.t;
|
|
1465
|
+
const fn = fnRef.path;
|
|
1466
|
+
const mod = fnRef.mod;
|
|
1467
|
+
const params = fn.node.params;
|
|
1468
|
+
const reqName = env.reqName !== undefined ? env.reqName : (params[0] && params[0].type === 'Identifier' ? params[0].name : null);
|
|
1469
|
+
const locals = new Map(Object.entries(env.paramSources || {}));
|
|
1470
|
+
const chainSource = (chain) => {
|
|
1471
|
+
if (!chain) return null;
|
|
1472
|
+
if (locals.has(chain[0])) return locals.get(chain[0]);
|
|
1473
|
+
if (reqName && chain[0] === reqName) {
|
|
1474
|
+
if (/^(body|query|params|headers|cookies|files|file|nextUrl|url)$/.test(chain[1] || '')) return 'client';
|
|
1475
|
+
if (chain[1] && IDENTITY_SEGS.test(chain[1])) return 'identity';
|
|
1476
|
+
if (/^(db|client|tx)$/.test(chain[1] || '')) return null;
|
|
1477
|
+
return null;
|
|
1478
|
+
}
|
|
1479
|
+
if (chain[0] === 'res' && chain[1] === 'locals' && chain[2] && IDENTITY_SEGS.test(chain[2])) return 'identity';
|
|
1480
|
+
return null;
|
|
1481
|
+
};
|
|
1482
|
+
const of = (n, depth = 0) => {
|
|
1483
|
+
if (!n || depth > 8) return 'unknown';
|
|
1484
|
+
switch (n.type) {
|
|
1485
|
+
case 'StringLiteral': case 'NumericLiteral': case 'BooleanLiteral': case 'NullLiteral': return 'literal';
|
|
1486
|
+
// new URL(req.url): its search parameters are what the request sent
|
|
1487
|
+
case 'NewExpression': return n.callee.type === 'Identifier' && n.callee.name === 'URL' && n.arguments[0] && (memberChain(n.arguments[0]) || [])[0] === reqName ? 'client' : 'unknown';
|
|
1488
|
+
case 'TemplateLiteral': return n.expressions.length ? worstOf(n.expressions.map((e) => of(e, depth + 1))) : 'literal';
|
|
1489
|
+
case 'TSAsExpression': case 'TSNonNullExpression': case 'ParenthesizedExpression': case 'AwaitExpression': return of(n.expression || n.argument, depth + 1);
|
|
1490
|
+
case 'Identifier': {
|
|
1491
|
+
if (locals.has(n.name)) return locals.get(n.name);
|
|
1492
|
+
return 'unknown';
|
|
1493
|
+
}
|
|
1494
|
+
case 'MemberExpression': case 'OptionalMemberExpression': {
|
|
1495
|
+
const s = chainSource(memberChain(n));
|
|
1496
|
+
if (s) return s;
|
|
1497
|
+
return of(n.object, depth + 1) === 'identity' ? 'identity' : of(n.object, depth + 1) === 'client' ? 'client' : of(n.object, depth + 1) === 'record' ? 'record' : 'unknown';
|
|
1498
|
+
}
|
|
1499
|
+
case 'CallExpression': case 'OptionalCallExpression': {
|
|
1500
|
+
const callee = memberChain(n.callee) || [];
|
|
1501
|
+
// a Fetch-style request: await req.json(), req.formData(), req.headers.get(...)
|
|
1502
|
+
if (reqName && callee[0] === reqName && /^(json|formData|text|arrayBuffer|blob)$/.test(callee[callee.length - 1] || '')) return 'client';
|
|
1503
|
+
// body.get('x'), url.searchParams.get('x'): a method of something the request sent
|
|
1504
|
+
if ((n.callee.type === 'MemberExpression' || n.callee.type === 'OptionalMemberExpression') && /^(get|getAll|has)$/.test(n.callee.property.name || '') && of(n.callee.object, depth + 1) === 'client') return 'client';
|
|
1505
|
+
// Number(x), String(x), parseInt(x): the value's source is its argument's
|
|
1506
|
+
if (/^(Number|String|parseInt|parseFloat|BigInt|Boolean)$/.test(callee.join('.')) || /^(trim|toLowerCase|toUpperCase|toString)$/.test(callee[callee.length - 1] || '')) {
|
|
1507
|
+
return n.arguments.length ? of(n.arguments[0], depth + 1) : of(n.callee.object, depth + 1);
|
|
1508
|
+
}
|
|
1509
|
+
// user(req).orgId: a helper of the request that returns the signed-in person
|
|
1510
|
+
if (reqName && n.arguments.some((a) => t.isIdentifier(a, { name: reqName })) && t.isIdentifier(n.callee)) {
|
|
1511
|
+
const b = fn.scope.getBinding(n.callee.name) || mod.program.scope.getBinding(n.callee.name);
|
|
1512
|
+
if (b) {
|
|
1513
|
+
const r = resolveRef(ctx, mod, bindingTarget(b));
|
|
1514
|
+
if (r.kind === 'fn') {
|
|
1515
|
+
const p0 = r.path.node.params[0] && r.path.node.params[0].name;
|
|
1516
|
+
const body = r.path.node.body;
|
|
1517
|
+
let hit = false;
|
|
1518
|
+
const visit = (x) => {
|
|
1519
|
+
if (!x || hit || typeof x !== 'object') return;
|
|
1520
|
+
if (Array.isArray(x)) return x.forEach(visit);
|
|
1521
|
+
if ((x.type === 'MemberExpression' || x.type === 'OptionalMemberExpression')) {
|
|
1522
|
+
const c = memberChain(x);
|
|
1523
|
+
if (c && c[0] === p0 && c[1] && IDENTITY_SEGS.test(c[1])) hit = true;
|
|
1524
|
+
}
|
|
1525
|
+
for (const k of Object.keys(x)) if (k !== 'loc') visit(x[k]);
|
|
1526
|
+
};
|
|
1527
|
+
visit(body);
|
|
1528
|
+
if (hit) return 'identity';
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
return 'unknown';
|
|
1533
|
+
}
|
|
1534
|
+
case 'LogicalExpression': return worstOf([of(n.left, depth + 1), of(n.right, depth + 1)]);
|
|
1535
|
+
case 'ConditionalExpression': return worstOf([of(n.consequent, depth + 1), of(n.alternate, depth + 1)]);
|
|
1536
|
+
default: return 'unknown';
|
|
1537
|
+
}
|
|
1538
|
+
};
|
|
1539
|
+
// locals, in order: const { title } = req.body / const user = req.session.user / const shipment = (await query(...)).rows[0]
|
|
1540
|
+
const rowOf = new Map();
|
|
1541
|
+
fn.traverse({
|
|
1542
|
+
VariableDeclarator(q) {
|
|
1543
|
+
const id = q.node.id;
|
|
1544
|
+
const init = q.node.init;
|
|
1545
|
+
if (!init) return;
|
|
1546
|
+
let s = of(init);
|
|
1547
|
+
// const { data: { user } } = await supabase.auth.getUser(): the signed-in person
|
|
1548
|
+
const awaited = init.type === 'AwaitExpression' ? init.argument : init;
|
|
1549
|
+
if (s === 'unknown' && isSessionLookup(awaited)) s = 'identity';
|
|
1550
|
+
if (s === 'unknown' && /query|rows|select|find|maybeSingle|single\(/i.test(mod.source.slice(init.start, init.end))) s = 'record';
|
|
1551
|
+
for (const name of patternNames(id)) if (!locals.has(name)) locals.set(name, s);
|
|
1552
|
+
},
|
|
1553
|
+
// for (const s of pending): each item is a row of the list it walks
|
|
1554
|
+
ForOfStatement(q) {
|
|
1555
|
+
const left = q.node.left;
|
|
1556
|
+
const id = left.type === 'VariableDeclaration' && left.declarations[0] && left.declarations[0].id;
|
|
1557
|
+
if (id && t.isIdentifier(id) && t.isIdentifier(q.node.right) && locals.get(q.node.right.name) === 'record') {
|
|
1558
|
+
locals.set(id.name, 'record');
|
|
1559
|
+
rowOf.set(id.name, q.node.right.name);
|
|
1560
|
+
}
|
|
1561
|
+
},
|
|
1562
|
+
});
|
|
1563
|
+
// the local a value is read from: shipment.org_id -> 'shipment'
|
|
1564
|
+
const rootLocal = (n) => {
|
|
1565
|
+
const chain = n && memberChain(n.type === 'TSAsExpression' || n.type === 'TSNonNullExpression' ? n.expression : n);
|
|
1566
|
+
if (!chain || locals.get(chain[0]) !== 'record') return null;
|
|
1567
|
+
return rowOf.get(chain[0]) || chain[0];
|
|
1568
|
+
};
|
|
1569
|
+
return { of, reqName, rootLocal };
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
function worstOf(list) {
|
|
1573
|
+
if (list.includes('client')) return 'client';
|
|
1574
|
+
if (list.includes('unknown')) return 'unknown';
|
|
1575
|
+
if (list.includes('record')) return 'record';
|
|
1576
|
+
if (list.includes('identity')) return 'identity';
|
|
1577
|
+
return 'literal';
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
/**
|
|
1581
|
+
* Every database call a route's handler makes, with whether the rows it touches
|
|
1582
|
+
* are limited to the signed-in person's organisation (or the person):
|
|
1583
|
+
* scoping guard_detected a tenant or owner column compared with the signed-in person's value
|
|
1584
|
+
* scoping not_detected the statement was read in full and has no such limit
|
|
1585
|
+
* scoping unknown the statement, its values or the table could not all be read
|
|
1586
|
+
*/
|
|
1587
|
+
function readDb(ctx, fnRef, schema, opts = {}) {
|
|
1588
|
+
const t = ctx.t;
|
|
1589
|
+
const out = [];
|
|
1590
|
+
const depth = opts.depth || 0;
|
|
1591
|
+
if (depth > 3) return out;
|
|
1592
|
+
const src = sourceReader(ctx, fnRef, { paramSources: opts.paramSources, reqName: opts.reqName });
|
|
1593
|
+
const mod = fnRef.mod;
|
|
1594
|
+
const seenCalls = new Set();
|
|
1595
|
+
const recordScopes = new Map();
|
|
1596
|
+
const visitCall = (q) => {
|
|
1597
|
+
if (seenCalls.has(q.node)) return;
|
|
1598
|
+
seenCalls.add(q.node);
|
|
1599
|
+
const callee = q.get('callee');
|
|
1600
|
+
const chain = memberChain(q.node.callee) || [];
|
|
1601
|
+
const last = chain[chain.length - 1] || '';
|
|
1602
|
+
const line = q.node.loc.start.line;
|
|
1603
|
+
// supabase: .from('table')...select/insert/update/delete with .eq() filters - read from the outermost call
|
|
1604
|
+
if (callee.isMemberExpression() && SUPABASE_OPS[callee.node.property.name] && fromCall(t, q)) {
|
|
1605
|
+
if (q.parentPath.isMemberExpression() && q.parentPath.parentPath.isCallExpression() && /^(select|insert|update|upsert|delete)$/.test(q.parentPath.node.property.name || '') && false) return;
|
|
1606
|
+
out.push(supabaseOp(ctx, mod, q, src, schema));
|
|
1607
|
+
return;
|
|
1608
|
+
}
|
|
1609
|
+
// prisma.model.findMany({ where }) / db.model.create({ data })
|
|
1610
|
+
if (chain.length >= 3 && PRISMA_OPS[last] && /^(prisma|db|client|tx)$/i.test(chain[chain.length - 3])) {
|
|
1611
|
+
out.push(prismaOp(ctx, mod, q, chain, src, schema));
|
|
1612
|
+
return;
|
|
1613
|
+
}
|
|
1614
|
+
// SQL: pool.query(sql, params), a wrapper query(sql, params), or sql`...`
|
|
1615
|
+
let sqlArg = null;
|
|
1616
|
+
let paramsArg = null;
|
|
1617
|
+
if (SQL_CALLS.test(last) && chain.length >= 2 && q.node.arguments.length) {
|
|
1618
|
+
sqlArg = q.get('arguments')[0];
|
|
1619
|
+
paramsArg = q.get('arguments')[1] || null;
|
|
1620
|
+
} else if (callee.isIdentifier() && q.node.arguments.length && isQueryWrapper(ctx, mod, callee)) {
|
|
1621
|
+
sqlArg = q.get('arguments')[0];
|
|
1622
|
+
paramsArg = q.get('arguments')[1] || null;
|
|
1623
|
+
}
|
|
1624
|
+
if (sqlArg) {
|
|
1625
|
+
const texts = sqlTexts(ctx, mod, sqlArg);
|
|
1626
|
+
if (!texts) {
|
|
1627
|
+
out.push({ op: '?', table: null, file: mod.rel, line, sql: snippet(mod, line), scoping: { status: STATUS.UNKNOWN, why: 'the SQL is built at run time and could not be read' } });
|
|
1628
|
+
return;
|
|
1629
|
+
}
|
|
1630
|
+
const here = [];
|
|
1631
|
+
for (const tx of texts) for (const st of parseSql(tx.text)) here.push(judgeSql(ctx, mod, line, st, tx, paramsArg, src, schema, recordScopes));
|
|
1632
|
+
joinWith(here);
|
|
1633
|
+
out.push(...here);
|
|
1634
|
+
// const shipment = (await query('SELECT ... WHERE id=$1 AND org_id=$2')).rows[0]: remember how its row was found
|
|
1635
|
+
const decl = q.findParent((x) => x.isVariableDeclarator() || x.isFunction());
|
|
1636
|
+
if (decl && decl.isVariableDeclarator() && t.isIdentifier(decl.node.id)) {
|
|
1637
|
+
const main = here.find((x) => !x.joinedTo);
|
|
1638
|
+
if (main) recordScopes.set(decl.node.id.name, { table: main.table, status: main.scoping.status, line, file: mod.rel });
|
|
1639
|
+
}
|
|
1640
|
+
if (texts.every((tx) => !parseSql(tx.text).length) && !/^\s*(begin|commit|rollback|select\s+1|set\s|savepoint|release|select\s+set_config|select\s+pg_)/i.test(texts[0].text)) {
|
|
1641
|
+
out.push({ op: '?', table: null, file: mod.rel, line, sql: snippet(mod, line), scoping: { status: STATUS.UNKNOWN, why: 'a statement this map does not read' } });
|
|
1642
|
+
}
|
|
1643
|
+
return;
|
|
1644
|
+
}
|
|
1645
|
+
// a helper of the app's own: follow it, with what each argument is
|
|
1646
|
+
if (callee.isIdentifier() && depth < 3) {
|
|
1647
|
+
const b = q.scope.getBinding(callee.node.name);
|
|
1648
|
+
if (!b) return;
|
|
1649
|
+
const r = resolveRef(ctx, mod, bindingTarget(b));
|
|
1650
|
+
if (r.kind !== 'fn' || r.path.node === fnRef.path.node) return;
|
|
1651
|
+
const paramSources = {};
|
|
1652
|
+
r.path.node.params.forEach((pp, i) => {
|
|
1653
|
+
if (pp.type === 'Identifier' && q.node.arguments[i]) paramSources[pp.name] = src.of(q.node.arguments[i]);
|
|
1654
|
+
});
|
|
1655
|
+
const inner = readDb(ctx, r, schema, { depth: depth + 1, paramSources, reqName: null });
|
|
1656
|
+
for (const op of inner) out.push(Object.assign({}, op, { via: callee.node.name + '() at ' + mod.rel + ':' + line }));
|
|
1657
|
+
}
|
|
1658
|
+
};
|
|
1659
|
+
fnRef.path.traverse({
|
|
1660
|
+
CallExpression: visitCall,
|
|
1661
|
+
TaggedTemplateExpression(q) {
|
|
1662
|
+
const tag = memberChain(q.node.tag) || [];
|
|
1663
|
+
if (!/^(sql|SQL)$/.test(tag[tag.length - 1] || '')) return;
|
|
1664
|
+
const line = q.node.loc.start.line;
|
|
1665
|
+
const quasi = q.get('quasi');
|
|
1666
|
+
const parts = q.node.quasi.quasis.map((x) => x.value.cooked);
|
|
1667
|
+
// sql`... ${value} ...`: each value is a parameter
|
|
1668
|
+
const text = parts.map((p, i) => p + (i < parts.length - 1 ? '$' + (i + 1) : '')).join('');
|
|
1669
|
+
const values = quasi.get('expressions');
|
|
1670
|
+
for (const st of parseSql(text)) out.push(judgeSql(ctx, mod, line, st, { text, dynamic: false }, { tagged: values }, src, schema));
|
|
1671
|
+
},
|
|
1672
|
+
});
|
|
1673
|
+
return out;
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1676
|
+
/** The outermost call of a supabase chain that has .from('x') in it. */
|
|
1677
|
+
function fromCall(t, q) {
|
|
1678
|
+
let n = q.node.callee.object;
|
|
1679
|
+
while (n) {
|
|
1680
|
+
if (n.type === 'CallExpression' && n.callee.type === 'MemberExpression' && n.callee.property.name === 'from' && n.arguments[0] && n.arguments[0].type === 'StringLiteral') return n;
|
|
1681
|
+
if (n.type === 'CallExpression') n = n.callee.type === 'MemberExpression' ? n.callee.object : null;
|
|
1682
|
+
else if (n.type === 'MemberExpression') n = n.object;
|
|
1683
|
+
else n = null;
|
|
1684
|
+
}
|
|
1685
|
+
return null;
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
function supabaseOp(ctx, mod, q, src, schema) {
|
|
1689
|
+
const t = ctx.t;
|
|
1690
|
+
const line = q.node.loc.start.line;
|
|
1691
|
+
const from = fromCall(t, q);
|
|
1692
|
+
const table = from.arguments[0].value.toLowerCase();
|
|
1693
|
+
const op = SUPABASE_OPS[q.node.callee.property.name];
|
|
1694
|
+
// filters are the calls after this one: walk up the chain
|
|
1695
|
+
const filters = [];
|
|
1696
|
+
let p = q;
|
|
1697
|
+
while (p.parentPath && p.parentPath.isMemberExpression() && p.parentPath.parentPath.isCallExpression()) {
|
|
1698
|
+
const call = p.parentPath.parentPath;
|
|
1699
|
+
const name = p.parentPath.node.property.name;
|
|
1700
|
+
const a = call.node.arguments;
|
|
1701
|
+
if (/^(eq|in|is|match|contains|filter)$/.test(name)) {
|
|
1702
|
+
if (name === 'match' && a[0] && a[0].type === 'ObjectExpression') for (const prop of a[0].properties) filters.push({ col: (prop.key.name || prop.key.value || '').toLowerCase(), src: src.of(prop.value) });
|
|
1703
|
+
else if (a[0] && a[0].type === 'StringLiteral') filters.push({ col: a[0].value.toLowerCase(), src: a[1] ? src.of(a[1]) : 'unknown' });
|
|
1704
|
+
}
|
|
1705
|
+
p = call;
|
|
1706
|
+
}
|
|
1707
|
+
const data = op === 'INSERT' || op === 'UPSERT' ? q.node.arguments[0] : null;
|
|
1708
|
+
const insertCols = [];
|
|
1709
|
+
if (data && data.type === 'ObjectExpression') for (const prop of data.properties) if (prop.key) insertCols.push({ col: (prop.key.name || prop.key.value || '').toLowerCase(), src: src.of(prop.value) });
|
|
1710
|
+
// which key the client was made with: the service role key skips row level security
|
|
1711
|
+
const key = clientKey(ctx, mod, from);
|
|
1712
|
+
const v = scopeVerdict(mod, line, { op, table }, filters, insertCols, key === 'service role' ? Object.assign(new Map(schema), { rls: new Set() }) : schema, 'supabase', !!(data && data.type !== 'ObjectExpression'));
|
|
1713
|
+
v.client = key;
|
|
1714
|
+
if (key === 'service role' && schema.rls && schema.rls.has(table)) v.scoping.serviceRole = 'row level security is on for ' + table + ', but this client uses the service role key, which skips it';
|
|
1715
|
+
return v;
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
/** The key a supabase client is made with: 'service role', 'anon' (row level security applies), or 'unknown'. */
|
|
1719
|
+
function clientKey(ctx, mod, fromNode) {
|
|
1720
|
+
let n = fromNode.callee.object;
|
|
1721
|
+
while (n && (n.type === 'MemberExpression' || n.type === 'CallExpression')) n = n.type === 'MemberExpression' ? n.object : n.callee;
|
|
1722
|
+
if (!n || n.type !== 'Identifier') return 'unknown';
|
|
1723
|
+
// the declaration of the client: a createClient(url, key) call, here or in a file it is imported from
|
|
1724
|
+
const decl = (name, m, depth = 0) => {
|
|
1725
|
+
if (depth > 4) return null;
|
|
1726
|
+
const b = m.program && findBinding(m, name);
|
|
1727
|
+
if (b && b.path.isVariableDeclarator() && b.path.node.init) return { init: b.path.node.init, mod: m };
|
|
1728
|
+
if (b && b.path.isFunctionDeclaration()) return { init: b.path.node, mod: m };
|
|
1729
|
+
const imp = m.imports.get(name);
|
|
1730
|
+
const abs = imp && ctx.resolveModule(m.abs, imp.source);
|
|
1731
|
+
const other = abs && ctx.load(abs);
|
|
1732
|
+
if (!other) return null;
|
|
1733
|
+
const e = other.exportsNamed.get(imp.imported === 'default' ? 'default' : imp.imported) || (imp.imported === 'default' && other.exportDefault);
|
|
1734
|
+
if (e && e.node && e.node.type === 'Identifier') return decl(e.node.name, other, depth + 1);
|
|
1735
|
+
if (e && e.node) return { init: e.node, mod: other };
|
|
1736
|
+
return null;
|
|
1737
|
+
};
|
|
1738
|
+
const d = decl(n.name, mod);
|
|
1739
|
+
if (!d) return 'unknown';
|
|
1740
|
+
const text = d.mod.source.slice(d.init.start, d.init.end);
|
|
1741
|
+
if (!/createClient|createServerClient|createRouteHandlerClient|createBrowserClient/.test(text)) return 'unknown';
|
|
1742
|
+
if (/SERVICE_ROLE|SERVICE_KEY|SECRET_KEY|sb_secret/i.test(text)) return 'service role';
|
|
1743
|
+
if (/ANON|PUBLISHABLE|anon/i.test(text)) return 'anon';
|
|
1744
|
+
return 'unknown';
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
function findBinding(mod, name) {
|
|
1748
|
+
let found = null;
|
|
1749
|
+
mod.program.traverse({
|
|
1750
|
+
VariableDeclarator(p) {
|
|
1751
|
+
if (!found && p.node.id.type === 'Identifier' && p.node.id.name === name) found = p.scope.getBinding(name);
|
|
1752
|
+
},
|
|
1753
|
+
FunctionDeclaration(p) {
|
|
1754
|
+
if (!found && p.node.id && p.node.id.name === name) found = p.parentPath.scope.getBinding(name);
|
|
1755
|
+
},
|
|
1756
|
+
});
|
|
1757
|
+
return found;
|
|
1758
|
+
}
|
|
1759
|
+
|
|
1760
|
+
function prismaOp(ctx, mod, q, chain, src, schema) {
|
|
1761
|
+
const line = q.node.loc.start.line;
|
|
1762
|
+
const model = chain[chain.length - 2];
|
|
1763
|
+
const op = PRISMA_OPS[chain[chain.length - 1]];
|
|
1764
|
+
const arg = q.node.arguments[0];
|
|
1765
|
+
const filters = [];
|
|
1766
|
+
const insertCols = [];
|
|
1767
|
+
const read = (obj, into) => {
|
|
1768
|
+
if (!obj || obj.type !== 'ObjectExpression') return false;
|
|
1769
|
+
for (const prop of obj.properties) {
|
|
1770
|
+
if (!prop.key) continue;
|
|
1771
|
+
const k = (prop.key.name || prop.key.value || '');
|
|
1772
|
+
if (prop.value && prop.value.type === 'ObjectExpression' && !/^(equals|in)$/.test(k)) {
|
|
1773
|
+
const eq = prop.value.properties.find((x) => x.key && (x.key.name === 'equals'));
|
|
1774
|
+
into.push({ col: k.toLowerCase().replace(/([a-z])([A-Z])/g, '$1_$2'), src: eq ? src.of(eq.value) : 'unknown' });
|
|
1775
|
+
} else into.push({ col: k.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase(), src: src.of(prop.value) });
|
|
1776
|
+
}
|
|
1777
|
+
return true;
|
|
1778
|
+
};
|
|
1779
|
+
let readable = !arg || arg.type === 'ObjectExpression';
|
|
1780
|
+
if (arg && arg.type === 'ObjectExpression') {
|
|
1781
|
+
for (const prop of arg.properties) {
|
|
1782
|
+
const k = prop.key && (prop.key.name || prop.key.value);
|
|
1783
|
+
if (k === 'where') readable = read(prop.value, filters) && readable;
|
|
1784
|
+
if (k === 'data') read(prop.value, insertCols);
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
const table = model.toLowerCase();
|
|
1788
|
+
return scopeVerdict(mod, line, { op, table }, filters, insertCols, schema, 'prisma', !readable);
|
|
1789
|
+
}
|
|
1790
|
+
|
|
1791
|
+
/** Whether calling `name(sql, params)` sends SQL: a function of the app that passes its first parameter to .query(). */
|
|
1792
|
+
function isQueryWrapper(ctx, mod, calleePath) {
|
|
1793
|
+
const r = resolveRef(ctx, mod, calleePath);
|
|
1794
|
+
if (r.kind !== 'fn') return false;
|
|
1795
|
+
const p0 = r.path.node.params[0];
|
|
1796
|
+
if (!p0 || p0.type !== 'Identifier') return false;
|
|
1797
|
+
let yes = false;
|
|
1798
|
+
r.path.traverse({
|
|
1799
|
+
CallExpression(q) {
|
|
1800
|
+
const chain = memberChain(q.node.callee) || [];
|
|
1801
|
+
if (SQL_CALLS.test(chain[chain.length - 1] || '') && chain.length >= 2 && ctx.t.isIdentifier(q.node.arguments[0], { name: p0.name })) yes = true;
|
|
1802
|
+
},
|
|
1803
|
+
});
|
|
1804
|
+
return yes;
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
/** One SQL statement's touch on one table, judged for scoping. */
|
|
1808
|
+
function judgeSql(ctx, mod, line, st, tx, paramsArg, src, schema, recordScopes) {
|
|
1809
|
+
// the values behind $1, $2..., and the row each one was read from, if any
|
|
1810
|
+
let values = null;
|
|
1811
|
+
let elements = null;
|
|
1812
|
+
if (paramsArg && paramsArg.tagged) elements = paramsArg.tagged.map((v) => v.node);
|
|
1813
|
+
else if (paramsArg) {
|
|
1814
|
+
const pa = unwrapTs(paramsArg);
|
|
1815
|
+
if (pa.isArrayExpression()) elements = pa.node.elements;
|
|
1816
|
+
else if (pa.isIdentifier()) {
|
|
1817
|
+
const b = pa.scope.getBinding(pa.node.name);
|
|
1818
|
+
const init = b && b.path.isVariableDeclarator() && b.path.node.init;
|
|
1819
|
+
if (init && init.type === 'ArrayExpression' && !b.constantViolations.length && !refersPush(b)) elements = init.elements;
|
|
1820
|
+
}
|
|
1821
|
+
} else elements = [];
|
|
1822
|
+
if (elements) values = elements.map((e) => (e ? src.of(e) : 'unknown'));
|
|
1823
|
+
const at = (ref) => {
|
|
1824
|
+
const m = /^\$(\d+)$/.exec(ref.trim());
|
|
1825
|
+
return m ? Number(m[1]) - 1 : -1;
|
|
1826
|
+
};
|
|
1827
|
+
const valueOf = (ref) => {
|
|
1828
|
+
const i = at(ref);
|
|
1829
|
+
if (i >= 0) return values && values[i] !== undefined ? values[i] : 'unknown';
|
|
1830
|
+
if (/auth\.uid\(\)|current_setting\(|auth\.jwt\(\)|current_user|session_user/i.test(ref)) return 'identity';
|
|
1831
|
+
if (/^'.*'$|^\d+$|^(true|false|null)$/i.test(ref.trim())) return 'literal';
|
|
1832
|
+
return 'unknown';
|
|
1833
|
+
};
|
|
1834
|
+
// a value taken from a row read earlier in the route: how was that row found?
|
|
1835
|
+
const rowOf = (ref) => {
|
|
1836
|
+
const i = at(ref);
|
|
1837
|
+
if (i < 0 || !elements || !elements[i] || !recordScopes) return null;
|
|
1838
|
+
const local = src.rootLocal(elements[i]);
|
|
1839
|
+
return local && recordScopes.has(local) ? recordScopes.get(local) : null;
|
|
1840
|
+
};
|
|
1841
|
+
const withRow = (col, ref) => {
|
|
1842
|
+
const f = { col, src: valueOf(ref) };
|
|
1843
|
+
const row = f.src === 'record' && rowOf(ref);
|
|
1844
|
+
if (row) f.row = row;
|
|
1845
|
+
return f;
|
|
1846
|
+
};
|
|
1847
|
+
const filters = [];
|
|
1848
|
+
if (st.where) {
|
|
1849
|
+
const re = /(?:\b(\w+)\.)?"?(\w+)"?\s*(=|\bin\b|=\s*any)\s*\(?\s*([$]\d+|auth\.uid\(\)|auth\.jwt\(\)[^)]*\)|current_setting\([^)]*\)(?:::\w+)?|'[^']*'|\d+)/gi;
|
|
1850
|
+
let m;
|
|
1851
|
+
while ((m = re.exec(st.where))) {
|
|
1852
|
+
const alias = m[1] && m[1].toLowerCase();
|
|
1853
|
+
if (alias && st.alias && alias !== st.alias && alias !== st.table) continue;
|
|
1854
|
+
filters.push(withRow(m[2].toLowerCase(), m[4]));
|
|
1855
|
+
}
|
|
1856
|
+
}
|
|
1857
|
+
const insertCols = (st.insertCols || []).map((c, i) => (st.insertVals && st.insertVals[i] ? withRow(c, st.insertVals[i]) : { col: c, src: 'unknown' }));
|
|
1858
|
+
const v = scopeVerdict(mod, line, st, filters, insertCols, schema, 'sql', tx.dynamic || values === null);
|
|
1859
|
+
// the values sent with the statement, kept off the printed map: the validation read asks which request fields reach a write
|
|
1860
|
+
Object.defineProperty(v, 'valueNodes', { value: elements || [], enumerable: false });
|
|
1861
|
+
if (st.joinedTo) v.joinedTo = st.joinedTo;
|
|
1862
|
+
return v;
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
/** A table reached through a JOIN is limited by whatever limits the table it is joined to. */
|
|
1866
|
+
function joinWith(list) {
|
|
1867
|
+
const main = list.find((x) => !x.joinedTo && x.op === 'SELECT');
|
|
1868
|
+
for (const x of list) {
|
|
1869
|
+
if (!x.joinedTo || !main) continue;
|
|
1870
|
+
x.scoping = Object.assign({}, main.scoping, { joined: true, why: 'reached through a join on ' + main.table + (main.scoping.why ? ' - ' + main.scoping.why : ''), evidence: main.scoping.evidence });
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
function refersPush(binding) {
|
|
1875
|
+
return binding.referencePaths.some((r) => r.parentPath.isMemberExpression() && /^(push|unshift|splice|concat)$/.test(r.parentPath.node.property.name || ''));
|
|
1876
|
+
}
|
|
1877
|
+
|
|
1878
|
+
function scopeVerdict(mod, line, st, filters, insertCols, schema, via, partlyUnread) {
|
|
1879
|
+
const table = st.table;
|
|
1880
|
+
const known = schema.get(table);
|
|
1881
|
+
const ev = (how) => ({ file: mod.rel, line, code: snippet(mod, line), how });
|
|
1882
|
+
const scopeCol = (c) => TENANT_COLS.test(c) || OWNER_COLS.test(c) || (TENANT_TABLES.test(table) && c === 'id');
|
|
1883
|
+
// whether the table says which organisation a row is in, or only which person: the words for a missing limit differ
|
|
1884
|
+
const level = known ? (Array.from(known).some((c) => TENANT_COLS.test(c)) || TENANT_TABLES.test(table) ? 'organisation' : Array.from(known).some((c) => OWNER_COLS.test(c)) ? 'owner' : null) : null;
|
|
1885
|
+
const base = { op: st.op, table, file: mod.rel, line, sql: snippet(mod, line), via: via === 'sql' ? undefined : via, level: level || undefined };
|
|
1886
|
+
const isInsert = st.op === 'INSERT' || (st.op === 'UPSERT' && !filters.length);
|
|
1887
|
+
// a row found by its id, where that id comes from a row read earlier: the earlier read decides
|
|
1888
|
+
const viaRow = (f) => f.src === 'record' && f.row && ((f.col === 'id' && f.row.table === table) || scopeCol(f.col));
|
|
1889
|
+
const all = isInsert ? insertCols : filters;
|
|
1890
|
+
// the organisation decides first: an owner column written right does not make up for an organisation taken from elsewhere
|
|
1891
|
+
const tenantList = all.filter((f) => TENANT_COLS.test(f.col) || (TENANT_TABLES.test(table) && f.col === 'id'));
|
|
1892
|
+
const list = tenantList.length ? Array.from(new Set(tenantList.concat(all.filter(viaRow)))) : all;
|
|
1893
|
+
const cols = (fs2) => Array.from(new Set(fs2.map((f) => f.col))).join(', ');
|
|
1894
|
+
const byIdentity = list.filter((f) => scopeCol(f.col) && f.src === 'identity');
|
|
1895
|
+
const byScopedRow = list.filter((f) => viaRow(f) && f.row.status === STATUS.DETECTED);
|
|
1896
|
+
const byClient = list.filter((f) => scopeCol(f.col) && f.src === 'client');
|
|
1897
|
+
const byOpenRow = list.filter((f) => viaRow(f) && f.row.status === STATUS.NOT);
|
|
1898
|
+
const hasScopeCol = known ? Array.from(known).some((c) => TENANT_COLS.test(c) || OWNER_COLS.test(c)) || TENANT_TABLES.test(table) : null;
|
|
1899
|
+
// the database may limit the rows itself; its rules are read by the database check, not here
|
|
1900
|
+
const rls = schema.rls && schema.rls.has(table);
|
|
1901
|
+
if (rls && !byIdentity.length && !byScopedRow.length) return Object.assign(base, { scoping: { status: STATUS.UNKNOWN, rls: true, why: 'row level security is on for ' + table + ': the database decides which rows - npx kryptheon-night reads those rules' } });
|
|
1902
|
+
if (byClient.length) {
|
|
1903
|
+
return Object.assign(base, { scoping: { status: STATUS.NOT, evidence: ev((isInsert ? 'writes ' : 'limited by ') + cols(byClient) + ' from a value the request sends'), clientChosen: true } });
|
|
1904
|
+
}
|
|
1905
|
+
if (byIdentity.length) {
|
|
1906
|
+
return Object.assign(base, { scoping: { status: STATUS.DETECTED, evidence: ev((isInsert ? 'writes ' : 'limited by ') + cols(byIdentity) + ' from the signed-in person') } });
|
|
1907
|
+
}
|
|
1908
|
+
if (byScopedRow.length) {
|
|
1909
|
+
const r = byScopedRow[0].row;
|
|
1910
|
+
return Object.assign(base, { scoping: { status: STATUS.DETECTED, evidence: ev((isInsert ? 'writes ' : 'limited by ') + cols(byScopedRow) + ' of a row read with the organisation limit at ' + r.file + ':' + r.line) } });
|
|
1911
|
+
}
|
|
1912
|
+
if (byOpenRow.length) {
|
|
1913
|
+
const r = byOpenRow[0].row;
|
|
1914
|
+
return Object.assign(base, { scoping: { status: STATUS.NOT, evidence: ev((isInsert ? 'writes ' : 'limited by ') + cols(byOpenRow) + ' of a row read without any organisation limit at ' + r.file + ':' + r.line), fromOpenRow: true } });
|
|
1915
|
+
}
|
|
1916
|
+
if (partlyUnread) return Object.assign(base, { scoping: { status: STATUS.UNKNOWN, why: 'part of the statement or its values is chosen at run time' } });
|
|
1917
|
+
if (hasScopeCol === false) return Object.assign(base, { scoping: { status: STATUS.NOT, applies: false, why: 'the table has no organisation or owner column' } });
|
|
1918
|
+
const unclear = list.filter((f) => scopeCol(f.col) && f.src !== 'literal');
|
|
1919
|
+
if (unclear.length) return Object.assign(base, { scoping: { status: STATUS.UNKNOWN, why: 'limited by ' + cols(unclear) + ', from a value whose source could not be told (' + unclear.map((f) => f.src).join(', ') + ')' } });
|
|
1920
|
+
if (hasScopeCol === null) {
|
|
1921
|
+
return Object.assign(base, { scoping: { status: STATUS.UNKNOWN, why: 'no schema was found for ' + table + ', so whether it has an organisation column is not known' } });
|
|
1922
|
+
}
|
|
1923
|
+
return Object.assign(base, { scoping: { status: STATUS.NOT, applies: true, why: (isInsert ? 'the row is written without an organisation or owner column' : 'no organisation or owner limit in the statement') } });
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1926
|
+
/** The handler of a route: the last element in front of it that is the app's own code. */
|
|
1927
|
+
function handlerOf(r) {
|
|
1928
|
+
for (let i = r.chain.length - 1; i >= 0; i--) if (r.chain[i].ref.kind === 'fn' && !r.chain[i].inherited) return r.chain[i].ref;
|
|
1929
|
+
return null;
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
// --- validation: what each route checks about what the request sends ------------------
|
|
1933
|
+
|
|
1934
|
+
const calledName = (n) => (n.callee && (n.callee.type === 'MemberExpression' || n.callee.type === 'OptionalMemberExpression') && !n.callee.computed ? n.callee.property.name : n.callee && n.callee.type === 'Identifier' ? n.callee.name : '');
|
|
1935
|
+
const CHECK_KINDS = [
|
|
1936
|
+
['enum', (n) => n.type === 'CallExpression' && /^(includes|has|indexOf)$/.test(calledName(n))],
|
|
1937
|
+
['format', (n) => n.type === 'CallExpression' && /^(test|match|isEmail|isURL|isUUID|isISO8601|isMobilePhone|isDate|validate)$/.test(calledName(n))],
|
|
1938
|
+
['type', (n) => n.type === 'CallExpression' && /^(isFinite|isInteger|isSafeInteger|isNaN|isArray)$/.test(calledName(n)) || (n.type === 'UnaryExpression' && n.operator === 'typeof')],
|
|
1939
|
+
['length', (n) => (n.type === 'MemberExpression' || n.type === 'OptionalMemberExpression') && !n.computed && n.property.name === 'length'],
|
|
1940
|
+
['range', (n) => n.type === 'BinaryExpression' && /^[<>]=?$/.test(n.operator)],
|
|
1941
|
+
['required', () => true],
|
|
1942
|
+
];
|
|
1943
|
+
const SCHEMA_CALLS = /^(parse|safeParse|parseAsync|safeParseAsync|validate|validateAsync|assert|is|create)$/;
|
|
1944
|
+
|
|
1945
|
+
/**
|
|
1946
|
+
* The request fields a handler reads, and the checks it makes on each before
|
|
1947
|
+
* answering: { fields: [{ name, from, checks, status, reachesWrite }], schemas }.
|
|
1948
|
+
* A field with a check that turns the request away (400, a redirect back, a
|
|
1949
|
+
* throw) is guard_detected; a field read with none in a handler read in full is
|
|
1950
|
+
* not_detected; a field handed to code that could not be followed is unknown.
|
|
1951
|
+
*/
|
|
1952
|
+
function readValidation(ctx, fnRef, elements, db) {
|
|
1953
|
+
const t = ctx.t;
|
|
1954
|
+
const fn = fnRef.path;
|
|
1955
|
+
const mod = fnRef.mod;
|
|
1956
|
+
const params = fn.node.params;
|
|
1957
|
+
const reqName = params[0] && params[0].type === 'Identifier' ? params[0].name : null;
|
|
1958
|
+
const resName = params[1] && params[1].type === 'Identifier' ? params[1].name : null;
|
|
1959
|
+
const fields = new Map();
|
|
1960
|
+
const localField = new Map(); // const title = String(req.body.title || '') -> body.title
|
|
1961
|
+
const key = (from, name) => from + '.' + name;
|
|
1962
|
+
// a Next route handler gets its URL parameters beside the request: GET(req, { params }) or GET(req, context)
|
|
1963
|
+
const second = params[1];
|
|
1964
|
+
const paramsLocal = second && second.type === 'ObjectPattern' ? (second.properties.find((p) => p.key && p.key.name === 'params' && p.value.type === 'Identifier') || {}).value : null;
|
|
1965
|
+
const contextName = second && second.type === 'Identifier' && /^(context|ctx|props|route|segment)/i.test(second.name) ? second.name : null;
|
|
1966
|
+
const fieldOfChain = (chain) => {
|
|
1967
|
+
if (!chain) return null;
|
|
1968
|
+
if (paramsLocal && chain[0] === paramsLocal.name && chain[1]) return { from: 'params', name: chain[1] };
|
|
1969
|
+
if (contextName && chain[0] === contextName && chain[1] === 'params' && chain[2]) return { from: 'params', name: chain[2] };
|
|
1970
|
+
if (!reqName || chain[0] !== reqName || !/^(body|query|params)$/.test(chain[1] || '') || !chain[2]) return null;
|
|
1971
|
+
return { from: chain[1], name: chain[2] };
|
|
1972
|
+
};
|
|
1973
|
+
// searchParams.get('page'), req.nextUrl.searchParams.get('page'): a query field
|
|
1974
|
+
const queryGet = (n) => {
|
|
1975
|
+
if (!n || n.type !== 'CallExpression' || calledName(n) !== 'get' || !n.arguments[0] || n.arguments[0].type !== 'StringLiteral' || n.callee.type !== 'MemberExpression') return null;
|
|
1976
|
+
const obj = memberChain(n.callee.object) || [];
|
|
1977
|
+
return obj[obj.length - 1] === 'searchParams' ? { from: 'query', name: n.arguments[0].value } : null;
|
|
1978
|
+
};
|
|
1979
|
+
const fieldsIn = (node) => {
|
|
1980
|
+
const out = [];
|
|
1981
|
+
const visit = (n) => {
|
|
1982
|
+
if (!n || typeof n !== 'object') return;
|
|
1983
|
+
if (Array.isArray(n)) return n.forEach(visit);
|
|
1984
|
+
if (n.type === 'MemberExpression' || n.type === 'OptionalMemberExpression') {
|
|
1985
|
+
const f = fieldOfChain(memberChain(n));
|
|
1986
|
+
if (f) return out.push(f);
|
|
1987
|
+
}
|
|
1988
|
+
if (n.type === 'Identifier' && localField.has(n.name)) return out.push(localField.get(n.name));
|
|
1989
|
+
const qg = queryGet(n);
|
|
1990
|
+
if (qg) return out.push(qg);
|
|
1991
|
+
if (n.type === 'ArrowFunctionExpression' || n.type === 'FunctionExpression') return;
|
|
1992
|
+
for (const k of Object.keys(n)) if (k !== 'loc' && k !== 'start' && k !== 'end') visit(n[k]);
|
|
1993
|
+
};
|
|
1994
|
+
visit(node);
|
|
1995
|
+
return out;
|
|
1996
|
+
};
|
|
1997
|
+
const note = (f, line) => {
|
|
1998
|
+
const k = key(f.from, f.name);
|
|
1999
|
+
if (!fields.has(k)) fields.set(k, { name: f.name, from: f.from, line, checks: [] });
|
|
2000
|
+
return fields.get(k);
|
|
2001
|
+
};
|
|
2002
|
+
const bodyAlias = new Set(); // const b = req.body; b.status
|
|
2003
|
+
fn.traverse({
|
|
2004
|
+
VariableDeclarator(q) {
|
|
2005
|
+
const id = q.node.id;
|
|
2006
|
+
const init = q.node.init;
|
|
2007
|
+
if (!init) return;
|
|
2008
|
+
let chain = memberChain(init.type === 'TSAsExpression' ? init.expression : init);
|
|
2009
|
+
// await req.json() / await req.formData() in a Fetch-style handler is the body
|
|
2010
|
+
const awaited = init.type === 'AwaitExpression' ? init.argument : init;
|
|
2011
|
+
if (!chain && awaited.type === 'CallExpression' && reqName) {
|
|
2012
|
+
const c = memberChain(awaited.callee) || [];
|
|
2013
|
+
if (c[0] === reqName && /^(json|formData)$/.test(c[1] || '') && c.length === 2) chain = [reqName, 'body'];
|
|
2014
|
+
}
|
|
2015
|
+
// const { title, price = 0 } = req.body
|
|
2016
|
+
if (t.isObjectPattern(id) && chain && reqName && chain[0] === reqName && /^(body|query|params)$/.test(chain[1] || '') && chain.length === 2) {
|
|
2017
|
+
for (const prop of id.properties) {
|
|
2018
|
+
if (prop.type !== 'ObjectProperty') continue;
|
|
2019
|
+
const name = prop.key.name || prop.key.value;
|
|
2020
|
+
const local = prop.value.type === 'AssignmentPattern' ? prop.value.left : prop.value;
|
|
2021
|
+
if (local.type === 'Identifier') {
|
|
2022
|
+
localField.set(local.name, { from: chain[1], name });
|
|
2023
|
+
note({ from: chain[1], name }, q.node.loc.start.line);
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
return;
|
|
2027
|
+
}
|
|
2028
|
+
if (t.isIdentifier(id) && chain && reqName && chain[0] === reqName && /^(body|query|params)$/.test(chain[1] || '') && chain.length === 2) {
|
|
2029
|
+
bodyAlias.add(id.name);
|
|
2030
|
+
localField.set('\u0000' + id.name, chain[1]);
|
|
2031
|
+
return;
|
|
2032
|
+
}
|
|
2033
|
+
if (t.isIdentifier(id)) {
|
|
2034
|
+
const fs2 = fieldsIn(init);
|
|
2035
|
+
if (fs2.length === 1 && reshapes(init)) {
|
|
2036
|
+
localField.set(id.name, fs2[0]);
|
|
2037
|
+
// Math.min(100, Math.max(1, Number(req.query.limit))): kept in bounds rather than turned away
|
|
2038
|
+
if (clamps(init)) note(fs2[0], q.node.loc.start.line).checks.push({ kind: 'clamped', file: mod.rel, line: q.node.loc.start.line, code: snippet(mod, q.node.loc.start.line) });
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
},
|
|
2042
|
+
});
|
|
2043
|
+
// b.status where const b = req.body
|
|
2044
|
+
const aliasField = (n) => {
|
|
2045
|
+
const chain = (n.type === 'MemberExpression' || n.type === 'OptionalMemberExpression') && memberChain(n);
|
|
2046
|
+
return chain && bodyAlias.has(chain[0]) && chain[1] ? { from: localField.get('\u0000' + chain[0]), name: chain[1] } : null;
|
|
2047
|
+
};
|
|
2048
|
+
const allFields = (node) => {
|
|
2049
|
+
const out = fieldsIn(node);
|
|
2050
|
+
const visit = (n) => {
|
|
2051
|
+
if (!n || typeof n !== 'object') return;
|
|
2052
|
+
if (Array.isArray(n)) return n.forEach(visit);
|
|
2053
|
+
const a = aliasField(n);
|
|
2054
|
+
if (a) return out.push(a);
|
|
2055
|
+
if (n.type === 'ArrowFunctionExpression' || n.type === 'FunctionExpression') return;
|
|
2056
|
+
for (const k of Object.keys(n)) if (k !== 'loc' && k !== 'start' && k !== 'end') visit(n[k]);
|
|
2057
|
+
};
|
|
2058
|
+
visit(node);
|
|
2059
|
+
return out;
|
|
2060
|
+
};
|
|
2061
|
+
// every field the handler reads
|
|
2062
|
+
fn.traverse({
|
|
2063
|
+
MemberExpression(q) {
|
|
2064
|
+
const f = fieldOfChain(memberChain(q.node)) || aliasField(q.node);
|
|
2065
|
+
if (f) note(f, q.node.loc.start.line);
|
|
2066
|
+
},
|
|
2067
|
+
CallExpression(q) {
|
|
2068
|
+
const f = queryGet(q.node);
|
|
2069
|
+
if (f) note(f, q.node.loc.start.line);
|
|
2070
|
+
},
|
|
2071
|
+
});
|
|
2072
|
+
// checks: a test on a field whose branch turns the request away
|
|
2073
|
+
const rejects = (node) => {
|
|
2074
|
+
let hit = false;
|
|
2075
|
+
const visit = (n) => {
|
|
2076
|
+
if (!n || hit || typeof n !== 'object') return;
|
|
2077
|
+
if (Array.isArray(n)) return n.forEach(visit);
|
|
2078
|
+
if (n.type === 'ThrowStatement' || isErrorResponse(n)) hit = true;
|
|
2079
|
+
if (n.type === 'CallExpression' || n.type === 'OptionalCallExpression') {
|
|
2080
|
+
let c = n.callee;
|
|
2081
|
+
while (c && (c.type === 'MemberExpression' || c.type === 'OptionalMemberExpression')) c = c.object;
|
|
2082
|
+
const root = c && (c.type === 'CallExpression' ? memberChain(c.callee) : c.type === 'Identifier' ? [c.name] : null);
|
|
2083
|
+
const chain = memberChain(n.callee) || [];
|
|
2084
|
+
if (resName && ((root && root[0] === resName) || chain[0] === resName)) hit = true;
|
|
2085
|
+
}
|
|
2086
|
+
if (n.type === 'ArrowFunctionExpression' || n.type === 'FunctionExpression') return;
|
|
2087
|
+
for (const k of Object.keys(n)) if (k !== 'loc') visit(n[k]);
|
|
2088
|
+
};
|
|
2089
|
+
visit(node);
|
|
2090
|
+
return hit;
|
|
2091
|
+
};
|
|
2092
|
+
const rejectsHere = (stmt) => (stmt.type === 'BlockStatement' ? stmt.body.some((x) => x.type !== 'IfStatement' && x.type !== 'ForStatement' && x.type !== 'ForOfStatement' && x.type !== 'WhileStatement' && x.type !== 'TryStatement' && rejects(x)) : stmt.type !== 'IfStatement' && rejects(stmt));
|
|
2093
|
+
const kindsOf = (test, f) => {
|
|
2094
|
+
// every kind of check the test makes on this field: !Number.isFinite(x) || x < 0 is a type and a range check
|
|
2095
|
+
const found = new Set();
|
|
2096
|
+
const visit = (n) => {
|
|
2097
|
+
if (!n || typeof n !== 'object') return;
|
|
2098
|
+
if (Array.isArray(n)) return n.forEach(visit);
|
|
2099
|
+
const mentions = allFields(n).some((x) => x.name === f.name && x.from === f.from);
|
|
2100
|
+
if (!mentions) return;
|
|
2101
|
+
for (const [k, test2] of CHECK_KINDS.slice(0, 5)) if (test2(n)) found.add(k);
|
|
2102
|
+
for (const k2 of Object.keys(n)) if (k2 !== 'loc') visit(n[k2]);
|
|
2103
|
+
};
|
|
2104
|
+
visit(test);
|
|
2105
|
+
return found.size ? CHECK_KINDS.map((c) => c[0]).filter((k) => found.has(k)) : ['required'];
|
|
2106
|
+
};
|
|
2107
|
+
const consider = (test, at) => {
|
|
2108
|
+
for (const f of allFields(test)) {
|
|
2109
|
+
const entry = note(f, at.loc.start.line);
|
|
2110
|
+
for (const kind of kindsOf(test, f)) {
|
|
2111
|
+
if (entry.checks.some((c) => c.line === at.loc.start.line && c.kind === kind)) continue;
|
|
2112
|
+
const c = { kind, file: mod.rel, line: at.loc.start.line, code: snippet(mod, at.loc.start.line) };
|
|
2113
|
+
// ['standard', 'express'].includes(service): the values it allows, so a test can send one that passes
|
|
2114
|
+
if (kind === 'enum') {
|
|
2115
|
+
const values = [];
|
|
2116
|
+
const visit = (n) => {
|
|
2117
|
+
if (!n || typeof n !== 'object') return;
|
|
2118
|
+
if (Array.isArray(n)) return n.forEach(visit);
|
|
2119
|
+
if (n.type === 'CallExpression' && calledName(n) === 'includes' && n.callee.object && n.callee.object.type === 'ArrayExpression') {
|
|
2120
|
+
for (const e of n.callee.object.elements) if (e && (e.type === 'StringLiteral' || e.type === 'NumericLiteral')) values.push(e.value);
|
|
2121
|
+
}
|
|
2122
|
+
for (const k of Object.keys(n)) if (k !== 'loc') visit(n[k]);
|
|
2123
|
+
};
|
|
2124
|
+
visit(test);
|
|
2125
|
+
if (values.length) c.values = values;
|
|
2126
|
+
}
|
|
2127
|
+
entry.checks.push(c);
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
};
|
|
2131
|
+
fn.traverse({
|
|
2132
|
+
IfStatement(q) {
|
|
2133
|
+
if (rejectsHere(q.node.consequent) || (q.node.alternate && rejectsHere(q.node.alternate))) consider(q.node.test, q.node);
|
|
2134
|
+
},
|
|
2135
|
+
ConditionalExpression(q) {
|
|
2136
|
+
if (rejects(q.node.consequent) !== rejects(q.node.alternate)) consider(q.node.test, q.node);
|
|
2137
|
+
},
|
|
2138
|
+
});
|
|
2139
|
+
// schemas: listQuery.parse(req.query) / schema.safeParse(req.body)
|
|
2140
|
+
const schemas = [];
|
|
2141
|
+
fn.traverse({
|
|
2142
|
+
CallExpression(q) {
|
|
2143
|
+
const chain = memberChain(q.node.callee) || [];
|
|
2144
|
+
if (!SCHEMA_CALLS.test(chain[chain.length - 1] || '') || chain.length < 2) return;
|
|
2145
|
+
const arg = q.node.arguments[0];
|
|
2146
|
+
const argChain = arg && memberChain(arg);
|
|
2147
|
+
if (!argChain || argChain[0] !== reqName || !/^(body|query|params)$/.test(argChain[1] || '')) return;
|
|
2148
|
+
const from = argChain[1];
|
|
2149
|
+
const line = q.node.loc.start.line;
|
|
2150
|
+
// the schema is a value built by a library (z.object(...)): read where it is declared, here or in the file it is imported from
|
|
2151
|
+
const declared = (p, m, depth = 0) => {
|
|
2152
|
+
if (depth > 4 || !p.isIdentifier()) return null;
|
|
2153
|
+
const b = p.scope.getBinding(p.node.name);
|
|
2154
|
+
if (!b) return null;
|
|
2155
|
+
if (b.path.isVariableDeclarator() && b.path.node.init) return { node: b.path.node.init, mod: m };
|
|
2156
|
+
const imp = m.imports.get(p.node.name);
|
|
2157
|
+
const abs = imp && ctx.resolveModule(m.abs, imp.source);
|
|
2158
|
+
const other = abs && ctx.load(abs);
|
|
2159
|
+
const e = other && other.exportsNamed.get(imp.imported);
|
|
2160
|
+
return e && e.node && e.node.type !== 'VariableDeclaration' ? { node: e.node, mod: other } : null;
|
|
2161
|
+
};
|
|
2162
|
+
const at2 = declared(q.get('callee.object'), mod);
|
|
2163
|
+
const obj = at2 ? { kind: 'value', path: { node: at2.node }, mod: at2.mod } : resolveRef(ctx, mod, q.get('callee.object'));
|
|
2164
|
+
const keysOf = obj.kind === 'value' ? schemaKeys(t, obj.path.node) : null;
|
|
2165
|
+
schemas.push({ from, file: mod.rel, line, code: snippet(mod, line), fields: keysOf ? keysOf.map((k) => k.name) : null, why: keysOf ? null : 'the schema could not be read' });
|
|
2166
|
+
if (keysOf) for (const k of keysOf) note({ from, name: k.name }, line).checks.push({ kind: 'schema', file: obj.mod.rel, line: k.line, code: snippet(obj.mod, k.line) });
|
|
2167
|
+
else for (const e of fields.values()) if (e.from === from && !e.checks.length) e.schemaUnread = { file: mod.rel, line };
|
|
2168
|
+
},
|
|
2169
|
+
});
|
|
2170
|
+
// which fields reach a write
|
|
2171
|
+
const writes = (db || []).filter((d) => d.op !== 'SELECT' && d.op !== '?');
|
|
2172
|
+
for (const d of writes) for (const node of d.valueNodes || []) for (const f of node ? allFields(node) : []) {
|
|
2173
|
+
const e = note(f, d.line);
|
|
2174
|
+
if (!e.reachesWrite) e.reachesWrite = [];
|
|
2175
|
+
if (!e.reachesWrite.some((w) => w.line === d.line && w.table === d.table)) e.reachesWrite.push({ op: d.op, table: d.table, file: d.file, line: d.line });
|
|
2176
|
+
}
|
|
2177
|
+
// middleware with checks from express-validator: body('email').isEmail()
|
|
2178
|
+
for (const el of elements || []) {
|
|
2179
|
+
if (el.kind === 'package' && /express-validator|celebrate|joi/.test(el.source || '')) schemas.push({ from: 'body', file: el.usedFile, line: el.usedLine, code: el.name, fields: null, why: 'checked by ' + el.source + ' middleware (its rules are not read)' });
|
|
2180
|
+
}
|
|
2181
|
+
const unread = (elements || []).some((e) => e.kind === 'package' && /express-validator|celebrate|joi/.test(e.source || ''));
|
|
2182
|
+
const out = Array.from(fields.values()).map((e) => {
|
|
2183
|
+
let status = e.checks.length ? STATUS.DETECTED : (e.schemaUnread || unread ? STATUS.UNKNOWN : STATUS.NOT);
|
|
2184
|
+
return { name: e.name, from: e.from, line: e.line, file: mod.rel, status, checks: e.checks, reachesWrite: e.reachesWrite || [], why: status === STATUS.UNKNOWN ? 'checked by a schema or middleware whose rules are not read' : null };
|
|
2185
|
+
});
|
|
2186
|
+
return { fields: out.sort((a, b) => a.line - b.line), schemas };
|
|
2187
|
+
}
|
|
2188
|
+
|
|
2189
|
+
/** The keys of z.object({...}) / Joi.object({...}) / yup.object({...}), with their lines. */
|
|
2190
|
+
/** Whether an expression only reshapes a value - converts, trims, defaults, bounds it - and looks nothing up. */
|
|
2191
|
+
function reshapes(node) {
|
|
2192
|
+
let ok = true;
|
|
2193
|
+
const visit = (n) => {
|
|
2194
|
+
if (!ok || !n || typeof n !== 'object') return;
|
|
2195
|
+
if (Array.isArray(n)) return n.forEach(visit);
|
|
2196
|
+
if (n.type === 'AwaitExpression' || n.type === 'NewExpression' || n.type === 'ArrowFunctionExpression' || n.type === 'FunctionExpression') {
|
|
2197
|
+
ok = false;
|
|
2198
|
+
return;
|
|
2199
|
+
}
|
|
2200
|
+
if (n.type === 'CallExpression' || n.type === 'OptionalCallExpression') {
|
|
2201
|
+
const name = calledName(n);
|
|
2202
|
+
const chain = memberChain(n.callee) || [];
|
|
2203
|
+
// searchParams.get('page') reads the field, it looks nothing up
|
|
2204
|
+
if (name === 'get' && n.callee.type === 'MemberExpression' && (memberChain(n.callee.object) || []).slice(-1)[0] === 'searchParams') {
|
|
2205
|
+
for (const k of Object.keys(n)) if (k !== 'loc') visit(n[k]);
|
|
2206
|
+
return;
|
|
2207
|
+
}
|
|
2208
|
+
if (!/^(String|Number|Boolean|parseInt|parseFloat|BigInt|trim|trimStart|trimEnd|toLowerCase|toUpperCase|toString|slice|substring|split|join|replace|min|max|round|floor|ceil|abs|toFixed|normalize|parse)$/.test(name) || (name === 'parse' && chain[0] !== 'JSON')) {
|
|
2209
|
+
ok = false;
|
|
2210
|
+
return;
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
for (const k of Object.keys(n)) if (k !== 'loc') visit(n[k]);
|
|
2214
|
+
};
|
|
2215
|
+
visit(node);
|
|
2216
|
+
return ok;
|
|
2217
|
+
}
|
|
2218
|
+
|
|
2219
|
+
function clamps(node) {
|
|
2220
|
+
let hit = false;
|
|
2221
|
+
const visit = (n) => {
|
|
2222
|
+
if (hit || !n || typeof n !== 'object') return;
|
|
2223
|
+
if (Array.isArray(n)) return n.forEach(visit);
|
|
2224
|
+
if (n.type === 'CallExpression' && (memberChain(n.callee) || []).join('.').match(/^Math\.(min|max)$/)) hit = true;
|
|
2225
|
+
for (const k of Object.keys(n)) if (k !== 'loc') visit(n[k]);
|
|
2226
|
+
};
|
|
2227
|
+
visit(node);
|
|
2228
|
+
return hit;
|
|
2229
|
+
}
|
|
2230
|
+
|
|
2231
|
+
function schemaKeys(t, node) {
|
|
2232
|
+
let n = node;
|
|
2233
|
+
// z.object({...}).strict() / .partial(): walk down to the object call
|
|
2234
|
+
while (n && n.type === 'CallExpression' && n.callee.type === 'MemberExpression' && !(n.arguments[0] && n.arguments[0].type === 'ObjectExpression' && /^(object|strictObject|looseObject|keys)$/.test(n.callee.property.name))) n = n.callee.object;
|
|
2235
|
+
if (!n || n.type !== 'CallExpression' || !n.arguments[0] || n.arguments[0].type !== 'ObjectExpression') return null;
|
|
2236
|
+
return n.arguments[0].properties.filter((p) => p.key).map((p) => ({ name: p.key.name || p.key.value, line: p.loc.start.line }));
|
|
2237
|
+
}
|
|
2238
|
+
|
|
2239
|
+
// --- background jobs ------------------------------------------------------------
|
|
2240
|
+
|
|
2241
|
+
/**
|
|
2242
|
+
* Code that runs on a timer or a queue, not on a request: setInterval,
|
|
2243
|
+
* node-cron, node-schedule, cron's CronJob, bull and bullmq workers, agenda,
|
|
2244
|
+
* Deno.cron. Each with its schedule, its file and line, and its database statements.
|
|
2245
|
+
*/
|
|
2246
|
+
function findJobs(ctx, schema) {
|
|
2247
|
+
const t = ctx.t;
|
|
2248
|
+
const jobs = [];
|
|
2249
|
+
for (const mod of ctx.modules.values()) {
|
|
2250
|
+
if (!mod) continue;
|
|
2251
|
+
const consider = (p, kind, schedule, fnArg) => {
|
|
2252
|
+
const r = fnArg ? resolveRef(ctx, mod, fnArg) : { kind: 'unknown', why: 'no function given' };
|
|
2253
|
+
const line = p.node.loc.start.line;
|
|
2254
|
+
const job = { kind, schedule, file: mod.rel, line, code: snippet(mod, line) };
|
|
2255
|
+
if (r.kind === 'fn') {
|
|
2256
|
+
job.handler = { file: r.mod.rel, line: r.path.node.loc.start.line };
|
|
2257
|
+
job.db = readDb(ctx, r, schema, { reqName: null });
|
|
2258
|
+
} else {
|
|
2259
|
+
job.db = [];
|
|
2260
|
+
job.why = 'its function could not be followed: ' + r.why;
|
|
2261
|
+
ctx.notRead.push({ file: mod.rel, line, what: 'a ' + kind + ' job whose function could not be followed: ' + r.why, pattern: 'job' });
|
|
2262
|
+
}
|
|
2263
|
+
jobs.push(job);
|
|
2264
|
+
};
|
|
2265
|
+
const text = (a) => (a && (a.type === 'StringLiteral' ? a.value : a.type === 'NumericLiteral' ? String(a.value) + ' ms' : a.type === 'TemplateLiteral' && !a.expressions.length ? a.quasis[0].value.cooked : null));
|
|
2266
|
+
for (const call of mod.calls) {
|
|
2267
|
+
const chain = memberChain(call.node.callee) || [];
|
|
2268
|
+
const args = call.get('arguments');
|
|
2269
|
+
const a = call.node.arguments;
|
|
2270
|
+
const last = chain[chain.length - 1];
|
|
2271
|
+
if (chain.length === 1 && last === 'setInterval' && args[0]) consider(call, 'timer', text(a[1]) || 'an interval set at run time', args[0]);
|
|
2272
|
+
else if (chain.length === 2 && chain[1] === 'schedule' && /cron/i.test(chain[0]) && args[1]) consider(call, 'cron', text(a[0]), args[1]);
|
|
2273
|
+
else if (chain.length === 2 && chain[1] === 'scheduleJob' && args.length >= 2) consider(call, 'cron', text(a[0]), args[args.length - 1]);
|
|
2274
|
+
else if (chain.join('.') === 'Deno.cron' && args.length >= 3) consider(call, 'cron', text(a[1]), args[2]);
|
|
2275
|
+
else if (chain.length === 2 && chain[1] === 'define' && /agenda/i.test(chain[0]) && args.length >= 2) consider(call, 'queue', text(a[0]), args[args.length - 1]);
|
|
2276
|
+
else if (chain.length === 2 && chain[1] === 'process' && /queue/i.test(chain[0]) && args.length >= 1) consider(call, 'queue', chain[0], args[args.length - 1]);
|
|
2277
|
+
}
|
|
2278
|
+
mod.program.traverse({
|
|
2279
|
+
NewExpression(q) {
|
|
2280
|
+
const name = (memberChain(q.node.callee) || []).join('.');
|
|
2281
|
+
const args = q.get('arguments');
|
|
2282
|
+
if (/(^|\.)Worker$/.test(name) && args.length >= 2 && (t.isStringLiteral(q.node.arguments[0]) || t.isIdentifier(q.node.arguments[0]))) {
|
|
2283
|
+
const imp = Array.from(mod.imports.values()).some((i) => /^bullmq$|^bull$/.test(i.source)) || /bullmq|bull/.test(mod.source.slice(0, 2000));
|
|
2284
|
+
if (imp) consider(q, 'queue', text(q.node.arguments[0]) || 'a queue', args[1]);
|
|
2285
|
+
} else if (/(^|\.)CronJob$/.test(name) && args.length >= 2) consider(q, 'cron', text(q.node.arguments[0]), args[1]);
|
|
2286
|
+
},
|
|
2287
|
+
});
|
|
2288
|
+
}
|
|
2289
|
+
return jobs;
|
|
2290
|
+
}
|
|
2291
|
+
|
|
2292
|
+
// --- Supabase Edge Functions ----------------------------------------------------
|
|
2293
|
+
|
|
2294
|
+
const EDGE_FILE = /(^|\/)supabase\/functions\/([^/_.][^/]*)\/index\.(ts|js|mts|mjs|tsx|jsx)$/;
|
|
2295
|
+
|
|
2296
|
+
/** verify_jwt per function from supabase/config.toml: false when the platform lets any request in. */
|
|
2297
|
+
function edgeJwtSettings(root) {
|
|
2298
|
+
const out = new Map();
|
|
2299
|
+
let text = '';
|
|
2300
|
+
try {
|
|
2301
|
+
text = fs.readFileSync(path.join(root, 'supabase', 'config.toml'), 'utf8');
|
|
2302
|
+
} catch (err) {
|
|
2303
|
+
return out;
|
|
2304
|
+
}
|
|
2305
|
+
let current = null;
|
|
2306
|
+
for (const line of text.split(/\r?\n/)) {
|
|
2307
|
+
const sec = /^\s*\[functions\.([^\]]+)\]\s*$/.exec(line);
|
|
2308
|
+
if (sec) {
|
|
2309
|
+
current = sec[1].replace(/["']/g, '');
|
|
2310
|
+
continue;
|
|
2311
|
+
}
|
|
2312
|
+
if (/^\s*\[/.test(line)) current = null;
|
|
2313
|
+
const v = /^\s*verify_jwt\s*=\s*(true|false)/.exec(line);
|
|
2314
|
+
if (current && v) out.set(current, v[1] === 'true');
|
|
2315
|
+
}
|
|
2316
|
+
return out;
|
|
2317
|
+
}
|
|
2318
|
+
|
|
2319
|
+
/**
|
|
2320
|
+
* Each function in supabase/functions/<name>/index.ts, as a route the way the
|
|
2321
|
+
* platform serves it: /functions/v1/<name>, every method unless the code turns
|
|
2322
|
+
* other methods away. Read with the same guard, database and validation reads
|
|
2323
|
+
* as an Express handler.
|
|
2324
|
+
*/
|
|
2325
|
+
function edgeRoutes(ctx, root, schema) {
|
|
2326
|
+
const t = ctx.t;
|
|
2327
|
+
const jwt = edgeJwtSettings(root);
|
|
2328
|
+
const routes = [];
|
|
2329
|
+
for (const mod of ctx.modules.values()) {
|
|
2330
|
+
if (!mod) continue;
|
|
2331
|
+
const m = EDGE_FILE.exec(mod.rel);
|
|
2332
|
+
if (!m) continue;
|
|
2333
|
+
const name = m[2];
|
|
2334
|
+
// the handler: Deno.serve(fn), Deno.serve(options, fn), serve(fn) from the standard library, export default { fetch }
|
|
2335
|
+
let handler = null;
|
|
2336
|
+
let at = null;
|
|
2337
|
+
for (const call of mod.calls) {
|
|
2338
|
+
const chain = memberChain(call.node.callee) || [];
|
|
2339
|
+
const isServe = chain.join('.') === 'Deno.serve' || (chain.length === 1 && chain[0] === 'serve' && Array.from(mod.imports.values()).some((i) => /std(@[^/]*)?\/http|deno\.land\/std/.test(i.source)));
|
|
2340
|
+
if (!isServe) continue;
|
|
2341
|
+
const args = call.get('arguments');
|
|
2342
|
+
const fnArg = args.slice().reverse().find((a) => !a.isObjectExpression());
|
|
2343
|
+
if (fnArg) {
|
|
2344
|
+
const r = resolveRef(ctx, mod, fnArg);
|
|
2345
|
+
at = call.node.loc.start.line;
|
|
2346
|
+
if (r.kind === 'fn') handler = r;
|
|
2347
|
+
else ctx.notRead.push({ file: mod.rel, line: at, what: 'the edge function ' + name + ' serves something that could not be followed: ' + (r.why || (memberChain(fnArg.node) || []).join('.')), pattern: 'edge-handler' });
|
|
2348
|
+
}
|
|
2349
|
+
}
|
|
2350
|
+
if (!handler && !at) {
|
|
2351
|
+
ctx.notRead.push({ file: mod.rel, line: 1, what: 'the edge function ' + name + ' has no Deno.serve() handler this map could find', pattern: 'edge-handler' });
|
|
2352
|
+
continue;
|
|
2353
|
+
}
|
|
2354
|
+
if (!handler) continue;
|
|
2355
|
+
// the methods it answers: if (req.method !== 'POST') return new Response(..., { status: 405 })
|
|
2356
|
+
const reqName = handler.path.node.params[0] && handler.path.node.params[0].type === 'Identifier' ? handler.path.node.params[0].name : null;
|
|
2357
|
+
void reqName;
|
|
2358
|
+
const element = readElement(ctx, { ref: handler, mod, line: at, text: name + ' handler', inherited: false });
|
|
2359
|
+
const methods = (element.guards && element.guards.methods) || new Set();
|
|
2360
|
+
const g = judge({}, [element]);
|
|
2361
|
+
const db = readDb(ctx, handler, schema);
|
|
2362
|
+
const validation = readValidation(ctx, handler, [element], db);
|
|
2363
|
+
// true / false from supabase/config.toml; null when it does not say (a deploy flag like --no-verify-jwt is not in the code)
|
|
2364
|
+
const verify = jwt.has(name) ? jwt.get(name) : null;
|
|
2365
|
+
routes.push({
|
|
2366
|
+
method: methods.size === 1 ? Array.from(methods)[0] : 'ANY',
|
|
2367
|
+
methods: methods.size > 1 ? Array.from(methods).sort() : undefined,
|
|
2368
|
+
path: '/functions/v1/' + name,
|
|
2369
|
+
file: mod.rel,
|
|
2370
|
+
line: at,
|
|
2371
|
+
framework: 'supabase-edge',
|
|
2372
|
+
unmounted: false,
|
|
2373
|
+
orderAcrossFiles: false,
|
|
2374
|
+
middleware: [{ name: element.text, kind: element.kind, file: element.file || null, line: element.line || null, usedFile: mod.rel, usedLine: at, inherited: false, source: null, why: null }],
|
|
2375
|
+
auth: g.auth,
|
|
2376
|
+
role: g.role,
|
|
2377
|
+
signature: g.signature,
|
|
2378
|
+
partialChecks: g.partial,
|
|
2379
|
+
platform: { verifyJwt: verify, says: verify === true ? 'verify_jwt is on in supabase/config.toml: the platform asks for a valid JWT before the code runs - the public anon key is one, so this alone does not mean signed in'
|
|
2380
|
+
: verify === false ? 'verify_jwt is false in supabase/config.toml: the platform lets every request in'
|
|
2381
|
+
: 'supabase/config.toml does not say: the platform asks for a JWT unless the function is deployed with --no-verify-jwt, which the code does not show - and the public anon key is a valid JWT, so this alone never means signed in' },
|
|
2382
|
+
db,
|
|
2383
|
+
validation,
|
|
2384
|
+
});
|
|
2385
|
+
}
|
|
2386
|
+
return routes;
|
|
2387
|
+
}
|
|
2388
|
+
|
|
2389
|
+
// --- Next.js: pages/api, app router route handlers, middleware ------------------------
|
|
2390
|
+
|
|
2391
|
+
const NEXT_PAGES_API = /(^|\/)(?:src\/)?pages\/api\/(.+)\.(js|jsx|ts|tsx|mjs)$/;
|
|
2392
|
+
const NEXT_ROUTE = /(^|\/)(?:src\/)?app\/((?:.+\/)?)route\.(js|jsx|ts|tsx|mjs)$/;
|
|
2393
|
+
const NEXT_MIDDLEWARE = /^(?:src\/)?middleware\.(js|ts|mjs)$/;
|
|
2394
|
+
const HTTP_EXPORTS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
|
|
2395
|
+
// Package wrappers known to turn away whoever is not signed in.
|
|
2396
|
+
const NEXT_AUTH_WRAPPERS = /^(withApiAuthRequired|withPageAuthRequired)$/;
|
|
2397
|
+
|
|
2398
|
+
/** pages/api/users/[id].ts -> /api/users/:id; app/(shop)/api/[...slug]/route.ts -> /api/:slug* */
|
|
2399
|
+
function nextPath(segments) {
|
|
2400
|
+
const out = [];
|
|
2401
|
+
for (const s of segments) {
|
|
2402
|
+
if (!s || /^\(.*\)$/.test(s) || s.startsWith('@')) continue; // route groups and parallel slots are not in the URL
|
|
2403
|
+
const opt = /^\[\[\.\.\.(\w+)\]\]$/.exec(s);
|
|
2404
|
+
const all = /^\[\.\.\.(\w+)\]$/.exec(s);
|
|
2405
|
+
const one = /^\[(\w+)\]$/.exec(s);
|
|
2406
|
+
out.push(opt ? ':' + opt[1] + '*' : all ? ':' + all[1] + '*' : one ? ':' + one[1] : s);
|
|
2407
|
+
}
|
|
2408
|
+
return '/' + out.join('/');
|
|
2409
|
+
}
|
|
2410
|
+
|
|
2411
|
+
/** A Next middleware matcher ('/dashboard/:path*', '/((?!api|_next).*)') as a test of a route path. */
|
|
2412
|
+
function matcherTest(pattern) {
|
|
2413
|
+
let s = String(pattern);
|
|
2414
|
+
s = s.replace(/:(\w+)\*/g, '(?:.*)').replace(/:(\w+)\+/g, '(?:.+)').replace(/:(\w+)\?/g, '(?:[^/]*)').replace(/:(\w+)(?![\w(])/g, '(?:[^/]+)');
|
|
2415
|
+
try {
|
|
2416
|
+
const re = new RegExp('^' + s + '/?$');
|
|
2417
|
+
return (p) => re.test(p.replace(/:(\w+)\*?/g, 'x'));
|
|
2418
|
+
} catch (err) {
|
|
2419
|
+
return null;
|
|
2420
|
+
}
|
|
2421
|
+
}
|
|
2422
|
+
|
|
2423
|
+
/** The middleware.ts of a Next app: what it checks, which paths it runs for, and which it lets through untouched. */
|
|
2424
|
+
function readNextMiddleware(ctx) {
|
|
2425
|
+
const t = ctx.t;
|
|
2426
|
+
for (const mod of ctx.modules.values()) {
|
|
2427
|
+
if (!mod || !NEXT_MIDDLEWARE.test(mod.rel)) continue;
|
|
2428
|
+
const named = mod.exportsNamed.get('middleware');
|
|
2429
|
+
// export { default } from 'next-auth/middleware' - the package protects every matched path
|
|
2430
|
+
const reexport = named && named.reexport ? named : mod.exportsNamed.get('default');
|
|
2431
|
+
let ref = named && !named.reexport ? exportOf(ctx, mod, 'middleware', 0, new Set()) : exportOf(ctx, mod, 'default', 0, new Set());
|
|
2432
|
+
if (reexport && reexport.reexport) ref = { kind: 'pkg', name: 'default', source: reexport.reexport };
|
|
2433
|
+
let element;
|
|
2434
|
+
const line = 1;
|
|
2435
|
+
if (ref.kind === 'fn') element = readElement(ctx, { ref, mod, line: ref.path.node.loc.start.line, text: 'middleware', inherited: true });
|
|
2436
|
+
else if (ref.kind === 'pkg' && /^next-auth\/middleware$/.test(ref.source)) element = { text: 'middleware (' + ref.source + ')', kind: 'package', source: ref.source, usedFile: mod.rel, usedLine: line, inherited: true, guards: { auth: { file: mod.rel, line, code: snippet(mod, line), how: 'next-auth middleware: turns away whoever is not signed in, for every path it runs for' } } };
|
|
2437
|
+
else element = { text: 'middleware', kind: ref.kind === 'pkg' ? 'package' : 'unknown', source: ref.source || null, usedFile: mod.rel, usedLine: line, inherited: true, guards: null, why: ref.why || ('comes from the package ' + ref.source + ', whose code is not read') };
|
|
2438
|
+
// export const config = { matcher: [...] }
|
|
2439
|
+
let matchers = null;
|
|
2440
|
+
let matcherWhy = null;
|
|
2441
|
+
const cfg = mod.exportsNamed.get('config');
|
|
2442
|
+
const cfgNode = cfg && cfg.node;
|
|
2443
|
+
if (cfgNode && cfgNode.type === 'ObjectExpression') {
|
|
2444
|
+
const m = cfgNode.properties.find((p) => p.key && (p.key.name || p.key.value) === 'matcher');
|
|
2445
|
+
if (m) {
|
|
2446
|
+
const list = m.value.type === 'ArrayExpression' ? m.value.elements : [m.value];
|
|
2447
|
+
matchers = [];
|
|
2448
|
+
for (const e of list) {
|
|
2449
|
+
const src = e && e.type === 'StringLiteral' ? e.value : e && e.type === 'ObjectExpression' ? ((e.properties.find((p) => p.key && p.key.name === 'source') || {}).value || {}).value : null;
|
|
2450
|
+
const test = src && matcherTest(src);
|
|
2451
|
+
if (!test) matcherWhy = 'a matcher could not be read';
|
|
2452
|
+
else matchers.push({ src, test, conditional: !!(e.type === 'ObjectExpression' && e.properties.some((p) => p.key && /^(has|missing)$/.test(p.key.name))) });
|
|
2453
|
+
}
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
// paths the middleware lets straight through: if (pathname.startsWith('/api/public')) return NextResponse.next()
|
|
2457
|
+
const skips = [];
|
|
2458
|
+
let skipsUnread = false;
|
|
2459
|
+
if (ref.kind === 'fn') {
|
|
2460
|
+
ref.path.traverse({
|
|
2461
|
+
IfStatement(q) {
|
|
2462
|
+
const cons = q.node.consequent;
|
|
2463
|
+
const text = mod.source.slice(cons.start, cons.end);
|
|
2464
|
+
if (!/NextResponse\.next\(\)|return\s*;|return\s+undefined/.test(text) || /redirect|status:\s*4\d\d/.test(text)) return;
|
|
2465
|
+
const lits = [];
|
|
2466
|
+
const visit = (n) => {
|
|
2467
|
+
if (!n || typeof n !== 'object') return;
|
|
2468
|
+
if (Array.isArray(n)) return n.forEach(visit);
|
|
2469
|
+
if (n.type === 'CallExpression' && /^(startsWith|includes)$/.test(calledName(n)) && n.arguments[0] && n.arguments[0].type === 'StringLiteral') lits.push({ kind: calledName(n), value: n.arguments[0].value });
|
|
2470
|
+
else if (n.type === 'BinaryExpression' && /^[!=]==?$/.test(n.operator) && [n.left, n.right].some((x) => x.type === 'StringLiteral' && x.value.startsWith('/'))) lits.push({ kind: 'equals', value: [n.left, n.right].find((x) => x.type === 'StringLiteral').value });
|
|
2471
|
+
for (const k of Object.keys(n)) if (k !== 'loc') visit(n[k]);
|
|
2472
|
+
};
|
|
2473
|
+
visit(q.node.test);
|
|
2474
|
+
if (lits.length && /pathname|url|path/i.test(mod.source.slice(q.node.test.start, q.node.test.end))) skips.push(...lits.map((l) => Object.assign(l, { line: q.node.loc.start.line })));
|
|
2475
|
+
else if (/pathname|url|path/i.test(mod.source.slice(q.node.test.start, q.node.test.end))) skipsUnread = true;
|
|
2476
|
+
},
|
|
2477
|
+
});
|
|
2478
|
+
}
|
|
2479
|
+
return { mod, element, matchers, matcherWhy, skips, skipsUnread };
|
|
2480
|
+
}
|
|
2481
|
+
return null;
|
|
2482
|
+
}
|
|
2483
|
+
|
|
2484
|
+
/**
|
|
2485
|
+
* The API routes of a Next app: pages/api/** (one handler for every method,
|
|
2486
|
+
* unless it checks req.method) and app/**\/route.ts (one route per exported
|
|
2487
|
+
* GET, POST...), each with what middleware.ts does in front of it.
|
|
2488
|
+
*/
|
|
2489
|
+
function nextRoutes(ctx, schema) {
|
|
2490
|
+
const routes = [];
|
|
2491
|
+
const mw = readNextMiddleware(ctx);
|
|
2492
|
+
const front = (p) => {
|
|
2493
|
+
if (!mw) return { elements: [] };
|
|
2494
|
+
if (mw.matcherWhy) return { elements: [Object.assign({}, mw.element, { guards: null, why: 'middleware.ts: ' + mw.matcherWhy + ', so whether it runs for this route is not known' })] };
|
|
2495
|
+
const hit = !mw.matchers || mw.matchers.some((m) => m.test(p));
|
|
2496
|
+
if (!hit) return { elements: [] };
|
|
2497
|
+
const conditional = mw.matchers && mw.matchers.filter((m) => m.test(p)).every((m) => m.conditional);
|
|
2498
|
+
const skipped = mw.skips.find((s) => (s.kind === 'equals' ? p === s.value : s.kind === 'startsWith' ? p.startsWith(s.value) : p.includes(s.value)));
|
|
2499
|
+
if (skipped) return { elements: [], note: 'middleware.ts lets ' + p + ' through untouched (line ' + skipped.line + ')' };
|
|
2500
|
+
if (mw.skipsUnread || conditional) return { elements: [Object.assign({}, mw.element, { guards: mw.element.guards ? Object.assign({}, mw.element.guards, { auth: null, role: null, authPartial: mw.element.guards.auth || mw.element.guards.role }) : null, why: 'middleware.ts lets some paths through by a rule that could not be read' })] };
|
|
2501
|
+
return { elements: [mw.element] };
|
|
2502
|
+
};
|
|
2503
|
+
const add = (method, p, mod, line, handlerRef, wrapper) => {
|
|
2504
|
+
const f = front(p);
|
|
2505
|
+
const elements = f.elements.slice();
|
|
2506
|
+
if (wrapper) elements.push(wrapper);
|
|
2507
|
+
let el = null;
|
|
2508
|
+
if (handlerRef.kind === 'fn') {
|
|
2509
|
+
el = readElement(ctx, { ref: handlerRef, mod, line, text: method + ' handler', inherited: false });
|
|
2510
|
+
elements.push(el);
|
|
2511
|
+
} else {
|
|
2512
|
+
elements.push({ text: method + ' handler', kind: handlerRef.kind === 'pkg' ? 'package' : 'unknown', source: handlerRef.source || null, usedFile: mod.rel, usedLine: line, guards: null, why: handlerRef.why || ('comes from the package ' + handlerRef.source + ', whose code is not read') });
|
|
2513
|
+
ctx.notRead.push({ file: mod.rel, line, what: method + ' ' + p + ': the handler could not be followed (' + (handlerRef.why || 'package ' + handlerRef.source) + ')', pattern: 'handler' });
|
|
2514
|
+
}
|
|
2515
|
+
const g = judge({}, elements);
|
|
2516
|
+
const methods = el && el.guards && el.guards.methods;
|
|
2517
|
+
const db = handlerRef.kind === 'fn' ? readDb(ctx, handlerRef, schema) : [];
|
|
2518
|
+
const validation = handlerRef.kind === 'fn' ? readValidation(ctx, handlerRef, elements, db) : { fields: [], schemas: [] };
|
|
2519
|
+
routes.push({
|
|
2520
|
+
method: method === 'ANY' && methods && methods.size === 1 ? Array.from(methods)[0] : method,
|
|
2521
|
+
methods: method === 'ANY' && methods && methods.size > 1 ? Array.from(methods).sort() : undefined,
|
|
2522
|
+
path: p,
|
|
2523
|
+
file: mod.rel,
|
|
2524
|
+
line,
|
|
2525
|
+
framework: 'next',
|
|
2526
|
+
unmounted: false,
|
|
2527
|
+
orderAcrossFiles: false,
|
|
2528
|
+
middleware: elements.map((e) => ({ name: e.text, kind: e.kind, file: e.file || null, line: e.line || null, usedFile: e.usedFile, usedLine: e.usedLine, inherited: !!e.inherited, source: e.source || null, why: e.why || null })),
|
|
2529
|
+
auth: g.auth,
|
|
2530
|
+
role: g.role,
|
|
2531
|
+
signature: g.signature,
|
|
2532
|
+
partialChecks: g.partial,
|
|
2533
|
+
note: f.note,
|
|
2534
|
+
db,
|
|
2535
|
+
validation,
|
|
2536
|
+
});
|
|
2537
|
+
};
|
|
2538
|
+
// a package that wraps the handler: withApiAuthRequired(handler) protects it; another one is not read
|
|
2539
|
+
const unwrap = (mod, p) => {
|
|
2540
|
+
p = unwrapTs(p);
|
|
2541
|
+
if (p && p.isCallExpression() && p.node.arguments.length) {
|
|
2542
|
+
const callee = resolveRef(ctx, mod, p.get('callee'));
|
|
2543
|
+
const inner = resolveRef(ctx, mod, p.get('arguments.0'));
|
|
2544
|
+
if (callee.kind === 'pkg' && inner.kind === 'fn') {
|
|
2545
|
+
const name = callee.name.split('.').pop();
|
|
2546
|
+
const line = p.node.loc.start.line;
|
|
2547
|
+
const known = NEXT_AUTH_WRAPPERS.test(name) || (PACKAGE_AUTH.test(name) && PACKAGE_AUTH_SOURCES.test(callee.source));
|
|
2548
|
+
const wrapper = { text: name + '()', kind: 'package', source: callee.source, usedFile: mod.rel, usedLine: line, guards: known ? { auth: { file: mod.rel, line, code: snippet(mod, line), how: name + ' from ' + callee.source + ' turns away whoever is not signed in' } } : null, why: known ? null : 'wrapped in ' + name + '() from ' + callee.source + ', whose code is not read' };
|
|
2549
|
+
return { ref: inner, wrapper };
|
|
2550
|
+
}
|
|
2551
|
+
}
|
|
2552
|
+
return { ref: resolveRef(ctx, mod, p), wrapper: null };
|
|
2553
|
+
};
|
|
2554
|
+
for (const mod of ctx.modules.values()) {
|
|
2555
|
+
if (!mod) continue;
|
|
2556
|
+
let m = NEXT_PAGES_API.exec(mod.rel);
|
|
2557
|
+
if (m) {
|
|
2558
|
+
const segs = ('api/' + m[2]).split('/');
|
|
2559
|
+
if (segs[segs.length - 1] === 'index') segs.pop();
|
|
2560
|
+
const p = nextPath(segs);
|
|
2561
|
+
const d = mod.exportDefault;
|
|
2562
|
+
if (!d) {
|
|
2563
|
+
ctx.notRead.push({ file: mod.rel, line: 1, what: p + ' (pages/api) has no default export handler this map could find', pattern: 'handler' });
|
|
2564
|
+
continue;
|
|
2565
|
+
}
|
|
2566
|
+
const u = d.isFunctionDeclaration() || d.isFunction() ? { ref: { kind: 'fn', path: d, mod }, wrapper: null } : unwrap(mod, d);
|
|
2567
|
+
add('ANY', p, mod, d.node.loc.start.line, u.ref, u.wrapper);
|
|
2568
|
+
continue;
|
|
2569
|
+
}
|
|
2570
|
+
m = NEXT_ROUTE.exec(mod.rel);
|
|
2571
|
+
if (m) {
|
|
2572
|
+
const p = nextPath(m[2].split('/').filter(Boolean));
|
|
2573
|
+
let any = false;
|
|
2574
|
+
for (const method of HTTP_EXPORTS) {
|
|
2575
|
+
const e = mod.exportsNamed.get(method);
|
|
2576
|
+
if (!e) continue;
|
|
2577
|
+
any = true;
|
|
2578
|
+
let target = e;
|
|
2579
|
+
if (e.local) {
|
|
2580
|
+
const b = mod.program.scope.getBinding(e.local);
|
|
2581
|
+
target = b ? bindingTarget(b) : null;
|
|
2582
|
+
}
|
|
2583
|
+
if (e.reexport) {
|
|
2584
|
+
add(method, p, mod, 1, fromModule(ctx, mod, e.reexport, e.name, 0, new Set()), null);
|
|
2585
|
+
continue;
|
|
2586
|
+
}
|
|
2587
|
+
if (!target) continue;
|
|
2588
|
+
const line = (target.node && target.node.loc ? target.node.loc.start.line : 1);
|
|
2589
|
+
const u = target.isFunction && (target.isFunction() || target.isFunctionDeclaration()) ? { ref: { kind: 'fn', path: target, mod }, wrapper: null } : unwrap(mod, target);
|
|
2590
|
+
add(method, p, mod, line, u.ref, u.wrapper);
|
|
2591
|
+
}
|
|
2592
|
+
if (!any) ctx.notRead.push({ file: mod.rel, line: 1, what: p + ' (route.ts) exports none of GET, POST, PUT, PATCH, DELETE that this map could find', pattern: 'handler' });
|
|
2593
|
+
}
|
|
2594
|
+
}
|
|
2595
|
+
// server actions are endpoints too: said, never left out in silence
|
|
2596
|
+
for (const mod of ctx.modules.values()) {
|
|
2597
|
+
if (!mod) continue;
|
|
2598
|
+
const fileLevel = mod.ast.program.directives && mod.ast.program.directives.some((d) => d.value.value === 'use server');
|
|
2599
|
+
let count = 0;
|
|
2600
|
+
let first = null;
|
|
2601
|
+
mod.program.traverse({
|
|
2602
|
+
Function(q) {
|
|
2603
|
+
const body = q.node.body;
|
|
2604
|
+
const own = body && body.directives && body.directives.some((d) => d.value.value === 'use server');
|
|
2605
|
+
if (own || (fileLevel && q.parentPath && (q.parentPath.isExportNamedDeclaration() || (q.parentPath.isVariableDeclarator() && q.parentPath.parentPath.parentPath.isExportNamedDeclaration())))) {
|
|
2606
|
+
count++;
|
|
2607
|
+
if (!first) first = q.node.loc.start.line;
|
|
2608
|
+
}
|
|
2609
|
+
},
|
|
2610
|
+
});
|
|
2611
|
+
if (count) ctx.notRead.push({ file: mod.rel, line: first, what: count + ' server action' + (count === 1 ? '' : 's') + " ('use server') - each one can be called from a browser like a route, and this map does not read them yet", pattern: 'server-action' });
|
|
2612
|
+
}
|
|
2613
|
+
return routes;
|
|
2614
|
+
}
|
|
2615
|
+
|
|
2616
|
+
/** What kind of route this is, beside an ordinary one: a webhook, or a way to start a job. */
|
|
2617
|
+
function routeKind(r) {
|
|
2618
|
+
if (/(^|\/)(webhooks?|hooks?|callbacks?|ipn|notify)(\/|$)/i.test(r.path || '') || r.signature.status === STATUS.DETECTED || r.signature.presenceOnly) return 'webhook';
|
|
2619
|
+
if (/(^|\/)(jobs?|cron|tasks?|workers?|queues?|schedules?)(\/|$)/i.test(r.path || '')) return 'job';
|
|
2620
|
+
return 'route';
|
|
2621
|
+
}
|
|
2622
|
+
|
|
2623
|
+
function otherDbIn(ctx) {
|
|
2624
|
+
for (const mod of ctx.modules.values()) {
|
|
2625
|
+
if (!mod) continue;
|
|
2626
|
+
const seen = new Set();
|
|
2627
|
+
for (const [, imp] of mod.imports) if (OTHER_DB.test(imp.source) && !seen.has(imp.source)) {
|
|
2628
|
+
seen.add(imp.source);
|
|
2629
|
+
ctx.notRead.push({ file: mod.rel, line: imp.line, what: 'database calls through ' + imp.source + ' are not read: the tables of routes in this file may be missing', pattern: 'database-library' });
|
|
2630
|
+
}
|
|
2631
|
+
for (const call of mod.calls) {
|
|
2632
|
+
const req = requireOf(ctx.t, call.node);
|
|
2633
|
+
if (req && OTHER_DB.test(req) && !seen.has(req)) {
|
|
2634
|
+
seen.add(req);
|
|
2635
|
+
ctx.notRead.push({ file: mod.rel, line: call.node.loc.start.line, what: 'database calls through ' + req + ' are not read: the tables of routes in this file may be missing', pattern: 'database-library' });
|
|
2636
|
+
}
|
|
2637
|
+
}
|
|
2638
|
+
}
|
|
2639
|
+
}
|
|
2640
|
+
|
|
2641
|
+
// --- the map ----------------------------------------------------------------------
|
|
2642
|
+
|
|
2643
|
+
function frameworksIn(ctx) {
|
|
2644
|
+
const found = new Map();
|
|
2645
|
+
for (const mod of ctx.modules.values()) {
|
|
2646
|
+
if (!mod) continue;
|
|
2647
|
+
const add = (source, line) => {
|
|
2648
|
+
const name = source.replace(/^@([^/]+)\/.*$/, '@$1').replace(/^koa-router$|^@koa$/, 'koa');
|
|
2649
|
+
mod.otherFramework = name;
|
|
2650
|
+
if (!found.has(name)) found.set(name, { file: mod.rel, line, files: new Set() });
|
|
2651
|
+
found.get(name).files.add(mod.rel);
|
|
2652
|
+
};
|
|
2653
|
+
for (const [, imp] of mod.imports) if (OTHER_FRAMEWORKS.test(packageName(imp.source)) && imp.imported !== undefined) add(packageName(imp.source), imp.line);
|
|
2654
|
+
for (const call of mod.calls) {
|
|
2655
|
+
const req = requireOf(ctx.t, call.node);
|
|
2656
|
+
if (req && OTHER_FRAMEWORKS.test(packageName(req))) add(packageName(req), call.node.loc.start.line);
|
|
2657
|
+
}
|
|
2658
|
+
}
|
|
2659
|
+
return found;
|
|
2660
|
+
}
|
|
2661
|
+
|
|
2662
|
+
/** The package an import names, however Deno or a CDN spells it: npm:hono@4, jsr:@hono/hono, https://deno.land/x/hono@v3/mod.ts, https://esm.sh/hono. */
|
|
2663
|
+
function packageName(source) {
|
|
2664
|
+
let s = String(source || '').replace(/^(npm|jsr|node):/, '');
|
|
2665
|
+
const url = /^https?:\/\/(?:deno\.land\/x|esm\.sh|cdn\.skypack\.dev|unpkg\.com|cdn\.jsdelivr\.net\/npm)\/(@[^/@]+\/[^/@]+|[^/@]+)/.exec(s);
|
|
2666
|
+
if (url) s = url[1];
|
|
2667
|
+
return s.replace(/^(@[^/@]+\/[^/@]+|[^/@]+)@[^/]*/, '$1').replace(/\/.*$/, (rest) => (s.startsWith('@') ? rest.replace(/^(\/[^/]+).*/, '$1') : ''));
|
|
2668
|
+
}
|
|
2669
|
+
|
|
2670
|
+
/**
|
|
2671
|
+
* The map of a project folder: { ran, routes, notRead, unreadable, filesRead }.
|
|
2672
|
+
* Reads files only; nothing in the folder is run or changed.
|
|
2673
|
+
*/
|
|
2674
|
+
function mapProject(root, options) {
|
|
2675
|
+
const packageDir = (options && options.packageDir) || __dirname;
|
|
2676
|
+
const parser = (options && options.parser) || code.loadParser(packageDir);
|
|
2677
|
+
if (!parser) return { ran: false, why: 'the JavaScript parser this check uses was not found in this install of Playwright', routes: [], notRead: [], unreadable: [], filesRead: 0 };
|
|
2678
|
+
const ctx = makeContext(root, parser);
|
|
2679
|
+
const files = listFiles(root);
|
|
2680
|
+
for (const f of files) ctx.load(f);
|
|
2681
|
+
for (const [source, at] of frameworksIn(ctx)) {
|
|
2682
|
+
ctx.notRead.push({ file: at.file, line: at.line, what: 'the app uses ' + source + ' (' + at.files.size + ' file' + (at.files.size === 1 ? '' : 's') + '), whose routes this map does not read yet - none of them is in this map', pattern: 'framework' });
|
|
2683
|
+
}
|
|
2684
|
+
const containers = findContainers(ctx);
|
|
2685
|
+
collectRegistrations(ctx, containers);
|
|
2686
|
+
const schema = readSchema(ctx, root);
|
|
2687
|
+
otherDbIn(ctx);
|
|
2688
|
+
const raw = flatten(ctx, containers);
|
|
2689
|
+
const routes = raw.map((r) => {
|
|
2690
|
+
const elements = r.chain.map((h) => readElement(ctx, h));
|
|
2691
|
+
const g = judge(r, elements);
|
|
2692
|
+
if (r.maybe && r.maybe.length) {
|
|
2693
|
+
for (const k of ['auth', 'role']) if (g[k].status === STATUS.NOT) g[k] = { status: STATUS.UNKNOWN, why: ['its path could not be read, so whether ' + r.maybe.join(', ') + ' runs before it is not known'] };
|
|
2694
|
+
}
|
|
2695
|
+
if (r.path === null) ctx.notRead.push({ file: r.file, line: r.line, what: r.method + ' route whose path could not be read: ' + r.pathWhy, pattern: 'route-path' });
|
|
2696
|
+
for (const e of elements) {
|
|
2697
|
+
if (e.kind === 'unknown' || (e.kind === 'package' && e.guards === null)) ctx.notRead.push({ file: e.usedFile, line: e.usedLine, what: 'could not follow ' + e.text + ' in front of ' + r.method + ' ' + (r.path || '(unknown path)') + ': ' + e.why, pattern: 'handler' });
|
|
2698
|
+
}
|
|
2699
|
+
const h = handlerOf(r);
|
|
2700
|
+
const db = h ? readDb(ctx, h, schema) : [];
|
|
2701
|
+
const validation = h ? readValidation(ctx, h, elements, db) : { fields: [], schemas: [], why: 'the handler could not be followed' };
|
|
2702
|
+
return {
|
|
2703
|
+
method: r.method,
|
|
2704
|
+
path: r.path,
|
|
2705
|
+
file: r.file,
|
|
2706
|
+
line: r.line,
|
|
2707
|
+
unmounted: !!r.unmounted,
|
|
2708
|
+
orderAcrossFiles: r.crossFileOrder,
|
|
2709
|
+
middleware: elements.map((e) => ({ name: e.text, kind: e.kind, file: e.file || null, line: e.line || null, usedFile: e.usedFile, usedLine: e.usedLine, inherited: e.inherited, source: e.source || null, why: e.why || null })),
|
|
2710
|
+
auth: g.auth,
|
|
2711
|
+
role: g.role,
|
|
2712
|
+
signature: g.signature,
|
|
2713
|
+
partialChecks: g.partial,
|
|
2714
|
+
db,
|
|
2715
|
+
validation,
|
|
2716
|
+
};
|
|
2717
|
+
});
|
|
2718
|
+
routes.push(...edgeRoutes(ctx, root, schema));
|
|
2719
|
+
routes.push(...nextRoutes(ctx, schema));
|
|
2720
|
+
for (const r of routes) r.kind = routeKind(r);
|
|
2721
|
+
const jobs = findJobs(ctx, schema);
|
|
2722
|
+
// the same problem said once
|
|
2723
|
+
const seen = new Set();
|
|
2724
|
+
const notRead = ctx.notRead.filter((n) => {
|
|
2725
|
+
const k = n.file + ':' + n.line + ':' + n.what;
|
|
2726
|
+
if (seen.has(k)) return false;
|
|
2727
|
+
seen.add(k);
|
|
2728
|
+
return true;
|
|
2729
|
+
});
|
|
2730
|
+
return { ran: true, filesRead: files.length, routes, jobs, notRead, unreadable: ctx.unreadable, tablesKnown: schema.size };
|
|
2731
|
+
}
|
|
2732
|
+
|
|
2733
|
+
// --- what is worth a look: read from code, never proven ---------------------------------
|
|
2734
|
+
|
|
2735
|
+
// Paths whose change is sensitive enough that a missing role check is worth a look - but
|
|
2736
|
+
// only in an app that checks roles somewhere, or every single-role app would light up.
|
|
2737
|
+
const SENSITIVE_PATH = /(^|\/)(roles?|admin|team|members?|permissions?|invites?|invitations?|settings|billing|refunds?|plans?|users?|api-?keys?)(\/|$)/i;
|
|
2738
|
+
// Routes that are open by nature: signing in, signing up, a password reset, an invitation link.
|
|
2739
|
+
const AUTH_PATH = /(^|\/)(log-?in|log-?out|sign-?in|sign-?out|sign-?up|register|password|forgot|reset|verify|confirm|auth|callback|oauth|session|invite\/:)/i;
|
|
2740
|
+
const ADVICE = {
|
|
2741
|
+
'webhook-signature': 'verify the provider\'s signature over the raw body with the webhook secret, before anything in the body is used, and answer 401 when the header is missing or does not match.',
|
|
2742
|
+
'webhook-signature-skippable': 'treat a request without the signature header as invalid: answer 401, the same as a wrong signature.',
|
|
2743
|
+
'no-sign-in': 'require a signed-in person (or the right key) before it changes anything, and answer 401 otherwise. If this route is meant to be open to anyone, tell me that instead of changing it.',
|
|
2744
|
+
'tenant-from-request': 'take the organisation from the signed-in person\'s session, never from the request body or query string; for an id the request sends, look the record up with the organisation condition before using it.',
|
|
2745
|
+
'tenant-unscoped': 'add the signed-in person\'s organisation (or owner) to the statement - WHERE org_id = <the session\'s org> - or, for a row found by its id, check that the row belongs to that organisation before using it.',
|
|
2746
|
+
'no-role': 'allow only the roles that should be able to do this, and answer 403 for the others.',
|
|
2747
|
+
};
|
|
2748
|
+
|
|
2749
|
+
/**
|
|
2750
|
+
* Things in the map worth a look, each with its evidence and a prompt for an
|
|
2751
|
+
* AI tool. Every one is "to check": this is a reading of code, and only a run
|
|
2752
|
+
* (npx kryptheon roles, the database check) can prove a hole.
|
|
2753
|
+
*/
|
|
2754
|
+
function toCheck(map) {
|
|
2755
|
+
const items = [];
|
|
2756
|
+
const routes = (map.routes || []).filter((r) => !r.unmounted);
|
|
2757
|
+
const checksRoles = routes.some((r) => r.role.status === STATUS.DETECTED);
|
|
2758
|
+
const ev = (e) => (e ? e.file + ':' + e.line + ' ' + (e.code || '') : null);
|
|
2759
|
+
const verb = (d) => ({ SELECT: 'reads', INSERT: 'writes to', UPSERT: 'writes to', UPDATE: 'changes', DELETE: 'deletes from' }[d.op] || 'uses');
|
|
2760
|
+
const add = (r, kind, severity, headline, evidence) => {
|
|
2761
|
+
const name = r.method + ' ' + (r.path || '(path not read)');
|
|
2762
|
+
items.push({ kind, severity, route: name, where: r.file + ':' + r.line, headline, evidence: evidence.filter(Boolean) });
|
|
2763
|
+
};
|
|
2764
|
+
// the tables a route touches one way, said once: "changes shipments, organizations and labels"
|
|
2765
|
+
const tables = (list) => {
|
|
2766
|
+
const byVerb = new Map();
|
|
2767
|
+
for (const d of list) {
|
|
2768
|
+
const v = verb(d);
|
|
2769
|
+
if (!byVerb.has(v)) byVerb.set(v, []);
|
|
2770
|
+
if (!byVerb.get(v).includes(d.table)) byVerb.get(v).push(d.table);
|
|
2771
|
+
}
|
|
2772
|
+
return Array.from(byVerb.entries()).map(([v, ts]) => v + ' ' + (ts.length > 1 ? ts.slice(0, -1).join(', ') + ' and ' + ts[ts.length - 1] : ts[0])).join(', ');
|
|
2773
|
+
};
|
|
2774
|
+
const at = (d) => ev(d.scoping.evidence) || d.file + ':' + d.line + ' ' + d.sql;
|
|
2775
|
+
for (const r of routes) {
|
|
2776
|
+
const name = r.method + ' ' + (r.path || '(path not read)');
|
|
2777
|
+
const writes = /^(POST|PUT|PATCH|DELETE|ANY|ALL)$/.test(r.method);
|
|
2778
|
+
const changing = (r.db || []).filter((d) => d.op !== 'SELECT');
|
|
2779
|
+
if (r.kind === 'webhook') {
|
|
2780
|
+
if (r.signature.status === STATUS.NOT) {
|
|
2781
|
+
add(r, 'webhook-signature', 'HIGH', name + ' is a webhook, and no check of its signature was found' + (r.signature.presenceOnly ? ': it only looks at whether a signature header is there' : ''),
|
|
2782
|
+
[r.file + ':' + r.line, r.signature.presenceOnly && ev(r.signature.presenceOnly)]);
|
|
2783
|
+
} else if (r.signature.status === STATUS.DETECTED && r.signature.skippable) {
|
|
2784
|
+
add(r, 'webhook-signature-skippable', 'HIGH', name + ' checks the signature only when one is sent: a request without the header is let through', [ev(r.signature.evidence)]);
|
|
2785
|
+
}
|
|
2786
|
+
continue;
|
|
2787
|
+
}
|
|
2788
|
+
// a route with no sign-in that changes something - sign-in and sign-up routes are open by nature
|
|
2789
|
+
if (writes && r.auth.status === STATUS.NOT && changing.length && !AUTH_PATH.test(r.path || '')) {
|
|
2790
|
+
add(r, 'no-sign-in', 'HIGH', name + ' ' + tables(changing) + ', and no sign-in check was found in front of it', [r.file + ':' + r.line].concat(changing.slice(0, 3).map((d) => d.file + ':' + d.line + ' ' + d.sql)));
|
|
2791
|
+
}
|
|
2792
|
+
// rows of the organisation the request names: read or written, signed in or not, that is another organisation's data
|
|
2793
|
+
const chosen = (r.db || []).filter((d) => d.scoping.clientChosen);
|
|
2794
|
+
if (chosen.length && (r.auth.status !== STATUS.NOT || !AUTH_PATH.test(r.path || ''))) {
|
|
2795
|
+
add(r, 'tenant-from-request', 'HIGH', name + ' ' + tables(chosen) + ' for the organisation the request names' + (r.auth.status === STATUS.NOT ? ', and is open to anyone' : ', not the signed-in person\'s'), chosen.map(at));
|
|
2796
|
+
}
|
|
2797
|
+
if (r.auth.status === STATUS.DETECTED) {
|
|
2798
|
+
const open = (r.db || []).filter((d) => !d.scoping.clientChosen && d.scoping.status === STATUS.NOT && d.scoping.applies !== false && !d.joinedTo);
|
|
2799
|
+
if (open.length) {
|
|
2800
|
+
const fromRow = open.some((d) => d.scoping.fromOpenRow);
|
|
2801
|
+
const byOrg = open.some((d) => d.level !== 'owner');
|
|
2802
|
+
add(r, 'tenant-unscoped', open.some((d) => d.op !== 'SELECT') ? 'HIGH' : 'MEDIUM', name + ' ' + tables(open) + (byOrg ? ' with no limit to the signed-in person\'s organisation' : ' with no check that the rows belong to the signed-in person') + (fromRow ? ' (rows found by an id that was itself looked up without one)' : ''), open.map(at));
|
|
2803
|
+
}
|
|
2804
|
+
if (checksRoles && writes && r.role.status === STATUS.NOT && SENSITIVE_PATH.test(r.path || '')) {
|
|
2805
|
+
add(r, 'no-role', 'MEDIUM', name + ' is a sensitive change, and no role check was found in front of it, while other routes of this app check roles', [r.file + ':' + r.line]);
|
|
2806
|
+
}
|
|
2807
|
+
}
|
|
2808
|
+
}
|
|
2809
|
+
const rank = { HIGH: 0, MEDIUM: 1 };
|
|
2810
|
+
items.sort((a, b) => rank[a.severity] - rank[b.severity] || a.where.localeCompare(b.where, undefined, { numeric: true }));
|
|
2811
|
+
for (const i of items) i.fixPrompt = fixPromptFor(i);
|
|
2812
|
+
return items;
|
|
2813
|
+
}
|
|
2814
|
+
|
|
2815
|
+
function fixPromptFor(item) {
|
|
2816
|
+
return [
|
|
2817
|
+
'Kryptheon read my app\'s server code (it did not run it) and points at this, to check:',
|
|
2818
|
+
'',
|
|
2819
|
+
item.headline + '.',
|
|
2820
|
+
'',
|
|
2821
|
+
'Where:',
|
|
2822
|
+
].concat(item.evidence.map((e) => ' ' + e), [
|
|
2823
|
+
'',
|
|
2824
|
+
'First check whether this is a real problem in my app. If it is, ' + ADVICE[item.kind],
|
|
2825
|
+
'',
|
|
2826
|
+
'Do not change anything else. Afterwards I will run: npx kryptheon map',
|
|
2827
|
+
]).join('\n');
|
|
2828
|
+
}
|
|
2829
|
+
|
|
2830
|
+
/** The counts the report and the dashboard say. */
|
|
2831
|
+
function summary(map) {
|
|
2832
|
+
const routes = (map.routes || []).filter((r) => !r.unmounted);
|
|
2833
|
+
const count = (key) => {
|
|
2834
|
+
const c = { guard_detected: 0, not_detected: 0, unknown: 0 };
|
|
2835
|
+
for (const r of routes) c[r[key].status]++;
|
|
2836
|
+
return c;
|
|
2837
|
+
};
|
|
2838
|
+
const db = routes.flatMap((r) => r.db || []);
|
|
2839
|
+
const scope = { guard_detected: 0, not_detected: 0, unknown: 0 };
|
|
2840
|
+
for (const d of db) if (d.scoping.applies !== false && !d.joinedTo) scope[d.scoping.status]++;
|
|
2841
|
+
const frameworks = {};
|
|
2842
|
+
for (const r of routes) frameworks[r.framework || 'express'] = (frameworks[r.framework || 'express'] || 0) + 1;
|
|
2843
|
+
return {
|
|
2844
|
+
routes: routes.length,
|
|
2845
|
+
unmounted: (map.routes || []).length - routes.length,
|
|
2846
|
+
frameworks,
|
|
2847
|
+
auth: count('auth'),
|
|
2848
|
+
role: count('role'),
|
|
2849
|
+
webhooks: routes.filter((r) => r.kind === 'webhook').length,
|
|
2850
|
+
jobRoutes: routes.filter((r) => r.kind === 'job').length,
|
|
2851
|
+
jobs: (map.jobs || []).length,
|
|
2852
|
+
statements: db.length,
|
|
2853
|
+
tables: new Set(db.map((d) => d.table).filter(Boolean)).size,
|
|
2854
|
+
scope,
|
|
2855
|
+
notRead: (map.notRead || []).length,
|
|
2856
|
+
};
|
|
2857
|
+
}
|
|
2858
|
+
|
|
2859
|
+
/** The terminal report: counts, what to check, and what was not read. */
|
|
2860
|
+
function reportLines(map, opts = {}) {
|
|
2861
|
+
const s = summary(map);
|
|
2862
|
+
const items = toCheck(map);
|
|
2863
|
+
const out = [''];
|
|
2864
|
+
const FW = { express: ['Express route', 'Express routes'], 'supabase-edge': ['Supabase Edge Function', 'Supabase Edge Functions'], next: ['Next.js route', 'Next.js routes'] };
|
|
2865
|
+
const fw = Object.entries(s.frameworks).map(([k, n]) => n + ' ' + (FW[k] || [k, k])[n === 1 ? 0 : 1]).join(', ');
|
|
2866
|
+
out.push(' I read ' + map.filesRead + ' file' + (map.filesRead === 1 ? '' : 's') + ' of your app\'s server code. Nothing was run, sent or changed.');
|
|
2867
|
+
out.push('');
|
|
2868
|
+
if (!s.routes) {
|
|
2869
|
+
out.push(' I found no route I can read' + (s.notRead ? ' - see "Not read" below.' : '.') + ' This map reads Express, Supabase Edge Functions and Next.js.');
|
|
2870
|
+
} else {
|
|
2871
|
+
out.push(' Routes: ' + s.routes + (fw ? ' (' + fw + ')' : '') + (s.webhooks ? ', ' + s.webhooks + ' of them webhook' + (s.webhooks === 1 ? '' : 's') : ''));
|
|
2872
|
+
const line = (label, c) => ' ' + label.padEnd(16) + 'found ' + String(c.guard_detected).padEnd(5) + 'none found ' + String(c.not_detected).padEnd(5) + 'could not tell ' + c.unknown;
|
|
2873
|
+
out.push(line('sign-in check', s.auth));
|
|
2874
|
+
out.push(line('role check', s.role));
|
|
2875
|
+
if (s.statements) {
|
|
2876
|
+
out.push(' Database: ' + s.statements + ' statement' + (s.statements === 1 ? '' : 's') + ' on ' + s.tables + ' table' + (s.tables === 1 ? '' : 's'));
|
|
2877
|
+
out.push(' ' + 'organisation'.padEnd(16) + 'limited ' + String(s.scope.guard_detected).padEnd(5) + 'not limited ' + String(s.scope.not_detected).padEnd(5) + 'could not tell ' + s.scope.unknown);
|
|
2878
|
+
}
|
|
2879
|
+
if (s.jobs) out.push(' Background jobs: ' + s.jobs);
|
|
2880
|
+
}
|
|
2881
|
+
out.push('');
|
|
2882
|
+
if (items.length) {
|
|
2883
|
+
out.push(' ' + items.length + ' thing' + (items.length === 1 ? '' : 's') + ' to check - read from your code, not proven:');
|
|
2884
|
+
for (const i of items.slice(0, opts.limit || 40)) {
|
|
2885
|
+
out.push('');
|
|
2886
|
+
out.push(' ' + i.severity.padEnd(7) + i.headline);
|
|
2887
|
+
for (const e of i.evidence) out.push(' ' + e);
|
|
2888
|
+
}
|
|
2889
|
+
if (items.length > (opts.limit || 40)) out.push('', ' ... and ' + (items.length - (opts.limit || 40)) + ' more in the saved map.');
|
|
2890
|
+
out.push('');
|
|
2891
|
+
out.push(' To prove one on your running app: npx kryptheon roles (who can do what), or the database check.');
|
|
2892
|
+
} else if (s.routes) {
|
|
2893
|
+
out.push(' Nothing to check stood out in what I could read.' + (s.auth.unknown || s.scope.unknown || s.notRead ? ' Some of it I could not tell - see below.' : ''));
|
|
2894
|
+
}
|
|
2895
|
+
if (map.notRead && map.notRead.length) {
|
|
2896
|
+
out.push('');
|
|
2897
|
+
out.push(' Not read (' + map.notRead.length + ') - what is here is not in the map, and is not a pass:');
|
|
2898
|
+
for (const n of map.notRead.slice(0, opts.limit || 40)) out.push(' ' + n.file + ':' + n.line + ' ' + n.what);
|
|
2899
|
+
if (map.notRead.length > (opts.limit || 40)) out.push(' ... and ' + (map.notRead.length - (opts.limit || 40)) + ' more in the saved map.');
|
|
2900
|
+
}
|
|
2901
|
+
if (map.unreadable && map.unreadable.length) {
|
|
2902
|
+
out.push('');
|
|
2903
|
+
out.push(' Files I could not read (' + map.unreadable.length + '):');
|
|
2904
|
+
for (const u of map.unreadable.slice(0, 20)) out.push(' ' + u.file + ' ' + u.why);
|
|
2905
|
+
}
|
|
2906
|
+
out.push('');
|
|
2907
|
+
return out;
|
|
2908
|
+
}
|
|
2909
|
+
|
|
2910
|
+
module.exports = { mapProject, listFiles, joinPath, covers, STATUS, snippet, toCheck, summary, reportLines };
|