@myrialabs/clopen 0.3.19 → 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/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/install-recipes.ts +1 -109
- package/backend/http/files-upload.ts +84 -3
- 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/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 +3 -4
- package/backend/ws/tunnel/config.ts +17 -25
- package/backend/ws/tunnel/operations.ts +63 -68
- package/dist/assets/{main-BOUXyIaW.js → main-72Z_L-nD.js} +199 -199
- package/dist/index.html +1 -1
- package/package.json +2 -1
- 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
|
@@ -58,6 +58,7 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
58
58
|
private defaultSchema: string | null = null;
|
|
59
59
|
private conn: DbClientConnection | null = null;
|
|
60
60
|
private tunnelPort: number | undefined = undefined;
|
|
61
|
+
private ensureLock = Promise.resolve();
|
|
61
62
|
|
|
62
63
|
private buildUrl(conn: DbClientConnection, tunnelPort?: number): string {
|
|
63
64
|
const host = tunnelPort ? '127.0.0.1' : (conn.host ?? '127.0.0.1');
|
|
@@ -91,31 +92,46 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
91
92
|
|
|
92
93
|
private async ensureDatabase(database?: string): Promise<void> {
|
|
93
94
|
if (!this.conn) return;
|
|
94
|
-
// No specific database → revert to the home database, so connection-level
|
|
95
|
-
// operations don't run against whatever database was last browsed.
|
|
96
95
|
const target = database || this.homeDb;
|
|
97
96
|
if (target === this.defaultDb) return;
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
97
|
+
|
|
98
|
+
let release: () => void;
|
|
99
|
+
const prev = this.ensureLock;
|
|
100
|
+
this.ensureLock = new Promise<void>((resolve) => { release = resolve; });
|
|
101
|
+
await prev;
|
|
102
|
+
|
|
103
|
+
try {
|
|
104
|
+
if (target === this.defaultDb) return;
|
|
105
|
+
const newConn = { ...this.conn, database: target };
|
|
106
|
+
const url = this.buildUrl(newConn, this.tunnelPort);
|
|
107
|
+
const next = new SQL(url);
|
|
108
|
+
await next.connect();
|
|
109
|
+
const prevSql = this.sql;
|
|
110
|
+
this.sql = next;
|
|
111
|
+
this.defaultDb = target;
|
|
112
|
+
this.conn = newConn;
|
|
113
|
+
this.alive = true;
|
|
114
|
+
if (prevSql) await prevSql.close().catch((err) => debug.warn('db-client', 'pg switch close error:', err));
|
|
115
|
+
} finally {
|
|
116
|
+
release!();
|
|
117
|
+
}
|
|
108
118
|
}
|
|
109
119
|
|
|
110
120
|
async close(): Promise<void> {
|
|
111
|
-
|
|
112
|
-
|
|
121
|
+
let release: () => void;
|
|
122
|
+
const prev = this.ensureLock;
|
|
123
|
+
this.ensureLock = new Promise<void>((resolve) => { release = resolve; });
|
|
124
|
+
await prev;
|
|
125
|
+
|
|
113
126
|
try {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
127
|
+
this.alive = false;
|
|
128
|
+
this.conn = null;
|
|
129
|
+
if (!this.sql) return;
|
|
130
|
+
await this.sql.close().catch((err) => debug.warn('db-client', 'Postgres close error:', err));
|
|
131
|
+
this.sql = null;
|
|
132
|
+
} finally {
|
|
133
|
+
release!();
|
|
117
134
|
}
|
|
118
|
-
this.sql = null;
|
|
119
135
|
}
|
|
120
136
|
|
|
121
137
|
isAlive(): boolean {
|
|
@@ -20,7 +20,7 @@ import { getClopenDir } from '$backend/utils/paths';
|
|
|
20
20
|
import { resolveBinary, resolveBinaryWithRefresh } from '$backend/utils/cli';
|
|
21
21
|
import { resolveStaticCurlAsset } from '$backend/utils/static-curl';
|
|
22
22
|
|
|
23
|
-
export type ToolId = 'git' | 'claude' | 'opencode' | 'copilot' | 'codex' | 'qwen' | 'chrome'
|
|
23
|
+
export type ToolId = 'git' | 'claude' | 'opencode' | 'copilot' | 'codex' | 'qwen' | 'chrome';
|
|
24
24
|
|
|
25
25
|
export interface ManualInstruction {
|
|
26
26
|
label: string;
|
|
@@ -205,15 +205,6 @@ export async function getToolStatus(tool: ToolId): Promise<ToolStatus> {
|
|
|
205
205
|
const version = await runVersion(resolved);
|
|
206
206
|
if (!version) return { tool, installed: false, version: null, source: null };
|
|
207
207
|
|
|
208
|
-
// Cloudflared: tag binaries under ~/.clopen/bin as "clopen"-managed so the
|
|
209
|
-
// UI distinguishes System Tools installs from system-wide ones.
|
|
210
|
-
if (tool === 'cloudflared') {
|
|
211
|
-
const clopenBinDir = join(getClopenDir(), 'bin');
|
|
212
|
-
if (resolved.startsWith(clopenBinDir)) {
|
|
213
|
-
return { tool, installed: true, version, source: 'clopen' };
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
|
|
217
208
|
return { tool, installed: true, version, source: resolved };
|
|
218
209
|
}
|
|
219
210
|
|
|
@@ -628,104 +619,6 @@ function pickLinuxChromeStrategy(
|
|
|
628
619
|
return null;
|
|
629
620
|
}
|
|
630
621
|
|
|
631
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
632
|
-
// Cloudflared recipe — downloads the Cloudflare-signed binary into ~/.clopen/bin
|
|
633
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
634
|
-
|
|
635
|
-
const CLOUDFLARED_RELEASE_BASE = 'https://github.com/cloudflare/cloudflared/releases/latest/download';
|
|
636
|
-
const CLOUDFLARED_DOCS = 'https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/';
|
|
637
|
-
|
|
638
|
-
const CLOUDFLARED_LINUX_ARCH: Record<string, string> = {
|
|
639
|
-
x64: 'amd64',
|
|
640
|
-
arm64: 'arm64',
|
|
641
|
-
arm: 'arm',
|
|
642
|
-
ia32: '386'
|
|
643
|
-
};
|
|
644
|
-
|
|
645
|
-
async function resolveCloudflaredRecipe(): Promise<Recipe> {
|
|
646
|
-
const base: Recipe = {
|
|
647
|
-
tool: 'cloudflared',
|
|
648
|
-
autoInstallable: false,
|
|
649
|
-
missingPrereqs: [],
|
|
650
|
-
manualInstructions: []
|
|
651
|
-
};
|
|
652
|
-
|
|
653
|
-
const binDir = join(getClopenDir(), 'bin');
|
|
654
|
-
|
|
655
|
-
if (process.platform === 'darwin') {
|
|
656
|
-
const archKey = process.arch === 'arm64' ? 'arm64' : 'amd64';
|
|
657
|
-
const file = `cloudflared-darwin-${archKey}.tgz`;
|
|
658
|
-
const url = `${CLOUDFLARED_RELEASE_BASE}/${file}`;
|
|
659
|
-
const cmd =
|
|
660
|
-
`mkdir -p "${binDir}" && ` +
|
|
661
|
-
`curl -fsSL -o "${binDir}/${file}" "${url}" && ` +
|
|
662
|
-
`tar -xzf "${binDir}/${file}" -C "${binDir}" && ` +
|
|
663
|
-
`rm -f "${binDir}/${file}" && ` +
|
|
664
|
-
`chmod +x "${binDir}/cloudflared"`;
|
|
665
|
-
|
|
666
|
-
base.manualInstructions.push({
|
|
667
|
-
label: 'curl + tar',
|
|
668
|
-
command: cmd,
|
|
669
|
-
docs: CLOUDFLARED_DOCS
|
|
670
|
-
});
|
|
671
|
-
if (!attachCurlRequirement(base, 'Cloudflared')) return base;
|
|
672
|
-
base.autoInstallable = true;
|
|
673
|
-
base.shell = { program: 'bash', args: ['-c'] };
|
|
674
|
-
base.command = [cmd];
|
|
675
|
-
base.displayCommand = cmd;
|
|
676
|
-
return base;
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
if (process.platform === 'linux') {
|
|
680
|
-
const archKey = CLOUDFLARED_LINUX_ARCH[process.arch];
|
|
681
|
-
if (!archKey) {
|
|
682
|
-
base.unavailableReason = `Cloudflared has no published Linux build for ${process.arch}.`;
|
|
683
|
-
return base;
|
|
684
|
-
}
|
|
685
|
-
const file = `cloudflared-linux-${archKey}`;
|
|
686
|
-
const url = `${CLOUDFLARED_RELEASE_BASE}/${file}`;
|
|
687
|
-
const cmd =
|
|
688
|
-
`mkdir -p "${binDir}" && ` +
|
|
689
|
-
`curl -fsSL -o "${binDir}/cloudflared" "${url}" && ` +
|
|
690
|
-
`chmod +x "${binDir}/cloudflared"`;
|
|
691
|
-
|
|
692
|
-
base.manualInstructions.push({
|
|
693
|
-
label: 'curl',
|
|
694
|
-
command: cmd,
|
|
695
|
-
docs: CLOUDFLARED_DOCS
|
|
696
|
-
});
|
|
697
|
-
if (!attachCurlRequirement(base, 'Cloudflared')) return base;
|
|
698
|
-
base.autoInstallable = true;
|
|
699
|
-
base.shell = { program: 'bash', args: ['-c'] };
|
|
700
|
-
base.command = [cmd];
|
|
701
|
-
base.displayCommand = cmd;
|
|
702
|
-
return base;
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
if (process.platform === 'win32') {
|
|
706
|
-
const archKey = process.arch === 'ia32' ? '386' : 'amd64';
|
|
707
|
-
const file = `cloudflared-windows-${archKey}.exe`;
|
|
708
|
-
const url = `${CLOUDFLARED_RELEASE_BASE}/${file}`;
|
|
709
|
-
const psCmd =
|
|
710
|
-
`New-Item -ItemType Directory -Path "${binDir}" -Force | Out-Null; ` +
|
|
711
|
-
`Invoke-WebRequest -Uri "${url}" -OutFile "${binDir}\\cloudflared.exe"`;
|
|
712
|
-
|
|
713
|
-
base.manualInstructions.push({
|
|
714
|
-
label: 'PowerShell',
|
|
715
|
-
command: psCmd,
|
|
716
|
-
docs: CLOUDFLARED_DOCS
|
|
717
|
-
});
|
|
718
|
-
base.autoInstallable = true;
|
|
719
|
-
base.shell = { program: 'powershell.exe', args: ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command'] };
|
|
720
|
-
base.command = [psCmd];
|
|
721
|
-
base.displayCommand = psCmd;
|
|
722
|
-
return base;
|
|
723
|
-
}
|
|
724
|
-
|
|
725
|
-
base.unavailableReason = `Unsupported platform: ${process.platform}`;
|
|
726
|
-
return base;
|
|
727
|
-
}
|
|
728
|
-
|
|
729
622
|
/**
|
|
730
623
|
* Resolve the install recipe for a tool on the current platform.
|
|
731
624
|
* Result is platform- and privilege-aware: recipes that would fail
|
|
@@ -740,6 +633,5 @@ export async function resolveRecipe(tool: ToolId): Promise<Recipe> {
|
|
|
740
633
|
case 'codex': return resolveCodexRecipe();
|
|
741
634
|
case 'qwen': return resolveQwenRecipe();
|
|
742
635
|
case 'chrome': return resolveChromeRecipe();
|
|
743
|
-
case 'cloudflared': return resolveCloudflaredRecipe();
|
|
744
636
|
}
|
|
745
637
|
}
|
|
@@ -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
|
});
|
|
@@ -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
|
}
|