@myrialabs/clopen 0.3.18 → 0.3.20
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/chat/stream-manager.ts +11 -1
- package/backend/database/migrations/039_create_file_audit_log.ts +45 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/file-audit-log-queries.test.ts +377 -0
- package/backend/database/queries/file-audit-log-queries.ts +184 -0
- package/backend/database/queries/index.ts +2 -1
- package/backend/db-client/drivers/mongodb.ts +52 -0
- package/backend/db-client/drivers/mysql.ts +168 -11
- package/backend/db-client/drivers/postgres.ts +182 -19
- package/backend/db-client/drivers/redis.ts +27 -0
- package/backend/db-client/drivers/sqlite.ts +66 -0
- package/backend/db-client/drivers/types.ts +13 -0
- package/backend/engine/install-recipes.ts +1 -109
- package/backend/http/files-upload.ts +84 -3
- package/backend/preview/browser/browser-preview-service.ts +44 -11
- package/backend/snapshot/snapshot-service.ts +82 -52
- package/backend/tunnel/tunnel-config.ts +76 -209
- package/backend/utils/client-ip.test.ts +55 -0
- package/backend/utils/client-ip.ts +42 -0
- package/backend/utils/ws.ts +6 -3
- package/backend/ws/auth/login.test.ts +271 -0
- package/backend/ws/auth/login.ts +36 -3
- package/backend/ws/auth/users.ts +3 -2
- package/backend/ws/db-client/schema.ts +14 -0
- package/backend/ws/db-client/structure.ts +120 -0
- package/backend/ws/files/path-access.test.ts +60 -1
- package/backend/ws/files/path-access.ts +21 -0
- package/backend/ws/snapshot/restore.ts +34 -29
- package/backend/ws/system-tools/install.ts +0 -1
- package/backend/ws/system-tools/status.ts +3 -4
- package/backend/ws/tunnel/config.ts +17 -25
- package/backend/ws/tunnel/operations.ts +63 -68
- package/dist/assets/{main-CaqEjA6B.js → main-72Z_L-nD.js} +224 -223
- package/dist/assets/main-ClADBkFf.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +2 -1
- package/shared/types/db-client/query.ts +9 -0
- package/shared/utils/ws-client.ts +188 -38
- package/backend/tunnel/cloudflared/binary.ts +0 -171
- package/backend/tunnel/cloudflared/index.ts +0 -24
- package/backend/tunnel/cloudflared/tunnel.ts +0 -444
- package/backend/tunnel/global-tunnel-manager.ts +0 -687
- package/backend/tunnel/project-tunnel-manager.ts +0 -264
- package/dist/assets/main-6cCq8H0w.css +0 -1
|
@@ -45,6 +45,13 @@ export interface RestoreConflict {
|
|
|
45
45
|
modifiedAt: string;
|
|
46
46
|
restoreContent?: string;
|
|
47
47
|
currentContent?: string;
|
|
48
|
+
/**
|
|
49
|
+
* 'cross-session' (default): file was changed by a different session after the
|
|
50
|
+
* reference time. 'local': the current on-disk content was never captured by
|
|
51
|
+
* this session's snapshots, so restoring would overwrite an unrecoverable
|
|
52
|
+
* manual edit.
|
|
53
|
+
*/
|
|
54
|
+
reason?: 'cross-session' | 'local';
|
|
48
55
|
}
|
|
49
56
|
|
|
50
57
|
/**
|
|
@@ -147,82 +154,76 @@ export class SnapshotService {
|
|
|
147
154
|
messageId: string
|
|
148
155
|
): Promise<MessageSnapshot> {
|
|
149
156
|
try {
|
|
150
|
-
const dirtyFiles = fileWatcher.getDirtyFiles(projectId);
|
|
151
|
-
|
|
152
157
|
const previousSnapshots = snapshotQueries.getBySessionId(sessionId);
|
|
153
158
|
const previousSnapshot = previousSnapshots.length > 0
|
|
154
159
|
? previousSnapshots[previousSnapshots.length - 1]
|
|
155
160
|
: null;
|
|
156
161
|
|
|
157
|
-
//
|
|
158
|
-
|
|
159
|
-
debug.log('snapshot', 'No file changes detected, skipping snapshot');
|
|
160
|
-
return previousSnapshot;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
// Get previous tree (in-memory baseline)
|
|
162
|
+
// Previous tree (in-memory baseline = disk state at session start or the
|
|
163
|
+
// last capture/restore).
|
|
164
164
|
const previousTree = await this.getSessionBaseline(projectPath, sessionId);
|
|
165
165
|
|
|
166
|
-
//
|
|
167
|
-
|
|
166
|
+
// The source of truth is the DISK, not the file watcher's dirty set. The
|
|
167
|
+
// watcher only runs while the Files/Git panel is mounted, so relying on it
|
|
168
|
+
// silently dropped snapshots whenever the user chatted with those panels
|
|
169
|
+
// closed (worsened once dock state became per-project). A gitignore-aware
|
|
170
|
+
// scan + hash diff against the baseline is always correct, and
|
|
171
|
+
// blobStore.hashFile's mtime+size cache keeps it cheap — only files that
|
|
172
|
+
// actually changed are re-read.
|
|
173
|
+
const files = await getSnapshotFiles(projectPath);
|
|
174
|
+
const currentTree: TreeMap = {};
|
|
168
175
|
const sessionChanges: SessionScopedChanges = {};
|
|
169
176
|
const readContents = new Map<string, Buffer>();
|
|
177
|
+
const seen = new Set<string>();
|
|
170
178
|
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
// Incremental: start from previous tree, update only dirty files
|
|
176
|
-
currentTree = { ...previousTree };
|
|
179
|
+
for (const filepath of files) {
|
|
180
|
+
try {
|
|
181
|
+
const stat = await fs.stat(filepath);
|
|
182
|
+
const relativePath = path.relative(projectPath, filepath).replace(/\\/g, '/');
|
|
177
183
|
|
|
178
|
-
|
|
179
|
-
|
|
184
|
+
// Files over the size cap are never tracked (mirrors the baseline
|
|
185
|
+
// scan). If one was tracked before, the deletion pass below records
|
|
186
|
+
// its removal from the tree.
|
|
187
|
+
if (stat.size > MAX_FILE_SIZE) continue;
|
|
180
188
|
|
|
181
|
-
|
|
182
|
-
const stat = await fs.stat(fullPath);
|
|
183
|
-
if (stat.size > MAX_FILE_SIZE) {
|
|
184
|
-
if (currentTree[relativePath]) {
|
|
185
|
-
const oldHash = currentTree[relativePath];
|
|
186
|
-
sessionChanges[relativePath] = { oldHash, newHash: '' };
|
|
187
|
-
delete currentTree[relativePath];
|
|
188
|
-
}
|
|
189
|
-
continue;
|
|
190
|
-
}
|
|
189
|
+
seen.add(relativePath);
|
|
191
190
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
191
|
+
const result = await blobStore.hashFile(relativePath, filepath);
|
|
192
|
+
const newHash = result.hash;
|
|
193
|
+
const oldHash = previousTree[relativePath] || '';
|
|
195
194
|
|
|
196
|
-
|
|
197
|
-
currentTree[relativePath] = newHash;
|
|
198
|
-
sessionChanges[relativePath] = { oldHash, newHash };
|
|
195
|
+
currentTree[relativePath] = newHash;
|
|
199
196
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
}
|
|
197
|
+
if (oldHash !== newHash) {
|
|
198
|
+
sessionChanges[relativePath] = { oldHash, newHash };
|
|
203
199
|
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
}
|
|
200
|
+
if (result.content !== null) {
|
|
201
|
+
readContents.set(relativePath, result.content);
|
|
207
202
|
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
const oldHash = currentTree[relativePath];
|
|
212
|
-
sessionChanges[relativePath] = { oldHash, newHash: '' };
|
|
213
|
-
delete currentTree[relativePath];
|
|
203
|
+
|
|
204
|
+
if (oldHash && !(await blobStore.hasBlob(oldHash))) {
|
|
205
|
+
debug.warn('snapshot', `Old blob missing for ${relativePath} (${oldHash.slice(0, 8)}), restore may be limited`);
|
|
214
206
|
}
|
|
215
207
|
}
|
|
208
|
+
} catch {
|
|
209
|
+
// Unreadable file — skip it
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Deletions: anything in the baseline that is no longer on disk.
|
|
214
|
+
for (const relativePath of Object.keys(previousTree)) {
|
|
215
|
+
if (!seen.has(relativePath)) {
|
|
216
|
+
sessionChanges[relativePath] = { oldHash: previousTree[relativePath], newHash: '' };
|
|
216
217
|
}
|
|
217
|
-
} else {
|
|
218
|
-
currentTree = { ...previousTree };
|
|
219
218
|
}
|
|
220
219
|
|
|
220
|
+
// The dirty set is no longer the snapshot source, but clear it so it does
|
|
221
|
+
// not grow unbounded for the Files panel UI.
|
|
221
222
|
fileWatcher.clearDirtyFiles(projectId);
|
|
222
223
|
|
|
223
|
-
//
|
|
224
|
+
// No changes vs the baseline → reuse the existing head snapshot.
|
|
224
225
|
if (Object.keys(sessionChanges).length === 0 && previousSnapshot) {
|
|
225
|
-
debug.log('snapshot', 'No
|
|
226
|
+
debug.log('snapshot', 'No file changes detected (full scan), skipping snapshot');
|
|
226
227
|
return previousSnapshot;
|
|
227
228
|
}
|
|
228
229
|
|
|
@@ -301,7 +302,10 @@ export class SnapshotService {
|
|
|
301
302
|
return { hasConflicts: false, conflicts: [], checkpointsToUndo: [] };
|
|
302
303
|
}
|
|
303
304
|
|
|
304
|
-
// Filter out files already in expected state on disk (no actual change needed)
|
|
305
|
+
// Filter out files already in expected state on disk (no actual change needed),
|
|
306
|
+
// and remember the current on-disk hash of the files that WOULD change so the
|
|
307
|
+
// local-drift pass below can run without re-reading them.
|
|
308
|
+
const currentHashByFile = new Map<string, string>();
|
|
305
309
|
if (projectPath) {
|
|
306
310
|
for (const [filepath, expectedHash] of expectedState) {
|
|
307
311
|
const fullPath = path.join(projectPath, filepath);
|
|
@@ -315,6 +319,8 @@ export class SnapshotService {
|
|
|
315
319
|
}
|
|
316
320
|
if (currentHash === expectedHash) {
|
|
317
321
|
expectedState.delete(filepath);
|
|
322
|
+
} else {
|
|
323
|
+
currentHashByFile.set(filepath, currentHash);
|
|
318
324
|
}
|
|
319
325
|
}
|
|
320
326
|
|
|
@@ -396,6 +402,30 @@ export class SnapshotService {
|
|
|
396
402
|
|
|
397
403
|
const uniqueConflicts = Array.from(conflictMap.values());
|
|
398
404
|
|
|
405
|
+
// Local-drift detection: a file restore would overwrite/delete whose CURRENT
|
|
406
|
+
// on-disk content was never captured by this session's snapshots. Overwriting
|
|
407
|
+
// it would lose an unrecoverable manual edit, so surface it as a conflict and
|
|
408
|
+
// let the user decide. Normal undo/redo never trips this — the working tree's
|
|
409
|
+
// content there always maps to a captured oldHash/newHash.
|
|
410
|
+
if (projectPath) {
|
|
411
|
+
const sessionReferenced = snapshotQueries.collectBlobHashes(sessionSnapshots);
|
|
412
|
+
const alreadyFlagged = new Set(uniqueConflicts.map(c => c.filepath));
|
|
413
|
+
for (const [filepath] of expectedState) {
|
|
414
|
+
if (alreadyFlagged.has(filepath)) continue;
|
|
415
|
+
const currentHash = currentHashByFile.get(filepath) || '';
|
|
416
|
+
if (!currentHash) continue; // no file on disk → nothing to lose
|
|
417
|
+
if (!sessionReferenced.has(currentHash)) {
|
|
418
|
+
uniqueConflicts.push({
|
|
419
|
+
filepath,
|
|
420
|
+
modifiedBySessionId: sessionId,
|
|
421
|
+
modifiedBySnapshotId: '',
|
|
422
|
+
modifiedAt: '',
|
|
423
|
+
reason: 'local'
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
399
429
|
// Populate file contents for diff display
|
|
400
430
|
if (uniqueConflicts.length > 0 && projectPath) {
|
|
401
431
|
await Promise.all(uniqueConflicts.map(async (conflict) => {
|
|
@@ -1,234 +1,101 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Tunnel
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* - Local (locally-managed): tunnel name, ID, credentials, ingress rules
|
|
7
|
-
*
|
|
8
|
-
* Config stored in ~/.clopen/tunnel/config.json
|
|
2
|
+
* Tunnel config & runtime — owns the single `TunnelKit` instance and the
|
|
3
|
+
* `TunnelStore` it auto-saves to (`~/.clopen/tunnel/config.json`). The WS layer
|
|
4
|
+
* reads/writes the store directly and calls `tunnelKit.*` for lifecycle
|
|
5
|
+
* operations (start/stop/create/login/…), so we don't need a separate manager.
|
|
9
6
|
*/
|
|
10
7
|
|
|
11
8
|
import { join } from 'path';
|
|
12
|
-
import {
|
|
9
|
+
import { TunnelKit, TunnelStore, type ActiveTunnel, type IngressInfo, type TunnelType } from 'tunnelkit';
|
|
13
10
|
import { getClopenDir } from '../utils/paths';
|
|
14
11
|
import { debug } from '$shared/utils/logger';
|
|
15
|
-
import { randomUUID } from 'crypto';
|
|
16
12
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export interface LocalTunnelIngressRule {
|
|
26
|
-
hostname: string;
|
|
27
|
-
service: string;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export interface LocalTunnelConfig {
|
|
31
|
-
id: string;
|
|
32
|
-
name: string;
|
|
33
|
-
tunnelId: string;
|
|
34
|
-
credentialsFile: string;
|
|
35
|
-
ingress: LocalTunnelIngressRule[];
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
interface TunnelConfigFile {
|
|
39
|
-
remotes: RemoteTunnelConfig[];
|
|
40
|
-
locals: LocalTunnelConfig[];
|
|
41
|
-
authorizedZone?: string;
|
|
13
|
+
/**
|
|
14
|
+
* Narrow tunnelkit's `IngressInfo[]` (where `hostname` is optional, to allow
|
|
15
|
+
* catch-all remote rules) to the hostname-bearing rules local tunnels always
|
|
16
|
+
* have — the shape the local WS responses declare.
|
|
17
|
+
*/
|
|
18
|
+
export function namedIngress(ingress: IngressInfo[]): { hostname: string; service: string }[] {
|
|
19
|
+
return ingress.filter((r): r is { hostname: string; service: string } => typeof r.hostname === 'string');
|
|
42
20
|
}
|
|
43
21
|
|
|
44
22
|
// --- Paths ---
|
|
45
23
|
|
|
46
24
|
const TUNNEL_DIR = join(getClopenDir(), 'tunnel');
|
|
47
|
-
const CONFIG_FILE = join(TUNNEL_DIR, 'config.json');
|
|
48
25
|
|
|
49
26
|
export function getTunnelDir(): string {
|
|
50
27
|
return TUNNEL_DIR;
|
|
51
28
|
}
|
|
52
29
|
|
|
53
|
-
// ---
|
|
54
|
-
|
|
55
|
-
function ensureDir(): void {
|
|
56
|
-
if (!existsSync(TUNNEL_DIR)) {
|
|
57
|
-
mkdirSync(TUNNEL_DIR, { recursive: true });
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
function readConfigFile(): TunnelConfigFile {
|
|
62
|
-
try {
|
|
63
|
-
if (!existsSync(CONFIG_FILE)) {
|
|
64
|
-
return { remotes: [], locals: [] };
|
|
65
|
-
}
|
|
66
|
-
const raw = readFileSync(CONFIG_FILE, 'utf-8');
|
|
67
|
-
const data = JSON.parse(raw);
|
|
68
|
-
|
|
69
|
-
// Migration: old format { configs: [{ id, token, domain }] }
|
|
70
|
-
if (data.configs && !data.remotes) {
|
|
71
|
-
const migrated: TunnelConfigFile = {
|
|
72
|
-
remotes: data.configs.map((c: { id: string; token: string; domain: string }) => ({
|
|
73
|
-
id: c.id,
|
|
74
|
-
label: c.domain,
|
|
75
|
-
token: c.token
|
|
76
|
-
})),
|
|
77
|
-
locals: []
|
|
78
|
-
};
|
|
79
|
-
writeConfigFile(migrated);
|
|
80
|
-
debug.log('tunnel', 'Migrated old tunnel config to remote/local format');
|
|
81
|
-
return migrated;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// Migration: single entry format { token, domain }
|
|
85
|
-
if (data.token && data.domain && !data.remotes && !data.configs) {
|
|
86
|
-
const migrated: TunnelConfigFile = {
|
|
87
|
-
remotes: [{ id: randomUUID(), label: data.domain, token: data.token }],
|
|
88
|
-
locals: []
|
|
89
|
-
};
|
|
90
|
-
writeConfigFile(migrated);
|
|
91
|
-
debug.log('tunnel', 'Migrated single tunnel config to remote/local format');
|
|
92
|
-
return migrated;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
return {
|
|
96
|
-
remotes: data.remotes ?? [],
|
|
97
|
-
locals: data.locals ?? [],
|
|
98
|
-
authorizedZone: data.authorizedZone
|
|
99
|
-
};
|
|
100
|
-
} catch (error) {
|
|
101
|
-
debug.error('tunnel', 'Failed to read tunnel config:', error);
|
|
102
|
-
return { remotes: [], locals: [] };
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
function writeConfigFile(data: TunnelConfigFile): void {
|
|
107
|
-
ensureDir();
|
|
108
|
-
writeFileSync(CONFIG_FILE, JSON.stringify(data, null, '\t'), 'utf-8');
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
// --- Remote tunnel config ---
|
|
112
|
-
|
|
113
|
-
export function getRemoteTunnelConfigs(): RemoteTunnelConfig[] {
|
|
114
|
-
return readConfigFile().remotes;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export function getRemoteTunnelConfigById(id: string): RemoteTunnelConfig | null {
|
|
118
|
-
return readConfigFile().remotes.find((c) => c.id === id) ?? null;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
export function addRemoteTunnelConfig(label: string, token: string): RemoteTunnelConfig {
|
|
122
|
-
const data = readConfigFile();
|
|
123
|
-
const entry: RemoteTunnelConfig = { id: randomUUID(), label, token };
|
|
124
|
-
data.remotes.push(entry);
|
|
125
|
-
writeConfigFile(data);
|
|
126
|
-
debug.log('tunnel', `Remote tunnel config added: ${label}`);
|
|
127
|
-
return entry;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
export function removeRemoteTunnelConfig(id: string): boolean {
|
|
131
|
-
const data = readConfigFile();
|
|
132
|
-
const before = data.remotes.length;
|
|
133
|
-
data.remotes = data.remotes.filter((c) => c.id !== id);
|
|
134
|
-
if (data.remotes.length < before) {
|
|
135
|
-
writeConfigFile(data);
|
|
136
|
-
debug.log('tunnel', `Remote tunnel config removed: ${id}`);
|
|
137
|
-
return true;
|
|
138
|
-
}
|
|
139
|
-
return false;
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
// --- Local tunnel config ---
|
|
30
|
+
// --- Shared logger ---
|
|
143
31
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
return readConfigFile().locals.find((c) => c.id === id) ?? null;
|
|
150
|
-
}
|
|
32
|
+
const tunnelLogger = {
|
|
33
|
+
log: (...args: unknown[]) => debug.log('tunnel', ...args),
|
|
34
|
+
warn: (...args: unknown[]) => debug.warn('tunnel', ...args),
|
|
35
|
+
error: (...args: unknown[]) => debug.error('tunnel', ...args)
|
|
36
|
+
};
|
|
151
37
|
|
|
152
|
-
|
|
153
|
-
name: string,
|
|
154
|
-
tunnelId: string,
|
|
155
|
-
credentialsFile: string
|
|
156
|
-
): LocalTunnelConfig {
|
|
157
|
-
const data = readConfigFile();
|
|
158
|
-
const entry: LocalTunnelConfig = {
|
|
159
|
-
id: randomUUID(),
|
|
160
|
-
name,
|
|
161
|
-
tunnelId,
|
|
162
|
-
credentialsFile,
|
|
163
|
-
ingress: []
|
|
164
|
-
};
|
|
165
|
-
data.locals.push(entry);
|
|
166
|
-
writeConfigFile(data);
|
|
167
|
-
debug.log('tunnel', `Local tunnel config added: ${name} (${tunnelId})`);
|
|
168
|
-
return entry;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
export function removeLocalTunnelConfig(id: string): boolean {
|
|
172
|
-
const data = readConfigFile();
|
|
173
|
-
const before = data.locals.length;
|
|
174
|
-
data.locals = data.locals.filter((c) => c.id !== id);
|
|
175
|
-
if (data.locals.length < before) {
|
|
176
|
-
writeConfigFile(data);
|
|
177
|
-
debug.log('tunnel', `Local tunnel config removed: ${id}`);
|
|
178
|
-
return true;
|
|
179
|
-
}
|
|
180
|
-
return false;
|
|
181
|
-
}
|
|
38
|
+
// --- Singleton store + kit ---
|
|
182
39
|
|
|
183
|
-
export
|
|
184
|
-
id: string,
|
|
185
|
-
hostname: string,
|
|
186
|
-
service: string
|
|
187
|
-
): LocalTunnelConfig | null {
|
|
188
|
-
const data = readConfigFile();
|
|
189
|
-
const config = data.locals.find((c) => c.id === id);
|
|
190
|
-
if (!config) return null;
|
|
40
|
+
export const tunnelStore = new TunnelStore({ dataDir: TUNNEL_DIR, logger: tunnelLogger });
|
|
191
41
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
42
|
+
/**
|
|
43
|
+
* The shared `TunnelKit` instance the WS layer uses. Persistence is on (via
|
|
44
|
+
* `tunnelStore`), and tunnelkit's default `isTunnelKnown` predicate
|
|
45
|
+
* automatically treats any tunnel in the store as known, so name-conflict
|
|
46
|
+
* recovery won't delete tunnels we already track.
|
|
47
|
+
*/
|
|
48
|
+
export const tunnelKit = new TunnelKit({
|
|
49
|
+
dataDir: TUNNEL_DIR,
|
|
50
|
+
store: tunnelStore,
|
|
51
|
+
logger: tunnelLogger
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
// --- ActiveTunnel adapter ---
|
|
55
|
+
|
|
56
|
+
export interface ActiveTunnelInfo {
|
|
57
|
+
port: number;
|
|
58
|
+
publicUrl: string;
|
|
59
|
+
startedAt: string;
|
|
60
|
+
autoStopMinutes: number;
|
|
61
|
+
type: TunnelType;
|
|
62
|
+
name?: string;
|
|
63
|
+
id?: string;
|
|
64
|
+
ingress?: IngressInfo[];
|
|
65
|
+
/** Number of live edge connections cloudflared has to Cloudflare; > 0 means the tunnel is publicly reachable. */
|
|
66
|
+
connections: number;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Recover the local port from a quick tunnel's resolved service URL (Clopen only ever exposes localhost ports). */
|
|
70
|
+
export function portFromService(service?: string): number {
|
|
71
|
+
if (!service) return 0;
|
|
72
|
+
try {
|
|
73
|
+
return Number(new URL(service).port) || 0;
|
|
74
|
+
} catch {
|
|
75
|
+
return 0;
|
|
198
76
|
}
|
|
199
|
-
|
|
200
|
-
writeConfigFile(data);
|
|
201
|
-
debug.log('tunnel', `Ingress rule added/updated for ${config.name}: ${hostname} -> ${service}`);
|
|
202
|
-
return config;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
export function removeLocalTunnelIngress(id: string, hostname: string): LocalTunnelConfig | null {
|
|
206
|
-
const data = readConfigFile();
|
|
207
|
-
const config = data.locals.find((c) => c.id === id);
|
|
208
|
-
if (!config) return null;
|
|
209
|
-
|
|
210
|
-
config.ingress = config.ingress.filter((r) => r.hostname !== hostname);
|
|
211
|
-
writeConfigFile(data);
|
|
212
|
-
debug.log('tunnel', `Ingress rule removed for ${config.name}: ${hostname}`);
|
|
213
|
-
return config;
|
|
214
77
|
}
|
|
215
78
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
79
|
+
/** Flatten tunnelkit's `ActiveTunnel` into the UI-facing shape (port extraction, connection count, etc.). */
|
|
80
|
+
export function mapActiveTunnel(t: ActiveTunnel): ActiveTunnelInfo {
|
|
81
|
+
return t.type === 'quick'
|
|
82
|
+
? {
|
|
83
|
+
port: portFromService(t.service),
|
|
84
|
+
publicUrl: t.publicUrl,
|
|
85
|
+
startedAt: t.startedAt,
|
|
86
|
+
autoStopMinutes: t.autoStopMinutes ?? 0,
|
|
87
|
+
type: t.type,
|
|
88
|
+
connections: t.connections.length
|
|
89
|
+
}
|
|
90
|
+
: {
|
|
91
|
+
port: 0,
|
|
92
|
+
publicUrl: t.publicUrl,
|
|
93
|
+
startedAt: t.startedAt,
|
|
94
|
+
autoStopMinutes: 0,
|
|
95
|
+
type: t.type,
|
|
96
|
+
name: t.name,
|
|
97
|
+
id: t.id,
|
|
98
|
+
ingress: t.ingress,
|
|
99
|
+
connections: t.connections.length
|
|
100
|
+
};
|
|
234
101
|
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
|
|
3
|
+
import { clientIpFromHeaders, clientIpFromRequest, clientIpFromConnection } from './client-ip';
|
|
4
|
+
|
|
5
|
+
describe('clientIpFromHeaders', () => {
|
|
6
|
+
test('prefers the leftmost x-forwarded-for hop', () => {
|
|
7
|
+
const headers = new Headers({ 'x-forwarded-for': '203.0.113.7, 70.41.3.18, 150.172.238.178' });
|
|
8
|
+
expect(clientIpFromHeaders(headers)).toBe('203.0.113.7');
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
test('falls back to x-real-ip when x-forwarded-for is absent', () => {
|
|
12
|
+
const headers = new Headers({ 'x-real-ip': '198.51.100.5' });
|
|
13
|
+
expect(clientIpFromHeaders(headers)).toBe('198.51.100.5');
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
test('returns undefined when no forwarding header is present', () => {
|
|
17
|
+
expect(clientIpFromHeaders(new Headers())).toBeUndefined();
|
|
18
|
+
});
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
describe('clientIpFromRequest', () => {
|
|
22
|
+
const makeServer = (address: string | null) => ({
|
|
23
|
+
requestIP: () => (address === null ? null : { address }),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('uses forwarding headers when present, ignoring the socket', () => {
|
|
27
|
+
const request = new Request('http://localhost/upload', {
|
|
28
|
+
headers: { 'x-forwarded-for': '203.0.113.7' },
|
|
29
|
+
});
|
|
30
|
+
expect(clientIpFromRequest(request, makeServer('10.0.0.1'))).toBe('203.0.113.7');
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('falls back to the socket address on a direct connection', () => {
|
|
34
|
+
const request = new Request('http://localhost/upload');
|
|
35
|
+
expect(clientIpFromRequest(request, makeServer('::1'))).toBe('::1');
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test('returns undefined when neither header nor socket resolves', () => {
|
|
39
|
+
const request = new Request('http://localhost/upload');
|
|
40
|
+
expect(clientIpFromRequest(request, makeServer(null))).toBeUndefined();
|
|
41
|
+
expect(clientIpFromRequest(request, null)).toBeUndefined();
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
describe('clientIpFromConnection', () => {
|
|
46
|
+
test('reads the socket remote address', () => {
|
|
47
|
+
const conn = { raw: { remoteAddress: '192.168.1.100' } } as any;
|
|
48
|
+
expect(clientIpFromConnection(conn)).toBe('192.168.1.100');
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test('returns undefined when the address is unavailable', () => {
|
|
52
|
+
expect(clientIpFromConnection({ raw: {} } as any)).toBeUndefined();
|
|
53
|
+
expect(clientIpFromConnection({} as any)).toBeUndefined();
|
|
54
|
+
});
|
|
55
|
+
});
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client IP resolution — one canonical place for both HTTP and WebSocket paths.
|
|
3
|
+
*
|
|
4
|
+
* Audit trails want the real client IP or nothing (null), so the connection/
|
|
5
|
+
* request helpers return `string | undefined`. Callers that need a stable,
|
|
6
|
+
* non-null key (e.g. rate-limit buckets) fall back to a sentinel at the call
|
|
7
|
+
* site — see `ws.getRemoteAddress`.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { WSConnection } from '$shared/utils/ws-server';
|
|
11
|
+
|
|
12
|
+
/** Structural subset of Bun's `Server` — just socket-address lookup, so we
|
|
13
|
+
* avoid coupling to its generic `Server<WebSocketData>` signature. */
|
|
14
|
+
type RequestIpResolver = { requestIP(request: Request): { address: string } | null };
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* First client IP from forwarding headers, preferring `x-forwarded-for`'s
|
|
18
|
+
* leftmost hop, then `x-real-ip`. Returns undefined when neither is present.
|
|
19
|
+
*/
|
|
20
|
+
export function clientIpFromHeaders(headers: Headers): string | undefined {
|
|
21
|
+
const forwarded = headers.get('x-forwarded-for')?.split(',')[0].trim();
|
|
22
|
+
if (forwarded) return forwarded;
|
|
23
|
+
return headers.get('x-real-ip') ?? undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Client IP for an HTTP request: forwarding headers first (correct when behind
|
|
28
|
+
* a reverse proxy), falling back to the socket address. Undefined when none
|
|
29
|
+
* resolve.
|
|
30
|
+
*/
|
|
31
|
+
export function clientIpFromRequest(request: Request, server: RequestIpResolver | null): string | undefined {
|
|
32
|
+
return clientIpFromHeaders(request.headers) ?? server?.requestIP(request)?.address ?? undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Client IP for a WebSocket connection — the socket's remote address, or
|
|
37
|
+
* undefined when unavailable.
|
|
38
|
+
*/
|
|
39
|
+
export function clientIpFromConnection(conn: WSConnection): string | undefined {
|
|
40
|
+
const raw = (conn as unknown as { raw?: { remoteAddress?: string } }).raw;
|
|
41
|
+
return raw?.remoteAddress ?? undefined;
|
|
42
|
+
}
|
package/backend/utils/ws.ts
CHANGED
|
@@ -33,6 +33,7 @@ import type { WSAPI } from '$backend/ws';
|
|
|
33
33
|
import type { WSConnection } from '$shared/utils/ws-server';
|
|
34
34
|
import { encodeBinaryMessage, isBinaryAction } from '$shared/utils/ws-server';
|
|
35
35
|
import { debug } from '$shared/utils/logger';
|
|
36
|
+
import { clientIpFromConnection } from './client-ip';
|
|
36
37
|
|
|
37
38
|
/**
|
|
38
39
|
* Performance configuration
|
|
@@ -571,11 +572,13 @@ class WSServer {
|
|
|
571
572
|
}
|
|
572
573
|
|
|
573
574
|
/**
|
|
574
|
-
* Get remote IP address of a connection.
|
|
575
|
+
* Get remote IP address of a connection as a stable rate-limit key.
|
|
576
|
+
* Falls back to 'unknown' so callers always have a non-null bucket key.
|
|
577
|
+
* For audit trails (which should record null, not a sentinel), use
|
|
578
|
+
* `clientIpFromConnection` directly.
|
|
575
579
|
*/
|
|
576
580
|
getRemoteAddress(conn: WSConnection): string {
|
|
577
|
-
|
|
578
|
-
return raw?.remoteAddress ?? 'unknown';
|
|
581
|
+
return clientIpFromConnection(conn) ?? 'unknown';
|
|
579
582
|
}
|
|
580
583
|
|
|
581
584
|
/**
|