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
+147
View File
@@ -0,0 +1,147 @@
import { eq } from 'drizzle-orm';
import { db } from 'officerdb/db';
import { encryptSecret, decryptSecret } from 'officerdb/crypto';
import { karakeepConfig, karakeepAccounts } from './schema';
// Karakeep store access. Callers deal in PLAINTEXT — encryption to and from at-rest ciphertext happens
// here, so neither the proxy nor the provisioner touches crypto directly. The key purpose is
// `karakeep`, minted on first use by the secret store (docs/secret-store.md).
// ── Instance configuration (server-wide, one row) ──
export type KarakeepConfig = { url: string | null; enabled: boolean; updatedAt: Date | null };
const EMPTY_CONFIG: KarakeepConfig = { url: null, enabled: true, updatedAt: null };
/**
* Where this install's Karakeep is, or `url: null` when the owner has not pointed it anywhere yet.
*
* Never throws and never creates the row. A missing row and an unset URL are the same answer to the only
* question anyone asks here, and an install nobody has configured is an ordinary state rather than an
* error. The admin token is deliberately NOT returned — see `getAdminApiKey`.
*/
export async function getKarakeepConfig(): Promise<KarakeepConfig> {
const [row] = await db.select().from(karakeepConfig).where(eq(karakeepConfig.id, 1));
if (!row) return EMPTY_CONFIG;
return { url: row.url, enabled: row.enabled, updatedAt: row.updatedAt };
}
/** Trailing slash removed on write, so `${url}/api/v1/...` can never double the separator. */
const normaliseUrl = (raw: string): string => raw.trim().replace(/\/+$/, '');
/**
* Point this install at a Karakeep, or change which one.
*
* The URL is stored as given (normalised) and NOT probed. Reachability is a separate question with its
* own route, and a setter that refused an unreachable address would make configuring an instance that is
* temporarily down impossible.
*/
export async function setKarakeepConfig(patch: {
url?: string | null;
enabled?: boolean;
adminApiKey?: string | null;
}): Promise<KarakeepConfig> {
const values = {
id: 1,
...(patch.url !== undefined ? { url: patch.url === null ? null : normaliseUrl(patch.url) } : {}),
...(patch.enabled !== undefined ? { enabled: patch.enabled } : {}),
...(patch.adminApiKey !== undefined
? { adminApiKey: patch.adminApiKey === null ? null : await encryptSecret('karakeep', patch.adminApiKey) }
: {}),
updatedAt: new Date(),
};
await db
.insert(karakeepConfig)
.values(values)
.onConflictDoUpdate({ target: karakeepConfig.id, set: values });
return getKarakeepConfig();
}
/**
* The admin token, decrypted. Read by provisioning and by nothing else.
*
* Separate from `getKarakeepConfig` on purpose: that one is handed to the settings panel and to the
* sidecar, and neither has any business holding a credential that can create accounts. A single function
* that returned everything would make the careful thing the one you have to remember to do.
*/
export async function getAdminApiKey(): Promise<string | null> {
const [row] = await db.select().from(karakeepConfig).where(eq(karakeepConfig.id, 1));
if (!row?.adminApiKey) return null;
return decryptSecret('karakeep', row.adminApiKey);
}
// ── Account mapping (one row per Officer user) ──
export type KarakeepAccount = {
userId: number;
karakeepUserId: string;
email: string;
/** Null when an account exists but no key has been minted for it yet. A real state, not an error. */
apiKey: string | null;
apiKeyId: string | null;
};
/** Who this Officer user is on Karakeep, or null when nobody has mapped them. */
export async function getAccount(userId: number): Promise<KarakeepAccount | null> {
const [row] = await db.select().from(karakeepAccounts).where(eq(karakeepAccounts.userId, userId));
if (!row) return null;
return {
userId: row.userId,
karakeepUserId: row.karakeepUserId,
email: row.email,
apiKey: row.apiKey ? await decryptSecret('karakeep', row.apiKey) : null,
apiKeyId: row.apiKeyId,
};
}
/** Every mapping, for the owner's account screen. Keys are NOT included — only whether one exists. */
export async function listAccounts(): Promise<
{ userId: number; karakeepUserId: string; email: string; hasKey: boolean }[]
> {
const rows = await db.select().from(karakeepAccounts);
return rows.map((row) => ({
userId: row.userId,
karakeepUserId: row.karakeepUserId,
email: row.email,
hasKey: !!row.apiKey,
}));
}
/** Map an Officer user onto a Karakeep account, or replace the mapping. Upsert on `userId`. */
export async function setAccount(account: {
userId: number;
karakeepUserId: string;
email: string;
apiKey?: string | null;
apiKeyId?: string | null;
}): Promise<void> {
const values = {
userId: account.userId,
karakeepUserId: account.karakeepUserId,
email: account.email,
...(account.apiKey !== undefined
? { apiKey: account.apiKey === null ? null : await encryptSecret('karakeep', account.apiKey) }
: {}),
...(account.apiKeyId !== undefined ? { apiKeyId: account.apiKeyId } : {}),
updatedAt: new Date(),
};
await db.insert(karakeepAccounts).values(values).onConflictDoUpdate({ target: karakeepAccounts.userId, set: values });
}
/**
* Forget the mapping. Does NOT delete the Karakeep account.
*
* Deliberate: Officer created it but does not own what is in it, and a person removed from an Officer
* install should not silently lose a library of saved reading. Deleting it there is a separate act, done
* by somebody who means it.
*/
export async function forgetAccount(userId: number): Promise<boolean> {
const rows = await db
.delete(karakeepAccounts)
.where(eq(karakeepAccounts.userId, userId))
.returning({ userId: karakeepAccounts.userId });
return rows.length > 0;
}
+107
View File
@@ -0,0 +1,107 @@
import { pgTable, integer, text, timestamp, boolean, check, index } from 'drizzle-orm/pg-core';
import { sql } from 'drizzle-orm';
import { users } from 'officerdb/auth/schema';
// Officer's server-side state for a self-hosted Karakeep. Officer stores no bookmarks: Karakeep owns
// those. What lives here is WHERE the instance is, and WHO on this Officer is who on that Karakeep.
// Every secret column is AES-256-GCM encrypted at rest (officerdb/crypto).
/**
* Where this install's Karakeep lives. ONE ROW, ever — `id` is pinned to 1 by a CHECK.
*
* A table rather than an env var, for the reasons Vault's schema sets out: a plugin cannot ask the owner
* to edit a file and restart a process, `.env` is auto-loaded into every pm2 process so a value one
* sidecar needs is readable from every other one, and a variable read at module load cannot change
* without a restart. Installing the plugin and pointing it at a server has to be enough.
*/
export const karakeepConfig = pgTable(
'karakeep_config',
{
/** Always 1. A single-row table wants to say so structurally, or a second row arrives eventually. */
id: integer('id').primaryKey().default(1),
/**
* Base URL, no trailing slash (normalised on write). Null before the owner has pointed it anywhere.
*
* ── The address the SIDECAR dials, which is not the one clients are told ──
*
* They come apart whenever Officer and the upstream share a host, and on this install they do. A
* browser elsewhere resolves the machine's name over the tailnet; ON that machine the same name
* resolves to 127.0.1.1, where nothing is bound. Measured during the Linkwarden build: the advertised
* name answered from every host except the one the sidecar runs on.
*
* So this holds the loopback address. What a client is told is a separate question, and with Karakeep
* a much smaller one — its API key is host-agnostic, so there is no third value to keep in step the
* way `NEXTAUTH_URL` had to be.
*/
url: text('url'),
/**
* An admin API key, used ONLY to provision accounts — `plugins/USER_PROVISIONING.md`.
*
* Separate from any user's key and never injected on a user's request: this one can list and delete
* accounts, so it is reachable from exactly one place (`api/accounts.ts`, owner-only) and is not what
* the proxy holds.
*/
adminApiKey: text('admin_api_key'), // encrypted
/**
* Whether to serve at all. Distinct from `url` being set: the owner may want to stop exposing an
* instance without forgetting where it is.
*/
enabled: boolean('enabled').notNull().default(true),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(table) => [check('ck_karakeep_config_singleton', sql`${table.id} = 1`)],
);
/**
* Who an Officer account is on that Karakeep.
*
* ── Why a mapping and not one shared login ──
*
* Karakeep has its own users, lists and sharing. One account shared between everyone would put every
* member's reading in one pile with no way to unpick it, and would make "revoke this person" mean
* "change the password for everybody". A row per user is what makes a member's bookmarks theirs, and
* removing them a delete rather than a negotiation.
*
* ── The key is the whole point ──
*
* With it, a proxied request carries the mapped user's own credential and Karakeep decides what they may
* see. Without it the platform would have to be the thing that decides, which is a permission model
* re-implemented on top of one that already exists and is already right.
*
* Unlike the Linkwarden attempt, nothing here has to be pasted by hand: `apiKeys.exchange` is a public
* procedure that turns a username and password into a key, so Officer creates the account, chooses the
* password, and mints the key itself.
*/
export const karakeepAccounts = pgTable(
'karakeep_accounts',
{
userId: integer('user_id')
.primaryKey()
.references(() => users.id, { onDelete: 'cascade' }),
/** The id Karakeep knows them by. Kept so a rename on either side cannot break the mapping. */
karakeepUserId: text('karakeep_user_id').notNull(),
/** What they log in as there — Karakeep identifies users by email. */
email: text('email').notNull(),
/**
* That account's own API key.
*
* Null is a real state and not an error: an account can exist before a key has been minted for it,
* and the panel says so rather than looking broken.
*/
apiKey: text('api_key'), // encrypted
/** Karakeep's own id for the key, so revoking it later does not mean guessing which one. */
apiKeyId: text('api_key_id'),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
/*
Ordinary, NOT unique.
Two Officer accounts pointing at one Karakeep account is a mistake, but it is the owner's to make
and un-make. A unique index turns it into a failed insert with no explanation at the moment of
provisioning; `api/accounts.ts` checks and refuses with a sentence instead.
*/
index('karakeep_accounts_by_karakeep_user').on(table.karakeepUserId),
],
);