kryptheon 0.1.57 → 0.1.61

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/kryptheon-keys.js CHANGED
@@ -1,353 +1,353 @@
1
- // Reads a project's code for keys that must never be in it.
2
- //
3
- // One key does more damage than any other mistake in an app built on
4
- // Supabase: the service_role key. It skips every row level security rule, so
5
- // whoever holds it can read, change and delete every row in every table. Put
6
- // in code that the browser downloads, it belongs to anyone who opens the
7
- // developer tools. Found on a blind test: a config.js fallback held one, and
8
- // every rule the database attack checked was beside the point - with that key
9
- // in the page, none of them apply.
10
- //
11
- // This is a read of the files, never a use of what is found: nothing is sent
12
- // anywhere and no key is tried. The key itself is never printed, saved or put
13
- // in a prompt - only its first characters and its length, enough for a person
14
- // to find it and too little for anyone to use it.
15
- //
16
- // Narrow on purpose, as the HTML read is. Only formats that are secret by
17
- // construction are reported as certain. Keys that are public by design - the
18
- // Supabase anon or publishable key, a Firebase web key - are never reported.
19
-
20
- const path = require('path');
21
-
22
- // A variable the build copies into the browser bundle, named as a secret.
23
- // Next, Vite, Create React App, Expo, Nuxt, SvelteKit and Gatsby all inline
24
- // anything with these prefixes, so the value ships whatever the file is.
25
- const PUBLIC_SECRET_NAME = /\b(NEXT_PUBLIC|VITE|REACT_APP|EXPO_PUBLIC|NUXT_PUBLIC|GATSBY|PUBLIC)_[A-Z0-9_]*(?:SERVICE_ROLE|SECRET)[A-Z0-9_]*\b/g;
26
-
27
- const SUPABASE_ROTATE = 'in the Supabase dashboard, open Project Settings, then API Keys, and roll the ' +
28
- 'service_role (secret) key';
29
- const SUPABASE_OPENS = 'It skips every row level security rule: anyone who has it can read, change ' +
30
- 'and delete every row in every table, and act as any user.';
31
- const SUPABASE_INSTEAD = 'the anon (publishable) key, with row level security doing the protecting';
32
-
33
- // Formats that are a secret whatever they are called. Each needs a real
34
- // length after its prefix, so a placeholder like "sb_secret_..." is not one.
35
- const FORMATS = [
36
- {
37
- re: /\bsb_secret_[A-Za-z0-9_-]{20,}/g,
38
- label: 'Supabase secret key',
39
- opens: SUPABASE_OPENS,
40
- rotate: SUPABASE_ROTATE,
41
- instead: SUPABASE_INSTEAD,
42
- },
43
- {
44
- re: /\b[sr]k_live_[A-Za-z0-9]{20,}/g,
45
- label: 'Stripe live secret key',
46
- opens: 'It can charge cards, issue refunds and read every customer and payment in your Stripe account.',
47
- rotate: 'in the Stripe dashboard, open Developers, then API keys, and roll it',
48
- instead: 'the publishable key (pk_live_...), with every charge made from your server',
49
- },
50
- {
51
- re: /\b[sr]k_test_[A-Za-z0-9]{20,}/g,
52
- label: 'Stripe test secret key',
53
- opens: 'It controls your Stripe test account. It moves no real money, but a live key in the same place would.',
54
- rotate: 'in the Stripe dashboard, open Developers, then API keys, and roll it',
55
- instead: 'the publishable key (pk_test_...), with every charge made from your server',
56
- },
57
- {
58
- re: /\bsk-ant-[A-Za-z0-9_-]{32,}/g,
59
- label: 'Anthropic API key',
60
- opens: 'Anyone who has it can run requests on your account and your bill.',
61
- rotate: 'in the Anthropic Console, open API Keys, and delete it',
62
- instead: 'a call to your own server, which holds the key',
63
- },
64
- {
65
- re: /\bsk-(?!ant-)(?:proj-|svcacct-)?[A-Za-z0-9_-]{32,}/g,
66
- label: 'OpenAI API key',
67
- opens: 'Anyone who has it can run requests on your account and your bill.',
68
- rotate: 'in the OpenAI dashboard, open API keys, and revoke it',
69
- instead: 'a call to your own server, which holds the key',
70
- },
71
- {
72
- re: /\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{40,})/g,
73
- label: 'GitHub token',
74
- opens: 'It acts as you on GitHub, with whatever access it was given - often every repository you have.',
75
- rotate: 'on GitHub, open Settings, then Developer settings, then Personal access tokens, and delete it',
76
- instead: 'nothing - a GitHub token has no business in app code at all',
77
- },
78
- ];
79
-
80
- const JWT = /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g;
81
-
82
- /** The claims of a JWT, or null when it is not one this can read. */
83
- function claimsOf(token) {
84
- try {
85
- const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
86
- const claims = JSON.parse(Buffer.from(part, 'base64').toString('utf8'));
87
- return claims && typeof claims === 'object' ? claims : null;
88
- } catch (err) {
89
- return null;
90
- }
91
- }
92
-
93
- // A quoted value that is shaped like a key and says it is a service-role one,
94
- // in a format this does not know. Digits are required: "YOUR_SERVICE_ROLE_KEY"
95
- // is somebody's placeholder, not a key. Reported as unconfirmed, because the
96
- // format cannot say whether it is real.
97
- const QUOTED = /(["'`])([A-Za-z0-9_.-]{24,})\1/g;
98
- function looksLikeServiceRoleKey(value) {
99
- if (!/service[_-]?role/i.test(value)) return false;
100
- if (/your|example|placeholder|changeme|x{4,}|here/i.test(value)) return false;
101
- return (value.match(/[0-9]/g) || []).length >= 4;
102
- }
103
-
104
- // A quoted value given to something named as a secret, in a format this does
105
- // not know. Found on a blind test (HarborLine): api.js held
106
- // `const replaySigningKey = 'hl_replay_8JQ4-...'` in code every visitor
107
- // downloads, and the read named nothing - it knew only famous formats. The
108
- // name says what it is meant to be; the value has to look like one too:
109
- // long, letters and digits, no spaces, not a placeholder. Names that are
110
- // public by design (anon, publishable, public) are left alone.
111
- const NAMED_SECRET = /\b([A-Za-z_$][\w$]*)\s*[:=]\s*(["'`])([^"'`\s]{16,})\2/g;
112
- const SECRET_NAME = /(secret|signingkey|privatekey|apikey|accesstoken|authtoken|refreshtoken|password|passwd|clientsecret|webhooksecret|encryptionkey|hmackey)$/;
113
- function looksLikeNamedSecret(name, value) {
114
- const bare = name.toLowerCase().replace(/[_$]/g, '');
115
- if (!SECRET_NAME.test(bare) || /anon|publishable|public/.test(bare)) return false;
116
- if (/your|example|placeholder|changeme|x{4,}|here|dummy|redacted|<|\$\{/i.test(value)) return false;
117
- if (/^(https?:|\/|\.)/i.test(value) || /^eyJ/.test(value)) return false; // an address or a path; JWTs are read above
118
- return (value.match(/[0-9]/g) || []).length >= 3 && (value.match(/[A-Za-z]/g) || []).length >= 3;
119
- }
120
-
121
- /** First characters and length - enough to find it, too little to use it. */
122
- function masked(value) {
123
- return value.slice(0, 6) + '... (' + value.length + ' characters, not shown)';
124
- }
125
-
126
- // Wrapped here, as the HTML read's prompts are: pasted into a chat box as
127
- // often as read in a terminal, and a long line is a wall in both.
128
- function wrap(text, width) {
129
- const out = [];
130
- let current = '';
131
- for (const word of String(text).split(' ')) {
132
- if (current && (current + ' ' + word).length > width) {
133
- out.push(current);
134
- current = word;
135
- } else {
136
- current = current ? current + ' ' + word : word;
137
- }
138
- }
139
- out.push(current);
140
- return out.join('\n');
141
- }
142
-
143
- function lineAt(source, index) {
144
- let line = 1;
145
- for (let i = 0; i < index; i++) if (source.charCodeAt(i) === 10) line++;
146
- return line;
147
- }
148
-
149
- // Where a file runs. A page, a file a page loads, or code that touches the
150
- // document is browser code; a file under api/, server/ or functions/, or one
151
- // that starts a server, is not. Anything else is said as it is: unknown.
152
- const SERVER_PATH = /(^|\/)(api|server|backend|functions|scripts|cron|workers?)\//i;
153
- const SERVER_CODE = /['"]use server['"]|require\(\s*['"](express|fastify|koa|http)['"]\s*\)|from\s+['"](express|fastify|koa)['"]|Deno\.serve\s*\(/;
154
- const BROWSER_CODE = /\b(?:document|window|localStorage|sessionStorage)\s*\.|['"]use client['"]|\buse(?:State|Effect)\s*\(/;
155
-
156
- function whereItRuns(rel, source, loadedBy) {
157
- if (/\.(html?|vue|svelte)$/i.test(rel)) return { browser: true, why: rel + ' is a page, so every visitor downloads it' };
158
- if (loadedBy && loadedBy.get(rel)) {
159
- return { browser: true, why: loadedBy.get(rel) + ' loads ' + rel + ', so every visitor downloads it' };
160
- }
161
- if (SERVER_PATH.test(rel) || SERVER_CODE.test(source)) return { browser: false, why: null };
162
- if (BROWSER_CODE.test(source)) return { browser: true, why: rel + ' runs in the browser' };
163
- return { browser: null, why: null };
164
- }
165
-
166
- /**
167
- * Which pages load which scripts: <script src="..."> read out of every page,
168
- * resolved against the page's folder. A full URL is skipped - it is not ours.
169
- */
170
- function scriptsLoadedBy(pages) {
171
- const loaded = new Map();
172
- for (const page of pages) {
173
- const re = /<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/gi;
174
- let m;
175
- while ((m = re.exec(page.source))) {
176
- const src = m[1].split('?')[0].split('#')[0];
177
- if (/^[a-z]+:|^\/\//i.test(src)) continue;
178
- const rel = src.startsWith('/')
179
- ? path.posix.normalize(src.slice(1))
180
- : path.posix.normalize(path.posix.join(path.posix.dirname(page.rel), src));
181
- if (!loaded.has(rel)) loaded.set(rel, page.rel);
182
- }
183
- }
184
- return loaded;
185
- }
186
-
187
- function keyFinding(rel, source, index, value, kind, confidence, runs) {
188
- const line = lineAt(source, index);
189
- const severity = kind.severity || (runs.browser === false ? 'HIGH' : runs.browser ? 'CRITICAL' : 'HIGH');
190
- const shown = masked(value);
191
- const a = confidence === 'high' ? 'A ' : 'What looks like a ';
192
- const f = {
193
- kind: 'secret-in-code',
194
- status: 'verification required',
195
- evidence: 'code analysis',
196
- severity: severity,
197
- confidence: confidence,
198
- file: rel,
199
- line: line,
200
- sink: 'secret key',
201
- expression: shown,
202
- origin: 'code',
203
- parts: [],
204
- via: null,
205
- headline: a + kind.label + ' is written into ' + rel + ':' + line +
206
- (runs.browser ? ', and it reaches the browser.'
207
- : runs.browser === false ? ' (server code - still in every copy of the repository).' : '.'),
208
- };
209
- f.fixPrompt = [
210
- 'My app has a secret key written into its code. Please fix it - and do not paste the key back to me.',
211
- '',
212
- 'In ' + rel + ' at line ' + line + ' there is ' + a.toLowerCase() + kind.label +
213
- ' (it starts with "' + value.slice(0, 6) + '").' + (runs.why ? ' ' + runs.why + '.' : ''),
214
- kind.opens,
215
- '',
216
- '1. Rotate it first: ' + kind.rotate + '. Taking it out of the code is not enough - it is already in ' +
217
- 'the deployed site and in the git history.',
218
- '2. Remove it from this file and from anything that reads it. Code that runs in the browser should only ' +
219
- 'ever use ' + kind.instead + '.',
220
- '3. Anything that truly needs the secret moves to server code - an API route or a Supabase Edge Function - ' +
221
- 'reading it from an environment variable with no public prefix (not NEXT_PUBLIC_, VITE_ or REACT_APP_).',
222
- '4. Search the whole project, config files and HTML included, for any other copy of it.',
223
- ].map((l) => wrap(l, 72)).join('\n');
224
- return f;
225
- }
226
-
227
- function publicNameFinding(rel, source, index, name, prefix) {
228
- const line = lineAt(source, index);
229
- const supabase = /SUPABASE|SERVICE_ROLE/.test(name);
230
- return {
231
- kind: 'secret-in-code',
232
- status: 'verification required',
233
- evidence: 'code analysis',
234
- severity: 'CRITICAL',
235
- confidence: 'high',
236
- file: rel,
237
- line: line,
238
- sink: 'secret in a public variable',
239
- expression: name,
240
- origin: 'code',
241
- parts: [],
242
- via: null,
243
- headline: rel + ':' + line + ' reads ' + name + ' - every variable starting ' + prefix +
244
- ' is copied into the browser, so the secret ships with the site.',
245
- fixPrompt: [
246
- 'My app puts a secret into the browser through an environment variable. Please fix it - and do not ' +
247
- 'paste the value back to me.',
248
- '',
249
- 'In ' + rel + ' at line ' + line + ' the code reads ' + name + '. The build copies every variable ' +
250
- 'starting ' + prefix + ' into the JavaScript each visitor downloads, whatever file reads it.',
251
- supabase ? SUPABASE_OPENS : 'Whoever opens the browser tools has the secret.',
252
- '',
253
- '1. Rotate the secret first' + (supabase ? ': ' + SUPABASE_ROTATE : '') + '. The built site already contains it.',
254
- '2. Rename the variable without the public prefix and read it only in server code - an API route or a ' +
255
- 'Supabase Edge Function.',
256
- '3. Code that runs in the browser should only ever use ' +
257
- (supabase ? SUPABASE_INSTEAD : 'values that are safe to publish') + '.',
258
- '4. Search the whole project for every other place that reads it.',
259
- ].map((l) => wrap(l, 72)).join('\n'),
260
- };
261
- }
262
-
263
- /** Every secret in one file. `loadedBy` maps a script to a page that loads it. */
264
- function secretsIn(rel, source, loadedBy) {
265
- const out = [];
266
- const seen = new Set();
267
- const runs = whereItRuns(rel, source, loadedBy);
268
- const add = (index, value, kind, confidence) => {
269
- if (seen.has(value)) return;
270
- seen.add(value);
271
- out.push(keyFinding(rel, source, index, value, kind, confidence, runs));
272
- };
273
-
274
- for (const format of FORMATS) {
275
- format.re.lastIndex = 0;
276
- let m;
277
- while ((m = format.re.exec(source))) add(m.index, m[0], format, 'high');
278
- }
279
-
280
- JWT.lastIndex = 0;
281
- let j;
282
- while ((j = JWT.exec(source))) {
283
- const claims = claimsOf(j[0]);
284
- if (!claims || claims.role !== 'service_role') continue; // anon and user tokens are public by design
285
- // Supabase's local development key is the same published value on every
286
- // machine: harmless against a laptop, but a sign of where a real one goes.
287
- const demo = claims.iss === 'supabase-demo';
288
- add(j.index, j[0], demo
289
- ? {
290
- label: 'Supabase service_role key (the published local-development one)',
291
- opens: 'Against a laptop it does no harm. But this is the place a real project\'s service_role key ' +
292
- 'would go, and there it would open every table to anyone.',
293
- rotate: 'nothing to rotate for the local key itself - check that no real key is used the same way',
294
- instead: SUPABASE_INSTEAD,
295
- severity: 'MEDIUM',
296
- }
297
- : { label: 'Supabase service_role key', opens: SUPABASE_OPENS, rotate: SUPABASE_ROTATE, instead: SUPABASE_INSTEAD },
298
- 'high');
299
- }
300
-
301
- QUOTED.lastIndex = 0;
302
- let q;
303
- while ((q = QUOTED.exec(source))) {
304
- if (!looksLikeServiceRoleKey(q[2])) continue;
305
- add(q.index + 1, q[2], {
306
- label: 'Supabase service_role key',
307
- opens: SUPABASE_OPENS + ' Its format is not one I know, so check whether it is a real key.',
308
- rotate: SUPABASE_ROTATE,
309
- instead: SUPABASE_INSTEAD,
310
- }, 'medium');
311
- }
312
-
313
- // Never in a test, whose secrets are made up for it and ship nowhere.
314
- const inTest = /(^|\/)__tests__\/|\.(test|spec|check)\.[cm]?[jt]sx?$/i.test(rel);
315
- NAMED_SECRET.lastIndex = 0;
316
- let s;
317
- while (!inTest && (s = NAMED_SECRET.exec(source))) {
318
- if (!looksLikeNamedSecret(s[1], s[3])) continue;
319
- add(s.index + s[0].indexOf(s[3]), s[3], {
320
- label: 'secret ("' + s[1] + '")',
321
- opens: 'Its name says it is a secret, and whoever has it can do whatever it signs or unlocks. ' +
322
- 'Its format is not one I know, so check whether it is a real one.',
323
- rotate: 'wherever it was issued, issue a new one and revoke this one',
324
- instead: 'a call to your own server, which holds the secret',
325
- severity: runs.browser ? 'HIGH' : 'MEDIUM',
326
- }, 'medium');
327
- }
328
-
329
- // Only where it is read from the environment, and never in a test: found on
330
- // Kryptheon's own code, a constant called PUBLIC_SECRET_NAME is a name in a
331
- // program, not a variable the build ships - and a test file ships nothing.
332
- const isTest = /(^|\/)__tests__\/|\.(test|spec|check)\.[cm]?[jt]sx?$/i.test(rel);
333
- const svelteEnv = /from\s+['"]\$env\/(static|dynamic)\/public['"]/.test(source);
334
- PUBLIC_SECRET_NAME.lastIndex = 0;
335
- let n;
336
- while (!isTest && (n = PUBLIC_SECRET_NAME.exec(source))) {
337
- const before = source.slice(Math.max(0, n.index - 40), n.index);
338
- const read = /(process\.env|import\.meta\.env|\benv)\s*(\.|\[\s*['"])$/.test(before) || svelteEnv;
339
- if (!read || seen.has(n[0])) continue;
340
- seen.add(n[0]);
341
- out.push(publicNameFinding(rel, source, n.index, n[0], n[1] + '_'));
342
- }
343
-
344
- return out;
345
- }
346
-
347
- module.exports = {
348
- secretsIn: secretsIn,
349
- scriptsLoadedBy: scriptsLoadedBy,
350
- whereItRuns: whereItRuns,
351
- masked: masked,
352
- claimsOf: claimsOf,
353
- };
1
+ // Reads a project's code for keys that must never be in it.
2
+ //
3
+ // One key does more damage than any other mistake in an app built on
4
+ // Supabase: the service_role key. It skips every row level security rule, so
5
+ // whoever holds it can read, change and delete every row in every table. Put
6
+ // in code that the browser downloads, it belongs to anyone who opens the
7
+ // developer tools. Found on a blind test: a config.js fallback held one, and
8
+ // every rule the database attack checked was beside the point - with that key
9
+ // in the page, none of them apply.
10
+ //
11
+ // This is a read of the files, never a use of what is found: nothing is sent
12
+ // anywhere and no key is tried. The key itself is never printed, saved or put
13
+ // in a prompt - only its first characters and its length, enough for a person
14
+ // to find it and too little for anyone to use it.
15
+ //
16
+ // Narrow on purpose, as the HTML read is. Only formats that are secret by
17
+ // construction are reported as certain. Keys that are public by design - the
18
+ // Supabase anon or publishable key, a Firebase web key - are never reported.
19
+
20
+ const path = require('path');
21
+
22
+ // A variable the build copies into the browser bundle, named as a secret.
23
+ // Next, Vite, Create React App, Expo, Nuxt, SvelteKit and Gatsby all inline
24
+ // anything with these prefixes, so the value ships whatever the file is.
25
+ const PUBLIC_SECRET_NAME = /\b(NEXT_PUBLIC|VITE|REACT_APP|EXPO_PUBLIC|NUXT_PUBLIC|GATSBY|PUBLIC)_[A-Z0-9_]*(?:SERVICE_ROLE|SECRET)[A-Z0-9_]*\b/g;
26
+
27
+ const SUPABASE_ROTATE = 'in the Supabase dashboard, open Project Settings, then API Keys, and roll the ' +
28
+ 'service_role (secret) key';
29
+ const SUPABASE_OPENS = 'It skips every row level security rule: anyone who has it can read, change ' +
30
+ 'and delete every row in every table, and act as any user.';
31
+ const SUPABASE_INSTEAD = 'the anon (publishable) key, with row level security doing the protecting';
32
+
33
+ // Formats that are a secret whatever they are called. Each needs a real
34
+ // length after its prefix, so a placeholder like "sb_secret_..." is not one.
35
+ const FORMATS = [
36
+ {
37
+ re: /\bsb_secret_[A-Za-z0-9_-]{20,}/g,
38
+ label: 'Supabase secret key',
39
+ opens: SUPABASE_OPENS,
40
+ rotate: SUPABASE_ROTATE,
41
+ instead: SUPABASE_INSTEAD,
42
+ },
43
+ {
44
+ re: /\b[sr]k_live_[A-Za-z0-9]{20,}/g,
45
+ label: 'Stripe live secret key',
46
+ opens: 'It can charge cards, issue refunds and read every customer and payment in your Stripe account.',
47
+ rotate: 'in the Stripe dashboard, open Developers, then API keys, and roll it',
48
+ instead: 'the publishable key (pk_live_...), with every charge made from your server',
49
+ },
50
+ {
51
+ re: /\b[sr]k_test_[A-Za-z0-9]{20,}/g,
52
+ label: 'Stripe test secret key',
53
+ opens: 'It controls your Stripe test account. It moves no real money, but a live key in the same place would.',
54
+ rotate: 'in the Stripe dashboard, open Developers, then API keys, and roll it',
55
+ instead: 'the publishable key (pk_test_...), with every charge made from your server',
56
+ },
57
+ {
58
+ re: /\bsk-ant-[A-Za-z0-9_-]{32,}/g,
59
+ label: 'Anthropic API key',
60
+ opens: 'Anyone who has it can run requests on your account and your bill.',
61
+ rotate: 'in the Anthropic Console, open API Keys, and delete it',
62
+ instead: 'a call to your own server, which holds the key',
63
+ },
64
+ {
65
+ re: /\bsk-(?!ant-)(?:proj-|svcacct-)?[A-Za-z0-9_-]{32,}/g,
66
+ label: 'OpenAI API key',
67
+ opens: 'Anyone who has it can run requests on your account and your bill.',
68
+ rotate: 'in the OpenAI dashboard, open API keys, and revoke it',
69
+ instead: 'a call to your own server, which holds the key',
70
+ },
71
+ {
72
+ re: /\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{40,})/g,
73
+ label: 'GitHub token',
74
+ opens: 'It acts as you on GitHub, with whatever access it was given - often every repository you have.',
75
+ rotate: 'on GitHub, open Settings, then Developer settings, then Personal access tokens, and delete it',
76
+ instead: 'nothing - a GitHub token has no business in app code at all',
77
+ },
78
+ ];
79
+
80
+ const JWT = /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g;
81
+
82
+ /** The claims of a JWT, or null when it is not one this can read. */
83
+ function claimsOf(token) {
84
+ try {
85
+ const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
86
+ const claims = JSON.parse(Buffer.from(part, 'base64').toString('utf8'));
87
+ return claims && typeof claims === 'object' ? claims : null;
88
+ } catch (err) {
89
+ return null;
90
+ }
91
+ }
92
+
93
+ // A quoted value that is shaped like a key and says it is a service-role one,
94
+ // in a format this does not know. Digits are required: "YOUR_SERVICE_ROLE_KEY"
95
+ // is somebody's placeholder, not a key. Reported as unconfirmed, because the
96
+ // format cannot say whether it is real.
97
+ const QUOTED = /(["'`])([A-Za-z0-9_.-]{24,})\1/g;
98
+ function looksLikeServiceRoleKey(value) {
99
+ if (!/service[_-]?role/i.test(value)) return false;
100
+ if (/your|example|placeholder|changeme|x{4,}|here/i.test(value)) return false;
101
+ return (value.match(/[0-9]/g) || []).length >= 4;
102
+ }
103
+
104
+ // A quoted value given to something named as a secret, in a format this does
105
+ // not know. Found on a blind test (HarborLine): api.js held
106
+ // `const replaySigningKey = 'hl_replay_8JQ4-...'` in code every visitor
107
+ // downloads, and the read named nothing - it knew only famous formats. The
108
+ // name says what it is meant to be; the value has to look like one too:
109
+ // long, letters and digits, no spaces, not a placeholder. Names that are
110
+ // public by design (anon, publishable, public) are left alone.
111
+ const NAMED_SECRET = /\b([A-Za-z_$][\w$]*)\s*[:=]\s*(["'`])([^"'`\s]{16,})\2/g;
112
+ const SECRET_NAME = /(secret|signingkey|privatekey|apikey|accesstoken|authtoken|refreshtoken|password|passwd|clientsecret|webhooksecret|encryptionkey|hmackey)$/;
113
+ function looksLikeNamedSecret(name, value) {
114
+ const bare = name.toLowerCase().replace(/[_$]/g, '');
115
+ if (!SECRET_NAME.test(bare) || /anon|publishable|public/.test(bare)) return false;
116
+ if (/your|example|placeholder|changeme|x{4,}|here|dummy|redacted|<|\$\{/i.test(value)) return false;
117
+ if (/^(https?:|\/|\.)/i.test(value) || /^eyJ/.test(value)) return false; // an address or a path; JWTs are read above
118
+ return (value.match(/[0-9]/g) || []).length >= 3 && (value.match(/[A-Za-z]/g) || []).length >= 3;
119
+ }
120
+
121
+ /** First characters and length - enough to find it, too little to use it. */
122
+ function masked(value) {
123
+ return value.slice(0, 6) + '... (' + value.length + ' characters, not shown)';
124
+ }
125
+
126
+ // Wrapped here, as the HTML read's prompts are: pasted into a chat box as
127
+ // often as read in a terminal, and a long line is a wall in both.
128
+ function wrap(text, width) {
129
+ const out = [];
130
+ let current = '';
131
+ for (const word of String(text).split(' ')) {
132
+ if (current && (current + ' ' + word).length > width) {
133
+ out.push(current);
134
+ current = word;
135
+ } else {
136
+ current = current ? current + ' ' + word : word;
137
+ }
138
+ }
139
+ out.push(current);
140
+ return out.join('\n');
141
+ }
142
+
143
+ function lineAt(source, index) {
144
+ let line = 1;
145
+ for (let i = 0; i < index; i++) if (source.charCodeAt(i) === 10) line++;
146
+ return line;
147
+ }
148
+
149
+ // Where a file runs. A page, a file a page loads, or code that touches the
150
+ // document is browser code; a file under api/, server/ or functions/, or one
151
+ // that starts a server, is not. Anything else is said as it is: unknown.
152
+ const SERVER_PATH = /(^|\/)(api|server|backend|functions|scripts|cron|workers?)\//i;
153
+ const SERVER_CODE = /['"]use server['"]|require\(\s*['"](express|fastify|koa|http)['"]\s*\)|from\s+['"](express|fastify|koa)['"]|Deno\.serve\s*\(/;
154
+ const BROWSER_CODE = /\b(?:document|window|localStorage|sessionStorage)\s*\.|['"]use client['"]|\buse(?:State|Effect)\s*\(/;
155
+
156
+ function whereItRuns(rel, source, loadedBy) {
157
+ if (/\.(html?|vue|svelte)$/i.test(rel)) return { browser: true, why: rel + ' is a page, so every visitor downloads it' };
158
+ if (loadedBy && loadedBy.get(rel)) {
159
+ return { browser: true, why: loadedBy.get(rel) + ' loads ' + rel + ', so every visitor downloads it' };
160
+ }
161
+ if (SERVER_PATH.test(rel) || SERVER_CODE.test(source)) return { browser: false, why: null };
162
+ if (BROWSER_CODE.test(source)) return { browser: true, why: rel + ' runs in the browser' };
163
+ return { browser: null, why: null };
164
+ }
165
+
166
+ /**
167
+ * Which pages load which scripts: <script src="..."> read out of every page,
168
+ * resolved against the page's folder. A full URL is skipped - it is not ours.
169
+ */
170
+ function scriptsLoadedBy(pages) {
171
+ const loaded = new Map();
172
+ for (const page of pages) {
173
+ const re = /<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/gi;
174
+ let m;
175
+ while ((m = re.exec(page.source))) {
176
+ const src = m[1].split('?')[0].split('#')[0];
177
+ if (/^[a-z]+:|^\/\//i.test(src)) continue;
178
+ const rel = src.startsWith('/')
179
+ ? path.posix.normalize(src.slice(1))
180
+ : path.posix.normalize(path.posix.join(path.posix.dirname(page.rel), src));
181
+ if (!loaded.has(rel)) loaded.set(rel, page.rel);
182
+ }
183
+ }
184
+ return loaded;
185
+ }
186
+
187
+ function keyFinding(rel, source, index, value, kind, confidence, runs) {
188
+ const line = lineAt(source, index);
189
+ const severity = kind.severity || (runs.browser === false ? 'HIGH' : runs.browser ? 'CRITICAL' : 'HIGH');
190
+ const shown = masked(value);
191
+ const a = confidence === 'high' ? 'A ' : 'What looks like a ';
192
+ const f = {
193
+ kind: 'secret-in-code',
194
+ status: 'verification required',
195
+ evidence: 'code analysis',
196
+ severity: severity,
197
+ confidence: confidence,
198
+ file: rel,
199
+ line: line,
200
+ sink: 'secret key',
201
+ expression: shown,
202
+ origin: 'code',
203
+ parts: [],
204
+ via: null,
205
+ headline: a + kind.label + ' is written into ' + rel + ':' + line +
206
+ (runs.browser ? ', and it reaches the browser.'
207
+ : runs.browser === false ? ' (server code - still in every copy of the repository).' : '.'),
208
+ };
209
+ f.fixPrompt = [
210
+ 'My app has a secret key written into its code. Please fix it - and do not paste the key back to me.',
211
+ '',
212
+ 'In ' + rel + ' at line ' + line + ' there is ' + a.toLowerCase() + kind.label +
213
+ ' (it starts with "' + value.slice(0, 6) + '").' + (runs.why ? ' ' + runs.why + '.' : ''),
214
+ kind.opens,
215
+ '',
216
+ '1. Rotate it first: ' + kind.rotate + '. Taking it out of the code is not enough - it is already in ' +
217
+ 'the deployed site and in the git history.',
218
+ '2. Remove it from this file and from anything that reads it. Code that runs in the browser should only ' +
219
+ 'ever use ' + kind.instead + '.',
220
+ '3. Anything that truly needs the secret moves to server code - an API route or a Supabase Edge Function - ' +
221
+ 'reading it from an environment variable with no public prefix (not NEXT_PUBLIC_, VITE_ or REACT_APP_).',
222
+ '4. Search the whole project, config files and HTML included, for any other copy of it.',
223
+ ].map((l) => wrap(l, 72)).join('\n');
224
+ return f;
225
+ }
226
+
227
+ function publicNameFinding(rel, source, index, name, prefix) {
228
+ const line = lineAt(source, index);
229
+ const supabase = /SUPABASE|SERVICE_ROLE/.test(name);
230
+ return {
231
+ kind: 'secret-in-code',
232
+ status: 'verification required',
233
+ evidence: 'code analysis',
234
+ severity: 'CRITICAL',
235
+ confidence: 'high',
236
+ file: rel,
237
+ line: line,
238
+ sink: 'secret in a public variable',
239
+ expression: name,
240
+ origin: 'code',
241
+ parts: [],
242
+ via: null,
243
+ headline: rel + ':' + line + ' reads ' + name + ' - every variable starting ' + prefix +
244
+ ' is copied into the browser, so the secret ships with the site.',
245
+ fixPrompt: [
246
+ 'My app puts a secret into the browser through an environment variable. Please fix it - and do not ' +
247
+ 'paste the value back to me.',
248
+ '',
249
+ 'In ' + rel + ' at line ' + line + ' the code reads ' + name + '. The build copies every variable ' +
250
+ 'starting ' + prefix + ' into the JavaScript each visitor downloads, whatever file reads it.',
251
+ supabase ? SUPABASE_OPENS : 'Whoever opens the browser tools has the secret.',
252
+ '',
253
+ '1. Rotate the secret first' + (supabase ? ': ' + SUPABASE_ROTATE : '') + '. The built site already contains it.',
254
+ '2. Rename the variable without the public prefix and read it only in server code - an API route or a ' +
255
+ 'Supabase Edge Function.',
256
+ '3. Code that runs in the browser should only ever use ' +
257
+ (supabase ? SUPABASE_INSTEAD : 'values that are safe to publish') + '.',
258
+ '4. Search the whole project for every other place that reads it.',
259
+ ].map((l) => wrap(l, 72)).join('\n'),
260
+ };
261
+ }
262
+
263
+ /** Every secret in one file. `loadedBy` maps a script to a page that loads it. */
264
+ function secretsIn(rel, source, loadedBy) {
265
+ const out = [];
266
+ const seen = new Set();
267
+ const runs = whereItRuns(rel, source, loadedBy);
268
+ const add = (index, value, kind, confidence) => {
269
+ if (seen.has(value)) return;
270
+ seen.add(value);
271
+ out.push(keyFinding(rel, source, index, value, kind, confidence, runs));
272
+ };
273
+
274
+ for (const format of FORMATS) {
275
+ format.re.lastIndex = 0;
276
+ let m;
277
+ while ((m = format.re.exec(source))) add(m.index, m[0], format, 'high');
278
+ }
279
+
280
+ JWT.lastIndex = 0;
281
+ let j;
282
+ while ((j = JWT.exec(source))) {
283
+ const claims = claimsOf(j[0]);
284
+ if (!claims || claims.role !== 'service_role') continue; // anon and user tokens are public by design
285
+ // Supabase's local development key is the same published value on every
286
+ // machine: harmless against a laptop, but a sign of where a real one goes.
287
+ const demo = claims.iss === 'supabase-demo';
288
+ add(j.index, j[0], demo
289
+ ? {
290
+ label: 'Supabase service_role key (the published local-development one)',
291
+ opens: 'Against a laptop it does no harm. But this is the place a real project\'s service_role key ' +
292
+ 'would go, and there it would open every table to anyone.',
293
+ rotate: 'nothing to rotate for the local key itself - check that no real key is used the same way',
294
+ instead: SUPABASE_INSTEAD,
295
+ severity: 'MEDIUM',
296
+ }
297
+ : { label: 'Supabase service_role key', opens: SUPABASE_OPENS, rotate: SUPABASE_ROTATE, instead: SUPABASE_INSTEAD },
298
+ 'high');
299
+ }
300
+
301
+ QUOTED.lastIndex = 0;
302
+ let q;
303
+ while ((q = QUOTED.exec(source))) {
304
+ if (!looksLikeServiceRoleKey(q[2])) continue;
305
+ add(q.index + 1, q[2], {
306
+ label: 'Supabase service_role key',
307
+ opens: SUPABASE_OPENS + ' Its format is not one I know, so check whether it is a real key.',
308
+ rotate: SUPABASE_ROTATE,
309
+ instead: SUPABASE_INSTEAD,
310
+ }, 'medium');
311
+ }
312
+
313
+ // Never in a test, whose secrets are made up for it and ship nowhere.
314
+ const inTest = /(^|\/)__tests__\/|\.(test|spec|check)\.[cm]?[jt]sx?$/i.test(rel);
315
+ NAMED_SECRET.lastIndex = 0;
316
+ let s;
317
+ while (!inTest && (s = NAMED_SECRET.exec(source))) {
318
+ if (!looksLikeNamedSecret(s[1], s[3])) continue;
319
+ add(s.index + s[0].indexOf(s[3]), s[3], {
320
+ label: 'secret ("' + s[1] + '")',
321
+ opens: 'Its name says it is a secret, and whoever has it can do whatever it signs or unlocks. ' +
322
+ 'Its format is not one I know, so check whether it is a real one.',
323
+ rotate: 'wherever it was issued, issue a new one and revoke this one',
324
+ instead: 'a call to your own server, which holds the secret',
325
+ severity: runs.browser ? 'HIGH' : 'MEDIUM',
326
+ }, 'medium');
327
+ }
328
+
329
+ // Only where it is read from the environment, and never in a test: found on
330
+ // Kryptheon's own code, a constant called PUBLIC_SECRET_NAME is a name in a
331
+ // program, not a variable the build ships - and a test file ships nothing.
332
+ const isTest = /(^|\/)__tests__\/|\.(test|spec|check)\.[cm]?[jt]sx?$/i.test(rel);
333
+ const svelteEnv = /from\s+['"]\$env\/(static|dynamic)\/public['"]/.test(source);
334
+ PUBLIC_SECRET_NAME.lastIndex = 0;
335
+ let n;
336
+ while (!isTest && (n = PUBLIC_SECRET_NAME.exec(source))) {
337
+ const before = source.slice(Math.max(0, n.index - 40), n.index);
338
+ const read = /(process\.env|import\.meta\.env|\benv)\s*(\.|\[\s*['"])$/.test(before) || svelteEnv;
339
+ if (!read || seen.has(n[0])) continue;
340
+ seen.add(n[0]);
341
+ out.push(publicNameFinding(rel, source, n.index, n[0], n[1] + '_'));
342
+ }
343
+
344
+ return out;
345
+ }
346
+
347
+ module.exports = {
348
+ secretsIn: secretsIn,
349
+ scriptsLoadedBy: scriptsLoadedBy,
350
+ whereItRuns: whereItRuns,
351
+ masked: masked,
352
+ claimsOf: claimsOf,
353
+ };