gestalt-mobile 0.78.4 → 0.79.0
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/README.md +22 -13
- package/dist/client/assets/index-PmiNsocJ.css +1 -0
- package/dist/client/assets/{index-jLy1t3Qp.js → index-t6olwrqi.js} +58 -53
- package/dist/client/index.html +2 -2
- package/dist/server/server/app.js +3 -0
- package/dist/server/server/cli.js +3 -0
- package/dist/server/server/composition.contracts.js +2 -0
- package/dist/server/server/composition.js +66 -0
- package/dist/server/server/config.js +39 -7
- package/dist/server/server/features/catalog/get-bootstrap/use-case.js +2 -0
- package/dist/server/server/features/previews/application/service.js +80 -0
- package/dist/server/server/features/previews/open-preview/endpoint.js +39 -0
- package/dist/server/server/features/previews/register-routes.js +11 -0
- package/dist/server/server/features/previews/stop-preview/endpoint.js +16 -0
- package/dist/server/server/features/sessions/get-impeccable/endpoint.js +10 -0
- package/dist/server/server/features/sessions/register-routes.js +3 -0
- package/dist/server/server/platform/previews/gateway.js +185 -0
- package/dist/server/server/platform/previews/impeccable.js +269 -0
- package/dist/server/server/platform/previews/proxy.js +178 -0
- package/dist/server/shared/contracts/impeccable.js +104 -0
- package/dist/server/shared/contracts/preview.js +6 -0
- package/package.json +1 -1
- package/dist/client/assets/index-DRiZTklh.css +0 -1
package/dist/client/index.html
CHANGED
|
@@ -16,8 +16,8 @@ SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
16
16
|
<link rel="icon" href="/icons/gestalt-mobile-192.png" />
|
|
17
17
|
<link rel="apple-touch-icon" href="/icons/gestalt-mobile-180.png" />
|
|
18
18
|
<title>Gestalt Mobile</title>
|
|
19
|
-
<script type="module" crossorigin src="/assets/index-
|
|
20
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
19
|
+
<script type="module" crossorigin src="/assets/index-t6olwrqi.js"></script>
|
|
20
|
+
<link rel="stylesheet" crossorigin href="/assets/index-PmiNsocJ.css">
|
|
21
21
|
</head>
|
|
22
22
|
<body>
|
|
23
23
|
<div id="app"></div>
|
|
@@ -21,6 +21,7 @@ import { registerOrgPlanAttentionRoutes } from './features/org-plan-attention/re
|
|
|
21
21
|
import { registerAutopilotRoutes } from './features/autopilot/register-routes.js';
|
|
22
22
|
import { registerFileRoutes } from './features/files/register-routes.js';
|
|
23
23
|
import { registerMaintenanceRoutes } from './features/maintenance/register-routes.js';
|
|
24
|
+
import { registerPreviewRoutes } from './features/previews/register-routes.js';
|
|
24
25
|
import { registerPwaRoutes } from './features/pwa/register-routes.js';
|
|
25
26
|
import { registerSelfDebug } from './features/self-debug/endpoint.js';
|
|
26
27
|
export async function buildApp(deps) {
|
|
@@ -76,6 +77,8 @@ export async function buildApp(deps) {
|
|
|
76
77
|
registerGitRoutes(app, deps);
|
|
77
78
|
registerSkillRoutes(app, deps);
|
|
78
79
|
registerMaintenanceRoutes(app, deps.upgrade);
|
|
80
|
+
if (deps.auth && deps.preview)
|
|
81
|
+
registerPreviewRoutes(app, deps.preview);
|
|
79
82
|
registerProblemHandler(app, Boolean(deps.staticDir));
|
|
80
83
|
return app;
|
|
81
84
|
}
|
|
@@ -29,6 +29,8 @@ Options:
|
|
|
29
29
|
--host <address> Listen address (default: 127.0.0.1)
|
|
30
30
|
--port <number> Listen port (default: 3000)
|
|
31
31
|
--public-origin <origin> Exact HTTPS browser origin for passkeys (localhost may use HTTP)
|
|
32
|
+
--preview-origin <origin> Enable the preview gateway on 127.0.0.1:8080 for this HTTPS origin
|
|
33
|
+
--preview-target-port <number> Loopback dev server port (default: 5173)
|
|
32
34
|
--disable-passkey-auth Disable passkey access control (unsafe on shared or network hosts)
|
|
33
35
|
--data-dir <path> Directory for persistent application data
|
|
34
36
|
--icon <path> SVG or PNG used as the installed PWA application icon
|
|
@@ -341,6 +343,7 @@ export async function runCli(dependencies = {}) {
|
|
|
341
343
|
testRunnerEnabled: config.testRunnerEnabled,
|
|
342
344
|
relyingParty: config.relyingParty,
|
|
343
345
|
passkeyAuthEnabled: config.passkeyAuthEnabled,
|
|
346
|
+
...(config.preview ? { preview: config.preview } : {}),
|
|
344
347
|
staticDir: packagedClientDir(moduleUrl),
|
|
345
348
|
pwaIcon,
|
|
346
349
|
profiles: new LauncherProfileCatalog(),
|
|
@@ -8163,6 +8163,8 @@ describe('production composition', () => {
|
|
|
8163
8163
|
'protected',
|
|
8164
8164
|
],
|
|
8165
8165
|
['GET', '/api/sessions/:id/attention', '/api/sessions/session-1/attention', 'protected'],
|
|
8166
|
+
['GET', '/api/sessions/:id/impeccable', '/api/sessions/session-1/impeccable', 'protected'],
|
|
8167
|
+
['HEAD', '/api/sessions/:id/impeccable', '/api/sessions/session-1/impeccable', 'protected'],
|
|
8166
8168
|
[
|
|
8167
8169
|
'POST',
|
|
8168
8170
|
'/api/sessions/:id/activity/refresh',
|
|
@@ -14,6 +14,10 @@ import { debuglog } from 'node:util';
|
|
|
14
14
|
import { SqliteTransportDiagnostics } from './platform/persistence/sqlite-transport-diagnostics.js';
|
|
15
15
|
import { buildApp } from './app.js';
|
|
16
16
|
import { ManagedUpgrade } from './platform/maintenance/managed-upgrade.js';
|
|
17
|
+
import { PreviewService } from './features/previews/application/service.js';
|
|
18
|
+
import { createPreviewGateway } from './platform/previews/gateway.js';
|
|
19
|
+
import { findImpeccableHelper } from './platform/previews/impeccable.js';
|
|
20
|
+
import { hasImpeccableSkill } from '../shared/contracts/impeccable.js';
|
|
17
21
|
import { LocalHostTestRunner } from './platform/host-tests/runner.js';
|
|
18
22
|
import { FilesystemSessionScratch } from './platform/scratch/filesystem-session-scratch.js';
|
|
19
23
|
import { FilesystemScratchCleanup } from './platform/scratch/filesystem-scratch-cleanup.js';
|
|
@@ -134,6 +138,8 @@ const checkpointDiagnostic = debuglog('gestalt-mobile:checkpoint');
|
|
|
134
138
|
const attentionDiagnostic = debuglog('gestalt-mobile:attention');
|
|
135
139
|
export async function composeRelayApp(options) {
|
|
136
140
|
const passkeyAuthEnabled = options.passkeyAuthEnabled ?? true;
|
|
141
|
+
if (options.preview && !passkeyAuthEnabled)
|
|
142
|
+
throw new Error('Previews require passkey authentication');
|
|
137
143
|
const relyingParty = createRelyingPartyConfig(options.relyingParty.publicOrigin);
|
|
138
144
|
if (relyingParty.rpId !== options.relyingParty.rpId ||
|
|
139
145
|
relyingParty.rpName !== options.relyingParty.rpName)
|
|
@@ -664,6 +670,34 @@ export async function composeRelayApp(options) {
|
|
|
664
670
|
project: project?.skills,
|
|
665
671
|
}).skillsConfig;
|
|
666
672
|
};
|
|
673
|
+
const impeccableAvailable = async (id) => {
|
|
674
|
+
const session = sessions.find(id);
|
|
675
|
+
if (!session)
|
|
676
|
+
return false;
|
|
677
|
+
if (session.effectiveSkillSelection)
|
|
678
|
+
return hasImpeccableSkill(session.effectiveSkillSelection.skills);
|
|
679
|
+
try {
|
|
680
|
+
const [catalog, project] = await Promise.all([
|
|
681
|
+
session.provider === 'kimi'
|
|
682
|
+
? kimiSkillCatalog.list(session.workspacePath)
|
|
683
|
+
: skillCatalog('codex', session.profile).list(session.workspacePath),
|
|
684
|
+
skillProfiles.readWorkspaceDefault(session.workspacePath),
|
|
685
|
+
]);
|
|
686
|
+
const effective = compileSkillOverride({
|
|
687
|
+
discovered: catalog.skills,
|
|
688
|
+
explicit: options.explicitSkillProfile?.skills,
|
|
689
|
+
project: project?.skills,
|
|
690
|
+
}).skillsConfig;
|
|
691
|
+
const enabledPaths = new Set(effective.filter((skill) => skill.enabled).map((skill) => skill.path));
|
|
692
|
+
return hasImpeccableSkill(catalog.skills.map(({ name, path }) => ({
|
|
693
|
+
name,
|
|
694
|
+
enabled: enabledPaths.has(path),
|
|
695
|
+
})));
|
|
696
|
+
}
|
|
697
|
+
catch {
|
|
698
|
+
return false;
|
|
699
|
+
}
|
|
700
|
+
};
|
|
667
701
|
const recentThreads = createRecentThreadLister({
|
|
668
702
|
root,
|
|
669
703
|
profiles: options.profiles,
|
|
@@ -2226,6 +2260,29 @@ export async function composeRelayApp(options) {
|
|
|
2226
2260
|
: null,
|
|
2227
2261
|
onSettled: ordinaryTurnDependencies.onSettled,
|
|
2228
2262
|
});
|
|
2263
|
+
const preview = (() => {
|
|
2264
|
+
if (!options.preview || !authorization)
|
|
2265
|
+
return;
|
|
2266
|
+
const repository = authorization;
|
|
2267
|
+
const clock = options.authorizationClock ?? (() => new Date());
|
|
2268
|
+
const service = new PreviewService({
|
|
2269
|
+
sessionActive: (id) => sessions.find(id)?.desiredState === 'active' && !forgetOperations.find(id),
|
|
2270
|
+
loginValid: (id) => repository.sessionDevice(id, clock().toISOString()) !== null,
|
|
2271
|
+
now: () => clock().getTime(),
|
|
2272
|
+
token: () => randomBytes(32).toString('base64url'),
|
|
2273
|
+
});
|
|
2274
|
+
return {
|
|
2275
|
+
routes: { service, origin: options.preview.origin, impeccableAvailable },
|
|
2276
|
+
gateway: createPreviewGateway({
|
|
2277
|
+
...options.preview,
|
|
2278
|
+
impeccableHelper: async (id) => {
|
|
2279
|
+
const session = sessions.find(id);
|
|
2280
|
+
if (session)
|
|
2281
|
+
return findImpeccableHelper(session.workspacePath);
|
|
2282
|
+
},
|
|
2283
|
+
}, service),
|
|
2284
|
+
};
|
|
2285
|
+
})();
|
|
2229
2286
|
let app;
|
|
2230
2287
|
try {
|
|
2231
2288
|
if (options.testRunnerEnabled !== false) {
|
|
@@ -2245,6 +2302,7 @@ export async function composeRelayApp(options) {
|
|
|
2245
2302
|
app = await buildApp({
|
|
2246
2303
|
transportDiagnostic: (id, event) => transportDiagnostics.record(id, event),
|
|
2247
2304
|
upgrade: new ManagedUpgrade(options.root),
|
|
2305
|
+
preview: preview?.routes,
|
|
2248
2306
|
...(authorization
|
|
2249
2307
|
? {
|
|
2250
2308
|
auth: {
|
|
@@ -2332,6 +2390,8 @@ export async function composeRelayApp(options) {
|
|
|
2332
2390
|
headerIconUrl: options.pwaIcon ? pwaIconUrl(options.pwaIcon) : undefined,
|
|
2333
2391
|
protocolCompatible: protocol.compatible,
|
|
2334
2392
|
providers: providerAvailability,
|
|
2393
|
+
preview: Boolean(preview),
|
|
2394
|
+
impeccable: true,
|
|
2335
2395
|
},
|
|
2336
2396
|
selfDebug: runtime
|
|
2337
2397
|
? {
|
|
@@ -2426,6 +2486,7 @@ export async function composeRelayApp(options) {
|
|
|
2426
2486
|
save: saveSession,
|
|
2427
2487
|
publish: publishSession,
|
|
2428
2488
|
find: (id) => withPendingInteractions(sessions.find(id)),
|
|
2489
|
+
impeccableAvailable,
|
|
2429
2490
|
list: () => sessions.list().map((session) => withPendingInteractions(session)),
|
|
2430
2491
|
plan: (id) => supervisedPlans.find(id),
|
|
2431
2492
|
workspaces,
|
|
@@ -2737,6 +2798,10 @@ export async function composeRelayApp(options) {
|
|
|
2737
2798
|
checkpoints.failPending(session.id, true);
|
|
2738
2799
|
});
|
|
2739
2800
|
};
|
|
2801
|
+
if (preview)
|
|
2802
|
+
app.addHook('onReady', async () => {
|
|
2803
|
+
await preview.gateway.start();
|
|
2804
|
+
});
|
|
2740
2805
|
app.addHook('onListen', async () => {
|
|
2741
2806
|
for (const id of forgetOperations.pendingIds())
|
|
2742
2807
|
void forgetSessions.execute(id).catch(() => undefined);
|
|
@@ -2774,6 +2839,7 @@ export async function composeRelayApp(options) {
|
|
|
2774
2839
|
closing = true;
|
|
2775
2840
|
providerRecovery.dispose();
|
|
2776
2841
|
runtime?.cancelHistoryReads();
|
|
2842
|
+
await preview?.gateway.close();
|
|
2777
2843
|
});
|
|
2778
2844
|
app.addHook('onClose', async () => {
|
|
2779
2845
|
await hostTests?.close();
|
|
@@ -14,6 +14,8 @@ const optionNames = new Set([
|
|
|
14
14
|
'--port',
|
|
15
15
|
'--data-dir',
|
|
16
16
|
'--public-origin',
|
|
17
|
+
'--preview-origin',
|
|
18
|
+
'--preview-target-port',
|
|
17
19
|
'--skills',
|
|
18
20
|
'--icon',
|
|
19
21
|
]);
|
|
@@ -52,6 +54,7 @@ export function parseConfig(args, cwd = process.cwd()) {
|
|
|
52
54
|
const publicOrigin = values.has('--public-origin')
|
|
53
55
|
? normalizePublicOrigin(values.get('--public-origin'))
|
|
54
56
|
: defaultPublicOrigin(host, port, passkeyAuthEnabled);
|
|
57
|
+
const preview = parsePreview(values, publicOrigin, port, passkeyAuthEnabled);
|
|
55
58
|
return {
|
|
56
59
|
host,
|
|
57
60
|
port,
|
|
@@ -62,34 +65,63 @@ export function parseConfig(args, cwd = process.cwd()) {
|
|
|
62
65
|
skillsProfile: values.get('--skills'),
|
|
63
66
|
iconPath: values.has('--icon') ? resolveIconPath(cwd, values.get('--icon')) : undefined,
|
|
64
67
|
testRunnerEnabled: !flags.has('--disable-test-runner'),
|
|
68
|
+
...(preview ? { preview } : {}),
|
|
65
69
|
};
|
|
66
70
|
}
|
|
71
|
+
function parsePreview(values, publicOrigin, relayPort, passkeyAuthEnabled) {
|
|
72
|
+
const originValue = values.get('--preview-origin');
|
|
73
|
+
const targetValue = values.get('--preview-target-port');
|
|
74
|
+
if (!originValue) {
|
|
75
|
+
if (targetValue)
|
|
76
|
+
throw new CliUsageError('--preview-target-port requires --preview-origin');
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (!passkeyAuthEnabled)
|
|
80
|
+
throw new CliUsageError('Previews require passkey authentication');
|
|
81
|
+
const origin = new URL(normalizePublicOrigin(originValue, '--preview-origin'));
|
|
82
|
+
const relay = new URL(publicOrigin);
|
|
83
|
+
if (origin.protocol !== 'https:' || relay.protocol !== 'https:')
|
|
84
|
+
throw new CliUsageError('Previews require HTTPS origins for Mobile and the preview site');
|
|
85
|
+
if (origin.hostname === relay.hostname || origin.hostname.endsWith(`.${relay.hostname}`))
|
|
86
|
+
throw new CliUsageError('--preview-origin requires an independent hostname for preview content');
|
|
87
|
+
const port = 8080;
|
|
88
|
+
if (relayPort === port)
|
|
89
|
+
throw new CliUsageError('The preview gateway requires port 8080');
|
|
90
|
+
const targetPort = Number(targetValue ?? '5173');
|
|
91
|
+
if (!Number.isInteger(targetPort) ||
|
|
92
|
+
targetPort < 1024 ||
|
|
93
|
+
targetPort > 65535 ||
|
|
94
|
+
targetPort === relayPort ||
|
|
95
|
+
targetPort === port)
|
|
96
|
+
throw new CliUsageError('--preview-target-port must be a distinct unprivileged local port');
|
|
97
|
+
return { origin: origin.origin, port, targetPort };
|
|
98
|
+
}
|
|
67
99
|
function resolveIconPath(cwd, value) {
|
|
68
100
|
if (!/\.(?:png|svg)$/i.test(value))
|
|
69
101
|
throw new CliUsageError('--icon must reference an SVG or PNG file');
|
|
70
102
|
return resolve(cwd, value);
|
|
71
103
|
}
|
|
72
|
-
export function normalizePublicOrigin(value) {
|
|
104
|
+
export function normalizePublicOrigin(value, option = '--public-origin') {
|
|
73
105
|
if (!/^[a-z][a-z\d+.-]*:\/\/[^/?#\s\\\\]+\/?$/i.test(value))
|
|
74
|
-
throw new CliUsageError(
|
|
106
|
+
throw new CliUsageError(`${option} must be a bare origin without a path, query, or fragment`);
|
|
75
107
|
let url;
|
|
76
108
|
try {
|
|
77
109
|
url = new URL(value);
|
|
78
110
|
}
|
|
79
111
|
catch {
|
|
80
|
-
throw new CliUsageError(`Invalid
|
|
112
|
+
throw new CliUsageError(`Invalid ${option}: ${value}`);
|
|
81
113
|
}
|
|
82
114
|
if (url.username || url.password)
|
|
83
|
-
throw new CliUsageError(
|
|
115
|
+
throw new CliUsageError(`${option} must not include credentials`);
|
|
84
116
|
if (url.pathname !== '/' || url.search || url.hash)
|
|
85
|
-
throw new CliUsageError(
|
|
117
|
+
throw new CliUsageError(`${option} must be a bare origin without a path, query, or fragment`);
|
|
86
118
|
const hostname = url.hostname.replace(/^\[|\]$/g, '');
|
|
87
119
|
if (isIP(hostname))
|
|
88
|
-
throw new CliUsageError(
|
|
120
|
+
throw new CliUsageError(`${option} must use a hostname, not an IP address`);
|
|
89
121
|
if (url.protocol === 'http:' && url.hostname === 'localhost')
|
|
90
122
|
return url.origin;
|
|
91
123
|
if (url.protocol !== 'https:')
|
|
92
|
-
throw new CliUsageError(
|
|
124
|
+
throw new CliUsageError(`${option} must use HTTPS, except for http://localhost`);
|
|
93
125
|
return url.origin;
|
|
94
126
|
}
|
|
95
127
|
export function createRelyingPartyConfig(publicOrigin) {
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2026 Dyne.org foundation
|
|
3
|
+
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
*/
|
|
6
|
+
const codeLifetime = 30_000;
|
|
7
|
+
export const previewSessionLifetime = 60 * 60;
|
|
8
|
+
const grantLimit = 128;
|
|
9
|
+
export class PreviewService {
|
|
10
|
+
deps;
|
|
11
|
+
preview;
|
|
12
|
+
constructor(deps) {
|
|
13
|
+
this.deps = deps;
|
|
14
|
+
}
|
|
15
|
+
open(sessionId, login, mode = 'view') {
|
|
16
|
+
const current = this.activePreview();
|
|
17
|
+
if (!this.deps.sessionActive(sessionId))
|
|
18
|
+
return { kind: 'inactive' };
|
|
19
|
+
if (!this.deps.loginValid(login))
|
|
20
|
+
return { kind: 'unauthorized' };
|
|
21
|
+
if (current && current.sessionId !== sessionId)
|
|
22
|
+
return { kind: 'busy' };
|
|
23
|
+
const preview = current ?? { sessionId, codes: new Map(), viewers: new Map() };
|
|
24
|
+
const code = this.issue(preview.codes, login, mode, codeLifetime);
|
|
25
|
+
if (!code)
|
|
26
|
+
return { kind: 'limit' };
|
|
27
|
+
this.preview = preview;
|
|
28
|
+
return { kind: 'opened', code };
|
|
29
|
+
}
|
|
30
|
+
exchange(code) {
|
|
31
|
+
const preview = this.activePreview();
|
|
32
|
+
const grant = preview?.codes.get(code);
|
|
33
|
+
if (!preview || !grant)
|
|
34
|
+
return;
|
|
35
|
+
preview.codes.delete(code);
|
|
36
|
+
if (!this.valid(grant))
|
|
37
|
+
return;
|
|
38
|
+
return this.issue(preview.viewers, grant.login, grant.mode, previewSessionLifetime * 1000);
|
|
39
|
+
}
|
|
40
|
+
authorized(viewer) {
|
|
41
|
+
return this.access(viewer) !== undefined;
|
|
42
|
+
}
|
|
43
|
+
access(viewer) {
|
|
44
|
+
const preview = this.activePreview();
|
|
45
|
+
const grant = preview?.viewers.get(viewer);
|
|
46
|
+
if (!preview || !grant)
|
|
47
|
+
return;
|
|
48
|
+
if (this.valid(grant))
|
|
49
|
+
return { sessionId: preview.sessionId, mode: grant.mode };
|
|
50
|
+
preview.viewers.delete(viewer);
|
|
51
|
+
}
|
|
52
|
+
stop(sessionId) {
|
|
53
|
+
const current = this.activePreview();
|
|
54
|
+
if (current && current.sessionId !== sessionId)
|
|
55
|
+
return false;
|
|
56
|
+
this.preview = undefined;
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
activePreview() {
|
|
60
|
+
if (this.preview && !this.deps.sessionActive(this.preview.sessionId))
|
|
61
|
+
this.preview = undefined;
|
|
62
|
+
return this.preview;
|
|
63
|
+
}
|
|
64
|
+
valid(grant) {
|
|
65
|
+
return grant.expiresAt > this.deps.now() && this.deps.loginValid(grant.login);
|
|
66
|
+
}
|
|
67
|
+
issue(grants, login, mode, lifetime) {
|
|
68
|
+
if (grants.size >= grantLimit) {
|
|
69
|
+
for (const [token, grant] of grants) {
|
|
70
|
+
if (!this.valid(grant))
|
|
71
|
+
grants.delete(token);
|
|
72
|
+
}
|
|
73
|
+
if (grants.size >= grantLimit)
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const token = this.deps.token();
|
|
77
|
+
grants.set(token, { login, expiresAt: this.deps.now() + lifetime, mode });
|
|
78
|
+
return token;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2026 Dyne.org foundation
|
|
3
|
+
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
*/
|
|
6
|
+
import { previewHandoffPath } from '../../../../shared/contracts/preview.js';
|
|
7
|
+
import { problem } from '../../../platform/http/problem.js';
|
|
8
|
+
import { parseAuthorizationSessionId } from '../../auth/domain/identifiers.js';
|
|
9
|
+
export function registerOpenPreview(app, deps) {
|
|
10
|
+
app.post('/api/sessions/:sessionId/preview', async (request, reply) => {
|
|
11
|
+
reply.header('Cache-Control', 'no-store');
|
|
12
|
+
const login = parseAuthorizationSessionId(request.cookies.gestalt_mobile_session);
|
|
13
|
+
const impeccable = request.body?.impeccable === true;
|
|
14
|
+
if (impeccable && !(await deps.impeccableAvailable?.(request.params.sessionId)))
|
|
15
|
+
return reply
|
|
16
|
+
.code(403)
|
|
17
|
+
.type('application/problem+json')
|
|
18
|
+
.send(problem('IMPECCABLE_UNAVAILABLE', 403, 'Impeccable is unavailable in this chat.'));
|
|
19
|
+
const result = login
|
|
20
|
+
? deps.service.open(request.params.sessionId, login, impeccable ? 'impeccable' : 'view')
|
|
21
|
+
: { kind: 'unauthorized' };
|
|
22
|
+
if (result.kind === 'opened') {
|
|
23
|
+
const url = new URL(previewHandoffPath, deps.origin);
|
|
24
|
+
url.hash = result.code;
|
|
25
|
+
return { url: url.href };
|
|
26
|
+
}
|
|
27
|
+
const errors = {
|
|
28
|
+
inactive: [404, 'PREVIEW_SESSION_INACTIVE', 'Open an active chat session first.'],
|
|
29
|
+
unauthorized: [401, 'AUTH_REQUIRED', 'Authentication is required.'],
|
|
30
|
+
busy: [409, 'PREVIEW_BUSY', 'Stop the preview in the other session first.'],
|
|
31
|
+
limit: [429, 'PREVIEW_LIMIT', 'Too many preview authorizations. Try again later.'],
|
|
32
|
+
};
|
|
33
|
+
const [status, code, title] = errors[result.kind];
|
|
34
|
+
return reply
|
|
35
|
+
.code(status)
|
|
36
|
+
.type('application/problem+json')
|
|
37
|
+
.send(problem(code, status, title));
|
|
38
|
+
});
|
|
39
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2026 Dyne.org foundation
|
|
3
|
+
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
*/
|
|
6
|
+
import { registerOpenPreview } from './open-preview/endpoint.js';
|
|
7
|
+
import { registerStopPreview } from './stop-preview/endpoint.js';
|
|
8
|
+
export function registerPreviewRoutes(app, deps) {
|
|
9
|
+
registerOpenPreview(app, deps);
|
|
10
|
+
registerStopPreview(app, deps.service);
|
|
11
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2026 Dyne.org foundation
|
|
3
|
+
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
*/
|
|
6
|
+
import { problem } from '../../../platform/http/problem.js';
|
|
7
|
+
export function registerStopPreview(app, service) {
|
|
8
|
+
app.delete('/api/sessions/:sessionId/preview', async (request, reply) => {
|
|
9
|
+
if (!service.stop(request.params.sessionId))
|
|
10
|
+
return reply
|
|
11
|
+
.code(409)
|
|
12
|
+
.type('application/problem+json')
|
|
13
|
+
.send(problem('PREVIEW_BUSY', 409, 'Stop the preview in the other session first.'));
|
|
14
|
+
return reply.code(204).send();
|
|
15
|
+
});
|
|
16
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2026 Dyne.org foundation
|
|
3
|
+
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
*/
|
|
6
|
+
export function registerGetImpeccable(app, available) {
|
|
7
|
+
app.get('/api/sessions/:id/impeccable', async (request) => ({
|
|
8
|
+
available: await available(request.params.id),
|
|
9
|
+
}));
|
|
10
|
+
}
|
|
@@ -7,6 +7,7 @@ import { authorizationSessionDevice } from '../../platform/http/authorization-bo
|
|
|
7
7
|
import { stopSession } from './lifecycle/use-case.js';
|
|
8
8
|
import { keepTemporaryFilesRoute, registerForgetSession } from './forget-session/endpoint.js';
|
|
9
9
|
import { registerGetHistory } from './get-history/endpoint.js';
|
|
10
|
+
import { registerGetImpeccable } from './get-impeccable/endpoint.js';
|
|
10
11
|
import { registerGetSession } from './get-session/endpoint.js';
|
|
11
12
|
import { registerInterruptTurn } from './interrupt-turn/endpoint.js';
|
|
12
13
|
import { registerListRecentThreads } from './list-recent-threads/endpoint.js';
|
|
@@ -36,6 +37,8 @@ export function registerSessionRoutes(app, deps) {
|
|
|
36
37
|
});
|
|
37
38
|
}
|
|
38
39
|
if (sessions) {
|
|
40
|
+
if (sessions.impeccableAvailable)
|
|
41
|
+
registerGetImpeccable(app, sessions.impeccableAvailable);
|
|
39
42
|
const conflict = (request) => {
|
|
40
43
|
if (!request.routeOptions.url?.startsWith('/api/sessions/:id'))
|
|
41
44
|
return null;
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2026 Dyne.org foundation
|
|
3
|
+
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
*/
|
|
6
|
+
import { randomBytes } from 'node:crypto';
|
|
7
|
+
import { once } from 'node:events';
|
|
8
|
+
import { createServer } from 'node:http';
|
|
9
|
+
import { previewHandoffPath } from '../../../shared/contracts/preview.js';
|
|
10
|
+
import { previewSessionLifetime, } from '../../features/previews/application/service.js';
|
|
11
|
+
import { cookieName, previewCookie, proxyHttp, proxyWebSocket, rejectUpgrade } from './proxy.js';
|
|
12
|
+
import { impeccablePath, serveImpeccable } from './impeccable.js';
|
|
13
|
+
export function createPreviewGateway(options, service) {
|
|
14
|
+
const origin = new URL(options.origin);
|
|
15
|
+
const target = { port: options.targetPort, origin };
|
|
16
|
+
const connections = new Set();
|
|
17
|
+
let expiryCheck;
|
|
18
|
+
function track(viewer) {
|
|
19
|
+
return (disconnect) => {
|
|
20
|
+
const connection = { viewer, disconnect };
|
|
21
|
+
connections.add(connection);
|
|
22
|
+
return () => connections.delete(connection);
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function validRequest(request) {
|
|
26
|
+
return (request.headers.host === origin.host &&
|
|
27
|
+
typeof request.url === 'string' &&
|
|
28
|
+
request.url.startsWith('/') &&
|
|
29
|
+
!request.url.startsWith('//'));
|
|
30
|
+
}
|
|
31
|
+
const server = createServer((request, response) => {
|
|
32
|
+
if (!validRequest(request))
|
|
33
|
+
return text(response, 421, 'Unknown preview host.');
|
|
34
|
+
if (request.url === previewHandoffPath) {
|
|
35
|
+
if (request.method === 'GET')
|
|
36
|
+
return handoff(response);
|
|
37
|
+
if (request.method === 'POST' && request.headers.origin === origin.origin) {
|
|
38
|
+
return exchange(request, response, (code) => service.exchange(code)).catch(() => {
|
|
39
|
+
if (!response.destroyed)
|
|
40
|
+
text(response, 400, 'Invalid preview authorization.');
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
return text(response, 403, 'Preview authorization must come from the preview site.');
|
|
44
|
+
}
|
|
45
|
+
if (!allowedHttpOrigin(request, origin.origin) ||
|
|
46
|
+
request.headers['service-worker'] ||
|
|
47
|
+
request.headers['sec-fetch-dest'] === 'serviceworker')
|
|
48
|
+
return text(response, 403, 'This preview request is forbidden.');
|
|
49
|
+
const viewer = readViewer(request);
|
|
50
|
+
const access = viewer && service.access(viewer);
|
|
51
|
+
if (!viewer || !access)
|
|
52
|
+
return text(response, 401, 'Open the preview from your Gestalt session.');
|
|
53
|
+
const editor = access.mode === 'impeccable' && options.impeccableHelper;
|
|
54
|
+
if (request.url?.startsWith(`${impeccablePath}/`)) {
|
|
55
|
+
if (!editor)
|
|
56
|
+
return text(response, 403, 'Open Impeccable Live from your Gestalt session.');
|
|
57
|
+
return void serveImpeccable(request, response, new URL(request.url, origin), () => editor(access.sessionId), track(viewer));
|
|
58
|
+
}
|
|
59
|
+
proxyHttp(request, response, target, track(viewer), Boolean(editor));
|
|
60
|
+
});
|
|
61
|
+
server.on('upgrade', (request, socket, head) => {
|
|
62
|
+
const viewer = readViewer(request);
|
|
63
|
+
if (!validRequest(request) ||
|
|
64
|
+
request.url === previewHandoffPath ||
|
|
65
|
+
request.url?.startsWith(`${impeccablePath}/`) ||
|
|
66
|
+
request.headers.upgrade?.toLowerCase() !== 'websocket' ||
|
|
67
|
+
request.headers.origin !== origin.origin ||
|
|
68
|
+
!viewer ||
|
|
69
|
+
!service.authorized(viewer)) {
|
|
70
|
+
socket.once('error', () => socket.destroy());
|
|
71
|
+
rejectUpgrade(socket, '401 Unauthorized');
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
proxyWebSocket(request, socket, head, target, track(viewer));
|
|
75
|
+
});
|
|
76
|
+
return {
|
|
77
|
+
async start() {
|
|
78
|
+
const listening = once(server, 'listening');
|
|
79
|
+
server.listen(options.port, '127.0.0.1');
|
|
80
|
+
await listening;
|
|
81
|
+
expiryCheck = setInterval(() => {
|
|
82
|
+
for (const connection of connections) {
|
|
83
|
+
if (!service.authorized(connection.viewer))
|
|
84
|
+
connection.disconnect();
|
|
85
|
+
}
|
|
86
|
+
}, 1000).unref();
|
|
87
|
+
const address = server.address();
|
|
88
|
+
if (!address || typeof address === 'string')
|
|
89
|
+
throw new Error('Preview listener has no port');
|
|
90
|
+
return address.port;
|
|
91
|
+
},
|
|
92
|
+
async close() {
|
|
93
|
+
clearInterval(expiryCheck);
|
|
94
|
+
for (const connection of connections)
|
|
95
|
+
connection.disconnect();
|
|
96
|
+
if (server.listening) {
|
|
97
|
+
const closed = once(server, 'close');
|
|
98
|
+
server.close();
|
|
99
|
+
server.closeAllConnections();
|
|
100
|
+
await closed;
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function readViewer(request) {
|
|
106
|
+
const pair = request.headers.cookie
|
|
107
|
+
?.split(';')
|
|
108
|
+
.filter((part) => cookieName(part) === previewCookie);
|
|
109
|
+
if (pair?.length !== 1)
|
|
110
|
+
return;
|
|
111
|
+
const token = pair[0].trim().slice(previewCookie.length + 1);
|
|
112
|
+
return validToken(token) ? token : undefined;
|
|
113
|
+
}
|
|
114
|
+
function validToken(token) {
|
|
115
|
+
return /^[\w-]{43}$/.test(token);
|
|
116
|
+
}
|
|
117
|
+
function allowedHttpOrigin(request, origin) {
|
|
118
|
+
if (request.headers.origin && request.headers.origin !== origin)
|
|
119
|
+
return false;
|
|
120
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
121
|
+
return request.headers.origin === origin;
|
|
122
|
+
const site = request.headers['sec-fetch-site'];
|
|
123
|
+
return (!site ||
|
|
124
|
+
site === 'none' ||
|
|
125
|
+
site === 'same-origin' ||
|
|
126
|
+
(request.headers['sec-fetch-mode'] === 'navigate' &&
|
|
127
|
+
request.headers['sec-fetch-dest'] === 'document'));
|
|
128
|
+
}
|
|
129
|
+
async function exchange(request, response, consume) {
|
|
130
|
+
let body = '';
|
|
131
|
+
for await (const chunk of request.iterator({ destroyOnReturn: false })) {
|
|
132
|
+
body += String(chunk);
|
|
133
|
+
if (body.length > 43) {
|
|
134
|
+
text(response, 400, 'Invalid preview authorization.');
|
|
135
|
+
request.resume();
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const viewer = validToken(body) ? consume(body) : undefined;
|
|
140
|
+
if (!viewer) {
|
|
141
|
+
text(response, 401, 'Preview authorization expired. Open the preview again from Gestalt.');
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
response
|
|
145
|
+
.writeHead(204, {
|
|
146
|
+
'cache-control': 'no-store',
|
|
147
|
+
'set-cookie': `${previewCookie}=${viewer}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=${previewSessionLifetime}`,
|
|
148
|
+
})
|
|
149
|
+
.end();
|
|
150
|
+
}
|
|
151
|
+
function text(response, status, message) {
|
|
152
|
+
response
|
|
153
|
+
.writeHead(status, {
|
|
154
|
+
'cache-control': 'no-store',
|
|
155
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
156
|
+
'x-content-type-options': 'nosniff',
|
|
157
|
+
})
|
|
158
|
+
.end(message);
|
|
159
|
+
}
|
|
160
|
+
function handoff(response) {
|
|
161
|
+
const nonce = randomBytes(16).toString('base64');
|
|
162
|
+
response.writeHead(200, {
|
|
163
|
+
'cache-control': 'no-store',
|
|
164
|
+
'content-type': 'text/html; charset=utf-8',
|
|
165
|
+
'content-security-policy': `default-src 'none'; script-src 'nonce-${nonce}'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'`,
|
|
166
|
+
'referrer-policy': 'no-referrer',
|
|
167
|
+
'x-content-type-options': 'nosniff',
|
|
168
|
+
}).end(`<!doctype html>
|
|
169
|
+
<html lang="en"><meta charset="utf-8"><title>Gestalt Preview</title>
|
|
170
|
+
<p id="status">Open the preview from your Gestalt session.</p>
|
|
171
|
+
<script nonce="${nonce}">
|
|
172
|
+
const code = location.hash.slice(1);
|
|
173
|
+
history.replaceState(null, '', location.pathname);
|
|
174
|
+
if (code) {
|
|
175
|
+
const status = document.getElementById('status');
|
|
176
|
+
status.textContent = 'Opening preview…';
|
|
177
|
+
fetch(location.pathname, { method: 'POST', body: code }).then((result) => {
|
|
178
|
+
if (result.ok) location.replace('/');
|
|
179
|
+
else status.textContent = 'Authorization expired. Open the preview again from Gestalt.';
|
|
180
|
+
}).catch(() => {
|
|
181
|
+
status.textContent = 'Could not connect. Open the preview again from Gestalt.';
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
</script></html>`);
|
|
185
|
+
}
|