feat(P23IM2-1,P23IM2-2,P23IM2-3): 密钥加密持久化/遮罩读模型/企微可重试语义/迁移脚本

这个提交包含在:
2026-03-13 21:50:04 +08:00
父节点 a4c7268b33
当前提交 a8ec86016c
共修改 9 个文件,包含 1063 行新增和 40 行删除
+41 -2
查看文件
@@ -1,5 +1,7 @@
const crypto = require('node:crypto');
const { resolveChannelSecret } = require('../../notifications/channelConfig');
function toSafeString(value, maxLength = 2000) {
if (value == null) {
return '';
@@ -47,7 +49,31 @@ function buildSignedWebhookUrl(webhookUrl, secret) {
return `${rawUrl}${separator}timestamp=${timestamp}&sign=${sign}`;
}
async function sendWecomMessage({ channel, message }) {
function mapSecretError(result, previewMessage) {
if (result?.errorCode === 'secret_missing_field_encryption_key') {
return {
ok: false,
skipped: false,
retryable: false,
code: 'wecom_secret_missing_field_encryption_key',
message: result.errorMessage ?? 'Missing FIELD_ENCRYPTION_KEY for encrypted WeCom secret',
response: null,
previewMessage,
};
}
return {
ok: false,
skipped: false,
retryable: false,
code: 'wecom_secret_decrypt_failed',
message: result?.errorMessage ?? 'Failed to decrypt WeCom secret',
response: null,
previewMessage,
};
}
async function sendWecomMessage({ config, channel, message }) {
const configJson = channel?.config_json && typeof channel.config_json === 'object' ? channel.config_json : {};
const mode = String(configJson.mode ?? 'mock').trim() || 'mock';
const previewMessage = buildWecomMarkdownMessage(message);
@@ -56,7 +82,9 @@ async function sendWecomMessage({ channel, message }) {
return {
ok: true,
skipped: false,
retryable: false,
code: 'mock_sent',
message: null,
response: {
channelType: 'wecom',
mode,
@@ -90,12 +118,20 @@ async function sendWecomMessage({ channel, message }) {
};
}
const secretResult = resolveChannelSecret({
config,
configJson,
});
if (secretResult.configured && !secretResult.secret) {
return mapSecretError(secretResult, previewMessage);
}
const timeoutMs = Math.max(100, Number(configJson.timeoutMs ?? 5000));
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(buildSignedWebhookUrl(webhookUrl, configJson.secret ?? null), {
const response = await fetch(buildSignedWebhookUrl(webhookUrl, secretResult.secret), {
method: 'POST',
headers: {
'content-type': 'application/json',
@@ -146,7 +182,9 @@ async function sendWecomMessage({ channel, message }) {
return {
ok: true,
skipped: false,
retryable: false,
code: 'wecom_sent',
message: null,
response: responseBody,
previewMessage,
};
@@ -178,6 +216,7 @@ async function sendWecomMessage({ channel, message }) {
}
module.exports = {
buildSignedWebhookUrl,
buildWecomMarkdownMessage,
sendWecomMessage,
};
@@ -0,0 +1,164 @@
const {
decryptStringOrThrow,
encryptStringOrThrow,
resolveFieldEncryptionKey,
} = require('../crypto');
function asObject(value) {
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
}
function trimToNull(value, maxLength = 2000) {
const normalized = String(value ?? '').trim();
if (!normalized) {
return null;
}
return normalized.slice(0, maxLength);
}
function maskSecret(secret) {
const value = trimToNull(secret, 500);
if (!value) {
return null;
}
if (value.length <= 2) {
return '*'.repeat(value.length);
}
if (value.length <= 6) {
return `${value.slice(0, 1)}${'*'.repeat(value.length - 2)}${value.slice(-1)}`;
}
return `${value.slice(0, 2)}${'*'.repeat(Math.max(4, value.length - 4))}${value.slice(-2)}`;
}
function readStoredSecret(configJson) {
const normalized = asObject(configJson);
return {
secretEncrypted: trimToNull(normalized.secretEncrypted, 4000),
legacySecret: trimToNull(normalized.secret, 500),
};
}
function hasFieldEncryptionKey(config) {
return Boolean(resolveFieldEncryptionKey(config));
}
function resolveChannelSecret({ config, configJson, logger } = {}) {
const { secretEncrypted, legacySecret } = readStoredSecret(configJson);
if (secretEncrypted) {
if (!hasFieldEncryptionKey(config)) {
return {
configured: true,
secret: null,
source: 'encrypted',
errorCode: 'secret_missing_field_encryption_key',
errorMessage: 'Missing FIELD_ENCRYPTION_KEY for encrypted notification channel secret',
};
}
try {
const secret = decryptStringOrThrow(config, secretEncrypted);
if (!secret) {
return {
configured: true,
secret: null,
source: 'encrypted',
errorCode: 'secret_decrypt_failed',
errorMessage: 'Failed to decrypt notification channel secret',
};
}
return {
configured: true,
secret,
source: 'encrypted',
errorCode: null,
errorMessage: null,
};
} catch (error) {
logger?.warn?.({ err: error }, 'Notification channel secret decrypt failed');
const message = String(error?.message ?? 'Failed to decrypt notification channel secret');
return {
configured: true,
secret: null,
source: 'encrypted',
errorCode: message.includes('FIELD_ENCRYPTION_KEY')
? 'secret_missing_field_encryption_key'
: 'secret_decrypt_failed',
errorMessage: message,
};
}
}
if (legacySecret) {
return {
configured: true,
secret: legacySecret,
source: 'legacy',
errorCode: null,
errorMessage: null,
};
}
return {
configured: false,
secret: null,
source: null,
errorCode: null,
errorMessage: null,
};
}
function getChannelSecretReadModel({ config, configJson, logger } = {}) {
const resolved = resolveChannelSecret({ config, configJson, logger });
return {
secretConfigured: resolved.configured,
secretMasked: resolved.secret ? maskSecret(resolved.secret) : resolved.configured ? '******' : null,
};
}
function buildStoredSecretFields({ config, existingConfig, inputSecret, clearSecret = false } = {}) {
if (clearSecret) {
return {};
}
const nextSecret = trimToNull(inputSecret, 500);
if (nextSecret) {
return {
secretEncrypted: encryptStringOrThrow(config, nextSecret),
};
}
const { secretEncrypted, legacySecret } = readStoredSecret(existingConfig);
if (secretEncrypted) {
return {
secretEncrypted,
};
}
if (legacySecret) {
if (hasFieldEncryptionKey(config)) {
return {
secretEncrypted: encryptStringOrThrow(config, legacySecret),
};
}
return {
secret: legacySecret,
};
}
return {};
}
module.exports = {
buildStoredSecretFields,
getChannelSecretReadModel,
hasFieldEncryptionKey,
maskSecret,
readStoredSecret,
resolveChannelSecret,
};
@@ -46,7 +46,9 @@ async function sendInstantMessageByChannel({ config, channel, payload }) {
return {
ok: true,
skipped: true,
retryable: false,
code: 'im_notifier_disabled',
message: 'IM notifier disabled',
response: { channelType: normalizedChannelType || null },
previewMessage: null,
};
@@ -56,7 +58,9 @@ async function sendInstantMessageByChannel({ config, channel, payload }) {
return {
ok: true,
skipped: true,
retryable: false,
code: 'channel_not_found',
message: 'Notification channel not found',
response: { channelType: normalizedChannelType || null },
previewMessage: null,
};
@@ -66,7 +70,9 @@ async function sendInstantMessageByChannel({ config, channel, payload }) {
return {
ok: true,
skipped: true,
retryable: false,
code: 'channel_disabled',
message: 'Notification channel disabled',
response: { channelType: normalizedChannelType || null },
previewMessage: null,
};
@@ -76,14 +82,16 @@ async function sendInstantMessageByChannel({ config, channel, payload }) {
return {
ok: true,
skipped: true,
retryable: false,
code: 'unsupported_channel_type',
message: 'Unsupported notification channel type',
response: { channelType: normalizedChannelType || null },
previewMessage: null,
};
}
const message = buildNotificationMessage(channel, payload);
return sendWecomMessage({ channel, message });
return sendWecomMessage({ config, channel, message });
}
module.exports = {