@yuriai/web 0.2.32-beta.1 → 0.2.32-beta.10
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 +19 -0
- package/dist/assets/{AgentAvatar-DLAQkFQe.js → AgentAvatar-DLzcNrQ0.js} +1 -1
- package/dist/assets/AssistantContactStatus-Bf1yg0yx.js +3 -0
- package/dist/assets/{AssistantUnreadBadge-CBGla2En.js → AssistantUnreadBadge-BUFyxUrT.js} +1 -1
- package/dist/assets/{AssistantView-CZUjOyM_.js → AssistantView-CELFybSr.js} +1 -1
- package/dist/assets/{DiagramView-D5Gts9DG.js → DiagramView-DV4P3-Wg.js} +1 -1
- package/dist/assets/{FadeInOnReveal-C9a7XnAh.js → FadeInOnReveal-BRrU2ivL.js} +1 -1
- package/dist/assets/{GuiPluginSurface-CMSZHZPC.js → GuiPluginSurface-NOHaJGy2.js} +1 -1
- package/dist/assets/{GuiPluginWindow-Ba1HfrjQ.js → GuiPluginWindow-BykPaQeY.js} +1 -1
- package/dist/assets/Icon-OJf0qBKf.js +1 -0
- package/dist/assets/{ImageLoadingPlaceholder-Dcy5lc7F.js → ImageLoadingPlaceholder-DlQbo9CM.js} +1 -1
- package/dist/assets/{LoadingImage-BxjJ_Xyj.js → LoadingImage-sZ5omN5L.js} +1 -1
- package/dist/assets/MarkdownRenderer-BFR9FWQL.js +2 -0
- package/dist/assets/MarkdownRendererImpl-iZFUMI3M.js +10 -0
- package/dist/assets/{MarkstreamRendererImpl-EpBnVy9J.css → MarkstreamRendererImpl-C6aiJnjl.css} +1 -1
- package/dist/assets/MarkstreamRendererImpl-DjC_Y4LS.js +3 -0
- package/dist/assets/{MobileDetailNavigation-DcgWfEOt.js → MobileDetailNavigation-BOZpHdI2.js} +1 -1
- package/dist/assets/{MobileResizableSheet-sV9XR-0k.js → MobileResizableSheet-DuAi_epR.js} +1 -1
- package/dist/assets/{MobileShareBridge-DRIEJUQs.js → MobileShareBridge-D1DrqLWf.js} +1 -1
- package/dist/assets/MobileTabPageHeader-BT9gWugr.js +2 -0
- package/dist/assets/{MultiRunWindow-CACYsA-W.js → MultiRunWindow-C0GYNaUU.js} +1 -1
- package/dist/assets/{OnboardingScreen-CnkijSLE.js → OnboardingScreen-CqsI0632.js} +1 -1
- package/dist/assets/{OverlayScrollbar-CCtBTJQj.js → OverlayScrollbar-CZD1yU06.js} +1 -1
- package/dist/assets/SettingsView-BYO8LY5A.js +29 -0
- package/dist/assets/{SettingsWindow-BwzDmS7Q.js → SettingsWindow-CM0Ph9WD.js} +1 -1
- package/dist/assets/SetupTourDialog-BYlSBPKZ.js +1 -0
- package/dist/assets/SetupTourDialog-DrL_4ODI.css +1 -0
- package/dist/assets/{TerminalView-Cw608T7E.js → TerminalView-DnyEAShU.js} +1 -1
- package/dist/assets/{ToolOutputDialog-aKZQU-Zq.js → ToolOutputDialog-BWONfWze.js} +1 -1
- package/dist/assets/{VoiceSettings-CnOk5wPJ.js → VoiceSettings-Ru_0ySgM.js} +2 -2
- package/dist/assets/{YuriLogo-BA5FWp-g.js → YuriLogo-CMUoGUHc.js} +1 -1
- package/dist/assets/YuriWordmark-DHYo0FlR.js +1 -0
- package/dist/assets/{appThemeRegistry-CE2UfF-N.js → appThemeRegistry-BMlAlm0m.js} +1 -1
- package/dist/assets/{button-CBjOhOI0.js → button-C-gRcs_2.js} +1 -1
- package/dist/assets/{capgoAdapter-BMIKl_SL.js → capgoAdapter-GdNfjwXs.js} +1 -1
- package/dist/assets/checkbox-BrJBzET8.js +1 -0
- package/dist/assets/{collapsible-B0j5IQ0T.js → collapsible-B7esGYLd.js} +1 -1
- package/dist/assets/{context-menu-C4e_bpls.js → context-menu-DWn1nSZC.js} +1 -1
- package/dist/assets/desktopHosts-BLU1tGSX.js +1 -0
- package/dist/assets/{desktopRelayRestore-AE3_TnQz.js → desktopRelayRestore-2BIIs8mZ.js} +1 -1
- package/dist/assets/{diagram-WPmk0Qh6.js → diagram-Bnra5_6g.js} +1 -1
- package/dist/assets/{dialog-Dx3IT7dQ.js → dialog-3UseH0hM.js} +1 -1
- package/dist/assets/{es-JU--16Gd.js → es-J7a_sZ1u.js} +2 -2
- package/dist/assets/{fileMentionTouchSelection-Bizsisaj.js → fileMentionTouchSelection-ByaQJcTS.js} +1 -1
- package/dist/assets/{fr-BUZcRuMk.js → fr-BYxUMKWp.js} +2 -2
- package/dist/assets/{gitApi-DXj7IjmF.js → gitApi-BdwvoQFb.js} +1 -1
- package/dist/assets/historyImportQueries-C8VK9R5_.js +1 -0
- package/dist/assets/host-z9PU8q1e.js +1 -0
- package/dist/assets/{input-CEJGM-TS.js → input-CmLlZdeD.js} +1 -1
- package/dist/assets/insertionBoundaries-BpQ6nLjP.js +1 -0
- package/dist/assets/{ja-BwtVLTXD.js → ja-DCdBiJmD.js} +2 -2
- package/dist/assets/{ko--sLsRFpA.js → ko-D-Nb_RJY.js} +2 -2
- package/dist/assets/main-Dosy2jXg.js +2 -0
- package/dist/assets/main-oBh-dk5-.js +169 -0
- package/dist/assets/{markdownHeightCache-D6iSNJG2.js → markdownHeightCache-xNkQdlqi.js} +1 -1
- package/dist/assets/{mcpQueries-D_zQ6E0z.js → mcpQueries-C8zsTQqJ.js} +1 -1
- package/dist/assets/miniChat-CI8ryDGT.js +2 -0
- package/dist/assets/mobile-e_mTK3dh.js +2 -0
- package/dist/assets/{mobileBackNavigation-DC1xEUeI.js → mobileBackNavigation-sB7c0Pi4.js} +1 -1
- package/dist/assets/multirun-DbmgWrsY.js +3 -0
- package/dist/assets/{native-config-BYi6K82g.js → native-config-C_mwkFzh.js} +1 -1
- package/dist/assets/{pl-C4_4J5yA.js → pl-AmU4w3aM.js} +2 -2
- package/dist/assets/{projectMeta-wH9DMvKG.js → projectMeta-1iUbVl_M.js} +1 -1
- package/dist/assets/{pt-BR-DvNC5K1q.js → pt-BR-BI4ft-Fj.js} +2 -2
- package/dist/assets/pwa-BdUAGhLt.js +2 -0
- package/dist/assets/{queue-abort-optimistic-CWoDO6jt.js → queue-abort-optimistic-BwDsaym5.js} +1 -1
- package/dist/assets/react-a6PrrNTm.js +1 -0
- package/dist/assets/{readiness-Br_Q47uu.js → readiness-D2N0DtZF.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-BEeiGIzG.js → renderElectronMiniChatApp-DV0cNt_O.js} +2 -2
- package/dist/assets/{renderMobileApp-B-XnwUvL.js → renderMobileApp-b7--jT5z.js} +7 -7
- package/dist/assets/{runtimeConfig-DainCJ5Y.js → runtimeConfig-DxmJLWUO.js} +1 -1
- package/dist/assets/runtimeEndpointReset-jYAYa3Rh.js +149 -0
- package/dist/assets/{select-bKMw5JE8.js → select-J8r9SxHt.js} +1 -1
- package/dist/assets/sessionLookup-CUQqj2N4.js +1 -0
- package/dist/assets/{sortable-tabs-strip-3sKiA7T1.js → sortable-tabs-strip-CiP6RIQa.js} +1 -1
- package/dist/assets/{speechSettingsQueries-Bv5rjojT.js → speechSettingsQueries-B3ziGQvb.js} +1 -1
- package/dist/assets/src-GtPQ8f4o.css +2 -0
- package/dist/assets/{store-X3lU0obe.js → store-OjrIiXCx.js} +5 -5
- package/dist/assets/{textarea-EsaDD051.js → textarea-BHgcxJdC.js} +1 -1
- package/dist/assets/{tooltip-LLDL5nIZ.js → tooltip-Degmpxnd.js} +1 -1
- package/dist/assets/tour-DDI0Zg7l.js +1 -0
- package/dist/assets/types-QETHY-S7.js +2 -0
- package/dist/assets/{uk-Dvj0JjiC.js → uk-CbdByxxj.js} +2 -2
- package/dist/assets/{useAppFontEffects-Br41do6c.js → useAppFontEffects-LADr3Zl1.js} +53 -53
- package/dist/assets/useDesktopWindowControlsLayout-BVNnRHtc.js +1 -0
- package/dist/assets/{useDictation-DlEHSN6P.js → useDictation-DFVJpRbm.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-niUN5Jtq.js → useEffectiveDirectory-8tqfGdV5.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-DKI3_RxB.js → useMobileNavigationStore-CLUFv-TZ.js} +13 -13
- package/dist/assets/usePluginsStore-B_SIDwsK.js +1 -0
- package/dist/assets/useStreamingTextThrottle-VhgGU_te.js +1 -0
- package/dist/assets/{useWorkerHighlightedLines-CBUWl8le.js → useWorkerHighlightedLines-jlxakDGs.js} +1 -1
- package/dist/assets/{vendor-markstream-react-DfLaSG3W.js → vendor-markstream-react-6zxyQLCD.js} +1 -1
- package/dist/assets/{zh-CN-2Y6u8t24.js → zh-CN-ufEVDbXp.js} +2 -2
- package/dist/assets/{zh-TW-Z5wVv4Fb.js → zh-TW-DTBlZ4YC.js} +2 -2
- package/dist/index.html +8 -8
- package/dist/mini-chat.html +8 -8
- package/dist/mobile.html +8 -8
- package/package.json +1 -1
- package/server/index.js +3 -0
- package/server/lib/client-auth/pairing.js +2 -0
- package/server/lib/client-auth/pairing.test.js +29 -0
- package/server/lib/config-sync/DOCUMENTATION.md +8 -4
- package/server/lib/config-sync/index.js +1 -1
- package/server/lib/config-sync/magpie-auth.js +10 -4
- package/server/lib/config-sync/magpie-auth.test.js +4 -0
- package/server/lib/config-sync/magpie.js +28 -22
- package/server/lib/config-sync/magpie.test.js +127 -2
- package/server/lib/config-sync/plugins.js +44 -0
- package/server/lib/config-sync/plugins.test.js +64 -0
- package/server/lib/config-sync/tar.js +61 -1
- package/server/lib/content-search/DOCUMENTATION.md +9 -0
- package/server/lib/content-search/routes.js +18 -1
- package/server/lib/content-search/routes.test.js +21 -0
- package/server/lib/content-search/runtime.js +7 -3
- package/server/lib/content-search/runtime.test.js +26 -0
- package/server/lib/gui-customization/DOCUMENTATION.md +21 -1
- package/server/lib/gui-customization/session-skill.js +2 -2
- package/server/lib/gui-customization/session-skill.test.js +3 -1
- package/server/lib/gui-customization/skill/SKILL.md +5 -1
- package/server/lib/gui-customization/skill/references/global-pages.md +1 -1
- package/server/lib/gui-customization/skill/references/gui-api.md +4 -1
- package/server/lib/gui-customization/skill/references/icons.md +134 -0
- package/server/lib/gui-customization/skill/references/plugin-styles.md +112 -0
- package/server/lib/gui-customization/skill/references/ui-surfaces.md +2 -0
- package/server/lib/gui-customization/skill/references/work-status.md +110 -0
- package/server/lib/history-import/AGENT_CONNECT_LICENSE +21 -0
- package/server/lib/history-import/DOCUMENTATION.md +223 -0
- package/server/lib/history-import/dev-proxy.integration.test.js +56 -0
- package/server/lib/history-import/events.js +322 -0
- package/server/lib/history-import/events.test.js +110 -0
- package/server/lib/history-import/installations.js +39 -0
- package/server/lib/history-import/installations.test.js +24 -0
- package/server/lib/history-import/native.js +49 -0
- package/server/lib/history-import/native.test.js +42 -0
- package/server/lib/history-import/routes.js +48 -0
- package/server/lib/history-import/routes.test.js +55 -0
- package/server/lib/history-import/service.js +374 -0
- package/server/lib/history-import/service.test.js +538 -0
- package/server/lib/history-import/settings.js +146 -0
- package/server/lib/history-import/settings.test.js +88 -0
- package/server/lib/history-import/sources.js +184 -0
- package/server/lib/history-import/sources.test.js +190 -0
- package/server/lib/history-import/sqlite.js +187 -0
- package/server/lib/history-import/store.js +58 -0
- package/server/lib/history-import/store.test.js +84 -0
- package/server/lib/history-import/targets.js +24 -0
- package/server/lib/host-update/DOCUMENTATION.md +6 -0
- package/server/lib/host-update/routes.test.js +1 -1
- package/server/lib/notifications/native-stream.relay.test.js +1 -0
- package/server/lib/opencode/DOCUMENTATION.md +14 -0
- package/server/lib/opencode/core-routes.js +1 -0
- package/server/lib/opencode/feature-routes-runtime.js +11 -1
- package/server/lib/opencode/plugin-routes.test.js +1 -0
- package/server/lib/opencode/plugins.js +1 -1
- package/server/lib/opencode/plugins.test.js +3 -2
- package/server/lib/opencode/proxy.js +29 -4
- package/server/lib/opencode/proxy.test.js +85 -1
- package/server/lib/opencode/server-utils-runtime.js +2 -0
- package/server/lib/opencode/settings-runtime.js +8 -6
- package/server/lib/opencode/settings-runtime.test.js +44 -0
- package/server/lib/opencode/yuri-routes.js +1 -1
- package/server/lib/relay/DOCUMENTATION.md +1 -1
- package/server/lib/relay/host-client.js +3 -1
- package/server/lib/relay/host-client.test.js +1 -0
- package/server/lib/relay/reasoning-projection.e2e.test.ts +1 -0
- package/server/lib/relay/relay-server.e2e.test.ts +32 -17
- package/server/lib/relay/service.js +2 -0
- package/server/lib/relay/tunnel-host.js +26 -1
- package/server/lib/relay/tunnel-host.test.js +27 -3
- package/server/lib/remote-desktop/runtime.test.js +2 -2
- package/server/lib/ui-auth/DOCUMENTATION.md +3 -0
- package/server/lib/ui-auth/ui-auth.js +27 -0
- package/server/lib/ui-auth/ui-auth.test.js +42 -1
- package/server/plugin-gui-proxy.test.js +1 -1
- package/dist/assets/AssistantContactStatus-CulNHdyA.js +0 -3
- package/dist/assets/Icon-Bh3TaKoN.js +0 -1
- package/dist/assets/MarkdownRenderer-Bn5CJH5N.js +0 -2
- package/dist/assets/MarkdownRendererImpl-ChrPEd5h.js +0 -10
- package/dist/assets/MarkstreamRendererImpl-BtSSTWH7.js +0 -3
- package/dist/assets/MobileTabPageHeader-yt_scp0W.js +0 -2
- package/dist/assets/SettingsView-BC2vBzaV.js +0 -29
- package/dist/assets/SetupTourDialog-Bwzqk4Yk.js +0 -1
- package/dist/assets/SetupTourDialog-CUzqT2sw.css +0 -1
- package/dist/assets/YuriWordmark-Cr1vkcue.js +0 -1
- package/dist/assets/desktopHosts-CMglnUdS.js +0 -1
- package/dist/assets/host-CBfSyi4l.js +0 -1
- package/dist/assets/insertionBoundaries-DC6L5MKG.js +0 -1
- package/dist/assets/main-7x9dVH7f.js +0 -169
- package/dist/assets/main-CA1ut79N.js +0 -2
- package/dist/assets/miniChat-ChJCHXb0.js +0 -2
- package/dist/assets/mobile-CHxWiGaS.js +0 -2
- package/dist/assets/multirun-BrjXkPGe.js +0 -3
- package/dist/assets/pwa-D7mhAQPf.js +0 -2
- package/dist/assets/react-Bwr5-XPi.js +0 -1
- package/dist/assets/runtimeEndpointReset-CUD8K7sC.js +0 -149
- package/dist/assets/sessionLookup-DpDG5rap.js +0 -1
- package/dist/assets/src-PTWgTO6W.css +0 -2
- package/dist/assets/tour-Db44qwfs.js +0 -1
- package/dist/assets/types-DtBBksTR.js +0 -2
- package/dist/assets/useDesktopWindowControlsLayout-ownw04lY.js +0 -1
- package/dist/assets/usePluginsStore-DxXqR1MI.js +0 -1
|
@@ -2,6 +2,9 @@ import express from 'express';
|
|
|
2
2
|
import request from 'supertest';
|
|
3
3
|
import { createGlobalUiEventBroadcaster } from '../event-stream/runtime.js';
|
|
4
4
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
import { createServer } from 'node:http';
|
|
6
|
+
import { createRequestSecurityRuntime } from '../security/request-security.js';
|
|
7
|
+
import { createUiAuth } from '../ui-auth/ui-auth.js';
|
|
5
8
|
|
|
6
9
|
import {
|
|
7
10
|
createDirectoryQueryCanonicalizer,
|
|
@@ -41,6 +44,8 @@ const readyRuntime = () => ({
|
|
|
41
44
|
|
|
42
45
|
const mountProxy = (options = {}) => {
|
|
43
46
|
const app = express();
|
|
47
|
+
const { beforeProxy, ...proxyOptions } = options;
|
|
48
|
+
beforeProxy?.(app);
|
|
44
49
|
// Fresh app each time — registerOpenCodeProxy guards on app setting.
|
|
45
50
|
registerOpenCodeProxy(app, {
|
|
46
51
|
fs: { promises: { realpath: async (v) => v } },
|
|
@@ -54,11 +59,90 @@ const mountProxy = (options = {}) => {
|
|
|
54
59
|
getOpenCodeAuthHeaders: () => ({}),
|
|
55
60
|
buildOpenCodeUrl: (path) => `http://127.0.0.1:4096${path}`,
|
|
56
61
|
ensureOpenCodeApiPrefix: () => {},
|
|
57
|
-
...
|
|
62
|
+
...proxyOptions,
|
|
58
63
|
});
|
|
59
64
|
return app;
|
|
60
65
|
};
|
|
61
66
|
|
|
67
|
+
describe('approved client provenance at the upstream boundary', () => {
|
|
68
|
+
it.each(['/api/session/ses_1/message', '/api/agent', '/api/event'])(
|
|
69
|
+
'accepts approved native clients without relaxing auth or unknown-origin rejection on %s', async (route) => {
|
|
70
|
+
const seen = [];
|
|
71
|
+
const originalMetadata = [];
|
|
72
|
+
const upstream = createServer((req, res) => {
|
|
73
|
+
seen.push({ origin: req.headers.origin, site: req.headers['sec-fetch-site'], auth: req.headers.authorization });
|
|
74
|
+
if (req.headers.origin && req.headers['sec-fetch-site'] === 'cross-site') {
|
|
75
|
+
res.writeHead(403, { 'content-type': 'application/json' });
|
|
76
|
+
return res.end(JSON.stringify({ error: 'Cross-site requests to the API are not allowed' }));
|
|
77
|
+
}
|
|
78
|
+
if (req.headers.authorization !== 'Basic upstream-fixture') {
|
|
79
|
+
res.writeHead(401);
|
|
80
|
+
return res.end();
|
|
81
|
+
}
|
|
82
|
+
res.writeHead(200, { 'content-type': route === '/api/event' ? 'text/event-stream' : 'application/json' });
|
|
83
|
+
res.end(route === '/api/event' ? 'data: {"type":"server.connected"}\n\n' : '[]');
|
|
84
|
+
});
|
|
85
|
+
await new Promise(resolve => upstream.listen(0, '127.0.0.1', resolve));
|
|
86
|
+
const base = `http://127.0.0.1:${upstream.address().port}`;
|
|
87
|
+
const security = createRequestSecurityRuntime({ readSettingsFromDiskMigrated: async () => ({}) });
|
|
88
|
+
const auth = createUiAuth({
|
|
89
|
+
requireClientAuth: true,
|
|
90
|
+
clientAuthController: { authenticateBearerToken: async token => token === 'fixture-client'
|
|
91
|
+
? { ok: true, clientId: 'fixture-client' } : null },
|
|
92
|
+
});
|
|
93
|
+
const app = mountProxy({
|
|
94
|
+
beforeProxy: app => app.use('/api', auth.requireAuth, (req, res, next) => {
|
|
95
|
+
const names = ['origin', 'sec-fetch-site', 'sec-fetch-mode', 'sec-fetch-dest', 'sec-fetch-user'];
|
|
96
|
+
const snapshot = () => Object.fromEntries(names.map(name => [name, req.headers[name]]));
|
|
97
|
+
const before = snapshot();
|
|
98
|
+
res.on('finish', () => originalMetadata.push({ before, after: snapshot() }));
|
|
99
|
+
next();
|
|
100
|
+
}),
|
|
101
|
+
isRequestOriginAllowed: security.isRequestOriginAllowed,
|
|
102
|
+
getRuntime: () => ({ ...readyRuntime(), openCodeBaseUrl: base, openCodePort: upstream.address().port }),
|
|
103
|
+
buildOpenCodeUrl: path => `${base}${path}`,
|
|
104
|
+
getOpenCodeAuthHeaders: () => ({ Authorization: 'Basic upstream-fixture' }),
|
|
105
|
+
});
|
|
106
|
+
try {
|
|
107
|
+
for (const origin of ['capacitor://localhost', 'https://localhost', 'yuri-ui://app']) {
|
|
108
|
+
const response = await request(app).get(route).set({ origin, 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'sec-fetch-user': '?1', authorization: 'Bearer fixture-client' });
|
|
109
|
+
expect(response.status).toBe(200);
|
|
110
|
+
expect(seen.at(-1)).toEqual({ origin, site: undefined, auth: 'Basic upstream-fixture' });
|
|
111
|
+
expect(originalMetadata.at(-1).after).toEqual(originalMetadata.at(-1).before);
|
|
112
|
+
expect(originalMetadata.at(-1).after['sec-fetch-site']).toBe('cross-site');
|
|
113
|
+
}
|
|
114
|
+
const denied = await request(app).get(route).set({ origin: 'https://untrusted.invalid', 'sec-fetch-site': 'cross-site', authorization: 'Bearer fixture-client' });
|
|
115
|
+
expect(denied.status).toBe(403);
|
|
116
|
+
expect(seen.at(-1).site).toBe('cross-site');
|
|
117
|
+
await request(app).get(route).set({ host: 'yuri.example', origin: 'http://yuri.example', 'sec-fetch-site': 'same-origin', authorization: 'Bearer fixture-client' }).expect(200);
|
|
118
|
+
await request(app).get(route).set({ host: 'yuri.example', origin: 'http://yuri.example.attacker.invalid', 'sec-fetch-site': 'cross-site', authorization: 'Bearer fixture-client' }).expect(403);
|
|
119
|
+
const before = seen.length;
|
|
120
|
+
await request(app).get(route).set({ origin: 'capacitor://localhost', 'sec-fetch-site': 'cross-site', authorization: 'Bearer invalid-fixture' }).expect(401);
|
|
121
|
+
expect(seen).toHaveLength(before);
|
|
122
|
+
const unavailablePolicy = mountProxy({
|
|
123
|
+
isRequestOriginAllowed: async () => { throw Error('policy unavailable'); },
|
|
124
|
+
getRuntime: () => ({ ...readyRuntime(), openCodeBaseUrl: base, openCodePort: upstream.address().port }),
|
|
125
|
+
buildOpenCodeUrl: path => `${base}${path}`,
|
|
126
|
+
getOpenCodeAuthHeaders: () => ({ Authorization: 'Basic upstream-fixture' }),
|
|
127
|
+
});
|
|
128
|
+
await request(unavailablePolicy).get(route).set({ origin: 'capacitor://localhost', 'sec-fetch-site': 'cross-site' }).expect(403);
|
|
129
|
+
expect(seen.at(-1).site).toBe('cross-site');
|
|
130
|
+
const missingPolicy = mountProxy({
|
|
131
|
+
getRuntime: () => ({ ...readyRuntime(), openCodeBaseUrl: base, openCodePort: upstream.address().port }),
|
|
132
|
+
buildOpenCodeUrl: path => `${base}${path}`,
|
|
133
|
+
getOpenCodeAuthHeaders: () => ({ Authorization: 'Basic upstream-fixture' }),
|
|
134
|
+
});
|
|
135
|
+
await request(missingPolicy).get(route).set({ origin: 'capacitor://localhost', 'sec-fetch-site': 'cross-site' }).expect(403);
|
|
136
|
+
expect(seen.at(-1).site).toBe('cross-site');
|
|
137
|
+
} finally {
|
|
138
|
+
auth.dispose();
|
|
139
|
+
upstream.closeAllConnections();
|
|
140
|
+
await new Promise(resolve => upstream.close(resolve));
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
);
|
|
144
|
+
});
|
|
145
|
+
|
|
62
146
|
describe('credential response boundary', () => {
|
|
63
147
|
it.each(['/api/credential', '/api/credential/', '/api/%63redential?directory=/repo'])('refuses raw credential list %s before upstream', async (path) => {
|
|
64
148
|
const fetchSpy = vi.fn();
|
|
@@ -16,6 +16,7 @@ export const createServerUtilsRuntime = (dependencies) => {
|
|
|
16
16
|
longRequestTimeoutMs,
|
|
17
17
|
getRuntime,
|
|
18
18
|
getOpenCodeAuthHeaders,
|
|
19
|
+
isRequestOriginAllowed = null,
|
|
19
20
|
buildOpenCodeUrl,
|
|
20
21
|
ensureOpenCodeApiPrefix,
|
|
21
22
|
getUiNotificationClients,
|
|
@@ -239,6 +240,7 @@ export const createServerUtilsRuntime = (dependencies) => {
|
|
|
239
240
|
LONG_REQUEST_TIMEOUT_MS: longRequestTimeoutMs,
|
|
240
241
|
getRuntime,
|
|
241
242
|
getOpenCodeAuthHeaders,
|
|
243
|
+
isRequestOriginAllowed,
|
|
242
244
|
buildOpenCodeUrl,
|
|
243
245
|
ensureOpenCodeApiPrefix,
|
|
244
246
|
getUiNotificationClients,
|
|
@@ -596,15 +596,16 @@ export const createSettingsRuntime = (deps) => {
|
|
|
596
596
|
const migrateSettingsFromLegacyLastDirectory = async (current) => {
|
|
597
597
|
const settings = current && typeof current === 'object' ? current : {};
|
|
598
598
|
const now = Date.now();
|
|
599
|
+
const hasProjectRegistry = Object.prototype.hasOwnProperty.call(settings, 'projects');
|
|
599
600
|
|
|
600
601
|
const sanitizedProjects = sanitizeProjects(settings.projects) || [];
|
|
601
602
|
let nextProjects = sanitizedProjects;
|
|
602
603
|
let nextActiveProjectId =
|
|
603
604
|
typeof settings.activeProjectId === 'string' ? settings.activeProjectId : undefined;
|
|
604
605
|
|
|
605
|
-
let changed =
|
|
606
|
+
let changed = !hasProjectRegistry;
|
|
606
607
|
|
|
607
|
-
if (
|
|
608
|
+
if (!hasProjectRegistry) {
|
|
608
609
|
const legacy = typeof settings.lastDirectory === 'string' ? settings.lastDirectory.trim() : '';
|
|
609
610
|
const candidate = legacy ? resolveDirectoryCandidate(legacy) : null;
|
|
610
611
|
|
|
@@ -852,10 +853,11 @@ export const createSettingsRuntime = (deps) => {
|
|
|
852
853
|
|
|
853
854
|
const persistSettings = async (changes) => runPersistedWrite(async () => {
|
|
854
855
|
const updateCurrent = typeof changes === 'function';
|
|
855
|
-
const
|
|
856
|
+
const stored = updateCurrent
|
|
856
857
|
? await readSettingsFromDiskStrict()
|
|
857
858
|
: await readSettingsFromDisk();
|
|
858
|
-
if (updateCurrent && Array.isArray(
|
|
859
|
+
if (updateCurrent && Array.isArray(stored)) throw new Error('Settings file is malformed (array payload)');
|
|
860
|
+
const { settings: current } = await migrateSettingsFromLegacyLastDirectory(stored);
|
|
859
861
|
if (typeof changes === 'function') changes = await changes(current);
|
|
860
862
|
// Log field names only — changes can carry credentials (UI password,
|
|
861
863
|
// client tokens) that must never reach the log file.
|
|
@@ -905,8 +907,8 @@ export const createSettingsRuntime = (deps) => {
|
|
|
905
907
|
}
|
|
906
908
|
|
|
907
909
|
await writeSettingsToDiskUnlocked(next);
|
|
908
|
-
if (JSON.stringify(
|
|
909
|
-
||
|
|
910
|
+
if (JSON.stringify(stored.projects) !== JSON.stringify(next.projects)
|
|
911
|
+
|| stored.projectSortOrder !== next.projectSortOrder) {
|
|
910
912
|
onProjectOrderChanged?.();
|
|
911
913
|
}
|
|
912
914
|
return formatSettingsResponse(next);
|
|
@@ -36,6 +36,48 @@ const createRuntime = async (overrides = {}) => {
|
|
|
36
36
|
};
|
|
37
37
|
|
|
38
38
|
describe('settings runtime', () => {
|
|
39
|
+
it.each(['read-first', 'write-first', 'functional-write-first'])(
|
|
40
|
+
'keeps a fresh home-directory bootstrap out of the project registry (%s)', async (order) => {
|
|
41
|
+
const { runtime, tempRoot, cleanup } = await createRuntime({
|
|
42
|
+
mergePersistedSettings: (current, changes) => ({ ...current, ...changes }),
|
|
43
|
+
});
|
|
44
|
+
try {
|
|
45
|
+
if (order === 'read-first') await runtime.readSettingsFromDiskMigrated();
|
|
46
|
+
const update = { lastDirectory: tempRoot, homeDirectory: tempRoot };
|
|
47
|
+
await runtime.persistSettings(order === 'functional-write-first' ? () => update : update);
|
|
48
|
+
const settings = await runtime.readSettingsFromDiskMigrated();
|
|
49
|
+
expect(settings.projects).toEqual([]);
|
|
50
|
+
expect(settings.activeProjectId).toBeUndefined();
|
|
51
|
+
expect(settings.lastDirectory).toBe(tempRoot);
|
|
52
|
+
expect((await runtime.readSettingsFromDiskMigrated()).projects).toEqual([]);
|
|
53
|
+
} finally { await cleanup(); }
|
|
54
|
+
},
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
it('does not resurrect a removed last project from the saved directory', async () => {
|
|
58
|
+
const { runtime, tempRoot, cleanup } = await createRuntime({
|
|
59
|
+
mergePersistedSettings: (current, changes) => ({ ...current, ...changes }),
|
|
60
|
+
});
|
|
61
|
+
try {
|
|
62
|
+
await runtime.persistSettings({ projects: [{ id: createProjectIdFromPath(tempRoot), path: tempRoot }], lastDirectory: tempRoot });
|
|
63
|
+
await runtime.persistSettings({ projects: [] });
|
|
64
|
+
expect((await runtime.readSettingsFromDiskMigrated()).projects).toEqual([]);
|
|
65
|
+
} finally { await cleanup(); }
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it.each([false, true])('still migrates a saved pre-registry directory exactly once (write first=%s)', async (writeFirst) => {
|
|
69
|
+
const { runtime, settingsFilePath, tempRoot, cleanup } = await createRuntime({
|
|
70
|
+
mergePersistedSettings: (current, changes) => ({ ...current, ...changes }),
|
|
71
|
+
});
|
|
72
|
+
try {
|
|
73
|
+
await fsPromises.writeFile(settingsFilePath, JSON.stringify({ lastDirectory: tempRoot }));
|
|
74
|
+
if (writeFirst) await runtime.persistSettings({ homeDirectory: '/home/fixture' });
|
|
75
|
+
const settings = await runtime.readSettingsFromDiskMigrated();
|
|
76
|
+
expect(settings.projects).toEqual([expect.objectContaining({ id: createProjectIdFromPath(tempRoot), path: tempRoot })]);
|
|
77
|
+
expect((await runtime.readSettingsFromDiskMigrated()).projects).toEqual(settings.projects);
|
|
78
|
+
} finally { await cleanup(); }
|
|
79
|
+
});
|
|
80
|
+
|
|
39
81
|
it.each([
|
|
40
82
|
[{}, 'cursor-dark'],
|
|
41
83
|
[{ darkThemeId: 'vitesse-dark-dark' }, 'vitesse-dark-dark'],
|
|
@@ -77,6 +119,8 @@ describe('settings runtime', () => {
|
|
|
77
119
|
expect((await runtime.readSettingsFromDisk()).projectSortOrder).toBe('recent');
|
|
78
120
|
fail = false;
|
|
79
121
|
await runtime.persistSettings({ projects: [] });
|
|
122
|
+
expect(tips).toBe(1);
|
|
123
|
+
await runtime.persistSettings({ projectSortOrder: 'manual' });
|
|
80
124
|
expect(tips).toBe(2);
|
|
81
125
|
} finally { await cleanup(); }
|
|
82
126
|
});
|
|
@@ -22,7 +22,7 @@ export const registerYuriRoutes = (app, dependencies) => {
|
|
|
22
22
|
getCommittedHostMetadata,
|
|
23
23
|
});
|
|
24
24
|
registerTranscriptCacheRoutes(app, { transcriptCacheService });
|
|
25
|
-
registerContentSearchRoutes(app, { contentSearch: dependencies.contentSearch });
|
|
25
|
+
registerContentSearchRoutes(app, { contentSearch: dependencies.contentSearch, uiAuthController: dependencies.uiAuthController });
|
|
26
26
|
registerConfigSyncRoutes(app, { express });
|
|
27
27
|
if (dependencies.hostUpdates) registerHostUpdateRoutes(app, {
|
|
28
28
|
express, runtime: dependencies.hostUpdates, uiAuthController: dependencies.uiAuthController,
|
|
@@ -70,7 +70,7 @@ See also `packages/web/server/lib/opencode/DOCUMENTATION.md` (“Catalog / Yuri-
|
|
|
70
70
|
|
|
71
71
|
## Authentication model
|
|
72
72
|
|
|
73
|
-
- The tunnel
|
|
73
|
+
- The tunnel forwards HTTP/SSE and WebSocket opens only after Host-owned `authorizeRelayRequest` confirms a current Relay-enabled pairing credential. Missing authorization wiring fails closed. SSH/password credentials, owner cookies and direct-only pairings are rejected before any loopback request/socket is opened; URL tokens are checked against their issuing client's current pairing grant, revocation and expiry. The local server still performs its ordinary route authentication. Only `POST /api/client-auth/pairing/redeem` may enter before a client credential exists, and that route validates the one-time secret and Relay-enabled pairing scope.
|
|
74
74
|
- A paired **desktop** client is a device-fleet operator: through the tunnel it can create pairing links using existing or custom Relay endpoints, list every paired device, and revoke other devices (parity with the SSH attach flow). Pairing with a new endpoint appends it without replacing existing endpoints. Wholesale endpoint-list replacement/removal remains an owner-UI / local-desktop-shell action. Mobile (and any other) paired clients stay scoped to their own record.
|
|
75
75
|
- Clients carry their normal credential. HTTP and SSE requests authenticate with the client's bearer token (a header). **WebSocket upgrades cannot send headers**, so they authenticate with a short-lived URL-scoped token minted beforehand and passed as a query parameter. This asymmetry is important when adding new WebSocket features (see the skill).
|
|
76
76
|
- Desktop switch preflight calls `/auth/session` with the saved bearer over a pinned tunnel before adopting it. `/health` and cached reachability badges provide transport information only. Failed or timed-out probes close their temporary tunnel and preserve the active runtime; successful switch probes transfer ownership of the authenticated tunnel to the runtime.
|
|
@@ -57,6 +57,7 @@ const resolveBatchWindowMs = (option) => {
|
|
|
57
57
|
* identity: { serverId: string, hostEncPrivateKey: CryptoKey, signRelayAuth: (role: string, connectionId?: string | null) => { ts: number, sig: string, pk: string } },
|
|
58
58
|
* localPort?: number,
|
|
59
59
|
* getLocalPort?: () => number,
|
|
60
|
+
* authorizeRequest?: (req: { method: string, url: string, headers: Record<string, string> }) => Promise<boolean>,
|
|
60
61
|
* onStatus?: (status: { state: string, lastError: string | null, connectedClients: number }) => void,
|
|
61
62
|
* logger?: Pick<Console, 'warn'>,
|
|
62
63
|
* reconnectBaseDelayMs?: number,
|
|
@@ -64,7 +65,7 @@ const resolveBatchWindowMs = (option) => {
|
|
|
64
65
|
* controlStableMs?: number,
|
|
65
66
|
* }} options
|
|
66
67
|
*/
|
|
67
|
-
export const startRelayHost = ({ relayUrl, identity, localPort, getLocalPort, onStatus, logger = console, batchWindowMs, batch, reconnectBaseDelayMs, reconnectMaxDelayMs, controlStableMs }) => {
|
|
68
|
+
export const startRelayHost = ({ relayUrl, identity, localPort, getLocalPort, authorizeRequest, onStatus, logger = console, batchWindowMs, batch, reconnectBaseDelayMs, reconnectMaxDelayMs, controlStableMs }) => {
|
|
68
69
|
const resolveLocalPort = typeof getLocalPort === 'function' ? getLocalPort : () => localPort;
|
|
69
70
|
const localBatch = batch !== false;
|
|
70
71
|
const resolvedBatchWindowMs = resolveBatchWindowMs(batchWindowMs);
|
|
@@ -197,6 +198,7 @@ export const startRelayHost = ({ relayUrl, identity, localPort, getLocalPort, on
|
|
|
197
198
|
: null;
|
|
198
199
|
entry.tunnel = createTunnelHost({
|
|
199
200
|
connectionId,
|
|
201
|
+
authorizeRequest,
|
|
200
202
|
getLocalPort: resolveLocalPort,
|
|
201
203
|
getBufferedAmount: () => socket.bufferedAmount,
|
|
202
204
|
sendFrame: (plaintextFrame, immediate = false) => {
|
|
@@ -250,6 +250,7 @@ describe('relay host-client integration', () => {
|
|
|
250
250
|
it('tunnels an HTTP GET /health with only binary frames post-handshake', async () => {
|
|
251
251
|
const identity = await buildIdentity();
|
|
252
252
|
host = startRelayHost({
|
|
253
|
+
authorizeRequest: async () => true,
|
|
253
254
|
relayUrl: `${relay.wsUrl}/`,
|
|
254
255
|
identity,
|
|
255
256
|
getLocalPort: () => origin.port,
|
|
@@ -398,6 +398,7 @@ describe('relay reasoning projection e2e (Host filter over private relay)', () =
|
|
|
398
398
|
|
|
399
399
|
const identity = await buildIdentity();
|
|
400
400
|
host = startRelayHost({
|
|
401
|
+
authorizeRequest: async () => true,
|
|
401
402
|
relayUrl,
|
|
402
403
|
identity,
|
|
403
404
|
getLocalPort: () => origin!.port,
|
|
@@ -195,10 +195,13 @@ const startOrigin = async (options: { recoveryEvents?: boolean } = {}) => {
|
|
|
195
195
|
const bearerRequests: string[] = [];
|
|
196
196
|
const observedOrigins: string[] = [];
|
|
197
197
|
const sockets = new Set<net.Socket>();
|
|
198
|
+
const pairedClient = { id: 'device-1', authMethod: 'pairing', pairingId: 'fixture-pairing', usesRelay: true };
|
|
199
|
+
const sshClient = { id: 'ssh-client', authMethod: 'password', clientKind: 'desktop-local', usesRelay: false };
|
|
198
200
|
const clientAuthController = {
|
|
201
|
+
listClients: async () => [pairedClient, sshClient],
|
|
199
202
|
authenticateBearerToken: async (token: string) => token === 'client-token'
|
|
200
|
-
? { ok: true, clientId: 'device-1', sessionToken: 'client:device-1' }
|
|
201
|
-
: { ok: false },
|
|
203
|
+
? { ok: true, clientId: 'device-1', sessionToken: 'client:device-1', client: pairedClient }
|
|
204
|
+
: token === 'ssh-token' ? { ok: true, clientId: sshClient.id, client: sshClient } : { ok: false },
|
|
202
205
|
};
|
|
203
206
|
const uiAuth = createUiAuth({ requireClientAuth: true, clientAuthController });
|
|
204
207
|
const requestSecurity = createRequestSecurityRuntime({ readSettingsFromDiskMigrated: async () => ({}) });
|
|
@@ -366,6 +369,7 @@ const startOrigin = async (options: { recoveryEvents?: boolean } = {}) => {
|
|
|
366
369
|
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
367
370
|
const port = (server.address() as net.AddressInfo).port;
|
|
368
371
|
return {
|
|
372
|
+
authorizeRequest: uiAuth.authorizeRelayRequest,
|
|
369
373
|
port, videoPath, previewPath, previewContent, guiBundle, pluginInventory, guiRequests, bearerRequests, observedOrigins, attachmentAssistant, getHostSubscriptions: () => hostSubscriptions,
|
|
370
374
|
advanceRecoveryRevision: () => { recoveryRevision += 1; return `ses_recovery_${recoveryRevision}`; },
|
|
371
375
|
stop: async () => {
|
|
@@ -484,7 +488,7 @@ describe('private relay compiled-process boundary', () => {
|
|
|
484
488
|
relay = await startCompiledRelay(binary, await freePort());
|
|
485
489
|
origin = await startOrigin();
|
|
486
490
|
const identity = await buildIdentity();
|
|
487
|
-
host = startRelayHost({ relayUrl: relay.url, identity, getLocalPort: () => origin!.port,
|
|
491
|
+
host = startRelayHost({ authorizeRequest: origin.authorizeRequest, relayUrl: relay.url, identity, getLocalPort: () => origin!.port,
|
|
488
492
|
batch: hostBatch, batchWindowMs: 2_000, onStatus() {}, logger: { warn() {}, info() {} } });
|
|
489
493
|
client = createRelayTunnelClient({ relayUrl: relay.url, serverId: identity.serverId, hostEncPubJwk: identity.hostEncPubJwk,
|
|
490
494
|
batch: clientBatch, batchWindowMs: 2_000, pingIntervalMs: 60_000 });
|
|
@@ -526,13 +530,13 @@ describe('private relay compiled-process boundary', () => {
|
|
|
526
530
|
};
|
|
527
531
|
origin = await startOrigin();
|
|
528
532
|
const identity = await buildIdentity();
|
|
529
|
-
host = startRelayHost({ relayUrl, identity, getLocalPort: () => origin!.port,
|
|
533
|
+
host = startRelayHost({ authorizeRequest: origin.authorizeRequest, relayUrl, identity, getLocalPort: () => origin!.port,
|
|
530
534
|
batchWindowMs: 5, onStatus() {}, logger: { warn() {}, info() {} } });
|
|
531
535
|
client = createRelayTunnelClient({ relayUrl, serverId: identity.serverId, hostEncPubJwk: identity.hostEncPubJwk,
|
|
532
536
|
batchWindowMs: 5, helloRetryMs: 50 });
|
|
533
537
|
await eventually(() => host!.getStatus().state === 'connected' && client!.getStatus().state === 'connected', 'Worker E2EE tunnel did not connect');
|
|
534
538
|
|
|
535
|
-
expect((await client.fetch('/api/event')).status).toBe(
|
|
539
|
+
expect((await client.fetch('/api/event')).status).toBe(403);
|
|
536
540
|
const headers = { authorization: 'Bearer client-token' };
|
|
537
541
|
const httpResponse = await client.fetch('/api/e2e/http', { method: 'POST', headers, body: 'worker-stream-body' });
|
|
538
542
|
expect(await httpResponse.json()).toEqual({ body: 'worker-stream-body', hasRelayConnection: true });
|
|
@@ -598,7 +602,7 @@ describe('private relay compiled-process boundary', () => {
|
|
|
598
602
|
relay = await startCompiledRelay(binary, port);
|
|
599
603
|
origin = await startOrigin({ recoveryEvents: true });
|
|
600
604
|
const identity = await buildIdentity();
|
|
601
|
-
const startHost = () => startRelayHost({ relayUrl: relay!.url, identity, getLocalPort: () => origin!.port,
|
|
605
|
+
const startHost = () => startRelayHost({ authorizeRequest: origin!.authorizeRequest, relayUrl: relay!.url, identity, getLocalPort: () => origin!.port,
|
|
602
606
|
onStatus() {}, logger: { warn() {}, info() {} }, reconnectBaseDelayMs: 30, reconnectMaxDelayMs: 100 });
|
|
603
607
|
host = startHost();
|
|
604
608
|
await eventually(() => host!.getStatus().state === 'connected', 'Host did not register');
|
|
@@ -719,7 +723,7 @@ describe('private relay compiled-process boundary', () => {
|
|
|
719
723
|
relay = await startCompiledRelay(binary, port);
|
|
720
724
|
origin = await startOrigin();
|
|
721
725
|
const identity = await buildIdentity();
|
|
722
|
-
host = startRelayHost({ relayUrl: relay.url, identity, getLocalPort: () => origin.port, onStatus: () => {}, logger: { warn: () => {}, info: () => {} } });
|
|
726
|
+
host = startRelayHost({ authorizeRequest: origin.authorizeRequest, relayUrl: relay.url, identity, getLocalPort: () => origin.port, onStatus: () => {}, logger: { warn: () => {}, info: () => {} } });
|
|
723
727
|
let receivedBytes = 0;
|
|
724
728
|
client = createRelayTunnelClient({
|
|
725
729
|
relayUrl: relay.url, serverId: identity.serverId, hostEncPubJwk: identity.hostEncPubJwk,
|
|
@@ -749,6 +753,17 @@ describe('private relay compiled-process boundary', () => {
|
|
|
749
753
|
});
|
|
750
754
|
|
|
751
755
|
await eventually(() => host!.getStatus().state === 'connected' && client!.getStatus().state === 'connected', 'host and TypeScript client did not connect');
|
|
756
|
+
const directSsh = await fetch(`http://127.0.0.1:${origin.port}/auth/url-token`, {
|
|
757
|
+
method: 'POST', headers: { authorization: 'Bearer ssh-token' },
|
|
758
|
+
});
|
|
759
|
+
expect(directSsh.status).toBe(200);
|
|
760
|
+
const sshUrlToken = (await directSsh.json()).token;
|
|
761
|
+
for (const route of ['/auth/session', '/api/e2e/initialization', '/api/e2e/sse']) {
|
|
762
|
+
expect((await client.fetch(route, { headers: { authorization: 'Bearer ssh-token' } })).status).toBe(403);
|
|
763
|
+
}
|
|
764
|
+
const unpairedSocket = client.openWebSocket(`/api/terminal/ws?yuri_url_token=${encodeURIComponent(sshUrlToken)}`);
|
|
765
|
+
await expect(waitSocketOpen(unpairedSocket)).rejects.toThrow();
|
|
766
|
+
expect(origin.observedOrigins).toEqual([]);
|
|
752
767
|
const body = new ReadableStream<Uint8Array>({
|
|
753
768
|
start(controller) { controller.enqueue(new TextEncoder().encode('stream-')); controller.enqueue(new TextEncoder().encode('body')); controller.close(); },
|
|
754
769
|
});
|
|
@@ -774,7 +789,7 @@ describe('private relay compiled-process boundary', () => {
|
|
|
774
789
|
expect(new TextDecoder().decode(Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))))).toBe('data: one\n\ndata: two\n\ndata: three\n\n');
|
|
775
790
|
|
|
776
791
|
const denied = await client.fetch('/api/event');
|
|
777
|
-
expect(denied.status).toBe(
|
|
792
|
+
expect(denied.status).toBe(403);
|
|
778
793
|
const hostEvents = await client.fetch('/api/event', { headers: { authorization: 'Bearer client-token' } });
|
|
779
794
|
expect(hostEvents.status).toBe(200);
|
|
780
795
|
const frames = (await hostEvents.text()).trim().split('\n\n').map((block) => JSON.parse(block.slice(6)));
|
|
@@ -821,7 +836,7 @@ describe('private relay compiled-process boundary', () => {
|
|
|
821
836
|
const assistantID = origin.attachmentAssistant.id;
|
|
822
837
|
const uploadPath = `/api/yuri/assistants/${assistantID}/contact/attachments`;
|
|
823
838
|
for (const headers of [{}, { authorization: 'Bearer invalid-token' }]) {
|
|
824
|
-
expect((await client.fetch(`${uploadPath}/denied`, { method: 'PUT', headers, body: previewPng })).status).toBe(
|
|
839
|
+
expect((await client.fetch(`${uploadPath}/denied`, { method: 'PUT', headers, body: previewPng })).status).toBe(403);
|
|
825
840
|
}
|
|
826
841
|
const attachmentParts: Awaited<ReturnType<typeof uploadAssistantAttachment>>[] = [];
|
|
827
842
|
for (const [index, file] of [
|
|
@@ -839,7 +854,7 @@ describe('private relay compiled-process boundary', () => {
|
|
|
839
854
|
const download = await runtimeFetch(`${uploadPath}/${descriptor.attachmentID}`);
|
|
840
855
|
expect(download.status).toBe(200);
|
|
841
856
|
expect(Buffer.from(await download.arrayBuffer())).toEqual(Buffer.from(await file.arrayBuffer()));
|
|
842
|
-
expect((await client.fetch(`${uploadPath}/${descriptor.attachmentID}`)).status).toBe(
|
|
857
|
+
expect((await client.fetch(`${uploadPath}/${descriptor.attachmentID}`)).status).toBe(403);
|
|
843
858
|
}
|
|
844
859
|
const admission = await runtimeFetch(`/api/yuri/assistants/${assistantID}/messages`, {
|
|
845
860
|
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
@@ -854,8 +869,8 @@ describe('private relay compiled-process boundary', () => {
|
|
|
854
869
|
const files = createWebFilesAPI({ getDirectory: () => path.dirname(origin.previewPath) });
|
|
855
870
|
expect(Buffer.byteLength(origin.guiBundle.code)).toBeGreaterThan(2_270_000);
|
|
856
871
|
for (const route of ['/api/plugin', '/api/plugin/gui?id=preview-fixture', `/api/fs/stat?path=${encodeURIComponent(origin.previewPath)}`, `/api/fs/raw?path=${encodeURIComponent(origin.previewPath)}`]) {
|
|
857
|
-
expect((await client.fetch(route)).status).toBe(
|
|
858
|
-
expect((await client.fetch(route, { headers: { authorization: 'Bearer invalid-token' } })).status).toBe(
|
|
872
|
+
expect((await client.fetch(route)).status).toBe(403);
|
|
873
|
+
expect((await client.fetch(route, { headers: { authorization: 'Bearer invalid-token' } })).status).toBe(403);
|
|
859
874
|
}
|
|
860
875
|
expect((await gui.plugin.list()).data).toEqual(origin.pluginInventory);
|
|
861
876
|
expect((await gui.plugin.gui({ id: 'preview-fixture' })).data).toEqual(origin.guiBundle);
|
|
@@ -908,10 +923,10 @@ describe('private relay compiled-process boundary', () => {
|
|
|
908
923
|
});
|
|
909
924
|
try {
|
|
910
925
|
const deniedSpeech = await client.fetch('/api/tts/speak', { method: 'POST' });
|
|
911
|
-
expect(deniedSpeech.status).toBe(
|
|
912
|
-
expect((await client.fetch('/api/voice/session', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"kind":"tts"}' })).status).toBe(
|
|
913
|
-
expect((await client.fetch('/api/voice/volcengine')).status).toBe(
|
|
914
|
-
expect((await client.fetch('/api/voice/volcengine', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: '{}' })).status).toBe(
|
|
926
|
+
expect(deniedSpeech.status).toBe(403);
|
|
927
|
+
expect((await client.fetch('/api/voice/session', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"kind":"tts"}' })).status).toBe(403);
|
|
928
|
+
expect((await client.fetch('/api/voice/volcengine')).status).toBe(403);
|
|
929
|
+
expect((await client.fetch('/api/voice/volcengine', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: '{}' })).status).toBe(403);
|
|
915
930
|
const saved = await realFetch(`http://127.0.0.1:${origin.port}/api/voice/settings`, {
|
|
916
931
|
method: 'PUT', headers: { authorization: 'Bearer client-token', 'Content-Type': 'application/json' },
|
|
917
932
|
body: JSON.stringify({ apiKey: 'fixture-speech-key', voice: 'zh_female_vv_uranus_bigtts', showMessageTTSButtons: true, voiceProvider: 'volcengine', dictationEnabled: true, sttProvider: 'volcengine' }),
|
|
@@ -978,7 +993,7 @@ describe('private relay compiled-process boundary', () => {
|
|
|
978
993
|
releaseAsset: async () => { released = true; },
|
|
979
994
|
} });
|
|
980
995
|
const deniedImage = await client.fetch('/api/fs/raw?path=%2Fremote%2Ficons-zoom.png');
|
|
981
|
-
expect(deniedImage.status).toBe(
|
|
996
|
+
expect(deniedImage.status).toBe(403);
|
|
982
997
|
for (const intent of ['inline', 'preview'] as const) {
|
|
983
998
|
received.length = 0;
|
|
984
999
|
ended = false;
|
|
@@ -133,6 +133,7 @@ export const createRelayService = ({
|
|
|
133
133
|
// regeneration — see identity.js/signing-key.js.
|
|
134
134
|
readSettingsStrict,
|
|
135
135
|
getLocalPort,
|
|
136
|
+
authorizeRequest = async () => false,
|
|
136
137
|
// Returns true when any paired device or pending pairing session uses the
|
|
137
138
|
// relay transport. The relay lifecycle is driven purely by this demand.
|
|
138
139
|
hasRelayDemand = async () => false,
|
|
@@ -316,6 +317,7 @@ export const createRelayService = ({
|
|
|
316
317
|
if (hostClients.has(relayUrl)) continue;
|
|
317
318
|
const hostClient = startRelayHost({
|
|
318
319
|
relayUrl,
|
|
320
|
+
authorizeRequest,
|
|
319
321
|
identity,
|
|
320
322
|
getLocalPort,
|
|
321
323
|
logger,
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// HTTP streams -> fetch http://127.0.0.1:<port> with streamed duplex bodies;
|
|
4
4
|
// WS streams -> `ws` client to the loopback WebSocket endpoints.
|
|
5
5
|
// The dispatcher NEVER injects credentials: tunneled requests authenticate
|
|
6
|
-
//
|
|
6
|
+
// using bearer/URL tokens, with Relay pairing admission before loopback forwarding.
|
|
7
7
|
// Spec: .opencode/plans/private-relay/01-protocol-spec.md (Layer 3).
|
|
8
8
|
|
|
9
9
|
import { WebSocket } from 'ws';
|
|
@@ -110,6 +110,7 @@ const isWsClosePayload = (parsed) => Boolean(parsed && typeof parsed === 'object
|
|
|
110
110
|
* getLocalPort: () => number,
|
|
111
111
|
* sendFrame: (plaintextFrame: Uint8Array, immediate?: boolean) => void | Promise<void>,
|
|
112
112
|
* getBufferedAmount: () => number,
|
|
113
|
+
* authorizeRequest?: (req: { method: string, url: string, headers: Record<string, string> }) => Promise<boolean>,
|
|
113
114
|
* createWebSocket?: (url: string, protocols: string[] | undefined, options: { headers: Record<string, string> }) => import('ws').WebSocket,
|
|
114
115
|
* }} deps
|
|
115
116
|
*/
|
|
@@ -118,6 +119,7 @@ export const createTunnelHost = ({
|
|
|
118
119
|
getLocalPort,
|
|
119
120
|
sendFrame,
|
|
120
121
|
getBufferedAmount,
|
|
122
|
+
authorizeRequest = async () => false,
|
|
121
123
|
createWebSocket = (url, protocols, options) => new WebSocket(url, protocols, options),
|
|
122
124
|
}) => {
|
|
123
125
|
/** @type {Map<number, { kind: 'http', abort: AbortController, body: ReadableStreamDefaultController | null } | { kind: 'ws', socket: WebSocket, opened: boolean }>} */
|
|
@@ -466,6 +468,29 @@ export const createTunnelHost = ({
|
|
|
466
468
|
if (closed) return;
|
|
467
469
|
const frame = decodeTunnelFrame(plaintextFrame);
|
|
468
470
|
|
|
471
|
+
if (frame.frameType === TunnelFrameType.HttpRequest || frame.frameType === TunnelFrameType.WsOpen) {
|
|
472
|
+
const websocket = frame.frameType === TunnelFrameType.WsOpen;
|
|
473
|
+
let authorized = false;
|
|
474
|
+
try {
|
|
475
|
+
const request = decodeJsonPayload(frame.payload, websocket ? isWsOpenPayload : isHttpRequestPayload);
|
|
476
|
+
authorized = await authorizeRequest({
|
|
477
|
+
method: websocket ? 'GET' : request.method.toUpperCase(),
|
|
478
|
+
url: `${request.path}${request.query ? `?${request.query}` : ''}`,
|
|
479
|
+
headers: websocket
|
|
480
|
+
? { upgrade: 'websocket', 'x-yuri-relay-connection': connectionId }
|
|
481
|
+
: buildRequestHeaders(request.headers),
|
|
482
|
+
}) === true;
|
|
483
|
+
} catch {
|
|
484
|
+
authorized = false;
|
|
485
|
+
}
|
|
486
|
+
if (closed) return;
|
|
487
|
+
if (!authorized) {
|
|
488
|
+
if (websocket) await sendAbort(frame.streamId, 'Relay pairing authorization required');
|
|
489
|
+
else await syntheticResponse(frame.streamId, 403, 'Relay pairing authorization required');
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
469
494
|
// WS message frames can be fragmented; everything else arrives whole.
|
|
470
495
|
if (frame.frameType === TunnelFrameType.WsText || frame.frameType === TunnelFrameType.WsBinary) {
|
|
471
496
|
const message = assembler.push(frame);
|
|
@@ -22,6 +22,27 @@ import { createTunnelHost, isTunnelWsPathAllowed } from './tunnel-host.js';
|
|
|
22
22
|
const textEncoder = new TextEncoder();
|
|
23
23
|
const textDecoder = new TextDecoder();
|
|
24
24
|
|
|
25
|
+
describe('relay admission before loopback access', () => {
|
|
26
|
+
it('denies HTTP and WebSocket traffic without an authorization provider', async () => {
|
|
27
|
+
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}'));
|
|
28
|
+
const dial = vi.fn(() => new FakeWebSocket('unused'));
|
|
29
|
+
const frames = [];
|
|
30
|
+
const host = createTunnelHost({ connectionId: 'unpaired', getLocalPort: () => 9,
|
|
31
|
+
sendFrame: (frame) => frames.push(decodeTunnelFrame(frame)), getBufferedAmount: () => 0, createWebSocket: dial });
|
|
32
|
+
try {
|
|
33
|
+
await host.handleFrame(encodeTunnelFrame(TunnelFrameType.HttpRequest, 1, encodeJsonPayload({
|
|
34
|
+
method: 'GET', path: '/auth/session', query: '', headers: { authorization: 'Bearer ssh-token' },
|
|
35
|
+
})));
|
|
36
|
+
await host.handleFrame(encodeTunnelFrame(TunnelFrameType.WsOpen, 2, encodeJsonPayload({
|
|
37
|
+
path: '/api/terminal/ws', query: 'yuri_url_token=ssh-url-token',
|
|
38
|
+
})));
|
|
39
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
40
|
+
expect(dial).not.toHaveBeenCalled();
|
|
41
|
+
expect(JSON.parse(textDecoder.decode(frames[0].payload)).status).toBe(403);
|
|
42
|
+
} finally { host.close(); fetchMock.mockRestore(); }
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
25
46
|
/** Minimal EventEmitter-shaped fake used only by createTunnelHost tests. */
|
|
26
47
|
class FakeWebSocket {
|
|
27
48
|
static OPEN = 1;
|
|
@@ -83,7 +104,7 @@ describe('negotiated JSON response compression', () => {
|
|
|
83
104
|
headers: { 'content-type': contentType, 'content-length': String(raw.byteLength) },
|
|
84
105
|
}));
|
|
85
106
|
const frames = [];
|
|
86
|
-
const host = createTunnelHost({ connectionId: 'compression-test', getLocalPort: () => 9,
|
|
107
|
+
const host = createTunnelHost({ authorizeRequest: async () => true, connectionId: 'compression-test', getLocalPort: () => 9,
|
|
87
108
|
sendFrame: (frame) => { frames.push(decodeTunnelFrame(frame)); }, getBufferedAmount: () => 0 });
|
|
88
109
|
try {
|
|
89
110
|
await host.handleFrame(encodeTunnelFrame(TunnelFrameType.HttpRequest, 1, encodeJsonPayload({
|
|
@@ -112,7 +133,7 @@ describe('negotiated JSON response compression', () => {
|
|
|
112
133
|
headers: { 'content-type': 'text/event-stream; charset=utf-8' },
|
|
113
134
|
}));
|
|
114
135
|
const frames = [];
|
|
115
|
-
const host = createTunnelHost({ connectionId: 'sse-gzip-test', getLocalPort: () => 9,
|
|
136
|
+
const host = createTunnelHost({ authorizeRequest: async () => true, connectionId: 'sse-gzip-test', getLocalPort: () => 9,
|
|
116
137
|
sendFrame: (frame) => { frames.push(decodeTunnelFrame(frame)); }, getBufferedAmount: () => 0 });
|
|
117
138
|
const bodies = () => frames.filter((frame) => frame.frameType === TunnelFrameType.HttpBody).map((frame) => textDecoder.decode(frame.payload));
|
|
118
139
|
try {
|
|
@@ -135,7 +156,7 @@ describe('remote desktop send scheduling', () => {
|
|
|
135
156
|
it.each(['/api/remote-desktop/ws', '/api/event/ws'])('only remote desktop requests immediate data flushes: %s', async (path) => {
|
|
136
157
|
FakeWebSocket.reset();
|
|
137
158
|
const sent = [];
|
|
138
|
-
const host = createTunnelHost({ connectionId: 'scheduling', getLocalPort: () => 9,
|
|
159
|
+
const host = createTunnelHost({ authorizeRequest: async () => true, connectionId: 'scheduling', getLocalPort: () => 9,
|
|
139
160
|
sendFrame: (frame, immediate) => { sent.push({ ...decodeTunnelFrame(frame), immediate }); },
|
|
140
161
|
getBufferedAmount: () => 0, createWebSocket: (url, protocols) => new FakeWebSocket(url, protocols) });
|
|
141
162
|
try {
|
|
@@ -184,6 +205,7 @@ describe('createTunnelHost WS path allowlist', () => {
|
|
|
184
205
|
/** @type {Uint8Array[]} */
|
|
185
206
|
const outbound = [];
|
|
186
207
|
const host = createTunnelHost({
|
|
208
|
+
authorizeRequest: async () => true,
|
|
187
209
|
connectionId: 'test-conn',
|
|
188
210
|
getLocalPort: () => 9,
|
|
189
211
|
sendFrame: (frame) => {
|
|
@@ -232,6 +254,7 @@ describe('createTunnelHost WS fragment ordering', () => {
|
|
|
232
254
|
};
|
|
233
255
|
|
|
234
256
|
const host = createTunnelHost({
|
|
257
|
+
authorizeRequest: async () => true,
|
|
235
258
|
connectionId: 'test-conn',
|
|
236
259
|
getLocalPort: () => 9,
|
|
237
260
|
sendFrame,
|
|
@@ -314,6 +337,7 @@ describe('createTunnelHost WS fragment ordering', () => {
|
|
|
314
337
|
};
|
|
315
338
|
|
|
316
339
|
const host = createTunnelHost({
|
|
340
|
+
authorizeRequest: async () => true,
|
|
317
341
|
connectionId: 'test-conn',
|
|
318
342
|
getLocalPort: () => 9,
|
|
319
343
|
sendFrame,
|
|
@@ -129,7 +129,7 @@ it('stops native control when the device is revoked', { timeout: 10000 }, async
|
|
|
129
129
|
});
|
|
130
130
|
it('carries screen frames and validated input through the real Relay WS dispatcher and auth gates', async () => {
|
|
131
131
|
const frames = [];
|
|
132
|
-
const host = createTunnelHost({ connectionId: 'desktop-test', getLocalPort: () => port,
|
|
132
|
+
const host = createTunnelHost({ authorizeRequest: async () => true, connectionId: 'desktop-test', getLocalPort: () => port,
|
|
133
133
|
sendFrame: frame => { frames.push(decodeTunnelFrame(frame)); }, getBufferedAmount: () => 0 });
|
|
134
134
|
try {
|
|
135
135
|
await host.handleFrame(encodeTunnelFrame(TunnelFrameType.WsOpen, 2, encodeJsonPayload({ path: '/api/remote-desktop/ws', query: `yuri_url_token=${token}` })));
|
|
@@ -157,7 +157,7 @@ it('carries screen frames and validated input through the real Relay WS dispatch
|
|
|
157
157
|
it('releases failed capture ownership and reconnects through the authenticated Relay dispatcher', async () => {
|
|
158
158
|
adapter.start.mockRejectedValueOnce(Object.assign(new Error('capture_timeout'), { code: 'capture_timeout' }));
|
|
159
159
|
const frames = [];
|
|
160
|
-
const host = createTunnelHost({ connectionId: 'desktop-recovery-test', getLocalPort: () => port,
|
|
160
|
+
const host = createTunnelHost({ authorizeRequest: async () => true, connectionId: 'desktop-recovery-test', getLocalPort: () => port,
|
|
161
161
|
sendFrame: frame => { frames.push(decodeTunnelFrame(frame)); }, getBufferedAmount: () => 0 });
|
|
162
162
|
const open = id => host.handleFrame(encodeTunnelFrame(TunnelFrameType.WsOpen, id,
|
|
163
163
|
encodeJsonPayload({ path: '/api/remote-desktop/ws', query: `yuri_url_token=${token}` })));
|
|
@@ -5,6 +5,8 @@ This module owns Yuri UI authentication for browser access, including password s
|
|
|
5
5
|
|
|
6
6
|
Trusted-device access has one durable credential model: a remote client bearer token stored by `packages/web/server/lib/client-auth/remote-clients.js`. Password, passkey, and Pairing v2 are issuance methods for that credential, not separate credential systems. Issued client tokens are returned once, stored server-side only as hashes, and are later authenticated via `Authorization: Bearer yuri_client_...`.
|
|
7
7
|
|
|
8
|
+
Relay admission additionally requires an active client record with `usesRelay: true`, `authMethod: 'pairing'`, and a pairing ID. `authorizeRelayRequest` enforces this before the tunnel forwards any HTTP/SSE request or WebSocket upgrade, including when the Host has no UI password. SSH/password/passkey credentials, owner cookies, and direct-only pairings do not grant Relay access. URL tokens resolve back to their issuing client and recheck current revocation/expiry and Relay permission. The only pre-credential route is `POST /api/client-auth/pairing/redeem`; its one-time secret validation also requires a Relay-enabled pairing when arriving through Relay. Direct authentication behavior is unchanged.
|
|
9
|
+
|
|
8
10
|
Pairing v2 is implemented by `packages/web/server/lib/client-auth/pairing.js`. It stores short-lived one-time pairing sessions with hashed secrets, exposes create/cancel/redeem routes under `/api/client-auth/pairing/*`, and redeems a valid pairing secret into the same remote client token used by password/passkey trusted-device flows.
|
|
9
11
|
|
|
10
12
|
Client deduplication is scoped by device `dedupeKey`, `usesRelay`, and the pairing's canonical `relayUrl`. The create route records the actual advertised Relay candidate (including a default or environment-selected endpoint), and redemption uses this stored scope even when it arrives over LAN. Re-pairing through the same Relay replaces that connection's credential; another Relay or direct-only pairing retains an independent client record, label, credential, and revocation. The endpoint is internal persistence metadata, not a client-supplied redemption override. Legacy records without `relayUrl` remain readable with an unknown Relay scope; new endpoint-specific pairings preserve them rather than guessing which connection to overwrite. No stored credential conversion is needed.
|
|
@@ -20,6 +22,7 @@ Remote desktop uses the exact `/api/remote-desktop/ws` scoped URL-token path, mi
|
|
|
20
22
|
## Public exports (ui-auth.js)
|
|
21
23
|
- `isUrlAuthWebSocketPath(pathname)`: true when a WebSocket upgrade may authenticate with `yuri_url_token` (exact terminal/dictation/event/realtime-proxy paths, plus prefix `/api/preview/proxy/` for Preview HMR). Keep in sync with tunnel-host `isTunnelWsPathAllowed`.
|
|
22
24
|
- `createUiAuth({ password, cookieName, sessionTtlMs, readSettingsFromDiskMigrated })`: creates UI auth controller with methods:
|
|
25
|
+
- `authorizeRelayRequest(req)`
|
|
23
26
|
- `enabled`
|
|
24
27
|
- `requireAuth(req, res, next)`
|
|
25
28
|
- `handleSessionStatus(req, res)`
|