From 250e55b4c704619be90e1c5e6c68dcae7589467c Mon Sep 17 00:00:00 2001 From: Adib Hanna Date: Fri, 20 Nov 2026 07:04:28 -0600 Subject: [PATCH 1/8] Feat(remote): a server behind Cloudflare Access is reachable with its headers (#1091) A self-hosted server put behind an access gateway such as Cloudflare Access was unreachable from the desktop app. The gateway turns away every request that lacks its credentials (a service token is two headers, CF-Access-Client-Id and CF-Access-Client-Secret) before the server sees it, and the app could only send its own auth token. The Auth Token step of Connect to Remote Vault now has Add extra headers, and a saved remote takes the same box under Edit: one `Name: value` per line, Enter for the next line, Cmd/Ctrl+Enter to connect. The step reads exactly as before until the link is chosen, so a server without a gateway costs nothing more. The headers go to the OS secret store beside the token, under their own entry, never to config.toml; a renderer only ever gets their names back. Every request carries them, uploads and asset bytes included, and so does the /api/watch handshake: without them there the socket never opens and live sync quietly drops to the 30 second refresh. One parser in shared-domain decides what a header list is, for the dialog, for main (which re-reads whatever a renderer sends) and for the bundled zn and MCP server, which cannot read the secret store and take the same lines from ZENNOTES_REMOTE_HEADERS. It refuses Authorization (the token has its own field and the server reads it as that token) and the names the connection sets itself, and a list that does not parse is dropped whole rather than sent in part. A gateway that still refuses now says so. An HTML 403 (the ZenNotes server answers in plain text) and a redirect to a sign-in page on another host both name the gateway, instead of quoting its page or failing on a JSON parse. What it deliberately does not do: the phones share this UI but their remote client does not send headers yet, so a capability flag keeps the box hidden there, and the standalone Go zn reads nothing here yet. Headers never go into credentials.toml, because the Go zn owns that file and rewrites it with only its [tokens] table. --- apps/desktop/src/cli/help.ts | 1 + apps/desktop/src/cli/remote/client.ts | 25 ++- apps/desktop/src/main/index.ts | 68 ++++++- apps/desktop/src/main/remote/connection.ts | 49 ++++- .../src/main/remote/gateway-headers.test.ts | 173 ++++++++++++++++++ apps/desktop/src/main/remote/server-client.ts | 43 +++-- apps/desktop/src/main/secret-store.ts | 108 ++++++++--- apps/desktop/src/preload/index.ts | 12 +- .../app-core/src/components/PromptHost.tsx | 27 +++ .../src/components/RemoteAuthModal.tsx | 78 ++++++++ .../src/components/RemoteHeadersField.tsx | 104 +++++++++++ .../RemoteWorkspaceProfileModal.tsx | 76 +++++++- .../app-core/src/components/SettingsModal.tsx | 3 + packages/app-core/src/lib/help.ts | 8 +- .../app-core/src/lib/remote-auth-requests.ts | 51 ++++++ packages/app-core/src/store.ts | 33 +++- packages/bridge-contract/src/bridge.ts | 9 +- packages/bridge-contract/src/ipc.ts | 13 ++ .../shared-domain/src/remote-headers.test.ts | 116 ++++++++++++ packages/shared-domain/src/remote-headers.ts | 150 +++++++++++++++ 20 files changed, 1090 insertions(+), 57 deletions(-) create mode 100644 apps/desktop/src/main/remote/gateway-headers.test.ts create mode 100644 packages/app-core/src/components/RemoteAuthModal.tsx create mode 100644 packages/app-core/src/components/RemoteHeadersField.tsx create mode 100644 packages/app-core/src/lib/remote-auth-requests.ts create mode 100644 packages/shared-domain/src/remote-headers.test.ts create mode 100644 packages/shared-domain/src/remote-headers.ts diff --git a/apps/desktop/src/cli/help.ts b/apps/desktop/src/cli/help.ts index 6cb4a18d..692e0ae1 100644 --- a/apps/desktop/src/cli/help.ts +++ b/apps/desktop/src/cli/help.ts @@ -199,6 +199,7 @@ const ENVIRONMENT: CommandRow[] = [ { name: 'ZENNOTES_VAULT', description: 'Default vault root when --vault is not given' }, { name: 'ZENNOTES_SERVER', description: 'Default server when neither --vault nor --server is given (otherwise zn follows the vault the app has open)' }, { name: 'ZENNOTES_REMOTE_TOKEN', description: 'Auth token for a server; for CI and headless use' }, + { name: 'ZENNOTES_REMOTE_HEADERS', description: 'Extra headers for a server behind an access gateway, one "Name: value" per line' }, { name: 'ZENNOTES_CONFIG_DIR', description: 'Override the ZenNotes config directory' }, { name: 'NO_COLOR', description: 'Disable ANSI color (industry standard)' } ] diff --git a/apps/desktop/src/cli/remote/client.ts b/apps/desktop/src/cli/remote/client.ts index 9c1283e1..fc569fa5 100644 --- a/apps/desktop/src/cli/remote/client.ts +++ b/apps/desktop/src/cli/remote/client.ts @@ -17,6 +17,7 @@ import { remoteFormRequest, remoteJsonRequest } from '../../main/remote/connection.js' +import { remoteHeadersFromEnv, type RemoteHeader } from '@shared/remote-headers' import type { CustomTemplateFile, DeletedVaultAsset, @@ -49,19 +50,33 @@ export interface RemoteAssetMeta { } export class CliRemoteClient { + /** + * `headers` defaults to `ZENNOTES_REMOTE_HEADERS` (#1091): this bundled + * `zn` and MCP server cannot read the app's secret store, where the desktop + * app keeps a remote's extra headers, so a server behind an access gateway + * gets them from the environment. The standalone Go `zn` (ZenNotes/tui) is + * a separate client and does not read this yet. A value that does not parse throws here, before + * any request, with the reason. + */ constructor( readonly baseUrl: string, - readonly authToken: string | null + readonly authToken: string | null, + readonly headers: readonly RemoteHeader[] = remoteHeadersFromEnv(process.env) ) {} private get(path: string): Promise { - return remoteJsonRequest(path, { baseUrl: this.baseUrl, authToken: this.authToken }) + return remoteJsonRequest(path, { + baseUrl: this.baseUrl, + authToken: this.authToken, + headers: this.headers + }) } private post(path: string, body?: unknown): Promise { return remoteJsonRequest(path, { baseUrl: this.baseUrl, authToken: this.authToken, + headers: this.headers, method: 'POST', body: body ?? {} }) @@ -130,7 +145,8 @@ export class CliRemoteClient { readAsset(relPath: string): Promise { return remoteBytesRequest(`/api/assets/raw?path=${encodeURIComponent(relPath)}`, { baseUrl: this.baseUrl, - authToken: this.authToken + authToken: this.authToken, + headers: this.headers }) } @@ -162,7 +178,8 @@ export class CliRemoteClient { form.append('file', new Blob([bytes as Uint8Array]), filename) return remoteFormRequest('/api/assets/upload', form, { baseUrl: this.baseUrl, - authToken: this.authToken + authToken: this.authToken, + headers: this.headers }) } diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index 2f393163..8a41ac65 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -136,6 +136,11 @@ import { writeAgentEditRecord, } from "./agent-edit-files"; import { parseAgentEditRecord } from "@shared/agent-edits"; +import { + formatRemoteHeaders, + parseRemoteHeaders, + type RemoteHeader, +} from "@shared/remote-headers"; import { initAppConfig, getPortableConfigSnapshot, @@ -212,10 +217,13 @@ import { getCloudAccountKeySecret, setCloudAccountKeySecret, deleteCloudAccountKeySecret, + deleteRemoteWorkspaceHeaders, deleteRemoteWorkspaceSecret, getCloudServiceSecret, + getRemoteWorkspaceHeaders, getRemoteWorkspaceSecret, setCloudServiceSecret, + setRemoteWorkspaceHeaders, setRemoteWorkspaceSecret, } from "./secret-store"; import { CloudAuthManager, resolveCloudBaseUrl } from "./cloud-auth"; @@ -2792,11 +2800,13 @@ async function setRemoteWorkspace( persist?: boolean; profileId?: string | null; vaultPath?: string | null; + headers?: readonly RemoteHeader[]; } = {}, ): Promise<{ vault: VaultInfo | null; capabilities: ServerCapabilities }> { const client = new RemoteServerClient({ baseUrl, authToken, + headers: options.headers, onStalePath: () => sendRemoteResync(), }); let capabilities = await client.getCapabilities(); @@ -3316,14 +3326,43 @@ async function listRemoteWorkspaceProfiles(): Promise< vaultPath: profile.vaultPath ?? null, lastConnectedAt: profile.lastConnectedAt ?? null, hasCredential: Boolean(await getRemoteWorkspaceSecret(profile.id)), + headerNames: (await getRemoteWorkspaceHeaders(profile.id)).map( + (header) => header.name, + ), })), ); } +/** + * Headers from a renderer are re-read here: main never trusts the renderer's + * list, and a list that does not parse is refused with the reason instead of + * being sent in part. `undefined` and `null` mean "not given". + */ +function remoteHeadersFromRenderer(value: unknown): RemoteHeader[] | undefined { + if (value === undefined || value === null) return undefined; + if (!Array.isArray(value)) { + throw new Error("Extra headers must be a list of name and value pairs."); + } + const pairs = value.map((entry) => { + const { name, value: headerValue } = (entry ?? {}) as Record< + string, + unknown + >; + if (typeof name !== "string" || typeof headerValue !== "string") { + throw new Error("Extra headers must be a list of name and value pairs."); + } + return { name, value: headerValue }; + }); + const parsed = parseRemoteHeaders(formatRemoteHeaders(pairs)); + if (!parsed.ok) throw new Error(parsed.error); + return parsed.headers; +} + async function saveRemoteWorkspaceProfile( input: RemoteWorkspaceProfileInput & { lastConnectedAt?: number | null }, ): Promise { const normalizedId = input.id?.trim() || randomUUID(); + const nextHeaders = remoteHeadersFromRenderer(input.headers); const nextToken = input.clearAuthToken ? null : typeof input.authToken === "string" && input.authToken.trim() @@ -3392,6 +3431,14 @@ async function saveRemoteWorkspaceProfile( } else if (typeof input.authToken === "string" && input.authToken.trim()) { await setRemoteWorkspaceSecret(normalizedId, input.authToken.trim()); } + if (nextHeaders !== undefined) { + const stored = await setRemoteWorkspaceHeaders(normalizedId, nextHeaders); + if (nextHeaders.length > 0 && !stored) { + throw new Error( + "ZenNotes could not store the extra headers securely, because no OS secret store is available.", + ); + } + } if (nextToken !== undefined) { await followSharedServerToken(input.baseUrl, previousToken, nextToken); } @@ -3414,6 +3461,9 @@ async function saveRemoteWorkspaceProfile( : typeof input.authToken === "string" && input.authToken.trim() ? true : Boolean(await getRemoteWorkspaceSecret(normalized.id)), + headerNames: (await getRemoteWorkspaceHeaders(normalized.id)).map( + (header) => header.name, + ), }; } @@ -3462,6 +3512,7 @@ async function deleteRemoteWorkspaceProfile(id: string): Promise { }; }); await deleteRemoteWorkspaceSecret(id); + await deleteRemoteWorkspaceHeaders(id); if (forgottenServer) { await followSharedServerToken(forgottenServer, deletedSecret, null); } @@ -3479,11 +3530,13 @@ async function connectRemoteWorkspaceProfile( throw new Error("That saved remote workspace no longer exists."); } const authToken = await getRemoteWorkspaceSecret(profile.id); + const headers = await getRemoteWorkspaceHeaders(profile.id); let result: Awaited>; try { result = await setRemoteWorkspace(profile.baseUrl, authToken, { profileId: profile.id, vaultPath: profile.vaultPath, + headers, }); } catch (err) { // A profile with no saved token that the server turns away is missing a @@ -3568,12 +3621,16 @@ async function loadCurrentVaultFromConfig(): Promise { (remoteProfile && (await getRemoteWorkspaceSecret(remoteProfile.id))) ?? cfg.remoteWorkspace.authToken ?? null; + const headers = remoteProfile + ? await getRemoteWorkspaceHeaders(remoteProfile.id) + : []; try { const loadRemote = async () => await setRemoteWorkspace(cfg.remoteWorkspace!.baseUrl, authToken, { persist: false, profileId: remoteProfile?.id ?? cfg.remoteWorkspaceProfileId, vaultPath: remoteProfile?.vaultPath ?? null, + headers, }); const result = win && !win.isDestroyed() @@ -4227,8 +4284,15 @@ function registerIpc(): void { handle(IPC.WORKSPACE_GET_INFO, async () => currentRemoteWorkspaceInfo()); handle( IPC.WORKSPACE_CONNECT_REMOTE, - async (_e, baseUrl: string, authToken?: string | null) => { - return await setRemoteWorkspace(baseUrl, authToken); + async ( + _e, + baseUrl: string, + authToken?: string | null, + headers?: unknown, + ) => { + return await setRemoteWorkspace(baseUrl, authToken, { + headers: remoteHeadersFromRenderer(headers) ?? [], + }); }, ); handle(IPC.WORKSPACE_DISCONNECT_REMOTE, async () => { diff --git a/apps/desktop/src/main/remote/connection.ts b/apps/desktop/src/main/remote/connection.ts index c17cefdf..b1484081 100644 --- a/apps/desktop/src/main/remote/connection.ts +++ b/apps/desktop/src/main/remote/connection.ts @@ -10,11 +10,14 @@ * module instead and stays fetch-only. */ +import { applyRemoteHeaders, type RemoteHeader } from '@shared/remote-headers' import { trustSystemCertificates } from '../system-trust' export interface RemoteRequestOptions { baseUrl: string authToken?: string | null + /** Extra headers for an access gateway in front of the server (#1091). */ + headers?: readonly RemoteHeader[] | null method?: string /** Serialised as JSON; sets Content-Type when present. */ body?: unknown @@ -58,15 +61,56 @@ export function connectionErrorMessage( export function requestErrorMessage( baseUrl: string, path: string, - response: { status: number; statusText: string }, + response: { + status: number + statusText: string + headers?: { get(name: string): string | null } + }, text: string ): string { if (response.status === 401) { return `The ZenNotes server rejected the connection. Check the auth token for ${baseUrl} and try again.` } + // The ZenNotes server answers in plain text. An HTML 403 came from + // something in front of it, most often an access gateway turning away a + // request without its headers (#1091); its page would only be noise here. + if ( + response.status === 403 && + /text\/html/i.test(response.headers?.get('content-type') ?? '') + ) { + return gatewayRefusedMessage(baseUrl) + } return `Remote server request failed (${response.status} ${response.statusText}) for ${path}${text ? `: ${text}` : ''}` } +/** An access gateway in front of the server turned the request away. */ +export function gatewayRefusedMessage(baseUrl: string): string { + return `Something in front of the ZenNotes server at ${baseUrl} refused the request. If it sits behind an access gateway such as Cloudflare Access, check the extra headers for this remote.` +} + +/** + * A gateway such as Cloudflare Access answers a request without its headers by + * redirecting it to a sign-in page on another host. fetch follows that, lands + * on HTML, and the caller would report a JSON parse error, so name the gateway + * instead. A redirect that stays on the server's host (http to https) is fine. + */ +export function gatewayRedirectMessage( + baseUrl: string, + response: { redirected: boolean; url: string } +): string | null { + if (!response.redirected || !response.url) return null + let from: string + let to: string + try { + from = new URL(baseUrl).hostname.toLowerCase() + to = new URL(response.url).hostname.toLowerCase() + } catch { + return null + } + if (from === to) return null + return `The ZenNotes server at ${baseUrl} sent the request to a sign-in page at ${to}. If the server sits behind an access gateway such as Cloudflare Access, add the gateway's headers to this remote.` +} + /** A non-2xx server answer, with the HTTP status attached so callers can * tell a 404 (absent file) from a real failure (#556 absence handling). */ export class RemoteRequestError extends Error { @@ -90,6 +134,7 @@ async function remoteFetch( if (options.authToken && !headers.has('Authorization')) { headers.set('Authorization', `Bearer ${options.authToken}`) } + applyRemoteHeaders(headers, options.headers) trustSystemCertificates() let response: Response try { @@ -101,6 +146,8 @@ async function remoteFetch( } catch (error) { throw new Error(connectionErrorMessage(options.baseUrl, error)) } + const redirected = gatewayRedirectMessage(options.baseUrl, response) + if (redirected) throw new RemoteRequestError(redirected, 403) if (!response.ok) { const text = (await response.text().catch(() => '')).trim() throw new RemoteRequestError( diff --git a/apps/desktop/src/main/remote/gateway-headers.test.ts b/apps/desktop/src/main/remote/gateway-headers.test.ts new file mode 100644 index 00000000..f741d623 --- /dev/null +++ b/apps/desktop/src/main/remote/gateway-headers.test.ts @@ -0,0 +1,173 @@ +import http from 'node:http' +import type { AddressInfo } from 'node:net' +import { WebSocketServer } from 'ws' +import { afterEach, describe, expect, it } from 'vitest' +import { RemoteRequestError, RemoteServerClient } from './server-client' +import { gatewayRedirectMessage, remoteJsonRequest, requestErrorMessage } from './connection' + +// #1091: a server behind an access gateway (Cloudflare Access service tokens) +// is only reachable with two extra headers on every request, the change +// feed's WebSocket handshake included. +const HEADERS = [ + { name: 'CF-Access-Client-Id', value: 'abc123.access' }, + { name: 'CF-Access-Client-Secret', value: 's3cr3t' } +] + +function passesGateway(req: http.IncomingMessage): boolean { + return ( + req.headers['cf-access-client-id'] === 'abc123.access' && + req.headers['cf-access-client-secret'] === 's3cr3t' + ) +} + +const servers: Array<() => Promise> = [] +afterEach(async () => { + while (servers.length) await servers.pop()!() +}) + +/** A ZenNotes stand-in behind a gateway: no headers, an HTML 403. */ +async function startGatedServer(): Promise<{ baseUrl: string; seen: string[] }> { + const seen: string[] = [] + const server = http.createServer((req, res) => { + seen.push(`${req.method} ${req.url} ${passesGateway(req) ? 'pass' : 'blocked'}`) + if (!passesGateway(req)) { + res.writeHead(403, { 'content-type': 'text/html' }) + res.end('Forbidden') + return + } + if (req.url === '/api/capabilities') { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ supportsWatch: true })) + return + } + if (req.url?.startsWith('/api/assets/raw')) { + res.writeHead(200, { 'content-type': 'text/plain' }) + res.end('bytes') + return + } + if (req.url === '/api/assets/upload') { + req.resume() + req.on('end', () => { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ path: 'assets/a.png' })) + }) + return + } + res.writeHead(404) + res.end() + }) + const wss = new WebSocketServer({ noServer: true }) + server.on('upgrade', (req, socket, head) => { + seen.push(`UPGRADE ${req.url} ${passesGateway(req) ? 'pass' : 'blocked'}`) + if (!passesGateway(req)) { + socket.end('HTTP/1.1 403 Forbidden\r\n\r\n') + return + } + wss.handleUpgrade(req, socket, head, (ws) => { + ws.send(JSON.stringify({ kind: 'add', path: 'gated.md', folder: 'inbox' })) + }) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + servers.push(async () => { + for (const client of wss.clients) client.terminate() + await new Promise((resolve) => wss.close(resolve)) + await new Promise((resolve) => server.close(resolve)) + }) + const { port } = server.address() as AddressInfo + return { baseUrl: `http://127.0.0.1:${port}`, seen } +} + +async function waitFor(check: () => boolean, what: string): Promise { + const deadline = Date.now() + 5_000 + while (!check()) { + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`) + await new Promise((resolve) => setTimeout(resolve, 25)) + } +} + +describe('extra headers reach a gated server (#1091)', () => { + it('the app client sends them on JSON, asset, upload and change-feed requests', async () => { + const { baseUrl, seen } = await startGatedServer() + const client = new RemoteServerClient({ baseUrl, authToken: 'tok', headers: HEADERS }) + + await expect(client.getCapabilities()).resolves.toEqual({ supportsWatch: true }) + await expect((await client.fetchAssetResponse('a.png')).text()).resolves.toBe('bytes') + await expect(client.uploadAsset('inbox/n.md', 'a.png', new Uint8Array([1]))).resolves.toEqual({ + path: 'assets/a.png' + }) + + const events: string[] = [] + const stop = client.watchVaultChanges((event) => events.push(event.path)) + try { + await waitFor(() => events.includes('gated.md'), 'the change feed event') + } finally { + stop() + } + expect(seen.every((line) => line.endsWith('pass'))).toBe(true) + expect(seen.some((line) => line.startsWith('UPGRADE /api/watch'))).toBe(true) + }) + + it('without them the gateway refusal reads as a gateway, not a ZenNotes error', async () => { + const { baseUrl } = await startGatedServer() + const client = new RemoteServerClient({ baseUrl, authToken: 'tok' }) + const err = await client.getCapabilities().then( + () => null, + (error: unknown) => error + ) + expect(err).toBeInstanceOf(RemoteRequestError) + expect((err as RemoteRequestError).status).toBe(403) + expect((err as Error).message).toContain('access gateway such as Cloudflare Access') + expect((err as Error).message).not.toContain('') + }) + + it('a header list that does not parse is dropped whole, never sent in part', () => { + const client = new RemoteServerClient({ + baseUrl: 'http://127.0.0.1:1', + headers: [...HEADERS, { name: 'Host', value: 'elsewhere' }] + }) + expect(client.headers).toEqual([]) + }) + + it('the CLI and MCP request helper sends them too', async () => { + const { baseUrl, seen } = await startGatedServer() + await expect( + remoteJsonRequest('/api/capabilities', { baseUrl, headers: HEADERS }) + ).resolves.toEqual({ supportsWatch: true }) + await expect(remoteJsonRequest('/api/capabilities', { baseUrl })).rejects.toThrow( + 'access gateway' + ) + expect(seen).toEqual(['GET /api/capabilities pass', 'GET /api/capabilities blocked']) + }) +}) + +describe('gateway messages', () => { + it('names a redirect to a sign-in page on another host', () => { + const message = gatewayRedirectMessage('https://notes.example.com', { + redirected: true, + url: 'https://team.cloudflareaccess.com/cdn-cgi/access/login/notes.example.com' + }) + expect(message).toContain('team.cloudflareaccess.com') + }) + + it('lets a redirect that stays on the server host through (http to https)', () => { + expect( + gatewayRedirectMessage('http://notes.example.com', { + redirected: true, + url: 'https://notes.example.com/api/vault' + }) + ).toBeNull() + expect( + gatewayRedirectMessage('https://notes.example.com', { redirected: false, url: '' }) + ).toBeNull() + }) + + it('keeps the server’s own plain-text 403', () => { + const message = requestErrorMessage( + 'https://notes.example.com', + '/api/fs/browse', + { status: 403, statusText: 'Forbidden', headers: new Headers({ 'content-type': 'text/plain' }) }, + 'path is outside the allowed browse roots' + ) + expect(message).toContain('path is outside the allowed browse roots') + }) +}) diff --git a/apps/desktop/src/main/remote/server-client.ts b/apps/desktop/src/main/remote/server-client.ts index b6b9d3dd..839d7111 100644 --- a/apps/desktop/src/main/remote/server-client.ts +++ b/apps/desktop/src/main/remote/server-client.ts @@ -24,14 +24,24 @@ import type { CustomTemplateFile, WriteTemplateInput } from '@zennotes/bridge-co import WebSocket from 'ws' import { connectionErrorMessage, + gatewayRedirectMessage, normalizeBaseUrl, requestErrorMessage } from './connection' import { trustSystemCertificates } from '../system-trust' +import { + applyRemoteHeaders, + sanitizeRemoteHeaders, + type RemoteHeader +} from '@shared/remote-headers' export interface RemoteServerClientOptions { baseUrl: string authToken?: string | null + /** Sent with every request and the change feed's handshake (#1091), for an + * access gateway such as Cloudflare Access that refuses anything without + * them. Checked again here; a list that would not parse sends nothing. */ + headers?: readonly RemoteHeader[] | null /** * Called with the vault-relative path when the server answers 404 to a * request about it. The list this app shows is behind the server, so the @@ -74,6 +84,7 @@ export class RemoteRequestError extends Error { export class RemoteServerClient { readonly baseUrl: string readonly authToken: string | null + readonly headers: readonly RemoteHeader[] private readonly onStalePath: ((path: string) => void) | null constructor(options: RemoteServerClientOptions) { @@ -81,6 +92,7 @@ export class RemoteServerClient { trustSystemCertificates() this.baseUrl = normalizeBaseUrl(options.baseUrl) this.authToken = options.authToken?.trim() || null + this.headers = sanitizeRemoteHeaders(options.headers ?? []) this.onStalePath = options.onStalePath ?? null } @@ -451,10 +463,7 @@ export class RemoteServerClient { const blob = bytes instanceof Blob ? bytes : new Blob([bytes as Uint8Array], { type: mimeType }) form.append('file', blob, filename) - const headers = new Headers() - if (this.authToken) { - headers.set('Authorization', `Bearer ${this.authToken}`) - } + const headers = this.requestHeaders() let response: Response try { response = await fetch(`${this.baseUrl}/api/assets/upload`, { @@ -476,10 +485,7 @@ export class RemoteServerClient { } async fetchAssetResponse(assetPath: string): Promise { - const headers = new Headers() - if (this.authToken) { - headers.set('Authorization', `Bearer ${this.authToken}`) - } + const headers = this.requestHeaders() const response = await fetch( `${this.baseUrl}/api/assets/raw?path=${encodeURIComponent(assetPath)}`, { headers } @@ -498,10 +504,10 @@ export class RemoteServerClient { options: { onReconnect?: () => void; stableAfterMs?: number; pollWhileDownMs?: number } = {} ): () => void { const url = new URL('/api/watch', `${this.baseUrl}/`) - const headers: Record = {} - if (this.authToken) { - headers['Authorization'] = `Bearer ${this.authToken}` - } + // The handshake is a plain HTTP request, and a gateway checks it like any + // other: without the extra headers the socket never opens and the app + // quietly falls back to polling. + const headers = Object.fromEntries(this.requestHeaders().entries()) // The subscription must outlive any single socket: a laptop sleep, a // Wi-Fi switch, a server restart, or an idle proxy all kill the @@ -626,11 +632,18 @@ export class RemoteServerClient { } } - private async jsonRequest(path: string, init?: JsonRequestInit): Promise { - const headers = new Headers(init?.headers) + /** Auth plus the extra headers, on top of whatever the request set. */ + private requestHeaders(init?: RequestInit['headers']): Headers { + const headers = new Headers(init) if (this.authToken && !headers.has('Authorization')) { headers.set('Authorization', `Bearer ${this.authToken}`) } + applyRemoteHeaders(headers, this.headers) + return headers + } + + private async jsonRequest(path: string, init?: JsonRequestInit): Promise { + const headers = this.requestHeaders(init?.headers) const hasBody = init?.body !== undefined if (hasBody && !headers.has('Content-Type')) { headers.set('Content-Type', 'application/json') @@ -646,6 +659,8 @@ export class RemoteServerClient { } catch (error) { throw new RemoteConnectionError(connectionErrorMessage(this.baseUrl, error)) } + const redirected = gatewayRedirectMessage(this.baseUrl, response) + if (redirected) throw new RemoteRequestError(redirected, 403) if (!response.ok) { const text = await response.text().catch(() => '') // A 404 for a path this app asked to change means the list is behind diff --git a/apps/desktop/src/main/secret-store.ts b/apps/desktop/src/main/secret-store.ts index a116f861..1923812c 100644 --- a/apps/desktop/src/main/secret-store.ts +++ b/apps/desktop/src/main/secret-store.ts @@ -2,12 +2,15 @@ import { app, safeStorage } from 'electron' import { randomUUID } from 'node:crypto' import { promises as fs } from 'node:fs' import path from 'node:path' +import { sanitizeRemoteHeaders, type RemoteHeader } from '@shared/remote-headers' const KEYTAR_SERVICE = 'ZenNotes Remote Workspace' const KEYTAR_ACCOUNT_PREFIX = 'remote-workspace:' const CLOUD_KEYTAR_SERVICE = 'ZenNotes Cloud' const CLOUD_KEYTAR_ACCOUNT_PREFIX = 'cloud:' const CLOUD_E2EE_ACCOUNT_PREFIX = 'cloud-e2ee:' +const HEADERS_ACCOUNT_PREFIX = 'remote-workspace-headers:' +const HEADERS_FALLBACK_PREFIX = 'headers:' const FALLBACK_FILE = 'remote-workspace-secrets.json' let warnedAboutFallback = false @@ -160,30 +163,33 @@ function decodeSecret(encoded: string): string | null { } } -export async function getRemoteWorkspaceSecret(id: string): Promise { - const normalizedId = id.trim() - if (!normalizedId) return null - +/** + * One remote workspace secret: in keytar under `account`, else in the + * safeStorage fallback file under `fallbackKey`. The auth token and the extra + * headers (#1091) are two such secrets per profile. + */ +async function getWorkspaceSecret(account: string, fallbackKey: string): Promise { const keytar = await loadKeytar() if (keytar) { - return await keytar.getPassword(KEYTAR_SERVICE, accountName(normalizedId)) + return await keytar.getPassword(KEYTAR_SERVICE, account) } const fallback = await loadFallbackSecrets() - const encoded = fallback[normalizedId] + const encoded = fallback[fallbackKey] return encoded ? decodeSecret(encoded) : null } -export async function setRemoteWorkspaceSecret(id: string, secret: string | null): Promise { - const normalizedId = id.trim() - if (!normalizedId) return false - +async function setWorkspaceSecret( + account: string, + fallbackKey: string, + secret: string | null +): Promise { const keytar = await loadKeytar() if (keytar) { if (secret && secret.trim()) { - await keytar.setPassword(KEYTAR_SERVICE, accountName(normalizedId), secret.trim()) + await keytar.setPassword(KEYTAR_SERVICE, account, secret.trim()) } else { - await keytar.deletePassword(KEYTAR_SERVICE, accountName(normalizedId)) + await keytar.deletePassword(KEYTAR_SERVICE, account) } return Boolean(secret && secret.trim()) } @@ -192,33 +198,93 @@ export async function setRemoteWorkspaceSecret(id: string, secret: string | null const encoded = encodeSecret(secret.trim()) if (!encoded) return false await updateFallbackSecrets((fallback) => { - fallback[normalizedId] = encoded + fallback[fallbackKey] = encoded }) } else { await updateFallbackSecrets((fallback) => { - delete fallback[normalizedId] + delete fallback[fallbackKey] }) } return Boolean(secret && secret.trim()) } -export async function deleteRemoteWorkspaceSecret(id: string): Promise { - const normalizedId = id.trim() - if (!normalizedId) return - +async function deleteWorkspaceSecret(account: string, fallbackKey: string): Promise { const keytar = await loadKeytar() if (keytar) { - await keytar.deletePassword(KEYTAR_SERVICE, accountName(normalizedId)) + await keytar.deletePassword(KEYTAR_SERVICE, account) return } const fallback = await loadFallbackSecrets() - if (!(normalizedId in fallback)) return + if (!(fallbackKey in fallback)) return await updateFallbackSecrets((secrets) => { - delete secrets[normalizedId] + delete secrets[fallbackKey] }) } +export async function getRemoteWorkspaceSecret(id: string): Promise { + const normalizedId = id.trim() + if (!normalizedId) return null + return await getWorkspaceSecret(accountName(normalizedId), normalizedId) +} + +export async function setRemoteWorkspaceSecret(id: string, secret: string | null): Promise { + const normalizedId = id.trim() + if (!normalizedId) return false + return await setWorkspaceSecret(accountName(normalizedId), normalizedId, secret) +} + +export async function deleteRemoteWorkspaceSecret(id: string): Promise { + const normalizedId = id.trim() + if (!normalizedId) return + await deleteWorkspaceSecret(accountName(normalizedId), normalizedId) +} + +/** The headers live beside the token, as JSON, so a header value is never in + * config.toml. The fallback key cannot collide with a profile id (a UUID). */ +function headersAccountName(id: string): string { + return `${HEADERS_ACCOUNT_PREFIX}${id}` +} + +function headersFallbackKey(id: string): string { + return `${HEADERS_FALLBACK_PREFIX}${id}` +} + +/** The saved headers for a profile, checked again before anything sends them. */ +export async function getRemoteWorkspaceHeaders(id: string): Promise { + const normalizedId = id.trim() + if (!normalizedId) return [] + const raw = await getWorkspaceSecret(headersAccountName(normalizedId), headersFallbackKey(normalizedId)) + if (!raw) return [] + try { + return sanitizeRemoteHeaders(JSON.parse(raw)) + } catch { + return [] + } +} + +/** Saves the list, or removes the entry for an empty one. Returns whether a + * list is now stored (false when no secure store could take it). */ +export async function setRemoteWorkspaceHeaders( + id: string, + headers: readonly RemoteHeader[] +): Promise { + const normalizedId = id.trim() + if (!normalizedId) return false + const clean = sanitizeRemoteHeaders(headers) + return await setWorkspaceSecret( + headersAccountName(normalizedId), + headersFallbackKey(normalizedId), + clean.length > 0 ? JSON.stringify(clean) : null + ) +} + +export async function deleteRemoteWorkspaceHeaders(id: string): Promise { + const normalizedId = id.trim() + if (!normalizedId) return + await deleteWorkspaceSecret(headersAccountName(normalizedId), headersFallbackKey(normalizedId)) +} + function cloudFallbackKey(baseUrl: string): string { return `${CLOUD_KEYTAR_ACCOUNT_PREFIX}${baseUrl}` } diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts index a766a659..78ab7d64 100644 --- a/apps/desktop/src/preload/index.ts +++ b/apps/desktop/src/preload/index.ts @@ -109,6 +109,7 @@ import type { RaycastExtensionStatus, RemoteWorkspaceInfo, RemoteWorkspaceProfile, + RemoteHeaderInput, RemoteWorkspaceProfileInput, ServerCapabilities, ServerSessionStatus, @@ -145,6 +146,7 @@ const DESKTOP_CAPABILITIES: ZenCapabilities = { supportsFloatingWindows: true, supportsLocalFilesystemPickers: true, supportsRemoteWorkspace: true, + supportsRemoteHeaders: true, supportsCloudSync: true, supportsImport: true, // CLI install is supported on macOS and Linux via /usr/local/bin or @@ -481,9 +483,15 @@ const api: ZenBridge = { await refreshRemoteWorkspaceInfo(), connectRemoteWorkspace: async ( baseUrl: string, - authToken?: string | null + authToken?: string | null, + headers?: RemoteHeaderInput[] | null ): Promise<{ vault: VaultInfo | null; capabilities: ServerCapabilities }> => { - const result = await ipcRenderer.invoke(IPC.WORKSPACE_CONNECT_REMOTE, baseUrl, authToken ?? null) + const result = await ipcRenderer.invoke( + IPC.WORKSPACE_CONNECT_REMOTE, + baseUrl, + authToken ?? null, + headers ?? null + ) await refreshRemoteWorkspaceInfo() return result }, diff --git a/packages/app-core/src/components/PromptHost.tsx b/packages/app-core/src/components/PromptHost.tsx index 043429d7..006dcd9b 100644 --- a/packages/app-core/src/components/PromptHost.tsx +++ b/packages/app-core/src/components/PromptHost.tsx @@ -5,19 +5,46 @@ import { subscribePromptRequests, type PromptRequest } from '../lib/prompt-requests' +import { + getRemoteAuthRequest, + settleRemoteAuthRequest, + subscribeRemoteAuthRequests, + type RemoteAuthRequest +} from '../lib/remote-auth-requests' const PromptModal = lazy(async () => { const module = await import('./PromptModal') return { default: module.PromptModal } }) +const RemoteAuthModal = lazy(async () => { + const module = await import('./RemoteAuthModal') + return { default: module.RemoteAuthModal } +}) + export function PromptHost(): JSX.Element | null { const [request, setRequest] = useState(getPromptRequest) + const [remoteAuth, setRemoteAuth] = useState(getRemoteAuthRequest) useEffect(() => { return subscribePromptRequests(setRequest) }, []) + useEffect(() => { + return subscribeRemoteAuthRequests(setRemoteAuth) + }, []) + + if (remoteAuth) { + return ( + + settleRemoteAuthRequest(remoteAuth, value)} + onCancel={() => settleRemoteAuthRequest(remoteAuth, null)} + /> + + ) + } + if (!request) return null return ( diff --git a/packages/app-core/src/components/RemoteAuthModal.tsx b/packages/app-core/src/components/RemoteAuthModal.tsx new file mode 100644 index 00000000..00de2c93 --- /dev/null +++ b/packages/app-core/src/components/RemoteAuthModal.tsx @@ -0,0 +1,78 @@ +import { useRef, useState } from 'react' +import { isImeComposing } from '../lib/ime' +import type { RemoteAuthAnswer } from '../lib/remote-auth-requests' +import { Modal } from './ui/Modal' +import { Button } from './ui/Button' +import { RemoteHeadersField, readRemoteHeadersDraft } from './RemoteHeadersField' + +/** + * The Auth Token step of Connect to Remote Vault on a host that sends extra + * headers (#1091). It reads as the old one-field step until "Add extra + * headers" is chosen, so a server without a gateway costs nothing more. + */ +export function RemoteAuthModal({ + onSubmit, + onCancel +}: { + onSubmit: (value: RemoteAuthAnswer) => void + onCancel: () => void +}): JSX.Element { + const [authToken, setAuthToken] = useState('') + const [headersText, setHeadersText] = useState('') + const [headersError, setHeadersError] = useState(null) + const tokenRef = useRef(null) + + const submit = (): void => { + const draft = readRemoteHeadersDraft(headersText) + if (!draft.ok) { + setHeadersError(draft.error) + return + } + onSubmit({ authToken: authToken.trim(), headers: draft.headers }) + } + + return ( + + +
+ setAuthToken(e.target.value)} + onKeyDown={(e) => { + if (isImeComposing(e)) return + if (e.key === 'Enter') { + e.preventDefault() + submit() + } + }} + className="w-full rounded-md border border-paper-300 bg-paper-50 px-3 py-2 text-sm text-ink-900 outline-none focus:border-accent" + /> + { + setHeadersText(value) + setHeadersError(null) + }} + onSubmit={submit} + error={headersError} + /> +
+ + + + +
+ ) +} diff --git a/packages/app-core/src/components/RemoteHeadersField.tsx b/packages/app-core/src/components/RemoteHeadersField.tsx new file mode 100644 index 00000000..d845a03b --- /dev/null +++ b/packages/app-core/src/components/RemoteHeadersField.tsx @@ -0,0 +1,104 @@ +import { useEffect, useRef, useState } from 'react' +import type { RemoteHeaderInput } from '@shared/ipc' +import { parseRemoteHeaders } from '@shared/remote-headers' + +/** What a header box says to its form: the list to send, or why it cannot. */ +export type RemoteHeadersDraft = + | { ok: true; headers: RemoteHeaderInput[] } + | { ok: false; error: string } + +export function readRemoteHeadersDraft(text: string): RemoteHeadersDraft { + return parseRemoteHeaders(text) +} + +/** Whether this host sends extra headers at all (#1091). The phones share + * this UI and do not yet, so the field is hidden there. */ +export function supportsRemoteHeaders(): boolean { + return Boolean(window.zen.getCapabilities().supportsRemoteHeaders) +} + +const PLACEHOLDER = 'CF-Access-Client-Id: \nCF-Access-Client-Secret: ' + +/** + * Extra request headers for a server behind an access gateway (#1091). Closed + * until asked for, since most servers need none: a remote that already has + * headers saved opens with their names listed. Enter adds a line, and + * Cmd/Ctrl+Enter submits the form (`onSubmit`). + */ +export function RemoteHeadersField({ + value, + onChange, + onSubmit, + savedNames = [], + error +}: { + value: string + onChange: (value: string) => void + onSubmit?: () => void + savedNames?: readonly string[] + error?: string | null +}): JSX.Element { + const [open, setOpen] = useState(() => value.trim().length > 0 || savedNames.length > 0) + const areaRef = useRef(null) + const focusOnOpen = useRef(false) + + useEffect(() => { + if (open && focusOnOpen.current) { + focusOnOpen.current = false + areaRef.current?.focus() + } + }, [open]) + + if (!open) { + return ( + + ) + } + + return ( +