launch-doctor 0.3.0 → 0.4.1
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 +92 -6
- package/LICENSE +1 -0
- package/README.md +138 -22
- package/dist/src/access.d.ts +52 -0
- package/dist/src/access.js +482 -0
- package/dist/src/baseline.d.ts +6 -3
- package/dist/src/baseline.js +15 -8
- package/dist/src/changed.d.ts +12 -0
- package/dist/src/changed.js +34 -0
- package/dist/src/checks/access.d.ts +7 -0
- package/dist/src/checks/access.js +868 -0
- package/dist/src/checks/costs.d.ts +7 -0
- package/dist/src/checks/costs.js +14 -6
- package/dist/src/checks/database.js +79 -3
- package/dist/src/checks/first-impressions.js +22 -2
- package/dist/src/checks/legal.js +3 -1
- package/dist/src/checks/monitoring.js +8 -5
- package/dist/src/checks/payments.js +10 -2
- package/dist/src/checks/secrets.d.ts +8 -0
- package/dist/src/checks/secrets.js +82 -9
- package/dist/src/checks/supabase-storage.d.ts +31 -0
- package/dist/src/checks/supabase-storage.js +216 -0
- package/dist/src/cli.js +175 -12
- package/dist/src/demo.js +1 -0
- package/dist/src/detect.d.ts +1 -1
- package/dist/src/detect.js +1 -1
- package/dist/src/fixes.js +8 -5
- package/dist/src/git.d.ts +25 -0
- package/dist/src/git.js +121 -0
- package/dist/src/github.d.ts +11 -1
- package/dist/src/github.js +56 -14
- package/dist/src/grades.d.ts +42 -0
- package/dist/src/grades.js +163 -0
- package/dist/src/history.js +17 -3
- package/dist/src/hook.d.ts +13 -0
- package/dist/src/hook.js +96 -0
- package/dist/src/hooks-setup.d.ts +24 -0
- package/dist/src/hooks-setup.js +187 -0
- package/dist/src/ignore.d.ts +36 -0
- package/dist/src/ignore.js +164 -0
- package/dist/src/index.js +28 -3
- package/dist/src/init.d.ts +32 -2
- package/dist/src/init.js +120 -6
- package/dist/src/live.d.ts +13 -1
- package/dist/src/live.js +111 -23
- package/dist/src/mcp.js +7 -2
- package/dist/src/net-guard.d.ts +42 -0
- package/dist/src/net-guard.js +147 -0
- package/dist/src/pinned-http.d.ts +31 -0
- package/dist/src/pinned-http.js +104 -0
- package/dist/src/project.d.ts +34 -5
- package/dist/src/project.js +145 -111
- package/dist/src/report.d.ts +4 -0
- package/dist/src/report.js +13 -0
- package/dist/src/routes.d.ts +10 -0
- package/dist/src/routes.js +21 -4
- package/dist/src/safe-fs.d.ts +19 -0
- package/dist/src/safe-fs.js +77 -0
- package/dist/src/sanitize.d.ts +17 -0
- package/dist/src/sanitize.js +90 -0
- package/dist/src/sarif.js +1 -1
- package/dist/src/summary.d.ts +4 -0
- package/dist/src/summary.js +9 -4
- package/dist/src/types.d.ts +24 -0
- package/dist/src/util.d.ts +1 -1
- package/dist/src/util.js +1 -1
- package/package.json +9 -5
|
@@ -0,0 +1,868 @@
|
|
|
1
|
+
import { bodyAfterParams, findUnits } from '../access.js';
|
|
2
|
+
import { AUTH_CHECK_RE, detectAuth } from '../detect.js';
|
|
3
|
+
import { matchBracket, matcherCovers, matcherToRegExp, withoutImports } from '../routes.js';
|
|
4
|
+
import { lineTextAt } from '../util.js';
|
|
5
|
+
import { appCode, clientCode, emptyOutput, isRouteLike, notApplicable, serverCode, where } from './common.js';
|
|
6
|
+
import { MIDDLEWARE_BLOCKS, matcherEntries } from './costs.js';
|
|
7
|
+
/*
|
|
8
|
+
* Access control: can one person reach or change data that isn't theirs?
|
|
9
|
+
*
|
|
10
|
+
* Everything here is pattern-based, so each finding is worded as "check this". The rules follow
|
|
11
|
+
* the official guidance they cite (Next.js data security guide, Supabase RLS docs, OWASP IDOR and
|
|
12
|
+
* mass assignment cheat sheets) and accept the usual ways apps do the check correctly:
|
|
13
|
+
* a scoped query, fetch-then-compare, a policy helper, an admin gate, or a signed-in wrapper.
|
|
14
|
+
*/
|
|
15
|
+
const MAX_PER_ID = 5;
|
|
16
|
+
// ---------- who is calling ----------
|
|
17
|
+
/** Sign-in helpers beyond the shared AUTH_CHECK_RE (getCurrentUser(), requireOrgMember(), ...). */
|
|
18
|
+
const AUTH_EXTRA = /\b(?:get|require|ensure|assert|check|verify|validate|fetch|load|must)(?:Current|Signed[iI]n|LoggedIn|Authed)?(?:User|Session|Auth|Viewer|Member|Account|Me)\w*\s*\(|\bgetClaims\s*\(|\bauthenticate\w*\s*\(|\bauth\.protect\s*\(/;
|
|
19
|
+
const PY_AUTH = /(?:Depends|Security)\(\s*[\w.]*(?:user|auth|current|session|token|login|verify|jwt|principal|account|member|admin|claims)\w*|\bcurrent_user\b|\bget_jwt_identity\s*\(|\bverify_jwt_in_request\s*\(|\brequest\.user\b|\bg\.user\b|\bsession\[\s*["']user/i;
|
|
20
|
+
/** Function names defined in `shared` that this unit calls and that check who is signed in. */
|
|
21
|
+
/** The source of one helper defined at `at` in `code`, cut at its real end (not running into the next function). */
|
|
22
|
+
function helperBody(code, at, python) {
|
|
23
|
+
if (python) {
|
|
24
|
+
const indent = /^[ \t]*/.exec(code.slice(code.lastIndexOf('\n', at) + 1))[0].length;
|
|
25
|
+
const lines = code.slice(at).split('\n');
|
|
26
|
+
let end = lines[0].length;
|
|
27
|
+
for (const line of lines.slice(1)) {
|
|
28
|
+
if (line.trim() && /^[ \t]*/.exec(line)[0].length <= indent)
|
|
29
|
+
break;
|
|
30
|
+
end += line.length + 1;
|
|
31
|
+
}
|
|
32
|
+
return code.slice(at, at + end);
|
|
33
|
+
}
|
|
34
|
+
const paren = code.indexOf('(', at);
|
|
35
|
+
const body = paren === -1 ? null : bodyAfterParams(code, paren);
|
|
36
|
+
return body ? code.slice(at, body.end) : '';
|
|
37
|
+
}
|
|
38
|
+
/** The helpers defined next to this unit (same file) that it calls. */
|
|
39
|
+
function calledHelpers(u) {
|
|
40
|
+
const out = [];
|
|
41
|
+
const seen = new Set();
|
|
42
|
+
for (const m of u.text.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)) {
|
|
43
|
+
const name = m[1];
|
|
44
|
+
if (seen.has(name))
|
|
45
|
+
continue;
|
|
46
|
+
seen.add(name);
|
|
47
|
+
const def = new RegExp(`(?:function\\s+|(?:const|let|var)\\s+|def\\s+)${name.replace(/\$/g, '\\$')}\\b`).exec(u.shared);
|
|
48
|
+
if (def)
|
|
49
|
+
out.push(helperBody(u.shared, def.index, u.kind === 'python'));
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
function callsAuthHelper(u) {
|
|
54
|
+
return calledHelpers(u).some((body) => AUTH_CHECK_RE.test(body) || AUTH_EXTRA.test(body) || PY_AUTH.test(body));
|
|
55
|
+
}
|
|
56
|
+
function signsInCaller(u) {
|
|
57
|
+
if (u.authOutside)
|
|
58
|
+
return true;
|
|
59
|
+
if (u.kind === 'python')
|
|
60
|
+
return PY_AUTH.test(u.text) || callsAuthHelper(u);
|
|
61
|
+
return (AUTH_CHECK_RE.test(u.text) ||
|
|
62
|
+
AUTH_EXTRA.test(u.text) ||
|
|
63
|
+
// The modules it reaches, without their import lines: a helper that is only imported checks nothing.
|
|
64
|
+
AUTH_CHECK_RE.test(withoutImports(u.reachedCode)) ||
|
|
65
|
+
callsAuthHelper(u));
|
|
66
|
+
}
|
|
67
|
+
const SESSION_SRC = /\b(?:session|getServerSession|getSession|auth|getAuth|currentUser|current_user|getCurrentUser|get_current_user|getUser|getClaims|claims|viewer|locals\.user|ctx\.user|ctx\.session|ctx\.auth|ctx\.userId|req\.user|req\.auth|request\.user|request\.auth|g\.user|get_jwt_identity)\b|\buser\??\.(?:id|uid|sub|userId|pk)\b|\bme\??\.id\b/;
|
|
68
|
+
const REQUEST_SRC = /\b(?:params|searchParams|query|body|formData|input|args|parsedInput|req\.(?:params|query|body|json|formData)|request\.(?:args|form|json|get_json|GET|POST|data|query_params|path_params|values|files|formData|nextUrl)|nextUrl|c\.req|event\.(?:params|body|queryStringParameters|pathParameters)|getRouterParam|getQuery|readBody)\b/;
|
|
69
|
+
/** Parameters that a framework fills in itself, not the caller. */
|
|
70
|
+
const INJECTED_PARAM = /^(?:request|req|res|response|self|cls|db|session|current_user|user|me|background_tasks|settings|ctx|context|next|c|event)$/;
|
|
71
|
+
function escapeRe(s) {
|
|
72
|
+
return s.replace(/[$]/g, '\\$');
|
|
73
|
+
}
|
|
74
|
+
function paramNames(u) {
|
|
75
|
+
if (!u.paramsFromCaller)
|
|
76
|
+
return [];
|
|
77
|
+
if (u.kind === 'trpc')
|
|
78
|
+
return ['input'];
|
|
79
|
+
if (u.kind === 'python') {
|
|
80
|
+
return u.params
|
|
81
|
+
.split(',')
|
|
82
|
+
.filter((p) => !/(?:Depends|Security)\(/.test(p))
|
|
83
|
+
.map((p) => /^\s*\**\s*(\w+)/.exec(p)?.[1] ?? '')
|
|
84
|
+
.filter((n) => n && !INJECTED_PARAM.test(n));
|
|
85
|
+
}
|
|
86
|
+
// Every identifier in a JS parameter list (destructured names included); type names never match a lookup value.
|
|
87
|
+
return [...u.params.matchAll(/(?<![\w$])([A-Za-z_$][\w$]*)\s*(?=[,:=})?]|$)/g)].map((m) => m[1]);
|
|
88
|
+
}
|
|
89
|
+
/** The right-hand side that defines `name` inside the function, or null. */
|
|
90
|
+
function definitionOf(name, u) {
|
|
91
|
+
const n = escapeRe(name);
|
|
92
|
+
if (u.kind === 'python') {
|
|
93
|
+
return new RegExp(`^[ \\t]*${n}\\s*(?::[^=\\n]+)?=(?!=)\\s*(.+)$`, 'm').exec(u.text)?.[1] ?? null;
|
|
94
|
+
}
|
|
95
|
+
const direct = new RegExp(`(?:const|let|var)\\s+${n}\\s*(?::[^=;]+)?=\\s*([^;\\n]+)`).exec(u.text);
|
|
96
|
+
if (direct)
|
|
97
|
+
return direct[1];
|
|
98
|
+
for (const m of u.text.matchAll(/(?:const|let|var)\s*\{([^{}]*)\}\s*(?::[^=;]+)?=\s*([^;\n]+)/g)) {
|
|
99
|
+
if (new RegExp(`(?:^|[,{\\s])${n}\\s*(?:[,=}]|$)|:\\s*${n}\\b`).test(m[1]))
|
|
100
|
+
return m[2];
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
/** Does this value come from the request, from the signed-in session, or can't we tell? */
|
|
105
|
+
export function originOf(expr, u, depth = 0) {
|
|
106
|
+
const e = expr
|
|
107
|
+
.trim()
|
|
108
|
+
.replace(/^await\s+/, '')
|
|
109
|
+
.replace(/^(?:Number|parseInt|parseFloat|String|BigInt|int|str|uuid\.UUID|UUID)\s*\(\s*/, '')
|
|
110
|
+
.replace(/\s+as\s+[\w<>[\]|\s]+$/, '')
|
|
111
|
+
.replace(/[!)\s]+$/, '');
|
|
112
|
+
if (!e)
|
|
113
|
+
return 'unknown';
|
|
114
|
+
if (SESSION_SRC.test(e))
|
|
115
|
+
return 'session';
|
|
116
|
+
if (REQUEST_SRC.test(e))
|
|
117
|
+
return 'request';
|
|
118
|
+
const id = /^([A-Za-z_$][\w$]*)$/.exec(e)?.[1] ?? /^\(?\s*([A-Za-z_$][\w$]*)/.exec(e)?.[1];
|
|
119
|
+
if (!id || depth > 2)
|
|
120
|
+
return 'unknown';
|
|
121
|
+
const rhs = definitionOf(id, u);
|
|
122
|
+
if (rhs !== null)
|
|
123
|
+
return originOf(rhs, u, depth + 1);
|
|
124
|
+
if (paramNames(u).includes(id))
|
|
125
|
+
return 'request';
|
|
126
|
+
return 'unknown';
|
|
127
|
+
}
|
|
128
|
+
// ---------- ownership evidence ----------
|
|
129
|
+
const OWNER_FIELD = /\b(?:user|owner|author|creator|created_?by|tenant|org|organi[sz]ation|account|team|workspace|member|profile|customer|seller|buyer)_?(?:id|Id|ID|uid)\b|\bcreated_?[bB]y\b|\buid\b/g;
|
|
130
|
+
const OWNER_RELATION = /\b(?:user|owner|author|creator|tenant|organi[sz]ation|org|account|team|workspace|members?)\s*:\s*\{/;
|
|
131
|
+
const PY_OWNER_KW = /\b(?:owner|user|author|created_by|creator|account|tenant|organization|org|team|customer)(?:_id)?\s*(?:=(?!=)|==)\s*([^,)\n]+)/g;
|
|
132
|
+
/** A filter in the query itself that limits it to the caller's records (and isn't taken from the request). */
|
|
133
|
+
function scopedQuery(query, u) {
|
|
134
|
+
if (OWNER_RELATION.test(query))
|
|
135
|
+
return true;
|
|
136
|
+
for (const m of query.matchAll(OWNER_FIELD)) {
|
|
137
|
+
const rest = query.slice(m.index + m[0].length);
|
|
138
|
+
const v = /^\s*["'`]?\s*\]?\s*(?:,|:|===?|==|=)\s*([^,})\n]+)/.exec(rest);
|
|
139
|
+
// No separator after it: only a shorthand key ({ id, userId }) counts. `body.userId` is a value, not a filter.
|
|
140
|
+
if (!v && !/[{,]\s*$/.test(query.slice(0, m.index)))
|
|
141
|
+
continue;
|
|
142
|
+
if (originOf(v ? v[1] : m[0], u) !== 'request')
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
if (u.kind === 'python') {
|
|
146
|
+
for (const m of query.matchAll(PY_OWNER_KW)) {
|
|
147
|
+
// "user=Depends(get_current_user)" is a parameter that receives the user, not a filter.
|
|
148
|
+
if (/^\s*(?:Depends|Security)\s*\(/.test(m[1]))
|
|
149
|
+
continue;
|
|
150
|
+
if (originOf(m[1], u) !== 'request')
|
|
151
|
+
return true;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
const OWNER_KEY = '(?:user|owner|author|creator|created_?by|tenant|org|organi[sz]ation|account|team|workspace|profile|customer|seller)_?(?:id|Id|ID|uid)';
|
|
157
|
+
/** Fetch-then-compare: `if (note.userId !== session.user.id)` or `if note.owner_id != current_user.id`. */
|
|
158
|
+
const OWNER_COMPARE = new RegExp([
|
|
159
|
+
`\\.${OWNER_KEY}\\b\\s*(?:!==?|===?|!=|==)`,
|
|
160
|
+
`(?:!==?|===?|!=|==)\\s*[\\w$.?\\[\\]'"]*\\.${OWNER_KEY}\\b`,
|
|
161
|
+
'\\b(?:session|user|currentUser|current_user|claims|viewer|me)\\??\\.(?:id|uid|sub|userId|pk)\\s*(?:!==?|===?|!=|==)',
|
|
162
|
+
'(?:!==?|===?|!=|==)\\s*(?:[\\w$]+\\??\\.)*(?:user|currentUser|current_user|claims|viewer|me)\\??\\.(?:id|uid|sub|userId|pk)\\b',
|
|
163
|
+
'\\.uid\\s*(?:!==?|===?|!=|==)',
|
|
164
|
+
'\\.(?:owner|user|author)\\s*(?:!=|==)\\s*(?:request\\.user|current_user|user)\\b',
|
|
165
|
+
'\\b(?:request\\.user|current_user)\\.\\w+\\.(?:get|filter|all)\\s*\\(',
|
|
166
|
+
].join('|'));
|
|
167
|
+
/** Policy helpers (CASL, Casbin, hand-written ones). */
|
|
168
|
+
const POLICY_HELPER = /\b(?:authori[sz]e\w*|can|cannot|ability\.can|checkPermission\w*|hasPermission\w*|checkAccess|hasAccess|canAccess|canEdit|canDelete|canView|canUpdate|isOwner|isMember|has_perm|has_object_permission|check_object_permissions|(?:assert|ensure|require|check|verify|enforce)\w*(?:Owner|Access|Permission|Member|Membership|Can)\w*|(?:assert|ensure|require|check|verify)_\w*(?:owner|access|permission|member)\w*)\s*\(/;
|
|
169
|
+
/** Admin-only code may legitimately touch anyone's records. */
|
|
170
|
+
const ADMIN_GATE = /\brole\s*(?:!==?|===?|!=|==)\s*["'`](?:admin|superadmin|super_admin|owner|staff)["'`]|["'`](?:admin|superadmin)["'`]\s*(?:!==?|===?|!=|==)\s*[\w$.?]*\brole\b|\bisAdmin\b|\bis_admin\b|\bis_staff\b|\bis_superuser\b|\b(?:require|assert|ensure|check|verify)_?Admin\w*|\bisSuperAdmin\b|\bhasRole\s*\(|\bhas_role\s*\(|\badminProcedure\b|\bIsAdminUser\b|\bstaff_member_required\b|\bhas\(\s*\{\s*role|\b(?:authenticate|verify|require|check|assert)\w*(?:Gateway|Internal|Worker|Machine)\w*\s*\(/;
|
|
171
|
+
function checksOwnership(u) {
|
|
172
|
+
return u.adminOnly || OWNER_COMPARE.test(u.text) || POLICY_HELPER.test(u.text) || ADMIN_GATE.test(u.text);
|
|
173
|
+
}
|
|
174
|
+
/** Models that are usually public, so reading one by id is normal. */
|
|
175
|
+
const PUBLIC_MODEL = /^(?:products?|posts?|articles?|blogs?|blogPosts?|pages?|categor(?:y|ies)|tags?|plans?|prices?|pricing|events?|listings?|courses?|lessons?|faqs?|reviews?|testimonials?|recipes?|jobs?|users?|profiles?|authors?|tools?|templates?|items?)$/i;
|
|
176
|
+
const NOT_A_MODEL = /^(?:stripe|cache|map|redis|kv|cookies|cookieStore|headers|store|storage|bucket|params|searchParams|url|formData|set|hash|crypto|hmac|resend|axios|api|http|fetch|localStorage|sessionStorage|queryClient|this|Object|Reflect)$/;
|
|
177
|
+
function statementAround(text, index) {
|
|
178
|
+
const before = text.lastIndexOf(';', index);
|
|
179
|
+
const start = Math.max(before + 1, index - 600, 0);
|
|
180
|
+
let end = text.indexOf(';', index);
|
|
181
|
+
if (end === -1 || end > index + 600)
|
|
182
|
+
end = Math.min(text.length, index + 600);
|
|
183
|
+
return text.slice(start, end);
|
|
184
|
+
}
|
|
185
|
+
/** From `index` to the end of its statement (or 600 characters). */
|
|
186
|
+
function statementAfter(text, index) {
|
|
187
|
+
let end = text.indexOf(';', index);
|
|
188
|
+
if (end === -1 || end > index + 600)
|
|
189
|
+
end = Math.min(text.length, index + 600);
|
|
190
|
+
return text.slice(index, end);
|
|
191
|
+
}
|
|
192
|
+
const ORM_CALL = /\.(findUnique(?:OrThrow)?|findFirst(?:OrThrow)?|update|delete|upsert|destroy|findOne|findOneAndUpdate|findOneAndDelete|findOneAndRemove|updateOne|deleteOne)\s*\(/g;
|
|
193
|
+
const READ_METHODS = /^(?:findUnique|findUniqueOrThrow|findFirst|findFirstOrThrow|findOne)$/;
|
|
194
|
+
const BY_ID_CALL = /\b([A-Z][\w$]*)\.(findById|findByIdAndUpdate|findByIdAndDelete|findByIdAndRemove|findByPk)\s*\(/g;
|
|
195
|
+
const DRIZZLE_EQ = /\beq\(\s*([\w$]+)\.(?:id|_id)\s*,\s*([^)]+)\)/g;
|
|
196
|
+
const SUPABASE_FROM = /\.from\(\s*["'`]([\w.-]+)["'`]\s*\)/g;
|
|
197
|
+
const FIREBASE_DOC = /\.collection\(\s*["'`]([\w-]+)["'`]\s*\)\s*\.doc\(\s*([^)]+)\)/g;
|
|
198
|
+
/** The value of the `id` key in an object literal, or null. */
|
|
199
|
+
function idValue(obj) {
|
|
200
|
+
const explicit = /(?:^|[{,\s])(?:_id|id)\s*:\s*([^,}\n]+)/.exec(obj);
|
|
201
|
+
if (explicit)
|
|
202
|
+
return explicit[1];
|
|
203
|
+
if (/[{,]\s*(?:_id|id)\s*[,}]/.test(obj))
|
|
204
|
+
return 'id';
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
function jsLookups(u, firebaseAdmin) {
|
|
208
|
+
const t = u.text;
|
|
209
|
+
const out = [];
|
|
210
|
+
for (const m of t.matchAll(ORM_CALL)) {
|
|
211
|
+
const receiver = /([\w$]+)\s*\??\.?\s*$/.exec(t.slice(Math.max(0, m.index - 60), m.index))?.[1] ?? '';
|
|
212
|
+
if (!receiver || NOT_A_MODEL.test(receiver))
|
|
213
|
+
continue;
|
|
214
|
+
// Supabase's builder (.from("x").update(...)) is read separately.
|
|
215
|
+
if (/\)\s*$/.test(t.slice(Math.max(0, m.index - 2), m.index)))
|
|
216
|
+
continue;
|
|
217
|
+
const open = m.index + m[0].length - 1;
|
|
218
|
+
const close = matchBracket(t, open);
|
|
219
|
+
if (close === -1)
|
|
220
|
+
continue;
|
|
221
|
+
let arg = t.slice(open, close + 1);
|
|
222
|
+
const whereAt = /\bwhere\s*:\s*\{/.exec(arg);
|
|
223
|
+
if (whereAt) {
|
|
224
|
+
const brace = whereAt.index + whereAt[0].length - 1;
|
|
225
|
+
const end = matchBracket(arg, brace);
|
|
226
|
+
if (end !== -1)
|
|
227
|
+
arg = arg.slice(brace, end + 1);
|
|
228
|
+
}
|
|
229
|
+
const id = idValue(arg);
|
|
230
|
+
if (id === null)
|
|
231
|
+
continue;
|
|
232
|
+
out.push({ index: m.index, id, model: receiver, mutation: !READ_METHODS.test(m[1]), query: arg });
|
|
233
|
+
}
|
|
234
|
+
for (const m of t.matchAll(BY_ID_CALL)) {
|
|
235
|
+
const open = m.index + m[0].length - 1;
|
|
236
|
+
const close = matchBracket(t, open);
|
|
237
|
+
if (close === -1)
|
|
238
|
+
continue;
|
|
239
|
+
const first = /^\(\s*([^,)]+)/.exec(t.slice(open, close + 1))?.[1];
|
|
240
|
+
if (!first)
|
|
241
|
+
continue;
|
|
242
|
+
out.push({ index: m.index, id: first, model: m[1], mutation: !/^find(?:ById|ByPk)$/.test(m[2]), query: '' });
|
|
243
|
+
}
|
|
244
|
+
for (const m of t.matchAll(DRIZZLE_EQ)) {
|
|
245
|
+
const stmt = statementAround(t, m.index);
|
|
246
|
+
out.push({
|
|
247
|
+
index: m.index,
|
|
248
|
+
id: m[2],
|
|
249
|
+
model: m[1],
|
|
250
|
+
mutation: /\.(?:update|delete)\s*\(\s*[\w$.]+\s*\)/.test(stmt),
|
|
251
|
+
query: stmt,
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
for (const m of t.matchAll(SUPABASE_FROM)) {
|
|
255
|
+
const stmt = statementAfter(t, m.index);
|
|
256
|
+
const eq = /\.(?:eq|match)\(\s*["'`]id["'`]\s*,\s*([^)]+)\)/.exec(stmt);
|
|
257
|
+
if (!eq)
|
|
258
|
+
continue;
|
|
259
|
+
out.push({
|
|
260
|
+
index: m.index,
|
|
261
|
+
id: eq[1],
|
|
262
|
+
model: m[1],
|
|
263
|
+
mutation: /\.(?:update|delete|upsert)\s*\(/.test(stmt),
|
|
264
|
+
query: stmt,
|
|
265
|
+
supabase: true,
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
if (firebaseAdmin) {
|
|
269
|
+
for (const m of t.matchAll(FIREBASE_DOC)) {
|
|
270
|
+
const stmt = statementAround(t, m.index);
|
|
271
|
+
out.push({
|
|
272
|
+
index: m.index,
|
|
273
|
+
id: m[2],
|
|
274
|
+
model: m[1],
|
|
275
|
+
mutation: /\.(?:update|delete|set)\s*\(/.test(stmt),
|
|
276
|
+
query: '',
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return out.sort((a, b) => a.index - b.index);
|
|
281
|
+
}
|
|
282
|
+
function pyLookups(u) {
|
|
283
|
+
const t = u.text;
|
|
284
|
+
const out = [];
|
|
285
|
+
const lineAt = (i) => lineTextAt(t, i);
|
|
286
|
+
const mutation = (i) => /^(?:PUT|PATCH|DELETE)$/.test(u.method) ||
|
|
287
|
+
/\.delete\s*\(|\.update\s*\(|\.commit\s*\(|\.save\s*\(/.test(lineAt(i)) ||
|
|
288
|
+
/\.delete\s*\(|\.commit\s*\(|\.save\s*\(/.test(t);
|
|
289
|
+
for (const m of t.matchAll(/\b(?:db|session|self\.db|self\.session|db\.session|async_session)\.get\(\s*([\w.]+)\s*,\s*([^)]+)\)/g))
|
|
290
|
+
out.push({ index: m.index, id: m[2], model: m[1].split('.').pop(), mutation: mutation(m.index), query: '' });
|
|
291
|
+
for (const m of t.matchAll(/\b([A-Z]\w*)\.query\.(?:get|get_or_404)\(\s*([^)]+)\)/g))
|
|
292
|
+
out.push({ index: m.index, id: m[2], model: m[1], mutation: mutation(m.index), query: '' });
|
|
293
|
+
for (const m of t.matchAll(/\bget_object_or_404\(\s*([\w.]+)\s*,([^)]*)\)/g)) {
|
|
294
|
+
const id = /\b(?:pk|id)\s*=\s*([^,)]+)/.exec(m[2])?.[1];
|
|
295
|
+
if (id)
|
|
296
|
+
out.push({ index: m.index, id, model: m[1].split('.').pop(), mutation: mutation(m.index), query: m[2] });
|
|
297
|
+
}
|
|
298
|
+
for (const m of t.matchAll(/\b([A-Z]\w*)\.objects\.(?:get|filter)\(([^)]*)\)/g)) {
|
|
299
|
+
const id = /\b(?:pk|id)\s*=\s*([^,)]+)/.exec(m[2])?.[1];
|
|
300
|
+
if (id)
|
|
301
|
+
out.push({ index: m.index, id, model: m[1], mutation: mutation(m.index), query: lineAt(m.index) });
|
|
302
|
+
}
|
|
303
|
+
for (const m of t.matchAll(/\.(?:filter|where)\(\s*([A-Z]\w*)\.id\s*==\s*([^,)]+)/g))
|
|
304
|
+
out.push({
|
|
305
|
+
index: m.index,
|
|
306
|
+
id: m[2],
|
|
307
|
+
model: m[1],
|
|
308
|
+
mutation: mutation(m.index),
|
|
309
|
+
query: statementAround(t, m.index),
|
|
310
|
+
});
|
|
311
|
+
for (const m of t.matchAll(/\.filter_by\(([^)]*)\)/g)) {
|
|
312
|
+
const id = /\bid\s*=\s*([^,)]+)/.exec(m[1])?.[1];
|
|
313
|
+
if (id)
|
|
314
|
+
out.push({ index: m.index, id, model: '', mutation: mutation(m.index), query: m[1] });
|
|
315
|
+
}
|
|
316
|
+
return out.sort((a, b) => a.index - b.index);
|
|
317
|
+
}
|
|
318
|
+
// ---------- writes ----------
|
|
319
|
+
const JS_WRITE = [
|
|
320
|
+
/\b(?:prisma|db|tx|ctx\.db|ctx\.prisma|database)\s*\.\s*[\w$]+\s*\.\s*(?:create|createMany|createManyAndReturn|update|updateMany|upsert|delete|deleteMany)\s*\(/,
|
|
321
|
+
/\b(?:db|tx|database)\s*\.\s*(?:insert|update|delete)\s*\(\s*[\w$.]+\s*\)/,
|
|
322
|
+
/\b(?!(?:Object|Array|Promise|Response|NextResponse|Error|Map|Set|URL|JSON|Math|Reflect|Symbol|Buffer|Date|String|Number|Intl|React)\.)[A-Z][\w$]*\.(?:create|insertMany|updateOne|updateMany|deleteOne|deleteMany|findByIdAndUpdate|findByIdAndDelete|findByIdAndRemove|findOneAndUpdate|findOneAndDelete|findOneAndRemove|replaceOne|bulkCreate|destroy)\s*\(/,
|
|
323
|
+
/\bsql\s*`\s*(?:insert|update|delete)\b/i,
|
|
324
|
+
/\.(?:query|execute)\s*\(\s*["'`]\s*(?:insert|update|delete)\b/i,
|
|
325
|
+
/\.collection\(\s*["'`][^"'`]+["'`]\s*\)\s*\.(?:insertOne|insertMany|updateOne|updateMany|deleteOne|deleteMany|replaceOne|findOneAndUpdate|findOneAndDelete)\s*\(/,
|
|
326
|
+
];
|
|
327
|
+
const SUPABASE_WRITE = /\.from\(\s*["'`][\w.-]+["'`]\s*\)\s*\.(?:insert|update|upsert|delete)\s*\(/;
|
|
328
|
+
const FIREBASE_ADMIN_WRITE = /\.(?:doc|collection)\([^)]*\)\s*\.(?:set|update|delete|add)\s*\(/;
|
|
329
|
+
const PY_WRITE = /\b(?:db|session|self\.db|db\.session)\.(?:add|delete|merge)\s*\(|\.commit\s*\(\s*\)|\.objects\.(?:create|update_or_create|get_or_create|bulk_create)\s*\(|\.save\s*\(\s*\)|\.delete\s*\(\s*\)|\.(?:insert_one|insert_many|update_one|update_many|delete_one|delete_many|replace_one)\s*\(|\.table\(\s*["'][^"']+["']\s*\)\.(?:insert|update|upsert|delete)\s*\(/;
|
|
330
|
+
/** A Supabase client that skips Row Level Security (the secret / service_role key). */
|
|
331
|
+
const SERVICE_ROLE = /SERVICE_ROLE|service_role|SUPABASE_SECRET_KEY|\bsupabaseAdmin\b|\bcreateAdminClient\b|\bcreateServiceClient\b|\bcreateServiceRoleClient\b/;
|
|
332
|
+
function usesServiceRole(u) {
|
|
333
|
+
return SERVICE_ROLE.test(u.text) || SERVICE_ROLE.test(u.shared) || SERVICE_ROLE.test(u.reachedCode);
|
|
334
|
+
}
|
|
335
|
+
/** Does this unit change data? Supabase writes through the signed-in user's client are left to RLS. */
|
|
336
|
+
function writes(u, env) {
|
|
337
|
+
const code = `${u.text}\n${u.reachedCode}`;
|
|
338
|
+
if (u.kind === 'python')
|
|
339
|
+
return PY_WRITE.test(u.text);
|
|
340
|
+
if (JS_WRITE.some((re) => re.test(code)))
|
|
341
|
+
return true;
|
|
342
|
+
if (SUPABASE_WRITE.test(code) && usesServiceRole(u))
|
|
343
|
+
return true;
|
|
344
|
+
return env.firebaseAdmin && FIREBASE_ADMIN_WRITE.test(code);
|
|
345
|
+
}
|
|
346
|
+
// ---------- endpoints that are meant to be public ----------
|
|
347
|
+
/**
|
|
348
|
+
* Function names of sign-in flows and similar endpoints that run before there is a user. The whole name has to be that
|
|
349
|
+
* flow, optionally with a verb in front ("handleSignIn", "submitContactForm"): deleteContact or updatePassword
|
|
350
|
+
* change existing data and are not exempt.
|
|
351
|
+
*/
|
|
352
|
+
const PUBLIC_FLOW_NAME = new RegExp('^(?:handle|submit|send|process|on|do)?_?' +
|
|
353
|
+
'(?:(?:log_?in|sign_?in|sign_?up|register|log_?out|sign_?out|oauth|magic_?link|otp|webhook)\\w*' +
|
|
354
|
+
'|(?:forgot|reset|request)_?password(?:_?reset)?|request_?password_?reset|verify_?(?:email|otp|code|token)?|confirm_?email' +
|
|
355
|
+
'|(?:auth_?)?callback|health_?check|cron)' +
|
|
356
|
+
'(?:_?(?:form|action|handler|request|route|view))?$', 'i');
|
|
357
|
+
/**
|
|
358
|
+
* Public forms and callbacks: subscribe, contact, feedback, inquiry, consume, bounces, ping. Only the action itself
|
|
359
|
+
* counts ("subscribe", "contact_submit", "newsletter_signup", "join_waitlist"), never a longer name that happens to
|
|
360
|
+
* start with it: "subscribers_delete" or "contacts_export" manage the records those forms collect.
|
|
361
|
+
*/
|
|
362
|
+
const PUBLIC_FORM_NAME = new RegExp('^(?:handle|submit|send|process|on|do)?_?' +
|
|
363
|
+
'(?:(?:un)?subscribe(?:_?(?:to_?)?(?:newsletter|emails?|updates|form|submit|request))?' +
|
|
364
|
+
'|(?:join_?)?(?:waitlist|newsletter)(?:_?(?:sign_?up|subscribe|join|submit))?' +
|
|
365
|
+
'|contact(?:_?(?:us|form|submit|message|email|request))?' +
|
|
366
|
+
'|feedback(?:_?(?:form|submit|message))?' +
|
|
367
|
+
'|(?:inquiry|enquiry)(?:_?(?:form|submit|message))?' +
|
|
368
|
+
'|consume(?:_?(?:token|invite|code|(?:magic_?)?link|webhook|event|message))?' +
|
|
369
|
+
'|bounces?|ping(?:_?(?:back|pong))?)' +
|
|
370
|
+
'(?:_?(?:form|action|handler|request|route|view))?$', 'i');
|
|
371
|
+
/** URL segments of webhooks, sign-in flows and cron jobs. */
|
|
372
|
+
const PUBLIC_FLOW_PATH = /(?:^|[/_.\-[])(?:webhooks?|hooks|cron|callback|oauth|auth|login|logout|signin|sign-in|signup|sign-up|register|inngest|qstash|health)(?=$|[/_.\-\]])/i;
|
|
373
|
+
/** URL segments of public forms. Like the names above, they stop being public when the URL also manages records. */
|
|
374
|
+
const PUBLIC_FORM_PATH = /(?:^|[/_.\-[])(?:contact|newsletter|subscribe|waitlist)(?=$|[/_.\-\]])/i;
|
|
375
|
+
/** A word in a name or URL that means "this works on stored records, or is for admins", whatever else it contains. */
|
|
376
|
+
const MANAGES_RECORDS = new Set([
|
|
377
|
+
...['delete', 'update', 'edit', 'export', 'list', 'admin', 'remove', 'all'],
|
|
378
|
+
...['deletes', 'updates', 'edits', 'exports', 'lists', 'admins', 'removes'],
|
|
379
|
+
]);
|
|
380
|
+
/** "subscribers_delete", "contactAdmin" and "/api/contacts/export" all contain a word from MANAGES_RECORDS. */
|
|
381
|
+
const managesRecords = (text) => text
|
|
382
|
+
.replace(/([a-z\d])([A-Z])/g, '$1 $2')
|
|
383
|
+
.toLowerCase()
|
|
384
|
+
.split(/[^a-z\d]+/)
|
|
385
|
+
.some((w) => MANAGES_RECORDS.has(w));
|
|
386
|
+
const SIGNED_REQUEST = /constructEvent|webhooks?\.(?:verify|unwrap|constructEvent)|verifySignature|verifyWebhook|validateWebhook|\bsvix\b|new\s+Webhook\s*\(|createHmac|timingSafeEqual|x-hub-signature|stripe-signature|CRON_SECRET|new\s+Receiver\s*\(|verify_webhook|compare_digest|signing\.(?:loads|unsign)|\bTimestampSigner\b|\bURLSafeTimedSerializer\b|\bitsdangerous\b/i;
|
|
387
|
+
/** A Python view that takes a secret from its URL (a signed link, a ping key, a token) is authenticated by that secret. */
|
|
388
|
+
const CAPABILITY_PARAM = /^(?:signed_\w+|\w*token|ping_key|api_key|secret|\w+_secret|magic\w*)$/i;
|
|
389
|
+
const hasCapabilityParam = (params) => params.split(',').some((p) => CAPABILITY_PARAM.test(p.split(/[:=]/)[0].trim()));
|
|
390
|
+
function meantToBePublic(u) {
|
|
391
|
+
if (u.kind !== 'route' &&
|
|
392
|
+
(PUBLIC_FLOW_NAME.test(u.name) || (PUBLIC_FORM_NAME.test(u.name) && !managesRecords(u.name))))
|
|
393
|
+
return true;
|
|
394
|
+
if (u.kind === 'python' && hasCapabilityParam(u.params))
|
|
395
|
+
return true;
|
|
396
|
+
const publicPath = (path) => PUBLIC_FLOW_PATH.test(path) || (PUBLIC_FORM_PATH.test(path) && !managesRecords(path));
|
|
397
|
+
if (publicPath(u.urlPath ?? ''))
|
|
398
|
+
return true;
|
|
399
|
+
// A Next.js route file is one URL, so its path is the URL. Files holding many routes are judged route by route.
|
|
400
|
+
if (u.kind === 'route' && publicPath(u.file.path))
|
|
401
|
+
return true;
|
|
402
|
+
// A signature check this handler actually runs (not one somewhere else in the file).
|
|
403
|
+
return [u.text, u.reachedCode, ...calledHelpers(u)].some((code) => SIGNED_REQUEST.test(code));
|
|
404
|
+
}
|
|
405
|
+
// ---------- middleware ----------
|
|
406
|
+
function isMiddlewareFile(f) {
|
|
407
|
+
return /(^|\/)(?:src\/)?(middleware|proxy)\.(t|j)s$/.test(f.path);
|
|
408
|
+
}
|
|
409
|
+
/** A blocking middleware runs on this URL path. */
|
|
410
|
+
function middlewareCovers(ctx, urlPath) {
|
|
411
|
+
return ctx.files.some((f) => {
|
|
412
|
+
if (!isMiddlewareFile(f))
|
|
413
|
+
return false;
|
|
414
|
+
const code = ctx.codeOf(f);
|
|
415
|
+
return MIDDLEWARE_BLOCKS.test(code) && matcherCovers(matcherEntries(code), urlPath) !== false;
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
/** A blocking middleware runs on every page (so on the pages that Server Actions post to). */
|
|
419
|
+
function middlewareCoversPages(ctx) {
|
|
420
|
+
return ctx.files.some((f) => {
|
|
421
|
+
if (!isMiddlewareFile(f))
|
|
422
|
+
return false;
|
|
423
|
+
const code = ctx.codeOf(f);
|
|
424
|
+
if (!MIDDLEWARE_BLOCKS.test(code))
|
|
425
|
+
return false;
|
|
426
|
+
// Protection limited to some routes ("if (isProtectedRoute(req)) auth.protect()") doesn't cover every page.
|
|
427
|
+
if (/createRouteMatcher|isProtectedRoute/.test(code) && !/isPublicRoute/.test(code))
|
|
428
|
+
return false;
|
|
429
|
+
const entries = matcherEntries(code);
|
|
430
|
+
if (entries === null)
|
|
431
|
+
return true;
|
|
432
|
+
// The matcher has to run on ordinary pages, not just /api or /dashboard.
|
|
433
|
+
const pages = ['/', '/settings', '/account/profile'];
|
|
434
|
+
return pages.every((p) => entries.some((e) => matcherToRegExp(e)?.test(p)));
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
// ---------- the other rules ----------
|
|
438
|
+
const META_KEYS = 'role|roles|is_?admin|isAdmin|admin|plan|tier|subscription\\w*|credits|permissions?|is_?pro|isPro|premium|isPremium|is_?paid|isPaid|access_?level|accessLevel';
|
|
439
|
+
const META_READ = new RegExp(`\\b(user_metadata|unsafeMetadata|unsafe_metadata|raw_user_meta_data)\\s*(?:\\?\\.|\\.)\\s*(${META_KEYS})\\b|\\b(user_metadata|unsafeMetadata|unsafe_metadata|raw_user_meta_data)\\s*(?:\\?\\.)?\\s*(?:\\[\\s*|\\.get\\(\\s*)["'\`](${META_KEYS})["'\`]`);
|
|
440
|
+
const SQL_META = /user_meta_?data|raw_user_meta_data/i;
|
|
441
|
+
const SQL_META_KEY = new RegExp(`(?:user_meta_?data|raw_user_meta_data)['"]?\\s*->>?\\s*'(${META_KEYS})'`, 'i');
|
|
442
|
+
const CLIENT_ADMIN = /\b(?:role|userRole|user_role)\s*(?:!==?|===?)\s*["'`](?:admin|superadmin|super_admin)["'`]|["'`](?:admin|superadmin)["'`]\s*(?:!==?|===?)\s*[\w$.?]*\brole\b|\.email\s*(?:!==?|===?)\s*["'`][^"'`\s@]+@[^"'`\s]+["'`]|\b(?:ADMIN_EMAILS?|ADMIN_EMAIL_LIST|NEXT_PUBLIC_ADMIN\w*|VITE_ADMIN\w*|EXPO_PUBLIC_ADMIN\w*)\b|\.includes\(\s*[\w$.?]*\.email\s*\)/;
|
|
443
|
+
const SERVER_ADMIN_SQL = /\b(?:is_)?admins?\b|\broles?\b|app_metadata/i;
|
|
444
|
+
const RULES_ADMIN = /request\.auth\.token\.(?:admin|role)|auth\.token\.(?:admin|role)/;
|
|
445
|
+
/** Raw request bodies passed whole into a database write. */
|
|
446
|
+
const JS_BODY_VAR = /(?:const|let|var)\s+([\w$]+)\s*(?::[^=;]+)?=\s*(?:await\s+)?(?:(?:req|request|c\.req|ctx\.request|event)\s*\.\s*(?:json\s*\(\s*\)|body\b(?!\s*[.[])|formData\s*\(\s*\))|Object\.fromEntries\(\s*(?:await\s+)?[\w$.]*(?:formData|form)\b[^)]*\))/g;
|
|
447
|
+
const NOT_A_RECORD = /^(?:Response|NextResponse|URL|Error|Request|Headers|Blob|FormData|URLSearchParams|Map|Set|Date|Uint8Array|TextEncoder|TextDecoder|WeakMap|Promise|RegExp)$/;
|
|
448
|
+
const PY_BODY_VAR = /^[ \t]*(\w+)\s*=\s*request\.(?:json|get_json\(\s*\)|data|form|POST)\b/gm;
|
|
449
|
+
const SCHEMA_SENSITIVE = /\b(role|is_?admin|isAdmin|is_staff|is_superuser|credits|balance|plan|tier|is_?verified|emailVerified|stripe\w*|subscription\w*|price|amount)\b/;
|
|
450
|
+
function fileOnce(items) {
|
|
451
|
+
const seen = new Set();
|
|
452
|
+
return items.filter((i) => !seen.has(i.file.path) && seen.add(i.file.path));
|
|
453
|
+
}
|
|
454
|
+
// ---------- the check ----------
|
|
455
|
+
export const accessCheck = {
|
|
456
|
+
id: 'access',
|
|
457
|
+
name: 'Access control',
|
|
458
|
+
weight: 3,
|
|
459
|
+
ids: [
|
|
460
|
+
'server-action-no-auth',
|
|
461
|
+
'api-write-no-auth',
|
|
462
|
+
'missing-ownership-check',
|
|
463
|
+
'user-metadata-role',
|
|
464
|
+
'mass-assignment',
|
|
465
|
+
'client-only-admin-check',
|
|
466
|
+
'jwt-not-verified',
|
|
467
|
+
'jwt-none-algorithm',
|
|
468
|
+
'supabase-getsession-server',
|
|
469
|
+
'test-other-users-data',
|
|
470
|
+
'server-actions-middleware-only',
|
|
471
|
+
],
|
|
472
|
+
run(ctx) {
|
|
473
|
+
const server = serverCode(ctx);
|
|
474
|
+
const client = clientCode(ctx);
|
|
475
|
+
const sqlFiles = ctx.files.filter((f) => f.path.endsWith('.sql') && !/(^|\/)(?:seed|tests?)\b/.test(f.path));
|
|
476
|
+
const projectPythonAuth = ctx.files.some((f) => f.path.endsWith('.py') && /LoginRequiredMiddleware/.test(ctx.codeOf(f))) ||
|
|
477
|
+
ctx.files.some((f) => f.path.endsWith('.py') && /include_router\([^)]*dependencies\s*=/s.test(ctx.codeOf(f)));
|
|
478
|
+
const units = findUnits(ctx, server, (f) => isRouteLike(f) || f.path.endsWith('.py'), projectPythonAuth);
|
|
479
|
+
const authLib = detectAuth(ctx);
|
|
480
|
+
const hasAccounts = authLib !== null ||
|
|
481
|
+
ctx.findCode(AUTH_CHECK_RE, server, 1).length > 0 ||
|
|
482
|
+
ctx.files.some((f) => server(f) && f.path.endsWith('.py') && PY_AUTH.test(ctx.codeOf(f)));
|
|
483
|
+
const usesSupabase = ctx.usesAny(['@supabase/supabase-js', '@supabase/ssr', 'supabase']);
|
|
484
|
+
const usesClerk = ctx.uses('@clerk/');
|
|
485
|
+
const usesTokens = ctx.usesAny(['jsonwebtoken', 'jose', 'jwt-decode', 'pyjwt', 'python-jose']);
|
|
486
|
+
if (!units.length && !sqlFiles.length && !hasAccounts && !usesSupabase && !usesClerk && !usesTokens)
|
|
487
|
+
return notApplicable('No API routes, Server Actions or user accounts found');
|
|
488
|
+
const out = emptyOutput();
|
|
489
|
+
const env = { firebaseAdmin: ctx.uses('firebase-admin') };
|
|
490
|
+
const loc = (u, index) => ({
|
|
491
|
+
file: u.file.path,
|
|
492
|
+
line: index === undefined ? u.line : ctx.lineOf(u.file, u.start + index),
|
|
493
|
+
});
|
|
494
|
+
const label = (u) => u.kind === 'action'
|
|
495
|
+
? `Server Action ${u.name}`
|
|
496
|
+
: u.kind === 'trpc'
|
|
497
|
+
? `tRPC procedure ${u.name}`
|
|
498
|
+
: u.kind === 'python'
|
|
499
|
+
? `${u.name} (${u.method === 'ANY' ? '' : `${u.method} `}${u.urlPath ?? u.file.path})`.replace('( ', '(')
|
|
500
|
+
: `${u.method === 'ANY' ? '' : `${u.method} `}${u.urlPath ?? u.file.path}`;
|
|
501
|
+
// 1. Server Actions that change data without asking who is calling.
|
|
502
|
+
const actions = units.filter((u) => u.kind === 'action');
|
|
503
|
+
const openActions = hasAccounts
|
|
504
|
+
? actions.filter((u) => writes(u, env) && !signsInCaller(u) && !meantToBePublic(u))
|
|
505
|
+
: [];
|
|
506
|
+
const middlewareOnly = openActions.length > 0 && middlewareCoversPages(ctx);
|
|
507
|
+
if (middlewareOnly) {
|
|
508
|
+
out.manual.push({
|
|
509
|
+
id: 'server-actions-middleware-only',
|
|
510
|
+
title: `Check that your Server Actions are protected by more than middleware (${openActions.length} rely on it)`,
|
|
511
|
+
how: `${openActions
|
|
512
|
+
.map((u) => u.name)
|
|
513
|
+
.slice(0, 5)
|
|
514
|
+
.join(', ')} change data and only your middleware checks sign-in. Next.js recommends checking inside each action, ` +
|
|
515
|
+
'because every action can be called with a direct POST request and middleware matchers are easy to get wrong (CVE-2025-29927 bypassed middleware on self-hosted apps).',
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
else {
|
|
519
|
+
const byFile = new Map();
|
|
520
|
+
for (const u of openActions)
|
|
521
|
+
byFile.set(u.file.path, [...(byFile.get(u.file.path) ?? []), u]);
|
|
522
|
+
for (const group of [...byFile.values()].slice(0, MAX_PER_ID)) {
|
|
523
|
+
const first = group[0];
|
|
524
|
+
const names = group.map((u) => u.name);
|
|
525
|
+
const list = names.length > 1
|
|
526
|
+
? `${names.slice(0, 4).join(', ')}${names.length > 4 ? ` and ${names.length - 4} more` : ''}`
|
|
527
|
+
: names[0];
|
|
528
|
+
out.findings.push({
|
|
529
|
+
id: 'server-action-no-auth',
|
|
530
|
+
severity: 'warning',
|
|
531
|
+
title: `${names.length > 1 ? `${names.length} Server Actions change` : 'A Server Action changes'} data without checking who is calling (${list})`,
|
|
532
|
+
why: 'Every exported Server Action is a public endpoint: anyone can call it with a direct POST request, even if the page that uses it is behind a login. ' +
|
|
533
|
+
'We found no sign-in check inside it (such as auth(), getUser() or getServerSession()). If it is meant to be public, like a contact form, you can ignore this.',
|
|
534
|
+
location: loc(first),
|
|
535
|
+
fixPrompt: `In ${first.file.path}, the Server Action${names.length > 1 ? 's' : ''} ${list} change data in my database but never check who is calling. ` +
|
|
536
|
+
'Next.js says every Server Action can be called directly with a POST request, so a check on the page does not protect it. For each action:\n' +
|
|
537
|
+
`1. At the top, get the signed-in user with the auth system my app already uses${authLib ? ` (${authLib})` : ''}, and throw or return an error if there is none.\n` +
|
|
538
|
+
'2. When the action changes an existing record, make sure that record belongs to this user (filter the query by the user id from the session, never from the arguments).\n' +
|
|
539
|
+
'3. Never take the user id, role or price from the action arguments; read them from the session or the database.\n' +
|
|
540
|
+
'Leave genuinely public actions (sign-in, sign-up, contact form) as they are and tell me which ones you left.',
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
// Only when the app has accounts: without them nothing was checked, so there is nothing to claim.
|
|
545
|
+
if (hasAccounts && actions.some((u) => writes(u, env)) && !openActions.length)
|
|
546
|
+
out.passed.push('Server Actions check who is calling');
|
|
547
|
+
// 2. API routes that change data without asking who is calling.
|
|
548
|
+
const apiUnits = units.filter((u) => u.kind !== 'action');
|
|
549
|
+
const writeUnits = apiUnits.filter((u) => u.method !== 'GET' && u.method !== 'HEAD' && writes(u, env));
|
|
550
|
+
const openRoutes = hasAccounts
|
|
551
|
+
? writeUnits.filter((u) => !signsInCaller(u) && !meantToBePublic(u) && !(u.kind === 'route' && middlewareCovers(ctx, u.urlPath)))
|
|
552
|
+
: [];
|
|
553
|
+
for (const u of openRoutes.slice(0, MAX_PER_ID)) {
|
|
554
|
+
out.findings.push({
|
|
555
|
+
id: 'api-write-no-auth',
|
|
556
|
+
severity: 'warning',
|
|
557
|
+
title: `Endpoint changes data without checking who is calling (${label(u)})`,
|
|
558
|
+
why: 'Your app has user accounts, but this endpoint writes to the database without a sign-in check, so anyone who finds the URL can call it. ' +
|
|
559
|
+
"We looked in the handler, the helpers it imports and its middleware. If it is meant to be public, or something we couldn't see protects it, you can ignore this.",
|
|
560
|
+
location: loc(u),
|
|
561
|
+
fixPrompt: `The ${label(u)} handler in ${where(loc(u))} changes data in my database but doesn't check who is calling. Please:\n` +
|
|
562
|
+
`1. Reject callers who aren't signed in (HTTP 401) using the auth system my app already uses${authLib ? ` (${authLib})` : ''}, and use the result of the check, not just call it.\n` +
|
|
563
|
+
'2. If it changes an existing record, only allow it when the record belongs to the signed-in user (filter by the user id from the session).\n' +
|
|
564
|
+
'3. Take the user id from the session, never from the request body or URL.\n' +
|
|
565
|
+
'If this endpoint is meant to be public (a webhook, a contact form), tell me how it is protected instead (a signature check, a rate limit) and leave it.',
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
if (hasAccounts && writeUnits.length && !openRoutes.length)
|
|
569
|
+
out.passed.push('Endpoints that change data check who is calling');
|
|
570
|
+
// 3. Records looked up by an id from the request, with nothing tying them to the caller.
|
|
571
|
+
let lookupsSeen = 0;
|
|
572
|
+
const unscoped = [];
|
|
573
|
+
for (const u of units) {
|
|
574
|
+
if (!signsInCaller(u) && !(u.kind === 'route' && middlewareCovers(ctx, u.urlPath)))
|
|
575
|
+
continue; // reported above when it writes
|
|
576
|
+
const lookups = u.kind === 'python' ? pyLookups(u) : jsLookups(u, env.firebaseAdmin);
|
|
577
|
+
for (const l of lookups) {
|
|
578
|
+
if (l.supabase && !usesServiceRole(u))
|
|
579
|
+
continue; // the user's own client: Row Level Security decides
|
|
580
|
+
if (originOf(l.id, u) !== 'request')
|
|
581
|
+
continue;
|
|
582
|
+
lookupsSeen++;
|
|
583
|
+
if (!l.mutation && PUBLIC_MODEL.test(l.model))
|
|
584
|
+
continue;
|
|
585
|
+
// The query is scoped, ownership is compared, or the handler ties the work to the caller somewhere else:
|
|
586
|
+
// an earlier scoped lookup of the same record, or a helper called with the caller's id
|
|
587
|
+
// (deleteDocument({ id, userId: ctx.user.id })), which usually means the check happens there.
|
|
588
|
+
if (scopedQuery(l.query, u) || checksOwnership(u) || scopedQuery(u.text, u))
|
|
589
|
+
continue;
|
|
590
|
+
unscoped.push({ u, l });
|
|
591
|
+
break; // one per handler
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
for (const { u, l } of unscoped.slice(0, MAX_PER_ID)) {
|
|
595
|
+
const what = l.model ? `a ${l.model.replace(/s$/, '')} record` : 'a record';
|
|
596
|
+
out.findings.push({
|
|
597
|
+
id: 'missing-ownership-check',
|
|
598
|
+
severity: 'warning',
|
|
599
|
+
title: `${l.mutation ? 'Changes' : 'Loads'} ${what} by an id from the request without checking who owns it (${label(u)})`,
|
|
600
|
+
why: 'This handler checks that someone is signed in, but not that the record is theirs. A signed-in user can change the id in the URL or request and ' +
|
|
601
|
+
`${l.mutation ? 'edit or delete' : 'read'} other people's data (an "IDOR", the most common access-control bug). ` +
|
|
602
|
+
'We looked for an owner filter in the query (like userId: session.user.id), an owner comparison after loading it, a permission helper or an admin check, and found none. ' +
|
|
603
|
+
'If this record is meant to be shared, or your database rules (RLS) already limit it, you can ignore this.',
|
|
604
|
+
location: loc(u, l.index),
|
|
605
|
+
fixPrompt: `In ${where(loc(u, l.index))}, ${label(u)} ${l.mutation ? 'changes' : 'loads'} ${what} using an id from the request, but never checks that it belongs to the signed-in user, ` +
|
|
606
|
+
`so one user could ${l.mutation ? 'change or delete' : 'read'} another user's data by changing the id. Please:\n` +
|
|
607
|
+
"1. Add the owner to the query itself (for example where: { id, userId: session.user.id }), or load the record and return 404 when its owner isn't the signed-in user.\n" +
|
|
608
|
+
'2. Take the user id from the session, never from the request.\n' +
|
|
609
|
+
'3. Check the other handlers that load records by id in the same way and fix them too.\n' +
|
|
610
|
+
'If this record is genuinely meant to be visible to every signed-in user, explain that to me instead of changing it.',
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
if (lookupsSeen && !unscoped.length)
|
|
614
|
+
out.passed.push('Records looked up by id are checked against the signed-in user');
|
|
615
|
+
// 4. Roles and plans read from metadata the user can edit.
|
|
616
|
+
const metaFindings = [];
|
|
617
|
+
for (const f of sqlFiles) {
|
|
618
|
+
const sql = ctx.codeOf(f);
|
|
619
|
+
let pos = 0;
|
|
620
|
+
for (const stmt of sql.split(';')) {
|
|
621
|
+
const at = pos;
|
|
622
|
+
pos += stmt.length + 1;
|
|
623
|
+
const hit = SQL_META.exec(stmt);
|
|
624
|
+
if (!hit)
|
|
625
|
+
continue;
|
|
626
|
+
const key = SQL_META_KEY.exec(stmt)?.[1];
|
|
627
|
+
if (!/create\s+policy/i.test(stmt) && !key)
|
|
628
|
+
continue; // copying full_name into profiles is the normal template
|
|
629
|
+
metaFindings.push({ file: f, index: at + hit.index, key: key ?? 'user_metadata', sql: true });
|
|
630
|
+
break;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
for (const m of ctx.findCode(META_READ, appCode)) {
|
|
634
|
+
if (metaFindings.some((x) => x.file.path === m.file.path))
|
|
635
|
+
continue;
|
|
636
|
+
metaFindings.push({ file: m.file, index: m.index, key: m.match[2] ?? m.match[4] ?? 'role', sql: false });
|
|
637
|
+
}
|
|
638
|
+
for (const mf of metaFindings.slice(0, MAX_PER_ID)) {
|
|
639
|
+
const l = { file: mf.file.path, line: ctx.lineOf(mf.file, mf.index) };
|
|
640
|
+
const clerk = /unsafe_?[mM]etadata/.test(lineTextAt(mf.file.content, mf.index));
|
|
641
|
+
const inBrowser = !mf.sql && ctx.isClient(mf.file);
|
|
642
|
+
const field = clerk ? 'unsafeMetadata' : 'user_metadata';
|
|
643
|
+
out.findings.push({
|
|
644
|
+
id: 'user-metadata-role',
|
|
645
|
+
severity: inBrowser ? 'warning' : 'critical',
|
|
646
|
+
title: mf.sql
|
|
647
|
+
? `A database rule trusts user_metadata, which every user can edit (${mf.file.path})`
|
|
648
|
+
: `"${mf.key}" is read from ${field}, which every user can edit`,
|
|
649
|
+
why: (clerk
|
|
650
|
+
? "Clerk's unsafeMetadata can be changed from the browser by the user themselves. "
|
|
651
|
+
: 'Supabase lets any signed-in user change their own user_metadata with a single call (supabase.auth.updateUser). ') +
|
|
652
|
+
`So anyone can give themselves ${mf.key === 'user_metadata' ? 'whatever this rule checks' : `a different "${mf.key}"`}, for example make themselves an admin or a paying customer.` +
|
|
653
|
+
(inBrowser
|
|
654
|
+
? ' Here it is only read in the browser, which is fine for display, but make sure nothing on the server or in your database rules trusts it.'
|
|
655
|
+
: ''),
|
|
656
|
+
location: l,
|
|
657
|
+
fixPrompt: `In ${where(l)} my app reads "${mf.key}" from ${field}, which users can edit themselves. ` +
|
|
658
|
+
(clerk
|
|
659
|
+
? 'Please move roles and plans to Clerk publicMetadata or privateMetadata (only my server can change those), set them from my backend, and check them on the server with auth().sessionClaims. '
|
|
660
|
+
: 'Please move roles, plans and similar fields to app_metadata (only my server can change it, via the service role key) or to a table that users cannot write to, ' +
|
|
661
|
+
"and update every RLS policy and server check that reads user_metadata to use auth.jwt() -> 'app_metadata' or that table instead. ") +
|
|
662
|
+
'Also check my sign-up code: users must not be able to choose their own role when they register.',
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
if (!metaFindings.length && (usesSupabase || usesClerk))
|
|
666
|
+
out.passed.push('Roles and plans are not read from metadata users can edit');
|
|
667
|
+
// 5. Whole request bodies written to the database (mass assignment).
|
|
668
|
+
const massHits = [];
|
|
669
|
+
for (const f of ctx.files) {
|
|
670
|
+
if (!server(f))
|
|
671
|
+
continue;
|
|
672
|
+
const code = ctx.codeOf(f);
|
|
673
|
+
if (f.path.endsWith('.py')) {
|
|
674
|
+
const vars = [...code.matchAll(PY_BODY_VAR)].map((m) => m[1]);
|
|
675
|
+
const raw = ['request\\.(?:json|get_json\\(\\s*\\)|data|form|POST)\\b', ...vars.map((v) => `\\b${v}\\b`)].join('|');
|
|
676
|
+
const sink = new RegExp(`\\b(?:[A-Z]\\w*|\\.objects\\.create|\\.objects\\.update_or_create|\\.update)\\(\\s*\\*\\*\\s*(?:${raw})`);
|
|
677
|
+
const m = sink.exec(code);
|
|
678
|
+
if (m)
|
|
679
|
+
massHits.push({ file: f, index: m.index });
|
|
680
|
+
const drf = /class\s+\w+\s*\([^)]*Model(?:Serializer|Form)[^)]*\)\s*:[\s\S]*?(?=^class\s|(?![\s\S]))/gm;
|
|
681
|
+
for (const c of code.matchAll(drf)) {
|
|
682
|
+
const all = /fields\s*=\s*["']__all__["']/.exec(c[0]);
|
|
683
|
+
if (all && !/read_only_fields/.test(c[0]))
|
|
684
|
+
massHits.push({ file: f, index: c.index + all.index });
|
|
685
|
+
}
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
if (!/\.[cm]?[jt]sx?$/.test(f.path))
|
|
689
|
+
continue;
|
|
690
|
+
const vars = [...code.matchAll(JS_BODY_VAR)].map((m) => m[1]);
|
|
691
|
+
// Server Action parameters arrive straight from the caller, whatever their TypeScript type says.
|
|
692
|
+
// (A parameter typed as a string or number can't carry extra fields.)
|
|
693
|
+
for (const u of units) {
|
|
694
|
+
if (u.kind !== 'action' || u.file !== f)
|
|
695
|
+
continue;
|
|
696
|
+
const primitive = (n) => new RegExp(`\\b${escapeRe(n)}\\??\\s*:\\s*(?:string|number|boolean|bigint|Date)\\b`).test(u.params);
|
|
697
|
+
vars.push(...paramNames(u).filter((n) => !primitive(n)));
|
|
698
|
+
}
|
|
699
|
+
const names = [...new Set(vars)]
|
|
700
|
+
.filter((v) => v.length > 1 && !/^(?:req|res|request|ctx|session|user)$/.test(v))
|
|
701
|
+
.map(escapeRe);
|
|
702
|
+
const raw = [
|
|
703
|
+
'(?:req|request)\\.body\\b(?!\\s*[.[])',
|
|
704
|
+
'(?:await\\s+)?(?:req|request|c\\.req)\\.json\\(\\s*\\)',
|
|
705
|
+
'Object\\.fromEntries\\([^)]*\\)',
|
|
706
|
+
...names.map((n) => `${n}\\b(?!\\s*[.[(])`),
|
|
707
|
+
].join('|');
|
|
708
|
+
const sinks = [
|
|
709
|
+
new RegExp(`\\bdata\\s*:\\s*(?:\\{\\s*\\.\\.\\.\\s*)?(?:${raw})\\s*(?=[,}\\n])`, 'g'),
|
|
710
|
+
// (?<![\w$]) starts the name only at the beginning of a word. Without it, a long run of letters made the
|
|
711
|
+
// regex try every position inside it, each one scanning to the end of the run (quadratic: minutes on 100 KB).
|
|
712
|
+
new RegExp(`(?<![\\w$])([\\w$]+)\\s*\\.\\s*(?:create|insertMany|findByIdAndUpdate|findOneAndUpdate|updateOne|updateMany|update|upsert|bulkCreate)\\s*\\(\\s*(?:[^,()]+,\\s*)?(?:\\{\\s*\\.\\.\\.\\s*)?(?:${raw})\\s*[,)}]`, 'g'),
|
|
713
|
+
new RegExp(`\\bnew\\s+([A-Z][\\w$]*)\\s*\\(\\s*(?:\\{\\s*\\.\\.\\.\\s*)?(?:${raw})\\s*[,)}]`, 'g'),
|
|
714
|
+
// Query builders: db.update(users).set(body), db.insert(t).values(body), supabase.from("t").insert(body)
|
|
715
|
+
new RegExp(`\\)\\s*\\.\\s*(?:set|values|insert|update|upsert)\\s*\\(\\s*(?:\\{\\s*\\.\\.\\.\\s*)?(?:${raw})\\s*[,)}]`, 'g'),
|
|
716
|
+
];
|
|
717
|
+
for (const [i, re] of sinks.entries()) {
|
|
718
|
+
for (const m of code.matchAll(re)) {
|
|
719
|
+
if (i === 0 &&
|
|
720
|
+
!/\.(?:create|createMany|update|updateMany|upsert)\s*\(\s*\{[^;]*$/.test(code.slice(Math.max(0, m.index - 400), m.index)))
|
|
721
|
+
continue;
|
|
722
|
+
if (i === 1 &&
|
|
723
|
+
/^(?:hash|hmac|crypto|digest|sha\w*|md5|cipher|decipher|params|searchParams|headers|map|cache|set|formData|url|state|form)$/i.test(m[1]))
|
|
724
|
+
continue;
|
|
725
|
+
if (i === 2 && NOT_A_RECORD.test(m[1]))
|
|
726
|
+
continue;
|
|
727
|
+
if (i === 3 &&
|
|
728
|
+
/create(?:Hash|Hmac|Cipheriv|Decipheriv|Sign|Verify)\s*\([^;]*$/.test(code.slice(Math.max(0, m.index - 200), m.index)))
|
|
729
|
+
continue;
|
|
730
|
+
massHits.push({ file: f, index: m.index });
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
const sensitiveSchema = ctx.files.find((f) => /(?:schema\.prisma|models\.py|schema\.[jt]s|models?\/[\w-]+\.[jt]s)$/.test(f.path) &&
|
|
735
|
+
SCHEMA_SENSITIVE.test(f.content));
|
|
736
|
+
const sensitiveField = sensitiveSchema ? SCHEMA_SENSITIVE.exec(sensitiveSchema.content)[1] : null;
|
|
737
|
+
for (const h of fileOnce(massHits.sort((a, b) => a.index - b.index)).slice(0, MAX_PER_ID)) {
|
|
738
|
+
const l = { file: h.file.path, line: ctx.lineOf(h.file, h.index) };
|
|
739
|
+
const drf = /__all__/.test(lineTextAt(h.file.content, h.index));
|
|
740
|
+
out.findings.push({
|
|
741
|
+
id: 'mass-assignment',
|
|
742
|
+
severity: 'warning',
|
|
743
|
+
title: drf
|
|
744
|
+
? `A serializer or form accepts every field of the model (${h.file.path})`
|
|
745
|
+
: `The whole request is saved to the database as-is (${h.file.path})`,
|
|
746
|
+
why: 'When every field the caller sends is written to the database, a user can add extra fields of their own, such as ' +
|
|
747
|
+
`${sensitiveField ? `"${sensitiveField}" (your schema has it)` : '"role", "isAdmin", "credits" or "userId"'}, and change things they should not be able to. ` +
|
|
748
|
+
'Only the fields a user is allowed to change should be copied over.',
|
|
749
|
+
location: l,
|
|
750
|
+
fixPrompt: `In ${where(l)} my app ${drf ? 'uses fields = "__all__"' : 'passes the whole request body (or form data) straight into a database write'}. ` +
|
|
751
|
+
'Please replace it with an explicit list of the fields users are allowed to set (for example with a zod schema or by picking fields one by one), ' +
|
|
752
|
+
'and make sure fields like role, isAdmin, plan, credits, price and the owner id are never taken from the request. ' +
|
|
753
|
+
'The owner id should come from the signed-in session. Check my other create and update handlers for the same problem.',
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
if (!massHits.length && (writeUnits.length || actions.some((u) => writes(u, env))))
|
|
757
|
+
out.passed.push('Request bodies are not saved to the database as-is');
|
|
758
|
+
// 6. Admin checks that only happen in the browser.
|
|
759
|
+
const clientAdmin = ctx.findCode(CLIENT_ADMIN, client);
|
|
760
|
+
if (clientAdmin.length) {
|
|
761
|
+
const serverAdmin = ctx.findCode(ADMIN_GATE, server, 1).length > 0 ||
|
|
762
|
+
ctx.findCode(CLIENT_ADMIN, server, 1).length > 0 ||
|
|
763
|
+
sqlFiles.some((f) => /create\s+policy|create\s+(?:or\s+replace\s+)?function/i.test(f.content) &&
|
|
764
|
+
SERVER_ADMIN_SQL.test(ctx.codeOf(f))) ||
|
|
765
|
+
ctx.files.some((f) => /(?:firestore|storage)\.rules$|database\.rules\.json$/.test(f.path) && RULES_ADMIN.test(f.content));
|
|
766
|
+
if (!serverAdmin) {
|
|
767
|
+
const first = clientAdmin[0];
|
|
768
|
+
const l = { file: first.file.path, line: first.line };
|
|
769
|
+
out.findings.push({
|
|
770
|
+
id: 'client-only-admin-check',
|
|
771
|
+
severity: 'warning',
|
|
772
|
+
title: `Admin access is only checked in the browser (${first.file.path})`,
|
|
773
|
+
why: 'Code in the browser can be changed by anyone using it, so a check like role === "admin" or a list of admin emails there only hides buttons. ' +
|
|
774
|
+
'We found no matching admin check on your server or in your database rules, so the data behind those screens may be open to every user. ' +
|
|
775
|
+
'If your admin data is protected by rules set up in your database dashboard, you can ignore this.',
|
|
776
|
+
location: l,
|
|
777
|
+
fixPrompt: `In ${where(l)} my app decides who is an admin in browser code. Please make sure every admin action and every admin data query is also checked on the server ` +
|
|
778
|
+
'(in the API route, Server Action, Edge Function or database policy), using a role stored where users cannot change it ' +
|
|
779
|
+
'(a database table they cannot write to, Supabase app_metadata, or Clerk publicMetadata). Keep the browser check only for showing or hiding the UI.',
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
// 7. Tokens decoded but never verified.
|
|
784
|
+
for (const f of ctx.files) {
|
|
785
|
+
if (!server(f))
|
|
786
|
+
continue;
|
|
787
|
+
const code = ctx.codeOf(f);
|
|
788
|
+
const none = /algorithms?\s*[:=]\s*(?:\[[^\]]*["']none["']|["']none["'])/i.exec(code);
|
|
789
|
+
if (none && /jwt|jose|token/i.test(code)) {
|
|
790
|
+
const l = { file: f.path, line: ctx.lineOf(f, none.index) };
|
|
791
|
+
out.findings.push({
|
|
792
|
+
id: 'jwt-none-algorithm',
|
|
793
|
+
severity: 'critical',
|
|
794
|
+
title: `Tokens with no signature ("none" algorithm) are accepted (${f.path})`,
|
|
795
|
+
why: 'With the "none" algorithm a token needs no signature at all, so anyone can write their own token and sign in as any user, including an admin.',
|
|
796
|
+
location: l,
|
|
797
|
+
fixPrompt: `In ${where(l)} my JWT code allows the "none" algorithm. Please remove it and only allow the one algorithm my tokens are actually signed with (for example HS256 or RS256), and reject every other token.`,
|
|
798
|
+
});
|
|
799
|
+
continue;
|
|
800
|
+
}
|
|
801
|
+
let decode = null;
|
|
802
|
+
if (f.path.endsWith('.py')) {
|
|
803
|
+
if (/^[ \t]*(?:import\s+jwt|from\s+jwt\s+import|from\s+jose\s+import)/m.test(code))
|
|
804
|
+
decode = /["']verify_signature["']\s*:\s*False|\bget_unverified_claims\s*\(/.exec(code);
|
|
805
|
+
}
|
|
806
|
+
else {
|
|
807
|
+
const jwtName = /import\s+(?:\*\s+as\s+)?([\w$]+)\s+from\s+["']jsonwebtoken["']|(?:const|let|var)\s+([\w$]+)\s*=\s*require\(\s*["']jsonwebtoken["']\s*\)/.exec(code);
|
|
808
|
+
const named = /import\s*\{[^}]*\bdecode\b[^}]*\}\s*from\s*["']jsonwebtoken["']/.test(code);
|
|
809
|
+
const verified = /\.verify\s*\(|\bverify\s*\(|\bjwtVerify\s*\(|\bverifyToken\s*\(|\bverifyIdToken\s*\(/.test(code);
|
|
810
|
+
if (!verified) {
|
|
811
|
+
const name = jwtName?.[1] ?? jwtName?.[2];
|
|
812
|
+
decode =
|
|
813
|
+
(name ? new RegExp(`\\b${escapeRe(name)}\\.decode\\s*\\(`).exec(code) : null) ??
|
|
814
|
+
(named ? /\bdecode\s*\(/.exec(code) : null) ??
|
|
815
|
+
// jwt-decode and hand-rolled decoding are browser tools; only count them in request handlers.
|
|
816
|
+
(isRouteLike(f)
|
|
817
|
+
? (/\bdecodeJwt\s*\(|\bjwtDecode\s*\(|\bjwt_decode\s*\(/.exec(code) ??
|
|
818
|
+
/JSON\.parse\(\s*(?:atob|Buffer\.from)\s*\(\s*[\w$.?]+\.split\(\s*["']\.["']\s*\)\s*\[\s*1\s*\]/.exec(code))
|
|
819
|
+
: /\bdecodeJwt\s*\(/.exec(code));
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
if (!decode)
|
|
823
|
+
continue;
|
|
824
|
+
const l = { file: f.path, line: ctx.lineOf(f, decode.index) };
|
|
825
|
+
out.findings.push({
|
|
826
|
+
id: 'jwt-not-verified',
|
|
827
|
+
severity: 'warning',
|
|
828
|
+
title: `A login token is read without checking its signature (${f.path})`,
|
|
829
|
+
why: 'Decoding a token only reads what is written in it; anyone can write a token that says they are another user. ' +
|
|
830
|
+
'Only a verified token proves who is calling. If this code only reads the expiry time for display, you can ignore this.',
|
|
831
|
+
location: l,
|
|
832
|
+
fixPrompt: `In ${where(l)} my server decodes a JWT without verifying its signature. Please verify it instead (jwt.verify from jsonwebtoken, jwtVerify from jose, or jwt.decode with the key and algorithms in PyJWT), ` +
|
|
833
|
+
'with my secret or public key and the one algorithm I use, and reject the request when verification fails. Then use only the verified result for the user id.',
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
if (!out.findings.some((f) => f.id.startsWith('jwt-')) && usesTokens)
|
|
837
|
+
out.passed.push('Login tokens are verified, not just decoded');
|
|
838
|
+
// 8. Supabase getSession() trusted on the server.
|
|
839
|
+
if (usesSupabase) {
|
|
840
|
+
const hits = ctx
|
|
841
|
+
.findCode(/\.auth\.getSession\s*\(/, (f) => server(f) && /\.[cm]?[jt]sx?$/.test(f.path))
|
|
842
|
+
.filter((m) => !/\.auth\.(?:getUser|getClaims)\s*\(/.test(ctx.codeOf(m.file)));
|
|
843
|
+
for (const m of fileOnce(hits.map((h) => ({ file: h.file, index: h.index }))).slice(0, MAX_PER_ID)) {
|
|
844
|
+
const l = { file: m.file.path, line: ctx.lineOf(m.file, m.index) };
|
|
845
|
+
out.findings.push({
|
|
846
|
+
id: 'supabase-getsession-server',
|
|
847
|
+
severity: 'warning',
|
|
848
|
+
title: `Server code trusts supabase.auth.getSession() (${m.file.path})`,
|
|
849
|
+
why: 'On the server, getSession() reads the login cookie without checking it with Supabase, so a forged or edited cookie is accepted. ' +
|
|
850
|
+
"Supabase's own docs say never to trust it in server code; use getClaims() or getUser(), which verify the token.",
|
|
851
|
+
location: l,
|
|
852
|
+
fixPrompt: `In ${where(l)} my server code uses supabase.auth.getSession() to find out who is signed in. Please switch it to supabase.auth.getClaims() ` +
|
|
853
|
+
'(or getUser()), which verifies the token, and use that result for any sign-in check or user id. Keep getSession() only where I just need to pass the access token along.',
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
// 9. What only a real test can show.
|
|
858
|
+
if (hasAccounts || usesSupabase || units.length) {
|
|
859
|
+
out.manual.push({
|
|
860
|
+
id: 'test-other-users-data',
|
|
861
|
+
title: "Try to open another user's data",
|
|
862
|
+
how: "Create two test accounts. Signed in as the second one, open, edit and delete the first one's records by changing the id in the URL or in the request " +
|
|
863
|
+
'(your browser\'s network tab shows it). Every attempt should fail with "not found" or "forbidden". Also try your admin pages and API while signed in as a normal user.',
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
return out;
|
|
867
|
+
},
|
|
868
|
+
};
|