@myrialabs/clopen 0.4.6 → 0.4.7

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.
@@ -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
 
@@ -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
  });