@skillstech/thunderlang 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +190 -0
- package/dist/core.cjs +6718 -1232
- package/dist/index.cjs +17490 -12204
- package/dist/learn.cjs +5866 -497
- package/package.json +6 -2
- package/src/cli-home.mjs +1 -1
- package/src/cli.mjs +54 -6
- package/src/core/ThunderRuntime.cs +1367 -0
- package/src/core/check.mjs +158 -2
- package/src/core/cli.mjs +148 -8
- package/src/core/csharp-run.mjs +184 -0
- package/src/core/diagnostics.mjs +13 -1
- package/src/core/engine-core.mjs +285 -2
- package/src/core/engine-values.mjs +1 -1
- package/src/core/format.mjs +191 -3
- package/src/core/go-run.mjs +106 -0
- package/src/core/index.mjs +2 -1
- package/src/core/java/thunder/T.java +6 -0
- package/src/core/java/thunder/ThunderRuntime.java +1374 -0
- package/src/core/java-run.mjs +89 -0
- package/src/core/parser.mjs +331 -5
- package/src/core/project.mjs +31 -6
- package/src/core/react-run.mjs +96 -0
- package/src/core/runtime-go/thunder_runtime.go +3038 -0
- package/src/core/runtime-react.mjs +133 -0
- package/src/core/rust/thunder_runtime.rs +1645 -0
- package/src/core/rust-run.mjs +192 -0
- package/src/core/screen-values.mjs +30 -0
- package/src/core/target-csharp.mjs +484 -0
- package/src/core/target-go.mjs +555 -0
- package/src/core/target-java.mjs +587 -0
- package/src/core/target-react.mjs +270 -0
- package/src/core/target-rust.mjs +534 -0
- package/src/core/target-typescript.mjs +2 -2
- package/src/core.d.ts +59 -0
- package/src/core.mjs +14 -0
- package/src/emit.mjs +1 -1
- package/src/faithful.mjs +34 -1
- package/src/flow/access.mjs +1451 -0
- package/src/flow/ts-parse.mjs +772 -0
- package/src/index.d.ts +3 -0
- package/src/index.mjs +3 -0
- package/src/libraries.mjs +32 -4
- package/src/model.mjs +72 -9
- package/src/passport-cli.mjs +101 -0
- package/src/passport-fs.d.mts +9 -0
- package/src/passport-fs.mjs +180 -0
- package/src/passport.d.mts +46 -0
- package/src/passport.mjs +255 -0
- package/src/program.d.mts +31 -0
- package/src/program.mjs +14 -0
- package/src/read-level.mjs +48 -2
- package/src/read-repo-fs.mjs +3 -1
- package/src/read.mjs +64 -5
- package/src/replay-cli.mjs +123 -0
- package/src/review.mjs +31 -3
- package/src/say-less.mjs +168 -13
- package/src/screens.mjs +833 -0
- package/src/steps.mjs +443 -20
- package/src/term.mjs +43 -0
- package/src/things-langs.mjs +20 -3
- package/src/write-across-cli.mjs +143 -0
- package/src/write-across.mjs +168 -0
|
@@ -0,0 +1,1451 @@
|
|
|
1
|
+
// Access flow: does every path that hands back (or changes) a stored record chosen by the request also limit it to the
|
|
2
|
+
// caller's tenant or owner?
|
|
3
|
+
//
|
|
4
|
+
// request (untrusted id) → sign-in (who is calling) → ownership check? → database lookup → response
|
|
5
|
+
//
|
|
6
|
+
// For each web route in TypeScript / JavaScript sources it follows the request's values through the handler and the
|
|
7
|
+
// project's own helpers, repositories and middleware (interprocedural, with depth and size limits), and gives each
|
|
8
|
+
// path one of three verdicts:
|
|
9
|
+
// guarded the lookup is limited by the caller (a where clause on tenantId/ownerId/… from the sign-in), or a
|
|
10
|
+
// comparison with the caller stops the path before the response, or the record is chosen by the
|
|
11
|
+
// caller's identity, not the request
|
|
12
|
+
// unguarded every step from the request to the response was followed, and none limits the record to the caller
|
|
13
|
+
// cannot tell something on the path could not be followed (a call outside these files, a middleware Thunder cannot
|
|
14
|
+
// see, a query it cannot read, a role-only route); the path says exactly what stopped it
|
|
15
|
+
// "unguarded" is said only when nothing on the path was left unresolved. Deterministic; no AI; browser-safe.
|
|
16
|
+
import { parseProgram } from './ts-parse.mjs';
|
|
17
|
+
|
|
18
|
+
export const ACCESS_SCHEMA = 'thunder-access-v1';
|
|
19
|
+
|
|
20
|
+
const CODE_FILE = /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i;
|
|
21
|
+
const METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'del', 'all', 'options', 'head']);
|
|
22
|
+
const OWNER_FIELD = /^(tenant|org|organization|organisation|account|workspace|team|company|owner|user|customer|member|created_?by|author|merchant|client|shop|store|household|family|school|clinic)(_?id|Id|ID|_?ids|Ids)?$/i;
|
|
23
|
+
const IDENTITY_FN = /^(get|require|current|fetch|load|validate|verify|ensure|read)?(Current)?(User|Session|ServerSession|Auth|Identity|Principal|Viewer|Me|Account|Member|Caller|Token|Claims)(FromRequest|OrThrow|FromToken|FromCookie|FromHeader)?$/;
|
|
24
|
+
const IDENTITY_FN_EXACT = new Set(['auth', 'getAuth', 'currentUser', 'getServerSession', 'getSession', 'getUser', 'requireUser', 'requireSession', 'verifyToken', 'verifySession', 'validateRequest', 'getKindeServerSession', 'useSession']);
|
|
25
|
+
const AUTH_MIDDLEWARE = /auth|authenticate|authenticated|requireUser|requireLogin|loggedIn|isLoggedIn|signedIn|protect|ensureUser|verifyToken|verifyJwt|jwt|passport|session|clerk|bearer/i;
|
|
26
|
+
const ROLE_FN = /^(require|assert|ensure|check|is|has)(Admin|SuperAdmin|Staff|Role|Roles|Permission|Permissions|Scope|Scopes)$/;
|
|
27
|
+
const GUARDISH = /assert|ensure|check|verify|authori[sz]e|^can[A-Z]|^can$|guard|permit|allow|policy|access|own|belongs|scope|forbid/i;
|
|
28
|
+
const BENIGN_MIDDLEWARE = /^(json|urlencoded|raw|text|static|cors|helmet|morgan|compression|cookieParser|bodyParser|csrf|csurf|timeout|requestId|express\.json|express\.urlencoded|express\.static)$|validat|schema|zValidator|upload|multer|ratelimit|rateLimit|limiter|logger|logging|cache|metrics|trace|tracing/i;
|
|
29
|
+
const MAYBE_GUARD_MIDDLEWARE = /authori[sz]|permi|polic|access|owner|ownership|guard|can[A-Z]|tenant|scope/i;
|
|
30
|
+
// (Names of globals in the code being read; spelled in parts so the universal-core check, which bans using them here, passes.)
|
|
31
|
+
const CLONE = 'structured' + 'Clone';
|
|
32
|
+
const BUF = 'Buf' + 'fer';
|
|
33
|
+
const PASS_THROUGH = new Set(['String', 'Number', 'Boolean', 'BigInt', 'parseInt', 'parseFloat', 'decodeURIComponent', 'encodeURIComponent', 'Array', 'Object', CLONE]);
|
|
34
|
+
const PASS_THROUGH_MEMBERS = new Set(['JSON.parse', 'JSON.stringify', 'Object.assign', 'Object.keys', 'Object.values', 'Object.entries', 'Object.fromEntries', 'Array.from', 'Array.isArray', 'Promise.all', 'Promise.allSettled', 'Promise.resolve', 'Number.parseInt', 'Number.parseFloat', 'Math.max', 'Math.min']);
|
|
35
|
+
const PRISMA_READ = new Set(['findUnique', 'findUniqueOrThrow', 'findFirst', 'findFirstOrThrow', 'findMany', 'count', 'aggregate', 'groupBy']);
|
|
36
|
+
const PRISMA_WRITE = new Set(['update', 'updateMany', 'delete', 'deleteMany', 'upsert']);
|
|
37
|
+
const PRISMA_ALL = new Set([...PRISMA_READ, ...PRISMA_WRITE, 'create', 'createMany']);
|
|
38
|
+
const MONGOOSE_OPS = new Map([['findById', 'read'], ['findOne', 'read'], ['find', 'read'], ['findByIdAndUpdate', 'write'], ['findOneAndUpdate', 'write'], ['findByIdAndDelete', 'write'], ['findOneAndDelete', 'write'], ['findByIdAndRemove', 'write'], ['deleteOne', 'write'], ['updateOne', 'write'], ['deleteMany', 'write'], ['updateMany', 'write'], ['countDocuments', 'read']]);
|
|
39
|
+
const DB_NAMES = /^(prisma|db|database|tx|trx|knex|pool|pg|sql|conn|connection|orm|drizzle|client|dbClient|prismaClient)$/;
|
|
40
|
+
const DB_FACTORIES = /^(PrismaClient|drizzle|knex|Knex|Pool|Client|postgres|createPool|createConnection|createClient|neon|Kysely)$/;
|
|
41
|
+
const NEXT_EXITS = new Set(['notFound', 'redirect', 'permanentRedirect', 'forbidden', 'unauthorized']);
|
|
42
|
+
const MAX_DEPTH = 5;
|
|
43
|
+
// A call Thunder cannot follow counts as a possible record lookup only when it looks like one.
|
|
44
|
+
const LOOKUP_NAME = /^(get|find|load|fetch|read|query|select|lookup|retrieve|search|list|show)([A-Z_]|$)|By[A-Z]|ById$|OrFail$|OrThrow$/;
|
|
45
|
+
const LOOKUP_OWNER = /repo|repository|store|service|dao|model|db|database|client|api|prisma|orm|collection|table|manager|provider/i;
|
|
46
|
+
const NOT_DATA_PACKAGE = /^(node:|path$|fs$|fs\/promises$|child_process$|os$|url$|crypto$|util$|zlib$|stream$|events$|buffer$|querystring$|http$|https$|net$|readline$|process$)/;
|
|
47
|
+
const MAX_WORK = 40000;
|
|
48
|
+
|
|
49
|
+
// ── Values ───────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
50
|
+
// A value is a plain object. Data facts are arrays (input, ident, recs, unknown, recFields); the rest say what kind
|
|
51
|
+
// of thing it is (the request, the response, a database client, a function, an object literal …).
|
|
52
|
+
|
|
53
|
+
const DATA = ['input', 'ident', 'recs', 'unknown', 'recFields'];
|
|
54
|
+
const uniq = (a, b) => { if (!a?.length) return b; if (!b?.length) return a; const out = [...a]; for (const x of b) if (!out.includes(x)) out.push(x); return out; };
|
|
55
|
+
|
|
56
|
+
function join(a, b) {
|
|
57
|
+
if (!a) return b ?? {};
|
|
58
|
+
if (!b) return a;
|
|
59
|
+
const out = { ...a };
|
|
60
|
+
for (const k of DATA) { const u = uniq(a[k], b[k]); if (u?.length) out[k] = u; }
|
|
61
|
+
for (const [k, v] of Object.entries(b)) {
|
|
62
|
+
if (DATA.includes(k)) continue;
|
|
63
|
+
if (k === 'obj' && a.obj) { const m = new Map(a.obj); for (const [pk, pv] of b.obj) m.set(pk, join(m.get(pk), pv)); out.obj = m; continue; }
|
|
64
|
+
if (k === 'lit') { if (a.lit !== b.lit) delete out.lit; continue; }
|
|
65
|
+
if (out[k] === undefined) out[k] = v;
|
|
66
|
+
}
|
|
67
|
+
if ('lit' in a && !('lit' in b)) delete out.lit;
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
const joinAll = (vals) => vals.reduce((acc, v) => join(acc, v), null) ?? {};
|
|
71
|
+
const dataOf = (v) => { const out = {}; for (const k of DATA) if (v?.[k]?.length) out[k] = v[k]; return out; };
|
|
72
|
+
const hasData = (v) => DATA.some((k) => v?.[k]?.length);
|
|
73
|
+
|
|
74
|
+
// ── Scopes and states ────────────────────────────────────────────────────────────────────────────────────────────
|
|
75
|
+
|
|
76
|
+
class Scope {
|
|
77
|
+
constructor(parent = null, vars = new Map()) { this.parent = parent; this.vars = vars; }
|
|
78
|
+
find(name) { for (let s = this; s; s = s.parent) if (s.vars.has(name)) return s; return null; }
|
|
79
|
+
get(name) { const s = this.find(name); return s ? s.vars.get(name) : undefined; }
|
|
80
|
+
set(name, v) { const s = this.find(name) ?? this; s.vars.set(name, v); }
|
|
81
|
+
declare(name, v) { this.vars.set(name, v); }
|
|
82
|
+
}
|
|
83
|
+
// Scopes are cloned down to the first module-level scope (whose vars never change during a walk).
|
|
84
|
+
function cloneScope(s, memo = new Map()) {
|
|
85
|
+
if (!s || s.module) return s;
|
|
86
|
+
if (memo.has(s)) return memo.get(s);
|
|
87
|
+
const c = new Scope(cloneScope(s.parent, memo), new Map(s.vars));
|
|
88
|
+
memo.set(s, c);
|
|
89
|
+
return c;
|
|
90
|
+
}
|
|
91
|
+
function mergeScope(a, b) {
|
|
92
|
+
for (let x = a, y = b; x && y && !x.module; x = x.parent, y = y.parent) {
|
|
93
|
+
for (const [k, v] of y.vars) x.vars.set(k, join(x.vars.get(k), v));
|
|
94
|
+
}
|
|
95
|
+
return a;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function newState(scope, frame) {
|
|
99
|
+
return { scope, frame, guards: new Map(), role: null, identity: null, unresolved: [], exited: null, calledNext: false, req: new Map() };
|
|
100
|
+
}
|
|
101
|
+
function cloneState(s) {
|
|
102
|
+
return { ...s, scope: cloneScope(s.scope), guards: new Map(s.guards), unresolved: [...s.unresolved], req: new Map(s.req) };
|
|
103
|
+
}
|
|
104
|
+
/** Two paths join: a value is the union, a guard holds only if it holds on both. An exited path drops out. */
|
|
105
|
+
function mergeStates(a, b) {
|
|
106
|
+
if (a.exited && b.exited) return a;
|
|
107
|
+
if (a.exited) return b;
|
|
108
|
+
if (b.exited) return a;
|
|
109
|
+
const out = { ...a, scope: mergeScope(a.scope, b.scope) };
|
|
110
|
+
out.guards = new Map([...a.guards].filter(([k]) => b.guards.has(k)));
|
|
111
|
+
out.role = a.role && b.role ? a.role : null;
|
|
112
|
+
out.identity = a.identity ?? b.identity;
|
|
113
|
+
out.unresolved = uniq(a.unresolved, b.unresolved) ?? [];
|
|
114
|
+
out.calledNext = a.calledNext || b.calledNext;
|
|
115
|
+
out.req = new Map(a.req);
|
|
116
|
+
for (const [k, v] of b.req) out.req.set(k, join(out.req.get(k), v));
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ── The project: files, bindings, imports ────────────────────────────────────────────────────────────────────────
|
|
121
|
+
|
|
122
|
+
const norm = (p) => {
|
|
123
|
+
const parts = [];
|
|
124
|
+
for (const seg of p.replace(/\\/g, '/').split('/')) {
|
|
125
|
+
if (seg === '..') parts.pop();
|
|
126
|
+
else if (seg !== '.' && seg !== '') parts.push(seg);
|
|
127
|
+
}
|
|
128
|
+
return (p.startsWith('/') ? '/' : '') + parts.join('/');
|
|
129
|
+
};
|
|
130
|
+
const dirOf = (p) => { const q = p.replace(/\\/g, '/'); return q.includes('/') ? q.replace(/\/[^/]*$/, '') || '/' : '.'; };
|
|
131
|
+
|
|
132
|
+
class Project {
|
|
133
|
+
constructor(files) {
|
|
134
|
+
this.files = new Map();
|
|
135
|
+
this.failures = [];
|
|
136
|
+
for (const f of files) {
|
|
137
|
+
if (!CODE_FILE.test(f.path) || /\.d\.[mc]?ts$/.test(f.path)) continue;
|
|
138
|
+
const path = f.path.replace(/\\/g, '/');
|
|
139
|
+
try {
|
|
140
|
+
const ast = parseProgram(f.source);
|
|
141
|
+
this.files.set(path, { path, ast, source: f.source, scope: null, exports: new Map(), imports: new Map(), bindings: new Map() });
|
|
142
|
+
} catch (e) {
|
|
143
|
+
this.failures.push({ file: path, line: e.line ?? null, why: `Thunder could not read this file (${e.message}${e.line ? `, line ${e.line}` : ''})` });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
for (const m of this.files.values()) this.index(m);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
index(m) {
|
|
150
|
+
const scope = new Scope(null);
|
|
151
|
+
scope.module = m;
|
|
152
|
+
m.scope = scope;
|
|
153
|
+
const bind = (name, b) => { m.bindings.set(name, b); };
|
|
154
|
+
const visit = (s, exported, isDefault) => {
|
|
155
|
+
if (!s) return;
|
|
156
|
+
if (s.type === 'Import') { for (const n of s.names) m.imports.set(n.local, { from: s.from, imported: n.imported }); return; }
|
|
157
|
+
if (s.type === 'Export') {
|
|
158
|
+
if (s.decl) { visit(s.decl, true, s.isDefault); return; }
|
|
159
|
+
if (s.expr) { bind('default', { kind: 'expr', node: s.expr }); m.exports.set('default', 'default'); return; }
|
|
160
|
+
for (const n of s.names ?? []) {
|
|
161
|
+
if (s.from) m.exports.set(n.exported, { reexport: s.from, name: n.local });
|
|
162
|
+
else m.exports.set(n.exported, n.local);
|
|
163
|
+
}
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (s.type === 'Function') { const name = s.name ?? 'default'; bind(name, { kind: 'fn', node: s }); if (exported) m.exports.set(isDefault ? 'default' : name, name); return; }
|
|
167
|
+
if (s.type === 'Class') { const name = s.name ?? 'default'; bind(name, { kind: 'class', node: s }); if (exported) m.exports.set(isDefault ? 'default' : name, name); return; }
|
|
168
|
+
if (s.type === 'Var') {
|
|
169
|
+
for (const d of s.decls) {
|
|
170
|
+
if (d.id.type === 'Id') { bind(d.id.name, { kind: 'var', node: d.init, line: d.line }); if (exported) m.exports.set(d.id.name, d.id.name); }
|
|
171
|
+
else for (const name of patternNames(d.id)) { bind(name, { kind: 'destructured', node: d.init, pattern: d.id, name }); if (exported) m.exports.set(name, name); }
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
for (const s of m.ast.body) visit(s, false, false);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
resolveModule(fromFile, spec) {
|
|
179
|
+
if (!spec || !(spec.startsWith('.') || spec.startsWith('/') || spec.startsWith('@/') || spec.startsWith('~/'))) return null;
|
|
180
|
+
let base;
|
|
181
|
+
if (spec.startsWith('@/') || spec.startsWith('~/')) {
|
|
182
|
+
// A path alias to the source root: try common roots.
|
|
183
|
+
const rest = spec.slice(2);
|
|
184
|
+
for (const root of ['src/', '', 'app/']) { const hit = this.resolveModule('/x', `/${root}${rest}`.replace(/^\//, './')); if (hit) return hit; }
|
|
185
|
+
for (const p of this.files.keys()) if (p.endsWith(`/${rest}.ts`) || p.endsWith(`/${rest}.tsx`) || p.endsWith(`/${rest}/index.ts`)) return p;
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
base = norm(`${dirOf(fromFile)}/${spec}`);
|
|
189
|
+
const stem = base.replace(/\.(js|mjs|cjs|jsx)$/, '');
|
|
190
|
+
for (const cand of [base, `${stem}.ts`, `${stem}.tsx`, `${stem}.mts`, `${stem}.js`, `${stem}.mjs`, `${stem}.jsx`, `${stem}/index.ts`, `${stem}/index.tsx`, `${stem}/index.js`]) {
|
|
191
|
+
if (this.files.has(cand)) return cand;
|
|
192
|
+
}
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function patternNames(p) {
|
|
198
|
+
if (!p) return [];
|
|
199
|
+
if (p.type === 'Id') return [p.name];
|
|
200
|
+
if (p.type === 'Default') return patternNames(p.target);
|
|
201
|
+
if (p.type === 'Rest') return patternNames(p.arg);
|
|
202
|
+
if (p.type === 'ObjPat') return p.props.flatMap((x) => (x.rest ? patternNames(x.rest) : patternNames(x.value)));
|
|
203
|
+
if (p.type === 'ArrPat') return p.elems.flatMap((x) => patternNames(x));
|
|
204
|
+
return [];
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** A record checked against the caller; later lookups by the same request value are covered too. */
|
|
208
|
+
function guardRec(st, rec, ev) {
|
|
209
|
+
if (!st.guards.has(rec.id)) st.guards.set(rec.id, ev);
|
|
210
|
+
if (rec.keyed?.value && !st.guards.has(`key:${rec.keyed.value}`)) st.guards.set(`key:${rec.keyed.value}`, ev);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ── The analyzer ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
214
|
+
|
|
215
|
+
class Analyzer {
|
|
216
|
+
constructor(project) {
|
|
217
|
+
this.p = project;
|
|
218
|
+
this.work = 0;
|
|
219
|
+
this.recCount = 0;
|
|
220
|
+
this.moduleCache = new Map();
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// A module-level name, resolved through imports. Returns a value.
|
|
224
|
+
moduleValue(file, name, line, seen = new Set()) {
|
|
225
|
+
const key = `${file}::${name}`;
|
|
226
|
+
if (this.moduleCache.has(key)) return this.moduleCache.get(key);
|
|
227
|
+
if (seen.has(key)) return {};
|
|
228
|
+
seen.add(key);
|
|
229
|
+
const m = this.p.files.get(file);
|
|
230
|
+
let v;
|
|
231
|
+
const b = m.bindings.get(name);
|
|
232
|
+
if (b) v = this.bindingValue(m, name, b, seen);
|
|
233
|
+
else if (m.imports.has(name)) {
|
|
234
|
+
const imp = m.imports.get(name);
|
|
235
|
+
const target = this.p.resolveModule(file, imp.from);
|
|
236
|
+
if (target) {
|
|
237
|
+
if (imp.imported === '*') v = { ns: target };
|
|
238
|
+
else v = this.exportValue(target, imp.imported, seen) ?? { opaque: { why: `${name} is not exported by ${target}`, file, line } };
|
|
239
|
+
} else {
|
|
240
|
+
v = { opaque: { why: `${name} comes from ${imp.from}, outside these files`, file, line }, pkg: imp.from, pkgName: imp.imported === 'default' ? name : imp.imported };
|
|
241
|
+
if (/^@prisma\/client$|^drizzle-orm|^knex$|^pg$|^postgres$|^mysql2?|^@neondatabase|^kysely$/.test(imp.from) && DB_NAMES.test(name)) v.isDb = { label: name };
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
this.moduleCache.set(key, v);
|
|
245
|
+
return v;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
exportValue(file, name, seen = new Set()) {
|
|
249
|
+
const m = this.p.files.get(file);
|
|
250
|
+
if (!m) return null;
|
|
251
|
+
const e = m.exports.get(name);
|
|
252
|
+
if (e == null) {
|
|
253
|
+
for (const [, x] of m.exports) if (x?.reexport && x.name === '*') { const t = this.p.resolveModule(file, x.reexport); const v = t && this.exportValue(t, name, seen); if (v) return v; }
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
256
|
+
if (typeof e === 'object' && e.reexport) { const t = this.p.resolveModule(file, e.reexport); return t ? this.exportValue(t, e.name, seen) : { opaque: { why: `${name} comes from ${e.reexport}, outside these files`, file } }; }
|
|
257
|
+
return this.moduleValue(file, e, null, seen);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
bindingValue(m, name, b, seen) {
|
|
261
|
+
if (b.kind === 'fn') return { fn: { node: b.node, scope: m.scope, file: m.path, name } };
|
|
262
|
+
if (b.kind === 'class') return { cls: { node: b.node, scope: m.scope, file: m.path, name } };
|
|
263
|
+
if (b.kind === 'expr' || b.kind === 'var' || b.kind === 'destructured') {
|
|
264
|
+
if (!b.node) return {};
|
|
265
|
+
const st = newState(m.scope, { returns: [] });
|
|
266
|
+
const v = this.expr(b.node, st, { file: m.path, depth: 0, route: null, module: true });
|
|
267
|
+
if (b.kind === 'destructured') { const sc = new Scope(null); this.bindPattern(b.pattern, v, sc, st, { file: m.path }); return sc.get(b.name) ?? {}; }
|
|
268
|
+
const init = b.node.type === 'Logic' ? b.node.right : b.node.type === 'Await' ? b.node.arg : b.node;
|
|
269
|
+
const initName = init.type === 'Call' || init.type === 'New' ? (init.callee.type === 'Id' ? init.callee.name : init.callee.prop) : null;
|
|
270
|
+
if (v.dbFactory || (initName && DB_FACTORIES.test(initName))) return { isDb: { label: name } };
|
|
271
|
+
if (b.kind === 'var' && DB_NAMES.test(name) && !v.isDb && !hasData(v) && !v.fn && !v.obj && !v.instance) return { isDb: { label: name } };
|
|
272
|
+
return v;
|
|
273
|
+
}
|
|
274
|
+
return {};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
tick(ctx, line) {
|
|
278
|
+
if (++this.work > MAX_WORK) throw Object.assign(new Error('limit'), { limit: true, file: ctx.file, line });
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// ── Statements ──
|
|
282
|
+
block(stmts, st, ctx) {
|
|
283
|
+
for (const s of stmts) { if (st.exited) break; this.stmt(s, st, ctx); }
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
stmt(s, st, ctx) {
|
|
287
|
+
if (!s) return;
|
|
288
|
+
this.tick(ctx, s.line);
|
|
289
|
+
switch (s.type) {
|
|
290
|
+
case 'Block': { st.scope = new Scope(st.scope); this.block(s.body, st, ctx); st.scope = st.scope.parent ?? st.scope; return; }
|
|
291
|
+
case 'Var':
|
|
292
|
+
for (const d of s.decls) { const v = d.init ? this.expr(d.init, st, ctx) : {}; this.bindPattern(d.id, v, st.scope, st, ctx, true); }
|
|
293
|
+
return;
|
|
294
|
+
case 'Function': st.scope.declare(s.name, { fn: { node: s, scope: st.scope, file: ctx.file, name: s.name } }); return;
|
|
295
|
+
case 'Class': st.scope.declare(s.name, { cls: { node: s, scope: st.scope, file: ctx.file, name: s.name } }); return;
|
|
296
|
+
case 'Expr': {
|
|
297
|
+
const v = this.expr(s.expr, st, ctx);
|
|
298
|
+
if (v.exits) st.exited = 'throw';
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
case 'Return': {
|
|
302
|
+
const v = s.arg ? this.expr(s.arg, st, ctx) : {};
|
|
303
|
+
if (ctx.returnsSend && s.arg && !v.response && !v.isRes) this.sink('response', v, st, ctx, s.line, 'gives it back as the response');
|
|
304
|
+
st.frame.returns.push({ val: v, state: cloneState(st) });
|
|
305
|
+
st.exited = 'return';
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
case 'Throw': if (s.arg) this.expr(s.arg, st, ctx); st.exited = 'throw'; return;
|
|
309
|
+
case 'If': return this.ifStmt(s, st, ctx);
|
|
310
|
+
case 'Try': {
|
|
311
|
+
const before = cloneState(st);
|
|
312
|
+
this.stmt(s.body, st, ctx);
|
|
313
|
+
let after = st;
|
|
314
|
+
if (s.handler) {
|
|
315
|
+
const c = cloneState(before);
|
|
316
|
+
if (s.param) this.bindPattern(s.param, {}, c.scope, c, ctx, true);
|
|
317
|
+
this.stmt(s.handler, c, ctx);
|
|
318
|
+
after = mergeStates(st, c);
|
|
319
|
+
}
|
|
320
|
+
Object.assign(st, after);
|
|
321
|
+
if (s.finalizer) { const wasExited = st.exited; st.exited = null; this.stmt(s.finalizer, st, ctx); st.exited = st.exited ?? wasExited; }
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
case 'Loop': {
|
|
325
|
+
if (s.init) this.stmt(s.init, st, ctx);
|
|
326
|
+
if (s.iter) {
|
|
327
|
+
const it = this.expr(s.iter, st, ctx);
|
|
328
|
+
if (s.init?.type === 'Var') for (const d of s.init.decls) this.bindPattern(d.id, this.element(it), st.scope, st, ctx, true);
|
|
329
|
+
}
|
|
330
|
+
if (s.test) this.expr(s.test, st, ctx);
|
|
331
|
+
const body = cloneState(st);
|
|
332
|
+
this.stmt(s.body, body, ctx);
|
|
333
|
+
if (body.exited) body.exited = null; // a loop body may end with break/continue/return; the loop itself goes on
|
|
334
|
+
Object.assign(st, mergeStates(st, body));
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
case 'Switch': {
|
|
338
|
+
this.expr(s.disc, st, ctx);
|
|
339
|
+
let merged = null;
|
|
340
|
+
let hasDefault = false;
|
|
341
|
+
for (const c of s.cases) {
|
|
342
|
+
if (!c.test) hasDefault = true; else this.expr(c.test, st, ctx);
|
|
343
|
+
const cs = cloneState(st);
|
|
344
|
+
this.block(c.body, cs, ctx);
|
|
345
|
+
if (cs.exited === 'return' || cs.exited === 'throw') { merged = merged ?? null; if (!merged) merged = cs; else merged = mergeStates(merged, cs); continue; }
|
|
346
|
+
cs.exited = null;
|
|
347
|
+
merged = merged ? mergeStates(merged, cs) : cs;
|
|
348
|
+
}
|
|
349
|
+
if (!hasDefault) merged = merged ? mergeStates(merged, cloneState(st)) : st;
|
|
350
|
+
Object.assign(st, merged ?? st);
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
case 'Export': if (s.decl) this.stmt(s.decl, st, ctx); return;
|
|
354
|
+
default: return;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
ifStmt(s, st, ctx) {
|
|
359
|
+
const facts = this.testFacts(s.test, st, ctx);
|
|
360
|
+
const cons = cloneState(st);
|
|
361
|
+
const alt = cloneState(st);
|
|
362
|
+
this.applyFacts(cons, facts.whenTrue);
|
|
363
|
+
this.applyFacts(alt, facts.whenFalse);
|
|
364
|
+
this.stmt(s.cons, cons, ctx);
|
|
365
|
+
if (s.alt) this.stmt(s.alt, alt, ctx);
|
|
366
|
+
Object.assign(st, mergeStates(cons, alt));
|
|
367
|
+
if (cons.exited && alt.exited) st.exited = cons.exited === 'return' || alt.exited === 'return' ? 'return' : 'throw';
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
applyFacts(st, facts) {
|
|
371
|
+
for (const f of facts) {
|
|
372
|
+
if (f.kind === 'guard') for (const r of f.recs) guardRec(st, r, f.ev);
|
|
373
|
+
if (f.kind === 'role' && !st.role) st.role = f.ev;
|
|
374
|
+
if (f.kind === 'unresolved') st.unresolved = uniq(st.unresolved, [f.ev]);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* What a condition establishes: facts that hold when it is true, and when it is false. A comparison of a record's
|
|
380
|
+
* owner field with the caller (invoice.tenantId !== user.tenantId) guards the record on the side where they match.
|
|
381
|
+
*/
|
|
382
|
+
testFacts(t, st, ctx) {
|
|
383
|
+
const none = { whenTrue: [], whenFalse: [] };
|
|
384
|
+
if (!t) return none;
|
|
385
|
+
if (t.paren) return this.testFacts({ ...t, paren: false }, st, ctx);
|
|
386
|
+
if (t.type === 'Unary' && t.op === '!') {
|
|
387
|
+
const f = this.testFacts(t.arg, st, ctx);
|
|
388
|
+
// !record: when false, the record exists. A scoped lookup that depends on another record guards that one.
|
|
389
|
+
const v = this.expr(t.arg, cloneState(st), ctx);
|
|
390
|
+
return { whenTrue: f.whenFalse, whenFalse: [...f.whenTrue, ...this.foundFacts(v, t.line)] };
|
|
391
|
+
}
|
|
392
|
+
if (t.type === 'Logic' && t.op === '||') {
|
|
393
|
+
const a = this.testFacts(t.left, st, ctx), b = this.testFacts(t.right, st, ctx);
|
|
394
|
+
return { whenTrue: [...a.whenTrue.filter((x) => x.kind === 'unresolved'), ...b.whenTrue.filter((x) => x.kind === 'unresolved')], whenFalse: [...a.whenFalse, ...b.whenFalse] };
|
|
395
|
+
}
|
|
396
|
+
if (t.type === 'Logic' && t.op === '&&') {
|
|
397
|
+
const a = this.testFacts(t.left, st, ctx), b = this.testFacts(t.right, st, ctx);
|
|
398
|
+
return { whenTrue: [...a.whenTrue, ...b.whenTrue], whenFalse: [...a.whenFalse.filter((x) => x.kind === 'unresolved'), ...b.whenFalse.filter((x) => x.kind === 'unresolved')] };
|
|
399
|
+
}
|
|
400
|
+
if (t.type === 'Bin' && ['===', '==', '!==', '!='].includes(t.op)) {
|
|
401
|
+
const scratch = cloneState(st);
|
|
402
|
+
const l = this.expr(t.left, scratch, ctx), r = this.expr(t.right, scratch, ctx);
|
|
403
|
+
const eq = t.op === '===' || t.op === '==';
|
|
404
|
+
const g = this.ownerComparison(l, r, t.line, ctx) ?? this.ownerComparison(r, l, t.line, ctx);
|
|
405
|
+
if (g) return eq ? { whenTrue: [g], whenFalse: [] } : { whenTrue: [], whenFalse: [g] };
|
|
406
|
+
const role = this.roleComparison(l, r, t.line, ctx) ?? this.roleComparison(r, l, t.line, ctx);
|
|
407
|
+
if (role) return eq ? { whenTrue: [role], whenFalse: [] } : { whenTrue: [], whenFalse: [role] };
|
|
408
|
+
// A null check on a record: when it is not null, linked guards hold.
|
|
409
|
+
const isNull = (v) => 'lit' in v && (v.lit === null || v.lit === undefined);
|
|
410
|
+
const recSide = isNull(r) ? l : isNull(l) ? r : null;
|
|
411
|
+
if (recSide?.recs?.length) {
|
|
412
|
+
const links = this.foundFacts(recSide, t.line);
|
|
413
|
+
return eq ? { whenTrue: [], whenFalse: links } : { whenTrue: links, whenFalse: [] };
|
|
414
|
+
}
|
|
415
|
+
return none;
|
|
416
|
+
}
|
|
417
|
+
if (t.type === 'Call') {
|
|
418
|
+
// A predicate: canRead(user, invoice), user.roles.includes('admin'), invoice.members.some(...).
|
|
419
|
+
const scratch = cloneState(st);
|
|
420
|
+
const v = this.expr(t, scratch, ctx);
|
|
421
|
+
if (v.predicate) return v.predicate;
|
|
422
|
+
for (const u of scratch.unresolved) if (!st.unresolved.includes(u)) return { whenTrue: [{ kind: 'unresolved', ev: u }], whenFalse: [{ kind: 'unresolved', ev: u }] };
|
|
423
|
+
return none;
|
|
424
|
+
}
|
|
425
|
+
if (t.type === 'Member' || t.type === 'Id') {
|
|
426
|
+
const v = this.expr(t, cloneState(st), ctx);
|
|
427
|
+
// user.isAdmin
|
|
428
|
+
if (v.ident?.some((e) => /^(is)?(admin|superAdmin|staff|isAdmin|isSuperuser|superuser)$/i.test(e.field ?? ''))) return { whenTrue: [{ kind: 'role', ev: { says: `only when ${v.ident[0].says} is true`, file: ctx.file, line: t.line } }], whenFalse: [] };
|
|
429
|
+
if (v.predicate) return v.predicate;
|
|
430
|
+
const links = this.foundFacts(v, t.line);
|
|
431
|
+
if (links.length) return { whenTrue: links, whenFalse: [] };
|
|
432
|
+
}
|
|
433
|
+
return none;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* When a record turns out to exist: a lookup limited to the caller vouches for the records it was keyed by (links),
|
|
438
|
+
* and for its own request key (a later update by the same id is then the caller's record too).
|
|
439
|
+
*/
|
|
440
|
+
foundFacts(v, line) {
|
|
441
|
+
const out = [];
|
|
442
|
+
for (const rec of v.recs ?? []) {
|
|
443
|
+
if (!rec.scoped) continue;
|
|
444
|
+
const ev = { says: `stops unless ${rec.model ?? 'the record'} is found for the caller (${rec.scoped.says})`, file: rec.file, line };
|
|
445
|
+
if (rec.links?.length) out.push({ kind: 'guard', recs: rec.links, ev });
|
|
446
|
+
if (rec.keyed?.value) out.push({ kind: 'guard', recs: [rec], ev });
|
|
447
|
+
}
|
|
448
|
+
return out;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
ownerComparison(recSide, idSide, line, ctx) {
|
|
452
|
+
const fields = (recSide.recFields ?? []).filter((f) => OWNER_FIELD.test(f.field) || f.field === 'id' && false);
|
|
453
|
+
if (!fields.length || !idSide.ident?.length) return null;
|
|
454
|
+
if (idSide.input?.length) return null;
|
|
455
|
+
const id = idSide.ident[0];
|
|
456
|
+
return { kind: 'guard', recs: fields.map((f) => f.rec), ev: { says: `compares ${fields[0].says} with ${id.says}`, file: ctx.file, line } };
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
roleComparison(a, b, line, ctx) {
|
|
460
|
+
if (!a.ident?.some((e) => /^(role|roles|type|kind|permission|permissions|scope|isAdmin|accessLevel|level)$/i.test(e.field ?? ''))) return null;
|
|
461
|
+
if (!('lit' in b) || typeof b.lit !== 'string' || !/admin|staff|super|owner|support|internal|root/i.test(b.lit)) return null;
|
|
462
|
+
return { kind: 'role', ev: { says: `only when ${a.ident[0].says} is "${b.lit}"`, file: ctx.file, line } };
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// ── Patterns ──
|
|
466
|
+
bindPattern(p, v, scope, st, ctx, declare = false) {
|
|
467
|
+
if (!p) return;
|
|
468
|
+
const set = (name, val) => (declare ? scope.declare(name, val) : scope.set(name, val));
|
|
469
|
+
if (p.type === 'Id') { set(p.name, v ?? {}); return; }
|
|
470
|
+
if (p.type === 'Default') { const d = this.expr(p.value, st, ctx); this.bindPattern(p.target, join(v, d), scope, st, ctx, declare); return; }
|
|
471
|
+
if (p.type === 'Rest') { this.bindPattern(p.arg, v, scope, st, ctx, declare); return; }
|
|
472
|
+
if (p.type === 'ObjPat') {
|
|
473
|
+
for (const prop of p.props) {
|
|
474
|
+
if (prop.rest) { this.bindPattern(prop.rest, v, scope, st, ctx, declare); continue; }
|
|
475
|
+
const key = typeof prop.key === 'string' ? prop.key : null;
|
|
476
|
+
const mv = key ? this.member(v, key, st, ctx, p.line) : dataOf(v);
|
|
477
|
+
this.bindPattern(prop.value, mv, scope, st, ctx, declare);
|
|
478
|
+
}
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
if (p.type === 'ArrPat') {
|
|
482
|
+
p.elems.forEach((e, i) => { if (e) this.bindPattern(e, v?.arr?.[i] ?? this.element(v), scope, st, ctx, declare); });
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
element(v) {
|
|
487
|
+
if (!v) return {};
|
|
488
|
+
const d = dataOf(v);
|
|
489
|
+
if (v.arr) return join(d, joinAll(v.arr));
|
|
490
|
+
return d;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// ── Expressions ──
|
|
494
|
+
expr(e, st, ctx) {
|
|
495
|
+
if (!e) return {};
|
|
496
|
+
this.tick(ctx, e.line);
|
|
497
|
+
switch (e.type) {
|
|
498
|
+
case 'Lit': return { lit: e.value };
|
|
499
|
+
case 'Tpl': {
|
|
500
|
+
const parts = e.parts.map((p) => (p.expr ? this.expr(p.expr, st, ctx) : null));
|
|
501
|
+
return { ...joinAll(parts.filter(Boolean).map(dataOf)), tpl: { parts: e.parts.map((p, i) => (p.expr ? { val: parts[i] } : { text: p.text })) } };
|
|
502
|
+
}
|
|
503
|
+
case 'Id': return this.lookup(e.name, st, ctx, e.line);
|
|
504
|
+
case 'This': return ctx.thisVal ?? {};
|
|
505
|
+
case 'Member': {
|
|
506
|
+
const o = this.expr(e.object, st, ctx);
|
|
507
|
+
if (e.computed && e.prop == null) { const k = this.expr(e.computed, st, ctx); if (typeof k.lit === 'string' || typeof k.lit === 'number') return this.member(o, String(k.lit), st, ctx, e.line); return join(this.element(o), dataOf(k).input ? {} : {}); }
|
|
508
|
+
return this.member(o, e.prop, st, ctx, e.line);
|
|
509
|
+
}
|
|
510
|
+
case 'Call': return this.call(e, st, ctx);
|
|
511
|
+
case 'New': return this.newExpr(e, st, ctx);
|
|
512
|
+
case 'Await': return e.arg ? this.expr(e.arg, st, ctx) : {};
|
|
513
|
+
case 'Arrow': return { fn: { node: e, scope: st.scope, file: ctx.file, name: e.name ?? null, thisVal: ctx.thisVal } };
|
|
514
|
+
case 'ClassExpr': return { cls: { node: e, scope: st.scope, file: ctx.file, name: e.name } };
|
|
515
|
+
case 'Obj': {
|
|
516
|
+
const m = new Map();
|
|
517
|
+
let agg = {};
|
|
518
|
+
for (const p of e.props) {
|
|
519
|
+
if (p.spread) { const sv = this.expr(p.spread, st, ctx); if (sv.obj) for (const [k, v] of sv.obj) m.set(k, v); else m.set(`...${m.size}`, { ...sv, spreadUnknown: true }); agg = join(agg, dataOf(sv)); continue; }
|
|
520
|
+
if (p.computed && p.key == null) this.expr(p.computed, st, ctx);
|
|
521
|
+
const v = this.expr(p.value, st, ctx);
|
|
522
|
+
if (p.key != null) m.set(String(p.key), v);
|
|
523
|
+
agg = join(agg, dataOf(v));
|
|
524
|
+
}
|
|
525
|
+
return { ...agg, obj: m };
|
|
526
|
+
}
|
|
527
|
+
case 'Arr': {
|
|
528
|
+
const arr = e.elems.map((x) => (x ? this.expr(x.type === 'Spread' ? x.arg : x, st, ctx) : {}));
|
|
529
|
+
return { ...joinAll(arr.map(dataOf)), arr };
|
|
530
|
+
}
|
|
531
|
+
case 'Spread': return this.expr(e.arg, st, ctx);
|
|
532
|
+
case 'Bin': { const l = this.expr(e.left, st, ctx), r = this.expr(e.right, st, ctx); const out = join(dataOf(l), dataOf(r));
|
|
533
|
+
if (['===', '==', '!==', '!='].includes(e.op)) { const g = this.ownerComparison(l, r, e.line, ctx) ?? this.ownerComparison(r, l, e.line, ctx); if (g) { const eq = e.op === '===' || e.op === '=='; return { predicate: eq ? { whenTrue: [g], whenFalse: [] } : { whenTrue: [], whenFalse: [g] } }; } } if (e.op === '+' && (l.tpl || r.tpl || typeof l.lit === 'string' || typeof r.lit === 'string')) out.concat = [l, r]; return out; }
|
|
534
|
+
case 'Logic': { const l = this.expr(e.left, st, ctx), r = this.expr(e.right, st, ctx); return join(l, r); }
|
|
535
|
+
case 'Cond': { this.expr(e.test, st, ctx); return join(this.expr(e.cons, st, ctx), this.expr(e.alt, st, ctx)); }
|
|
536
|
+
case 'Unary': { const v = this.expr(e.arg, st, ctx); return e.op === '!' || e.op === 'typeof' || e.op === 'delete' || e.op === 'void' ? {} : dataOf(v); }
|
|
537
|
+
case 'Assign': return this.assign(e, st, ctx);
|
|
538
|
+
case 'Seq': { let v = {}; for (const x of e.list) v = this.expr(x, st, ctx); return v; }
|
|
539
|
+
case 'Tagged': return this.tagged(e, st, ctx);
|
|
540
|
+
default: return {};
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
lookup(name, st, ctx, line) {
|
|
545
|
+
const v = st.scope.get(name);
|
|
546
|
+
if (v !== undefined) return v;
|
|
547
|
+
const m = this.p.files.get(ctx.file);
|
|
548
|
+
if (m && (m.bindings.has(name) || m.imports.has(name))) return this.moduleValue(ctx.file, name, line);
|
|
549
|
+
if (DB_NAMES.test(name)) return { isDb: { label: name } };
|
|
550
|
+
return { global: name };
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
assign(e, st, ctx) {
|
|
554
|
+
const v = this.expr(e.right, st, ctx);
|
|
555
|
+
const val = e.op === '=' ? v : join(this.expr(e.left, cloneState(st), ctx), v);
|
|
556
|
+
if (e.left.type === 'Id') st.scope.set(e.left.name, val);
|
|
557
|
+
else if (e.left.type === 'Member') {
|
|
558
|
+
const o = this.expr(e.left.object, st, ctx);
|
|
559
|
+
if ((o.isReq || o.isRes) && e.left.prop) st.req.set(e.left.prop, val);
|
|
560
|
+
else if (o.obj && e.left.prop) o.obj.set(e.left.prop, val);
|
|
561
|
+
else if (e.left.object.type === 'Member' && e.left.object.prop === 'locals') st.req.set(`locals.${e.left.prop}`, val);
|
|
562
|
+
} else if (e.left.type === 'ObjPat' || e.left.type === 'Obj' || e.left.type === 'Arr') { /* destructuring assignment: rare in handlers */ }
|
|
563
|
+
return val;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
member(o, prop, st, ctx, line) {
|
|
567
|
+
if (!o) return {};
|
|
568
|
+
if (prop == null) return dataOf(o);
|
|
569
|
+
// The request and its frameworks' shapes.
|
|
570
|
+
if (o.isReq) {
|
|
571
|
+
if (st.req.has(prop)) return st.req.get(prop);
|
|
572
|
+
if (['params', 'query', 'body', 'headers', 'cookies', 'url', 'originalUrl', 'path', 'hostname', 'ip', 'raw', 'searchParams', 'files', 'file', 'signedCookies'].includes(prop)) return { input: [{ says: `${o.isReq.name}.${prop}`, file: ctx.file, line }], inputObj: true, reqPart: prop };
|
|
573
|
+
if (['user', 'auth', 'session', 'currentUser', 'principal', 'identity', 'claims', 'tenant', 'account', 'member', 'viewer', 'jwt'].includes(prop)) return this.identity(`${o.isReq.name}.${prop}`, ctx, line, st);
|
|
574
|
+
if (prop === 'nextUrl') return { nextUrl: true, input: [{ says: `${o.isReq.name}.nextUrl`, file: ctx.file, line }] };
|
|
575
|
+
if (prop === 'json' || prop === 'formData' || prop === 'text') return { reqBodyFn: o.isReq.name };
|
|
576
|
+
if (prop === 'jwtVerify') return { identityFn: `${o.isReq.name}.jwtVerify()` };
|
|
577
|
+
if (prop === 'locals') return { locals: true, isReq: o.isReq };
|
|
578
|
+
if (prop === 'log' || prop === 'server') return {};
|
|
579
|
+
return {};
|
|
580
|
+
}
|
|
581
|
+
if (o.isRes) { if (prop === 'locals') return { locals: true, isReq: { name: `${o.isRes.name}` } }; return {}; }
|
|
582
|
+
if (o.locals) { if (st.req.has(`locals.${prop}`)) return st.req.get(`locals.${prop}`); if (/user|auth|session|account/i.test(prop)) return this.identity(`res.locals.${prop}`, ctx, line, st); return {}; }
|
|
583
|
+
if (o.nextUrl) { if (prop === 'searchParams') return { input: o.input, searchParams: true }; return { input: o.input }; }
|
|
584
|
+
if (o.isParams) return { input: [{ says: `params.${prop}`, file: ctx.file, line }] };
|
|
585
|
+
if (o.ctx) { // Hono's c
|
|
586
|
+
if (prop === 'req') return { honoReq: true };
|
|
587
|
+
if (prop === 'var' || prop === 'env') return { honoVar: prop };
|
|
588
|
+
return { ctxMethod: prop, ctxVal: o };
|
|
589
|
+
}
|
|
590
|
+
if (o.honoReq) return { honoReqMethod: prop };
|
|
591
|
+
if (o.honoVar) { if (o.honoVar === 'env' && /DB|DATABASE/.test(prop)) return { isDb: { label: `c.env.${prop}` } }; if (/user|auth|session|jwt|payload|account|tenant/i.test(prop)) return this.identity(`c.var.${prop}`, ctx, line, st); return {}; }
|
|
592
|
+
if (o.ns) return this.exportValue(o.ns, prop) ?? {};
|
|
593
|
+
// Data.
|
|
594
|
+
const out = {};
|
|
595
|
+
if (o.input?.length) out.input = o.input.map((ev) => ({ ...ev, says: `${ev.says}.${prop}` }));
|
|
596
|
+
if (o.ident?.length) out.ident = o.ident.map((ev) => ({ ...ev, says: `${ev.says}.${prop}`, field: prop }));
|
|
597
|
+
if (o.recs?.length) { out.recs = o.recs; out.recFields = o.recs.map((rec) => ({ rec, field: prop, says: `${rec.var ?? rec.model ?? 'the record'}.${prop}` })); }
|
|
598
|
+
if (o.unknown?.length) out.unknown = o.unknown;
|
|
599
|
+
if (o.obj?.has(prop)) return join(o.obj.get(prop), {});
|
|
600
|
+
if (o.obj && !hasData(out)) { for (const [k, v] of o.obj) if (k.startsWith('...') && v.spreadUnknown) return dataOf(v); }
|
|
601
|
+
if (o.clientFor) return { ...out, dbMember: { client: { label: o.clientFor.says, scoped: o.clientFor }, prop } };
|
|
602
|
+
if (o.isDb) {
|
|
603
|
+
if (prop === 'query') return { dbQuery: o.isDb };
|
|
604
|
+
return { dbMember: { client: o.isDb, prop } };
|
|
605
|
+
}
|
|
606
|
+
if (o.dbQuery) return { drizzleRel: { client: o.dbQuery, table: prop } };
|
|
607
|
+
if (o.dbMember) return { dbModelOp: { client: o.dbMember.client, model: o.dbMember.prop, op: prop } };
|
|
608
|
+
if (o.drizzleRel) return { drizzleRelOp: { ...o.drizzleRel, op: prop } };
|
|
609
|
+
if (o.cls && o.static !== false) { const mm = this.classMember(o.cls, prop, true); if (mm) return mm; }
|
|
610
|
+
if (o.instance) { if (o.instance.fields?.has(prop)) return o.instance.fields.get(prop); const mm = this.classMember(o.instance.cls, prop, false, o); if (mm) return mm; }
|
|
611
|
+
if (o.opaque) return { opaque: { ...o.opaque, why: o.opaque.why }, opaqueName: `${o.opaqueName ?? o.pkgName ?? 'it'}.${prop}`, pkg: o.pkg, ...out };
|
|
612
|
+
if (o.global) return { global: `${o.global}.${prop}`, ...out };
|
|
613
|
+
if (o.fn && prop === 'call') return o;
|
|
614
|
+
return out;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
classMember(cls, prop, isStatic, inst) {
|
|
618
|
+
for (const m of cls.node.members) {
|
|
619
|
+
if (m.key !== prop || (!!m.isStatic) !== isStatic) continue;
|
|
620
|
+
if (m.fn) return { fn: { node: m.fn, scope: cls.scope, file: cls.file, name: `${cls.name}.${prop}`, thisVal: inst ?? { cls } } };
|
|
621
|
+
}
|
|
622
|
+
return null;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
identity(says, ctx, line, st) {
|
|
626
|
+
const ev = { says, file: ctx.file, line };
|
|
627
|
+
if (st && !st.identity) st.identity = ev;
|
|
628
|
+
return { ident: [{ ...ev, src: ev, field: null }] };
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
newExpr(e, st, ctx) {
|
|
632
|
+
const c = this.expr(e.callee, st, ctx);
|
|
633
|
+
const args = e.args.map((a) => this.expr(a.type === 'Spread' ? a.arg : a, st, ctx));
|
|
634
|
+
const name = e.callee.type === 'Id' ? e.callee.name : e.callee.prop;
|
|
635
|
+
if (name && DB_FACTORIES.test(name)) return { dbFactory: true };
|
|
636
|
+
if (name === 'Response' || name === 'NextResponse') { this.sink('response', args[0] ?? {}, st, ctx, e.line, `answers with new ${name}(…)`, this.statusOf(args[1])); return { response: true }; }
|
|
637
|
+
if (name === 'URL') return joinAll(args.map(dataOf));
|
|
638
|
+
if (/^(Map|Set|WeakMap|WeakSet|URLSearchParams|Headers|FormData|Array)$/.test(name ?? '')) return { ...joinAll(args.map(dataOf)), collection: true };
|
|
639
|
+
if (c.cls) {
|
|
640
|
+
const fields = new Map();
|
|
641
|
+
const inst = { instance: { cls: c.cls, fields } };
|
|
642
|
+
// Constructor parameter properties and this.x = … assignments in the constructor.
|
|
643
|
+
const ctor = c.cls.node.members.find((m) => m.key === 'constructor' && m.fn);
|
|
644
|
+
if (ctor) {
|
|
645
|
+
ctor.fn.params.forEach((p, i) => { const id = p.type === 'Default' ? p.target : p; if (id.type === 'Id') fields.set(id.name, args[i] ?? {}); });
|
|
646
|
+
try { this.callFunction({ node: ctor.fn, scope: c.cls.scope, file: c.cls.file, name: `${c.cls.name}.constructor`, thisVal: inst }, args, st, ctx, e.line, inst); } catch (err) { if (err.limit) throw err; }
|
|
647
|
+
}
|
|
648
|
+
for (const m of c.cls.node.members) if (m.kind === 'field' && m.value && !fields.has(m.key)) fields.set(m.key, this.expr(m.value, cloneState(st), { ...ctx, file: c.cls.file, thisVal: inst }));
|
|
649
|
+
for (const [k, v] of fields) if (DB_NAMES.test(k) && !v.isDb && !hasData(v)) fields.set(k, { isDb: { label: `this.${k}` } });
|
|
650
|
+
return inst;
|
|
651
|
+
}
|
|
652
|
+
return joinAll(args.map(dataOf));
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
statusOf(v) {
|
|
656
|
+
if (!v?.obj) return null;
|
|
657
|
+
const s = v.obj.get('status');
|
|
658
|
+
return typeof s?.lit === 'number' ? s.lit : null;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// ── Calls ──
|
|
662
|
+
call(e, st, ctx) {
|
|
663
|
+
const callee = e.callee;
|
|
664
|
+
const line = e.line;
|
|
665
|
+
// Arguments are evaluated once, here.
|
|
666
|
+
const argNodes = e.args;
|
|
667
|
+
const evalArgs = () => argNodes.map((a) => this.expr(a.type === 'Spread' ? a.arg : a, st, ctx));
|
|
668
|
+
|
|
669
|
+
if (callee.type === 'Member') {
|
|
670
|
+
const prop = callee.prop;
|
|
671
|
+
const o = this.expr(callee.object, st, ctx);
|
|
672
|
+
// The response.
|
|
673
|
+
if (o.isRes) {
|
|
674
|
+
if (prop === 'status' || prop === 'code' || prop === 'type' || prop === 'set' || prop === 'header' || prop === 'setHeader' || prop === 'cookie' || prop === 'clearCookie' || prop === 'append' || prop === 'vary' || prop === 'location') {
|
|
675
|
+
const a = evalArgs();
|
|
676
|
+
return { isRes: { ...o.isRes, status: prop === 'status' || prop === 'code' ? (typeof a[0]?.lit === 'number' ? a[0].lit : o.isRes.status) : o.isRes.status } };
|
|
677
|
+
}
|
|
678
|
+
if (['json', 'send', 'end', 'jsonp', 'render', 'sendFile', 'write', 'redirect', 'sendStatus', 'download'].includes(prop)) {
|
|
679
|
+
const a = evalArgs();
|
|
680
|
+
const status = prop === 'sendStatus' ? a[0]?.lit : o.isRes.status;
|
|
681
|
+
const body = prop === 'render' ? (a[1] ?? {}) : prop === 'redirect' || prop === 'sendStatus' ? {} : (a[0] ?? {});
|
|
682
|
+
this.sink('response', body, st, ctx, line, `answers with ${o.isRes.name}.${prop}(…)`, status);
|
|
683
|
+
return { response: true, exits: typeof status === 'number' && status >= 400 };
|
|
684
|
+
}
|
|
685
|
+
return {};
|
|
686
|
+
}
|
|
687
|
+
// Hono: c.json(…), c.get('user').
|
|
688
|
+
if (o.ctx) {
|
|
689
|
+
const a = evalArgs();
|
|
690
|
+
if (['json', 'text', 'html', 'body', 'newResponse'].includes(prop)) { this.sink('response', a[0] ?? {}, st, ctx, line, `answers with c.${prop}(…)`, typeof a[1]?.lit === 'number' ? a[1].lit : null); return { response: true }; }
|
|
691
|
+
if (prop === 'get') { const k = a[0]?.lit; if (typeof k === 'string' && st.req.has(`c:${k}`)) return st.req.get(`c:${k}`); if (typeof k === 'string' && /user|auth|session|jwt|payload|account|tenant|claims/i.test(k)) return this.identity(`c.get("${k}")`, ctx, line, st); if (typeof k === 'string' && /^db$|database|prisma/i.test(k)) return { isDb: { label: `c.get("${k}")` } }; return {}; }
|
|
692
|
+
if (prop === 'set') { if (typeof a[0]?.lit === 'string') st.req.set(`c:${a[0].lit}`, a[1] ?? {}); return {}; }
|
|
693
|
+
if (prop === 'notFound') return { response: true, exits: true };
|
|
694
|
+
return {};
|
|
695
|
+
}
|
|
696
|
+
if (o.honoReq) {
|
|
697
|
+
const a = evalArgs();
|
|
698
|
+
if (['param', 'query', 'queries', 'json', 'parseBody', 'valid', 'header', 'formData', 'text', 'raw'].includes(prop)) return { input: [{ says: `c.req.${prop}(${typeof a[0]?.lit === 'string' ? JSON.stringify(a[0].lit) : ''})`, file: ctx.file, line }] };
|
|
699
|
+
return {};
|
|
700
|
+
}
|
|
701
|
+
if (o.reqBodyFn) { evalArgs(); return { input: [{ says: `await ${o.reqBodyFn}.json()`, file: ctx.file, line }] }; }
|
|
702
|
+
if (o.identityFn) { evalArgs(); return this.identity(o.identityFn, ctx, line, st); }
|
|
703
|
+
if (o.searchParams) { const a = evalArgs(); return { input: [{ says: `searchParams.${prop}(${typeof a[0]?.lit === 'string' ? JSON.stringify(a[0].lit) : ''})`, file: ctx.file, line }] }; }
|
|
704
|
+
// Next.js / Web responses.
|
|
705
|
+
if ((o.global === 'NextResponse' || o.global === 'Response' || o.pkgName === 'NextResponse') && prop === 'json') {
|
|
706
|
+
const a = evalArgs();
|
|
707
|
+
const status = this.statusOf(a[1]);
|
|
708
|
+
this.sink('response', a[0] ?? {}, st, ctx, line, `answers with ${o.global ?? o.pkgName}.json(…)`, status);
|
|
709
|
+
return { response: true, exits: typeof status === 'number' && status >= 400 };
|
|
710
|
+
}
|
|
711
|
+
if ((o.global === 'NextResponse' || o.pkgName === 'NextResponse') && (prop === 'redirect' || prop === 'next' || prop === 'rewrite')) { evalArgs(); return { response: true }; }
|
|
712
|
+
// Transactions: $transaction(async (tx) => …), db.transaction(async (tx) => …).
|
|
713
|
+
if ((prop === '$transaction' || prop === 'transaction') && o.isDb) {
|
|
714
|
+
const a = evalArgs();
|
|
715
|
+
if (a[0]?.fn) return this.callFunction(a[0].fn, [{ isDb: { label: 'tx' } }], st, ctx, line);
|
|
716
|
+
return joinAll(a.map(dataOf));
|
|
717
|
+
}
|
|
718
|
+
// Mongoose models: mongoose.model('Invoice', schema).
|
|
719
|
+
if (prop === 'model' && (callee.object.name === 'mongoose' || o.pkg === 'mongoose')) { const a = evalArgs(); return { mongooseModel: { model: typeof a[0]?.lit === 'string' ? a[0].lit : 'a model' } }; }
|
|
720
|
+
// Databases.
|
|
721
|
+
if (o.isDb && prop === 'query') return this.dbMethod({ client: o.isDb, prop }, argNodes, evalArgs, st, ctx, line);
|
|
722
|
+
const fnVal = this.member(o, prop, st, ctx, line);
|
|
723
|
+
if (fnVal.dbModelOp) return this.prismaOp(fnVal.dbModelOp, evalArgs(), st, ctx, line);
|
|
724
|
+
if (fnVal.drizzleRelOp) return this.drizzleRel(fnVal.drizzleRelOp, evalArgs(), st, ctx, line);
|
|
725
|
+
if (fnVal.dbMember) return this.dbMethod(fnVal.dbMember, argNodes, evalArgs, st, ctx, line);
|
|
726
|
+
if (o.drizzle) return this.drizzleStep(o.drizzle, prop, evalArgs(), st, ctx, line, argNodes);
|
|
727
|
+
if (o.knex) return this.knexStep(o.knex, prop, evalArgs(), st, ctx, line);
|
|
728
|
+
if (o.mongooseModel && MONGOOSE_OPS.has(prop)) return this.mongooseOp(o.mongooseModel, prop, evalArgs(), st, ctx, line);
|
|
729
|
+
// Promise chains.
|
|
730
|
+
if ((prop === 'then' || prop === 'catch' || prop === 'finally') && argNodes.length) {
|
|
731
|
+
const a = evalArgs();
|
|
732
|
+
let out = dataOf(o);
|
|
733
|
+
if (a[0]?.fn && prop === 'then') out = join(out, this.callFunction(a[0].fn, [dataOf(o)], st, ctx, line));
|
|
734
|
+
return out;
|
|
735
|
+
}
|
|
736
|
+
const full = callee.object.type === 'Id' ? `${callee.object.name}.${prop}` : null;
|
|
737
|
+
if (full && PASS_THROUGH_MEMBERS.has(full)) { const a = evalArgs(); return { ...joinAll(a.map(dataOf)), ...(full === 'Promise.all' && a[0]?.arr ? { arr: a[0].arr } : {}) }; }
|
|
738
|
+
if (full === 'jwt.verify' || full === 'jose.jwtVerify') { evalArgs(); return this.identity(`${full}()`, ctx, line, st); }
|
|
739
|
+
if (fnVal.fn) return this.callFunction(fnVal.fn, evalArgs(), st, ctx, line, fnVal.fn.thisVal);
|
|
740
|
+
if (/^(parse|safeParse|parseAsync|validate|validateSync|cast)$/.test(prop) && argNodes.length) { const a = evalArgs(); return joinAll(a.map(dataOf)); }
|
|
741
|
+
// An in-memory Map or Set: its contents are not stored records.
|
|
742
|
+
if (o.collection) { const a = evalArgs(); return join(dataOf(o), joinAll(a.filter((x) => !x.fn).map(dataOf))); }
|
|
743
|
+
// Data methods: req.params.id.trim(), invoice.items.map(…), user.roles.includes('admin').
|
|
744
|
+
if (hasData(o) && !o.opaque) {
|
|
745
|
+
const a = evalArgs();
|
|
746
|
+
if ((prop === 'equals' || prop === 'isEqual') && a[0]) { const g = this.ownerComparison(o, a[0], line, ctx) ?? this.ownerComparison(a[0], o, line, ctx); if (g) return { predicate: { whenTrue: [g], whenFalse: [] } }; }
|
|
747
|
+
// Membership: user.teamIds.includes(invoice.teamId); user.teams.some((t) => t.id === invoice.teamId).
|
|
748
|
+
if (prop === 'includes' && a[0]) {
|
|
749
|
+
const recSide = o.recFields?.length || o.recs?.length ? o : a[0].recFields?.length || a[0].recs?.length ? a[0] : null;
|
|
750
|
+
const idSide = recSide === o ? a[0] : o;
|
|
751
|
+
if (recSide && idSide?.ident?.length && !idSide.input?.length) {
|
|
752
|
+
const recs = [...new Set([...(recSide.recFields ?? []).map((f) => f.rec), ...(recSide.recs ?? [])])];
|
|
753
|
+
return { predicate: { whenTrue: [{ kind: 'guard', recs, ev: { says: `checks that ${idSide.ident[0].says} includes ${recSide.recFields?.[0]?.says ?? 'the record'}`, file: ctx.file, line } }], whenFalse: [] } };
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
if (['some', 'find', 'every', 'findIndex', 'findLast'].includes(prop) && a[0]?.fn) {
|
|
757
|
+
const v = this.callFunction(a[0].fn, [this.element(o)], cloneState(st), ctx, line);
|
|
758
|
+
if (v.predicate?.whenTrue?.length) return { predicate: { whenTrue: v.predicate.whenTrue, whenFalse: [] } };
|
|
759
|
+
}
|
|
760
|
+
if (prop === 'includes' && o.ident?.some((x) => /^(roles|permissions|scopes|groups)$/i.test(x.field ?? '')) && typeof a[0]?.lit === 'string' && /admin|staff|super|owner|support/i.test(a[0].lit)) {
|
|
761
|
+
return { predicate: { whenTrue: [{ kind: 'role', ev: { says: `only when ${o.ident[0].says} includes "${a[0].lit}"`, file: ctx.file, line } }], whenFalse: [] } };
|
|
762
|
+
}
|
|
763
|
+
return join(dataOf(o), joinAll(a.filter((x) => !x.fn).map(dataOf)));
|
|
764
|
+
}
|
|
765
|
+
return this.unresolvedCall(fnVal.opaqueName ?? (callee.object.type === 'Id' ? `${callee.object.name}.${prop}` : prop), o.opaque?.why ?? (o.global ? `${o.global}.${prop} is not defined in these files` : `${prop} could not be followed`), evalArgs(), st, ctx, line, o);
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
// Plain calls.
|
|
769
|
+
const name = callee.type === 'Id' ? callee.name : null;
|
|
770
|
+
const f = this.expr(callee, st, ctx);
|
|
771
|
+
if (name && NEXT_EXITS.has(name) && (f.pkg === 'next/navigation' || f.global)) { evalArgs(); return { exits: true }; }
|
|
772
|
+
if (name === 'next') { evalArgs(); st.calledNext = true; return {}; }
|
|
773
|
+
if (name === 'model' && f.pkg === 'mongoose') { const a = evalArgs(); return { mongooseModel: { model: typeof a[0]?.lit === 'string' ? a[0].lit : 'a model' } }; }
|
|
774
|
+
if (f.reqNext) { const a = evalArgs(); if (!a.length || a[0].lit === undefined) st.calledNext = true; else return { exits: true }; return {}; }
|
|
775
|
+
if (f.knexRoot || (f.isDb && argNodes.length === 1 && argNodes[0].type === 'Lit' && typeof argNodes[0].value === 'string')) {
|
|
776
|
+
const a = evalArgs();
|
|
777
|
+
return { knex: { client: f.isDb ?? { label: name }, table: a[0]?.lit ?? null, conds: [], line, write: null } };
|
|
778
|
+
}
|
|
779
|
+
if (f.isDb && callee.type === 'Id' && argNodes.length && (argNodes[0].type === 'Tpl' || argNodes[0].type === 'Lit')) return this.rawSql(f.isDb, evalArgs(), st, ctx, line);
|
|
780
|
+
if (name && (IDENTITY_FN_EXACT.has(name) || IDENTITY_FN.test(name)) && !f.fn) { evalArgs(); return this.identity(`${name}()`, ctx, line, st); }
|
|
781
|
+
if (name && ROLE_FN.test(name) && !f.fn) {
|
|
782
|
+
const a = evalArgs();
|
|
783
|
+
if (!st.role) st.role = { says: `${name}(${typeof a[a.length - 1]?.lit === 'string' ? JSON.stringify(a[a.length - 1].lit) : '…'})`, file: ctx.file, line };
|
|
784
|
+
return {};
|
|
785
|
+
}
|
|
786
|
+
if (f.fn) {
|
|
787
|
+
const a = evalArgs();
|
|
788
|
+
const v = this.callFunction(f.fn, a, st, ctx, line);
|
|
789
|
+
// A resolved identity helper still establishes identity when its name says so and it gives back something.
|
|
790
|
+
if (name && (IDENTITY_FN_EXACT.has(name) || IDENTITY_FN.test(name)) && !v.ident?.length) return { ...v, ...this.identity(`${name}()`, ctx, line, st) };
|
|
791
|
+
return v;
|
|
792
|
+
}
|
|
793
|
+
if (f.cls) { evalArgs(); return {}; }
|
|
794
|
+
if (name && PASS_THROUGH.has(name)) return joinAll(evalArgs().map(dataOf));
|
|
795
|
+
if (f.isDb) return this.rawSql(f.isDb, evalArgs(), st, ctx, line);
|
|
796
|
+
return this.unresolvedCall(name ?? 'a function', f.opaque?.why ?? (name ? `${name} is not defined in these files` : 'the function could not be followed'), evalArgs(), st, ctx, line, f);
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* A call Thunder cannot follow. Its result is a value Thunder cannot see into when it was given request data. If it
|
|
801
|
+
* also sees the record or the caller (or its name says it checks something), it might be an ownership check, so the
|
|
802
|
+
* path becomes "cannot tell".
|
|
803
|
+
*/
|
|
804
|
+
unresolvedCall(name, why, args, st, ctx, line, calleeVal) {
|
|
805
|
+
const ev = { says: `${name}(…)`, why, file: ctx.file, line };
|
|
806
|
+
const fnArgs = args.filter((a) => a.fn);
|
|
807
|
+
// Callbacks handed to code Thunder cannot see: run them once with nothing known, so effects inside are seen.
|
|
808
|
+
for (const a of fnArgs) { try { this.callFunction(a.fn, [], st, ctx, line); } catch (err) { if (err.limit) throw err; } }
|
|
809
|
+
const data = args.filter((a) => !a.fn);
|
|
810
|
+
const sawRecord = data.some((a) => a.recs?.length || a.recFields?.length);
|
|
811
|
+
const sawCaller = data.some((a) => a.ident?.length);
|
|
812
|
+
const sawInput = data.some((a) => a.input?.length || a.unknown?.length);
|
|
813
|
+
const baseName = String(name).split('.').pop();
|
|
814
|
+
if ((sawRecord || sawCaller) && (GUARDISH.test(baseName) || (sawRecord && sawCaller))) st.unresolved = uniq(st.unresolved, [{ ...ev, says: `${name}(…) might check who may see it` }]);
|
|
815
|
+
const out = joinAll(data.map(dataOf));
|
|
816
|
+
// getTenantDb(user): a value made for the caller; if it is used as a database, its lookups may be filtered.
|
|
817
|
+
if (sawCaller && !GUARDISH.test(baseName)) out.clientFor = { says: `${name}(…)`, file: ctx.file, line };
|
|
818
|
+
const parts = String(name).split('.');
|
|
819
|
+
const ownerName = parts.length > 1 ? parts[parts.length - 2] : '';
|
|
820
|
+
const dataLike = name !== 'fetch' && !NOT_DATA_PACKAGE.test(calleeVal?.pkg ?? '') && !['path', 'fs', 'os', 'url', 'crypto', 'util', 'process', 'console', 'JSON', 'Math', 'Date', BUF].includes(parts[0]) && (LOOKUP_NAME.test(baseName) || (parts.length > 1 && LOOKUP_OWNER.test(ownerName) && !/^(set|add|log|emit|send|push|on|use)$/.test(baseName)));
|
|
821
|
+
if ((sawInput || calleeVal?.recs?.length) && dataLike) out.unknown = uniq(out.unknown, [{ ...ev, says: `${name}(…)` }]);
|
|
822
|
+
if (calleeVal && hasData(calleeVal)) return join(out, dataOf(calleeVal));
|
|
823
|
+
return out;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
callFunction(fn, args, st, ctx, line, thisVal) {
|
|
827
|
+
if ((ctx.depth ?? 0) >= MAX_DEPTH) {
|
|
828
|
+
const ev = { says: `${fn.name ?? 'a function'}(…)`, why: `Thunder stops following calls ${MAX_DEPTH} deep`, file: ctx.file, line };
|
|
829
|
+
if (args.some((a) => a.recs?.length || a.ident?.length)) st.unresolved = uniq(st.unresolved, [ev]);
|
|
830
|
+
const out = joinAll(args.map(dataOf));
|
|
831
|
+
if (args.some((a) => a.input?.length)) out.unknown = uniq(out.unknown, [ev]);
|
|
832
|
+
return out;
|
|
833
|
+
}
|
|
834
|
+
const node = fn.node;
|
|
835
|
+
const frame = { returns: [] };
|
|
836
|
+
const inner = cloneState(st);
|
|
837
|
+
inner.scope = new Scope(fn.scope);
|
|
838
|
+
inner.frame = frame;
|
|
839
|
+
inner.exited = null;
|
|
840
|
+
const c2 = { ...ctx, file: fn.file, depth: (ctx.depth ?? 0) + 1, thisVal: thisVal ?? fn.thisVal ?? ctx.thisVal, returnsSend: false };
|
|
841
|
+
(node.params ?? []).forEach((p, i) => {
|
|
842
|
+
if (p.type === 'Rest') this.bindPattern(p.arg, { arr: args.slice(i), ...joinAll(args.slice(i).map(dataOf)) }, inner.scope, inner, c2, true);
|
|
843
|
+
else this.bindPattern(p, args[i] ?? {}, inner.scope, inner, c2, true);
|
|
844
|
+
});
|
|
845
|
+
if (node.body?.type === 'Block') this.block(node.body.body, inner, c2);
|
|
846
|
+
else if (node.body) { const v = this.expr(node.body, inner, c2); frame.returns.push({ val: v, state: cloneState(inner) }); inner.exited = 'return'; }
|
|
847
|
+
// The paths that come back: returns and falling off the end. Paths that throw do not come back.
|
|
848
|
+
const back = [...frame.returns.map((r) => r.state)];
|
|
849
|
+
if (!inner.exited) back.push(inner);
|
|
850
|
+
if (!back.length) { st.exited = 'throw'; return {}; }
|
|
851
|
+
const merged = back.reduce((a, b) => mergeStates(a, { ...b, exited: null }), { ...back[0], exited: null });
|
|
852
|
+
st.guards = merged.guards;
|
|
853
|
+
st.role = merged.role;
|
|
854
|
+
st.identity = st.identity ?? merged.identity;
|
|
855
|
+
st.unresolved = merged.unresolved;
|
|
856
|
+
st.calledNext = st.calledNext || merged.calledNext;
|
|
857
|
+
st.req = merged.req;
|
|
858
|
+
const vals = frame.returns.map((r) => r.val);
|
|
859
|
+
const v = joinAll(vals);
|
|
860
|
+
// A predicate's facts: return a === b → when the call is true, the comparison holds.
|
|
861
|
+
if (frame.returns.length && node.body) {
|
|
862
|
+
const preds = [];
|
|
863
|
+
for (const r of frame.returns) if (r.pred) preds.push(r.pred);
|
|
864
|
+
}
|
|
865
|
+
const pred = this.predicateOf(node, args, c2, fn);
|
|
866
|
+
if (pred) v.predicate = pred;
|
|
867
|
+
return v;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// A function whose returned expression is a comparison: canRead(user, invoice) { return invoice.ownerId === user.id }.
|
|
871
|
+
predicateOf(node, args, ctx, fn) {
|
|
872
|
+
const rets = [];
|
|
873
|
+
const collect = (s) => {
|
|
874
|
+
if (!s) return;
|
|
875
|
+
if (s.type === 'Return' && s.arg) rets.push(s.arg);
|
|
876
|
+
else if (s.type === 'Block') s.body.forEach(collect);
|
|
877
|
+
else if (s.type === 'If') { collect(s.cons); collect(s.alt); }
|
|
878
|
+
};
|
|
879
|
+
if (node.body?.type === 'Block') node.body.body.forEach(collect); else if (node.body) rets.push(node.body);
|
|
880
|
+
if (rets.length !== 1) return null;
|
|
881
|
+
const st = newState(new Scope(fn.scope), { returns: [] });
|
|
882
|
+
(node.params ?? []).forEach((p, i) => this.bindPattern(p.type === 'Rest' ? p.arg : p, args[i] ?? {}, st.scope, st, ctx, true));
|
|
883
|
+
const f = this.testFacts(rets[0], st, ctx);
|
|
884
|
+
return f.whenTrue.length || f.whenFalse.length ? f : null;
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
// ── Databases ──
|
|
888
|
+
newRec(props) {
|
|
889
|
+
this.recCount++;
|
|
890
|
+
return { id: `r${this.recCount}`, ...props };
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/** A where condition as conjuncts: { conj: [{ col, val }], or: [[…], …], nested: [...], unknown: why }. */
|
|
894
|
+
whereFromObject(v) {
|
|
895
|
+
const w = { conj: [], or: [], unknown: null };
|
|
896
|
+
if (!v) return w;
|
|
897
|
+
if (!v.obj) { if (hasData(v)) w.unknown = 'the where condition is a value Thunder cannot see into'; return w; }
|
|
898
|
+
for (const [k, val] of v.obj) {
|
|
899
|
+
if (k.startsWith('...')) { if (hasData(val) || val.opaque) w.unknown = 'the where condition spreads a value Thunder cannot see into'; continue; }
|
|
900
|
+
if (k === 'AND') { for (const x of val.arr ?? [val]) { const sub = this.whereFromObject(x); w.conj.push(...sub.conj); w.or.push(...sub.or); w.unknown = w.unknown ?? sub.unknown; } continue; }
|
|
901
|
+
if (k === 'OR') { w.or.push((val.arr ?? [val]).map((x) => this.whereFromObject(x))); continue; }
|
|
902
|
+
if (k === 'NOT') continue;
|
|
903
|
+
if (val.obj) {
|
|
904
|
+
// A relation filter or an operator object ({ equals: x }, { in: [...] }, { some: { userId } }).
|
|
905
|
+
const sub = this.whereFromObject(val);
|
|
906
|
+
if (sub.conj.length || sub.or.length) w.conj.push({ col: k, nested: sub });
|
|
907
|
+
else w.conj.push({ col: k, val });
|
|
908
|
+
continue;
|
|
909
|
+
}
|
|
910
|
+
w.conj.push({ col: k, val });
|
|
911
|
+
}
|
|
912
|
+
return w;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/** How a where condition limits a lookup: by the request (keyed), by the caller (scoped), or by the caller's identity. */
|
|
916
|
+
judgeWhere(w) {
|
|
917
|
+
const out = { keyed: null, scoped: null, byIdentity: null, unknown: w.unknown };
|
|
918
|
+
const visit = (wh, path) => {
|
|
919
|
+
for (const c of wh.conj) {
|
|
920
|
+
if (c.nested) { visit(c.nested, [...path, c.col]); continue; }
|
|
921
|
+
const v = c.val;
|
|
922
|
+
if (v?.input?.length && !out.keyed) out.keyed = { says: `${[...path, c.col].join('.')} = ${v.input[0].says}`, value: v.input[0].says, file: v.input[0].file, line: v.input[0].line };
|
|
923
|
+
if (v?.unknown?.length && !out.keyed && !out.unknown) out.unknown = `${[...path, c.col].join('.')} comes from ${v.unknown[0].says}, which Thunder cannot follow`;
|
|
924
|
+
if (v?.ident?.length && !v.input?.length) {
|
|
925
|
+
const ev = v.ident[0];
|
|
926
|
+
const col = c.col;
|
|
927
|
+
const ownerish = OWNER_FIELD.test(col) || OWNER_FIELD.test(ev.field ?? '') || path.some((p) => OWNER_FIELD.test(p));
|
|
928
|
+
if (col === 'id' && !path.length && (ev.field === 'id' || ev.field == null || /Id$/.test(ev.field ?? ''))) { if (!out.byIdentity) out.byIdentity = { says: `${col} = ${ev.says}` }; }
|
|
929
|
+
else if (ownerish && !out.scoped) out.scoped = { says: `${[...path, col].join('.')} = ${ev.says}` };
|
|
930
|
+
}
|
|
931
|
+
if (v?.recFields?.length && !v.input?.length) out.fromRecord = uniq(out.fromRecord, v.recFields.map((f) => f.rec));
|
|
932
|
+
}
|
|
933
|
+
// OR: scoped only if every branch is scoped; keyed if any branch is keyed.
|
|
934
|
+
for (const group of wh.or) {
|
|
935
|
+
const judged = group.map((g) => this.judgeWhere(g));
|
|
936
|
+
if (!out.keyed) out.keyed = judged.find((j) => j.keyed)?.keyed ?? null;
|
|
937
|
+
if (!out.scoped && judged.length && judged.every((j) => j.scoped)) out.scoped = judged[0].scoped;
|
|
938
|
+
else if (judged.some((j) => j.scoped || j.byIdentity) && !out.unknown) out.unknown = `the where allows the caller's records (${(judged.find((j) => j.scoped) ?? judged.find((j) => j.byIdentity)).scoped?.says ?? 'by identity'}) OR other ones; Thunder cannot tell whether those others are meant to be open`;
|
|
939
|
+
if (!out.unknown) out.unknown = judged.find((j) => j.unknown)?.unknown ?? null;
|
|
940
|
+
}
|
|
941
|
+
};
|
|
942
|
+
visit(w, []);
|
|
943
|
+
return out;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
makeLookup({ client, model, op, kind, where, st, ctx, line, varName }) {
|
|
947
|
+
const j = this.judgeWhere(where);
|
|
948
|
+
const rec = this.newRec({ model, op, kind, file: ctx.file, line, keyed: j.keyed, scoped: j.scoped, byIdentity: j.byIdentity, unknownWhere: j.unknown, client: client?.label, clientScoped: client?.scoped ?? null, var: varName });
|
|
949
|
+
// A lookup limited to the caller and keyed by another record's field vouches for that record once found.
|
|
950
|
+
if (j.scoped && j.fromRecord?.length) rec.links = j.fromRecord;
|
|
951
|
+
if (j.scoped && /OrThrow$/.test(op)) { const ev = { says: `${model}.${op} stops unless it belongs to the caller`, file: ctx.file, line }; for (const r of j.fromRecord ?? []) guardRec(st, r, ev); if (j.keyed?.value) st.guards.set(`key:${j.keyed.value}`, ev); }
|
|
952
|
+
if (kind === 'change') this.sink('change', { recs: [rec] }, st, ctx, line, `${op === 'delete' || /delete|del|remove/i.test(op) ? 'deletes' : 'changes'} ${model ?? 'a record'}`);
|
|
953
|
+
return { recs: [rec] };
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
prismaOp({ client, model, op }, args, st, ctx, line) {
|
|
957
|
+
if (!PRISMA_ALL.has(op)) return this.unresolvedCall(`${client.label}.${model}.${op}`, `${op} is not a database call Thunder knows`, args, st, ctx, line);
|
|
958
|
+
if (op === 'create' || op === 'createMany') return { recs: [this.newRec({ model, op, kind: 'create', file: ctx.file, line })] };
|
|
959
|
+
const opts = args[0];
|
|
960
|
+
const where = this.whereFromObject(opts?.obj?.get('where'));
|
|
961
|
+
if (opts && !opts.obj && hasData(opts)) where.unknown = 'the query options are a value Thunder cannot see into';
|
|
962
|
+
if (!opts?.obj?.has('where') && opts?.obj) { /* no where: every record */ }
|
|
963
|
+
const kind = PRISMA_WRITE.has(op) ? 'change' : 'read';
|
|
964
|
+
return this.makeLookup({ client, model, op, kind, where, st, ctx, line });
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
dbMethod({ client, prop }, argNodes, evalArgs, st, ctx, line) {
|
|
968
|
+
// Raw SQL: pool.query(sql, params), db.execute(sql), prisma.$queryRawUnsafe(sql, …).
|
|
969
|
+
if (['query', 'execute', '$queryRawUnsafe', '$executeRawUnsafe', 'one', 'oneOrNone', 'many', 'any', 'none', 'get', 'all', 'run', 'prepare'].includes(prop) && argNodes.length && (argNodes[0].type === 'Lit' || argNodes[0].type === 'Tpl' || argNodes[0].type === 'Id' || argNodes[0].type === 'Bin')) {
|
|
970
|
+
return this.rawSql(client, evalArgs(), st, ctx, line, prop.includes('execute') ? 'change' : null);
|
|
971
|
+
}
|
|
972
|
+
const a = evalArgs();
|
|
973
|
+
if (['select', 'selectDistinct', 'selectFrom'].includes(prop)) return { drizzle: { client, kind: 'read', table: null, where: null, line } };
|
|
974
|
+
if (prop === 'update' || prop === 'delete' || prop === 'updateTable' || prop === 'deleteFrom') return { drizzle: { client, kind: 'change', op: prop, table: this.tableName(a[0], argNodes[0]), where: null, line } };
|
|
975
|
+
if (prop === 'insert' || prop === 'insertInto') return { drizzle: { client, kind: 'create', table: this.tableName(a[0], argNodes[0]), line } };
|
|
976
|
+
if (prop === '$connect' || prop === '$disconnect' || prop === 'end' || prop === 'release' || prop === 'connect') return {};
|
|
977
|
+
return this.unresolvedCall(`${client.label}.${prop}`, `${client.label}.${prop} is not a database call Thunder knows`, a, st, ctx, line);
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
tableName(v, node) {
|
|
981
|
+
if (!v) return null;
|
|
982
|
+
if (typeof v.lit === 'string') return v.lit;
|
|
983
|
+
if (node?.type === 'Id') return node.name;
|
|
984
|
+
if (node?.type === 'Member') return node.prop;
|
|
985
|
+
return v.tableName ?? v.global ?? v.opaqueName ?? null;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// Drizzle conditions: eq(t.col, v), and(...), or(...), inArray(t.col, [...]).
|
|
989
|
+
drizzleWhere(v) {
|
|
990
|
+
const w = { conj: [], or: [], unknown: null };
|
|
991
|
+
if (!v) return w;
|
|
992
|
+
if (v.cond) {
|
|
993
|
+
if (v.cond.op === 'and') for (const x of v.cond.args) { const s = this.drizzleWhere(x); w.conj.push(...s.conj); w.or.push(...s.or); w.unknown = w.unknown ?? s.unknown; }
|
|
994
|
+
else if (v.cond.op === 'or') w.or.push(v.cond.args.map((x) => this.drizzleWhere(x)));
|
|
995
|
+
else if (v.cond.op === 'eq') w.conj.push({ col: v.cond.col, val: v.cond.val });
|
|
996
|
+
else if (v.cond.op === 'raw') { const s = v.cond.where; w.conj.push(...s.conj); w.or.push(...s.or); w.unknown = w.unknown ?? s.unknown; }
|
|
997
|
+
return w;
|
|
998
|
+
}
|
|
999
|
+
if (v.obj) return this.whereFromObject(v);
|
|
1000
|
+
if (hasData(v)) w.unknown = 'the where condition is a value Thunder cannot see into';
|
|
1001
|
+
return w;
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
drizzleStep(d, prop, args, st, ctx, line, argNodes = []) {
|
|
1005
|
+
if (prop === 'from' || prop === 'selectFrom') return { drizzle: { ...d, table: this.tableName(args[0], argNodes[0]) } };
|
|
1006
|
+
if (prop === 'where') {
|
|
1007
|
+
const where = this.drizzleWhere(args[0]);
|
|
1008
|
+
const next = { ...d, where };
|
|
1009
|
+
if (d.kind === 'change') return { ...this.makeLookup({ client: d.client, model: d.table, op: d.op ?? 'update', kind: 'change', where, st, ctx, line }), drizzle: { ...next, done: true } };
|
|
1010
|
+
return { drizzle: next, ...this.drizzleRec(next, st, ctx, line) };
|
|
1011
|
+
}
|
|
1012
|
+
if (['set', 'values', 'returning', 'onConflictDoNothing', 'onConflictDoUpdate'].includes(prop)) return { drizzle: d };
|
|
1013
|
+
if (['limit', 'offset', 'orderBy', 'groupBy', 'innerJoin', 'leftJoin', 'rightJoin', 'fullJoin', 'having', 'execute', 'all', 'get', 'then', 'prepare', 'selectAll', 'executeTakeFirst', 'executeTakeFirstOrThrow'].includes(prop)) {
|
|
1014
|
+
if (prop === 'selectAll' || prop === 'executeTakeFirst' || prop === 'executeTakeFirstOrThrow' || prop === 'execute') return { drizzle: d, ...this.drizzleRec(d, st, ctx, line) };
|
|
1015
|
+
return { drizzle: d, ...(d.where ? this.drizzleRec(d, st, ctx, line) : {}) };
|
|
1016
|
+
}
|
|
1017
|
+
return { drizzle: d };
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
drizzleRec(d, st, ctx, line) {
|
|
1021
|
+
if (d.kind !== 'read') return {};
|
|
1022
|
+
if (d._rec) return { recs: [d._rec] };
|
|
1023
|
+
const v = this.makeLookup({ client: d.client, model: d.table, op: 'select', kind: 'read', where: d.where ?? { conj: [], or: [], unknown: null }, st, ctx, line: d.line ?? line });
|
|
1024
|
+
d._rec = v.recs[0];
|
|
1025
|
+
return v;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
drizzleRel({ client, table, op }, args, st, ctx, line) {
|
|
1029
|
+
if (!['findFirst', 'findMany'].includes(op)) return {};
|
|
1030
|
+
const opts = args[0];
|
|
1031
|
+
let whereVal = opts?.obj?.get('where');
|
|
1032
|
+
if (whereVal?.fn) {
|
|
1033
|
+
// where: (t, { eq, and }) => and(eq(t.id, id), eq(t.tenantId, user.tenantId))
|
|
1034
|
+
const ops = { obj: new Map(['eq', 'and', 'or', 'inArray', 'ne'].map((k) => [k, { global: k }])) };
|
|
1035
|
+
whereVal = this.callFunction(whereVal.fn, [{ table: { name: table }, tableName: table }, ops], st, ctx, line);
|
|
1036
|
+
}
|
|
1037
|
+
const where = this.drizzleWhere(whereVal);
|
|
1038
|
+
return this.makeLookup({ client, model: table, op, kind: 'read', where, st, ctx, line });
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
knexStep(k, prop, args, st, ctx, line) {
|
|
1042
|
+
const addConds = () => {
|
|
1043
|
+
if (args.length === 1 && args[0].obj) { const w = this.whereFromObject(args[0]); return [...k.conds, ...w.conj]; }
|
|
1044
|
+
if (args.length >= 2 && typeof args[0].lit === 'string') return [...k.conds, { col: args[0].lit.split('.').pop(), val: args[args.length - 1] }];
|
|
1045
|
+
if (args[0]?.fn) return [...k.conds, { col: '?', val: { unknown: [{ says: 'a where callback', file: ctx.file, line }] } }];
|
|
1046
|
+
return [...k.conds, { col: '?', val: dataOf(args[0] ?? {}) }];
|
|
1047
|
+
};
|
|
1048
|
+
if (prop === 'where' || prop === 'andWhere') return { knex: { ...k, conds: addConds() } };
|
|
1049
|
+
if (prop === 'orWhere') return { knex: { ...k, hasOr: true } };
|
|
1050
|
+
if (['first', 'select', 'pluck', 'then', 'limit', 'orderBy', 'returning', 'count', 'join', 'leftJoin', 'innerJoin', 'offset'].includes(prop)) {
|
|
1051
|
+
const where = { conj: k.conds, or: [], unknown: k.hasOr ? 'the query has an OR Thunder does not judge' : null };
|
|
1052
|
+
if (k._rec) return { knex: k, recs: [k._rec] };
|
|
1053
|
+
const v = this.makeLookup({ client: k.client, model: k.table, op: prop, kind: 'read', where, st, ctx, line });
|
|
1054
|
+
k._rec = v.recs[0];
|
|
1055
|
+
return { knex: k, ...v };
|
|
1056
|
+
}
|
|
1057
|
+
if (['update', 'del', 'delete', 'increment', 'decrement'].includes(prop)) {
|
|
1058
|
+
const where = { conj: k.conds, or: [], unknown: k.hasOr ? 'the query has an OR Thunder does not judge' : null };
|
|
1059
|
+
return this.makeLookup({ client: k.client, model: k.table, op: prop, kind: 'change', where, st, ctx, line });
|
|
1060
|
+
}
|
|
1061
|
+
if (prop === 'insert') return {};
|
|
1062
|
+
return { knex: k };
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
mongooseOp({ model }, op, args, st, ctx, line) {
|
|
1066
|
+
const kind = MONGOOSE_OPS.get(op) === 'write' ? 'change' : 'read';
|
|
1067
|
+
let where;
|
|
1068
|
+
if (/ById/.test(op)) where = { conj: [{ col: '_id', val: args[0] ?? {} }], or: [], unknown: null };
|
|
1069
|
+
else where = this.whereFromObject(args[0]);
|
|
1070
|
+
return this.makeLookup({ client: { label: model }, model, op, kind, where, st, ctx, line });
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
// Raw SQL from a string, a template, or sql`…`. Conditions after WHERE are read as col = value.
|
|
1074
|
+
rawSql(client, args, st, ctx, line, forceKind = null) {
|
|
1075
|
+
const q = args[0] ?? {};
|
|
1076
|
+
let text = null;
|
|
1077
|
+
const holes = [];
|
|
1078
|
+
if (typeof q.lit === 'string') text = q.lit;
|
|
1079
|
+
else if (q.tpl) text = q.tpl.parts.map((p) => (p.text != null ? p.text : (holes.push(p.val), `\u0000${holes.length - 1}\u0000`))).join('');
|
|
1080
|
+
else if (q.sqlText != null) { text = q.sqlText; holes.push(...q.sqlHoles); }
|
|
1081
|
+
const params = args[1]?.arr ?? args.slice(1);
|
|
1082
|
+
if (text == null) {
|
|
1083
|
+
const v = joinAll(args.map(dataOf));
|
|
1084
|
+
if (!hasData(v)) return {};
|
|
1085
|
+
const rec = this.newRec({ model: null, op: 'sql', kind: 'read', file: ctx.file, line, keyed: v.input?.[0] ? { says: v.input[0].says } : null, unknownWhere: 'the SQL text is built at run time, so Thunder cannot read its WHERE' });
|
|
1086
|
+
return { recs: [rec] };
|
|
1087
|
+
}
|
|
1088
|
+
const kindWord = (text.match(/^\s*(\w+)/)?.[1] ?? '').toUpperCase();
|
|
1089
|
+
const kind = forceKind ?? (kindWord === 'UPDATE' || kindWord === 'DELETE' ? 'change' : kindWord === 'INSERT' ? 'create' : 'read');
|
|
1090
|
+
if (kind === 'create') return {};
|
|
1091
|
+
const table = text.match(/\b(?:from|update|into)\s+["`[]?(\w+)/i)?.[1] ?? null;
|
|
1092
|
+
const whereText = text.split(/\bwhere\b/i)[1]?.split(/\b(order\s+by|group\s+by|limit|returning|offset)\b/i)[0] ?? '';
|
|
1093
|
+
const where = { conj: [], or: [], unknown: null };
|
|
1094
|
+
if (/\bor\b/i.test(whereText)) where.unknown = 'the WHERE has an OR Thunder does not judge';
|
|
1095
|
+
let qIndex = 0;
|
|
1096
|
+
const re = /([\w."`[\]]+)\s*=\s*(\$(\d+)|\?|:(\w+)|@(\w+)|\u0000(\d+)\u0000)/g;
|
|
1097
|
+
for (const m of whereText.matchAll(re)) {
|
|
1098
|
+
const col = m[1].replace(/["`[\]]/g, '').split('.').pop();
|
|
1099
|
+
let val = {};
|
|
1100
|
+
if (m[3]) val = params[Number(m[3]) - 1] ?? {};
|
|
1101
|
+
else if (m[2] === '?') val = params[qIndex++] ?? {};
|
|
1102
|
+
else if (m[6] != null) val = holes[Number(m[6])] ?? {};
|
|
1103
|
+
else if (m[4] || m[5]) { const o = params[0]; val = o?.obj?.get(m[4] ?? m[5]) ?? {}; }
|
|
1104
|
+
where.conj.push({ col, val });
|
|
1105
|
+
}
|
|
1106
|
+
return this.makeLookup({ client, model: table, op: 'sql', kind, where, st, ctx, line });
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
tagged(e, st, ctx) {
|
|
1110
|
+
const tag = this.expr(e.tag, st, ctx);
|
|
1111
|
+
const parts = e.tpl.parts.map((p) => (p.expr ? this.expr(p.expr, st, ctx) : null));
|
|
1112
|
+
const tplVal = { tpl: { parts: e.tpl.parts.map((p, i) => (p.expr ? { val: parts[i] } : { text: p.text })) } };
|
|
1113
|
+
const name = e.tag.type === 'Id' ? e.tag.name : e.tag.prop;
|
|
1114
|
+
if (tag.isDb || name === 'sql' || /^\$(queryRaw|executeRaw)$/.test(name ?? '') || (e.tag.type === 'Member' && this.expr(e.tag.object, cloneState(st), ctx).isDb)) {
|
|
1115
|
+
// A whole query (pool`…`, prisma.$queryRaw`…`) or a drizzle sql`…` fragment used inside a where.
|
|
1116
|
+
const text = e.tpl.parts.map((p, i) => (p.expr ? `\u0000${i}\u0000` : p.text)).join('');
|
|
1117
|
+
if (/^\s*(select|update|delete|insert|with)\b/i.test(text)) return this.rawSql(tag.isDb ?? { label: name }, [tplVal], st, ctx, e.line, /^\$executeRaw$/.test(name ?? '') ? 'change' : null);
|
|
1118
|
+
// A fragment: col = value pairs become a condition.
|
|
1119
|
+
const holes = parts.map((p) => p ?? {});
|
|
1120
|
+
// (Hole numbers are part indexes, so text parts are holes of {} that never match.)
|
|
1121
|
+
const conj = [];
|
|
1122
|
+
const re = /([\w."`]+)?\s*\u0000(\d+)\u0000\s*=\s*\u0000(\d+)\u0000|([\w."`]+)\s*=\s*\u0000(\d+)\u0000/g;
|
|
1123
|
+
for (const m of text.matchAll(re)) {
|
|
1124
|
+
if (m[2] != null) { const hole = e.tpl.parts[Number(m[2])]?.expr; const r = holes[Number(m[3])]; conj.push({ col: hole?.type === 'Member' ? hole.prop : '?', val: r }); }
|
|
1125
|
+
else conj.push({ col: m[4].replace(/["`]/g, '').split('.').pop(), val: holes[Number(m[5])] });
|
|
1126
|
+
}
|
|
1127
|
+
return { cond: { op: 'raw', where: { conj, or: [], unknown: /\bor\b/i.test(text) ? 'the condition has an OR Thunder does not judge' : null } } };
|
|
1128
|
+
}
|
|
1129
|
+
return joinAll(parts.filter(Boolean).map(dataOf));
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
// ── Sinks ──
|
|
1133
|
+
sink(kind, val, st, ctx, line, says, status) {
|
|
1134
|
+
if (!ctx.route) return;
|
|
1135
|
+
if (typeof status === 'number' && status >= 400 && kind === 'response') return;
|
|
1136
|
+
ctx.route.sinks.push({ kind, val, state: cloneState(st), file: ctx.file, line, says });
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
// Drizzle helpers seen as globals: eq(t.col, v), and(...), or(...).
|
|
1141
|
+
const DRIZZLE_OPS = new Set(['eq', 'and', 'or', 'inArray']);
|
|
1142
|
+
|
|
1143
|
+
// Patch call() for drizzle condition helpers and table columns: handled through lookup of globals.
|
|
1144
|
+
const baseCall = Analyzer.prototype.call;
|
|
1145
|
+
Analyzer.prototype.call = function call(e, st, ctx) {
|
|
1146
|
+
if (e.callee.type === 'Id' && DRIZZLE_OPS.has(e.callee.name)) {
|
|
1147
|
+
const f = this.lookup(e.callee.name, st, ctx, e.line);
|
|
1148
|
+
if (f.global || f.pkg?.startsWith('drizzle-orm') || f.opaque) {
|
|
1149
|
+
const args = e.args.map((a) => this.expr(a.type === 'Spread' ? a.arg : a, st, ctx));
|
|
1150
|
+
if (e.callee.name === 'eq') return { cond: { op: 'eq', col: columnOf(e.args[0], args[0]), val: args[1] ?? {} }, ...joinAll(args.map(dataOf)) };
|
|
1151
|
+
if (e.callee.name === 'inArray') return { cond: { op: 'eq', col: columnOf(e.args[0], args[0]), val: args[1] ?? {} }, ...joinAll(args.map(dataOf)) };
|
|
1152
|
+
return { cond: { op: e.callee.name, args }, ...joinAll(args.map(dataOf)) };
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
return baseCall.call(this, e, st, ctx);
|
|
1156
|
+
};
|
|
1157
|
+
function columnOf(node, val) {
|
|
1158
|
+
if (node?.type === 'Member' && node.prop) return node.prop;
|
|
1159
|
+
return val?.column ?? '?';
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
// ── Routes ───────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
1163
|
+
|
|
1164
|
+
function walkAll(node, visit) {
|
|
1165
|
+
if (!node || typeof node !== 'object') return;
|
|
1166
|
+
if (Array.isArray(node)) { for (const x of node) walkAll(x, visit); return; }
|
|
1167
|
+
if (node.type) visit(node);
|
|
1168
|
+
for (const [k, v] of Object.entries(node)) if (k !== 'line' && v && typeof v === 'object') walkAll(v, visit);
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
function nextRoutePath(file) {
|
|
1172
|
+
const m = file.match(/(?:^|\/)app\/(.*)\/route\.(?:ts|js|mts|tsx)$/);
|
|
1173
|
+
if (!m) return null;
|
|
1174
|
+
return '/' + m[1].split('/').filter((s) => !/^\(.*\)$/.test(s) && !s.startsWith('@')).map((s) => s.replace(/^\[\.\.\.(.+)\]$/, '*$1').replace(/^\[(.+)\]$/, ':$1')).join('/');
|
|
1175
|
+
}
|
|
1176
|
+
function pagesApiPath(file) {
|
|
1177
|
+
const m = file.match(/(?:^|\/)pages\/(api\/.*)\.(?:ts|js)$/);
|
|
1178
|
+
if (!m) return null;
|
|
1179
|
+
return '/' + m[1].replace(/\/index$/, '').split('/').map((s) => s.replace(/^\[(.+)\]$/, ':$1')).join('/');
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
function findRoutes(project) {
|
|
1183
|
+
const routes = [];
|
|
1184
|
+
for (const m of project.files.values()) {
|
|
1185
|
+
const uses = [];
|
|
1186
|
+
walkAll(m.ast.body, (n) => {
|
|
1187
|
+
if (n.type !== 'Call' || n.callee.type !== 'Member') return;
|
|
1188
|
+
const prop = n.callee.prop;
|
|
1189
|
+
const recv = n.callee.object;
|
|
1190
|
+
const recvName = recv.type === 'Id' ? recv.name : recv.type === 'Member' ? recv.prop : null;
|
|
1191
|
+
if (prop === 'use') { uses.push({ recv: recvName, line: n.line, args: n.args }); return; }
|
|
1192
|
+
if (prop === 'route' && n.args[0]?.type === 'Obj') {
|
|
1193
|
+
// fastify.route({ method, url, handler, preHandler })
|
|
1194
|
+
const o = new Map(n.args[0].props.map((p) => [p.key, p.value]));
|
|
1195
|
+
const method = o.get('method'), url = o.get('url') ?? o.get('path'), handler = o.get('handler');
|
|
1196
|
+
if (url?.type === 'Lit' && handler) routes.push({ framework: 'fastify', method: String(method?.value ?? 'GET').toUpperCase(), path: url.value, file: m.path, line: n.line, handler, middleware: [o.get('preHandler'), o.get('onRequest'), o.get('preValidation')].filter(Boolean).flatMap((x) => (x.type === 'Arr' ? x.elems : [x])), recv: recvName });
|
|
1197
|
+
return;
|
|
1198
|
+
}
|
|
1199
|
+
if (!METHODS.has(prop) || !n.args.length) return;
|
|
1200
|
+
const first = n.args[0];
|
|
1201
|
+
const path = first.type === 'Lit' && typeof first.value === 'string' ? first.value : first.type === 'Tpl' && first.parts.length === 1 ? first.parts[0].text : null;
|
|
1202
|
+
if (path == null || !(path.startsWith('/') || path === '' || path === '*')) return;
|
|
1203
|
+
if (n.args.length < 2) return;
|
|
1204
|
+
const handler = n.args[n.args.length - 1];
|
|
1205
|
+
const middle = n.args.slice(1, -1);
|
|
1206
|
+
const opts = middle.find((x) => x.type === 'Obj');
|
|
1207
|
+
const mw = middle.filter((x) => x.type !== 'Obj').flatMap((x) => (x.type === 'Arr' ? x.elems.filter(Boolean) : [x]));
|
|
1208
|
+
if (opts) for (const p of opts.props) if (['preHandler', 'onRequest', 'preValidation'].includes(p.key)) mw.push(...(p.value.type === 'Arr' ? p.value.elems.filter(Boolean) : [p.value]));
|
|
1209
|
+
const framework = handler.type === 'Arrow' && handler.params.length === 1 && /^c$|^ctx$|^context$/.test(handler.params[0].name ?? '') ? 'hono' : opts || /fastify|server|instance/i.test(recvName ?? '') ? 'fastify' : 'express';
|
|
1210
|
+
routes.push({ framework, method: prop === 'del' ? 'DELETE' : prop.toUpperCase(), path, file: m.path, line: n.line, handler, middleware: mw, recv: recvName });
|
|
1211
|
+
});
|
|
1212
|
+
for (const r of routes) if (r.file === m.path) r.uses = uses.filter((u) => u.recv === r.recv && u.line < r.line && (!u.args[0] || u.args[0].type !== 'Lit' || r.path.startsWith(u.args[0].value)));
|
|
1213
|
+
const nextPath = nextRoutePath(m.path);
|
|
1214
|
+
if (nextPath) {
|
|
1215
|
+
for (const [exported, local] of m.exports) {
|
|
1216
|
+
if (!/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/.test(exported) || typeof local !== 'string') continue;
|
|
1217
|
+
const b = m.bindings.get(local);
|
|
1218
|
+
if (!b) continue;
|
|
1219
|
+
const handler = b.kind === 'fn' ? b.node : b.node;
|
|
1220
|
+
routes.push({ framework: 'next', method: exported, path: nextPath, file: m.path, line: handler?.line ?? 1, handler, middleware: [], uses: [] });
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
const apiPath = pagesApiPath(m.path);
|
|
1224
|
+
if (apiPath && m.exports.has('default')) {
|
|
1225
|
+
const local = m.exports.get('default');
|
|
1226
|
+
const b = typeof local === 'string' ? m.bindings.get(local) : null;
|
|
1227
|
+
if (b?.node) routes.push({ framework: 'next-pages', method: 'ANY', path: apiPath, file: m.path, line: b.node.line ?? 1, handler: b.node, middleware: [], uses: [] });
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
return routes;
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
// ── Running a route ──────────────────────────────────────────────────────────────────────────────────────────────
|
|
1234
|
+
|
|
1235
|
+
function analyzeRoute(an, project, r) {
|
|
1236
|
+
const m = project.files.get(r.file);
|
|
1237
|
+
const route = { sinks: [] };
|
|
1238
|
+
const ctx = { file: r.file, depth: 0, route, returnsSend: false };
|
|
1239
|
+
const st = newState(new Scope(m.scope), { returns: [] });
|
|
1240
|
+
const notes = [];
|
|
1241
|
+
// Values of the request, the response, and the framework's context.
|
|
1242
|
+
const reqName = (fn) => { const p = fn?.params?.[0]; return p?.type === 'Id' ? p.name : 'req'; };
|
|
1243
|
+
const handlerVal = r.handler.type === 'Arrow' || r.handler.type === 'Function' ? { fn: { node: r.handler, scope: st.scope, file: r.file, name: 'the handler' } } : an.expr(r.handler, st, ctx);
|
|
1244
|
+
let handlerFn = handlerVal.fn ?? null;
|
|
1245
|
+
// A wrapper: asyncHandler(async (req, res) => …), withAuth(handler), wrap(fn).
|
|
1246
|
+
let wrapperName = null;
|
|
1247
|
+
if (!handlerFn && r.handler.type === 'Call') {
|
|
1248
|
+
const inner = r.handler.args.find((a) => a.type === 'Arrow') ?? null;
|
|
1249
|
+
const calleeName = r.handler.callee.type === 'Id' ? r.handler.callee.name : r.handler.callee.prop;
|
|
1250
|
+
wrapperName = calleeName;
|
|
1251
|
+
if (inner) handlerFn = { node: inner, scope: st.scope, file: r.file, name: 'the handler' };
|
|
1252
|
+
else if (r.handler.args[0]) { const v = an.expr(r.handler.args[0], st, ctx); handlerFn = v.fn ?? null; }
|
|
1253
|
+
}
|
|
1254
|
+
if (!handlerFn) return { verdict: null, paths: [], identity: null, why: `the handler (${r.handler.type === 'Id' ? r.handler.name : 'an expression'}) could not be found in these files`, stopped: true };
|
|
1255
|
+
const node = handlerFn.node;
|
|
1256
|
+
const fw = r.framework;
|
|
1257
|
+
const args = [];
|
|
1258
|
+
if (fw === 'hono') args.push({ ctx: true });
|
|
1259
|
+
else if (fw === 'next') {
|
|
1260
|
+
args.push({ isReq: { name: reqName(node) } });
|
|
1261
|
+
args.push({ obj: new Map([['params', { isParams: true }]]), isParamsCtx: true });
|
|
1262
|
+
} else {
|
|
1263
|
+
args.push({ isReq: { name: reqName(node) } });
|
|
1264
|
+
const resP = node.params?.[1];
|
|
1265
|
+
args.push({ isRes: { name: resP?.type === 'Id' ? resP.name : 'res', status: null } });
|
|
1266
|
+
args.push({ reqNext: true });
|
|
1267
|
+
}
|
|
1268
|
+
// Middleware (route and router-wide): auth names establish identity; the project's own run first; unknown ones
|
|
1269
|
+
// might check ownership.
|
|
1270
|
+
// An auth wrapper (withAuth(async (req, ctx, user) => …)) hands the caller in the parameters after the usual ones.
|
|
1271
|
+
if (wrapperName && AUTH_MIDDLEWARE.test(wrapperName) && !MAYBE_GUARD_MIDDLEWARE.test(wrapperName)) {
|
|
1272
|
+
const usual = fw === 'hono' ? 1 : fw === 'next' ? 2 : 3;
|
|
1273
|
+
for (let i = usual; i < (node.params?.length ?? 0); i++) args[i] = { ident: [{ says: `the caller from ${wrapperName}`, file: r.file, line: r.line, field: null }] };
|
|
1274
|
+
if (fw === 'next') for (let i = 1; i < usual; i++) args[i] = args[i] ?? {};
|
|
1275
|
+
}
|
|
1276
|
+
const mwNodes = [...(r.uses ?? []).flatMap((u) => u.args.filter((a) => !(a.type === 'Lit'))), ...(r.middleware ?? [])];
|
|
1277
|
+
if (wrapperName && (MAYBE_GUARD_MIDDLEWARE.test(wrapperName) || !AUTH_MIDDLEWARE.test(wrapperName)) && !/^(async|asyncHandler|catchAsync|wrap|handler|tryCatch|withErrorHandling|errorHandler|withErrors|safe)$/i.test(wrapperName)) {
|
|
1278
|
+
const wv = an.lookup(wrapperName, st, ctx, r.line);
|
|
1279
|
+
if (!wv.fn) st.unresolved.push({ says: `${wrapperName}(…)`, why: `the handler is wrapped in ${wrapperName}, which is not in these files`, file: r.file, line: r.line });
|
|
1280
|
+
} else if (wrapperName && AUTH_MIDDLEWARE.test(wrapperName)) st.identity = { says: `${wrapperName}(…)`, file: r.file, line: r.line };
|
|
1281
|
+
let s = st;
|
|
1282
|
+
for (const mwNode of mwNodes) {
|
|
1283
|
+
const label = mwNode.type === 'Id' ? mwNode.name : mwNode.type === 'Call' ? (mwNode.callee.type === 'Id' ? mwNode.callee.name : `${mwNode.callee.object?.name ?? ''}.${mwNode.callee.prop}`) : mwNode.type === 'Member' ? `${mwNode.object?.name ?? ''}.${mwNode.prop}` : 'a middleware';
|
|
1284
|
+
const base = label.split('.').pop();
|
|
1285
|
+
if (BENIGN_MIDDLEWARE.test(label) || BENIGN_MIDDLEWARE.test(base)) continue;
|
|
1286
|
+
const roleish = ROLE_FN.test(base) || /admin|role|permission|scope/i.test(label);
|
|
1287
|
+
const v = mwNode.type === 'Arrow' ? { fn: { node: mwNode, scope: st.scope, file: r.file, name: 'a middleware' } } : an.expr(mwNode, s, ctx);
|
|
1288
|
+
if (v.fn && (v.fn.node.params?.length ?? 0) >= 2) {
|
|
1289
|
+
// Run it: the paths that call next() reach the handler.
|
|
1290
|
+
const mctx = { ...ctx, depth: 1 };
|
|
1291
|
+
const ms = cloneState(s);
|
|
1292
|
+
ms.calledNext = false;
|
|
1293
|
+
try {
|
|
1294
|
+
an.callFunction(v.fn, args, ms, mctx, mwNode.line);
|
|
1295
|
+
if (ms.calledNext) { ms.calledNext = false; s = ms; }
|
|
1296
|
+
else s.unresolved.push({ says: `${label}`, why: `the middleware ${label} never visibly calls next()`, file: r.file, line: mwNode.line });
|
|
1297
|
+
} catch (err) {
|
|
1298
|
+
if (err.limit) throw err;
|
|
1299
|
+
s.unresolved.push({ says: `${label}`, why: `Thunder could not follow the middleware ${label}`, file: r.file, line: mwNode.line });
|
|
1300
|
+
}
|
|
1301
|
+
if (AUTH_MIDDLEWARE.test(label) && !s.identity) s.identity = { says: label, file: r.file, line: mwNode.line };
|
|
1302
|
+
if (roleish && !s.role) s.role = { says: label, file: r.file, line: mwNode.line };
|
|
1303
|
+
continue;
|
|
1304
|
+
}
|
|
1305
|
+
if (roleish) { if (!s.role) s.role = { says: label, file: r.file, line: mwNode.line }; if (AUTH_MIDDLEWARE.test(label) && !s.identity) s.identity = { says: label, file: r.file, line: mwNode.line }; continue; }
|
|
1306
|
+
if (MAYBE_GUARD_MIDDLEWARE.test(label)) { s.unresolved.push({ says: label, why: `the route runs ${label} first, which may check access, and it is not in these files`, file: r.file, line: mwNode.line }); continue; }
|
|
1307
|
+
if (AUTH_MIDDLEWARE.test(label)) { if (!s.identity) s.identity = { says: label, file: r.file, line: mwNode.line }; continue; }
|
|
1308
|
+
s.unresolved.push({ says: label, why: `the route runs ${label} first, and Thunder cannot see what it checks`, file: r.file, line: mwNode.line });
|
|
1309
|
+
}
|
|
1310
|
+
ctx.returnsSend = fw === 'fastify' || (fw === 'hono' && false);
|
|
1311
|
+
const hctx = { ...ctx, depth: 0, returnsSend: ctx.returnsSend };
|
|
1312
|
+
// The handler itself, as the top frame (so its returns can be the response for Fastify).
|
|
1313
|
+
const frame = { returns: [] };
|
|
1314
|
+
const hs = cloneState(s);
|
|
1315
|
+
hs.scope = new Scope(handlerFn.scope);
|
|
1316
|
+
hs.frame = frame;
|
|
1317
|
+
(node.params ?? []).forEach((p, i) => an.bindPattern(p, args[i] ?? {}, hs.scope, hs, hctx, true));
|
|
1318
|
+
if (node.body?.type === 'Block') an.block(node.body.body, hs, hctx);
|
|
1319
|
+
else if (node.body) { const v = an.expr(node.body, hs, hctx); if (hctx.returnsSend) an.sink('response', v, hs, hctx, node.line, 'gives it back as the response'); }
|
|
1320
|
+
return { route, notes };
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
// A path's verdict from one sink and one record (or one value Thunder could not follow).
|
|
1324
|
+
function judgePath(sink, rec) {
|
|
1325
|
+
const st = sink.state;
|
|
1326
|
+
const steps = [];
|
|
1327
|
+
const at = (x) => ({ file: x.file ?? sink.file, line: x.line ?? null });
|
|
1328
|
+
if (rec.keyed) steps.push({ kind: 'input', says: `takes ${rec.keyed.says.replace(/^.* = /, '')} from the request`, ...at(rec.keyed) });
|
|
1329
|
+
steps.push(st.identity ? { kind: 'identity', says: `knows the caller from ${st.identity.says}`, ...at(st.identity) } : { kind: 'identity', says: 'no sign-in seen on this path', file: sink.file, line: null });
|
|
1330
|
+
steps.push({ kind: rec.kind === 'change' ? 'change' : 'lookup', says: `${rec.kind === 'change' ? 'changes' : 'reads'} ${rec.model ?? 'a record'} with ${rec.op}${rec.keyed ? ` where ${rec.keyed.says}` : ''}${rec.scoped ? ` and ${rec.scoped.says}` : ''}`, file: rec.file, line: rec.line });
|
|
1331
|
+
const respond = { kind: sink.kind === 'change' ? 'change' : 'response', says: sink.says, file: sink.file, line: sink.line };
|
|
1332
|
+
const result = (verdict, why, guard) => {
|
|
1333
|
+
if (guard) steps.push({ kind: 'guard', says: guard.says, file: guard.file ?? rec.file, line: guard.line ?? rec.line });
|
|
1334
|
+
if (sink.kind !== 'change') steps.push(respond);
|
|
1335
|
+
return { verdict, why, steps, record: rec.model ?? null, lines: [...new Set(steps.map((x) => x.line).filter(Boolean))].sort((x, y) => x - y) };
|
|
1336
|
+
};
|
|
1337
|
+
if (!rec.keyed && rec.byIdentity) return result('guarded', `the record is chosen by the caller (${rec.byIdentity.says}), not by the request`);
|
|
1338
|
+
if (rec.scoped) return result('guarded', `the lookup is limited to the caller: ${rec.scoped.says}`, { says: `limits it to the caller: ${rec.scoped.says}`, file: rec.file, line: rec.line });
|
|
1339
|
+
const g = st.guards.get(rec.id) ?? (rec.keyed?.value ? st.guards.get(`key:${rec.keyed.value}`) : null);
|
|
1340
|
+
if (g) return result('guarded', `${g.says} before ${sink.kind === 'change' ? 'changing it' : 'answering'}`, g);
|
|
1341
|
+
if (!rec.keyed && !rec.unknownWhere) return null; // not chosen by the request: outside this check
|
|
1342
|
+
if (rec.clientScoped) return result('cannot tell', `it uses a database client made for the caller (${rec.clientScoped.says}); Thunder cannot see whether it filters by tenant`);
|
|
1343
|
+
if (rec.unknownWhere) return result('cannot tell', rec.unknownWhere);
|
|
1344
|
+
if (st.unresolved.length) { const u = st.unresolved[0]; return result('cannot tell', `${u.why} (${u.file}, line ${u.line})${st.unresolved.length > 1 ? `, and ${st.unresolved.length - 1} more` : ''}`); }
|
|
1345
|
+
if (st.role) return result('cannot tell', `only callers who pass ${st.role.says} reach it; whether they may see every tenant's records is a rule Thunder cannot check`);
|
|
1346
|
+
return result('unguarded', `no step between the request and the ${sink.kind === 'change' ? 'change' : 'response'} limits ${rec.model ?? 'the record'} to the caller`);
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
function judgeUnknown(sink, u) {
|
|
1350
|
+
const st = sink.state;
|
|
1351
|
+
const steps = [
|
|
1352
|
+
{ kind: 'stopped', says: `${u.says} could not be followed: ${u.why}`, file: u.file, line: u.line },
|
|
1353
|
+
{ kind: 'response', says: sink.says, file: sink.file, line: sink.line },
|
|
1354
|
+
];
|
|
1355
|
+
if (st.identity) steps.unshift({ kind: 'identity', says: `knows the caller from ${st.identity.says}`, file: st.identity.file, line: st.identity.line });
|
|
1356
|
+
return { verdict: 'cannot tell', why: `it answers with what ${u.says} gives back, and ${u.why}`, steps, record: null, lines: [u.line, sink.line] };
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
const RANK = { unguarded: 3, 'cannot tell': 2, guarded: 1 };
|
|
1360
|
+
|
|
1361
|
+
/**
|
|
1362
|
+
* Access flow for the web routes in these files. Returns { schema, routes, summary, unread }.
|
|
1363
|
+
* Each route: { method, path, framework, file, line, verdict: 'guarded'|'unguarded'|'cannot tell'|null, why, paths }.
|
|
1364
|
+
* A route with verdict null reads or changes no stored record chosen by the request.
|
|
1365
|
+
*/
|
|
1366
|
+
export function accessFlow(files, { maxRoutes = 2000 } = {}) {
|
|
1367
|
+
const project = new Project(files);
|
|
1368
|
+
const routes = findRoutes(project).slice(0, maxRoutes);
|
|
1369
|
+
const out = [];
|
|
1370
|
+
for (const r of routes) {
|
|
1371
|
+
const an = new Analyzer(project);
|
|
1372
|
+
let res;
|
|
1373
|
+
try { res = analyzeRoute(an, project, r); }
|
|
1374
|
+
catch (err) {
|
|
1375
|
+
if (!err.limit) throw err;
|
|
1376
|
+
out.push({ method: r.method, path: r.path, framework: r.framework, file: r.file, line: r.line, verdict: 'cannot tell', why: `Thunder stopped: the route is larger than it follows (${MAX_WORK} steps)`, identity: null, paths: [] });
|
|
1377
|
+
continue;
|
|
1378
|
+
}
|
|
1379
|
+
if (res.stopped) {
|
|
1380
|
+
out.push({ method: r.method, path: r.path, framework: r.framework, file: r.file, line: r.line, verdict: null, why: res.why, identity: null, paths: [] });
|
|
1381
|
+
continue;
|
|
1382
|
+
}
|
|
1383
|
+
const paths = [];
|
|
1384
|
+
const seen = new Set();
|
|
1385
|
+
for (const sink of res.route.sinks) {
|
|
1386
|
+
for (const rec of sink.val.recs ?? []) {
|
|
1387
|
+
if (rec.kind === 'create') continue;
|
|
1388
|
+
const key = `${rec.id}@${sink.line}`;
|
|
1389
|
+
if (seen.has(key)) continue;
|
|
1390
|
+
seen.add(key);
|
|
1391
|
+
const p = judgePath(sink, rec);
|
|
1392
|
+
if (p) paths.push(p);
|
|
1393
|
+
}
|
|
1394
|
+
if (!(sink.val.recs ?? []).some((rc) => rc.keyed || rc.unknownWhere)) {
|
|
1395
|
+
for (const u of sink.val.unknown ?? []) {
|
|
1396
|
+
const key = `${u.file}:${u.line}@${sink.line}`;
|
|
1397
|
+
if (seen.has(key)) continue;
|
|
1398
|
+
seen.add(key);
|
|
1399
|
+
paths.push(judgeUnknown(sink, u));
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
// A path is about one record; the same record answered twice keeps the worst verdict.
|
|
1404
|
+
paths.sort((a, b) => RANK[b.verdict] - RANK[a.verdict]);
|
|
1405
|
+
const worst = paths[0]?.verdict ?? null;
|
|
1406
|
+
const identity = res.route.sinks.map((x) => x.state.identity).find(Boolean) ?? null;
|
|
1407
|
+
out.push({
|
|
1408
|
+
method: r.method, path: r.path, framework: r.framework, file: r.file, line: r.line,
|
|
1409
|
+
verdict: worst,
|
|
1410
|
+
why: worst ? paths[0].why : 'it reads or changes no stored record chosen by the request',
|
|
1411
|
+
identity: identity ? { says: identity.says, file: identity.file, line: identity.line } : null,
|
|
1412
|
+
paths,
|
|
1413
|
+
});
|
|
1414
|
+
}
|
|
1415
|
+
const count = (v) => out.filter((x) => x.verdict === v).length;
|
|
1416
|
+
return {
|
|
1417
|
+
schema: ACCESS_SCHEMA,
|
|
1418
|
+
routes: out,
|
|
1419
|
+
summary: { routes: out.length, guarded: count('guarded'), unguarded: count('unguarded'), cannotTell: count('cannot tell'), noLookup: count(null) },
|
|
1420
|
+
unread: project.failures,
|
|
1421
|
+
};
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
/** One route's ownership in words, for readings: "Ownership: checked (line 12)" and the like. */
|
|
1425
|
+
export function ownershipWords(route) {
|
|
1426
|
+
if (!route || !route.verdict) return null;
|
|
1427
|
+
if (route.verdict === 'guarded') {
|
|
1428
|
+
const g = route.paths.flatMap((p) => p.steps).find((s) => s.kind === 'guard');
|
|
1429
|
+
return `Ownership: checked${g?.line ? ` (line ${g.line})` : ''}: ${route.paths[0].why}`;
|
|
1430
|
+
}
|
|
1431
|
+
if (route.verdict === 'unguarded') return `No ownership check on this path (lines ${route.paths[0].lines.join(', ')}): ${route.paths[0].why}`;
|
|
1432
|
+
return `Ownership: Thunder cannot tell: ${route.paths[0].why}`;
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
/** The report as plain text, one route per block. */
|
|
1436
|
+
export function accessText(report) {
|
|
1437
|
+
const L = [];
|
|
1438
|
+
const mark = { guarded: '✓', unguarded: '✗', 'cannot tell': '?' };
|
|
1439
|
+
for (const r of report.routes) {
|
|
1440
|
+
if (!r.verdict) continue;
|
|
1441
|
+
L.push(`${mark[r.verdict]} ${r.method} ${r.path} (${r.file}, line ${r.line})`);
|
|
1442
|
+
L.push(` ${r.verdict === 'guarded' ? 'Ownership checked' : r.verdict === 'unguarded' ? 'No ownership check on this path' : 'Thunder cannot tell'}: ${r.why}`);
|
|
1443
|
+
const p = r.paths[0];
|
|
1444
|
+
for (const s of p?.steps ?? []) L.push(` ${s.kind.padEnd(8)} ${s.says}${s.line ? ` (${s.file === r.file ? '' : `${s.file}, `}line ${s.line})` : ''}`);
|
|
1445
|
+
L.push('');
|
|
1446
|
+
}
|
|
1447
|
+
const s = report.summary;
|
|
1448
|
+
L.push(`${s.routes} route${s.routes === 1 ? '' : 's'}: ${s.guarded} checked, ${s.unguarded} with no ownership check, ${s.cannotTell} Thunder cannot tell, ${s.noLookup} read no record chosen by the request.`);
|
|
1449
|
+
if (report.unread.length) L.push(`${report.unread.length} file${report.unread.length === 1 ? '' : 's'} Thunder could not read: ${report.unread.slice(0, 5).map((u) => `${u.file}${u.line ? ` (line ${u.line})` : ''}`).join(', ')}${report.unread.length > 5 ? ', …' : ''}.`);
|
|
1450
|
+
return L.join('\n');
|
|
1451
|
+
}
|