@myrialabs/clopen 0.3.19 → 0.3.21
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/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/mysql.ts +28 -10
- package/backend/db-client/drivers/postgres.ts +34 -18
- package/backend/engine/adapters/claude/models.ts +43 -0
- package/backend/engine/install-recipes.ts +53 -140
- package/backend/engine/version-check.ts +145 -0
- package/backend/git/git-parser.ts +11 -0
- package/backend/git/git-service.ts +52 -7
- package/backend/http/files-upload.ts +84 -3
- package/backend/index.ts +27 -12
- 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/chat/stream.ts +17 -6
- package/backend/ws/files/path-access.test.ts +60 -1
- package/backend/ws/files/path-access.ts +21 -0
- package/backend/ws/system-tools/install.ts +0 -1
- package/backend/ws/system-tools/status.ts +17 -4
- package/backend/ws/tunnel/config.ts +17 -25
- package/backend/ws/tunnel/operations.ts +63 -68
- package/dist/assets/main-BgOiIS43.js +360 -0
- package/dist/assets/{main-ClADBkFf.css → main-CJdJeen6.css} +1 -1
- package/dist/index.html +2 -2
- package/package.json +4 -1
- package/shared/types/git.ts +8 -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-BOUXyIaW.js +0 -362
|
@@ -20,8 +20,9 @@ import { mkdir, rename, stat, unlink } from 'node:fs/promises';
|
|
|
20
20
|
|
|
21
21
|
import { debug } from '$shared/utils/logger';
|
|
22
22
|
import { hashToken } from '../auth/tokens';
|
|
23
|
-
import { authQueries } from '../database/queries';
|
|
24
|
-
import { requireFilePathAccessFor } from '../ws/files/path-access';
|
|
23
|
+
import { authQueries, fileAuditLogQueries } from '../database/queries';
|
|
24
|
+
import { findContainingProjectId, requireFilePathAccessFor } from '../ws/files/path-access';
|
|
25
|
+
import { clientIpFromRequest } from '../utils/client-ip';
|
|
25
26
|
import { validateFileSize } from '../files/file-size-limit';
|
|
26
27
|
|
|
27
28
|
type AuthIdentity = { userId: string; role: string };
|
|
@@ -50,7 +51,7 @@ function authenticate(request: Request): AuthIdentity {
|
|
|
50
51
|
return { userId: user.id, role: user.role };
|
|
51
52
|
}
|
|
52
53
|
|
|
53
|
-
export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({ request, query }) => {
|
|
54
|
+
export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({ request, query, server }) => {
|
|
54
55
|
let identity: AuthIdentity;
|
|
55
56
|
try {
|
|
56
57
|
identity = authenticate(request);
|
|
@@ -71,9 +72,24 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
|
|
|
71
72
|
return new Response('Invalid fileSize query parameter', { status: 400 });
|
|
72
73
|
}
|
|
73
74
|
|
|
75
|
+
const ipAddress = clientIpFromRequest(request, server);
|
|
76
|
+
const userAgent = request.headers.get('user-agent') ?? undefined;
|
|
77
|
+
const projectId = await findContainingProjectId(`${targetPathParam}/${fileNameParam}`);
|
|
78
|
+
|
|
74
79
|
try {
|
|
75
80
|
validateFileSize(fileSizeParam);
|
|
76
81
|
} catch (error) {
|
|
82
|
+
fileAuditLogQueries.logOperation({
|
|
83
|
+
userId: identity.userId,
|
|
84
|
+
projectId,
|
|
85
|
+
action: 'upload',
|
|
86
|
+
filePath: `${targetPathParam}/${fileNameParam}`,
|
|
87
|
+
fileSize: fileSizeParam,
|
|
88
|
+
ipAddress,
|
|
89
|
+
userAgent,
|
|
90
|
+
success: false,
|
|
91
|
+
errorMessage: 'File too large'
|
|
92
|
+
});
|
|
77
93
|
return new Response(error instanceof Error ? error.message : 'Invalid file size', { status: 413 });
|
|
78
94
|
}
|
|
79
95
|
|
|
@@ -85,6 +101,17 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
|
|
|
85
101
|
resolvedFinal = await requireFilePathAccessFor(tentativeFinal, identity.role, identity.userId);
|
|
86
102
|
} catch (error) {
|
|
87
103
|
const message = error instanceof Error ? error.message : 'Access denied';
|
|
104
|
+
fileAuditLogQueries.logOperation({
|
|
105
|
+
userId: identity.userId,
|
|
106
|
+
projectId,
|
|
107
|
+
action: 'upload',
|
|
108
|
+
filePath: `${targetPathParam}/${fileNameParam}`,
|
|
109
|
+
fileSize: fileSizeParam,
|
|
110
|
+
ipAddress,
|
|
111
|
+
userAgent,
|
|
112
|
+
success: false,
|
|
113
|
+
errorMessage: 'Path access denied'
|
|
114
|
+
});
|
|
88
115
|
return new Response(message, { status: 403 });
|
|
89
116
|
}
|
|
90
117
|
|
|
@@ -99,6 +126,17 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
|
|
|
99
126
|
}
|
|
100
127
|
|
|
101
128
|
if (await Bun.file(resolvedFinal).exists()) {
|
|
129
|
+
fileAuditLogQueries.logOperation({
|
|
130
|
+
userId: identity.userId,
|
|
131
|
+
projectId,
|
|
132
|
+
action: 'upload',
|
|
133
|
+
filePath: resolvedFinal,
|
|
134
|
+
fileSize: fileSizeParam,
|
|
135
|
+
ipAddress,
|
|
136
|
+
userAgent,
|
|
137
|
+
success: false,
|
|
138
|
+
errorMessage: 'File already exists'
|
|
139
|
+
});
|
|
102
140
|
return new Response('File already exists', { status: 409 });
|
|
103
141
|
}
|
|
104
142
|
|
|
@@ -141,18 +179,50 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
|
|
|
141
179
|
validateFileSize(written);
|
|
142
180
|
} catch (error) {
|
|
143
181
|
await unlink(tempPath).catch(() => {});
|
|
182
|
+
fileAuditLogQueries.logOperation({
|
|
183
|
+
userId: identity.userId,
|
|
184
|
+
projectId,
|
|
185
|
+
action: 'upload',
|
|
186
|
+
filePath: resolvedFinal,
|
|
187
|
+
fileSize: written,
|
|
188
|
+
ipAddress,
|
|
189
|
+
userAgent,
|
|
190
|
+
success: false,
|
|
191
|
+
errorMessage: 'File too large'
|
|
192
|
+
});
|
|
144
193
|
return new Response(error instanceof Error ? error.message : 'File too large', { status: 413 });
|
|
145
194
|
}
|
|
146
195
|
|
|
147
196
|
// Race-check: refuse to overwrite if the destination appeared mid-upload.
|
|
148
197
|
if (await Bun.file(resolvedFinal).exists()) {
|
|
149
198
|
await unlink(tempPath).catch(() => {});
|
|
199
|
+
fileAuditLogQueries.logOperation({
|
|
200
|
+
userId: identity.userId,
|
|
201
|
+
projectId,
|
|
202
|
+
action: 'upload',
|
|
203
|
+
filePath: resolvedFinal,
|
|
204
|
+
fileSize: written,
|
|
205
|
+
ipAddress,
|
|
206
|
+
userAgent,
|
|
207
|
+
success: false,
|
|
208
|
+
errorMessage: 'File already exists (race condition)'
|
|
209
|
+
});
|
|
150
210
|
return new Response('File already exists', { status: 409 });
|
|
151
211
|
}
|
|
152
212
|
|
|
153
213
|
await rename(tempPath, resolvedFinal);
|
|
154
214
|
const stats = await stat(resolvedFinal);
|
|
155
215
|
|
|
216
|
+
fileAuditLogQueries.logOperation({
|
|
217
|
+
userId: identity.userId,
|
|
218
|
+
projectId,
|
|
219
|
+
action: 'upload',
|
|
220
|
+
filePath: resolvedFinal,
|
|
221
|
+
fileSize: stats.size,
|
|
222
|
+
ipAddress,
|
|
223
|
+
userAgent
|
|
224
|
+
});
|
|
225
|
+
|
|
156
226
|
return Response.json({
|
|
157
227
|
message: 'File uploaded successfully',
|
|
158
228
|
path: resolvedFinal,
|
|
@@ -163,6 +233,17 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
|
|
|
163
233
|
await cleanupTemp();
|
|
164
234
|
debug.error('file', 'HTTP upload error:', error);
|
|
165
235
|
const message = error instanceof Error ? error.message : 'Upload failed';
|
|
236
|
+
fileAuditLogQueries.logOperation({
|
|
237
|
+
userId: identity.userId,
|
|
238
|
+
projectId,
|
|
239
|
+
action: 'upload',
|
|
240
|
+
filePath: resolvedFinal,
|
|
241
|
+
fileSize: written,
|
|
242
|
+
ipAddress,
|
|
243
|
+
userAgent,
|
|
244
|
+
success: false,
|
|
245
|
+
errorMessage: message
|
|
246
|
+
});
|
|
166
247
|
return new Response(message, { status: 500 });
|
|
167
248
|
}
|
|
168
249
|
});
|
package/backend/index.ts
CHANGED
|
@@ -240,20 +240,23 @@ process.on('SIGHUP', () => {
|
|
|
240
240
|
debug.log('server', 'Received SIGHUP — ignoring (server stays running)');
|
|
241
241
|
});
|
|
242
242
|
|
|
243
|
-
// Safety net: prevent server crash from unhandled
|
|
244
|
-
// These can occur when
|
|
245
|
-
// the normal try/catch flow
|
|
243
|
+
// Safety net: prevent server crash from unhandled promise rejections.
|
|
244
|
+
// These can occur when third-party SDKs emit asynchronous errors that bypass
|
|
245
|
+
// the normal try/catch flow, e.g.:
|
|
246
|
+
// - AI engine SDKs whose subprocess is killed during initialization
|
|
247
|
+
// - puppeteer-extra's stealth evasions fire a non-awaited
|
|
248
|
+
// `Network.setUserAgentOverride` on a newly created popup target; when the
|
|
249
|
+
// target closes mid-call the resulting TargetCloseError rejects with no
|
|
250
|
+
// handler attached and would otherwise kill the whole server while the user
|
|
251
|
+
// is interacting with the Preview.
|
|
246
252
|
//
|
|
247
|
-
// IMPORTANT
|
|
248
|
-
// process.on('unhandledRejection')
|
|
249
|
-
//
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
event.preventDefault();
|
|
254
|
-
|
|
253
|
+
// IMPORTANT (Bun routing — verified on Bun 1.3.14): top-level unhandled
|
|
254
|
+
// rejections are suppressed by Node's process.on('unhandledRejection') but NOT
|
|
255
|
+
// by the Web API globalThis.addEventListener('unhandledrejection') +
|
|
256
|
+
// preventDefault() (the Web handler does not even fire for these). We register
|
|
257
|
+
// BOTH for cross-version safety; the shared reporter below dedups intent.
|
|
258
|
+
function reportUnhandledRejection(reason: unknown): void {
|
|
255
259
|
try {
|
|
256
|
-
const reason = event.reason;
|
|
257
260
|
const message = reason instanceof Error ? reason.message : String(reason);
|
|
258
261
|
if (message.includes('Operation aborted') || message.includes('aborted')) {
|
|
259
262
|
debug.warn('server', 'Suppressed expected SDK abort rejection:', message);
|
|
@@ -263,6 +266,18 @@ globalThis.addEventListener('unhandledrejection', (event: PromiseRejectionEvent)
|
|
|
263
266
|
} catch {
|
|
264
267
|
console.error('Unhandled promise rejection (server still running)');
|
|
265
268
|
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Primary net on Bun 1.3.x — registering this handler prevents the default
|
|
272
|
+
// crash-on-unhandled-rejection behavior.
|
|
273
|
+
process.on('unhandledRejection', (reason) => {
|
|
274
|
+
reportUnhandledRejection(reason);
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
// Belt-and-suspenders for Bun versions where only the Web API suppresses exit.
|
|
278
|
+
globalThis.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {
|
|
279
|
+
event.preventDefault();
|
|
280
|
+
reportUnhandledRejection(event.reason);
|
|
266
281
|
});
|
|
267
282
|
|
|
268
283
|
process.on('uncaughtException', (error) => {
|
|
@@ -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
|
/**
|