opencode-windows-scheduler 1.1.0 → 1.2.1

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 (144) hide show
  1. package/CHANGELOG.md +60 -1
  2. package/README.md +18 -8
  3. package/README.ru.md +13 -3
  4. package/ROADMAP-STRATEGY.md +2 -2
  5. package/ROADMAP.md +51 -18
  6. package/dist/core/analytics.d.ts +10 -0
  7. package/dist/core/analytics.d.ts.map +1 -1
  8. package/dist/core/analytics.js +21 -0
  9. package/dist/core/dry-run.d.ts +18 -1
  10. package/dist/core/dry-run.d.ts.map +1 -1
  11. package/dist/core/dry-run.js +49 -3
  12. package/dist/core/matrix.d.ts.map +1 -1
  13. package/dist/core/matrix.js +10 -0
  14. package/dist/core/one-shot.d.ts +62 -0
  15. package/dist/core/one-shot.d.ts.map +1 -0
  16. package/dist/core/one-shot.js +126 -0
  17. package/dist/core/otel.d.ts +4 -0
  18. package/dist/core/otel.d.ts.map +1 -0
  19. package/dist/core/otel.js +98 -0
  20. package/dist/core/prometheus.d.ts +23 -0
  21. package/dist/core/prometheus.d.ts.map +1 -0
  22. package/dist/core/prometheus.js +146 -0
  23. package/dist/core/ps-wrapper.d.ts +36 -2
  24. package/dist/core/ps-wrapper.d.ts.map +1 -1
  25. package/dist/core/ps-wrapper.js +124 -4
  26. package/dist/core/record-history.d.ts.map +1 -1
  27. package/dist/core/record-history.js +9 -0
  28. package/dist/core/schedule-gate.d.ts +2 -0
  29. package/dist/core/schedule-gate.d.ts.map +1 -0
  30. package/dist/core/schedule-gate.js +182 -0
  31. package/dist/core/schedule-v2.d.ts +88 -0
  32. package/dist/core/schedule-v2.d.ts.map +1 -0
  33. package/dist/core/schedule-v2.js +496 -0
  34. package/dist/core/scheduler/linux.d.ts +12 -3
  35. package/dist/core/scheduler/linux.d.ts.map +1 -1
  36. package/dist/core/scheduler/linux.js +80 -3
  37. package/dist/core/scheduler/mac.d.ts.map +1 -1
  38. package/dist/core/scheduler/mac.js +17 -3
  39. package/dist/core/scheduler/posix.d.ts.map +1 -1
  40. package/dist/core/scheduler/posix.js +3 -0
  41. package/dist/core/scheduler/registry.d.ts +4 -0
  42. package/dist/core/scheduler/registry.d.ts.map +1 -1
  43. package/dist/core/scheduler/types.d.ts +20 -3
  44. package/dist/core/scheduler/types.d.ts.map +1 -1
  45. package/dist/core/scheduler/windows.d.ts.map +1 -1
  46. package/dist/core/scheduler/windows.js +23 -2
  47. package/dist/core/session.d.ts +34 -0
  48. package/dist/core/session.d.ts.map +1 -0
  49. package/dist/core/session.js +105 -0
  50. package/dist/core/structured-log.d.ts +84 -0
  51. package/dist/core/structured-log.d.ts.map +1 -0
  52. package/dist/core/structured-log.js +137 -0
  53. package/dist/core/wrappers/bash.d.ts +24 -0
  54. package/dist/core/wrappers/bash.d.ts.map +1 -1
  55. package/dist/core/wrappers/bash.js +70 -3
  56. package/dist/db/history-repo.d.ts +8 -0
  57. package/dist/db/history-repo.d.ts.map +1 -1
  58. package/dist/db/history-repo.js +76 -6
  59. package/dist/db/metrics-repo.d.ts +3 -0
  60. package/dist/db/metrics-repo.d.ts.map +1 -1
  61. package/dist/db/metrics-repo.js +16 -8
  62. package/dist/db/migrate.d.ts.map +1 -1
  63. package/dist/db/migrate.js +8 -1
  64. package/dist/db/schema.d.ts +1 -1
  65. package/dist/db/schema.d.ts.map +1 -1
  66. package/dist/db/schema.js +19 -0
  67. package/dist/gui-experimental.cjs +1 -0
  68. package/dist/history.d.ts +7 -0
  69. package/dist/history.d.ts.map +1 -1
  70. package/dist/history.js +13 -0
  71. package/dist/index.d.ts +137 -1
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +1323 -78
  74. package/dist/integrations.d.ts +64 -0
  75. package/dist/integrations.d.ts.map +1 -0
  76. package/dist/integrations.js +205 -0
  77. package/dist/notifications.d.ts +112 -6
  78. package/dist/notifications.d.ts.map +1 -1
  79. package/dist/notifications.js +396 -34
  80. package/dist/profiles.d.ts +60 -0
  81. package/dist/profiles.d.ts.map +1 -0
  82. package/dist/profiles.js +209 -0
  83. package/dist/rpc.d.ts +592 -4
  84. package/dist/rpc.d.ts.map +1 -1
  85. package/dist/rpc.js +233 -6
  86. package/dist/server.d.ts +2 -0
  87. package/dist/server.d.ts.map +1 -1
  88. package/dist/server.js +473 -58
  89. package/dist/settings.d.ts +95 -0
  90. package/dist/settings.d.ts.map +1 -1
  91. package/dist/settings.js +186 -8
  92. package/dist/shared/jobs-view.d.ts +43 -5
  93. package/dist/shared/jobs-view.d.ts.map +1 -1
  94. package/dist/shared/jobs-view.js +125 -7
  95. package/dist/task-transfer.d.ts +32 -3
  96. package/dist/task-transfer.d.ts.map +1 -1
  97. package/dist/task-transfer.js +101 -3
  98. package/dist/types.d.ts.map +1 -1
  99. package/dist/types.js +3 -11
  100. package/dist/workspaces.d.ts +43 -0
  101. package/dist/workspaces.d.ts.map +1 -1
  102. package/dist/workspaces.js +174 -8
  103. package/docs/ARCHITECTURE.md +32 -12
  104. package/docs/FEATURES.md +186 -10
  105. package/gui-experimental.cjs +4 -2
  106. package/package.json +15 -2
  107. package/scripts/demo-dashboard.mjs +12 -2
  108. package/src/core/analytics.ts +36 -0
  109. package/src/core/dry-run.ts +65 -4
  110. package/src/core/matrix.ts +10 -0
  111. package/src/core/one-shot.ts +173 -0
  112. package/src/core/otel.ts +128 -0
  113. package/src/core/prometheus.ts +215 -0
  114. package/src/core/ps-wrapper.ts +144 -4
  115. package/src/core/record-history.ts +13 -0
  116. package/src/core/schedule-gate.ts +213 -0
  117. package/src/core/schedule-v2.ts +533 -0
  118. package/src/core/scheduler/linux.ts +90 -3
  119. package/src/core/scheduler/mac.ts +35 -4
  120. package/src/core/scheduler/posix.ts +3 -0
  121. package/src/core/scheduler/registry.ts +4 -0
  122. package/src/core/scheduler/types.ts +20 -3
  123. package/src/core/scheduler/windows.ts +24 -2
  124. package/src/core/session.ts +115 -0
  125. package/src/core/structured-log.ts +205 -0
  126. package/src/core/wrappers/bash.ts +98 -2
  127. package/src/db/history-repo.ts +90 -7
  128. package/src/db/metrics-repo.ts +19 -7
  129. package/src/db/migrate.ts +7 -1
  130. package/src/db/schema.ts +25 -0
  131. package/src/gui.tsx +3832 -2868
  132. package/src/history.ts +17 -0
  133. package/src/index.ts +1670 -117
  134. package/src/integrations.ts +253 -0
  135. package/src/notifications.ts +516 -40
  136. package/src/profiles.ts +236 -0
  137. package/src/rpc.ts +244 -6
  138. package/src/server.ts +506 -58
  139. package/src/settings.ts +336 -9
  140. package/src/shared/jobs-view.ts +158 -8
  141. package/src/task-transfer.ts +151 -5
  142. package/src/tui.tsx +290 -14
  143. package/src/types.ts +3 -13
  144. package/src/workspaces.ts +214 -8
@@ -0,0 +1,253 @@
1
+ import crypto from "node:crypto";
2
+ import type http from "node:http";
3
+ import type { HookSettings } from "./settings.js";
4
+
5
+ /**
6
+ * Входящие webhook-триггеры (Спринт 22).
7
+ *
8
+ * Контракт:
9
+ * POST /api/hooks/<task>?token=<token>
10
+ * X-Scheduler-Signature: sha256=<hex hmac по сырому телу>
11
+ * X-Scheduler-Timestamp: <unix seconds|milliseconds> (необязательно)
12
+ *
13
+ * Для совместимости с GitHub Actions принимается также `X-Hub-Signature-256`,
14
+ * для GitLab — `X-Gitlab-Token` вместо query-параметра.
15
+ *
16
+ * HMAC считается по **сырому телу** запроса (без нормализации JSON), поэтому
17
+ * отправитель должен подписывать ровно те байты, которые кладёт в body.
18
+ */
19
+
20
+ /** Заголовки, в которых может прийти HMAC-подпись. */
21
+ const SIGNATURE_HEADERS = [
22
+ "x-scheduler-signature",
23
+ "x-hub-signature-256",
24
+ "x-signature-256",
25
+ ] as const;
26
+
27
+ /** Заголовки, в которых может прийти токен (альтернатива query-параметру). */
28
+ const TOKEN_HEADERS = ["x-scheduler-token", "x-gitlab-token"] as const;
29
+
30
+ type HeaderMap = Record<string, string | string[] | undefined>;
31
+
32
+ /** Первое значение заголовка (Node может вернуть массив). */
33
+ function firstHeader(value: string | string[] | undefined): string | null {
34
+ if (Array.isArray(value)) return value.length > 0 ? String(value[0]) : null;
35
+ return typeof value === "string" && value.trim() ? value.trim() : null;
36
+ }
37
+
38
+ /** Сравнение строк без утечки длины через раннее завершение. */
39
+ export function timingSafeStringEqual(expected: string, provided: string): boolean {
40
+ if (typeof expected !== "string" || typeof provided !== "string") return false;
41
+ if (!expected || !provided) return false;
42
+ const expectedHash = crypto.createHash("sha256").update(expected, "utf8").digest();
43
+ const providedHash = crypto.createHash("sha256").update(provided, "utf8").digest();
44
+ const equal = crypto.timingSafeEqual(expectedHash, providedHash);
45
+ return equal && expected.length === provided.length;
46
+ }
47
+
48
+ /** Проверяет токен из query-параметра или заголовка. */
49
+ export function verifyHookToken(expected: string, provided: string | null): boolean {
50
+ return typeof provided === "string" && timingSafeStringEqual(expected, provided);
51
+ }
52
+
53
+ /** Считает HMAC-SHA256 по сырому телу и возвращает значение в формате `sha256=<hex>`. */
54
+ export function signHookPayload(secret: string, body: Buffer | string): string {
55
+ const payload = Buffer.isBuffer(body) ? body : Buffer.from(body, "utf8");
56
+ const digest = crypto.createHmac("sha256", secret).update(payload).digest("hex");
57
+ return `sha256=${digest}`;
58
+ }
59
+
60
+ /** Достаёт подпись из поддерживаемых заголовков. */
61
+ export function extractHookSignature(headers: HeaderMap): string | null {
62
+ for (const name of SIGNATURE_HEADERS) {
63
+ const value = firstHeader(headers[name]);
64
+ if (value) return value;
65
+ }
66
+ return null;
67
+ }
68
+
69
+ /** Достаёт токен из поддерживаемых заголовков (если нет query-параметра). */
70
+ export function extractHookToken(headers: HeaderMap): string | null {
71
+ for (const name of TOKEN_HEADERS) {
72
+ const value = firstHeader(headers[name]);
73
+ if (value) return value;
74
+ }
75
+ return null;
76
+ }
77
+
78
+ /**
79
+ * Проверяет HMAC-подпись. Принимает `sha256=<hex>` и «голый» hex;
80
+ * алгоритмы кроме SHA-256 намеренно не поддерживаются.
81
+ */
82
+ export function verifyHookSignature(
83
+ secret: string,
84
+ body: Buffer | string,
85
+ signature: string | null
86
+ ): boolean {
87
+ if (!secret || !signature) return false;
88
+ const normalized = signature.trim();
89
+ if (!/^sha256=/i.test(normalized) && !/^[a-f0-9]{64}$/i.test(normalized)) {
90
+ return false;
91
+ }
92
+ const provided = normalized.replace(/^sha256=/i, "").trim().toLowerCase();
93
+ if (!/^[a-f0-9]{64}$/.test(provided)) return false;
94
+ const expected = signHookPayload(secret, body).replace(/^sha256=/, "");
95
+ return timingSafeStringEqual(expected, provided);
96
+ }
97
+
98
+ /**
99
+ * Проверяет необязательный timestamp против текущего времени.
100
+ * 0 в настройках — проверка выключена. Без заголовка запрос разрешён.
101
+ */
102
+ export function verifyHookTimestamp(
103
+ value: string | null,
104
+ toleranceSeconds: number,
105
+ nowMs = Date.now()
106
+ ): { ok: boolean; reason?: string } {
107
+ if (!value || toleranceSeconds <= 0) return { ok: true };
108
+ const trimmed = value.trim();
109
+ if (!/^\d+$/.test(trimmed)) {
110
+ return { ok: false, reason: "Некорректный X-Scheduler-Timestamp." };
111
+ }
112
+ const numeric = Number(trimmed);
113
+ if (!Number.isFinite(numeric)) {
114
+ return { ok: false, reason: "Некорректный X-Scheduler-Timestamp." };
115
+ }
116
+ // Значения больше 1e12 трактуем как миллисекунды, иначе — как секунды.
117
+ const timestampMs = numeric > 1e12 ? numeric : numeric * 1000;
118
+ const skewMs = Math.abs(nowMs - timestampMs);
119
+ if (skewMs > toleranceSeconds * 1000) {
120
+ return {
121
+ ok: false,
122
+ reason: `Timestamp вне допустимого окна (±${toleranceSeconds} с).`,
123
+ };
124
+ }
125
+ return { ok: true };
126
+ }
127
+
128
+ export interface HookAuthInput {
129
+ settings: HookSettings;
130
+ token: string | null;
131
+ signature: string | null;
132
+ timestamp: string | null;
133
+ /** Сырое тело запроса — ровно те байты, по которым считался HMAC. */
134
+ body: Buffer;
135
+ /** Текущее время (для тестов). */
136
+ nowMs?: number;
137
+ }
138
+
139
+ export interface HookAuthResult {
140
+ ok: boolean;
141
+ /** HTTP-статус для отказа (200 при успехе). */
142
+ status: number;
143
+ error?: string;
144
+ }
145
+
146
+ /**
147
+ * Полная проверка входящего хука: включён ли канал, токен, HMAC, timestamp.
148
+ * Возвращает понятную ошибку на русском для ответа и логов.
149
+ */
150
+ export function authenticateHookRequest(input: HookAuthInput): HookAuthResult {
151
+ const { settings } = input;
152
+ if (!settings.enabled) {
153
+ return { ok: false, status: 403, error: "Входящие webhook-триггеры отключены." };
154
+ }
155
+ if (!settings.token) {
156
+ return {
157
+ ok: false,
158
+ status: 403,
159
+ error: "В настройках не задан token для входящих хуков.",
160
+ };
161
+ }
162
+ if (!verifyHookToken(settings.token, input.token)) {
163
+ return { ok: false, status: 401, error: "Неверный token." };
164
+ }
165
+ if (settings.requireSignature) {
166
+ if (!settings.secret) {
167
+ return {
168
+ ok: false,
169
+ status: 403,
170
+ error: "В настройках не задан secret для HMAC-подписи.",
171
+ };
172
+ }
173
+ if (!input.signature) {
174
+ return {
175
+ ok: false,
176
+ status: 401,
177
+ error: "Не передана HMAC-подпись (X-Scheduler-Signature).",
178
+ };
179
+ }
180
+ if (!verifyHookSignature(settings.secret, input.body, input.signature)) {
181
+ return { ok: false, status: 401, error: "Неверная HMAC-подпись." };
182
+ }
183
+ }
184
+ const timestamp = verifyHookTimestamp(
185
+ input.timestamp,
186
+ settings.timestampToleranceSeconds,
187
+ input.nowMs
188
+ );
189
+ if (!timestamp.ok) {
190
+ return { ok: false, status: 401, error: timestamp.reason };
191
+ }
192
+ return { ok: true, status: 200 };
193
+ }
194
+
195
+ export type BodyReadResult =
196
+ | { ok: true; body: Buffer }
197
+ | { ok: false; status: number; error: string };
198
+
199
+ /**
200
+ * Читает тело запроса с ограничением размера.
201
+ *
202
+ * Лишние байты не накапливаются в памяти: после превышения лимита поток
203
+ * дочитывается и отбрасывается, чтобы клиент получил внятный 413, а не reset.
204
+ */
205
+ export function readRequestBody(
206
+ req: http.IncomingMessage,
207
+ maxBytes: number
208
+ ): Promise<BodyReadResult> {
209
+ return new Promise((resolve) => {
210
+ const limit = Math.max(1, Math.floor(maxBytes) || 1);
211
+ let size = 0;
212
+ let tooLarge = false;
213
+ let settled = false;
214
+ const chunks: Buffer[] = [];
215
+
216
+ const finish = (result: BodyReadResult) => {
217
+ if (settled) return;
218
+ settled = true;
219
+ resolve(result);
220
+ };
221
+
222
+ req.on("data", (chunk: Buffer) => {
223
+ size += chunk.length;
224
+ if (tooLarge) return;
225
+ if (size > limit) {
226
+ tooLarge = true;
227
+ chunks.length = 0;
228
+ return;
229
+ }
230
+ chunks.push(chunk);
231
+ });
232
+ req.on("end", () => {
233
+ if (tooLarge) {
234
+ finish({
235
+ ok: false,
236
+ status: 413,
237
+ error: `Тело запроса больше ${limit} байт.`,
238
+ });
239
+ return;
240
+ }
241
+ finish({ ok: true, body: Buffer.concat(chunks) });
242
+ });
243
+ req.on("error", (err) => {
244
+ finish({
245
+ ok: false,
246
+ status: 400,
247
+ error: `Не удалось прочитать тело запроса: ${
248
+ err instanceof Error ? err.message : String(err)
249
+ }`,
250
+ });
251
+ });
252
+ });
253
+ }