@myrialabs/clopen 0.4.6 → 0.4.8

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/backend/auth/session-invalidation.test.ts +17 -21
  2. package/backend/auth/session-invalidation.ts +10 -11
  3. package/backend/db-client/drivers/mysql.ts +21 -0
  4. package/backend/db-client/drivers/postgres.ts +20 -0
  5. package/backend/db-client/drivers/sqlite.ts +21 -0
  6. package/backend/db-client/drivers/types.ts +19 -0
  7. package/backend/db-client/query-executor.ts +89 -1
  8. package/backend/engine/adapters/claude/models.ts +46 -3
  9. package/backend/files/file-archive.test.ts +86 -26
  10. package/backend/files/file-archive.ts +214 -134
  11. package/backend/terminal/index.ts +2 -5
  12. package/backend/terminal/ptykit.ts +64 -0
  13. package/backend/tunnel/tunnel-config.ts +1 -1
  14. package/backend/utils/ws.ts +14 -0
  15. package/backend/ws/db-client/query-history-retention.test.ts +217 -0
  16. package/backend/ws/db-client/query.ts +77 -2
  17. package/backend/ws/files/write.ts +23 -7
  18. package/backend/ws/git/ignored.ts +65 -0
  19. package/backend/ws/git/index.ts +3 -1
  20. package/backend/ws/projects/crud.ts +4 -4
  21. package/backend/ws/system/operations.ts +23 -0
  22. package/backend/ws/terminal/index.ts +6 -33
  23. package/backend/ws/terminal/tunnel.ts +76 -0
  24. package/dist/assets/__vite-browser-external-BIHI7g3E.js +1 -0
  25. package/dist/assets/index-B_F_OgoC.js +1 -0
  26. package/dist/assets/index-jGo0X72U.js +1 -0
  27. package/dist/assets/{main-TYNK6Orl.js → main-BkCc3WEB.js} +321 -260
  28. package/dist/assets/main-CWDwET4x.css +1 -0
  29. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm +0 -0
  30. package/dist/index.html +2 -2
  31. package/package.json +7 -11
  32. package/shared/constants/engines.ts +4 -4
  33. package/shared/types/db-client/query.ts +33 -0
  34. package/shared/utils/db-client/split-sql.test.ts +88 -0
  35. package/shared/utils/db-client/split-sql.ts +132 -0
  36. package/backend/terminal/helpers.ts +0 -14
  37. package/backend/terminal/pty-manager.ts +0 -4
  38. package/backend/terminal/pty-session-manager.ts +0 -349
  39. package/backend/terminal/stream-manager.ts +0 -300
  40. package/backend/ws/terminal/access.ts +0 -56
  41. package/backend/ws/terminal/persistence.ts +0 -145
  42. package/backend/ws/terminal/session.ts +0 -470
  43. package/backend/ws/terminal/stream.ts +0 -82
  44. package/dist/assets/main-BkMrek4_.css +0 -1
@@ -7,11 +7,7 @@ const mockGetProjectChatSessions = mock(() => new Map());
7
7
  const mockEmitUser = mock(() => {});
8
8
 
9
9
  const mockKillSession = mock(() => {});
10
- const mockGetAllSessions = mock(() => [] as Array<{
11
- sessionId: string;
12
- projectId?: string;
13
- userId: string;
14
- }>);
10
+ const mockList = mock((_namespace: string) => [] as Array<{ sessionId: string }>);
15
11
 
16
12
  mock.module('$backend/utils/ws', () => ({
17
13
  ws: {
@@ -24,9 +20,9 @@ mock.module('$backend/utils/ws', () => ({
24
20
  }
25
21
  }));
26
22
 
27
- mock.module('$backend/terminal/pty-session-manager', () => ({
28
- ptySessionManager: {
29
- getAllSessions: mockGetAllSessions,
23
+ mock.module('$backend/terminal/ptykit', () => ({
24
+ ptyKitManager: {
25
+ list: mockList,
30
26
  killSession: mockKillSession
31
27
  }
32
28
  }));
@@ -38,7 +34,7 @@ describe('invalidateUserSessions', () => {
38
34
  mockGetProjectChatSessions.mockClear();
39
35
  mockEmitUser.mockClear();
40
36
  mockKillSession.mockClear();
41
- mockGetAllSessions.mockClear();
37
+ mockList.mockClear();
42
38
  });
43
39
 
44
40
  test('clears auth on all connections for a user', () => {
@@ -62,33 +58,33 @@ describe('invalidateUserSessions', () => {
62
58
  expect(cleared).toBe(0);
63
59
  });
64
60
 
65
- test('kills only PTY sessions owned by the revoked user in the project', () => {
61
+ test('kills all PTY sessions in the project namespace on access revocation', () => {
66
62
  mockGetConnectionsForUser.mockReturnValue(['conn1']);
67
63
  mockClearAuthForConnections.mockReturnValue(1);
68
- mockGetAllSessions.mockReturnValue([
69
- { sessionId: 'alice-session', projectId: 'proj-1', userId: 'alice' },
70
- { sessionId: 'bob-session', projectId: 'proj-1', userId: 'bob' },
71
- { sessionId: 'bob-other', projectId: 'proj-2', userId: 'bob' }
64
+ // PtyKit lists sessions by namespace (= projectId); collaborative terminals
65
+ // are project-scoped, so all of proj-1's sessions are torn down.
66
+ mockList.mockReturnValue([
67
+ { sessionId: 'session-a' },
68
+ { sessionId: 'session-b' }
72
69
  ]);
73
70
 
74
71
  invalidateUserSessions('bob', 'proj-1');
75
72
 
76
- expect(mockKillSession).toHaveBeenCalledTimes(1);
77
- expect(mockKillSession).toHaveBeenCalledWith('bob-session', 'SIGKILL');
73
+ expect(mockList).toHaveBeenCalledWith('proj-1');
74
+ expect(mockKillSession).toHaveBeenCalledTimes(2);
75
+ expect(mockKillSession).toHaveBeenCalledWith('session-a', 'SIGKILL');
76
+ expect(mockKillSession).toHaveBeenCalledWith('session-b', 'SIGKILL');
78
77
  });
79
78
 
80
79
  test('kills PTY sessions when user has no websocket connections but project access was revoked', () => {
81
80
  mockGetConnectionsForUser.mockReturnValue([]);
82
- mockGetAllSessions.mockReturnValue([
83
- { sessionId: 'bob-session', projectId: 'proj-1', userId: 'bob' },
84
- { sessionId: 'alice-session', projectId: 'proj-1', userId: 'alice' }
85
- ]);
81
+ mockList.mockReturnValue([{ sessionId: 'session-a' }]);
86
82
 
87
83
  const cleared = invalidateUserSessions('bob', 'proj-1');
88
84
 
89
85
  expect(cleared).toBe(0);
90
86
  expect(mockKillSession).toHaveBeenCalledTimes(1);
91
- expect(mockKillSession).toHaveBeenCalledWith('bob-session', 'SIGKILL');
87
+ expect(mockKillSession).toHaveBeenCalledWith('session-a', 'SIGKILL');
92
88
  });
93
89
  });
94
90
 
@@ -7,7 +7,7 @@
7
7
 
8
8
  import { ws } from '$backend/utils/ws';
9
9
  import { debug } from '$shared/utils/logger';
10
- import { ptySessionManager } from '$backend/terminal/pty-session-manager';
10
+ import { ptyKitManager } from '$backend/terminal/ptykit';
11
11
 
12
12
  /**
13
13
  * Invalidate all active WebSocket sessions for a specific user.
@@ -46,23 +46,22 @@ export function invalidateUserSessions(userId: string, projectId?: string): numb
46
46
  }
47
47
 
48
48
  /**
49
- * Kill PTY terminal sessions owned by a specific user in a project.
50
- * Prevents orphaned shell processes from continuing to run after
51
- * project access is revoked, without affecting other users' sessions.
49
+ * Kill PTY terminal sessions in a project when a user's access is revoked.
50
+ * Prevents orphaned shell processes from continuing to run. Terminals are
51
+ * collaborative and project-scoped (PtyKit keys sessions by namespace =
52
+ * projectId), so revoking access tears down that project's terminals.
52
53
  */
53
54
  function killUserPtySessionsForProject(userId: string, projectId: string): void {
54
55
  let killedCount = 0;
55
56
 
56
- for (const session of ptySessionManager.getAllSessions()) {
57
- if (session.projectId === projectId && session.userId === userId) {
58
- debug.log('auth', `Killing PTY session ${session.sessionId} for user ${userId} (project ${projectId} access revoked)`);
59
- ptySessionManager.killSession(session.sessionId, 'SIGKILL');
60
- killedCount++;
61
- }
57
+ for (const session of ptyKitManager.list(projectId)) {
58
+ debug.log('auth', `Killing PTY session ${session.sessionId} (project ${projectId} access revoked for user ${userId})`);
59
+ ptyKitManager.killSession(session.sessionId, 'SIGKILL');
60
+ killedCount++;
62
61
  }
63
62
 
64
63
  if (killedCount > 0) {
65
- debug.log('auth', `Killed ${killedCount} PTY session(s) for user ${userId} in project ${projectId}`);
64
+ debug.log('auth', `Killed ${killedCount} PTY session(s) in project ${projectId}`);
66
65
  }
67
66
  }
68
67
 
@@ -18,6 +18,7 @@ import type {
18
18
  import type {
19
19
  AlterOperation,
20
20
  DbClientDriverAdapter,
21
+ DbClientTxContext,
21
22
  IndexDefinition,
22
23
  SchemaOpts,
23
24
  TableDefinition
@@ -157,6 +158,26 @@ export class MysqlAdapter implements DbClientDriverAdapter {
157
158
  return this.executeRead(`EXPLAIN ${q}`, [], opts);
158
159
  }
159
160
 
161
+ async withTransaction<T>(fn: (tx: DbClientTxContext) => Promise<T>, opts?: { database?: string }): Promise<T> {
162
+ await this.ensureDatabase(opts?.database);
163
+ const sql = this.requireSql();
164
+ // Bun.sql reserves one connection for the `begin` block. Note: MySQL
165
+ // implicitly commits on DDL (CREATE/ALTER/DROP/…), so a batch that
166
+ // mixes DDL with later failures cannot fully roll back the DDL — a
167
+ // server limitation, not an app one.
168
+ return sql.begin(async (tx) => {
169
+ const run = async (q: string, params: unknown[] = []): Promise<DbClientQueryResult> => {
170
+ const start = performance.now();
171
+ const raw = await tx.unsafe(q, params as never);
172
+ return normalizeBunSqlResult(raw, Math.round(performance.now() - start));
173
+ };
174
+ return fn({
175
+ executeRead: (q, params) => run(q, params ?? []),
176
+ executeWrite: (q, params) => run(q, params ?? [])
177
+ });
178
+ }) as Promise<T>;
179
+ }
180
+
160
181
  // ── Overview ──────────────────────────────────────────────────────────
161
182
 
162
183
  async overview(opts?: SchemaOpts): Promise<DbClientOverview> {
@@ -18,6 +18,7 @@ import type {
18
18
  import type {
19
19
  AlterOperation,
20
20
  DbClientDriverAdapter,
21
+ DbClientTxContext,
21
22
  IndexDefinition,
22
23
  SchemaOpts,
23
24
  TableDefinition
@@ -186,6 +187,25 @@ export class PostgresAdapter implements DbClientDriverAdapter {
186
187
  return this.executeRead(`EXPLAIN ${q}`, [], opts);
187
188
  }
188
189
 
190
+ async withTransaction<T>(fn: (tx: DbClientTxContext) => Promise<T>, opts?: { database?: string }): Promise<T> {
191
+ await this.ensureDatabase(opts?.database);
192
+ const sql = this.requireSql();
193
+ // Bun.sql reserves a single connection for the duration of `begin`, so
194
+ // every statement below shares one transaction. Postgres wraps DDL in
195
+ // the transaction too, so a mid-batch failure rolls everything back.
196
+ return sql.begin(async (tx) => {
197
+ const run = async (q: string, params: unknown[] = []): Promise<DbClientQueryResult> => {
198
+ const start = performance.now();
199
+ const raw = await tx.unsafe(q, params as never);
200
+ return normalizeBunSqlResult(raw, Math.round(performance.now() - start));
201
+ };
202
+ return fn({
203
+ executeRead: (q, params) => run(q, params ?? []),
204
+ executeWrite: (q, params) => run(q, params ?? [])
205
+ });
206
+ }) as Promise<T>;
207
+ }
208
+
189
209
  // ── Overview ──────────────────────────────────────────────────────────
190
210
 
191
211
  async overview(opts?: SchemaOpts): Promise<DbClientOverview> {
@@ -20,6 +20,7 @@ import type {
20
20
  import type {
21
21
  AlterOperation,
22
22
  DbClientDriverAdapter,
23
+ DbClientTxContext,
23
24
  IndexDefinition,
24
25
  SchemaOpts,
25
26
  TableDefinition
@@ -152,6 +153,26 @@ export class SqliteAdapter implements DbClientDriverAdapter {
152
153
  return this.executeRead(`EXPLAIN QUERY PLAN ${q}`);
153
154
  }
154
155
 
156
+ async withTransaction<T>(fn: (tx: DbClientTxContext) => Promise<T>): Promise<T> {
157
+ const db = this.requireDb();
158
+ db.exec('BEGIN');
159
+ try {
160
+ const out = await fn({
161
+ executeRead: (q, params) => this.executeRead(q, params ?? []),
162
+ executeWrite: (q, params) => this.executeWrite(q, params ?? [])
163
+ });
164
+ db.exec('COMMIT');
165
+ return out;
166
+ } catch (err) {
167
+ try {
168
+ db.exec('ROLLBACK');
169
+ } catch {
170
+ // Rollback failure is secondary to the error that triggered it.
171
+ }
172
+ throw err;
173
+ }
174
+ }
175
+
155
176
  // ── Overview ──────────────────────────────────────────────────────────
156
177
 
157
178
  async overview(): Promise<DbClientOverview> {
@@ -51,6 +51,16 @@ export type AlterOperation =
51
51
  | { kind: 'rename-column'; name: string; newName: string }
52
52
  | { kind: 'modify-column'; column: ColumnDefinition };
53
53
 
54
+ /**
55
+ * A connection-bound executor handed to `withTransaction`'s callback. Every
56
+ * call runs on the same transaction's connection, so a batch of statements
57
+ * commits or rolls back atomically.
58
+ */
59
+ export interface DbClientTxContext {
60
+ executeRead(q: string, params?: unknown[], opts?: { database?: string; limit?: number }): Promise<DbClientQueryResult>;
61
+ executeWrite(q: string, params?: unknown[], opts?: { database?: string }): Promise<DbClientQueryResult>;
62
+ }
63
+
54
64
  export interface DbClientDriverAdapter {
55
65
  readonly kind: DbDriver;
56
66
 
@@ -75,6 +85,15 @@ export interface DbClientDriverAdapter {
75
85
  explain?(q: string, opts?: { database?: string }): Promise<DbClientQueryResult>;
76
86
  cancel?(): Promise<void>;
77
87
 
88
+ /**
89
+ * Run `fn` inside a single database transaction on one dedicated
90
+ * connection. Implemented only by drivers that can guarantee atomicity
91
+ * (a pooled driver must reserve a connection). If `fn` throws, the
92
+ * transaction is rolled back and the error re-thrown. Absence of this
93
+ * method signals the caller to fall back to non-transactional execution.
94
+ */
95
+ withTransaction?<T>(fn: (tx: DbClientTxContext) => Promise<T>, opts?: { database?: string }): Promise<T>;
96
+
78
97
  // Structure
79
98
  createDatabase?(name: string): Promise<string>;
80
99
  dropDatabase?(name: string): Promise<string>;
@@ -5,10 +5,12 @@
5
5
  */
6
6
 
7
7
  import type {
8
+ DbClientBatchResult,
8
9
  DbClientQueryResult,
10
+ DbClientStatementResult,
9
11
  DbDriver
10
12
  } from '$shared/types/db-client';
11
- import type { DbClientDriverAdapter } from './drivers/types';
13
+ import type { DbClientDriverAdapter, DbClientTxContext } from './drivers/types';
12
14
 
13
15
  export type QueryClass = 'read' | 'write' | 'ddl' | 'unknown';
14
16
 
@@ -124,3 +126,89 @@ export async function runSafely(input: RunSafelyInput): Promise<DbClientQueryRes
124
126
  if (!fn) throw new Error(`Driver ${driver} does not support ${mode}`);
125
127
  return fn.call(adapter, query, params, { database });
126
128
  }
129
+
130
+ interface ExecuteBatchInput {
131
+ driver: DbDriver;
132
+ adapter: DbClientDriverAdapter;
133
+ statements: string[];
134
+ params?: unknown[];
135
+ database?: string;
136
+ limit?: number;
137
+ }
138
+
139
+ function skippedStatement(index: number, query: string, queryClass: QueryClass): DbClientStatementResult {
140
+ return { index, query, queryClass, status: 'skipped', result: null, error: null, durationMs: 0 };
141
+ }
142
+
143
+ /**
144
+ * Execute a pre-split batch of statements in order. Each statement is
145
+ * classified individually and routed to read (auto-LIMITed) or write
146
+ * execution accordingly — the classification of the whole batch never lets a
147
+ * write ride in on the read path. When the driver supports transactions the
148
+ * batch is atomic: the first failure rolls the whole batch back and every
149
+ * later statement is reported as `skipped`.
150
+ */
151
+ export async function executeBatch(input: ExecuteBatchInput): Promise<DbClientBatchResult> {
152
+ const { driver, adapter, statements, params, database, limit } = input;
153
+
154
+ const runAll = async (exec: DbClientTxContext): Promise<{ results: DbClientStatementResult[]; totalDurationMs: number; failed: boolean }> => {
155
+ const results: DbClientStatementResult[] = [];
156
+ let totalDurationMs = 0;
157
+ let failed = false;
158
+ for (let index = 0; index < statements.length; index++) {
159
+ const query = statements[index];
160
+ const queryClass = classifyQuery(driver, query);
161
+ if (failed) {
162
+ results.push(skippedStatement(index, query, queryClass));
163
+ continue;
164
+ }
165
+ try {
166
+ const result = queryClass === 'read'
167
+ ? await exec.executeRead(applyAutoLimit(query, limit ?? 500), params, { database })
168
+ : await exec.executeWrite(query, params, { database });
169
+ totalDurationMs += result.durationMs;
170
+ results.push({ index, query, queryClass, status: 'success', result, error: null, durationMs: result.durationMs });
171
+ } catch (err) {
172
+ failed = true;
173
+ results.push({
174
+ index,
175
+ query,
176
+ queryClass,
177
+ status: 'error',
178
+ result: null,
179
+ error: err instanceof Error ? err.message : String(err),
180
+ durationMs: 0
181
+ });
182
+ }
183
+ }
184
+ return { results, totalDurationMs, failed };
185
+ };
186
+
187
+ if (typeof adapter.withTransaction === 'function' && statements.length > 1) {
188
+ let captured: { results: DbClientStatementResult[]; totalDurationMs: number; failed: boolean } | null = null;
189
+ try {
190
+ await adapter.withTransaction(async (tx) => {
191
+ captured = await runAll(tx);
192
+ // Throw to force a rollback while preserving the per-statement report.
193
+ if (captured.failed) throw new BatchRollbackSignal();
194
+ }, { database });
195
+ } catch (err) {
196
+ if (!(err instanceof BatchRollbackSignal)) throw err;
197
+ }
198
+ // `captured` is always assigned unless withTransaction never ran the
199
+ // callback (which would have thrown a non-signal error above).
200
+ const c = captured as unknown as { results: DbClientStatementResult[]; totalDurationMs: number; failed: boolean };
201
+ return { statements: c.results, totalDurationMs: c.totalDurationMs, transaction: true, ok: !c.failed };
202
+ }
203
+
204
+ // Non-transactional fallback: statements run sequentially and independently.
205
+ const direct: DbClientTxContext = {
206
+ executeRead: (q, p, o) => runSafely({ driver, adapter, query: q, params: p, mode: 'read', database: o?.database, limit: o?.limit }),
207
+ executeWrite: (q, p, o) => runSafely({ driver, adapter, query: q, params: p, mode: 'write', database: o?.database })
208
+ };
209
+ const { results, totalDurationMs, failed } = await runAll(direct);
210
+ return { statements: results, totalDurationMs, transaction: false, ok: !failed };
211
+ }
212
+
213
+ /** Internal sentinel: thrown to trigger a transaction rollback on batch failure. */
214
+ class BatchRollbackSignal extends Error {}
@@ -100,8 +100,8 @@ export const CLAUDE_CODE_MODELS: EngineModel[] = [
100
100
  type: 'claude-code',
101
101
  provider: 'anthropic',
102
102
  model: {
103
- id: 'claude-sonnet-4-6',
104
- name: 'Claude Sonnet 4.6',
103
+ id: 'claude-sonnet-5',
104
+ name: 'Claude Sonnet 5',
105
105
  },
106
106
  account: {
107
107
  id: 0,
@@ -110,7 +110,7 @@ export const CLAUDE_CODE_MODELS: EngineModel[] = [
110
110
  },
111
111
  limit: {
112
112
  input: 1_000_000,
113
- output: 64_000,
113
+ output: 128_000,
114
114
  },
115
115
  modalities: {
116
116
  input: {
@@ -224,6 +224,49 @@ export const CLAUDE_CODE_MODELS: EngineModel[] = [
224
224
  output: 25,
225
225
  },
226
226
  },
227
+ {
228
+ engine: {
229
+ type: 'claude-code',
230
+ provider: 'anthropic',
231
+ model: {
232
+ id: 'claude-sonnet-4-6',
233
+ name: 'Claude Sonnet 4.6',
234
+ },
235
+ account: {
236
+ id: 0,
237
+ name: '',
238
+ },
239
+ },
240
+ limit: {
241
+ input: 1_000_000,
242
+ output: 128_000,
243
+ },
244
+ modalities: {
245
+ input: {
246
+ text: true,
247
+ image: true,
248
+ audio: false,
249
+ video: false,
250
+ pdf: true,
251
+ },
252
+ output: {
253
+ text: true,
254
+ image: false,
255
+ audio: false,
256
+ video: false,
257
+ pdf: false,
258
+ },
259
+ },
260
+ capabilities: {
261
+ reasoning: true,
262
+ tools: true,
263
+ structuredOutput: true,
264
+ },
265
+ cost: {
266
+ input: 3,
267
+ output: 15,
268
+ },
269
+ },
227
270
  {
228
271
  engine: {
229
272
  type: 'claude-code',
@@ -1,7 +1,8 @@
1
1
  import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
2
- import { rm, mkdir } from 'node:fs/promises';
2
+ import { rm, mkdir, stat as fsStat } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
4
  import { tmpdir } from 'node:os';
5
+ import { zip, type ZipEntryInput } from '@myrialabs/zipkit';
5
6
 
6
7
  // Stub settingsQueries before importing the module under test so the file-size
7
8
  // limit is controllable and never touches a real database during unit tests.
@@ -15,7 +16,7 @@ await mock.module('../database/queries', () => ({
15
16
  }
16
17
  }));
17
18
 
18
- const { extractZipOperation } = await import('./file-archive');
19
+ const { extractArchiveOperation } = await import('./file-archive');
19
20
 
20
21
  function setLimitMB(mb: number): void {
21
22
  mockSettingsRow = {
@@ -36,11 +37,17 @@ function readU32(buf: Uint8Array, off: number): number {
36
37
  return (buf[off] | (buf[off + 1] << 8) | (buf[off + 2] << 16) | (buf[off + 3] << 24)) >>> 0;
37
38
  }
38
39
 
40
+ /** Build a ZIP fixture from a name → bytes map (single deflate method). */
41
+ async function makeZip(files: Record<string, Uint8Array>): Promise<Uint8Array> {
42
+ const entries: ZipEntryInput[] = Object.entries(files).map(([name, data]) => ({ name, data, method: 'deflate', level: 9 }));
43
+ return zip(entries);
44
+ }
45
+
39
46
  // Overwrite the uncompressed-size fields in a single-file zip's local and
40
47
  // central headers with a forged (tiny) value, leaving the compressed data and
41
48
  // 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).
49
+ // to slip past any check that trusts the zip metadata. Assumes a single entry
50
+ // at local offset 0 and no archive comment (true for ZipKit's zip() output).
44
51
  function forgeUncompressedSizes(zip: Uint8Array, fakeSize: number): Uint8Array {
45
52
  const out = zip.slice();
46
53
  const eocd = out.length - 22;
@@ -65,19 +72,15 @@ describe('extractZipOperation — output-size cap', () => {
65
72
  });
66
73
 
67
74
  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
- );
75
+ const archive = await makeZip({
76
+ 'file1.txt': new TextEncoder().encode('Hello world, this is a test file'),
77
+ 'file2.txt': new TextEncoder().encode('Another test file with some content')
78
+ });
76
79
  const archivePath = join(testDir, 'normal.zip');
77
80
  const extractDir = join(testDir, 'extracted');
78
- await Bun.write(archivePath, zip);
81
+ await Bun.write(archivePath, archive);
79
82
 
80
- const result = await extractZipOperation(archivePath, extractDir);
83
+ const result = await extractArchiveOperation(archivePath, extractDir);
81
84
 
82
85
  expect(result.entries).toBe(2);
83
86
  expect(await Bun.file(join(extractDir, 'file1.txt')).text()).toBe('Hello world, this is a test file');
@@ -88,14 +91,13 @@ describe('extractZipOperation — output-size cap', () => {
88
91
  // 4MB of zeros compresses to a few KB, so the compressed archive sails
89
92
  // past the compressed-size guard — only the streaming output cap catches it.
90
93
  setLimitMB(1);
91
- const { zipSync } = await import('fflate');
92
- const zip = zipSync({ 'big.bin': new Uint8Array(4 * 1024 * 1024) }, { level: 9 });
94
+ const archive = await makeZip({ 'big.bin': new Uint8Array(4 * 1024 * 1024) });
93
95
  const archivePath = join(testDir, 'big.zip');
94
- await Bun.write(archivePath, zip);
96
+ await Bun.write(archivePath, archive);
95
97
 
96
- expect(zip.byteLength).toBeLessThan(1024 * 1024); // compressed archive is under the limit
98
+ expect(archive.byteLength).toBeLessThan(1024 * 1024); // compressed archive is under the limit
97
99
 
98
- await expect(extractZipOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(
100
+ await expect(extractArchiveOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(
99
101
  /exceeds maximum allowed size/
100
102
  );
101
103
  });
@@ -104,8 +106,7 @@ describe('extractZipOperation — output-size cap', () => {
104
106
  // The whole point of the reshape: the cap counts ACTUAL decompressed
105
107
  // bytes, so lying about the size in the central directory cannot bypass it.
106
108
  setLimitMB(1);
107
- const { zipSync } = await import('fflate');
108
- const honest = zipSync({ 'bomb.bin': new Uint8Array(4 * 1024 * 1024) }, { level: 9 });
109
+ const honest = await makeZip({ 'bomb.bin': new Uint8Array(4 * 1024 * 1024) });
109
110
  const forged = forgeUncompressedSizes(honest, 10);
110
111
 
111
112
  const eocd = forged.length - 22;
@@ -115,17 +116,76 @@ describe('extractZipOperation — output-size cap', () => {
115
116
  const archivePath = join(testDir, 'forged.zip');
116
117
  await Bun.write(archivePath, forged);
117
118
 
118
- await expect(extractZipOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(
119
+ await expect(extractArchiveOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(
119
120
  /exceeds maximum allowed size/
120
121
  );
121
122
  });
122
123
 
123
124
  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 });
125
+ const archive = await makeZip({ '../escape.txt': new TextEncoder().encode('nope') });
126
126
  const archivePath = join(testDir, 'traversal.zip');
127
- await Bun.write(archivePath, zip);
127
+ await Bun.write(archivePath, archive);
128
+
129
+ await expect(extractArchiveOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(/Unsafe path/);
130
+ });
131
+ });
132
+
133
+ describe('extractArchiveOperation — encryption', () => {
134
+ let testDir: string;
135
+
136
+ beforeEach(async () => {
137
+ mockSettingsRow = null;
138
+ testDir = join(tmpdir(), `clopen-archive-enc-${Date.now()}-${Math.random().toString(36).slice(2)}`);
139
+ await mkdir(testDir, { recursive: true });
140
+ });
141
+
142
+ afterEach(async () => {
143
+ mockSettingsRow = null;
144
+ await rm(testDir, { recursive: true, force: true });
145
+ });
146
+
147
+ async function makeEncryptedZip(name: string, text: string, password: string): Promise<Uint8Array> {
148
+ return zip([{ name, data: new TextEncoder().encode(text), method: 'deflate' }], { password });
149
+ }
150
+
151
+ async function dirExists(path: string): Promise<boolean> {
152
+ try {
153
+ return (await fsStat(path)).isDirectory();
154
+ } catch {
155
+ return false;
156
+ }
157
+ }
158
+
159
+ test('rejects an encrypted archive when no password is given', async () => {
160
+ const archive = await makeEncryptedZip('secret.txt', 'classified', 'hunter2');
161
+ const archivePath = join(testDir, 'enc.zip');
162
+ const outDir = join(testDir, 'out');
163
+ await Bun.write(archivePath, archive);
164
+
165
+ await expect(extractArchiveOperation(archivePath, outDir)).rejects.toThrow(/password-protected/);
166
+ // The output folder must not be created before a valid password succeeds.
167
+ expect(await dirExists(outDir)).toBe(false);
168
+ });
169
+
170
+ test('rejects an encrypted archive with the wrong password', async () => {
171
+ const archive = await makeEncryptedZip('secret.txt', 'classified', 'hunter2');
172
+ const archivePath = join(testDir, 'enc-wrong.zip');
173
+ const outDir = join(testDir, 'out');
174
+ await Bun.write(archivePath, archive);
175
+
176
+ await expect(extractArchiveOperation(archivePath, outDir, 'nope')).rejects.toThrow(/[Ii]ncorrect password/);
177
+ expect(await dirExists(outDir)).toBe(false);
178
+ });
179
+
180
+ test('extracts an encrypted archive with the correct password', async () => {
181
+ const archive = await makeEncryptedZip('secret.txt', 'classified', 'hunter2');
182
+ const archivePath = join(testDir, 'enc-ok.zip');
183
+ const outDir = join(testDir, 'out-ok');
184
+ await Bun.write(archivePath, archive);
185
+
186
+ const result = await extractArchiveOperation(archivePath, outDir, 'hunter2');
128
187
 
129
- await expect(extractZipOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(/Unsafe path/);
188
+ expect(result.entries).toBe(1);
189
+ expect(await Bun.file(join(outDir, 'secret.txt')).text()).toBe('classified');
130
190
  });
131
191
  });