包文件→ .shtukbase/packages/std-twelve-factor/checks/tf01_config.ts
checks/tf01_config.ts
32 行, 2.3 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // TF-R01 (III Config, observe): code does not hard-code the address of a backing service or a credential in a URL;
- // it reads them from the environment. A heuristic over code files (tests and fixtures excluded).
- import { codeFiles, COMMENT, PKG, PLACEHOLDER, READS_ENV, SAFE_HOST } from './tflib.ts';
- import { finish, norm, readTextFile } from './lib/std.ts';
- const n = norm(PKG, 'TF-R01', 'observe');
- const out: string[] = [];
- // "postgres://…", "redis://…", "amqp://…", "mongodb+srv://…" in a string literal.
- const CONN = /["'`](?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis|rediss|amqps?|nats|kafka|mssql|sqlserver|clickhouse):\/\/[^"'`\s]+["'`]/i;
- // DATABASE_URL = "https://…", REDIS_HOST: 'cache.internal', apiEndpoint = "https://api…"
- const NAMED = /\b([A-Za-z_]*(?:DATABASE|DB|REDIS|MONGO|AMQP|RABBIT|KAFKA|ELASTIC|SMTP|BROKER|QUEUE|CACHE|API|SERVICE|BACKEND)[_]?(?:URL|URI|HOST|DSN|ENDPOINT|ADDR|ADDRESS))\b["']?\s*(?::=|=|:)\s*["'`]([^"'`\s]{4,})["'`]/i;
- const CRED = /\b[a-z][a-z0-9+.-]*:\/\/[^\s:/@'"`]+:([^\s@/'"`]{3,})@([^\s/:'"`]+)/i;
- /** The host of a URL-ish value, if any. */
- const host = (v: string) => /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]*@)?([^/:?#]+)/i.exec(v)?.[1] ?? v.replace(/:\d+$/, '');
- if (n.active)
- for (const f of codeFiles()) {
- const text = readTextFile(f);
- if (text === null) continue;
- text.split('\n').forEach((l, i) => {
- if (l.length > 2000 || COMMENT.test(l) || READS_ENV.test(l) || /secrets:allow|12factor:allow/.test(l)) return;
- const cred = CRED.exec(l);
- const conn = CONN.exec(l);
- if (cred && !PLACEHOLDER.test(cred[1]) && !SAFE_HOST.test(cred[2])) out.push(`${f}:${i + 1}: a login and password in an address right in the code → read the address from an environment variable`);
- else if (cred) return;
- else if (conn && !SAFE_HOST.test(host(conn[0].slice(1, -1)))) out.push(`${f}:${i + 1}: the address of an external service (database, queue, cache) right in the code → read it from an environment variable`);
- else {
- const m = NAMED.exec(l);
- if (m && /^[a-z]+:\/\/|\.[a-z]{2,}(:\d+)?$|:\d{2,5}$/i.test(m[2]) && !SAFE_HOST.test(host(m[2]))) out.push(`${f}:${i + 1}: "${m[1]}" is set in the code → read it from an environment variable`);
- }
- });
- }
- finish(n, out);