Files
linkwarden/db/queries.ts
T
pastilhas 2acd103750 the sidecar, and the two doors
Officer holds the credential; Linkwarden holds the data and decides who may see
it. That split is the whole design and it is why there are two doors that look
alike from outside and are not.

`/lw/*` is the extension's. Unauthenticated, forwarded verbatim, the credential
is the caller's own - the same argument Vault's public router makes, that this is
one address instead of two rather than new exposure, and it is what lets
Linkwarden stop being reachable on its own.

`/api/*` is ours. An Officer session names the caller, we find their mapped
account and put THEIR token on the request. A browser holding an Officer session
never holds a Linkwarden credential, which is the property Vault exists to give,
applied per user. Officer decides whose token goes on; Linkwarden decides what it
may see, because re-implementing that here would be a second answer able to
disagree with the first.

`proxiedSubPath: '/lw'` is load-bearing rather than tidy. Claiming the whole
prefix would tell the body parser to leave /config alone too, and every field on
it would read as missing - the failure caldav hit the day it was extracted.

The sidecar is a plain HTTP proxy with no WebSocket: Vaultwarden pushes over
SignalR and Linkwarden does not, so a socket here would be scaffolding for a
protocol that does not exist. Its onCommand is empty for the same reason - it
forwards bytes, and everything that decides anything happens before a request
reaches it.

Two things measured rather than assumed while writing this. The port announcement
typechecks because SidecarPortAnnouncement was generalised, so a plugin no longer
needs a platform pull request to announce its own port. And the config URL is the
LOOPBACK address, not the advertised one: on alpha the name Linkwarden now
advertises resolves to 127.0.1.1, where nothing is bound, so a sidecar running
there would dial the name it publishes and get nothing.

Typechecks clean. No provisioning and no panel yet.
2026-09-05 20:56:18 +01:00

147 lines
5.7 KiB
TypeScript

import { eq } from 'drizzle-orm';
import { db } from 'officerdb/db';
import { encryptSecret, decryptSecret } from 'officerdb/crypto';
import { linkwardenConfig, linkwardenAccounts } from './schema';
// Linkwarden 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
// `linkwarden`, minted on first use by the secret store (docs/secret-store.md).
// ── Instance configuration (server-wide, one row) ──
export type LinkwardenConfig = { url: string | null; enabled: boolean; updatedAt: Date | null };
const EMPTY_CONFIG: LinkwardenConfig = { url: null, enabled: true, updatedAt: null };
/**
* Where this install's Linkwarden 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 `getAdminToken`.
*/
export async function getLinkwardenConfig(): Promise<LinkwardenConfig> {
const [row] = await db.select().from(linkwardenConfig).where(eq(linkwardenConfig.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 Linkwarden, 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 setLinkwardenConfig(patch: {
url?: string | null;
enabled?: boolean;
adminToken?: string | null;
}): Promise<LinkwardenConfig> {
const values = {
id: 1,
...(patch.url !== undefined ? { url: patch.url === null ? null : normaliseUrl(patch.url) } : {}),
...(patch.enabled !== undefined ? { enabled: patch.enabled } : {}),
...(patch.adminToken !== undefined
? { adminToken: patch.adminToken === null ? null : await encryptSecret('linkwarden', patch.adminToken) }
: {}),
updatedAt: new Date(),
};
await db
.insert(linkwardenConfig)
.values(values)
.onConflictDoUpdate({ target: linkwardenConfig.id, set: values });
return getLinkwardenConfig();
}
/**
* The admin token, decrypted. Read by provisioning and by nothing else.
*
* Separate from `getLinkwardenConfig` 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 getAdminToken(): Promise<string | null> {
const [row] = await db.select().from(linkwardenConfig).where(eq(linkwardenConfig.id, 1));
if (!row?.adminToken) return null;
return decryptSecret('linkwarden', row.adminToken);
}
// ── Account mapping (one row per Officer user) ──
export type LinkwardenAccount = {
userId: number;
linkwardenUserId: number;
username: string;
/** Null when an account exists but no token has been minted for it yet. A real state, not an error. */
accessToken: string | null;
};
/** Who this Officer user is on Linkwarden, or null when nobody has mapped them. */
export async function getAccount(userId: number): Promise<LinkwardenAccount | null> {
const [row] = await db.select().from(linkwardenAccounts).where(eq(linkwardenAccounts.userId, userId));
if (!row) return null;
return {
userId: row.userId,
linkwardenUserId: row.linkwardenUserId,
username: row.username,
accessToken: row.accessToken ? await decryptSecret('linkwarden', row.accessToken) : null,
};
}
/** Every mapping, for the owner's account screen. Tokens are NOT included — only whether one exists. */
export async function listAccounts(): Promise<
{ userId: number; linkwardenUserId: number; username: string; hasToken: boolean }[]
> {
const rows = await db.select().from(linkwardenAccounts);
return rows.map((row) => ({
userId: row.userId,
linkwardenUserId: row.linkwardenUserId,
username: row.username,
hasToken: !!row.accessToken,
}));
}
/** Map an Officer user onto a Linkwarden account, or replace the mapping. Upsert on `userId`. */
export async function setAccount(account: {
userId: number;
linkwardenUserId: number;
username: string;
accessToken?: string | null;
}): Promise<void> {
const values = {
userId: account.userId,
linkwardenUserId: account.linkwardenUserId,
username: account.username,
...(account.accessToken !== undefined
? {
accessToken:
account.accessToken === null ? null : await encryptSecret('linkwarden', account.accessToken),
}
: {}),
updatedAt: new Date(),
};
await db.insert(linkwardenAccounts).values(values).onConflictDoUpdate({ target: linkwardenAccounts.userId, set: values });
}
/**
* Forget the mapping. Does NOT delete the Linkwarden 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
* in Linkwarden, by somebody who means it.
*/
export async function forgetAccount(userId: number): Promise<boolean> {
const rows = await db
.delete(linkwardenAccounts)
.where(eq(linkwardenAccounts.userId, userId))
.returning({ userId: linkwardenAccounts.userId });
return rows.length > 0;
}