Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/desktop/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/cli/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)' }
]
Expand Down
25 changes: 21 additions & 4 deletions apps/desktop/src/cli/remote/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
remoteFormRequest,
remoteJsonRequest
} from '../../main/remote/connection.js'
import { remoteHeadersFromEnv, type RemoteHeader } from '@shared/remote-headers'
import type {
CustomTemplateFile,
DeletedVaultAsset,
Expand Down Expand Up @@ -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<T>(path: string): Promise<T> {
return remoteJsonRequest<T>(path, { baseUrl: this.baseUrl, authToken: this.authToken })
return remoteJsonRequest<T>(path, {
baseUrl: this.baseUrl,
authToken: this.authToken,
headers: this.headers
})
}

private post<T>(path: string, body?: unknown): Promise<T> {
return remoteJsonRequest<T>(path, {
baseUrl: this.baseUrl,
authToken: this.authToken,
headers: this.headers,
method: 'POST',
body: body ?? {}
})
Expand Down Expand Up @@ -130,7 +145,8 @@ export class CliRemoteClient {
readAsset(relPath: string): Promise<Uint8Array> {
return remoteBytesRequest(`/api/assets/raw?path=${encodeURIComponent(relPath)}`, {
baseUrl: this.baseUrl,
authToken: this.authToken
authToken: this.authToken,
headers: this.headers
})
}

Expand Down Expand Up @@ -162,7 +178,8 @@ export class CliRemoteClient {
form.append('file', new Blob([bytes as Uint8Array<ArrayBuffer>]), filename)
return remoteFormRequest<ImportedVaultAsset>('/api/assets/upload', form, {
baseUrl: this.baseUrl,
authToken: this.authToken
authToken: this.authToken,
headers: this.headers
})
}

Expand Down
27 changes: 27 additions & 0 deletions apps/desktop/src/main/custom-themes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,33 @@
},
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<void> => 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([])

Check failure on line 186 in apps/desktop/src/main/custom-themes.test.ts

View workflow job for this annotation

GitHub Actions / Build (ubuntu-24.04-arm)

src/main/custom-themes.test.ts > custom themes watcher > reports nothing after the watcher stops

AssertionError: expected [ 450 ] to deeply equal [] - Expected + Received - [] + [ + 450, + ] ❯ src/main/custom-themes.test.ts:186:18
}, 30_000)
})

describe('resolveThemeAssetPath', () => {
Expand Down
17 changes: 13 additions & 4 deletions apps/desktop/src/main/custom-themes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,17 +378,25 @@ export function resolveThemeAssetPath(slug: string, relPath: string): string | n
}

let watcher: ReturnType<typeof chokidar.watch> | 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<typeof setTimeout> | 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<typeof setTimeout> | null = null
clearPendingReport()
const fire = (): void => {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
timer = null
clearPendingReport()
pendingReport = setTimeout(() => {
pendingReport = null
void listCustomThemes().then(onChange)
}, 200)
}
Expand All @@ -412,6 +420,7 @@ export function startWatchingCustomThemes(onChange: (themes: CustomTheme[]) => v

/** Test/teardown hook: stop the themes watcher. */
export async function stopWatchingCustomThemes(): Promise<void> {
clearPendingReport()
await watcher?.close().catch(() => {})
watcher = null
}
Expand Down
68 changes: 66 additions & 2 deletions apps/desktop/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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<RemoteWorkspaceProfile> {
const normalizedId = input.id?.trim() || randomUUID();
const nextHeaders = remoteHeadersFromRenderer(input.headers);
const nextToken = input.clearAuthToken
? null
: typeof input.authToken === "string" && input.authToken.trim()
Expand Down Expand Up @@ -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);
}
Expand All @@ -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,
),
};
}

Expand Down Expand Up @@ -3462,6 +3512,7 @@ async function deleteRemoteWorkspaceProfile(id: string): Promise<void> {
};
});
await deleteRemoteWorkspaceSecret(id);
await deleteRemoteWorkspaceHeaders(id);
if (forgottenServer) {
await followSharedServerToken(forgottenServer, deletedSecret, null);
}
Expand All @@ -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<ReturnType<typeof setRemoteWorkspace>>;
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
Expand Down Expand Up @@ -3568,12 +3621,16 @@ async function loadCurrentVaultFromConfig(): Promise<VaultInfo | null> {
(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()
Expand Down Expand Up @@ -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 () => {
Expand Down
Loading
Loading