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
+181
View File
@@ -0,0 +1,181 @@
import { createRouter } from '@@/create-router';
import { createSidecarProxy } from '@@/sidecar/create-proxy';
import { getKarakeepConfig, setKarakeepConfig, getAccount } from '../db/queries';
import { stripHopByHop, stripResponseHeaders } from '../sidecar/upstream';
/**
* Mounted at `/api/karakeep`.
*
* Three things live here and they are worth telling apart, because two of them look the same from the
* outside and are not:
*
* `/lw/*` the extension's door. Unauthenticated, forwarded verbatim, credential is the caller's.
* `/api/*` OUR door. Officer session required; we swap in the caller's Karakeep token.
* `/config` where the instance is. Owner only, by the manifest.
*/
export const router = createRouter();
/*
The extension's door.
`proxiedSubPath` is the load-bearing argument. `registerProxiedPrefix` tells the body parser to leave a
prefix alone — right for forwarded traffic, and required for uploads — but this plugin serves its own
routes under the same prefix, and those need their bodies parsed. Claiming the whole of
`/api/karakeep` would make every field on `/config` read as missing, which is the failure caldav hit
on the day it was extracted. So the proxy claims `/lw` and nothing else.
*/
const proxy = createSidecarProxy({
name: 'karakeep',
prefix: '/api/karakeep',
proxiedSubPath: '/kk',
permissionKey: 'karakeep',
// Archiving a page can take a while, and the extension waits on it.
timeoutSeconds: 120,
});
/*
── The factory's ROUTER is not used, and that is the whole reason this is written out ──
`createSidecarProxy` is for AUTHENTICATED proxying: its forwarder does `ctx.get('user').id`, because
every other sidecar behind it is reached by somebody with an Officer session. This door is declared in
`unauthenticatedPaths`, so there is no user, and mounting the factory's router here answered every
request with `TypeError: undefined is not an object` as a 500. Measured on alpha, not reasoned about.
Vault hand-writes its public router for exactly this reason and I should have followed it rather than
reaching for the shared thing because it was shared.
What the factory IS still used for, and why it is still constructed: `getHttpUrl()`, so the port the
sidecar announced is discovered in one place; and `registerProxiedPrefix`, which runs at construction
and tells the body parser to leave `/api/karakeep/kk` alone. Both matter, and neither is the router.
*/
router.all('/kk/*', async (ctx) => {
const base = proxy.getHttpUrl();
if (!base) return ctx.text('the Karakeep sidecar is not running', 503);
const url = new URL(ctx.req.url);
const subpath = url.pathname.slice('/api/karakeep/kk'.length) || '/';
/*
Authorization is FORWARDED, not replaced — the opposite of the door below.
The client's own credential is the only one in play here, and Karakeep is the only thing entitled
to judge it. Officer adds no security to a stock extension because it has nothing to check: this is
the same exposure through one address instead of two, which is what lets Karakeep stop listening
on its own.
*/
const hasBody = ctx.req.method !== 'GET' && ctx.req.method !== 'HEAD';
const init: RequestInit & { duplex?: 'half' } = {
method: ctx.req.method,
headers: stripHopByHop(ctx.req.raw.headers),
redirect: 'manual',
...(hasBody ? { body: ctx.req.raw.body, duplex: 'half' as const } : {}),
};
try {
const upstream = await fetch(`${base}${subpath}${url.search}`, init);
return new Response(upstream.body, { status: upstream.status, headers: stripResponseHeaders(upstream.headers) });
} catch {
return ctx.text('Karakeep unreachable', 502);
}
});
// ── where the instance is ────────────────────────────────────────────────────────────────────────
router.get('/config', async (ctx) => {
const config = await getKarakeepConfig();
// The admin token is never returned, only whether one is set — see `getAdminToken` for why it is read
// through a separate function rather than being a field on this.
return ctx.json({ url: config.url, enabled: config.enabled, updatedAt: config.updatedAt });
});
router.put('/config', async (ctx) => {
const body = (await ctx.req.json().catch(() => null)) as {
url?: string | null;
enabled?: boolean;
adminApiKey?: string | null;
} | null;
if (!body) return ctx.json({ error: 'expected a JSON object' }, 400);
if (body.url !== undefined && body.url !== null && !/^https?:\/\//i.test(body.url.trim())) {
return ctx.json({ error: 'the address must start with http:// or https://' }, 400);
}
const config = await setKarakeepConfig(body);
return ctx.json({ url: config.url, enabled: config.enabled, updatedAt: config.updatedAt });
});
/**
* Can we actually reach it, and does the credential work?
*
* Separate from `/config` because "the owner typed an address" and "there is a Karakeep there" are
* different facts, and a settings panel that conflates them makes a typo look like an outage. Asked of
* the sidecar rather than from here: it is the thing that will have to reach it, and its answer is the
* one that matters.
*/
router.get('/config/health', async (ctx) => {
const base = proxy.getHttpUrl();
if (!base) return ctx.json({ ok: false, reason: 'sidecar not running' }, 503);
try {
const probe = await fetch(`${base}/_health`, { signal: AbortSignal.timeout(8000) });
return ctx.json(await probe.json(), probe.status as 200);
} catch {
return ctx.json({ ok: false, reason: 'sidecar unreachable' }, 502);
}
});
// ── our own door ─────────────────────────────────────────────────────────────────────────────────
/**
* Karakeep's API, as the calling Officer user.
*
* ── Why this exists next to `/lw`, which already forwards ──
*
* `/lw` forwards the caller's own credential, which is right for the extension and impossible for us: a
* browser holding an Officer session has no Karakeep token and must never be given one. So this route
* looks up who is calling, finds their mapped account, and puts THEIR token on the request. The device
* holds an Officer session and nothing else, which is the same property the Vault plugin exists to give.
*
* The permission model stays Karakeep's. Officer decides whose token goes on; Karakeep decides what
* that token may see. Re-implementing the second half here would be a second answer able to disagree
* with the first.
*/
router.all('/api/*', async (ctx) => {
const userId = ctx.get('user')?.id;
if (!userId) return ctx.json({ error: 'unauthenticated' }, 401);
const base = proxy.getHttpUrl();
if (!base) return ctx.json({ error: 'the Karakeep sidecar is not running' }, 503);
const account = await getAccount(userId);
if (!account) {
// Named rather than a bare 403: "you have no Karakeep account" is something the owner can fix, and
// a message that says so is the difference between a support question and a self-service one.
return ctx.json({ error: 'no Karakeep account is mapped to you — the owner can create one in Settings' }, 403);
}
if (!account.apiKey) {
return ctx.json({ error: 'your Karakeep account has no API key yet' }, 403);
}
const url = new URL(ctx.req.url);
// `/api/karakeep/api/v1/links` is Karakeep's `/api/v1/links`.
const subpath = url.pathname.slice('/api/karakeep'.length) || '/';
const headers = new Headers(ctx.req.raw.headers);
headers.delete('cookie'); // an Officer session cookie means nothing upstream and should not travel
headers.set('Authorization', `Bearer ${account.apiKey}`);
const hasBody = ctx.req.method !== 'GET' && ctx.req.method !== 'HEAD';
const init: RequestInit & { duplex?: 'half' } = {
method: ctx.req.method,
headers,
redirect: 'manual',
...(hasBody ? { body: ctx.req.raw.body, duplex: 'half' as const } : {}),
};
try {
const upstream = await fetch(`${base}${subpath}${url.search}`, init);
return new Response(upstream.body, { status: upstream.status, headers: stripResponseHeaders(upstream.headers) });
} catch {
return ctx.json({ error: 'Karakeep unreachable' }, 502);
}
});