@myrialabs/clopen 0.3.13 → 0.3.14

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,36 @@
1
+ [← Engine adapter guide](../README.md)
2
+
3
+ ## 10. Quick reference table
4
+
5
+ | Need | File |
6
+ |---------------------------------------------|-----------------------------------------------------------|
7
+ | Lazy + concurrency-safe init | `claude/environment.ts::setupEnvironmentOnce`, `opencode/server.ts::ensureClient` |
8
+ | Per-account credential override (env-var SDK) | `claude/environment.ts::getEngineEnv(accountId)` |
9
+ | Per-account credential override (constructor SDK) | `copilot/stream.ts::initialize(accountId)` + dispose+reinit in `streamQuery` |
10
+ | Subprocess spawn + health + recovery | `opencode/server.ts` |
11
+ | Stateful per-stream converter | `claude/message-converter.ts::createSdkMessageConverter` |
12
+ | Split one SDK message → N `EngineOutput` | `opencode/message-converter.ts::convertAssistantMessages`, `copilot/message-converter.ts::convertAssistantMessage` |
13
+ | Buffer until usage event arrives | `copilot/message-converter.ts::flushPending` + `captureUsage` |
14
+ | Reasoning stream lifecycle | `opencode/stream.ts::flushReasoning`, `copilot/message-converter.ts::convertReasoningDelta` |
15
+ | Cancel-before-RPC ordering | `opencode/stream.ts::cancel`, `claude/stream.ts::cancel`, `copilot/stream.ts::cancel` |
16
+ | Fork session (native vs. on-disk workaround) | `claude/stream.ts` (`forkSession: true`), `opencode/stream.ts` (`client.session.fork`), `copilot/stream.ts` (`client.rpc.sessions.fork`), `codex/session-fork.ts` + `qwen/session-fork.ts` (copy disk state) |
17
+ | Sub-agent (`Task`/`Agent`) routing | `claude/message-converter.ts` (`parent_tool_use_id`), `opencode/message-converter.ts::convertSubtaskToolUseOnly`, `copilot/message-converter.ts::resolveParentToolUseId` + `agentParentMap` (see §9.15) |
18
+ | AskUserQuestion event + HTTP fallback | `opencode/stream.ts::resolveUserAnswer`, `claude/stream.ts::canUseTool` |
19
+ | MCP servers exposed over HTTP (single source) | `backend/mcp/remote-server.ts`, `backend/mcp/config.ts::getOpenCodeMcpConfig` (and future `getXxxMcpConfig`) |
20
+ | Auth-blob swap into shared CLI dotfile | Pattern only (no implementation yet); see §3.3 callout + §9.13 |
21
+ | Restart-Server pattern (long-lived engines) | `backend/ws/engine/opencode/providers.ts::engine:opencode-server-restart`, `frontend/components/chat/input/components/EngineModelPicker.svelte::restartOCServer`, `AIEnginesSettings.svelte::handleRestartServer`/`forceRestartServer` |
22
+ | `generateStructured` (no tools, JSON) | `claude/stream.ts::generateStructured` (native `outputFormat`), `codex/stream.ts::generateStructured` (native `outputSchema`), `opencode/stream.ts::generateStructured` + `copilot/stream.ts::generateStructured` + `qwen/stream.ts::generateStructured` (prompt-engineered via `backend/engine/structured-helpers.ts`). See §9.16 for the strict-schema + part-fallback gotchas. |
23
+ | Error normalisation | `claude/error-handler.ts`, `copilot/error-handler.ts`, `opencode/error-handler.ts`, `qwen/error-handler.ts`, `codex/error-handler.ts` |
24
+ | DB provider/account access | `backend/database/queries/engine-queries.ts` |
25
+ | Per-platform install recipe | `backend/engine/install-recipes.ts` |
26
+ | Streaming install logs | `backend/engine/install-runner.ts` |
27
+ | Frontend account/provider stores | `frontend/stores/features/{claude-accounts,copilot-accounts,opencode-providers}.svelte.ts` |
28
+ | Frontend chat-model state | `frontend/stores/ui/chat-model.svelte.ts` |
29
+ | Settings UI (Engines) | `frontend/components/settings/engines/AIEnginesSettings.svelte` |
30
+ | Settings UI (System Tools) | `frontend/components/settings/system-tools/{SystemToolsSettings,ToolInstallCard}.svelte` |
31
+ | Chat picker (engine + model + account) | `frontend/components/chat/input/components/EngineModelPicker.svelte` |
32
+ | Chat send → backend | `frontend/services/chat/chat.service.ts` (`ws.emit('chat:stream', …)`), `backend/ws/chat/stream.ts` |
33
+ | Stream-manager (`EngineOutput` routing) | `backend/chat/stream-manager.ts` |
34
+
35
+ When in doubt: **mirror** the existing adapters and let `EngineOutput`
36
+ remain the only contract that crosses the adapter boundary.
@@ -0,0 +1,82 @@
1
+ [← Engine adapter guide](../README.md)
2
+
3
+ ## 7. Registering a binary in System Tools (`install-recipes.ts`)
4
+
5
+ `install-recipes.ts` is a **declarative** registry of install commands.
6
+ `install-runner.ts` is what actually runs them.
7
+
8
+ ### 7.1 Anatomy of a `Recipe`
9
+
10
+ ```ts
11
+ interface Recipe {
12
+ tool: ToolId;
13
+ autoInstallable: boolean;
14
+ unavailableReason?: string; // shown when not auto-installable
15
+ command?: string[]; // argv for Bun.spawn
16
+ shell?: { program; args }; // wrap argv (sh -c, pwsh -Command)
17
+ requiresCurl?: boolean; // staged static-curl if needed
18
+ pendingCurlDownload?: { version, url, sha256, archKey };
19
+ displayCommand?: string; // string for the confirm dialog
20
+ env?: Record<string, string>; // extra env for the subprocess
21
+ missingPrereqs: ToolId[];
22
+ manualInstructions: ManualInstruction[]; // always present (copy-able fallback)
23
+ }
24
+ ```
25
+
26
+ ### 7.2 Per-platform pattern
27
+
28
+ `resolveRecipe(tool)` switches to a per-tool resolver. Each resolver:
29
+ 1. Builds `base: Recipe` with full `manualInstructions` (always provide a
30
+ fallback for users on unsupported OSes).
31
+ 2. Checks platform (`process.platform`) and package manager:
32
+ - macOS: `brew`
33
+ - Linux: `apt | dnf | pacman | apk | zypper` (`detectLinuxPkgMgr`)
34
+ - Windows: `winget | scoop | choco` (`detectWindowsPkgMgr`)
35
+ 3. Checks privilege via `isElevated()` if the package manager needs
36
+ root/admin.
37
+ 4. If the installer uses `curl`, calls `attachCurlRequirement(base, label)`
38
+ so the runner can stage SHA-pinned static-curl from
39
+ `static-curl-assets.ts` when the system has no curl.
40
+ 5. Sets `autoInstallable = true` + `command` + `shell` + `displayCommand`,
41
+ or leaves it `false` with `unavailableReason` so the UI renders manual
42
+ instructions only.
43
+
44
+ ### 7.3 Status detection
45
+
46
+ `getToolStatus(tool)` returns `{ tool, installed, version, source }`:
47
+ - `chrome` has a special path (puppeteer cache scan + system Chrome).
48
+ - `cloudflared` at `~/.clopen/bin/cloudflared` is marked `source: 'clopen'`.
49
+ - Otherwise `resolveBinaryWithRefresh(tool)` + `runVersion(resolved)`.
50
+
51
+ ### 7.4 Runner
52
+
53
+ `install-runner.ts::startInstall(tool, userId)`:
54
+ 1. Verifies no other session is active for this tool
55
+ (`InstallAlreadyRunningError`).
56
+ 2. Resolves the recipe, validates `autoInstallable && command`
57
+ (`InstallNotAutoInstallableError`).
58
+ 3. If `requiresCurl`, calls `ensureCurlAvailable(...)` (downloads
59
+ pinned static-curl if needed, prepends its dir to PATH).
60
+ 4. `Bun.spawn(spawnArgs, { stdout: 'pipe', stderr: 'pipe', stdin: 'ignore', env })`.
61
+ 5. Streams stdout/stderr per-line into a ring buffer (10k lines) + emits
62
+ `system-tools:install-stream` to the user room.
63
+ 6. On exit: emits `system-tools:install-finished` + retains the session
64
+ for 5 minutes for re-attach.
65
+
66
+ Exit-code hints (`explainFailure(137|143, cancelled)`) explain SIGKILL OOM
67
+ or SIGTERM with actual total/free memory readings.
68
+
69
+ ### 7.5 Adding a new tool
70
+
71
+ 1. Add the literal to `ToolId` (`'goose'`).
72
+ 2. Write `resolveGooseRecipe(): Promise<Recipe>` following the
73
+ `resolveOpenCodeRecipe` pattern.
74
+ 3. Add a case in `resolveRecipe(tool)`.
75
+ 4. Add the literal to `TOOL_UNION` (`status.ts`, `install.ts`).
76
+ 5. Add `<ToolInstallCard tool="goose" ... />` in
77
+ `SystemToolsSettings.svelte`.
78
+ 6. (Optional) detect in `engine:<engine>-status` so Settings → Engines
79
+ knows the binary is installed.
80
+
81
+ ---
82
+
@@ -0,0 +1,240 @@
1
+ [← Engine adapter guide](../README.md)
2
+
3
+ ## 4. WebSocket routes
4
+
5
+ All handlers use `createRouter()` (Elysia + ws-server). Routers are merged
6
+ in `backend/ws/index.ts`. Four groups are relevant for engines:
7
+
8
+ | Group | Path | Purpose |
9
+ |---------------------------------|-------------------------------------|--------------------------------------------|
10
+ | `engine:claude-*` | `backend/ws/engine/claude/` | Status + Claude account CRUD |
11
+ | `engine:opencode-*` | `backend/ws/engine/opencode/` | Status + provider/account CRUD + restart |
12
+ | `engine:copilot-*` | `backend/ws/engine/copilot/` | Status + Copilot account CRUD |
13
+ | `system-tools:*` | `backend/ws/system-tools/` | Detect/install binaries |
14
+ | `models:list`, `chat:stream` | `backend/ws/settings/crud.ts`, `backend/ws/chat/stream.ts` | Model fetch + stream start |
15
+
16
+ ### 4.1 Claude — `engine:claude-*`
17
+
18
+ `backend/ws/engine/claude/index.ts` merges two sub-handlers:
19
+
20
+ | Event | Mode | Purpose |
21
+ |---------------------------------------------|---------|-----------------------------------------------|
22
+ | `engine:claude-status` | `.http` | `{ installed, version, activeAccount, accountsCount, backendOS }` |
23
+ | `engine:claude-accounts-list` | `.http` | List Claude accounts |
24
+ | `engine:claude-accounts-switch` | `.http` | Set active; calls `resetEnvironment()` so a new token is picked up on the next stream |
25
+ | `engine:claude-accounts-delete` | `.http` | |
26
+ | `engine:claude-accounts-rename` | `.http` | |
27
+ | `engine:claude-account-setup-start` | `.on` | Spawn PTY `claude setup-token` (state machine `waiting-url → waiting-token → done`) |
28
+ | `engine:claude-account-setup-submit` | `.on` | Send the auth code to the PTY |
29
+ | `engine:claude-account-setup-cancel` | `.on` | |
30
+ | `engine:claude-account-setup-url` (emit) | | OAuth URL detected in PTY output |
31
+ | `engine:claude-account-setup-complete` (emit) | | Token success → `engineQueries.createAccount` + `resetEnvironment()` |
32
+ | `engine:claude-account-setup-error` (emit) | | |
33
+ | `engine:claude-account-setup-pty-data` (emit) | | Stream raw PTY (debug) |
34
+
35
+ The Claude setup flow needs a PTY because Anthropic's CLI is interactive.
36
+ See `backend/ws/engine/claude/accounts.ts` for the state-machine details
37
+ (one `onData` listener + one `onExit` per session, the phase tracked in a
38
+ `phase` field).
39
+
40
+ ### 4.2 OpenCode — `engine:opencode-*`
41
+
42
+ `backend/ws/engine/opencode/index.ts` merges:
43
+
44
+ | Event | Purpose |
45
+ |---------------------------------------------|-----------------------------------------------|
46
+ | `engine:opencode-status` | `{ installed, version, backendOS }` |
47
+ | `engine:opencode-providers-list` | List `engine_providers WHERE engine_type='opencode'` + accounts |
48
+ | `engine:opencode-provider-add` | Create provider + first account (auto-active) |
49
+ | `engine:opencode-provider-remove` | Cascades to accounts |
50
+ | `engine:opencode-provider-toggle` | Flip `is_enabled` |
51
+ | `engine:opencode-provider-update-options` | Update JSON options (handler validates JSON) |
52
+ | `engine:opencode-account-add` | Add an account to a provider |
53
+ | `engine:opencode-account-switch` | |
54
+ | `engine:opencode-account-delete` | |
55
+ | `engine:opencode-account-rename` | |
56
+ | `engine:opencode-models-dev-list` | Cached catalog (auto-fetches if absent) |
57
+ | `engine:opencode-models-dev-fetch` | Force refetch |
58
+ | `engine:opencode-server-restart` | Stop subprocess + clear stored URL → next stream spawns a fresh server |
59
+
60
+ `engine:opencode-server-restart` first checks whether any OpenCode stream
61
+ is active: if so and `force` was not set, it returns
62
+ `{ needsConfirmation: true, activeChats: N }` so the UI can ask for
63
+ confirmation. When `force=true`, all OpenCode streams are `cancelStream`'d,
64
+ followed by `disposeEngine('opencode')` + `disposeOpenCodeClient(true)` —
65
+ the `forRestart` flag drops the stored URL and kills the server even if
66
+ Clopen did not spawn it (the reuse case).
67
+
68
+ #### Restart-Server pattern (long-lived server engines)
69
+
70
+ Engines that hold a **long-lived process or client** (OpenCode's `opencode
71
+ serve` subprocess, Copilot's `CopilotClient`) cache provider/account
72
+ credentials at boot or construction time. Adding, removing, or switching
73
+ an account does **not** automatically take effect for in-flight streams or
74
+ the cached client — the engine must be **restarted**. The adapter exposes
75
+ a `*-server-restart` event; the UI surfaces this to the user as a
76
+ **"Restart Server"** button in two places:
77
+
78
+ 1. **Settings → Engines** card — shown whenever the user has just changed
79
+ provider/account state (add / remove / switch). See
80
+ `AIEnginesSettings.svelte::handleRestartServer` (with the
81
+ `needsConfirmation` confirm-dialog flow) and
82
+ `forceRestartServer`.
83
+ 2. **Chat Input → next to the model/account picker** — shown when the
84
+ active session's account has just been switched mid-flight and the
85
+ user needs to apply it before sending the next prompt. See
86
+ `EngineModelPicker.svelte::ocNeedsRestart` / `restartOCServer`. The
87
+ button uses `force: true` so users in chat don't see another modal.
88
+
89
+ The handler contract any restart event must follow:
90
+
91
+ | Step | Behavior |
92
+ |---|---|
93
+ | 1 | Inspect the engine's active streams. If any exist and `force !== true`, return `{ needsConfirmation: true, activeChats: N }` — UI then opens a confirm dialog. |
94
+ | 2 | When `force === true`, call `cancelStream` on every active stream for that engine. |
95
+ | 3 | Call `disposeEngine(engineType)` (clears the per-project map) and any adapter-specific shared-resource cleanup (`disposeOpenCodeClient(true)`, etc.). The flag tells the cleanup routine that this is a restart, not a shutdown — drop cached URLs / sockets even if reused from outside. |
96
+ | 4 | Resolve. The next `streamQuery` call will lazy-init the engine fresh against the new account state. |
97
+
98
+ After a successful restart the UI also refreshes models
99
+ (`modelStore.refreshModels(engineType)`) because the model catalog can
100
+ change with the credential.
101
+
102
+ **When a new engine does NOT need this:** if the engine spawns a
103
+ **fresh subprocess per turn** (Codex's `codex exec`, Claude's per-turn
104
+ `query()`), the credential is re-read at every turn and there is nothing
105
+ to "restart". Such engines do not implement `*-server-restart`. The
106
+ appropriate analog for shared-CLI-dotfile engines like Codex is the
107
+ auth-blob swap (§9.13) — performed inside `accounts-switch`, not via a
108
+ separate restart event.
109
+
110
+ ### 4.3 Copilot — `engine:copilot-*`
111
+
112
+ `backend/ws/engine/copilot/index.ts` merges:
113
+
114
+ | Event | Purpose |
115
+ |--------------------------------------|-----------------------------------------------|
116
+ | `engine:copilot-status` | `{ installed, version, activeAccount, accountsCount, backendOS }` |
117
+ | `engine:copilot-accounts-list` | List Copilot accounts |
118
+ | `engine:copilot-accounts-add` | Add account by submitting a GitHub PAT |
119
+ | `engine:copilot-accounts-switch` | Set active |
120
+ | `engine:copilot-accounts-delete` | |
121
+ | `engine:copilot-accounts-rename` | |
122
+ | `engine:copilot-server-restart` | Restart cached `CopilotClient` so a new PAT applies — same Restart-Server pattern as §4.2 |
123
+
124
+ The Copilot setup flow does not need a PTY — the user pastes a GitHub
125
+ Personal Access Token in the UI (Copilot Requests + read:user scope), and
126
+ the handler stores it via `engineQueries.createAccount`. No re-auth dance.
127
+
128
+ Copilot follows the **same Restart-Server pattern** documented in §4.2
129
+ because `CopilotClient` takes the PAT at construction time. Account
130
+ add / remove / switch flips a `needsRestart` flag in the UI that surfaces
131
+ a "Restart Server" button in both Settings → Engines and Chat Input.
132
+
133
+ ### 4.4 System Tools — `system-tools:*`
134
+
135
+ `backend/ws/system-tools/`:
136
+
137
+ | Event | Purpose |
138
+ |------------------------------------|---------------------------------------------|
139
+ | `system-tools:status` | Detect a single tool: `{ status, recipe, activeSession }` |
140
+ | `system-tools:status-all` | Hardcoded list `['git','claude','opencode','chrome','cloudflared']` |
141
+ | `system-tools:install-start` | Spawn the recipe via `install-runner` |
142
+ | `system-tools:install-cancel` | |
143
+ | `system-tools:install-session` | Snapshot session (for re-attach) |
144
+ | `system-tools:install-started` (emit) | Session begun |
145
+ | `system-tools:install-stream` (emit) | Per-line stdout/stderr |
146
+ | `system-tools:install-finished` (emit) | exit code + final status |
147
+
148
+ ### 4.5 `models:list` (in `backend/ws/settings/crud.ts`)
149
+
150
+ ```ts
151
+ .http('models:list', { data: { engine } }, async ({ data }) => {
152
+ const engine = await initializeEngine(data.engine);
153
+ const models = await engine.getAvailableModels();
154
+ registerModels(data.engine, models);
155
+ return models;
156
+ })
157
+ ```
158
+
159
+ The handler is **uniform across engines** — no per-engine short-circuits.
160
+ Every engine flows through `initializeEngine` → `engine.getAvailableModels()`
161
+ → `registerModels(...)` so the shared in-memory `modelRegistry` is always
162
+ populated regardless of whether the catalog is static or dynamic.
163
+
164
+ > **Why uniform.** The previous version hard-coded `if (engine === 'claude-code') return CLAUDE_CODE_MODELS`
165
+ > for static engines. That short-circuit bypassed `registerModels()`, so the
166
+ > backend registry stayed empty for static engines and the frontend's
167
+ > `getByEngine('claude-code')` returned nothing — the symptom that motivated
168
+ > this whole standardization. Don't reintroduce the special case; if a static
169
+ > engine's `getAvailableModels()` is too expensive to call repeatedly, cache
170
+ > inside the adapter (`CLAUDE_CODE_MODELS` is already a module-level const,
171
+ > so the call is free).
172
+
173
+ Each engine owns its model catalog in `backend/engine/adapters/<engine>/models.ts`:
174
+
175
+ | Engine | Catalog kind | Source |
176
+ |---------------|--------------|-----------------------------------------------------|
177
+ | `claude-code` | static | hardcoded `CLAUDE_CODE_MODELS` array |
178
+ | `codex` | static | hardcoded `CODEX_MODELS` array |
179
+ | `copilot` | dynamic | `client.listModels()` via `fetchCopilotModels` |
180
+ | `opencode` | dynamic | `client.config.providers()` via `fetchOpenCodeModels`|
181
+ | `qwen` | dynamic | OpenAI-compatible `/models` via `fetchQwenModels` |
182
+
183
+ Failure-mode contract (dynamic engines): return `EngineModel[]` and use
184
+ `[]` as the failure sentinel — never `null` (see §2.6). The picker then
185
+ renders an empty list rather than a stale cached catalog. `fetchOpenCodeModels`
186
+ and `fetchQwenModels` already follow this; new dynamic fetchers must too.
187
+
188
+ ### 4.6 Engine-specific config (presets — multi-provider / multi-region)
189
+
190
+ Anything else an engine needs that the frontend has to render — provider
191
+ choice, region selection, BYOK templates — also lives with the adapter
192
+ rather than `shared/constants/engines.ts`. The canonical filename is
193
+ `presets.ts` (see §2.6). Two adapters use this slot:
194
+
195
+ - **Qwen** (`backend/engine/adapters/qwen/presets.ts`) — `QWEN_PROVIDER_PRESETS`
196
+ array (DashScope CN/INTL, OpenRouter, Fireworks), `DEFAULT_QWEN_PRESET`,
197
+ `getQwenPreset(id)`. Static, hardcoded.
198
+ - **OpenCode** (`backend/engine/adapters/opencode/presets.ts`) — the
199
+ models.dev provider catalog: `fetchAndCacheModelsDevCatalog()` +
200
+ `getCachedModelsDevCatalog()`. Dynamic (fetched + cached in `settings`).
201
+
202
+ The wire-format types (`QwenProviderPresetId`, `QwenProviderPreset`,
203
+ `ModelsDevProvider`) live in `shared/types/unified/engine.ts` (or are
204
+ re-exported there) so the frontend stays typed without importing from
205
+ `$backend`.
206
+
207
+ Each adapter that has a `presets.ts` ships a thin WS router exposing it:
208
+
209
+ | Engine | WS event | Frontend store |
210
+ |-----------|------------------------------------------|---------------------------------------------------|
211
+ | `qwen` | `engine:qwen-presets-list` | `qwenPresetsStore` (`frontend/stores/features/qwen-presets.svelte.ts`) |
212
+ | `opencode`| `engine:opencode-models-dev-list` (+ `…-fetch` to refresh) | `opencodeProvidersStore.catalog` (`frontend/stores/features/opencode-providers.svelte.ts`) |
213
+
214
+ The rule: **frontend never imports `$backend` directly**. Runtime values
215
+ the frontend needs (model lists, presets, …) flow through WS endpoints;
216
+ types flow through `$shared`.
217
+
218
+ ### 4.7 `chat:stream` — the streaming entry point
219
+
220
+ `backend/ws/chat/stream.ts` accepts:
221
+
222
+ ```ts
223
+ {
224
+ sessionId: string,
225
+ chatSessionId: string,
226
+ projectPath: string,
227
+ prompt: UserMessage,
228
+ engine: { type, provider, model: { id, name }, account: { id, name } },
229
+ sender: { id, name }
230
+ }
231
+ ```
232
+
233
+ The handler calls `streamManager.startStream(...)`, which then:
234
+ 1. Resolves `getProjectEngine(projectId, engine.type)`
235
+ 2. Calls `engine.streamQuery({ projectPath, prompt, providerSlug, modelId, accountId, mcpContext, ... })`
236
+ 3. Iterates over `EngineOutput` and emits each one to the chat session room
237
+ via `ws.emit.chatSession(...)`.
238
+
239
+ ---
240
+
@@ -0,0 +1,131 @@
1
+ import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
2
+ import { rm, mkdir } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { tmpdir } from 'node:os';
5
+
6
+ // Stub settingsQueries before importing the module under test so the file-size
7
+ // limit is controllable and never touches a real database during unit tests.
8
+ let mockSettingsRow: { key: string; value: string; updated_at: string } | null = null;
9
+ await mock.module('../database/queries', () => ({
10
+ settingsQueries: {
11
+ get: (_key: string) => mockSettingsRow,
12
+ getAll: () => [],
13
+ set: () => {},
14
+ delete: () => {}
15
+ }
16
+ }));
17
+
18
+ const { extractZipOperation } = await import('./file-archive');
19
+
20
+ function setLimitMB(mb: number): void {
21
+ mockSettingsRow = {
22
+ key: 'system:settings',
23
+ value: JSON.stringify({ maxFileSizeMB: mb }),
24
+ updated_at: ''
25
+ };
26
+ }
27
+
28
+ function writeU32(buf: Uint8Array, off: number, val: number): void {
29
+ buf[off] = val & 0xff;
30
+ buf[off + 1] = (val >>> 8) & 0xff;
31
+ buf[off + 2] = (val >>> 16) & 0xff;
32
+ buf[off + 3] = (val >>> 24) & 0xff;
33
+ }
34
+
35
+ function readU32(buf: Uint8Array, off: number): number {
36
+ return (buf[off] | (buf[off + 1] << 8) | (buf[off + 2] << 16) | (buf[off + 3] << 24)) >>> 0;
37
+ }
38
+
39
+ // Overwrite the uncompressed-size fields in a single-file zip's local and
40
+ // central headers with a forged (tiny) value, leaving the compressed data and
41
+ // compressed-size fields intact. Models an attacker lying about extracted size
42
+ // to slip past any check that trusts the zip metadata. Assumes no archive
43
+ // comment (true for fflate's zipSync output).
44
+ function forgeUncompressedSizes(zip: Uint8Array, fakeSize: number): Uint8Array {
45
+ const out = zip.slice();
46
+ const eocd = out.length - 22;
47
+ const cdOffset = readU32(out, eocd + 16);
48
+ writeU32(out, cdOffset + 24, fakeSize); // central directory header
49
+ writeU32(out, 22, fakeSize); // local file header (single file at offset 0)
50
+ return out;
51
+ }
52
+
53
+ describe('extractZipOperation — output-size cap', () => {
54
+ let testDir: string;
55
+
56
+ beforeEach(async () => {
57
+ mockSettingsRow = null;
58
+ testDir = join(tmpdir(), `clopen-archive-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
59
+ await mkdir(testDir, { recursive: true });
60
+ });
61
+
62
+ afterEach(async () => {
63
+ mockSettingsRow = null;
64
+ await rm(testDir, { recursive: true, force: true });
65
+ });
66
+
67
+ test('extracts a normal archive and writes its contents', async () => {
68
+ const { zipSync } = await import('fflate');
69
+ const zip = zipSync(
70
+ {
71
+ 'file1.txt': new TextEncoder().encode('Hello world, this is a test file'),
72
+ 'file2.txt': new TextEncoder().encode('Another test file with some content')
73
+ },
74
+ { level: 6 }
75
+ );
76
+ const archivePath = join(testDir, 'normal.zip');
77
+ const extractDir = join(testDir, 'extracted');
78
+ await Bun.write(archivePath, zip);
79
+
80
+ const result = await extractZipOperation(archivePath, extractDir);
81
+
82
+ expect(result.entries).toBe(2);
83
+ expect(await Bun.file(join(extractDir, 'file1.txt')).text()).toBe('Hello world, this is a test file');
84
+ expect(await Bun.file(join(extractDir, 'file2.txt')).text()).toBe('Another test file with some content');
85
+ });
86
+
87
+ test('rejects when actual decompressed output exceeds the limit', async () => {
88
+ // 4MB of zeros compresses to a few KB, so the compressed archive sails
89
+ // past the compressed-size guard — only the streaming output cap catches it.
90
+ setLimitMB(1);
91
+ const { zipSync } = await import('fflate');
92
+ const zip = zipSync({ 'big.bin': new Uint8Array(4 * 1024 * 1024) }, { level: 9 });
93
+ const archivePath = join(testDir, 'big.zip');
94
+ await Bun.write(archivePath, zip);
95
+
96
+ expect(zip.byteLength).toBeLessThan(1024 * 1024); // compressed archive is under the limit
97
+
98
+ await expect(extractZipOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(
99
+ /exceeds maximum allowed size/
100
+ );
101
+ });
102
+
103
+ test('rejects even when the zip metadata forges a tiny uncompressed size', async () => {
104
+ // The whole point of the reshape: the cap counts ACTUAL decompressed
105
+ // bytes, so lying about the size in the central directory cannot bypass it.
106
+ setLimitMB(1);
107
+ const { zipSync } = await import('fflate');
108
+ const honest = zipSync({ 'bomb.bin': new Uint8Array(4 * 1024 * 1024) }, { level: 9 });
109
+ const forged = forgeUncompressedSizes(honest, 10);
110
+
111
+ const eocd = forged.length - 22;
112
+ const cdOffset = readU32(forged, eocd + 16);
113
+ expect(readU32(forged, cdOffset + 24)).toBe(10); // metadata now claims 10 bytes
114
+
115
+ const archivePath = join(testDir, 'forged.zip');
116
+ await Bun.write(archivePath, forged);
117
+
118
+ await expect(extractZipOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(
119
+ /exceeds maximum allowed size/
120
+ );
121
+ });
122
+
123
+ test('rejects path-traversal entries before writing them', async () => {
124
+ const { zipSync } = await import('fflate');
125
+ const zip = zipSync({ '../escape.txt': new TextEncoder().encode('nope') }, { level: 6 });
126
+ const archivePath = join(testDir, 'traversal.zip');
127
+ await Bun.write(archivePath, zip);
128
+
129
+ await expect(extractZipOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(/Unsafe path/);
130
+ });
131
+ });
@@ -1,6 +1,6 @@
1
1
  import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
2
2
  import { mkdir, readdir, stat, writeFile } from 'node:fs/promises';
3
- import { zipSync, unzipSync } from 'fflate';
3
+ import { zipSync, Unzip, UnzipInflate, UnzipPassThrough } from 'fflate';
4
4
 
5
5
  import { debug } from '$shared/utils/logger';
6
6
  import { getMaxFileSize, validateFileSize } from './file-size-limit';
@@ -139,33 +139,7 @@ export async function extractZipOperation(archivePath: string, targetDir: string
139
139
  }
140
140
 
141
141
  const data = new Uint8Array(await archiveFile.arrayBuffer());
142
- const unzipped = unzipSync(data);
143
-
144
- let totalBytes = 0;
145
- for (const buf of Object.values(unzipped)) {
146
- totalBytes += buf.byteLength;
147
- if (totalBytes > limit) {
148
- throw new Error(`Extracted content exceeds maximum allowed size of ${limitMB}MB`);
149
- }
150
- }
151
-
152
- let entryCount = 0;
153
- for (const [entryPath, content] of Object.entries(unzipped)) {
154
- if (!isSafeEntryPath(entryPath, targetDir)) {
155
- throw new Error(`Unsafe path in archive: ${entryPath}`);
156
- }
157
- const normalized = entryPath.replace(/\\/g, '/');
158
- const isDirEntry = normalized.endsWith('/');
159
- const fullPath = join(targetDir, normalized.split('/').join(sep));
160
-
161
- if (isDirEntry) {
162
- await mkdir(fullPath, { recursive: true });
163
- continue;
164
- }
165
- await mkdir(dirname(fullPath), { recursive: true });
166
- await writeFile(fullPath, content);
167
- entryCount++;
168
- }
142
+ const entryCount = await extractWithinLimit(data, targetDir, limit, limitMB);
169
143
 
170
144
  const targetStats = await stat(targetDir);
171
145
  return {
@@ -189,3 +163,90 @@ export async function extractZipOperation(archivePath: string, targetDir: string
189
163
  }
190
164
  }
191
165
 
166
+ const STREAM_CHUNK_SIZE = 64 * 1024;
167
+
168
+ function concatChunks(chunks: Uint8Array[], total: number): Uint8Array {
169
+ const out = new Uint8Array(total);
170
+ let pos = 0;
171
+ for (const chunk of chunks) {
172
+ out.set(chunk, pos);
173
+ pos += chunk.length;
174
+ }
175
+ return out;
176
+ }
177
+
178
+ async function writeEntry(fullPath: string, content: Uint8Array): Promise<void> {
179
+ await mkdir(dirname(fullPath), { recursive: true });
180
+ await writeFile(fullPath, content);
181
+ }
182
+
183
+ /**
184
+ * Stream-extract a ZIP, aborting as soon as the running total of *actual*
185
+ * decompressed bytes exceeds the limit. Feeding the compressed data in small
186
+ * chunks bounds how much a single decode step can emit, so a crafted archive
187
+ * cannot allocate more than the limit before being rejected — unlike trusting
188
+ * the uncompressed-size fields in the central directory, which an attacker
189
+ * controls and can forge to defeat a pre-decompression size check.
190
+ */
191
+ async function extractWithinLimit(
192
+ data: Uint8Array,
193
+ targetDir: string,
194
+ limit: number,
195
+ limitMB: number
196
+ ): Promise<number> {
197
+ let totalBytes = 0;
198
+ let entryCount = 0;
199
+ let failure: Error | null = null;
200
+ const writes: Promise<void>[] = [];
201
+
202
+ const unzipper = new Unzip((file) => {
203
+ if (failure) return;
204
+
205
+ if (!isSafeEntryPath(file.name, targetDir)) {
206
+ failure = new Error(`Unsafe path in archive: ${file.name}`);
207
+ return;
208
+ }
209
+
210
+ const normalized = file.name.replace(/\\/g, '/');
211
+ const fullPath = join(targetDir, normalized.split('/').join(sep));
212
+
213
+ if (normalized.endsWith('/')) {
214
+ writes.push(mkdir(fullPath, { recursive: true }).then(() => undefined));
215
+ return;
216
+ }
217
+
218
+ const chunks: Uint8Array[] = [];
219
+ let fileBytes = 0;
220
+ file.ondata = (err, chunk, final) => {
221
+ if (failure) return;
222
+ if (err) {
223
+ failure = err;
224
+ return;
225
+ }
226
+ totalBytes += chunk.length;
227
+ if (totalBytes > limit) {
228
+ failure = new Error(`Extracted content exceeds maximum allowed size of ${limitMB}MB`);
229
+ return;
230
+ }
231
+ chunks.push(chunk);
232
+ fileBytes += chunk.length;
233
+ if (final) {
234
+ writes.push(writeEntry(fullPath, concatChunks(chunks, fileBytes)));
235
+ entryCount++;
236
+ }
237
+ };
238
+ file.start();
239
+ });
240
+ unzipper.register(UnzipInflate);
241
+ unzipper.register(UnzipPassThrough);
242
+
243
+ for (let offset = 0; offset < data.length && !failure; offset += STREAM_CHUNK_SIZE) {
244
+ const end = Math.min(offset + STREAM_CHUNK_SIZE, data.length);
245
+ unzipper.push(data.subarray(offset, end), end >= data.length);
246
+ }
247
+
248
+ if (failure) throw failure;
249
+ await Promise.all(writes);
250
+ return entryCount;
251
+ }
252
+
@@ -112,7 +112,7 @@ async function rmdir(path: string, options?: { recursive?: boolean }) {
112
112
  return rm(path, options);
113
113
  }
114
114
 
115
- export async function writeFileOperation(filePath: string, content: string) {
115
+ export async function writeFileOperation(filePath: string, content: string, baseModified?: string) {
116
116
  if (!filePath) {
117
117
  throw new Error('File path is required');
118
118
  }
@@ -125,6 +125,26 @@ export async function writeFileOperation(filePath: string, content: string) {
125
125
  const contentSize = Buffer.byteLength(content, 'utf8');
126
126
  validateFileSize(contentSize);
127
127
 
128
+ // Optimistic concurrency: if the caller told us which on-disk version their
129
+ // content is based on, refuse to overwrite when the file has since changed.
130
+ // Skipped when the file no longer exists (treated as a fresh create) or when
131
+ // no base token is supplied (explicit force-write).
132
+ if (baseModified) {
133
+ try {
134
+ const currentStats = await fsStat(filePath);
135
+ if (currentStats.mtime.toISOString() !== baseModified) {
136
+ throw new Error(
137
+ 'FILE_CONFLICT: file changed on disk since it was last loaded'
138
+ );
139
+ }
140
+ } catch (err) {
141
+ if (err instanceof Error && err.message.startsWith('FILE_CONFLICT')) {
142
+ throw err;
143
+ }
144
+ // stat failed because the file is gone — fall through and create it.
145
+ }
146
+ }
147
+
128
148
  try {
129
149
  debug.log('file', 'Writing file:', { filePath, contentLength: content.length });
130
150
  await Bun.write(filePath, content);