@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.
- package/backend/auth/session-invalidation.test.ts +17 -21
- package/backend/auth/session-invalidation.ts +10 -11
- package/backend/db-client/drivers/mysql.ts +21 -0
- package/backend/db-client/drivers/postgres.ts +20 -0
- package/backend/db-client/drivers/sqlite.ts +21 -0
- package/backend/db-client/drivers/types.ts +19 -0
- package/backend/db-client/query-executor.ts +89 -1
- package/backend/engine/adapters/claude/models.ts +46 -3
- package/backend/files/file-archive.test.ts +86 -26
- package/backend/files/file-archive.ts +214 -134
- package/backend/terminal/index.ts +2 -5
- package/backend/terminal/ptykit.ts +64 -0
- package/backend/tunnel/tunnel-config.ts +1 -1
- package/backend/utils/ws.ts +14 -0
- package/backend/ws/db-client/query-history-retention.test.ts +217 -0
- package/backend/ws/db-client/query.ts +77 -2
- package/backend/ws/files/write.ts +23 -7
- package/backend/ws/git/ignored.ts +65 -0
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/projects/crud.ts +4 -4
- package/backend/ws/system/operations.ts +23 -0
- package/backend/ws/terminal/index.ts +6 -33
- package/backend/ws/terminal/tunnel.ts +76 -0
- package/dist/assets/__vite-browser-external-BIHI7g3E.js +1 -0
- package/dist/assets/index-B_F_OgoC.js +1 -0
- package/dist/assets/index-jGo0X72U.js +1 -0
- package/dist/assets/{main-TYNK6Orl.js → main-BkCc3WEB.js} +321 -260
- package/dist/assets/main-CWDwET4x.css +1 -0
- package/dist/assets/zipkit-engine-CaR0t_Uy.wasm +0 -0
- package/dist/index.html +2 -2
- package/package.json +7 -11
- package/shared/constants/engines.ts +4 -4
- package/shared/types/db-client/query.ts +33 -0
- package/shared/utils/db-client/split-sql.test.ts +88 -0
- package/shared/utils/db-client/split-sql.ts +132 -0
- package/backend/terminal/helpers.ts +0 -14
- package/backend/terminal/pty-manager.ts +0 -4
- package/backend/terminal/pty-session-manager.ts +0 -349
- package/backend/terminal/stream-manager.ts +0 -300
- package/backend/ws/terminal/access.ts +0 -56
- package/backend/ws/terminal/persistence.ts +0 -145
- package/backend/ws/terminal/session.ts +0 -470
- package/backend/ws/terminal/stream.ts +0 -82
- package/dist/assets/main-BkMrek4_.css +0 -1
|
@@ -1,102 +1,165 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { isAbsolute, join, relative, sep } from 'node:path';
|
|
2
2
|
import { mkdir, readdir, stat, writeFile } from 'node:fs/promises';
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
zip,
|
|
5
|
+
tar,
|
|
6
|
+
tarGz,
|
|
7
|
+
tarZstd,
|
|
8
|
+
sevenZip,
|
|
9
|
+
extractStream,
|
|
10
|
+
type ZipEntryInput,
|
|
11
|
+
type TarEntryInput,
|
|
12
|
+
type SevenZipEntryInput,
|
|
13
|
+
type ArchiveFormat
|
|
14
|
+
} from '@myrialabs/zipkit';
|
|
4
15
|
|
|
5
16
|
import { debug } from '$shared/utils/logger';
|
|
6
17
|
import { getMaxFileSize, validateFileSize } from './file-size-limit';
|
|
7
18
|
|
|
8
|
-
|
|
9
|
-
|
|
19
|
+
/** Container formats Clopen can produce. */
|
|
20
|
+
export type ArchiveKind = 'zip' | 'tar' | 'tar.gz' | 'tar.zst' | '7z';
|
|
21
|
+
|
|
22
|
+
/** Options for {@link createArchiveOperation}. */
|
|
23
|
+
export interface CreateArchiveOptions {
|
|
24
|
+
/** Container format (default `'zip'`). */
|
|
25
|
+
format?: ArchiveKind;
|
|
26
|
+
/** ZIP compression method (default `'deflate'`). Ignored by tar/7z. */
|
|
27
|
+
method?: 'store' | 'deflate' | 'zstd';
|
|
28
|
+
/** Compression level (codec-specific; left to the codec default when omitted). */
|
|
29
|
+
level?: number;
|
|
30
|
+
/** Encrypt the archive with WinZip AES-256. ZIP only. */
|
|
31
|
+
password?: string;
|
|
10
32
|
}
|
|
11
33
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
? (existing as ZipTree)
|
|
22
|
-
: {};
|
|
23
|
-
tree[head] = child;
|
|
24
|
-
setInTree(child, parts.slice(1), value);
|
|
34
|
+
interface FlatFile {
|
|
35
|
+
name: string;
|
|
36
|
+
data: Uint8Array;
|
|
37
|
+
mode: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface FlatDir {
|
|
41
|
+
name: string;
|
|
42
|
+
mode: number;
|
|
25
43
|
}
|
|
26
44
|
|
|
27
|
-
|
|
45
|
+
/** Recursively collect files (and empty directories) under `sourcePath`. */
|
|
46
|
+
async function collectEntries(sourcePath: string, rootName: string, files: FlatFile[], emptyDirs: FlatDir[]): Promise<void> {
|
|
28
47
|
const stats = await stat(sourcePath);
|
|
29
48
|
if (stats.isFile()) {
|
|
30
49
|
const data = new Uint8Array(await Bun.file(sourcePath).arrayBuffer());
|
|
31
|
-
|
|
50
|
+
files.push({ name: rootName, data, mode: stats.mode & 0o777 });
|
|
32
51
|
return;
|
|
33
52
|
}
|
|
34
53
|
if (stats.isDirectory()) {
|
|
35
54
|
const entries = await readdir(sourcePath);
|
|
36
55
|
if (entries.length === 0) {
|
|
37
|
-
|
|
56
|
+
emptyDirs.push({ name: `${rootName}/`, mode: stats.mode & 0o777 });
|
|
38
57
|
return;
|
|
39
58
|
}
|
|
40
59
|
for (const entry of entries) {
|
|
41
|
-
await
|
|
42
|
-
join(sourcePath, entry),
|
|
43
|
-
`${rootName}/${entry}`,
|
|
44
|
-
tree
|
|
45
|
-
);
|
|
60
|
+
await collectEntries(join(sourcePath, entry), `${rootName}/${entry}`, files, emptyDirs);
|
|
46
61
|
}
|
|
47
62
|
}
|
|
48
63
|
}
|
|
49
64
|
|
|
50
|
-
|
|
65
|
+
/** Build the archive bytes for the requested container from collected entries. */
|
|
66
|
+
async function buildArchive(
|
|
67
|
+
format: ArchiveKind,
|
|
68
|
+
files: FlatFile[],
|
|
69
|
+
emptyDirs: FlatDir[],
|
|
70
|
+
opts: CreateArchiveOptions
|
|
71
|
+
): Promise<Uint8Array> {
|
|
72
|
+
if (opts.password && format !== 'zip') {
|
|
73
|
+
throw new Error('Password protection is only supported for ZIP archives');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (format === 'zip') {
|
|
77
|
+
const method = opts.method ?? 'deflate';
|
|
78
|
+
const entries: ZipEntryInput[] = [
|
|
79
|
+
...files.map((f) => ({ name: f.name, data: f.data, method, level: opts.level, unixPermissions: f.mode })),
|
|
80
|
+
...emptyDirs.map((d) => ({ name: d.name, data: new Uint8Array(0), unixPermissions: d.mode }))
|
|
81
|
+
];
|
|
82
|
+
return zip(entries, opts.password ? { password: opts.password } : {});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (format === '7z') {
|
|
86
|
+
// 7z entries are files only; empty directories aren't represented.
|
|
87
|
+
const entries: SevenZipEntryInput[] = files.map((f) => ({
|
|
88
|
+
name: f.name,
|
|
89
|
+
data: f.data,
|
|
90
|
+
method: opts.method === 'store' ? 'copy' : 'lzma',
|
|
91
|
+
level: opts.level
|
|
92
|
+
}));
|
|
93
|
+
return sevenZip(entries);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// tar family
|
|
97
|
+
const entries: TarEntryInput[] = [
|
|
98
|
+
...files.map((f) => ({ name: f.name, data: f.data, mode: f.mode })),
|
|
99
|
+
...emptyDirs.map((d) => ({ name: d.name, type: 'directory' as const, mode: d.mode }))
|
|
100
|
+
];
|
|
101
|
+
if (format === 'tar') return tar(entries);
|
|
102
|
+
if (format === 'tar.gz') return tarGz(entries, opts.level !== undefined ? { level: opts.level } : undefined);
|
|
103
|
+
return tarZstd(entries, opts.level !== undefined ? { level: opts.level } : undefined);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Compress a set of files/directories into a single archive. Supports ZIP
|
|
108
|
+
* (store/deflate/zstd, optional AES-256), tar/`.tar.gz`/`.tar.zst`, and 7z.
|
|
109
|
+
*/
|
|
110
|
+
export async function createArchiveOperation(
|
|
111
|
+
sourcePaths: string[],
|
|
112
|
+
targetPath: string,
|
|
113
|
+
opts: CreateArchiveOptions = {}
|
|
114
|
+
): Promise<{ message: string; path: string; size: number; modified: string }> {
|
|
51
115
|
if (!Array.isArray(sourcePaths) || sourcePaths.length === 0) {
|
|
52
116
|
throw new Error('At least one source path is required');
|
|
53
117
|
}
|
|
54
|
-
if (!
|
|
55
|
-
throw new Error('Target
|
|
118
|
+
if (!targetPath) {
|
|
119
|
+
throw new Error('Target archive path is required');
|
|
56
120
|
}
|
|
57
121
|
|
|
122
|
+
const format = opts.format ?? 'zip';
|
|
123
|
+
|
|
58
124
|
try {
|
|
59
|
-
const targetFile = Bun.file(
|
|
125
|
+
const targetFile = Bun.file(targetPath);
|
|
60
126
|
if (await targetFile.exists()) {
|
|
61
127
|
throw new Error('Target archive already exists');
|
|
62
128
|
}
|
|
63
129
|
|
|
64
|
-
const
|
|
65
|
-
|
|
130
|
+
const files: FlatFile[] = [];
|
|
131
|
+
const emptyDirs: FlatDir[] = [];
|
|
66
132
|
for (const source of sourcePaths) {
|
|
67
|
-
const name =
|
|
133
|
+
const name = source.split(sep).pop() ?? '';
|
|
68
134
|
if (!name || name === '.' || name === '..') {
|
|
69
135
|
throw new Error(`Invalid source path: ${source}`);
|
|
70
136
|
}
|
|
71
|
-
await
|
|
137
|
+
await collectEntries(source, name, files, emptyDirs);
|
|
72
138
|
}
|
|
73
139
|
|
|
74
|
-
const
|
|
75
|
-
validateFileSize(
|
|
76
|
-
await Bun.write(
|
|
77
|
-
const stats = await stat(
|
|
140
|
+
const archive = await buildArchive(format, files, emptyDirs, opts);
|
|
141
|
+
validateFileSize(archive.byteLength);
|
|
142
|
+
await Bun.write(targetPath, archive);
|
|
143
|
+
const stats = await stat(targetPath);
|
|
78
144
|
|
|
79
145
|
return {
|
|
80
146
|
message: 'Archive created successfully',
|
|
81
|
-
path:
|
|
147
|
+
path: targetPath,
|
|
82
148
|
size: stats.size,
|
|
83
149
|
modified: stats.mtime.toISOString()
|
|
84
150
|
};
|
|
85
151
|
} catch (error) {
|
|
86
|
-
debug.error('file', 'Create
|
|
152
|
+
debug.error('file', 'Create archive error:', error);
|
|
87
153
|
if (error instanceof Error) {
|
|
88
|
-
if (error.message.includes('EPERM'))
|
|
89
|
-
|
|
90
|
-
}
|
|
91
|
-
if (error.message.includes('ENOSPC')) {
|
|
92
|
-
throw new Error('Not enough space on disk');
|
|
93
|
-
}
|
|
154
|
+
if (error.message.includes('EPERM')) throw new Error('Permission denied while creating archive');
|
|
155
|
+
if (error.message.includes('ENOSPC')) throw new Error('Not enough space on disk');
|
|
94
156
|
throw error;
|
|
95
157
|
}
|
|
96
158
|
throw new Error('Failed to create archive');
|
|
97
159
|
}
|
|
98
160
|
}
|
|
99
161
|
|
|
162
|
+
/** Reject entry paths that are absolute or escape the extraction root. */
|
|
100
163
|
function isSafeEntryPath(entryPath: string, targetRoot: string): boolean {
|
|
101
164
|
if (!entryPath) return false;
|
|
102
165
|
if (isAbsolute(entryPath)) return false;
|
|
@@ -107,18 +170,54 @@ function isSafeEntryPath(entryPath: string, targetRoot: string): boolean {
|
|
|
107
170
|
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
108
171
|
}
|
|
109
172
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
if (
|
|
115
|
-
|
|
173
|
+
/** Map a filename to a ZipKit container format; `undefined` → auto-detect. */
|
|
174
|
+
function formatFromPath(archivePath: string): ArchiveFormat | undefined {
|
|
175
|
+
const n = archivePath.toLowerCase();
|
|
176
|
+
if (n.endsWith('.tar.gz') || n.endsWith('.tgz')) return 'tar.gz';
|
|
177
|
+
if (n.endsWith('.tar.zst') || n.endsWith('.tzst')) return 'tar.zst';
|
|
178
|
+
if (n.endsWith('.tar.xz') || n.endsWith('.txz')) return 'tar.xz';
|
|
179
|
+
if (n.endsWith('.tar.bz2') || n.endsWith('.tbz2')) return 'tar.bz2';
|
|
180
|
+
if (n.endsWith('.tar')) return 'tar';
|
|
181
|
+
if (n.endsWith('.zip')) return 'zip';
|
|
182
|
+
if (n.endsWith('.7z')) return '7z';
|
|
183
|
+
// Lone-stream / ambiguous extensions: let extractStream sniff the magic bytes.
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function concatChunks(chunks: Uint8Array[], total: number): Uint8Array {
|
|
188
|
+
const out = new Uint8Array(total);
|
|
189
|
+
let pos = 0;
|
|
190
|
+
for (const chunk of chunks) {
|
|
191
|
+
out.set(chunk, pos);
|
|
192
|
+
pos += chunk.length;
|
|
116
193
|
}
|
|
194
|
+
return out;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async function writeEntry(fullPath: string, chunks: Uint8Array[], total: number): Promise<void> {
|
|
198
|
+
await mkdir(join(fullPath, '..'), { recursive: true });
|
|
199
|
+
await writeFile(fullPath, concatChunks(chunks, total));
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Extract an archive into `targetDir`. Auto-detects the container (ZIP, tar,
|
|
204
|
+
* `.tar.gz`/`.tar.zst`, 7z, …) from the filename or magic bytes and streams via
|
|
205
|
+
* ZipKit's {@link extractStream}, which caps the running total of *actually
|
|
206
|
+
* decompressed* bytes at the configured file-size limit — so a crafted archive
|
|
207
|
+
* that forges its uncompressed-size fields still can't blow past the cap. Each
|
|
208
|
+
* entry is path-checked before it touches disk; symlinks are skipped to avoid
|
|
209
|
+
* symlink-escape writes.
|
|
210
|
+
*/
|
|
211
|
+
export async function extractArchiveOperation(
|
|
212
|
+
archivePath: string,
|
|
213
|
+
targetDir: string,
|
|
214
|
+
password?: string
|
|
215
|
+
): Promise<{ message: string; path: string; entries: number; modified: string }> {
|
|
216
|
+
if (!archivePath) throw new Error('Archive path is required');
|
|
217
|
+
if (!targetDir) throw new Error('Target directory is required');
|
|
117
218
|
|
|
118
219
|
const archiveFile = Bun.file(archivePath);
|
|
119
|
-
if (!(await archiveFile.exists()))
|
|
120
|
-
throw new Error('Archive does not exist');
|
|
121
|
-
}
|
|
220
|
+
if (!(await archiveFile.exists())) throw new Error('Archive does not exist');
|
|
122
221
|
|
|
123
222
|
const limit = getMaxFileSize();
|
|
124
223
|
const limitMB = Math.floor(limit / (1024 * 1024));
|
|
@@ -131,16 +230,18 @@ export async function extractZipOperation(archivePath: string, targetDir: string
|
|
|
131
230
|
const targetExists = await Bun.file(targetDir).exists();
|
|
132
231
|
if (targetExists) {
|
|
133
232
|
const targetStats = await stat(targetDir);
|
|
134
|
-
if (!targetStats.isDirectory())
|
|
135
|
-
throw new Error('Target path exists and is not a directory');
|
|
136
|
-
}
|
|
137
|
-
} else {
|
|
138
|
-
await mkdir(targetDir, { recursive: true });
|
|
233
|
+
if (!targetStats.isDirectory()) throw new Error('Target path exists and is not a directory');
|
|
139
234
|
}
|
|
235
|
+
// The target directory is created lazily, only as entries are written, so a
|
|
236
|
+
// failed extraction — e.g. an encrypted archive before its password is
|
|
237
|
+
// entered, or an incorrect one — never leaves an empty folder behind.
|
|
140
238
|
|
|
141
239
|
const data = new Uint8Array(await archiveFile.arrayBuffer());
|
|
142
|
-
const entryCount = await extractWithinLimit(data, targetDir, limit, limitMB);
|
|
240
|
+
const entryCount = await extractWithinLimit(data, archivePath, targetDir, limit, limitMB, password);
|
|
143
241
|
|
|
242
|
+
// Ensure the directory exists even for an archive that yielded no file
|
|
243
|
+
// entries, so the stat below has something to read.
|
|
244
|
+
await mkdir(targetDir, { recursive: true });
|
|
144
245
|
const targetStats = await stat(targetDir);
|
|
145
246
|
return {
|
|
146
247
|
message: 'Archive extracted successfully',
|
|
@@ -149,104 +250,83 @@ export async function extractZipOperation(archivePath: string, targetDir: string
|
|
|
149
250
|
modified: targetStats.mtime.toISOString()
|
|
150
251
|
};
|
|
151
252
|
} catch (error) {
|
|
152
|
-
debug.error('file', 'Extract
|
|
253
|
+
debug.error('file', 'Extract archive error:', error);
|
|
153
254
|
if (error instanceof Error) {
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
throw new Error('Not enough space on disk');
|
|
255
|
+
// Translate ZipKit's technical encryption errors into a clean message the
|
|
256
|
+
// UI can detect to prompt for (or re-prompt) a password.
|
|
257
|
+
if (/encrypted|wrong password|bad password|decrypt/i.test(error.message)) {
|
|
258
|
+
throw new Error(password ? 'Incorrect password for this archive' : 'This archive is password-protected');
|
|
159
259
|
}
|
|
260
|
+
if (error.message.includes('EPERM')) throw new Error('Permission denied while extracting archive');
|
|
261
|
+
if (error.message.includes('ENOSPC')) throw new Error('Not enough space on disk');
|
|
160
262
|
throw error;
|
|
161
263
|
}
|
|
162
264
|
throw new Error('Failed to extract archive');
|
|
163
265
|
}
|
|
164
266
|
}
|
|
165
267
|
|
|
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
268
|
/**
|
|
184
|
-
* Stream-extract
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
188
|
-
* the uncompressed-size fields in the central directory, which an attacker
|
|
189
|
-
* controls and can forge to defeat a pre-decompression size check.
|
|
269
|
+
* Stream-extract an archive, translating ZipKit's cap error into Clopen's
|
|
270
|
+
* user-facing size-limit message. `maxTotalBytes` bounds actual decompressed
|
|
271
|
+
* output, so a zip bomb (or one that forges its metadata) is rejected before it
|
|
272
|
+
* can allocate past the limit.
|
|
190
273
|
*/
|
|
191
274
|
async function extractWithinLimit(
|
|
192
275
|
data: Uint8Array,
|
|
276
|
+
archivePath: string,
|
|
193
277
|
targetDir: string,
|
|
194
278
|
limit: number,
|
|
195
|
-
limitMB: number
|
|
279
|
+
limitMB: number,
|
|
280
|
+
password?: string
|
|
196
281
|
): Promise<number> {
|
|
197
|
-
let totalBytes = 0;
|
|
198
282
|
let entryCount = 0;
|
|
199
|
-
let
|
|
200
|
-
|
|
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
|
-
}
|
|
283
|
+
let currentPath: string | null = null;
|
|
284
|
+
let chunks: Uint8Array[] = [];
|
|
285
|
+
let currentTotal = 0;
|
|
209
286
|
|
|
210
|
-
|
|
211
|
-
const
|
|
287
|
+
try {
|
|
288
|
+
for await (const { info, chunk, done } of extractStream(data, {
|
|
289
|
+
maxTotalBytes: limit,
|
|
290
|
+
format: formatFromPath(archivePath),
|
|
291
|
+
password
|
|
292
|
+
})) {
|
|
293
|
+
if (!isSafeEntryPath(info.name, targetDir)) {
|
|
294
|
+
throw new Error(`Unsafe path in archive: ${info.name}`);
|
|
295
|
+
}
|
|
296
|
+
const normalized = info.name.replace(/\\/g, '/');
|
|
297
|
+
const fullPath = join(targetDir, normalized.split('/').join(sep));
|
|
212
298
|
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
299
|
+
if (info.type === 'directory') {
|
|
300
|
+
await mkdir(fullPath, { recursive: true });
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
// Skip symlinks: recreating them from an untrusted archive risks
|
|
304
|
+
// symlink-escape writes on later entries.
|
|
305
|
+
if (info.type === 'symlink') continue;
|
|
217
306
|
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
if (err) {
|
|
223
|
-
failure = err;
|
|
224
|
-
return;
|
|
307
|
+
if (currentPath !== fullPath) {
|
|
308
|
+
currentPath = fullPath;
|
|
309
|
+
chunks = [];
|
|
310
|
+
currentTotal = 0;
|
|
225
311
|
}
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
return;
|
|
312
|
+
if (chunk.length) {
|
|
313
|
+
chunks.push(chunk);
|
|
314
|
+
currentTotal += chunk.length;
|
|
230
315
|
}
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
if (final) {
|
|
234
|
-
writes.push(writeEntry(fullPath, concatChunks(chunks, fileBytes)));
|
|
316
|
+
if (done) {
|
|
317
|
+
await writeEntry(fullPath, chunks, currentTotal);
|
|
235
318
|
entryCount++;
|
|
319
|
+
currentPath = null;
|
|
320
|
+
chunks = [];
|
|
321
|
+
currentTotal = 0;
|
|
236
322
|
}
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
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);
|
|
323
|
+
}
|
|
324
|
+
} catch (error) {
|
|
325
|
+
if (error instanceof Error && /maxTotalBytes|remaining cap/.test(error.message)) {
|
|
326
|
+
throw new Error(`Extracted content exceeds maximum allowed size of ${limitMB}MB`);
|
|
327
|
+
}
|
|
328
|
+
throw error;
|
|
246
329
|
}
|
|
247
330
|
|
|
248
|
-
if (failure) throw failure;
|
|
249
|
-
await Promise.all(writes);
|
|
250
331
|
return entryCount;
|
|
251
332
|
}
|
|
252
|
-
|
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
// Export shell utilities
|
|
2
2
|
export * from './shell-utils.js';
|
|
3
3
|
|
|
4
|
-
// Export
|
|
5
|
-
export * from './
|
|
6
|
-
|
|
7
|
-
// Export terminal stream manager
|
|
8
|
-
export * from './stream-manager.js';
|
|
4
|
+
// Export the PtyKit backend bridge (session engine + embedded server)
|
|
5
|
+
export * from './ptykit.js';
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PtyKit backend bridge.
|
|
3
|
+
*
|
|
4
|
+
* Clopen adopts @myrialabs/ptykit wholesale for terminal PTY sessions: the core
|
|
5
|
+
* `PtyKitManager` owns spawn + scrollback + serialized reattach + backend
|
|
6
|
+
* auto-detect, and an embedded `PtyKitServer` speaks the PtyKit wire protocol.
|
|
7
|
+
* There is no second WebSocket — the server is driven over Clopen's existing
|
|
8
|
+
* app-wide socket via `handleFrame` (see `backend/ws/terminal/tunnel.ts`).
|
|
9
|
+
*
|
|
10
|
+
* - `namespace` = Clopen `projectId` (collaborative room + anti-hijack scope).
|
|
11
|
+
* - `authorize` bridges to Clopen's project-access check.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { PtyKitManager } from '@myrialabs/ptykit/core';
|
|
15
|
+
import { createPtyKitServer } from '@myrialabs/ptykit/server';
|
|
16
|
+
import { projectQueries } from '$backend/database/queries';
|
|
17
|
+
|
|
18
|
+
/** Terminal-friendly env, matching the previous `createCleanPtyEnv` overrides. */
|
|
19
|
+
const TERMINAL_ENV = {
|
|
20
|
+
FORCE_COLOR: '1',
|
|
21
|
+
COLORTERM: 'truecolor',
|
|
22
|
+
TERM: 'xterm-256color',
|
|
23
|
+
TERM_PROGRAM: 'xterm.js',
|
|
24
|
+
CLICOLOR: '1',
|
|
25
|
+
LC_ALL: 'en_US.UTF-8',
|
|
26
|
+
LANG: 'en_US.UTF-8'
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** Singleton session engine — replaces pty-session-manager + stream-manager. */
|
|
30
|
+
export const ptyKitManager = new PtyKitManager({
|
|
31
|
+
scrollback: 5000,
|
|
32
|
+
// Sessions live until the tab is killed; keep exited sessions briefly so a
|
|
33
|
+
// refresh/reconnect can still replay their final screen (matches old 5-min window).
|
|
34
|
+
idleTtl: null,
|
|
35
|
+
retainExitedMs: 5 * 60_000,
|
|
36
|
+
env: { sanitize: true, inject: TERMINAL_ENV }
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Embedded WebSocket server over the manager. No HTTP/Bun mounting — Clopen's
|
|
41
|
+
* tunnel feeds it frames and supplies per-connection `send`. `authorize` enforces
|
|
42
|
+
* project access; the room is the project so output is collaborative.
|
|
43
|
+
*/
|
|
44
|
+
export const ptyKitServer = createPtyKitServer(ptyKitManager, {
|
|
45
|
+
room: (ctx) => ctx.namespace,
|
|
46
|
+
authorize: (ctx) => {
|
|
47
|
+
const userId = ctx.conn.data.userId;
|
|
48
|
+
if (typeof userId !== 'string' || !userId) return false;
|
|
49
|
+
return projectQueries.userHasProject(userId, ctx.namespace);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Kill every PTY session belonging to a project (namespace). Used on project
|
|
55
|
+
* delete/remove to reap orphaned shells. Returns the number killed.
|
|
56
|
+
*/
|
|
57
|
+
export function cleanupProjectSessions(projectId: string): number {
|
|
58
|
+
let killed = 0;
|
|
59
|
+
for (const session of ptyKitManager.list(projectId)) {
|
|
60
|
+
ptyKitManager.killSession(session.sessionId, 'SIGKILL');
|
|
61
|
+
killed++;
|
|
62
|
+
}
|
|
63
|
+
return killed;
|
|
64
|
+
}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { join } from 'path';
|
|
9
|
-
import { TunnelKit, TunnelStore, type ActiveTunnel, type IngressInfo, type TunnelType } from 'tunnelkit';
|
|
9
|
+
import { TunnelKit, TunnelStore, type ActiveTunnel, type IngressInfo, type TunnelType } from '@myrialabs/tunnelkit';
|
|
10
10
|
import { getClopenDir } from '../utils/paths';
|
|
11
11
|
import { debug } from '$shared/utils/logger';
|
|
12
12
|
|
package/backend/utils/ws.ts
CHANGED
|
@@ -1026,6 +1026,20 @@ class WSServer {
|
|
|
1026
1026
|
}
|
|
1027
1027
|
};
|
|
1028
1028
|
|
|
1029
|
+
/**
|
|
1030
|
+
* Send a pre-serialized message to a single connection by its stable id.
|
|
1031
|
+
* Resolves the CURRENT wrapper (Elysia recreates wrappers per handler call),
|
|
1032
|
+
* so it is safe to hold a connection id in a long-lived closure and send later
|
|
1033
|
+
* — e.g. an embedded PtyKit transport tunneling frames to one viewer. Applies
|
|
1034
|
+
* the same backpressure guard as room emits. Returns false if the connection is
|
|
1035
|
+
* gone or backpressured.
|
|
1036
|
+
*/
|
|
1037
|
+
sendToConnectionId(connId: string, message: string | ArrayBuffer): boolean {
|
|
1038
|
+
const conn = this.connections.get(connId);
|
|
1039
|
+
if (!conn) return false;
|
|
1040
|
+
return this.sendToConnection(conn, message);
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1029
1043
|
/**
|
|
1030
1044
|
* Get all connections (optionally filtered by project)
|
|
1031
1045
|
*/
|