来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
154 lines
6.2 KiB
TypeScript
154 lines
6.2 KiB
TypeScript
/**
|
||
* 密钥泄漏探测器(只读)——用于回答"以后还会不会泄漏"。
|
||
*
|
||
* 做了什么:
|
||
* ① 扫所有 schema 的 `operation_logs.new_value/old_value`(历史泄漏点);
|
||
* ② 扫所有 schema 里**全部文本/JSON 列**,看除"配置本体"外还有没有别的地方存下密钥;
|
||
* ③ 只输出 `schema.表.列 → 命中行数`,**绝不打印密钥内容**;不写任何数据(纯 SELECT)。
|
||
*
|
||
* 预期内 vs 异常:
|
||
* - `system_configs.config_value` 命中属**预期**(LLM 配置本体必须存密钥才能调模型),单列一节列出;
|
||
* - 其它任何位置命中都算**异常**,脚本以退出码 1 结束(可用于 CI / 上线前/后巡检)。
|
||
*
|
||
* 用法(server 目录):
|
||
* npm run diag:secret-scan # 扫当前 DATABASE_URL
|
||
* npm run diag:secret-scan -- --all-tenants # 默认就是全部 schema,参数保留以示意
|
||
*
|
||
* 设计:docs/design/20260924-audit-redaction-hardening.md
|
||
*/
|
||
import pg from 'pg';
|
||
|
||
const { Pool } = pg;
|
||
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||
|
||
/**
|
||
* 与 src/services/auditRedaction.ts 的 SECRET_VALUE_PATTERNS 对应,但**按大小写敏感性分两组**
|
||
* (踩过坑:把 AKIA 放进大小写不敏感组会误报 —— COS 签名 URL 里出现过含小写的 `AKIAMB…`,不是 AWS key)。
|
||
* 同时键名规则要求"值非空且未打码"(`[^"*]`),否则 `"apiKeys": ""` 会被误报。
|
||
*/
|
||
const CONTENT_PATTERN_CI = [
|
||
'(sk-|apikey-|ark-)[A-Za-z0-9_-]{16,}',
|
||
'Bearer\\s+[A-Za-z0-9._~+/-]{24,}=*',
|
||
'postgres(ql)?://[^"\\s]+:[^"@\\s]+@',
|
||
'(q-)?signature=[A-Za-z0-9%._-]{16,}',
|
||
].join('|');
|
||
|
||
const CONTENT_PATTERN_CS = [
|
||
'AKIA[0-9A-Z]{16}',
|
||
'eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{5,}',
|
||
'-----BEGIN [A-Z ]*PRIVATE KEY-----',
|
||
].join('|');
|
||
|
||
/** 敏感键名 + 值非空且未打码(未脱敏)形态 */
|
||
const UNMASKED_KEY_PATTERN =
|
||
'(api_?keys?|apiKey|apiKeys|private_?key|privateKey|access_?key|accessKey|accessKeyId|llm_?key|' +
|
||
'secret|secretKey|appSecret|client_?secret|token|authToken|sessionToken|refresh_?token|idToken|' +
|
||
'authorization|cookie|signature|credential|credentials|passwd|password)"\\s*:\\s*"[^"*]';
|
||
|
||
const PATTERN_CI = `${CONTENT_PATTERN_CI}|${UNMASKED_KEY_PATTERN}`;
|
||
const PATTERN_CS = CONTENT_PATTERN_CS;
|
||
|
||
/** 命中判定:大小写不敏感组用 ~*,大小写敏感组(AWS/JWT/PEM)用 ~ —— 避免误报。 */
|
||
const HIT_PREDICATE = `(col::text ~* $1 OR col::text ~ $2)`;
|
||
|
||
/** 配置本体:按设计允许存密钥,单独统计(不算泄漏) */
|
||
const EXPECTED_CONFIG_TABLE = 'system_configs';
|
||
const EXPECTED_CONFIG_COLUMN = 'config_value';
|
||
|
||
type Hit = { schema: string; table: string; column: string; rows: number };
|
||
|
||
async function schemas(): Promise<string[]> {
|
||
const res = await pool.query(
|
||
`SELECT nspname FROM pg_namespace
|
||
WHERE nspname = 'public' OR nspname = 'legacy_public' OR nspname = 'tenant_template' OR nspname LIKE 'tenant_%'
|
||
ORDER BY 1`
|
||
);
|
||
return res.rows.map((r) => String(r.nspname));
|
||
}
|
||
|
||
async function scanOperationLogs(schema: string): Promise<Hit[]> {
|
||
const exists = await pool.query(
|
||
`SELECT 1 FROM information_schema.tables WHERE table_schema = $1 AND table_name = 'operation_logs'`,
|
||
[schema]
|
||
);
|
||
if (!exists.rowCount) return [];
|
||
const res = await pool.query(
|
||
`SELECT count(*)::int AS c FROM "${schema}".operation_logs
|
||
WHERE (new_value::text ~* $1 OR new_value::text ~ $2)
|
||
OR (old_value::text ~* $1 OR old_value::text ~ $2)`,
|
||
[PATTERN_CI, PATTERN_CS]
|
||
);
|
||
const rows = Number(res.rows[0]?.c) || 0;
|
||
return rows
|
||
? [{ schema, table: 'operation_logs', column: 'new_value/old_value', rows }]
|
||
: [];
|
||
}
|
||
|
||
async function scanAllTextColumns(schema: string): Promise<Hit[]> {
|
||
const cols = await pool.query(
|
||
`SELECT table_name, column_name FROM information_schema.columns
|
||
WHERE table_schema = $1
|
||
AND data_type IN ('text', 'character varying', 'json', 'jsonb')
|
||
ORDER BY table_name, column_name`,
|
||
[schema]
|
||
);
|
||
const hits: Hit[] = [];
|
||
for (const row of cols.rows) {
|
||
const table = String(row.table_name);
|
||
const column = String(row.column_name);
|
||
if (table === 'operation_logs' && (column === 'new_value' || column === 'old_value')) continue;
|
||
const res = await pool.query(
|
||
`SELECT count(*)::int AS c FROM "${schema}"."${table}"
|
||
WHERE "${column}"::text ~* $1 OR "${column}"::text ~ $2`,
|
||
[PATTERN_CI, PATTERN_CS]
|
||
);
|
||
const rows = Number(res.rows[0]?.c) || 0;
|
||
if (rows > 0) hits.push({ schema, table, column, rows });
|
||
}
|
||
return hits;
|
||
}
|
||
|
||
function isExpected(hit: Hit): boolean {
|
||
return hit.table === EXPECTED_CONFIG_TABLE && hit.column === EXPECTED_CONFIG_COLUMN;
|
||
}
|
||
|
||
async function main() {
|
||
const target = String(process.env.DATABASE_URL || '');
|
||
const host = target.replace(/:\/\/[^@]*@/, '://***@');
|
||
console.log(`[secret-scan] 目标:${host || '(未设置 DATABASE_URL)'}`);
|
||
console.log('[secret-scan] 只读扫描;不打印任何密钥内容\n');
|
||
|
||
const all: Hit[] = [];
|
||
for (const schema of await schemas()) {
|
||
all.push(...(await scanOperationLogs(schema)));
|
||
all.push(...(await scanAllTextColumns(schema)));
|
||
}
|
||
|
||
const unexpected = all.filter((h) => !isExpected(h));
|
||
const expected = all.filter(isExpected);
|
||
|
||
if (expected.length) {
|
||
console.log('预期内(LLM 配置本体,按设计存明文密钥,不算泄漏):');
|
||
for (const h of expected) console.log(` ${h.schema}.${h.table}.${h.column} → ${h.rows} 行`);
|
||
console.log('');
|
||
}
|
||
|
||
if (!unexpected.length) {
|
||
console.log('✅ 未发现异常密钥残留(operation_logs 与全部文本/JSON 列均为 0)');
|
||
await pool.end();
|
||
return;
|
||
}
|
||
|
||
console.error('❌ 发现异常密钥残留(这些位置不应出现密钥):');
|
||
for (const h of unexpected) console.error(` ${h.schema}.${h.table}.${h.column} → ${h.rows} 行`);
|
||
console.error('\n处置:先按 docs/design/20260924-audit-redaction-hardening.md §5 走脱敏迁移,再复查。');
|
||
await pool.end();
|
||
process.exit(1);
|
||
}
|
||
|
||
main().catch(async (error) => {
|
||
console.error('[secret-scan] 失败:', error instanceof Error ? error.message : error);
|
||
await pool.end().catch(() => undefined);
|
||
process.exit(2);
|
||
});
|