@myrialabs/clopen 0.4.33 → 0.4.34
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/permissions.ts +3 -0
- package/backend/auth/rate-limiter.test.ts +115 -0
- package/backend/auth/rate-limiter.ts +25 -12
- package/backend/db-client/connection-manager.ts +13 -0
- package/backend/index.ts +9 -0
- package/backend/middleware/security.test.ts +95 -0
- package/backend/middleware/security.ts +114 -0
- package/backend/ports/attribute.test.ts +231 -0
- package/backend/ports/attribute.ts +444 -0
- package/backend/ports/kill.ts +203 -0
- package/backend/ports/monitor.ts +365 -0
- package/backend/ports/processes.test.ts +98 -0
- package/backend/ports/processes.ts +374 -0
- package/backend/ports/registry.ts +165 -0
- package/backend/ports/runner.ts +195 -0
- package/backend/ports/scan-host.ts +260 -0
- package/backend/ports/scan.test.ts +341 -0
- package/backend/ports/scan.ts +687 -0
- package/backend/ports/ssh-lineage.ts +318 -0
- package/backend/ssh/forwards.ts +31 -0
- package/backend/ws/auth/device.ts +1 -1
- package/backend/ws/auth/login.ts +8 -4
- package/backend/ws/index.ts +2 -0
- package/backend/ws/ports/index.ts +19 -0
- package/backend/ws/ports/kill.ts +80 -0
- package/backend/ws/ports/list.ts +60 -0
- package/dist/assets/{index-BW0DA8NV.js → index-gGTMFUa8.js} +1 -1
- package/dist/assets/{index-BF4buYmI.js → index-vW2RpdHu.js} +1 -1
- package/dist/assets/main-CYCMEbXB.css +1 -0
- package/dist/assets/{main-BbwWLJRN.js → main-ZCojSzvW.js} +409 -406
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/ports/index.ts +5 -0
- package/shared/types/ports/port.ts +192 -0
- package/shared/utils/logger.ts +1 -0
- package/dist/assets/main-CCvRMXlP.css +0 -1
|
@@ -43,6 +43,9 @@ export const ADMIN_ONLY_ROUTES = new Set([
|
|
|
43
43
|
'settings:update-batch',
|
|
44
44
|
'system:run-update',
|
|
45
45
|
'system:clear-data',
|
|
46
|
+
// Port manager — anyone signed in may see what is listening, but ending a
|
|
47
|
+
// process can take down another member's work, so stopping is admin-only.
|
|
48
|
+
'ports:kill',
|
|
46
49
|
// Stack — binary installation is an admin-only operation.
|
|
47
50
|
'stack:status',
|
|
48
51
|
'stack:status-all',
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Behavior-based tests for AuthRateLimiter.
|
|
3
|
+
*
|
|
4
|
+
* Validates:
|
|
5
|
+
* - Failure-based lockout tiers (5/10/20 → 30s/2m/10m) still trigger.
|
|
6
|
+
* - Lockout state is per-route and per-identifier, so a lockout on one
|
|
7
|
+
* endpoint neither blocks nor is cleared by another.
|
|
8
|
+
* - `recordSuccess` clears only its own route's record.
|
|
9
|
+
*
|
|
10
|
+
* Each test uses a unique identifier so the singleton's in-memory state does
|
|
11
|
+
* not bleed across tests.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { describe, expect, test } from 'bun:test';
|
|
15
|
+
import { authRateLimiter } from './rate-limiter';
|
|
16
|
+
|
|
17
|
+
let seq = 0;
|
|
18
|
+
function uniqueId(label: string): string {
|
|
19
|
+
// IPv4-shaped string the rate limiter treats as opaque.
|
|
20
|
+
return `203.0.113.${++seq}-${label}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Read the remaining lockout out of `check()`'s message. */
|
|
24
|
+
function remainingMs(result: string | null): number | null {
|
|
25
|
+
if (result === null) return null;
|
|
26
|
+
const match = result.match(/Try again in (\d+) seconds/);
|
|
27
|
+
return match ? Number(match[1]) * 1000 : 0;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Drive an identifier to `count` failures on one route. */
|
|
31
|
+
function fail(id: string, action: string, count: number): void {
|
|
32
|
+
for (let i = 0; i < count; i++) authRateLimiter.recordFailure(id, action);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
describe('failure-based lockout tiers', () => {
|
|
36
|
+
test('four failures stay below the first threshold', () => {
|
|
37
|
+
const id = uniqueId('4fail');
|
|
38
|
+
fail(id, 'auth:login', 4);
|
|
39
|
+
expect(authRateLimiter.check(id, 'auth:login')).toBeNull();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('five failures lock for 30s', () => {
|
|
43
|
+
const id = uniqueId('5fail');
|
|
44
|
+
fail(id, 'auth:login', 5);
|
|
45
|
+
expect(remainingMs(authRateLimiter.check(id, 'auth:login'))).toBeGreaterThanOrEqual(25_000);
|
|
46
|
+
expect(remainingMs(authRateLimiter.check(id, 'auth:login'))).toBeLessThanOrEqual(30_500);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test('ten failures escalate to a 2-minute lockout', () => {
|
|
50
|
+
const id = uniqueId('10fail');
|
|
51
|
+
fail(id, 'auth:login', 10);
|
|
52
|
+
expect(remainingMs(authRateLimiter.check(id, 'auth:login'))).toBeGreaterThanOrEqual(115_000);
|
|
53
|
+
expect(remainingMs(authRateLimiter.check(id, 'auth:login'))).toBeLessThanOrEqual(120_500);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test('twenty failures escalate to a 10-minute lockout', () => {
|
|
57
|
+
const id = uniqueId('20fail');
|
|
58
|
+
fail(id, 'auth:login', 20);
|
|
59
|
+
expect(remainingMs(authRateLimiter.check(id, 'auth:login'))).toBeGreaterThanOrEqual(595_000);
|
|
60
|
+
expect(remainingMs(authRateLimiter.check(id, 'auth:login'))).toBeLessThanOrEqual(600_500);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('routes outside the rate-limited set are ignored', () => {
|
|
64
|
+
const id = uniqueId('unlimited');
|
|
65
|
+
fail(id, 'auth:logout', 5);
|
|
66
|
+
expect(authRateLimiter.check(id, 'auth:logout')).toBeNull();
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
describe('per-route isolation', () => {
|
|
71
|
+
test('a lockout on auth:login does not block auth:validate-invite', () => {
|
|
72
|
+
const id = uniqueId('route-iso');
|
|
73
|
+
fail(id, 'auth:login', 5);
|
|
74
|
+
|
|
75
|
+
expect(authRateLimiter.check(id, 'auth:login')).not.toBeNull();
|
|
76
|
+
expect(authRateLimiter.check(id, 'auth:validate-invite')).toBeNull();
|
|
77
|
+
expect(authRateLimiter.check(id, 'auth:claim-device-code')).toBeNull();
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test('success on one route does not clear another route\'s failures', () => {
|
|
81
|
+
const id = uniqueId('no-cross-clear');
|
|
82
|
+
fail(id, 'auth:login', 5);
|
|
83
|
+
authRateLimiter.recordSuccess(id, 'auth:validate-invite');
|
|
84
|
+
|
|
85
|
+
expect(authRateLimiter.check(id, 'auth:login')).not.toBeNull();
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test('success clears the lockout for its own route', () => {
|
|
89
|
+
const id = uniqueId('self-clear');
|
|
90
|
+
fail(id, 'auth:login', 5);
|
|
91
|
+
authRateLimiter.recordSuccess(id, 'auth:login');
|
|
92
|
+
|
|
93
|
+
expect(authRateLimiter.check(id, 'auth:login')).toBeNull();
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test('a valid invite clears the failures from earlier mistyped ones', () => {
|
|
97
|
+
const id = uniqueId('invite-retry');
|
|
98
|
+
fail(id, 'auth:validate-invite', 2);
|
|
99
|
+
authRateLimiter.recordSuccess(id, 'auth:validate-invite');
|
|
100
|
+
fail(id, 'auth:validate-invite', 4);
|
|
101
|
+
|
|
102
|
+
expect(authRateLimiter.check(id, 'auth:validate-invite')).toBeNull();
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
describe('per-identifier isolation', () => {
|
|
107
|
+
test('one identifier locking out does not affect another', () => {
|
|
108
|
+
const idA = uniqueId('ipA');
|
|
109
|
+
const idB = uniqueId('ipB');
|
|
110
|
+
fail(idA, 'auth:login', 5);
|
|
111
|
+
|
|
112
|
+
expect(authRateLimiter.check(idA, 'auth:login')).not.toBeNull();
|
|
113
|
+
expect(authRateLimiter.check(idB, 'auth:login')).toBeNull();
|
|
114
|
+
});
|
|
115
|
+
});
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Auth Rate Limiter
|
|
3
3
|
*
|
|
4
4
|
* Protects auth endpoints against brute-force and credential stuffing attacks.
|
|
5
|
-
* Tracks failed attempts per IP with progressive lockout.
|
|
5
|
+
* Tracks failed attempts per (IP, route) with progressive lockout.
|
|
6
6
|
*
|
|
7
7
|
* Thresholds:
|
|
8
8
|
* 5 failures → 30 second lockout
|
|
@@ -10,11 +10,15 @@
|
|
|
10
10
|
* 20 failures → 10 minute lockout
|
|
11
11
|
*
|
|
12
12
|
* Attempts decay after the lockout window expires.
|
|
13
|
+
*
|
|
14
|
+
* Records are keyed by IP *and* route: a lockout earned on one endpoint must
|
|
15
|
+
* not block an unrelated one, and clearing one route's record on success must
|
|
16
|
+
* not wipe another route's accumulated failures.
|
|
13
17
|
*/
|
|
14
18
|
|
|
15
19
|
import { debug } from '$shared/utils/logger';
|
|
16
20
|
|
|
17
|
-
/** Routes that should be rate-limited */
|
|
21
|
+
/** Routes that should be rate-limited. */
|
|
18
22
|
const RATE_LIMITED_ROUTES = new Set([
|
|
19
23
|
'auth:login',
|
|
20
24
|
'auth:accept-invite',
|
|
@@ -43,6 +47,7 @@ const STALE_AFTER_MS = 15 * 60_000; // 15 minutes
|
|
|
43
47
|
const CLEANUP_INTERVAL_MS = 5 * 60_000; // 5 minutes
|
|
44
48
|
|
|
45
49
|
class AuthRateLimiter {
|
|
50
|
+
/** Keyed by `${identifier}::${action}` — see the note on the module doc. */
|
|
46
51
|
private attempts = new Map<string, AttemptRecord>();
|
|
47
52
|
private cleanupTimer: ReturnType<typeof setInterval> | null = null;
|
|
48
53
|
|
|
@@ -51,6 +56,10 @@ class AuthRateLimiter {
|
|
|
51
56
|
this.cleanupTimer = setInterval(() => this.cleanup(), CLEANUP_INTERVAL_MS);
|
|
52
57
|
}
|
|
53
58
|
|
|
59
|
+
private static recordKey(identifier: string, action: string): string {
|
|
60
|
+
return `${identifier}::${action}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
54
63
|
/**
|
|
55
64
|
* Check if an action is rate-limited for the given identifier.
|
|
56
65
|
* Returns null if allowed, or an error message if blocked.
|
|
@@ -60,9 +69,9 @@ class AuthRateLimiter {
|
|
|
60
69
|
return null; // Not a rate-limited route
|
|
61
70
|
}
|
|
62
71
|
|
|
63
|
-
const record = this.attempts.get(identifier);
|
|
72
|
+
const record = this.attempts.get(AuthRateLimiter.recordKey(identifier, action));
|
|
64
73
|
if (!record) {
|
|
65
|
-
return null; // No previous
|
|
74
|
+
return null; // No previous activity
|
|
66
75
|
}
|
|
67
76
|
|
|
68
77
|
const now = Date.now();
|
|
@@ -70,7 +79,7 @@ class AuthRateLimiter {
|
|
|
70
79
|
// Check if currently locked out
|
|
71
80
|
if (record.lockedUntil > now) {
|
|
72
81
|
const remainingSec = Math.ceil((record.lockedUntil - now) / 1000);
|
|
73
|
-
debug.warn('auth', `Rate limited: ${identifier} (${remainingSec}s remaining, ${record.failures} failures)`);
|
|
82
|
+
debug.warn('auth', `Rate limited: ${identifier} on ${action} (${remainingSec}s remaining, ${record.failures} failures)`);
|
|
74
83
|
return `Too many failed attempts. Try again in ${remainingSec} seconds.`;
|
|
75
84
|
}
|
|
76
85
|
|
|
@@ -78,13 +87,15 @@ class AuthRateLimiter {
|
|
|
78
87
|
}
|
|
79
88
|
|
|
80
89
|
/**
|
|
81
|
-
* Record a failed auth attempt for the given identifier.
|
|
90
|
+
* Record a failed auth attempt for the given identifier + action.
|
|
91
|
+
* Escalates the failure-tier lockout when a new threshold is crossed.
|
|
82
92
|
*/
|
|
83
93
|
recordFailure(identifier: string, action: string): void {
|
|
84
94
|
if (!RATE_LIMITED_ROUTES.has(action)) return;
|
|
85
95
|
|
|
86
96
|
const now = Date.now();
|
|
87
|
-
const
|
|
97
|
+
const key = AuthRateLimiter.recordKey(identifier, action);
|
|
98
|
+
const record = this.attempts.get(key) ?? { failures: 0, lastFailure: 0, lockedUntil: 0 };
|
|
88
99
|
|
|
89
100
|
record.failures += 1;
|
|
90
101
|
record.lastFailure = now;
|
|
@@ -99,17 +110,19 @@ class AuthRateLimiter {
|
|
|
99
110
|
|
|
100
111
|
if (lockoutMs > 0) {
|
|
101
112
|
record.lockedUntil = now + lockoutMs;
|
|
102
|
-
debug.warn('auth', `Lockout triggered: ${identifier} — ${record.failures} failures, locked for ${lockoutMs / 1000}s`);
|
|
113
|
+
debug.warn('auth', `Lockout triggered: ${identifier} on ${action} — ${record.failures} failures, locked for ${lockoutMs / 1000}s`);
|
|
103
114
|
}
|
|
104
115
|
|
|
105
|
-
this.attempts.set(
|
|
116
|
+
this.attempts.set(key, record);
|
|
106
117
|
}
|
|
107
118
|
|
|
108
119
|
/**
|
|
109
|
-
* Clear failure record on successful auth (e.g., successful
|
|
120
|
+
* Clear the failure record for this route on successful auth (e.g., successful
|
|
121
|
+
* login). Other routes keep whatever they had accumulated.
|
|
110
122
|
*/
|
|
111
|
-
recordSuccess(identifier: string): void {
|
|
112
|
-
|
|
123
|
+
recordSuccess(identifier: string, action: string): void {
|
|
124
|
+
if (!RATE_LIMITED_ROUTES.has(action)) return;
|
|
125
|
+
this.attempts.delete(AuthRateLimiter.recordKey(identifier, action));
|
|
113
126
|
}
|
|
114
127
|
|
|
115
128
|
/**
|
|
@@ -40,6 +40,19 @@ class ConnectionManager {
|
|
|
40
40
|
private entries = new Map<string, ConnectionEntry>();
|
|
41
41
|
private sweeperHandle: ReturnType<typeof setInterval> | null = null;
|
|
42
42
|
|
|
43
|
+
/**
|
|
44
|
+
* Local ports currently held open by SSH tunnels, for the port manager.
|
|
45
|
+
* These are ephemeral ports nobody asked for by number, so without this the
|
|
46
|
+
* panel would show them as an unexplained listener owned by Clopen itself.
|
|
47
|
+
*/
|
|
48
|
+
activeTunnelPorts(): Array<{ connectionId: string; localPort: number }> {
|
|
49
|
+
const ports: Array<{ connectionId: string; localPort: number }> = [];
|
|
50
|
+
for (const [connectionId, entry] of this.entries) {
|
|
51
|
+
if (entry.tunnel) ports.push({ connectionId, localPort: entry.tunnel.localPort });
|
|
52
|
+
}
|
|
53
|
+
return ports;
|
|
54
|
+
}
|
|
55
|
+
|
|
43
56
|
private startSweeper(): void {
|
|
44
57
|
if (this.sweeperHandle) return;
|
|
45
58
|
this.sweeperHandle = setInterval(() => {
|
package/backend/index.ts
CHANGED
|
@@ -20,6 +20,7 @@ import { Elysia } from 'elysia';
|
|
|
20
20
|
import { corsMiddleware } from './middleware/cors';
|
|
21
21
|
import { errorHandlerMiddleware } from './middleware/error-handler';
|
|
22
22
|
import { loggerMiddleware } from './middleware/logger';
|
|
23
|
+
import { securityMiddleware } from './middleware/security';
|
|
23
24
|
|
|
24
25
|
// Database initialization
|
|
25
26
|
import { initializeDatabase, closeDatabase } from './database';
|
|
@@ -63,6 +64,7 @@ import { getAuthMode } from './settings/system-settings';
|
|
|
63
64
|
import { authQueries } from './database/queries';
|
|
64
65
|
import { authRateLimiter } from './auth';
|
|
65
66
|
import { sessionCleanupScheduler } from './auth/session-cleanup';
|
|
67
|
+
import { portMonitor } from './ports/monitor';
|
|
66
68
|
import { uploadTempCleanup } from './http/upload-temp-cleanup';
|
|
67
69
|
import { ws as wsServer } from './utils/ws';
|
|
68
70
|
import { messageRateLimiter } from './ws/message-rate-limiter';
|
|
@@ -129,6 +131,7 @@ const HOST = SERVER_ENV.HOST;
|
|
|
129
131
|
const app = new Elysia()
|
|
130
132
|
// Apply middleware
|
|
131
133
|
.use(corsMiddleware)
|
|
134
|
+
.use(securityMiddleware)
|
|
132
135
|
.use(errorHandlerMiddleware)
|
|
133
136
|
.use(loggerMiddleware)
|
|
134
137
|
|
|
@@ -267,6 +270,10 @@ async function startServer() {
|
|
|
267
270
|
// which also runs on the live process during "Clear All Data".
|
|
268
271
|
startEngineHotReload();
|
|
269
272
|
startEngineConfigWatcher();
|
|
273
|
+
// Sidebar count for the port manager. Idle-cheap by construction: with no
|
|
274
|
+
// terminal sessions running there are no session-born ports to count, so
|
|
275
|
+
// the tick skips the scan entirely.
|
|
276
|
+
portMonitor.start();
|
|
270
277
|
} catch (error) {
|
|
271
278
|
console.error('❌ Database initialization failed — refusing to start:', error);
|
|
272
279
|
console.error(` Data directory: ${SERVER_ENV.DATA_DIR}`);
|
|
@@ -330,6 +337,8 @@ async function gracefulShutdown() {
|
|
|
330
337
|
sessionCleanupScheduler.dispose();
|
|
331
338
|
// Dispose upload temp cleanup timer
|
|
332
339
|
uploadTempCleanup.dispose();
|
|
340
|
+
// Stop port polling and release any SSH leases it holds
|
|
341
|
+
portMonitor.stop();
|
|
333
342
|
// Close MCP remote server (before engines, as they may still reference it)
|
|
334
343
|
await closeMcpServer();
|
|
335
344
|
// Cleanup browser preview sessions
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The headers are only worth anything if they survive the way Clopen actually
|
|
3
|
+
* returns responses. The SPA fallback and the static file handler in
|
|
4
|
+
* `backend/index.ts` hand back a raw `Response`, which is a different path
|
|
5
|
+
* through Elysia than a plain object return — so both are exercised here.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { describe, expect, test } from 'bun:test';
|
|
9
|
+
import { Elysia } from 'elysia';
|
|
10
|
+
import { SECURITY_HEADERS, securityMiddleware } from './security';
|
|
11
|
+
|
|
12
|
+
const app = new Elysia()
|
|
13
|
+
.use(securityMiddleware)
|
|
14
|
+
.get('/json', () => ({ ok: true }))
|
|
15
|
+
// Mirrors the production SPA fallback: a raw Response with its own headers.
|
|
16
|
+
.get('/spa', () => new Response('<!doctype html>', {
|
|
17
|
+
headers: { 'Content-Type': 'text/html; charset=utf-8' }
|
|
18
|
+
}));
|
|
19
|
+
|
|
20
|
+
async function headersFor(path: string): Promise<Headers> {
|
|
21
|
+
const response = await app.handle(new Request(`http://localhost${path}`));
|
|
22
|
+
return response.headers;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function csp(headers: Headers): string {
|
|
26
|
+
return headers.get('content-security-policy') ?? '';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
describe('security headers reach the response', () => {
|
|
30
|
+
for (const path of ['/json', '/spa']) {
|
|
31
|
+
test(`every header is set on ${path}`, async () => {
|
|
32
|
+
const headers = await headersFor(path);
|
|
33
|
+
for (const [name, value] of Object.entries(SECURITY_HEADERS)) {
|
|
34
|
+
expect(headers.get(name.toLowerCase())).toBe(value);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
test('the raw Response keeps its own Content-Type', async () => {
|
|
40
|
+
const headers = await headersFor('/spa');
|
|
41
|
+
expect(headers.get('content-type')).toBe('text/html; charset=utf-8');
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
describe('CSP covers what the app loads', () => {
|
|
46
|
+
test('Monaco can load its scripts, styles and codicon font from the CDN', async () => {
|
|
47
|
+
const policy = csp(await headersFor('/spa'));
|
|
48
|
+
for (const directive of ['script-src', 'style-src', 'font-src', 'connect-src']) {
|
|
49
|
+
expect(policy).toMatch(new RegExp(`${directive} [^;]*https://cdn\\.jsdelivr\\.net`));
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("Monaco's blob-bootstrapped language workers are allowed", async () => {
|
|
54
|
+
const policy = csp(await headersFor('/spa'));
|
|
55
|
+
expect(policy).toMatch(/script-src [^;]*blob:/);
|
|
56
|
+
expect(policy).toMatch(/worker-src [^;]*blob:/);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('object-URL previews are allowed for media, frames and images', async () => {
|
|
60
|
+
const policy = csp(await headersFor('/spa'));
|
|
61
|
+
// MediaPreview.svelte: <audio>/<video> src, the PDF <iframe>, and images.
|
|
62
|
+
expect(policy).toMatch(/media-src [^;]*blob:/);
|
|
63
|
+
expect(policy).toMatch(/frame-src [^;]*blob:/);
|
|
64
|
+
expect(policy).toMatch(/img-src [^;]*blob:/);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test('remote images in rendered markdown are not blocked', async () => {
|
|
68
|
+
const policy = csp(await headersFor('/spa'));
|
|
69
|
+
expect(policy).toMatch(/img-src [^;]*https:/);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test('embedding, base rewriting and off-site form posts are shut down', async () => {
|
|
73
|
+
const policy = csp(await headersFor('/spa'));
|
|
74
|
+
expect(policy).toContain("frame-ancestors 'none'");
|
|
75
|
+
expect(policy).toContain("object-src 'none'");
|
|
76
|
+
expect(policy).toContain("base-uri 'self'");
|
|
77
|
+
expect(policy).toContain("form-action 'self'");
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
describe('Permissions-Policy matches what the host bridge relays', () => {
|
|
82
|
+
test('device APIs the Preview Browser relays stay available to the app', async () => {
|
|
83
|
+
const policy = (await headersFor('/spa')).get('permissions-policy') ?? '';
|
|
84
|
+
for (const feature of ['camera', 'microphone', 'geolocation', 'display-capture', 'clipboard-read']) {
|
|
85
|
+
expect(policy).toContain(`${feature}=(self)`);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test('features Clopen never uses are denied', async () => {
|
|
90
|
+
const policy = (await headersFor('/spa')).get('permissions-policy') ?? '';
|
|
91
|
+
for (const feature of ['payment', 'usb', 'serial', 'bluetooth', 'midi', 'hid']) {
|
|
92
|
+
expect(policy).toContain(`${feature}=()`);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
});
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { Elysia } from 'elysia';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Security Headers Middleware
|
|
5
|
+
*
|
|
6
|
+
* Adds the response headers a browser needs to constrain what a Clopen page is
|
|
7
|
+
* allowed to do. Each directive below is set to what the app actually uses —
|
|
8
|
+
* see the notes on the loose ones, which are loose for a reason rather than by
|
|
9
|
+
* oversight.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* `@monaco-editor/loader` fetches the editor at runtime from jsDelivr; nothing
|
|
14
|
+
* calls `loader.config()` to point it at a local copy, so the code editor, diff
|
|
15
|
+
* viewer, conflict resolver and SQL console all load their scripts, stylesheet
|
|
16
|
+
* and codicon font cross-origin. Monaco then boots its language workers from a
|
|
17
|
+
* `blob:` that `importScripts()` the same host, which is why `blob:` appears in
|
|
18
|
+
* `script-src` and `worker-src` too. Bundling Monaco locally would let every
|
|
19
|
+
* one of these entries go.
|
|
20
|
+
*/
|
|
21
|
+
const MONACO_CDN = 'https://cdn.jsdelivr.net';
|
|
22
|
+
|
|
23
|
+
const CONTENT_SECURITY_POLICY = [
|
|
24
|
+
"default-src 'self'",
|
|
25
|
+
|
|
26
|
+
// No <base> tag and no cross-origin form target in the app, so these cost
|
|
27
|
+
// nothing and close two common ways an injected tag redirects a page.
|
|
28
|
+
"base-uri 'self'",
|
|
29
|
+
"form-action 'self'",
|
|
30
|
+
"object-src 'none'",
|
|
31
|
+
|
|
32
|
+
// Clopen is never meant to be embedded. Paired with X-Frame-Options below
|
|
33
|
+
// for browsers that predate frame-ancestors.
|
|
34
|
+
"frame-ancestors 'none'",
|
|
35
|
+
|
|
36
|
+
// 'unsafe-inline' and 'unsafe-eval' are what Monaco's AMD loader needs. They
|
|
37
|
+
// blunt the XSS value of script-src considerably — the origin allowlist is
|
|
38
|
+
// what this directive still buys us.
|
|
39
|
+
`script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: ${MONACO_CDN}`,
|
|
40
|
+
`style-src 'self' 'unsafe-inline' ${MONACO_CDN}`,
|
|
41
|
+
`font-src 'self' data: ${MONACO_CDN}`,
|
|
42
|
+
|
|
43
|
+
// Markdown renders whatever image URL the author wrote, including remote
|
|
44
|
+
// ones from agent output and project READMEs. Narrowing this would silently
|
|
45
|
+
// break those, so images stay open and the tighter directives above carry
|
|
46
|
+
// the weight.
|
|
47
|
+
"img-src 'self' data: blob: https: http:",
|
|
48
|
+
|
|
49
|
+
// Media previews, notification sounds and the PDF viewer all read from
|
|
50
|
+
// object URLs built in the browser.
|
|
51
|
+
"media-src 'self' blob:",
|
|
52
|
+
"frame-src 'self' blob:",
|
|
53
|
+
"worker-src 'self' blob:",
|
|
54
|
+
"child-src 'self' blob:",
|
|
55
|
+
|
|
56
|
+
// The WebSocket is always same-origin (`frontend/utils/ws.ts` builds it from
|
|
57
|
+
// window.location), which 'self' covers under CSP3.
|
|
58
|
+
`connect-src 'self' blob: data: ${MONACO_CDN}`,
|
|
59
|
+
|
|
60
|
+
"manifest-src 'self'"
|
|
61
|
+
].join('; ');
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Browser features are granted to the app itself, not to third parties. The
|
|
65
|
+
* Preview Browser relays a page's device requests to the viewer's own browser
|
|
66
|
+
* (`frontend/services/preview/browser/host-bridge.service.ts`), so camera,
|
|
67
|
+
* microphone, geolocation, clipboard and screen capture have to stay
|
|
68
|
+
* available; everything Clopen never touches is denied outright.
|
|
69
|
+
*/
|
|
70
|
+
const PERMISSIONS_POLICY = [
|
|
71
|
+
'camera=(self)',
|
|
72
|
+
'microphone=(self)',
|
|
73
|
+
'geolocation=(self)',
|
|
74
|
+
'display-capture=(self)',
|
|
75
|
+
'clipboard-read=(self)',
|
|
76
|
+
'clipboard-write=(self)',
|
|
77
|
+
'fullscreen=(self)',
|
|
78
|
+
'accelerometer=()',
|
|
79
|
+
'ambient-light-sensor=()',
|
|
80
|
+
'bluetooth=()',
|
|
81
|
+
'gyroscope=()',
|
|
82
|
+
'hid=()',
|
|
83
|
+
'idle-detection=()',
|
|
84
|
+
'local-fonts=()',
|
|
85
|
+
'magnetometer=()',
|
|
86
|
+
'midi=()',
|
|
87
|
+
'payment=()',
|
|
88
|
+
'serial=()',
|
|
89
|
+
'usb=()',
|
|
90
|
+
'xr-spatial-tracking=()'
|
|
91
|
+
].join(', ');
|
|
92
|
+
|
|
93
|
+
export const SECURITY_HEADERS: Record<string, string> = {
|
|
94
|
+
'Content-Security-Policy': CONTENT_SECURITY_POLICY,
|
|
95
|
+
|
|
96
|
+
// Every asset the static handler serves gets an explicit Content-Type from
|
|
97
|
+
// Bun.file().type, so refusing to sniff can't strand one of them.
|
|
98
|
+
'X-Content-Type-Options': 'nosniff',
|
|
99
|
+
|
|
100
|
+
// frame-ancestors already covers this on current browsers; kept for older
|
|
101
|
+
// ones that only understand the legacy header.
|
|
102
|
+
'X-Frame-Options': 'DENY',
|
|
103
|
+
|
|
104
|
+
'Referrer-Policy': 'strict-origin-when-cross-origin',
|
|
105
|
+
'Permissions-Policy': PERMISSIONS_POLICY
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
export function securityMiddleware(app: Elysia) {
|
|
109
|
+
return app.onAfterHandle(({ set }) => {
|
|
110
|
+
for (const [name, value] of Object.entries(SECURITY_HEADERS)) {
|
|
111
|
+
set.headers[name] = value;
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
}
|