opencode-windows-scheduler 1.3.0 → 1.4.0
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/CHANGELOG.md +23 -1
- package/README.md +9 -3
- package/ROADMAP-STRATEGY.md +11 -11
- package/ROADMAP.md +2 -7
- package/dist/core/audit.d.ts +68 -0
- package/dist/core/audit.d.ts.map +1 -0
- package/dist/core/audit.js +206 -0
- package/dist/core/secrets.d.ts +57 -0
- package/dist/core/secrets.d.ts.map +1 -0
- package/dist/core/secrets.js +331 -0
- package/dist/core/structured-log.d.ts.map +1 -1
- package/dist/core/structured-log.js +9 -0
- package/dist/db/schema.d.ts +1 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +15 -0
- package/dist/index.d.ts +24 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +342 -19
- package/dist/rpc.d.ts +400 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +146 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +67 -0
- package/dist/settings.d.ts +16 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +29 -0
- package/dist/workspaces.d.ts +8 -2
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +21 -4
- package/docs/ARCHITECTURE.md +13 -5
- package/docs/FEATURES.md +29 -1
- package/docs/README.ru.md +13 -3
- package/gui-experimental.cjs +4 -4
- package/package.json +4 -2
- package/src/core/audit.ts +291 -0
- package/src/core/secrets.ts +385 -0
- package/src/core/structured-log.ts +9 -0
- package/src/db/schema.ts +15 -0
- package/src/gui.tsx +323 -0
- package/src/index.ts +452 -19
- package/src/rpc.ts +157 -0
- package/src/server.ts +67 -0
- package/src/settings.ts +51 -0
- package/src/workspaces.ts +22 -4
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-windows-scheduler",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "OpenCode v2 plugin for scheduling and orchestrating AI agent jobs: cron, one-shot runs, DAG pipelines, matrix builds, quality gates, SQLite history, metrics and a local web dashboard. Windows, macOS and Linux. Free and open source (MIT).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "opencode-windows-scheduler contributors",
|
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
"demo": "node scripts/demo-dashboard.mjs",
|
|
70
70
|
"prepare": "npm run build",
|
|
71
71
|
"prepublishOnly": "npm run build && npm run build:gui",
|
|
72
|
-
"test": "node test-sqlite.mjs && node test-crash-recovery.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-schedule-v2.mjs && node test-notifications-v2.mjs && node test-notifications-v3.mjs && node test-profiles.mjs && node test-env.mjs && node test-agent-tools.mjs && node test-skill.mjs && node test-integrations.mjs && node test-one-shot.mjs && node test-session-continuity.mjs && node test-task-status.mjs && node test-jobs-view.mjs && node test-dag.mjs && node test-dashboard.mjs && node test-dashboard-dag.mjs && node test-dashboard-json.mjs && node test-docs.mjs",
|
|
72
|
+
"test": "node test-sqlite.mjs && node test-crash-recovery.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-schedule-v2.mjs && node test-notifications-v2.mjs && node test-notifications-v3.mjs && node test-secrets.mjs && node test-audit.mjs && node test-profiles.mjs && node test-env.mjs && node test-agent-tools.mjs && node test-skill.mjs && node test-integrations.mjs && node test-one-shot.mjs && node test-session-continuity.mjs && node test-task-status.mjs && node test-jobs-view.mjs && node test-dag.mjs && node test-dashboard.mjs && node test-dashboard-dag.mjs && node test-dashboard-json.mjs && node test-docs.mjs",
|
|
73
73
|
"test:sqlite": "node test-sqlite.mjs",
|
|
74
74
|
"test:crash": "node test-crash-recovery.mjs",
|
|
75
75
|
"test:workspaces": "node test-workspaces.mjs",
|
|
@@ -83,6 +83,8 @@
|
|
|
83
83
|
"test:schedule-v2": "node test-schedule-v2.mjs",
|
|
84
84
|
"test:notifications-v2": "node test-notifications-v2.mjs",
|
|
85
85
|
"test:notifications-v3": "node test-notifications-v3.mjs",
|
|
86
|
+
"test:secrets": "node test-secrets.mjs",
|
|
87
|
+
"test:audit": "node test-audit.mjs",
|
|
86
88
|
"test:profiles": "node test-profiles.mjs",
|
|
87
89
|
"test:env": "node test-env.mjs",
|
|
88
90
|
"test:agent": "node test-agent-tools.mjs",
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import { getDb } from "../db/index.js";
|
|
2
|
+
import { redactSecretsInText } from "./secrets.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Журнал аудита мутаций (Спринт 26).
|
|
6
|
+
*
|
|
7
|
+
* Фиксирует кто, когда и через какой интерфейс создал / изменил / запустил /
|
|
8
|
+
* удалил задачу или настройки. Записи лежат в SQLite рядом с историей, поэтому
|
|
9
|
+
* аудит не зависит от файловых логов и переживает перезапуск. Любая ошибка
|
|
10
|
+
* записи проглатывается: аудит не должен ломать основную операцию.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export type AuditActor = "mcp" | "gui" | "http" | "system" | string;
|
|
14
|
+
|
|
15
|
+
export interface AuditEntryInput {
|
|
16
|
+
action: string;
|
|
17
|
+
targetType?: string | null;
|
|
18
|
+
target?: string | null;
|
|
19
|
+
actor: AuditActor;
|
|
20
|
+
/** Конкретный инструмент / RPC-метод / HTTP-маршрут. */
|
|
21
|
+
source?: string | null;
|
|
22
|
+
details?: unknown;
|
|
23
|
+
remote?: string | null;
|
|
24
|
+
/** Время события (ISO). По умолчанию — сейчас. */
|
|
25
|
+
ts?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface AuditRecord {
|
|
29
|
+
id: number;
|
|
30
|
+
ts: string;
|
|
31
|
+
action: string;
|
|
32
|
+
targetType: string | null;
|
|
33
|
+
target: string | null;
|
|
34
|
+
actor: string;
|
|
35
|
+
source: string | null;
|
|
36
|
+
details: unknown;
|
|
37
|
+
remote: string | null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface ReadAuditFilter {
|
|
41
|
+
action?: string;
|
|
42
|
+
target?: string;
|
|
43
|
+
actor?: string;
|
|
44
|
+
since?: string;
|
|
45
|
+
until?: string;
|
|
46
|
+
limit?: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface ReadAuditResult {
|
|
50
|
+
records: AuditRecord[];
|
|
51
|
+
total: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export const DEFAULT_AUDIT_RETENTION_DAYS = 90;
|
|
55
|
+
export const DEFAULT_AUDIT_MAX_RECORDS = 10_000;
|
|
56
|
+
|
|
57
|
+
const SENSITIVE_KEY_RE = /(TOKEN|SECRET|PASS|PASSWORD|PASSWD|API_?KEY|CREDENTIAL|AUTH)/i;
|
|
58
|
+
const PURE_SECRET_REF_RE = /^\$\{secret:[A-Za-z0-9_.-]{1,64}\}$/;
|
|
59
|
+
|
|
60
|
+
function looksLikeSecretRef(value: string): boolean {
|
|
61
|
+
return PURE_SECRET_REF_RE.test(value.trim());
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Рекурсивно вычищает секреты из произвольной структуры details. */
|
|
65
|
+
export function redactAuditDetails(value: unknown, depth = 0): unknown {
|
|
66
|
+
if (depth > 8) return "[truncated]";
|
|
67
|
+
if (typeof value === "string") return redactSecretsInText(value);
|
|
68
|
+
if (value == null || typeof value !== "object") return value;
|
|
69
|
+
if (Array.isArray(value)) {
|
|
70
|
+
return value.slice(0, 200).map((item) => redactAuditDetails(item, depth + 1));
|
|
71
|
+
}
|
|
72
|
+
const result: Record<string, unknown> = {};
|
|
73
|
+
for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
|
|
74
|
+
if (
|
|
75
|
+
typeof item === "string" &&
|
|
76
|
+
SENSITIVE_KEY_RE.test(key) &&
|
|
77
|
+
!looksLikeSecretRef(item)
|
|
78
|
+
) {
|
|
79
|
+
result[key] = "***";
|
|
80
|
+
} else {
|
|
81
|
+
result[key] = redactAuditDetails(item, depth + 1);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return result;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function safeJson(value: unknown): string | null {
|
|
88
|
+
if (value === undefined || value === null) return null;
|
|
89
|
+
try {
|
|
90
|
+
return JSON.stringify(redactAuditDetails(value));
|
|
91
|
+
} catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
let lastCleanupAt = 0;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Записывает событие аудита. Никогда не бросает исключение.
|
|
100
|
+
* Возвращает id записи или null при ошибке.
|
|
101
|
+
*/
|
|
102
|
+
export function recordAudit(entry: AuditEntryInput): number | null {
|
|
103
|
+
try {
|
|
104
|
+
const ts = entry.ts ?? new Date().toISOString();
|
|
105
|
+
const result = getDb()
|
|
106
|
+
.prepare(
|
|
107
|
+
`INSERT INTO audit_log
|
|
108
|
+
(ts, action, target_type, target, actor, source, details_json, remote)
|
|
109
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
|
110
|
+
)
|
|
111
|
+
.run(
|
|
112
|
+
ts,
|
|
113
|
+
String(entry.action || "unknown").slice(0, 128),
|
|
114
|
+
entry.targetType == null ? null : String(entry.targetType).slice(0, 64),
|
|
115
|
+
entry.target == null ? null : String(entry.target).slice(0, 256),
|
|
116
|
+
String(entry.actor || "system").slice(0, 32),
|
|
117
|
+
entry.source == null ? null : String(entry.source).slice(0, 128),
|
|
118
|
+
safeJson(entry.details),
|
|
119
|
+
entry.remote == null ? null : String(entry.remote).slice(0, 128)
|
|
120
|
+
);
|
|
121
|
+
maybeCleanup();
|
|
122
|
+
return Number(result.lastInsertRowid) || null;
|
|
123
|
+
} catch (err) {
|
|
124
|
+
try {
|
|
125
|
+
console.warn(
|
|
126
|
+
`[audit] не удалось записать событие: ${
|
|
127
|
+
err instanceof Error ? err.message : String(err)
|
|
128
|
+
}`
|
|
129
|
+
);
|
|
130
|
+
} catch {
|
|
131
|
+
// console недоступен — молча игнорируем.
|
|
132
|
+
}
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Ленивая ротация: не чаще раза в час, лимиты по умолчанию. Точные лимиты из
|
|
139
|
+
* settings применяются в cleanupHistory / manage_settings.
|
|
140
|
+
*/
|
|
141
|
+
function maybeCleanup(): void {
|
|
142
|
+
const now = Date.now();
|
|
143
|
+
if (now - lastCleanupAt < 60 * 60 * 1000) return;
|
|
144
|
+
lastCleanupAt = now;
|
|
145
|
+
try {
|
|
146
|
+
cleanupAuditLog({
|
|
147
|
+
retentionDays: DEFAULT_AUDIT_RETENTION_DAYS,
|
|
148
|
+
maxRecords: DEFAULT_AUDIT_MAX_RECORDS,
|
|
149
|
+
});
|
|
150
|
+
} catch {
|
|
151
|
+
// очистка не критична
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function rowToRecord(row: any): AuditRecord {
|
|
156
|
+
let details: unknown = null;
|
|
157
|
+
if (row.details_json) {
|
|
158
|
+
try {
|
|
159
|
+
details = JSON.parse(String(row.details_json));
|
|
160
|
+
} catch {
|
|
161
|
+
details = String(row.details_json);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
id: Number(row.id),
|
|
166
|
+
ts: String(row.ts),
|
|
167
|
+
action: String(row.action),
|
|
168
|
+
targetType: row.target_type == null ? null : String(row.target_type),
|
|
169
|
+
target: row.target == null ? null : String(row.target),
|
|
170
|
+
actor: String(row.actor ?? "system"),
|
|
171
|
+
source: row.source == null ? null : String(row.source),
|
|
172
|
+
details,
|
|
173
|
+
remote: row.remote == null ? null : String(row.remote),
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Читает журнал аудита (новые сверху). */
|
|
178
|
+
export function readAuditLog(filter: ReadAuditFilter = {}): ReadAuditResult {
|
|
179
|
+
const limit = Math.max(1, Math.min(5000, Math.floor(filter.limit ?? 200) || 200));
|
|
180
|
+
const where: string[] = [];
|
|
181
|
+
const params: unknown[] = [];
|
|
182
|
+
if (filter.action?.trim()) {
|
|
183
|
+
where.push("action = ?");
|
|
184
|
+
params.push(filter.action.trim());
|
|
185
|
+
}
|
|
186
|
+
if (filter.target?.trim()) {
|
|
187
|
+
where.push("target = ?");
|
|
188
|
+
params.push(filter.target.trim());
|
|
189
|
+
}
|
|
190
|
+
if (filter.actor?.trim()) {
|
|
191
|
+
where.push("actor = ?");
|
|
192
|
+
params.push(filter.actor.trim());
|
|
193
|
+
}
|
|
194
|
+
if (filter.since?.trim()) {
|
|
195
|
+
where.push("ts >= ?");
|
|
196
|
+
params.push(filter.since.trim());
|
|
197
|
+
}
|
|
198
|
+
if (filter.until?.trim()) {
|
|
199
|
+
where.push("ts <= ?");
|
|
200
|
+
params.push(filter.until.trim());
|
|
201
|
+
}
|
|
202
|
+
const clause = where.length ? `WHERE ${where.join(" AND ")}` : "";
|
|
203
|
+
try {
|
|
204
|
+
const db = getDb();
|
|
205
|
+
const totalRow = db
|
|
206
|
+
.prepare(`SELECT COUNT(*) AS count FROM audit_log ${clause}`)
|
|
207
|
+
.get(...params) as any;
|
|
208
|
+
const rows = db
|
|
209
|
+
.prepare(`SELECT * FROM audit_log ${clause} ORDER BY ts DESC, id DESC LIMIT ?`)
|
|
210
|
+
.all(...params, limit) as any[];
|
|
211
|
+
return { records: rows.map(rowToRecord), total: Number(totalRow?.count) || 0 };
|
|
212
|
+
} catch (err) {
|
|
213
|
+
try {
|
|
214
|
+
console.warn(
|
|
215
|
+
`[audit] не удалось прочитать журнал: ${
|
|
216
|
+
err instanceof Error ? err.message : String(err)
|
|
217
|
+
}`
|
|
218
|
+
);
|
|
219
|
+
} catch {
|
|
220
|
+
// ignore
|
|
221
|
+
}
|
|
222
|
+
return { records: [], total: 0 };
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Удаляет старые записи и лишние сверх maxRecords.
|
|
228
|
+
* Возвращает количество удалённых строк.
|
|
229
|
+
*/
|
|
230
|
+
export function cleanupAuditLog(options: {
|
|
231
|
+
retentionDays?: number;
|
|
232
|
+
maxRecords?: number;
|
|
233
|
+
} = {}): number {
|
|
234
|
+
const retentionDays = Math.max(
|
|
235
|
+
0,
|
|
236
|
+
Math.floor(options.retentionDays ?? DEFAULT_AUDIT_RETENTION_DAYS) || 0
|
|
237
|
+
);
|
|
238
|
+
const maxRecords = Math.max(
|
|
239
|
+
100,
|
|
240
|
+
Math.floor(options.maxRecords ?? DEFAULT_AUDIT_MAX_RECORDS) || DEFAULT_AUDIT_MAX_RECORDS
|
|
241
|
+
);
|
|
242
|
+
let deleted = 0;
|
|
243
|
+
try {
|
|
244
|
+
const db = getDb();
|
|
245
|
+
if (retentionDays > 0) {
|
|
246
|
+
const cutoff = new Date(
|
|
247
|
+
Date.now() - retentionDays * 24 * 60 * 60 * 1000
|
|
248
|
+
).toISOString();
|
|
249
|
+
const result = db.prepare("DELETE FROM audit_log WHERE ts < ?").run(cutoff);
|
|
250
|
+
deleted += Number(result.changes) || 0;
|
|
251
|
+
}
|
|
252
|
+
const countRow = db.prepare("SELECT COUNT(*) AS count FROM audit_log").get() as any;
|
|
253
|
+
const count = Number(countRow?.count) || 0;
|
|
254
|
+
if (count > maxRecords) {
|
|
255
|
+
const excess = count - maxRecords;
|
|
256
|
+
const result = db
|
|
257
|
+
.prepare(
|
|
258
|
+
`DELETE FROM audit_log WHERE id IN (
|
|
259
|
+
SELECT id FROM audit_log ORDER BY ts ASC, id ASC LIMIT ?
|
|
260
|
+
)`
|
|
261
|
+
)
|
|
262
|
+
.run(excess);
|
|
263
|
+
deleted += Number(result.changes) || 0;
|
|
264
|
+
}
|
|
265
|
+
} catch (err) {
|
|
266
|
+
try {
|
|
267
|
+
console.warn(
|
|
268
|
+
`[audit] не удалось очистить журнал: ${
|
|
269
|
+
err instanceof Error ? err.message : String(err)
|
|
270
|
+
}`
|
|
271
|
+
);
|
|
272
|
+
} catch {
|
|
273
|
+
// ignore
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return deleted;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Удаляет все записи (тесты / обслуживание). */
|
|
280
|
+
export function clearAuditLog(): void {
|
|
281
|
+
try {
|
|
282
|
+
getDb().exec("DELETE FROM audit_log");
|
|
283
|
+
} catch {
|
|
284
|
+
// ignore
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Сбрасывает троттлинг очистки (для тестов). */
|
|
289
|
+
export function resetAuditCleanupThrottle(): void {
|
|
290
|
+
lastCleanupAt = 0;
|
|
291
|
+
}
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { PLUGIN_DIR } from "../types.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Зашифрованное хранилище секретов (Спринт 26).
|
|
8
|
+
*
|
|
9
|
+
* Зависимостей нет: ключ 32 байта лежит в `secrets.key` (права 0600), сами
|
|
10
|
+
* значения — в `secrets.json`, зашифрованные AES-256-GCM. Имя секрета
|
|
11
|
+
* используется как AAD, поэтому перестановка записей между именами ломает
|
|
12
|
+
* расшифровку. В открытом виде секреты не попадают ни в settings.json, ни в
|
|
13
|
+
* tasks.json, ни в историю, ни в логи — для этого есть resolveSecretRefs()
|
|
14
|
+
* и redactSecretsInText().
|
|
15
|
+
*
|
|
16
|
+
* Ссылка на секрет в env выглядит как `${secret:NAME}`. Ссылка может быть
|
|
17
|
+
* частью значения: `Authorization=Bearer ${secret:GITHUB_TOKEN}`.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export const SECRETS_FILE = path.join(PLUGIN_DIR, "secrets.json");
|
|
21
|
+
export const SECRETS_KEY_FILE = path.join(PLUGIN_DIR, "secrets.key");
|
|
22
|
+
export const SECRET_REF_RE = /\$\{secret:([A-Za-z0-9_.-]{1,64})\}/g;
|
|
23
|
+
const SECRET_NAME_RE = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
24
|
+
const KEY_BYTES = 32;
|
|
25
|
+
|
|
26
|
+
interface StoredSecret {
|
|
27
|
+
/** IV в base64 (12 байт). */
|
|
28
|
+
iv: string;
|
|
29
|
+
/** Auth tag в base64 (16 байт). */
|
|
30
|
+
tag: string;
|
|
31
|
+
/** Шифротекст в base64. */
|
|
32
|
+
data: string;
|
|
33
|
+
updatedAt: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface SecretsFile {
|
|
37
|
+
version: 1;
|
|
38
|
+
secrets: Record<string, StoredSecret>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface SecretListItem {
|
|
42
|
+
name: string;
|
|
43
|
+
/** Маска вида `••••ABCD` — само значение никогда не возвращается. */
|
|
44
|
+
preview: string;
|
|
45
|
+
updatedAt: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface CacheEntry {
|
|
49
|
+
stamp: string;
|
|
50
|
+
file: SecretsFile;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
let cache: CacheEntry | null = null;
|
|
54
|
+
let keyCache: { stamp: string; key: Buffer } | null = null;
|
|
55
|
+
|
|
56
|
+
function warn(message: string, err: unknown): void {
|
|
57
|
+
try {
|
|
58
|
+
console.warn(
|
|
59
|
+
`[secrets] ${message}: ${err instanceof Error ? err.message : String(err)}`
|
|
60
|
+
);
|
|
61
|
+
} catch {
|
|
62
|
+
// console может быть недоступен — молча игнорируем.
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Проверяет имя секрета; возвращает trimmed-значение. */
|
|
67
|
+
export function validateSecretName(name: string): string {
|
|
68
|
+
const value = String(name ?? "").trim();
|
|
69
|
+
if (!SECRET_NAME_RE.test(value)) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
"Имя секрета: латиница, цифры, '_', '.', '-', от 1 до 64 символов."
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
return value;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** true, если значение содержит хотя бы одну ссылку `${secret:...}`. */
|
|
78
|
+
export function hasSecretRef(value: unknown): boolean {
|
|
79
|
+
if (typeof value !== "string") return false;
|
|
80
|
+
SECRET_REF_RE.lastIndex = 0;
|
|
81
|
+
return SECRET_REF_RE.test(value);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function ensureDir(): void {
|
|
85
|
+
fs.mkdirSync(PLUGIN_DIR, { recursive: true });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function chmodPrivate(file: string): void {
|
|
89
|
+
if (process.platform === "win32") return;
|
|
90
|
+
try {
|
|
91
|
+
fs.chmodSync(file, 0o600);
|
|
92
|
+
} catch {
|
|
93
|
+
// ACL на некоторых ФС не поддерживают chmod — не критично.
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Читает или создаёт ключ шифрования. */
|
|
98
|
+
function loadKey(): Buffer {
|
|
99
|
+
ensureDir();
|
|
100
|
+
try {
|
|
101
|
+
const stat = fs.statSync(SECRETS_KEY_FILE);
|
|
102
|
+
const stamp = `${stat.mtimeMs}:${stat.size}`;
|
|
103
|
+
if (keyCache && keyCache.stamp === stamp) return keyCache.key;
|
|
104
|
+
const raw = fs.readFileSync(SECRETS_KEY_FILE);
|
|
105
|
+
if (raw.length !== KEY_BYTES) {
|
|
106
|
+
throw new Error("повреждён файл ключа секретов");
|
|
107
|
+
}
|
|
108
|
+
keyCache = { stamp, key: raw };
|
|
109
|
+
return raw;
|
|
110
|
+
} catch (err: any) {
|
|
111
|
+
if (err?.code !== "ENOENT") throw err;
|
|
112
|
+
const key = crypto.randomBytes(KEY_BYTES);
|
|
113
|
+
fs.writeFileSync(SECRETS_KEY_FILE, key, { mode: 0o600 });
|
|
114
|
+
chmodPrivate(SECRETS_KEY_FILE);
|
|
115
|
+
keyCache = { stamp: `${fs.statSync(SECRETS_KEY_FILE).mtimeMs}:${KEY_BYTES}`, key };
|
|
116
|
+
return key;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function emptyFile(): SecretsFile {
|
|
121
|
+
return { version: 1, secrets: {} };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Читает secrets.json с кэшем по mtime/size. Битый файл — пустое хранилище. */
|
|
125
|
+
function readFileSafe(): SecretsFile {
|
|
126
|
+
try {
|
|
127
|
+
const stat = fs.statSync(SECRETS_FILE);
|
|
128
|
+
const stamp = `${stat.mtimeMs}:${stat.size}`;
|
|
129
|
+
if (cache && cache.stamp === stamp) return cache.file;
|
|
130
|
+
const parsed = JSON.parse(fs.readFileSync(SECRETS_FILE, "utf8"));
|
|
131
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
132
|
+
throw new Error("некорректный формат secrets.json");
|
|
133
|
+
}
|
|
134
|
+
const rawSecrets = (parsed as any).secrets;
|
|
135
|
+
const secrets: Record<string, StoredSecret> = {};
|
|
136
|
+
if (rawSecrets && typeof rawSecrets === "object" && !Array.isArray(rawSecrets)) {
|
|
137
|
+
for (const [name, entry] of Object.entries(rawSecrets)) {
|
|
138
|
+
const record = entry as Partial<StoredSecret>;
|
|
139
|
+
if (
|
|
140
|
+
SECRET_NAME_RE.test(name) &&
|
|
141
|
+
typeof record?.iv === "string" &&
|
|
142
|
+
typeof record?.tag === "string" &&
|
|
143
|
+
typeof record?.data === "string"
|
|
144
|
+
) {
|
|
145
|
+
secrets[name] = {
|
|
146
|
+
iv: record.iv,
|
|
147
|
+
tag: record.tag,
|
|
148
|
+
data: record.data,
|
|
149
|
+
updatedAt:
|
|
150
|
+
typeof record.updatedAt === "string"
|
|
151
|
+
? record.updatedAt
|
|
152
|
+
: new Date(0).toISOString(),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const file: SecretsFile = { version: 1, secrets };
|
|
158
|
+
cache = { stamp, file };
|
|
159
|
+
return file;
|
|
160
|
+
} catch (err: any) {
|
|
161
|
+
if (err?.code !== "ENOENT") warn("не удалось прочитать secrets.json", err);
|
|
162
|
+
return emptyFile();
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Атомарная запись: temp + rename, права 0600. */
|
|
167
|
+
function writeFileSafe(file: SecretsFile): void {
|
|
168
|
+
ensureDir();
|
|
169
|
+
const tmp = `${SECRETS_FILE}.tmp`;
|
|
170
|
+
fs.writeFileSync(tmp, JSON.stringify(file, null, 2), { encoding: "utf8", mode: 0o600 });
|
|
171
|
+
try {
|
|
172
|
+
fs.rmSync(SECRETS_FILE, { force: true });
|
|
173
|
+
} catch {
|
|
174
|
+
// файла нет — не ошибка
|
|
175
|
+
}
|
|
176
|
+
fs.renameSync(tmp, SECRETS_FILE);
|
|
177
|
+
chmodPrivate(SECRETS_FILE);
|
|
178
|
+
try {
|
|
179
|
+
const stat = fs.statSync(SECRETS_FILE);
|
|
180
|
+
cache = { stamp: `${stat.mtimeMs}:${stat.size}`, file };
|
|
181
|
+
} catch {
|
|
182
|
+
cache = null;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function encryptValue(name: string, value: string, key: Buffer): StoredSecret {
|
|
187
|
+
const iv = crypto.randomBytes(12);
|
|
188
|
+
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
|
|
189
|
+
cipher.setAAD(Buffer.from(name, "utf8"));
|
|
190
|
+
const data = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
|
|
191
|
+
return {
|
|
192
|
+
iv: iv.toString("base64"),
|
|
193
|
+
tag: cipher.getAuthTag().toString("base64"),
|
|
194
|
+
data: data.toString("base64"),
|
|
195
|
+
updatedAt: new Date().toISOString(),
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function decryptValue(name: string, entry: StoredSecret, key: Buffer): string {
|
|
200
|
+
const decipher = crypto.createDecipheriv(
|
|
201
|
+
"aes-256-gcm",
|
|
202
|
+
key,
|
|
203
|
+
Buffer.from(entry.iv, "base64")
|
|
204
|
+
);
|
|
205
|
+
decipher.setAAD(Buffer.from(name, "utf8"));
|
|
206
|
+
decipher.setAuthTag(Buffer.from(entry.tag, "base64"));
|
|
207
|
+
return Buffer.concat([
|
|
208
|
+
decipher.update(Buffer.from(entry.data, "base64")),
|
|
209
|
+
decipher.final(),
|
|
210
|
+
]).toString("utf8");
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Сохраняет (или перезаписывает) секрет. Значение не логируется. */
|
|
214
|
+
export function setSecret(name: string, value: string): SecretListItem {
|
|
215
|
+
const secretName = validateSecretName(name);
|
|
216
|
+
const text = String(value ?? "");
|
|
217
|
+
const key = loadKey();
|
|
218
|
+
const file = readFileSafe();
|
|
219
|
+
file.secrets[secretName] = encryptValue(secretName, text, key);
|
|
220
|
+
writeFileSafe(file);
|
|
221
|
+
return {
|
|
222
|
+
name: secretName,
|
|
223
|
+
preview: previewOf(text),
|
|
224
|
+
updatedAt: file.secrets[secretName].updatedAt,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Читает секрет; undefined, если его нет или он не расшифровывается. */
|
|
229
|
+
export function getSecret(name: string): string | undefined {
|
|
230
|
+
try {
|
|
231
|
+
const secretName = validateSecretName(name);
|
|
232
|
+
const file = readFileSafe();
|
|
233
|
+
const entry = file.secrets[secretName];
|
|
234
|
+
if (!entry) return undefined;
|
|
235
|
+
return decryptValue(secretName, entry, loadKey());
|
|
236
|
+
} catch (err) {
|
|
237
|
+
warn("не удалось расшифровать секрет", err);
|
|
238
|
+
return undefined;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** true, если секрет существует и расшифровывается. */
|
|
243
|
+
export function hasSecret(name: string): boolean {
|
|
244
|
+
return getSecret(name) !== undefined;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Удаляет секрет; true — запись была. */
|
|
248
|
+
export function deleteSecret(name: string): boolean {
|
|
249
|
+
const secretName = validateSecretName(name);
|
|
250
|
+
const file = readFileSafe();
|
|
251
|
+
if (!(secretName in file.secrets)) return false;
|
|
252
|
+
delete file.secrets[secretName];
|
|
253
|
+
writeFileSafe(file);
|
|
254
|
+
return true;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function previewOf(value: string): string {
|
|
258
|
+
const text = String(value ?? "");
|
|
259
|
+
if (!text) return "••••";
|
|
260
|
+
const tail = text.length >= 4 ? text.slice(-4) : "";
|
|
261
|
+
return tail ? `••••${tail}` : "••••";
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Список секретов без значений (только имена, маски и время обновления). */
|
|
265
|
+
export function listSecrets(): SecretListItem[] {
|
|
266
|
+
const file = readFileSafe();
|
|
267
|
+
return Object.keys(file.secrets)
|
|
268
|
+
.sort((a, b) => a.localeCompare(b))
|
|
269
|
+
.map((name) => {
|
|
270
|
+
let preview = "••••";
|
|
271
|
+
try {
|
|
272
|
+
const value = decryptValue(name, file.secrets[name], loadKey());
|
|
273
|
+
preview = previewOf(value);
|
|
274
|
+
} catch {
|
|
275
|
+
preview = "••••";
|
|
276
|
+
}
|
|
277
|
+
return { name, preview, updatedAt: file.secrets[name].updatedAt };
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Подставляет все ссылки `${secret:NAME}` в строку. */
|
|
282
|
+
export function expandSecretRefs(value: string): {
|
|
283
|
+
value: string;
|
|
284
|
+
missing: string[];
|
|
285
|
+
} {
|
|
286
|
+
const missing = new Set<string>();
|
|
287
|
+
const result = String(value ?? "").replace(SECRET_REF_RE, (_match, name: string) => {
|
|
288
|
+
const secret = getSecret(name);
|
|
289
|
+
if (secret === undefined) {
|
|
290
|
+
missing.add(name);
|
|
291
|
+
return "";
|
|
292
|
+
}
|
|
293
|
+
return secret;
|
|
294
|
+
});
|
|
295
|
+
return { value: result, missing: [...missing] };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Разворачивает ссылки во всех значениях env. Отсутствующие секреты дают
|
|
300
|
+
* пустую строку и попадают в `missing` (только имена — без значений).
|
|
301
|
+
*/
|
|
302
|
+
export function resolveSecretRefs(env: Record<string, string>): {
|
|
303
|
+
env: Record<string, string>;
|
|
304
|
+
missing: string[];
|
|
305
|
+
} {
|
|
306
|
+
const resolved: Record<string, string> = {};
|
|
307
|
+
const missing = new Set<string>();
|
|
308
|
+
for (const [key, value] of Object.entries(env ?? {})) {
|
|
309
|
+
const result = expandSecretRefs(String(value ?? ""));
|
|
310
|
+
resolved[key] = result.value;
|
|
311
|
+
for (const name of result.missing) missing.add(name);
|
|
312
|
+
}
|
|
313
|
+
return { env: resolved, missing: [...missing] };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Все расшифрованные значения (для редактирования текста). Кэш на 5 секунд. */
|
|
317
|
+
let valuesCache: { at: number; values: string[] } | null = null;
|
|
318
|
+
|
|
319
|
+
function knownSecretValues(): string[] {
|
|
320
|
+
const now = Date.now();
|
|
321
|
+
if (valuesCache && now - valuesCache.at < 5_000) return valuesCache.values;
|
|
322
|
+
const file = readFileSafe();
|
|
323
|
+
const values: string[] = [];
|
|
324
|
+
let key: Buffer;
|
|
325
|
+
try {
|
|
326
|
+
key = loadKey();
|
|
327
|
+
} catch {
|
|
328
|
+
return [];
|
|
329
|
+
}
|
|
330
|
+
for (const [name, entry] of Object.entries(file.secrets)) {
|
|
331
|
+
try {
|
|
332
|
+
const value = decryptValue(name, entry, key);
|
|
333
|
+
if (value.length >= 4) values.push(value);
|
|
334
|
+
} catch {
|
|
335
|
+
// повреждённая запись пропускается
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
// Длинные значения первыми, чтобы не оставить хвост после короткой замены.
|
|
339
|
+
values.sort((a, b) => b.length - a.length);
|
|
340
|
+
valuesCache = { at: now, values };
|
|
341
|
+
return values;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Вырезает из произвольного текста известные значения секретов и типовые
|
|
346
|
+
* присваивания вида `TOKEN=...` / `password: ...`.
|
|
347
|
+
*/
|
|
348
|
+
export function redactSecretsInText(text: unknown): string {
|
|
349
|
+
const source = typeof text === "string" ? text : String(text ?? "");
|
|
350
|
+
if (!source) return source;
|
|
351
|
+
let result = source;
|
|
352
|
+
|
|
353
|
+
// Защищаем ссылки ${secret:NAME} от общих правил маскировки: слово "secret"
|
|
354
|
+
// попадает под чувствительные ключи и ломало бы ссылки.
|
|
355
|
+
const protectedRefs: string[] = [];
|
|
356
|
+
result = result.replace(SECRET_REF_RE, (_match: string, name: string) => {
|
|
357
|
+
const placeholder = `\u0000SECRET_REF_${protectedRefs.length}\u0000`;
|
|
358
|
+
protectedRefs.push(`\${secret:${name}}`);
|
|
359
|
+
return placeholder;
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
for (const value of knownSecretValues()) {
|
|
363
|
+
if (!value) continue;
|
|
364
|
+
result = result.split(value).join("***");
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
result = result.replace(
|
|
368
|
+
/\b([A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|APIKEY|CREDENTIAL|AUTH)[A-Za-z0-9_]*)\b(\s*[=:]\s*)(["']?)([^\s"',;]+)\3/gi,
|
|
369
|
+
(_match: string, key: string, sep: string, quote: string) => `${key}${sep}${quote}***${quote}`
|
|
370
|
+
);
|
|
371
|
+
|
|
372
|
+
// Восстанавливаем защищённые ссылки.
|
|
373
|
+
for (let i = 0; i < protectedRefs.length; i++) {
|
|
374
|
+
result = result.split(`\u0000SECRET_REF_${i}\u0000`).join(protectedRefs[i]);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
return result;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** Сбрасывает кэши (для тестов и после ручного изменения файлов). */
|
|
381
|
+
export function resetSecretsCache(): void {
|
|
382
|
+
cache = null;
|
|
383
|
+
keyCache = null;
|
|
384
|
+
valuesCache = null;
|
|
385
|
+
}
|