diff --git a/apps/desktop/package.json b/apps/desktop/package.json index f9d7a676..72822331 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,7 +1,7 @@ { "name": "@zennotes/desktop", "productName": "ZenNotes", - "version": "2.88.0", + "version": "2.89.0", "description": "ZenNotes desktop shell", "private": true, "main": "./out/main/index.js", 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..9670fb63 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) + * reads the same variable under the same rules. 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/custom-themes.test.ts b/apps/desktop/src/main/custom-themes.test.ts index 3613147f..11472054 100644 --- a/apps/desktop/src/main/custom-themes.test.ts +++ b/apps/desktop/src/main/custom-themes.test.ts @@ -158,6 +158,33 @@ describe('custom themes watcher', () => { }, 15_000 ) + + // An edit just before the stop left its 200 ms debounce running, and the + // report it then made landed after teardown: in this file it read the + // config dir once ZENNOTES_CONFIG_DIR was gone and rejected on electron's + // missing `app` (an unhandled error in the 2.89.0 gate run). + it('reports nothing after the watcher stops', async () => { + const dir = await ensureCustomThemesDir() + await mkdir(join(dir, 'busy')) + const sleep = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)) + // chokidar reports an edit once it has settled (about 250 ms here), and the + // report then waits out its 200 ms debounce. A stop somewhere in between + // must cancel it; stepping the stop across that window hits it on any + // machine's timing. + const late: number[] = [] + for (let delay = 150; delay <= 650; delay += 50) { + let reports = 0 + startWatchingCustomThemes(() => reports++) + await sleep(150) + await writeFile(join(dir, 'busy', 'theme.css'), `:root { --n: ${delay}; }\n`) + await sleep(delay) + await stopWatchingCustomThemes() + const atStop = reports + await sleep(450) + if (reports !== atStop) late.push(delay) + } + expect(late).toEqual([]) + }, 30_000) }) describe('resolveThemeAssetPath', () => { diff --git a/apps/desktop/src/main/custom-themes.ts b/apps/desktop/src/main/custom-themes.ts index d4e718d8..aaf4b6b0 100644 --- a/apps/desktop/src/main/custom-themes.ts +++ b/apps/desktop/src/main/custom-themes.ts @@ -378,17 +378,25 @@ export function resolveThemeAssetPath(slug: string, relPath: string): string | n } let watcher: ReturnType | null = null +// The debounce outlives no watcher: a stop or a restart clears it, or an edit +// just before the stop reports a list after it (into a torn-down test, once). +let pendingReport: ReturnType | null = null + +function clearPendingReport(): void { + if (pendingReport) clearTimeout(pendingReport) + pendingReport = null +} /** Watch the themes dir (incl. one level into each theme folder) and call * `onChange` (debounced) with the fresh list. */ export function startWatchingCustomThemes(onChange: (themes: CustomTheme[]) => void): void { const dir = getCustomThemesDir() void watcher?.close() - let timer: ReturnType | null = null + clearPendingReport() const fire = (): void => { - if (timer) clearTimeout(timer) - timer = setTimeout(() => { - timer = null + clearPendingReport() + pendingReport = setTimeout(() => { + pendingReport = null void listCustomThemes().then(onChange) }, 200) } @@ -412,6 +420,7 @@ export function startWatchingCustomThemes(onChange: (themes: CustomTheme[]) => v /** Test/teardown hook: stop the themes watcher. */ export async function stopWatchingCustomThemes(): Promise { + clearPendingReport() await watcher?.close().catch(() => {}) watcher = null } 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/apps/desktop/terminal-release.json b/apps/desktop/terminal-release.json index 722f1571..244f4345 100644 --- a/apps/desktop/terminal-release.json +++ b/apps/desktop/terminal-release.json @@ -3,24 +3,24 @@ "release": { "repository": "ZenNotes/tui", "protocol": 1, - "version": "0.17.3", - "commit": "9f623e7c61bb46ede882c78d33083aae7e99b65e", + "version": "0.18.0", + "commit": "e443a8b0f3c8886dcdcac3aeec6269914968060b", "artifacts": { "darwin-arm64": { - "url": "https://github.com/ZenNotes/tui/releases/download/v0.17.3/zn_0.17.3_darwin_arm64.tar.gz", - "sha256": "3bcc766cf99c6ca31dfe7d2ea3d7edc5dbe5b7ab53304a61e1bee952d1e4b976" + "url": "https://github.com/ZenNotes/tui/releases/download/v0.18.0/zn_0.18.0_darwin_arm64.tar.gz", + "sha256": "3b57795dece8e11d7a500ee2b301621d3187145e7264b7242851fd54b473d2a9" }, "darwin-x64": { - "url": "https://github.com/ZenNotes/tui/releases/download/v0.17.3/zn_0.17.3_darwin_amd64.tar.gz", - "sha256": "093239ad3b4451922b42751a0a8212abd1bfb5a480c2fd3ad7e939dba9fed0e2" + "url": "https://github.com/ZenNotes/tui/releases/download/v0.18.0/zn_0.18.0_darwin_amd64.tar.gz", + "sha256": "da3bed8f9e436f5c3f3fc78007df704ac18be317890d85e19fc76ba2124b1476" }, "linux-arm64": { - "url": "https://github.com/ZenNotes/tui/releases/download/v0.17.3/zn_0.17.3_linux_arm64.tar.gz", - "sha256": "b8c08678f04de6552e75553a78d09abbd54f27ad2220f7f3871d7858dba4d70b" + "url": "https://github.com/ZenNotes/tui/releases/download/v0.18.0/zn_0.18.0_linux_arm64.tar.gz", + "sha256": "cb4816d57f2a8b2f10748173cf232a04aaf0be40ab2c072fbeeb1e9380a1d48e" }, "linux-x64": { - "url": "https://github.com/ZenNotes/tui/releases/download/v0.17.3/zn_0.17.3_linux_amd64.tar.gz", - "sha256": "7ee12a339c2e3cc4b30ac979ea2585c8a3ab1a30cd33f6d9e6f05212622e071f" + "url": "https://github.com/ZenNotes/tui/releases/download/v0.18.0/zn_0.18.0_linux_amd64.tar.gz", + "sha256": "7b738d0d5ce98a817d0017689e6fea464649240f42ba4baaae4a5b70de90e538" } } } diff --git a/apps/quicklook/package.json b/apps/quicklook/package.json index f4186bf2..9de53735 100644 --- a/apps/quicklook/package.json +++ b/apps/quicklook/package.json @@ -1,7 +1,7 @@ { "name": "@zennotes/quicklook", "private": true, - "version": "2.88.0", + "version": "2.89.0", "type": "module", "description": "The macOS Quick Look preview for Markdown files: the page it renders and the Swift extension that serves it", "homepage": "https://zennotes.org", diff --git a/apps/share-viewer/package.json b/apps/share-viewer/package.json index 4b2ec500..be62cdd1 100644 --- a/apps/share-viewer/package.json +++ b/apps/share-viewer/package.json @@ -1,7 +1,7 @@ { "name": "@zennotes/share-viewer", "private": true, - "version": "2.88.0", + "version": "2.89.0", "type": "module", "description": "Read-only renderer for publicly shared ZenNotes, embedded by the zennotes.org website", "homepage": "https://zennotes.org", diff --git a/apps/web/package.json b/apps/web/package.json index 668e5353..110a508d 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,7 +1,7 @@ { "name": "@zennotes/web", "private": true, - "version": "2.88.0", + "version": "2.89.0", "type": "module", "description": "ZenNotes web client for self-hosted and hosted deployments", "homepage": "https://zennotes.org", diff --git a/package-lock.json b/package-lock.json index 1e35005b..986580a0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "zennotes-monorepo", - "version": "2.88.0", + "version": "2.89.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "zennotes-monorepo", - "version": "2.88.0", + "version": "2.89.0", "hasInstallScript": true, "workspaces": [ "apps/*", @@ -23,7 +23,7 @@ }, "apps/desktop": { "name": "@zennotes/desktop", - "version": "2.88.0", + "version": "2.89.0", "license": "MIT", "dependencies": { "@codemirror/autocomplete": "^6.18.3", @@ -927,7 +927,7 @@ }, "apps/quicklook": { "name": "@zennotes/quicklook", - "version": "2.88.0", + "version": "2.89.0", "dependencies": { "@codemirror/autocomplete": "^6.18.3", "@codemirror/commands": "^6.7.1", @@ -1013,7 +1013,7 @@ }, "apps/share-viewer": { "name": "@zennotes/share-viewer", - "version": "2.88.0", + "version": "2.89.0", "dependencies": { "@codemirror/autocomplete": "^6.18.3", "@codemirror/commands": "^6.7.1", @@ -1085,7 +1085,7 @@ }, "apps/web": { "name": "@zennotes/web", - "version": "2.88.0", + "version": "2.89.0", "dependencies": { "@codemirror/autocomplete": "^6.18.3", "@codemirror/commands": "^6.7.1", @@ -2960,15 +2960,15 @@ "license": "MIT" }, "node_modules/@hono/node-server": { - "version": "1.19.17", - "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.17.tgz", - "integrity": "sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ==", + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.6.tgz", + "integrity": "sha512-p/KH9MnfNcsm3sR6x4lNgm5j+QN4Et8srKredl9DZfXiyZ1UQ3aQ2YVpFLbqktYN5JI+DB+VZFKM2PqE5hLKjQ==", "license": "MIT", "engines": { - "node": ">=18.14.1" + "node": ">=20" }, "peerDependencies": { - "hono": "^4" + "hono": "^4 || ^5.0.0-0" } }, "node_modules/@iconify/types": { @@ -9094,9 +9094,9 @@ } }, "node_modules/fast-uri": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz", - "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "funding": [ { "type": "github", @@ -10031,9 +10031,9 @@ } }, "node_modules/hono": { - "version": "4.13.7", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.7.tgz", - "integrity": "sha512-c8/gF9ac8Y78/agExVocyLevgR+JlpNB444Py0FSX8pJoPdYUfUzRcXtYEYGwt6l19qIlVZPN5Mfsw9jFShmQQ==", + "version": "4.13.16", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.16.tgz", + "integrity": "sha512-AOLOEhvrV+iH92xXCnFr/5+3KjPKcI3xP63XJtX5spAnkznPdHijlIsUTpi7/9EhWqrTCekw5c5zh1K+YsVw7A==", "license": "MIT", "engines": { "node": ">=16.9.0" @@ -10277,9 +10277,9 @@ } }, "node_modules/ip-address": { - "version": "10.5.0", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.5.0.tgz", - "integrity": "sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g==", + "version": "10.7.4", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.4.tgz", + "integrity": "sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==", "license": "MIT", "engines": { "node": ">= 12" @@ -16426,7 +16426,7 @@ }, "packages/app-core": { "name": "@zennotes/app-core", - "version": "2.88.0", + "version": "2.89.0", "dependencies": { "@codemirror/autocomplete": "^6.18.3", "@codemirror/commands": "^6.7.1", @@ -16515,14 +16515,14 @@ }, "packages/bridge-contract": { "name": "@zennotes/bridge-contract", - "version": "2.88.0", + "version": "2.89.0", "devDependencies": { "typescript": "^5.7.2" } }, "packages/portable-vault": { "name": "@zennotes/portable-vault", - "version": "2.88.0", + "version": "2.89.0", "dependencies": { "@zennotes/bridge-contract": "*", "@zennotes/shared-domain": "*" @@ -16534,7 +16534,7 @@ }, "packages/shared-domain": { "name": "@zennotes/shared-domain", - "version": "2.88.0", + "version": "2.89.0", "dependencies": { "@scure/bip39": "2.4.0", "@zennotes/bridge-contract": "*", @@ -16548,7 +16548,7 @@ }, "packages/shared-ui": { "name": "@zennotes/shared-ui", - "version": "2.88.0" + "version": "2.89.0" } } } diff --git a/package.json b/package.json index 41d42398..ddc23857 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "zennotes-monorepo", "private": true, - "version": "2.88.0", + "version": "2.89.0", "description": "ZenNotes monorepo for desktop, web, and self-hosted server builds", "packageManager": "npm@10.9.2", "engines": { diff --git a/packages/app-core/package.json b/packages/app-core/package.json index 0cb1d9a3..c410a5c2 100644 --- a/packages/app-core/package.json +++ b/packages/app-core/package.json @@ -1,7 +1,7 @@ { "name": "@zennotes/app-core", "private": true, - "version": "2.88.0", + "version": "2.89.0", "type": "module", "exports": { "./main": "./src/main.tsx", 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 ( +