@lendle/classroomai 0.0.0-stage → 0.6.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.
@@ -0,0 +1,292 @@
1
+ /**
2
+ * OpenAI-compatible local API server(與 Python 版 server.py 對齊)。
3
+ *
4
+ * 1. Relay 狀態(enabled/disabled)
5
+ * 2. 三窗口 request limit
6
+ * 3. 動態降速(5m window spacing)
7
+ * 4. 轉發 OpenRouter:回應完全串流(SSE 不暫存)
8
+ * 5. log-payloads(opt-in):旁路擷取成功回應寫檔
9
+ * 6. 逐層 log 寫入 `.logs/relay/relay.log`(不輸出 console)
10
+ */
11
+ "use strict";
12
+
13
+ const http = require("http");
14
+ const { relayLogger } = require("./log");
15
+ const { PayloadLogger, MAX_RESPONSE_CAPTURE } = require("./payload-log");
16
+
17
+ const RE_MODEL = /"model"\s*:\s*"([^"]+)"/;
18
+ const RE_TOTAL_TOKENS = /"total_tokens"\s*:\s*(\d+)/;
19
+ const MAX_REQUEST_BODY = 50 * 1024 * 1024;
20
+
21
+ function isChatCompletions(pathname) {
22
+ return String(pathname).replace(/^\/+|\/+$/g, "").endsWith("chat/completions");
23
+ }
24
+
25
+ /** 串流時逐塊掃描 model id / total_tokens(不暫存整份回應) */
26
+ class ChunkProbe {
27
+ constructor() {
28
+ this._text = Buffer.alloc(0);
29
+ this.modelId = null;
30
+ this.totalTokens = null;
31
+ }
32
+
33
+ feed(chunk) {
34
+ if (this.modelId !== null && this.totalTokens !== null) return;
35
+ this._text = Buffer.concat([this._text, chunk]);
36
+ if (this._text.length > 64 * 1024) this._text = this._text.subarray(this._text.length - 16 * 1024);
37
+ const s = this._text.toString("utf8");
38
+ if (this.modelId === null) {
39
+ const m = s.match(RE_MODEL);
40
+ if (m) this.modelId = m[1];
41
+ }
42
+ if (this.totalTokens === null) {
43
+ const t = s.match(RE_TOTAL_TOKENS);
44
+ if (t) this.totalTokens = Number(t[1]);
45
+ }
46
+ }
47
+ }
48
+
49
+ function readBody(req) {
50
+ return new Promise((resolve, reject) => {
51
+ const chunks = [];
52
+ let size = 0;
53
+ req.on("data", (c) => {
54
+ size += c.length;
55
+ if (size > MAX_REQUEST_BODY) {
56
+ reject(new Error("request body too large"));
57
+ req.destroy();
58
+ return;
59
+ }
60
+ chunks.push(c);
61
+ });
62
+ req.on("end", () => resolve(Buffer.concat(chunks)));
63
+ req.on("error", reject);
64
+ });
65
+ }
66
+
67
+ class LocalApiServer {
68
+ constructor(engine, { port = 4141, client, sleepFunc = null, payloadLog = null } = {}) {
69
+ if (!client) throw new Error("LocalApiServer 需要 OpenRouter client");
70
+ this.engine = engine;
71
+ this.port = port;
72
+ this.client = client;
73
+ this.sleep = sleepFunc || ((ms) => new Promise((r) => setTimeout(r, ms)));
74
+ this.payloadLog = payloadLog || new PayloadLogger(false);
75
+ this._server = null;
76
+ this.log = relayLogger();
77
+ }
78
+
79
+ start() {
80
+ if (this._server) return Promise.resolve();
81
+ this._server = http.createServer((req, res) => {
82
+ this._handle(req, res).catch((e) => {
83
+ this.log.error(`handler error: ${e.message}`);
84
+ if (!res.headersSent) res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
85
+ res.end("internal error");
86
+ });
87
+ });
88
+ return new Promise((resolve, reject) => {
89
+ this._server.once("error", reject);
90
+ this._server.listen(this.port, "127.0.0.1", () => {
91
+ this.port = this._server.address().port;
92
+ resolve();
93
+ });
94
+ });
95
+ }
96
+
97
+ stop() {
98
+ if (!this._server) return Promise.resolve();
99
+ const srv = this._server;
100
+ this._server = null;
101
+ return new Promise((resolve) => srv.close(() => resolve()));
102
+ }
103
+
104
+ _reject(res, status, reason) {
105
+ this.log.info(`reject ${status} : ${reason}`);
106
+ const body = JSON.stringify({ error: { message: reason, type: "relay_rejected" } });
107
+ res.writeHead(status, { "Content-Type": "application/json" });
108
+ res.end(body);
109
+ }
110
+
111
+ _pathname(req) {
112
+ return new URL(req.url, "http://localhost").pathname;
113
+ }
114
+
115
+ async _handle(req, res) {
116
+ const pathname = this._pathname(req);
117
+ if (!pathname.startsWith("/v1")) {
118
+ this._reject(res, 404, "not found");
119
+ return;
120
+ }
121
+ const upstream = pathname.replace(/^\/v1\/?/, "");
122
+ if (req.method === "GET") return this._handleGet(req, res, upstream);
123
+ if (req.method !== "POST") return this._reject(res, 405, "method not allowed");
124
+
125
+ const engine = this.engine;
126
+ const started = Date.now();
127
+ const priorCount = engine.fiveMinWindowCount();
128
+
129
+ const gate = engine.canAcceptRequest();
130
+ if (!gate.ok) {
131
+ this.log.info(`reject 403 ${upstream} : ${gate.reason}`);
132
+ this._reject(res, 403, gate.reason);
133
+ return;
134
+ }
135
+
136
+ const delay = engine.throttleDelay(priorCount);
137
+ if (delay > 0) {
138
+ this.log.info(
139
+ `throttle ${upstream} : 5m window prior=${priorCount}/` +
140
+ `${engine.state.requestLimit["5m"]} -> wait ${delay}s`
141
+ );
142
+ await this.sleep(delay * 1000);
143
+ }
144
+
145
+ let body;
146
+ try {
147
+ const raw = await readBody(req);
148
+ body = JSON.parse(raw.toString("utf8") || "{}");
149
+ } catch {
150
+ engine.requestFinished(false); // 沒送出去,不計 error
151
+ this._reject(res, 400, "invalid json body");
152
+ return;
153
+ }
154
+
155
+ if (!engine.apiKey) {
156
+ engine.requestFinished(true);
157
+ this._reject(res, 503, "no API key available (尚未取得 credential)");
158
+ return;
159
+ }
160
+
161
+ const isChat = isChatCompletions(upstream);
162
+ if (isChat) {
163
+ applyModelRouting(body, engine.state);
164
+ this.log.info(
165
+ `forward ${upstream} : requested model=${JSON.stringify(body.model)} ` +
166
+ `fallback=${JSON.stringify(body.models || [])} stream=${!!body.stream} ` +
167
+ `session=${engine.sessionStats().totalRequests + 1}`
168
+ );
169
+ }
170
+
171
+ const probe = isChat ? new ChunkProbe() : null;
172
+ engine.requestStarted();
173
+ let up;
174
+ try {
175
+ up = await this.client.openStream(engine.apiKey, upstream, body);
176
+ } catch (e) {
177
+ this.log.warning(`upstream connect error ${upstream} : ${e.message}`);
178
+ engine.requestFinished(true);
179
+ this._reject(res, 502, `openrouter error: ${e.message}`);
180
+ return;
181
+ }
182
+
183
+ let hadError = up.status >= 400;
184
+ let bytesOut = 0;
185
+ let capture = isChat && this.payloadLog.enabled ? [] : null;
186
+ let captured = 0;
187
+ let captureTruncated = false;
188
+
189
+ res.writeHead(up.status, {
190
+ "Content-Type": up.headers["content-type"] || "application/json",
191
+ });
192
+
193
+ try {
194
+ for await (const chunk of up.stream) {
195
+ bytesOut += chunk.length;
196
+ if (probe) probe.feed(chunk);
197
+ if (capture) {
198
+ const remaining = MAX_RESPONSE_CAPTURE - captured;
199
+ if (remaining > 0) {
200
+ const take = chunk.subarray(0, Math.min(remaining, chunk.length));
201
+ capture.push(Buffer.from(take));
202
+ captured += take.length;
203
+ if (take.length < chunk.length) captureTruncated = true;
204
+ } else {
205
+ captureTruncated = true;
206
+ }
207
+ }
208
+ res.write(chunk);
209
+ }
210
+ res.end();
211
+ } catch (e) {
212
+ hadError = true;
213
+ this.log.warning(`stream aborted ${upstream} : ${e.message} (${bytesOut} bytes sent)`);
214
+ try {
215
+ res.destroy();
216
+ } catch {
217
+ /* 忽略 */
218
+ }
219
+ } finally {
220
+ up.close();
221
+ engine.requestFinished(hadError);
222
+ }
223
+
224
+ const ms = Date.now() - started;
225
+ const modelId = (probe && probe.modelId) || (isChat ? body.model : null) || null;
226
+ if (probe) engine.recordChatResponse(modelId, probe.totalTokens);
227
+
228
+ const logLine =
229
+ `upstream ${up.status} ${upstream} : model=${modelId} ` +
230
+ `tokens=${probe && probe.totalTokens !== null ? probe.totalTokens : "-"} ` +
231
+ `${bytesOut} bytes, ${ms} ms${hadError ? " (error)" : ""}`;
232
+ if (hadError) this.log.error(logLine);
233
+ else this.log.info(logLine);
234
+
235
+ if (capture && up.status >= 200 && up.status < 300) {
236
+ this.payloadLog.record({
237
+ path: upstream,
238
+ body,
239
+ response: Buffer.concat(capture),
240
+ status: up.status,
241
+ modelId,
242
+ tokens: probe ? probe.totalTokens : null,
243
+ durationMs: ms,
244
+ responseTruncated: captureTruncated,
245
+ });
246
+ }
247
+ }
248
+
249
+ async _handleGet(req, res, upstream) {
250
+ if (!this.engine.apiKey) {
251
+ this._reject(res, 503, "no API key available");
252
+ return;
253
+ }
254
+ this.log.info(`forward GET ${upstream}`);
255
+ try {
256
+ const { status, text } = await this.client.get(this.engine.apiKey, upstream);
257
+ this.log.info(`upstream ${status} GET ${upstream} : ${Buffer.byteLength(text)} bytes`);
258
+ let payload;
259
+ try {
260
+ payload = JSON.parse(text);
261
+ } catch {
262
+ payload = text;
263
+ }
264
+ res.writeHead(status, { "Content-Type": "application/json" });
265
+ res.end(JSON.stringify(payload));
266
+ } catch (e) {
267
+ this.log.warning(`upstream GET error ${upstream} : ${e.message}`);
268
+ res.writeHead(502, { "Content-Type": "application/json" });
269
+ res.end(JSON.stringify({ error: { message: `openrouter error: ${e.message}`, type: "relay_rejected" } }));
270
+ }
271
+ }
272
+ }
273
+
274
+ /**
275
+ * 對 chat/completions body 套用 Teacher 指定的 model routing:
276
+ * body.model = primary;fallback 非空才注入 body.models。
277
+ */
278
+ function applyModelRouting(body, state) {
279
+ body.model = state.primaryModel;
280
+ if (Array.isArray(state.models) && state.models.length > 0) {
281
+ body.models = [...state.models];
282
+ }
283
+ return body;
284
+ }
285
+
286
+ module.exports = {
287
+ LocalApiServer,
288
+ ChunkProbe,
289
+ isChatCompletions,
290
+ applyModelRouting,
291
+ MAX_REQUEST_BODY,
292
+ };
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Relay session 安全(與 Python 版 / teacher 對齊)。
3
+ *
4
+ * - PIN + Salt → PBKDF2-HMAC-SHA256(100_000) → 32-byte key(與 teacher/src/session.js 相同)。
5
+ * - credential:AES-256-GCM(iv 12 bytes;tag 於 ciphertext 尾端)。
6
+ * - fallback.bin:magic "CLFK1"(5) + iv(12) + ciphertext + tag(16);
7
+ * key = SHA256("imsofa.rocks")(固定金鑰,非安全機制)。
8
+ */
9
+ "use strict";
10
+
11
+ const crypto = require("crypto");
12
+
13
+ const PBKDF2_ITERATIONS = 100_000;
14
+ const FALLBACK_SECRET = "imsofa.rocks";
15
+ const FALLBACK_MAGIC = Buffer.from("CLFK1", "utf8");
16
+
17
+ /** 由 PIN + hex salt 衍生 AES-256 key */
18
+ function deriveKey(pin, salt) {
19
+ return crypto.pbkdf2Sync(String(pin), String(salt), PBKDF2_ITERATIONS, 32, "sha256");
20
+ }
21
+
22
+ /**
23
+ * 解密 Teacher credential { iv, ciphertext, tag }(皆 hex)。
24
+ * 失敗(PIN 錯誤 / 封包被改)丟 Error。
25
+ */
26
+ function decryptCredential(key, packet) {
27
+ const iv = Buffer.from(packet.iv, "hex");
28
+ const ciphertext = Buffer.from(packet.ciphertext, "hex");
29
+ const tag = Buffer.from(packet.tag, "hex");
30
+ try {
31
+ const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
32
+ decipher.setAuthTag(tag);
33
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
34
+ } catch {
35
+ throw new Error("credential 解密失敗(PIN 或封包不正確)");
36
+ }
37
+ }
38
+
39
+ /** SHA256("imsofa.rocks") → 32-byte AES key(teacher 端相同) */
40
+ function deriveFallbackKey() {
41
+ return crypto.createHash("sha256").update(FALLBACK_SECRET, "utf8").digest();
42
+ }
43
+
44
+ /**
45
+ * 解開 fallback.bin → API key;格式錯誤/驗證失敗丟 Error。
46
+ */
47
+ function decryptFallbackBin(data) {
48
+ if (data.length < FALLBACK_MAGIC.length + 12 + 16 || !data.subarray(0, FALLBACK_MAGIC.length).equals(FALLBACK_MAGIC)) {
49
+ throw new Error("fallback.bin 格式不正確");
50
+ }
51
+ const iv = data.subarray(FALLBACK_MAGIC.length, FALLBACK_MAGIC.length + 12);
52
+ const tag = data.subarray(data.length - 16);
53
+ const ciphertext = data.subarray(FALLBACK_MAGIC.length + 12, data.length - 16);
54
+ try {
55
+ const decipher = crypto.createDecipheriv("aes-256-gcm", deriveFallbackKey(), iv);
56
+ decipher.setAuthTag(tag);
57
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
58
+ } catch {
59
+ throw new Error("fallback.bin 解密失敗");
60
+ }
61
+ }
62
+
63
+ module.exports = {
64
+ PBKDF2_ITERATIONS,
65
+ FALLBACK_SECRET,
66
+ FALLBACK_MAGIC,
67
+ deriveKey,
68
+ decryptCredential,
69
+ deriveFallbackKey,
70
+ decryptFallbackBin,
71
+ };
package/relay/state.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Relay Current State(與 Python 版 student/relay/state.py 對齊)。
3
+ *
4
+ * - template_name/template_version 代表「已安裝成功」的樣板(heartbeat 回報 Teacher 的版本)。
5
+ * - pending_* 為「剛收到、尚未安裝」的樣板內容;安裝成功才前進 installed。
6
+ * - request_limit / model routing 由 Teacher config 套用(fallback 模式會強制 free)。
7
+ */
8
+ "use strict";
9
+
10
+ const DEFAULT_PRIMARY_MODEL = "openrouter/free";
11
+ const DEFAULT_FALLBACK_MODELS = []; // 預設不注入 models(純 free 路徑)
12
+
13
+ function timeNowMs() {
14
+ return Date.now();
15
+ }
16
+
17
+ class RelayState {
18
+ constructor(relayId = "") {
19
+ this.relayId = relayId;
20
+ this.studentId = "";
21
+ this.status = "enabled"; // enabled | disabled
22
+ this.requestLimit = { "5m": 20, "30m": 80, "60m": 120 };
23
+ this.policyVersion = 0;
24
+ this.primaryModel = DEFAULT_PRIMARY_MODEL;
25
+ this.models = [...DEFAULT_FALLBACK_MODELS];
26
+ this.modelRoutingVersion = 0;
27
+ // installed(安裝成功)template
28
+ this.templateName = null;
29
+ this.templateVersion = 0;
30
+ // clock
31
+ this.serverTime = 0;
32
+ this.serverTimeLocal = 0;
33
+ this.credential = null;
34
+ // pending(已收到未安裝)
35
+ this.pendingTemplateName = null;
36
+ this.pendingTemplateVersion = 0;
37
+ this.pendingTemplateFiles = {};
38
+ this.pendingTemplateZipB64 = null;
39
+ }
40
+
41
+ /** serverTime - localTime(>0 表示伺服器時鐘領先) */
42
+ clockOffsetMs() {
43
+ return this.serverTime - this.serverTimeLocal;
44
+ }
45
+
46
+ /** 以 Teacher clock 校正後的現在時間 */
47
+ effectiveNowMs() {
48
+ return timeNowMs() + this.clockOffsetMs();
49
+ }
50
+
51
+ /** 套用 Teacher config payload */
52
+ applyConfig(payload = {}) {
53
+ if (payload.status !== undefined) this.status = payload.status;
54
+ if (payload.requestLimit) this.requestLimit = payload.requestLimit;
55
+ if (payload.policyVersion !== undefined) this.policyVersion = payload.policyVersion;
56
+ const routing = payload.modelRouting;
57
+ if (routing && typeof routing === "object") {
58
+ if (routing.primary !== undefined) this.primaryModel = routing.primary;
59
+ if (Array.isArray(routing.models)) this.models = [...routing.models];
60
+ }
61
+ if (payload.modelRoutingVersion !== undefined) {
62
+ this.modelRoutingVersion = payload.modelRoutingVersion;
63
+ }
64
+ // 兼容舊 teacher(現行已不於 config 帶 template 資訊,改由 project-template 下發)
65
+ if (payload.template !== undefined) this.templateName = payload.template;
66
+ if (payload.projectTemplateVersion !== undefined) {
67
+ this.templateVersion = payload.projectTemplateVersion;
68
+ }
69
+ if (payload.serverTime) this.updateServerTime(payload.serverTime);
70
+ if (payload.credential) this.credential = payload.credential;
71
+ }
72
+
73
+ updateServerTime(serverTime) {
74
+ if (!serverTime) return;
75
+ this.serverTime = serverTime;
76
+ this.serverTimeLocal = timeNowMs();
77
+ }
78
+ }
79
+
80
+ module.exports = { RelayState, DEFAULT_PRIMARY_MODEL, DEFAULT_FALLBACK_MODELS, timeNowMs };
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Project Template 套用(與 Python 版對齊)。
3
+ *
4
+ * - zip 來源:teacher 的 STORE zip(支援 method 0/8;UTF-8 檔名)。
5
+ * - 只覆蓋 template 內的檔案;template 以外的檔案不動。
6
+ * - 嚴格原子性:staging → 備份 → 逐檔 replace → 失敗回滾,不留半套用。
7
+ * - zip-slip 防護:拒絕絕對路徑 / `..` / 磁碟機路徑 / `~` 開頭。
8
+ */
9
+ "use strict";
10
+
11
+ const fs = require("fs");
12
+ const path = require("path");
13
+ const zlib = require("zlib");
14
+ const crypto = require("crypto");
15
+
16
+ /** zip entry 安全檢查 */
17
+ function isSafeEntry(name) {
18
+ if (!name || name.startsWith("/") || name.startsWith("\\")) return false;
19
+ const normalized = name.replace(/\\/g, "/");
20
+ const parts = normalized.split("/");
21
+ if (parts.includes("..")) return false;
22
+ if (normalized.length > 1 && /^[A-Za-z]:/.test(normalized)) return false;
23
+ return !normalized.startsWith("~");
24
+ }
25
+
26
+ /**
27
+ * 解析 zip(STORE / DEFLATE)→ { 相對路徑: Buffer }(略過不安全/目錄)。
28
+ */
29
+ function readZipEntries(zipBuffer) {
30
+ // 找 EOCD(從檔尾往前掃)
31
+ let eocd = -1;
32
+ for (let i = zipBuffer.length - 22; i >= 0; i--) {
33
+ if (zipBuffer.readUInt32LE(i) === 0x06054b50) {
34
+ eocd = i;
35
+ break;
36
+ }
37
+ }
38
+ if (eocd < 0) throw new Error("invalid zip: EOCD not found");
39
+
40
+ const count = zipBuffer.readUInt16LE(eocd + 10);
41
+ const cdOffset = zipBuffer.readUInt32LE(eocd + 16);
42
+ const entries = {};
43
+ let p = cdOffset;
44
+ for (let i = 0; i < count; i++) {
45
+ if (zipBuffer.readUInt32LE(p) !== 0x02014b50) throw new Error("invalid zip: bad central header");
46
+ const method = zipBuffer.readUInt16LE(p + 10);
47
+ const compSize = zipBuffer.readUInt32LE(p + 20);
48
+ const nameLen = zipBuffer.readUInt16LE(p + 28);
49
+ const extraLen = zipBuffer.readUInt16LE(p + 30);
50
+ const commentLen = zipBuffer.readUInt16LE(p + 32);
51
+ const localOffset = zipBuffer.readUInt32LE(p + 42);
52
+ const name = zipBuffer.subarray(p + 46, p + 46 + nameLen).toString("utf8");
53
+ p += 46 + nameLen + extraLen + commentLen;
54
+
55
+ if (name.endsWith("/")) continue; // 目錄
56
+ if (!isSafeEntry(name)) continue;
57
+
58
+ if (zipBuffer.readUInt32LE(localOffset) !== 0x04034b50) throw new Error("invalid zip: bad local header");
59
+ const localNameLen = zipBuffer.readUInt16LE(localOffset + 26);
60
+ const localExtraLen = zipBuffer.readUInt16LE(localOffset + 28);
61
+ const dataStart = localOffset + 30 + localNameLen + localExtraLen;
62
+ const raw = zipBuffer.subarray(dataStart, dataStart + compSize);
63
+ if (method === 0) {
64
+ entries[name] = Buffer.from(raw);
65
+ } else if (method === 8) {
66
+ entries[name] = zlib.inflateRawSync(raw);
67
+ } else {
68
+ throw new Error(`unsupported zip compression method: ${method}`);
69
+ }
70
+ }
71
+ return entries;
72
+ }
73
+
74
+ /**
75
+ * 原子式安裝檔案。
76
+ * @param {Record<string, Buffer>} entries 相對路徑 → 內容
77
+ * @param {string} targetFolder
78
+ * @param {{replace?:(src:string,dst:string)=>void}} [ops] 測試可注入 replace
79
+ * @returns {string[]} 實際套用的路徑
80
+ */
81
+ function installEntriesAtomic(entries, targetFolder, ops = {}) {
82
+ const replace = ops.replace || fs.renameSync;
83
+ const target = path.resolve(targetFolder);
84
+ fs.mkdirSync(target, { recursive: true });
85
+ const parent = path.dirname(target);
86
+ const suffix = crypto.randomBytes(8).toString("hex");
87
+ const staging = path.join(parent, `.relay-staging-${suffix}`);
88
+ const backup = path.join(parent, `.relay-backup-${suffix}`);
89
+
90
+ const rels = Object.keys(entries).sort();
91
+ const applied = [];
92
+ try {
93
+ // 1) 完整寫入 staging(失敗 → target 完全未動)
94
+ for (const rel of rels) {
95
+ const dest = path.resolve(staging, rel);
96
+ if (!dest.startsWith(path.resolve(staging) + path.sep)) continue;
97
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
98
+ fs.writeFileSync(dest, entries[rel]);
99
+ }
100
+ // 2) 備份將被覆蓋的既有檔
101
+ fs.mkdirSync(backup, { recursive: true });
102
+ for (const rel of rels) {
103
+ const existing = path.join(target, rel);
104
+ if (fs.existsSync(existing) && fs.statSync(existing).isFile()) {
105
+ const bdest = path.join(backup, rel);
106
+ fs.mkdirSync(path.dirname(bdest), { recursive: true });
107
+ fs.copyFileSync(existing, bdest);
108
+ }
109
+ }
110
+ // 3) 逐檔原子套用
111
+ for (const rel of rels) {
112
+ const src = path.join(staging, rel);
113
+ if (!fs.existsSync(src)) continue;
114
+ const dest = path.join(target, rel);
115
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
116
+ replace(src, dest);
117
+ applied.push(rel);
118
+ }
119
+ return applied;
120
+ } catch (e) {
121
+ // 4) 回滾
122
+ for (const rel of applied) {
123
+ const bsrc = path.join(backup, rel);
124
+ try {
125
+ if (fs.existsSync(bsrc)) replace(bsrc, path.join(target, rel));
126
+ else fs.rmSync(path.join(target, rel), { force: true });
127
+ } catch {
128
+ /* 盡力而為 */
129
+ }
130
+ }
131
+ throw e;
132
+ } finally {
133
+ fs.rmSync(staging, { recursive: true, force: true });
134
+ fs.rmSync(backup, { recursive: true, force: true });
135
+ }
136
+ }
137
+
138
+ /** 文字 map(files)原子式套用 */
139
+ function applyTemplate(files, targetFolder, ops = {}) {
140
+ const entries = {};
141
+ for (const [rel, content] of Object.entries(files || {})) {
142
+ if (isSafeEntry(rel)) entries[rel] = Buffer.from(String(content), "utf8");
143
+ }
144
+ return installEntriesAtomic(entries, targetFolder, ops);
145
+ }
146
+
147
+ /** zip 原子式解壓 */
148
+ function extractTemplateZip(zipBuffer, targetFolder, ops = {}) {
149
+ return installEntriesAtomic(readZipEntries(zipBuffer), targetFolder, ops);
150
+ }
151
+
152
+ module.exports = {
153
+ isSafeEntry,
154
+ readZipEntries,
155
+ installEntriesAtomic,
156
+ applyTemplate,
157
+ extractTemplateZip,
158
+ };