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.
This commit is contained in:
2026-09-05 21:36:19 +01:00
commit 58688365f0
13 changed files with 1283 additions and 0 deletions
+174
View File
@@ -0,0 +1,174 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router';
import { useClient } from 'hooks/useClient';
import { Input } from '@/components/ui/input';
import { ExternalLink, FileText, StickyNote, Image as ImageIcon } from 'lucide-react';
import { ALL } from './ListsPanel';
/**
* Your saved bookmarks, as the calling Officer user.
*
* Every request goes through `/api/karakeep/api/*` — the authenticated door, which finds the caller's
* mapped account and puts THEIR key on the request. This panel holds no credential and could not send
* one if it wanted to, which is the property the whole plugin exists for.
*
* ── Search is Karakeep's, not ours ──
*
* `/bookmarks/search?q=` searches titles, notes, tags and the archived text. Re-implementing it here
* would mean pulling every bookmark to the browser to filter it, and would still only see the fields we
* happened to fetch.
*/
/**
* A bookmark is a discriminated union on `content.type` — a link, a note, or an asset.
*
* Officer reads the minimum: enough to draw a row and open the thing. Everything else stays Karakeep's,
* which is what keeps an upstream field addition from being a change here.
*/
type Bookmark = {
id: string;
title?: string | null;
createdAt?: string;
tags?: { id: string; name: string }[];
content?:
| { type: 'link'; url: string; title?: string | null; description?: string | null }
| { type: 'text'; text?: string }
| { type: 'asset'; assetType?: string; fileName?: string | null };
};
/** Paginated, and the cursor is ignored for now — the first page is a screenful. */
type Page = { bookmarks?: Bookmark[]; nextCursor?: string | null };
export const BookmarksPanel = () => {
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 [params] = useSearchParams();
const list = params.get('list') ?? ALL;
const [query, setQuery] = useState('');
const [rows, setRows] = useState<Bookmark[] | null>(null);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async (listId: string, search: string) => {
/*
Three different endpoints, because Karakeep models them as three questions rather than one with
filters: everything, one list's contents, and a search. Search wins when there is one — narrowing a
search to a list is a fourth thing the API does not offer, and pretending otherwise here would mean
filtering results in the browser and calling it the same feature.
*/
const path =
search.trim() ? `/karakeep/api/v1/bookmarks/search?q=${encodeURIComponent(search.trim())}`
: listId !== ALL ? `/karakeep/api/v1/lists/${encodeURIComponent(listId)}/bookmarks`
: '/karakeep/api/v1/bookmarks';
try {
const body = await clientRef.current.get<Page>(path);
setRows(body.bookmarks ?? []);
setError(null);
} catch (failure) {
setError(failure instanceof Error ? failure.message : 'Could not read your bookmarks.');
setRows(null);
}
}, []);
// Debounced, because this types straight into a request: long enough that a five-letter word is one
// query instead of five, short enough that the list moves while you type.
useEffect(() => {
const timer = setTimeout(() => void load(list, query), 250);
return () => clearTimeout(timer);
}, [list, query, load]);
return (
<div className="flex size-full flex-col">
<header className="border-b p-2">
<Input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="Search titles, notes, tags and saved text…"
className="h-8 text-xs"
/>
{query.trim() && list !== ALL && (
// Said rather than silently ignored: the result set is not what the sidebar implies.
<p className="mt-1 text-[10px] text-muted-foreground">Searching everything, not just this list.</p>
)}
</header>
{error && (
<p className="px-3 py-2 text-xs text-destructive">
{error}
{error.includes('no Karakeep account') && ' — the owner maps accounts in Settings.'}
</p>
)}
{rows === null && !error ? (
<Centred>Loading…</Centred>
) : rows && rows.length === 0 ? (
<Centred>{query.trim() ? `Nothing matches “${query.trim()}”.` : 'Nothing saved here yet.'}</Centred>
) : (
<ul className="flex-1 divide-y overflow-auto">
{rows?.map((bookmark) => (
<li key={bookmark.id} className="group px-3 py-2 hover:bg-muted/40">
<Row bookmark={bookmark} />
</li>
))}
</ul>
)}
</div>
);
};
const Row = ({ bookmark }: { bookmark: Bookmark }) => {
const content = bookmark.content;
const url = content?.type === 'link' ? content.url : null;
const title =
bookmark.title ||
(content?.type === 'link' ? content.title : null) ||
(content?.type === 'asset' ? content.fileName : null) ||
(content?.type === 'text' ? content.text?.slice(0, 80) : null) ||
url ||
'Untitled';
const Icon = content?.type === 'text' ? StickyNote : content?.type === 'asset' ? ImageIcon : FileText;
return (
<div className="flex items-start gap-2">
<Icon className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
{url ? (
<a
href={url}
target="_blank"
rel="noreferrer noopener"
className="flex items-center gap-1 text-xs hover:underline"
>
<span className="min-w-0 truncate">{title}</span>
<ExternalLink className="size-3 shrink-0 opacity-0 transition-opacity group-hover:opacity-60" />
</a>
) : (
// A note or an asset has nowhere to go, so it is not dressed as a link.
<span className="block truncate text-xs">{title}</span>
)}
{url && <p className="truncate text-[11px] text-muted-foreground">{url}</p>}
{bookmark.tags && bookmark.tags.length > 0 && (
<p className="mt-0.5 flex flex-wrap items-center gap-1 text-[10px] text-muted-foreground">
{bookmark.tags.map((tag) => (
<span key={tag.id} className="rounded bg-muted px-1 py-px">
{tag.name}
</span>
))}
</p>
)}
</div>
</div>
);
};
const Centred = ({ children }: { children: React.ReactNode }) => (
<div className="flex flex-1 items-center justify-center p-6 text-center text-xs text-muted-foreground">
{children}
</div>
);
+111
View File
@@ -0,0 +1,111 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router';
import { useClient } from 'hooks/useClient';
import { Folder, Settings2, Layers } from 'lucide-react';
import { SettingsForm } from './SettingsForm';
/**
* The lists, and a way back to the settings.
*
* Selection is `?list=<id>` in the URL rather than a channel, so which list you are looking
* at survives a reload and can be linked to — `docs/navigation-audit.md`. The links panel reads the same
* parameter rather than being handed the id.
*
* The settings live behind the gear rather than on a screen of their own. They were a screen of their
* own for an afternoon and it was the wrong shape: nothing else was built, so opening the plugin put you
* on a configuration form with no way forward, which reads as broken rather than unfinished.
*/
/** Karakeep list ids are strings, and lists nest through `parentId`. */
type List = { id: string; name: string; icon?: string | null; parentId?: string | null };
/** `?list=` for "everything", which is a real choice and not the absence of one. */
export const ALL = 'all';
export const ListsPanel = () => {
const client = useClient();
const clientRef = useRef(client);
clientRef.current = client;
const [rows, setRows] = useState<List[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [showSettings, setShowSettings] = useState(false);
const [params, setParams] = useSearchParams();
const selected = params.get('list') ?? ALL;
const load = useCallback(async () => {
try {
const body = await clientRef.current.get<{ lists: List[] }>('/karakeep/api/v1/lists');
setRows(body.lists ?? []);
setError(null);
} catch (failure) {
// The message matters here. "No account is mapped to you" is something the owner can fix and is
// the state every user starts in, so it must not read as an outage.
setError(failure instanceof Error ? failure.message : 'Could not read your lists.');
setRows(null);
setShowSettings(true);
}
}, []);
useEffect(() => {
void load();
}, [load]);
const select = (id: string) =>
setParams(
(p) => {
p.set('list', id);
return p;
},
{ replace: true },
);
return (
<div className="flex size-full flex-col">
<header className="flex items-center justify-between border-b px-2 py-1.5">
<span className="text-xs font-medium">Lists</span>
<button
type="button"
onClick={() => setShowSettings((was) => !was)}
className="p-1 text-muted-foreground hover:text-foreground"
aria-label="Settings"
>
<Settings2 className="size-3.5" />
</button>
</header>
{error && <p className="px-3 py-2 text-[11px] text-destructive">{error}</p>}
<ul className="flex-1 overflow-auto">
<li>
<button
type="button"
onClick={() => select(ALL)}
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs hover:bg-muted/50 ${
selected === ALL ? 'bg-muted' : ''
}`}
>
<Layers className="size-3.5 shrink-0 text-muted-foreground" />
Everything
</button>
</li>
{rows?.map((row) => (
<li key={row.id}>
<button
type="button"
onClick={() => select(row.id)}
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs hover:bg-muted/50 ${
selected === row.id ? 'bg-muted' : ''
}`}
>
<Folder className="size-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate">{row.name}</span>
</button>
</li>
))}
</ul>
{showSettings && <SettingsForm />}
</div>
);
};
+131
View File
@@ -0,0 +1,131 @@
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>
);
};
+13
View File
@@ -0,0 +1,13 @@
import type { LayoutNode } from 'officerdev';
// The bookmarks are the screen; the lists are how you narrow them. 24/76 because a list name is short
// and a saved page needs room for its title, its address and its tags without wrapping.
export const defaultLayout: LayoutNode = {
type: 'group',
id: 'karakeep-root',
direction: 'horizontal',
children: [
{ node: { type: 'panel', id: 'karakeep-lists', appType: 'karakeep-lists' }, size: 24 },
{ node: { type: 'panel', id: 'karakeep-bookmarks', appType: 'karakeep-bookmarks' }, size: 76 },
],
};
+15
View File
@@ -0,0 +1,15 @@
import type { AppRegistryMeta } from 'officerdev';
import { Bookmark, ListTree } from 'lucide-react';
import { ListsPanel } from './ListsPanel';
import { BookmarksPanel } from './BookmarksPanel';
// Two panels: what you have saved, and how it is filed. The settings are a disclosure inside the lists
// panel rather than a screen of their own — a plugin whose only screen is its own configuration is one
// you cannot leave, which is how the first version of the sister plugin shipped and what it taught.
//
// `availableOnPanel: false` keeps them out of the generic picker: they belong to the /karakeep screen
// rather than being things to drop into an arbitrary dashboard.
export const appRegistryMetas: AppRegistryMeta[] = [
{ key: 'karakeep-lists', name: 'Lists', icon: ListTree, component: ListsPanel, availableOnPanel: false },
{ key: 'karakeep-bookmarks', name: 'Bookmarks', icon: Bookmark, component: BookmarksPanel, availableOnPanel: false },
];