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.
Files changed (44) hide show
  1. package/CHANGELOG.md +23 -1
  2. package/README.md +9 -3
  3. package/ROADMAP-STRATEGY.md +11 -11
  4. package/ROADMAP.md +2 -7
  5. package/dist/core/audit.d.ts +68 -0
  6. package/dist/core/audit.d.ts.map +1 -0
  7. package/dist/core/audit.js +206 -0
  8. package/dist/core/secrets.d.ts +57 -0
  9. package/dist/core/secrets.d.ts.map +1 -0
  10. package/dist/core/secrets.js +331 -0
  11. package/dist/core/structured-log.d.ts.map +1 -1
  12. package/dist/core/structured-log.js +9 -0
  13. package/dist/db/schema.d.ts +1 -1
  14. package/dist/db/schema.d.ts.map +1 -1
  15. package/dist/db/schema.js +15 -0
  16. package/dist/index.d.ts +24 -4
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +342 -19
  19. package/dist/rpc.d.ts +400 -0
  20. package/dist/rpc.d.ts.map +1 -1
  21. package/dist/rpc.js +146 -0
  22. package/dist/server.d.ts.map +1 -1
  23. package/dist/server.js +67 -0
  24. package/dist/settings.d.ts +16 -0
  25. package/dist/settings.d.ts.map +1 -1
  26. package/dist/settings.js +29 -0
  27. package/dist/workspaces.d.ts +8 -2
  28. package/dist/workspaces.d.ts.map +1 -1
  29. package/dist/workspaces.js +21 -4
  30. package/docs/ARCHITECTURE.md +13 -5
  31. package/docs/FEATURES.md +29 -1
  32. package/docs/README.ru.md +13 -3
  33. package/gui-experimental.cjs +4 -4
  34. package/package.json +4 -2
  35. package/src/core/audit.ts +291 -0
  36. package/src/core/secrets.ts +385 -0
  37. package/src/core/structured-log.ts +9 -0
  38. package/src/db/schema.ts +15 -0
  39. package/src/gui.tsx +323 -0
  40. package/src/index.ts +452 -19
  41. package/src/rpc.ts +157 -0
  42. package/src/server.ts +67 -0
  43. package/src/settings.ts +51 -0
  44. package/src/workspaces.ts +22 -4
package/src/rpc.ts CHANGED
@@ -441,6 +441,41 @@ const NotificationSettingsSchema = {
441
441
  },
442
442
  required: ["include", "exclude"],
443
443
  },
444
+ telegram: {
445
+ type: "object" as const,
446
+ properties: {
447
+ enabled: { type: "boolean" },
448
+ botToken: { type: "string" },
449
+ chatId: { type: "string" },
450
+ parseMode: {
451
+ type: "string",
452
+ enum: ["", "HTML", "Markdown", "MarkdownV2"],
453
+ },
454
+ disableNotification: { type: "boolean" },
455
+ messageThreadId: { type: ["number", "null"] },
456
+ includeDashboardLink: { type: "boolean" },
457
+ apiBase: { type: "string" },
458
+ },
459
+ required: ["enabled"],
460
+ },
461
+ native: {
462
+ type: "object" as const,
463
+ properties: {
464
+ enabled: { type: "boolean" },
465
+ sound: { type: "boolean" },
466
+ },
467
+ required: ["enabled"],
468
+ },
469
+ quietHours: {
470
+ type: "object" as const,
471
+ properties: {
472
+ enabled: { type: "boolean" },
473
+ from: { type: "string" },
474
+ to: { type: "string" },
475
+ },
476
+ required: ["enabled", "from", "to"],
477
+ },
478
+ dashboardUrl: { type: "string" },
444
479
  matrix: {
445
480
  type: "object" as const,
446
481
  properties: {
@@ -477,6 +512,17 @@ const HistorySettingsSchema = {
477
512
  required: ["retentionDays", "maxRecords"],
478
513
  } as const;
479
514
 
515
+ /** Журнал аудита (Спринт 26). */
516
+ const AuditSettingsSchema = {
517
+ type: "object" as const,
518
+ properties: {
519
+ enabled: { type: "boolean" },
520
+ retentionDays: { type: "number" },
521
+ maxRecords: { type: "number" },
522
+ },
523
+ required: ["enabled", "retentionDays", "maxRecords"],
524
+ } as const;
525
+
480
526
  const GetSettingsOutput = {
481
527
  type: "object" as const,
482
528
  properties: {
@@ -484,6 +530,7 @@ const GetSettingsOutput = {
484
530
  winterMode: { type: "boolean" },
485
531
  notifications: NotificationSettingsSchema,
486
532
  history: HistorySettingsSchema,
533
+ audit: AuditSettingsSchema,
487
534
  },
488
535
  required: ["maxConcurrent", "winterMode", "notifications"],
489
536
  } as const;
@@ -495,6 +542,7 @@ const SaveSettingsInput = {
495
542
  winterMode: { type: "boolean" },
496
543
  notifications: NotificationSettingsSchema,
497
544
  history: HistorySettingsSchema,
545
+ audit: AuditSettingsSchema,
498
546
  },
499
547
  additionalProperties: false,
500
548
  } as const;
@@ -507,6 +555,7 @@ const SaveSettingsOutput = {
507
555
  winterMode: { type: "boolean" },
508
556
  notifications: NotificationSettingsSchema,
509
557
  history: HistorySettingsSchema,
558
+ audit: AuditSettingsSchema,
510
559
  },
511
560
  required: ["success", "maxConcurrent", "winterMode", "notifications"],
512
561
  } as const;
@@ -591,6 +640,110 @@ const SendDigestOutput = {
591
640
  required: ["success", "message"],
592
641
  } as const;
593
642
 
643
+ /** Секрет: имя и маскированный превью, значение никогда не возвращается. */
644
+ const SecretItem = {
645
+ type: "object" as const,
646
+ properties: {
647
+ name: { type: "string" },
648
+ preview: { type: "string" },
649
+ updatedAt: { type: "string" },
650
+ },
651
+ required: ["name", "preview"],
652
+ } as const;
653
+
654
+ const ListSecretsInput = {
655
+ type: "object" as const,
656
+ properties: {},
657
+ additionalProperties: false,
658
+ } as const;
659
+
660
+ const ListSecretsOutput = {
661
+ type: "object" as const,
662
+ properties: {
663
+ success: { type: "boolean" },
664
+ secrets: { type: "array", items: SecretItem },
665
+ },
666
+ required: ["success", "secrets"],
667
+ } as const;
668
+
669
+ const SaveSecretInput = {
670
+ type: "object" as const,
671
+ properties: {
672
+ name: { type: "string" },
673
+ value: { type: "string" },
674
+ },
675
+ required: ["name", "value"],
676
+ additionalProperties: false,
677
+ } as const;
678
+
679
+ const SaveSecretOutput = {
680
+ type: "object" as const,
681
+ properties: {
682
+ success: { type: "boolean" },
683
+ message: { type: "string" },
684
+ secret: SecretItem,
685
+ },
686
+ required: ["success"],
687
+ } as const;
688
+
689
+ const DeleteSecretInput = {
690
+ type: "object" as const,
691
+ properties: {
692
+ name: { type: "string" },
693
+ },
694
+ required: ["name"],
695
+ additionalProperties: false,
696
+ } as const;
697
+
698
+ const DeleteSecretOutput = {
699
+ type: "object" as const,
700
+ properties: {
701
+ success: { type: "boolean" },
702
+ message: { type: "string" },
703
+ },
704
+ required: ["success", "message"],
705
+ } as const;
706
+
707
+ /** Запись журнала аудита (Спринт 26). */
708
+ const AuditRecordSchema = {
709
+ type: "object" as const,
710
+ properties: {
711
+ id: { type: "number" },
712
+ ts: { type: "string" },
713
+ action: { type: "string" },
714
+ targetType: { type: ["string", "null"] },
715
+ target: { type: ["string", "null"] },
716
+ actor: { type: "string" },
717
+ source: { type: ["string", "null"] },
718
+ details: {},
719
+ remote: { type: ["string", "null"] },
720
+ },
721
+ required: ["id", "ts", "action", "actor"],
722
+ } as const;
723
+
724
+ const GetAuditInput = {
725
+ type: "object" as const,
726
+ properties: {
727
+ action: { type: "string" },
728
+ target: { type: "string" },
729
+ actor: { type: "string" },
730
+ since: { type: "string" },
731
+ until: { type: "string" },
732
+ limit: { type: "number" },
733
+ },
734
+ additionalProperties: false,
735
+ } as const;
736
+
737
+ const GetAuditOutput = {
738
+ type: "object" as const,
739
+ properties: {
740
+ success: { type: "boolean" },
741
+ records: { type: "array", items: AuditRecordSchema },
742
+ total: { type: "number" },
743
+ },
744
+ required: ["success", "records", "total"],
745
+ } as const;
746
+
594
747
  const TemplateItem = {
595
748
  type: "object" as const,
596
749
  properties: {
@@ -1230,6 +1383,10 @@ export const SchedulerRpc = Rpc.define({
1230
1383
  input: SendDigestInput,
1231
1384
  output: SendDigestOutput,
1232
1385
  },
1386
+ list_secrets: { input: ListSecretsInput, output: ListSecretsOutput },
1387
+ save_secret: { input: SaveSecretInput, output: SaveSecretOutput },
1388
+ delete_secret: { input: DeleteSecretInput, output: DeleteSecretOutput },
1389
+ get_audit: { input: GetAuditInput, output: GetAuditOutput },
1233
1390
  },
1234
1391
  events: {},
1235
1392
  });
package/src/server.ts CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  import { appendStructuredLog, readStructuredLogs } from "./core/structured-log.js";
22
22
  import { PROMETHEUS_CONTENT_TYPE, renderPrometheusMetrics } from "./core/prometheus.js";
23
23
  import { buildOtlpExport } from "./core/otel.js";
24
+ import { readAuditLog, recordAudit } from "./core/audit.js";
24
25
 
25
26
  /**
26
27
  * Локальный веб-дашборд (Спринт 5).
@@ -621,6 +622,7 @@ async function handleRequest(
621
622
  pathname === "/api/history/export" ||
622
623
  pathname === "/api/export-db" ||
623
624
  pathname === "/api/workspaces" ||
625
+ pathname === "/api/audit" ||
624
626
  pathname === "/api/health" ||
625
627
  pathname === "/api/logs" ||
626
628
  pathname === "/metrics" ||
@@ -935,6 +937,27 @@ async function handleRequest(
935
937
  return;
936
938
  }
937
939
 
940
+ // Журнал аудита (Спринт 26): GET /api/audit?action=…&actor=…&limit=…
941
+ if (req.method === "GET" && pathname === "/api/audit") {
942
+ try {
943
+ const limitRaw = Number(url.searchParams.get("limit"));
944
+ const result = readAuditLog({
945
+ action: url.searchParams.get("action") ?? undefined,
946
+ target: url.searchParams.get("target") ?? undefined,
947
+ actor: url.searchParams.get("actor") ?? undefined,
948
+ since: url.searchParams.get("since") ?? undefined,
949
+ until: url.searchParams.get("until") ?? undefined,
950
+ limit: Number.isFinite(limitRaw) ? limitRaw : undefined,
951
+ });
952
+ sendJson(res, 200, { success: true, ...result });
953
+ } catch (err: any) {
954
+ sendJson(res, 500, {
955
+ error: err instanceof Error ? err.message : String(err),
956
+ });
957
+ }
958
+ return;
959
+ }
960
+
938
961
  // Входящий webhook-триггер (Спринт 22): POST /api/hooks/:task?token=…
939
962
  const hookMatch = req.method === "POST" && pathname.match(/^\/api\/hooks\/(.+)$/);
940
963
  if (hookMatch) {
@@ -1022,6 +1045,15 @@ async function handleRequest(
1022
1045
  ? `Задача "${task.name}" уже выполняется.`
1023
1046
  : `Задача "${task.name}" запущена по webhook.`;
1024
1047
  logHook(202, "accepted", undefined, bodyResult.body.length);
1048
+ recordAudit({
1049
+ action: "task.run",
1050
+ targetType: "task",
1051
+ target: task.name,
1052
+ actor: "http",
1053
+ source: "POST /api/hooks/:name",
1054
+ remote,
1055
+ details: { trigger: "hook" },
1056
+ });
1025
1057
  sendJson(res, 202, {
1026
1058
  success: true,
1027
1059
  task: task.name,
@@ -1046,6 +1078,15 @@ async function handleRequest(
1046
1078
  }
1047
1079
  try {
1048
1080
  const result = await deps.runTask(name);
1081
+ recordAudit({
1082
+ action: "task.run",
1083
+ targetType: "task",
1084
+ target: name,
1085
+ actor: "http",
1086
+ source: "POST /api/run/:name",
1087
+ remote: req.socket.remoteAddress ?? null,
1088
+ details: { alreadyRunning: Boolean(result?.alreadyRunning) },
1089
+ });
1049
1090
  sendJson(res, 200, {
1050
1091
  success: true,
1051
1092
  message: result?.alreadyRunning
@@ -1076,6 +1117,15 @@ async function handleRequest(
1076
1117
  }
1077
1118
  try {
1078
1119
  const result = await deps.cancelMatrix(name);
1120
+ recordAudit({
1121
+ action: "matrix.cancel",
1122
+ targetType: "matrix",
1123
+ target: name,
1124
+ actor: "http",
1125
+ source: "POST /api/cancel-matrix/:name",
1126
+ remote: req.socket.remoteAddress ?? null,
1127
+ details: { cancelled: result.cancelled },
1128
+ });
1079
1129
  sendJson(res, 200, {
1080
1130
  success: true,
1081
1131
  message: result.message,
@@ -1098,6 +1148,15 @@ async function handleRequest(
1098
1148
  }
1099
1149
  try {
1100
1150
  const removed = await deps.cleanupMatrixOrphans();
1151
+ recordAudit({
1152
+ action: "matrix.cleanup",
1153
+ targetType: "matrix",
1154
+ target: "orphans",
1155
+ actor: "http",
1156
+ source: "POST /api/matrix-cleanup",
1157
+ remote: req.socket.remoteAddress ?? null,
1158
+ details: { removed: removed.length },
1159
+ });
1101
1160
  sendJson(res, 200, {
1102
1161
  success: true,
1103
1162
  removed,
@@ -1125,6 +1184,14 @@ async function handleRequest(
1125
1184
  }
1126
1185
  try {
1127
1186
  await deps.deleteTask(name);
1187
+ recordAudit({
1188
+ action: "task.delete",
1189
+ targetType: "task",
1190
+ target: name,
1191
+ actor: "http",
1192
+ source: "POST /api/delete/:name",
1193
+ remote: req.socket.remoteAddress ?? null,
1194
+ });
1128
1195
  sendJson(res, 200, { success: true, message: `Задача "${name}" удалена.` });
1129
1196
  } catch (err: any) {
1130
1197
  sendJson(res, 500, {
package/src/settings.ts CHANGED
@@ -178,6 +178,16 @@ export interface IntegrationSettings {
178
178
  hooks: HookSettings;
179
179
  }
180
180
 
181
+ /** Настройки журнала аудита (Спринт 26). */
182
+ export interface AuditSettings {
183
+ /** Вести журнал мутаций. */
184
+ enabled: boolean;
185
+ /** Сколько дней хранить записи; 0 — без ограничения по времени. */
186
+ retentionDays: number;
187
+ /** Максимум записей; старые удаляются первыми. */
188
+ maxRecords: number;
189
+ }
190
+
181
191
  /**
182
192
  * Глобальные настройки плагина, которые меняются из GUI.
183
193
  * Хранятся в settings.json рядом с tasks.json / history.json.
@@ -193,6 +203,8 @@ export interface SchedulerSettings {
193
203
  history: HistorySettings;
194
204
  /** Внешние интеграции: входящие webhook-триггеры. */
195
205
  integrations: IntegrationSettings;
206
+ /** Журнал аудита мутаций (Спринт 26). */
207
+ audit: AuditSettings;
196
208
  }
197
209
 
198
210
  export const SETTINGS_FILE = path.join(PLUGIN_DIR, "settings.json");
@@ -213,6 +225,38 @@ export const DEFAULT_HOOK_TIMESTAMP_TOLERANCE_SECONDS = 300;
213
225
  const MAX_HOOK_BODY_BYTES = 5 * 1024 * 1024;
214
226
  const MAX_HOOK_CREDENTIAL_LENGTH = 512;
215
227
 
228
+ /** Аудит (Спринт 26): включён, 90 дней и не больше 10 000 записей. */
229
+ export const DEFAULT_AUDIT_RETENTION_DAYS = 90;
230
+ export const DEFAULT_AUDIT_MAX_RECORDS = 10_000;
231
+
232
+ /** Значения аудита по умолчанию. */
233
+ export function defaultAuditSettings(): AuditSettings {
234
+ return {
235
+ enabled: true,
236
+ retentionDays: DEFAULT_AUDIT_RETENTION_DAYS,
237
+ maxRecords: DEFAULT_AUDIT_MAX_RECORDS,
238
+ };
239
+ }
240
+
241
+ /** Приводит настройки аудита к безопасному виду. */
242
+ function normalizeAuditSettings(
243
+ value: unknown,
244
+ fallback: AuditSettings
245
+ ): AuditSettings {
246
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
247
+ return { ...fallback };
248
+ }
249
+ const raw = value as Partial<AuditSettings>;
250
+ return {
251
+ enabled: typeof raw.enabled === "boolean" ? raw.enabled : fallback.enabled,
252
+ retentionDays: normalizeRetentionLimit(
253
+ raw.retentionDays,
254
+ fallback.retentionDays
255
+ ),
256
+ maxRecords: normalizeRetentionLimit(raw.maxRecords, fallback.maxRecords),
257
+ };
258
+ }
259
+
216
260
  /** Значения интеграций по умолчанию: хуки выключены, подпись обязательна. */
217
261
  export function defaultIntegrations(): IntegrationSettings {
218
262
  return {
@@ -636,6 +680,7 @@ export async function loadSettings(): Promise<SchedulerSettings> {
636
680
  const fallbackNotifications = defaultNotifications();
637
681
  const fallbackHistory = defaultHistorySettings();
638
682
  const fallbackIntegrations = defaultIntegrations();
683
+ const fallbackAudit = defaultAuditSettings();
639
684
  try {
640
685
  const raw = await fs.readFile(SETTINGS_FILE, "utf8");
641
686
  const parsed = JSON.parse(raw) as Partial<SchedulerSettings> | null;
@@ -657,6 +702,7 @@ export async function loadSettings(): Promise<SchedulerSettings> {
657
702
  parsed?.integrations,
658
703
  fallbackIntegrations
659
704
  ),
705
+ audit: normalizeAuditSettings(parsed?.audit, fallbackAudit),
660
706
  };
661
707
  } catch {
662
708
  return {
@@ -665,6 +711,7 @@ export async function loadSettings(): Promise<SchedulerSettings> {
665
711
  notifications: fallbackNotifications,
666
712
  history: fallbackHistory,
667
713
  integrations: fallbackIntegrations,
714
+ audit: fallbackAudit,
668
715
  };
669
716
  }
670
717
  }
@@ -695,6 +742,10 @@ export async function saveSettings(
695
742
  patch.integrations !== undefined
696
743
  ? normalizeIntegrations(patch.integrations, current.integrations)
697
744
  : current.integrations,
745
+ audit:
746
+ patch.audit !== undefined
747
+ ? normalizeAuditSettings(patch.audit, current.audit)
748
+ : current.audit,
698
749
  };
699
750
 
700
751
  // Удобство: при включении хуков без явных учётных данных генерируем их,
package/src/workspaces.ts CHANGED
@@ -4,6 +4,7 @@ import { basename, join, resolve } from "node:path";
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { getDb } from "./db/index.js";
6
6
  import { clearWorkspaceAssignments } from "./db/tasks-repo.js";
7
+ import { hasSecretRef, resolveSecretRefs } from "./core/secrets.js";
7
8
 
8
9
  /**
9
10
  * Multi-repo workspaces.
@@ -134,14 +135,23 @@ export function readWorkspaceEnvFile(envFile?: string): Record<string, string> {
134
135
 
135
136
  /**
136
137
  * Итоговые env-переменные workspace: сначала .env-файл, затем явные пары
137
- * (пары важнее файла). Никогда не бросает.
138
+ * (пары важнее файла). Ссылки `${secret:NAME}` разворачиваются из
139
+ * зашифрованного хранилища (Спринт 26); отсутствующий секрет даёт пустую
140
+ * строку и предупреждение с именем — без значения. Никогда не бросает.
138
141
  */
139
142
  export function resolveWorkspaceEnv(workspace: Workspace | undefined): Record<string, string> {
140
143
  if (!workspace) return {};
141
- return {
144
+ const merged = {
142
145
  ...readWorkspaceEnvFile(workspace.envFile),
143
146
  ...(workspace.env ?? {}),
144
147
  };
148
+ const resolved = resolveSecretRefs(merged);
149
+ if (resolved.missing.length > 0) {
150
+ console.warn(
151
+ `[workspace] "${workspace.name}": не найдены секреты: ${resolved.missing.join(", ")}`
152
+ );
153
+ }
154
+ return resolved.env;
145
155
  }
146
156
 
147
157
  /** Маскирует значение секрета для логов. */
@@ -151,12 +161,20 @@ export function maskSecretValue(): string {
151
161
 
152
162
  const SECRET_KEY_RE = /(TOKEN|SECRET|PASS|PASSWORD|KEY|CREDENTIAL|AUTH)/i;
153
163
 
154
- /** Копия env для логов: значения «секретных» ключей заменены на ***. */
164
+ /**
165
+ * Копия env для логов: значения «секретных» ключей заменены на ***.
166
+ * Чистые ссылки `${secret:NAME}` сохраняются как есть — это не секрет,
167
+ * а указатель, и он помогает диагностике (Спринт 26).
168
+ */
155
169
  export function maskEnvForLog(env: Record<string, string> | undefined): Record<string, string> {
156
170
  if (!env) return {};
157
171
  const masked: Record<string, string> = {};
158
172
  for (const [key, value] of Object.entries(env)) {
159
- masked[key] = SECRET_KEY_RE.test(key) ? maskSecretValue() : value;
173
+ if (hasSecretRef(value)) {
174
+ masked[key] = String(value);
175
+ } else {
176
+ masked[key] = SECRET_KEY_RE.test(key) ? maskSecretValue() : value;
177
+ }
160
178
  }
161
179
  return masked;
162
180
  }