24 lines
1.4 KiB
JavaScript
24 lines
1.4 KiB
JavaScript
const credentialText = /\b(?:authorization|(?:set[-_ ]?)?cookie|x[-_ ]?api[-_ ]?key|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|password|secret[-_ ]?key)["']?\s*[:=]\s*[^\r\n]+|\bbearer[ \t]+[a-z0-9._~+/=-]{4,}|\b(?:sk-(?:proj-)?|dcs_|dca_)[a-z0-9_-]{16,}/gi;
|
|
const credentialKeys = new Set(['authorization', 'cookie', 'setcookie', 'apikey', 'xapikey',
|
|
'accesstoken', 'refreshtoken', 'password', 'secretkey', 'credentials', 'privatekey', 'token', 'composerdrafttoken']);
|
|
|
|
export const redactText = text => text.replace(credentialText, '[已脱敏]');
|
|
|
|
export function redact(value) {
|
|
if (typeof value === 'string') return redactText(value);
|
|
if (Array.isArray(value)) return value.map(redact);
|
|
if (!value || typeof value !== 'object') return value;
|
|
return Object.fromEntries(Object.entries(value)
|
|
.filter(([key, item]) => !credentialKeys.has(key.toLowerCase().replace(/[-_ ]/g, '')) && redactText(key) === key
|
|
&& !(key.toLowerCase() === 'key' && typeof item === 'string' && item.startsWith('sk-')))
|
|
.map(([key, item]) => [key, redact(item)]));
|
|
}
|
|
|
|
export function protectSession(manager) {
|
|
for (const name of ['appendMessage', 'appendCompaction', 'branchWithSummary', 'appendCustomEntry', 'appendCustomMessageEntry']) {
|
|
const append = manager[name].bind(manager);
|
|
manager[name] = (...args) => append(...args.map(redact));
|
|
}
|
|
return manager;
|
|
}
|