Files
karakeep/web/SettingsForm.tsx
T
pastilhas 58688365f0 the plugin, written against karakeep instead of linkwarden
Same model as Vault: one instance per install, a sidecar that is the only thing
knowing where it is, two doors - one authenticated for our own UI that injects
the caller's credential, one unauthenticated for a client that carries its own -
and an account per Officer user.

── Why this upstream ──

Linkwarden authenticates its extension through NextAuth: host-scoped cookies,
CSRF checked against the host, absolute URLs baked from NEXTAUTH_URL. Proxying
that means telling the upstream the address the CLIENT uses, which is not the
address the SIDECAR dials, and getting it wrong bounces the extension out of the
proxy mid-login. It cost a NEXTAUTH_URL change, a container recreate, a lost csrf
cookie, and it retired the upstream's own web login as the price of going through
Officer.

Karakeep's extension holds an API key and sends it as a header. Nothing is
host-pinned, so none of that exists. And provisioning needs nothing pasted:
users.create and apiKeys.exchange are both public procedures, so Officer creates
the account, chooses the password, and mints the key itself - where Linkwarden
could only take a key a person made by hand.

── Carried over deliberately ──

Two fixes from the Linkwarden build, both upstream-agnostic and both found by
running it rather than reading it. `content-encoding` stripped from proxied
responses, because fetch decompresses the body while the headers still claim
gzip - which hides until the first response big enough to compress. And
Set-Cookie copied with append rather than set, because it is the one header that
legitimately repeats. Karakeep should never need the second one; it is here
because a proxy correct only for the traffic its author tested is a trap for
whoever changes the upstream later.

Also carried: the unauthenticated door is hand-written rather than the shared
createSidecarProxy router, which does ctx.get("user").id and 500s where there is
no session.

Written against source, not yet run. The response shapes in the panels come from
packages/api/routes/ and are the first thing to check against a live instance.
No provisioning yet.
2026-09-05 21:36:19 +01:00

132 lines
4.8 KiB
TypeScript

import { useCallback, useEffect, useRef, useState } from 'react';
import { useClient } from 'hooks/useClient';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
/**
* Where this install's Karakeep is, and whether it answers.
*
* Was the whole plugin for an afternoon, which was the mistake: a settings screen with nothing behind it
* is a screen you cannot leave. It is a disclosure inside the lists panel now — reachable when
* something is wrong, and out of the way when it is not.
*
* ── Two addresses, and they are not the same one ──
*
* The field below is the address the SIDECAR dials, which on a machine running both Officer and
* Karakeep is loopback. It is NOT the address a browser or the extension is given — that is
* `NEXTAUTH_URL` inside Karakeep's own container, and it has to be reachable from wherever the client
* is. Measured on this install: the name Karakeep advertises resolves to 127.0.1.1 on the host it runs
* on, where nothing is bound, so a sidecar told to use it dials a name that answers from everywhere
* except the one place that matters.
*/
type Config = { url: string | null; enabled: boolean; updatedAt: string | null };
type Health = { ok: boolean; upstream?: number; reason?: string };
export const SettingsForm = () => {
const client = useClient();
// `useClient()` rebuilds its verbs every render, so they must never sit in a dependency list.
const clientRef = useRef(client);
clientRef.current = client;
const [config, setConfig] = useState<Config | null>(null);
const [url, setUrl] = useState('');
const [adminApiKey, setAdminToken] = useState('');
const [health, setHealth] = useState<Health | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
try {
const next = await clientRef.current.get<Config>('/karakeep/config');
setConfig(next);
setUrl(next.url ?? '');
setError(null);
} catch {
setError('Could not read the configuration.');
}
}, []);
useEffect(() => {
void load();
}, [load]);
const check = useCallback(async () => {
setHealth(null);
try {
setHealth(await clientRef.current.get<Health>('/karakeep/config/health'));
} catch {
setHealth({ ok: false, reason: 'the check itself failed' });
}
}, []);
const save = async () => {
setBusy(true);
try {
// The token is sent only when one was typed: leaving a write-only field alone means "unchanged",
// not "clear it".
await clientRef.current.put('/karakeep/config', {
url: url.trim() || null,
...(adminApiKey.trim() ? { adminApiKey: adminApiKey.trim() } : {}),
});
setAdminToken('');
setError(null);
await load();
await check();
} catch (failure) {
setError(failure instanceof Error ? failure.message : 'Could not save that.');
} finally {
setBusy(false);
}
};
return (
<div className="space-y-3 border-t p-3">
{error && <p className="text-xs text-destructive">{error}</p>}
<div className="space-y-1">
<label className="text-[11px] text-muted-foreground">Address the sidecar dials</label>
<Input
value={url}
onChange={(event) => setUrl(event.target.value)}
placeholder="http://127.0.0.1:3000"
className="h-8 text-xs"
/>
</div>
<div className="space-y-1">
<label className="text-[11px] text-muted-foreground">Admin API key</label>
<Input
type="password"
value={adminApiKey}
onChange={(event) => setAdminToken(event.target.value)}
placeholder={config?.url ? 'unchanged' : 'Karakeep → Settings → Access Tokens'}
className="h-8 text-xs"
/>
</div>
<div className="flex items-center gap-2">
<Button size="sm" className="h-7 text-xs" onClick={() => void save()} disabled={busy}>
{busy ? 'Saving…' : 'Save'}
</Button>
<Button size="sm" variant="secondary" className="h-7 text-xs" onClick={() => void check()}>
Test
</Button>
</div>
{health && (
<p className="text-[11px]">
{health.ok ? (
<span className="text-muted-foreground">Answering{health.upstream ? ` (${health.upstream})` : ''}.</span>
) : (
/*
Three distinct reasons on purpose — unconfigured, unreachable, sidecar not running are three
different next actions, and one word for all of them sends somebody to check the wrong thing.
*/
<span className="text-destructive">Not answering — {health.reason ?? 'no reason given'}.</span>
)}
</p>
)}
</div>
);
};