The notes existed but there was nowhere to write them: a CLI command on a laptop, a tool call through Claude, or a file in a Docker volume. None of those is reachable from a phone in a lesson, which is where notes are actually taken. So: `/app`, served only when WEB_PASSWORD is set. A login, the day's notes, and a settings page for the Schulcloud token — the one surface here meant for a person rather than a program. The shape follows how the notes are written: one note per school day, one `##` heading per lesson, prose and lists and tables beneath. That turns out to be the design decision that matters, twice over. First, it is what lets WebUntis earn its keep. Opening a day with no note fills in that day's lessons — numbered, with times, teacher and room, cancellations dropped and substitutions marked. Retyping the timetable is exactly the work the second upstream exists to avoid, and "Stunden ergänzen" tops up a note started before the day ended without touching what is already written. Second, it changes how notes are indexed. A day note is indexed per lesson, not whole: search answers "my own note, Deutsch, 18.09.2026" rather than "my own note, Friday", and `list_notes subject=Deutsch` finds a day whose frontmatter names no subject at all. Indexed whole, every hit would read as a weekday and "what did we do in Deutsch" would match notes whose other five lessons were something else. `lessonHeading` and `subjectFromHeading` are a loop — the app writes the heading, the indexer reads the subject back out — and a test holds them to it. Notes taken in a lesson cannot be retaken, so the editor is built around not losing them: autosave, every keystroke mirrored to local storage, a save when the phone locks, and a fallback to the local copy when the request never arrives. A save that would overwrite a version the editor never saw is refused and the choice handed back — the notes folder is synced and open in more than one place, and a phone must not silently win over a laptop. `replaceNote` is separate from `writeNote` for that reason: never-overwrite is right for `add_note` and exactly wrong for an editor. WEB_PASSWORD is the first credential here a human types, so it is the first that can be guessed: scrypt at startup, never stored or compared in the clear, per-address rate limiting — which is not decoration, since the scrypt cost is itself a denial-of-service vector without it. The session is a signed HttpOnly SameSite=Strict cookie whose key is derived from the password, so changing it logs everyone out and there is no second secret to keep. It opens /api, because a session is the user, and never /mcp, because nothing in a browser speaks MCP. Also here, because the app made them matter: frontmatter now reads the indented `- item` list form editors write, so an Obsidian vault round-trips its tags; and a four-digit folder is a filing scheme, not a subject, so `2026/` does not file a school year under one. 357 tests; 106/107 smoke against the local instance, the one failure being the H5P service that instance does not run. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
99 lines
3.9 KiB
TypeScript
99 lines
3.9 KiB
TypeScript
import { timingSafeEqual } from 'node:crypto';
|
|
import type { NextFunction, Request, Response } from 'express';
|
|
|
|
/**
|
|
* Bearer-token gate for the public endpoint.
|
|
*
|
|
* This server is reachable from the internet by construction — Claude's
|
|
* connectors call it from Anthropic's cloud, not from the user's machine — so
|
|
* the token is the only thing between a stranger and the account's data.
|
|
* Comparison is constant-time, and a miss returns a bare 401 with a
|
|
* `WWW-Authenticate` challenge and no detail about why.
|
|
*
|
|
* A route can accept more than one token: `/mcp` also takes the connector
|
|
* token claude.ai stores, which `/api` refuses.
|
|
*
|
|
* `alsoAccept` is the other kind of caller: a person logged into the web app,
|
|
* carrying a session cookie rather than a token. `/api` takes it because the
|
|
* app is built on `/api` and a session *is* the user; `/mcp` does not, because
|
|
* nothing in a browser speaks MCP and a surface not needed is a surface not
|
|
* offered.
|
|
*/
|
|
export function bearerAuth(accepted: string | string[], alsoAccept?: (req: Request) => boolean) {
|
|
const expected = (Array.isArray(accepted) ? accepted : [accepted]).map((token) => Buffer.from(token, 'utf8'));
|
|
|
|
return function authenticate(req: Request, res: Response, next: NextFunction): void {
|
|
// A logged-in browser instead of a token. Checked first because the app's
|
|
// own fetches carry no Authorization header at all, and running them
|
|
// through the token comparison would only waste it.
|
|
if (alsoAccept?.(req)) {
|
|
next();
|
|
return;
|
|
}
|
|
|
|
const presented = extractToken(req.get('authorization'), req.get('x-api-key') ?? req.get('x-auth-token'));
|
|
// Every token is compared even after a match, so the timing does not
|
|
// tell which one was presented.
|
|
const matched =
|
|
presented !== undefined &&
|
|
expected.map((token) => constantTimeEquals(Buffer.from(presented, 'utf8'), token)).includes(true);
|
|
if (!matched) {
|
|
res.setHeader('WWW-Authenticate', 'Bearer realm="schulcloud-mcp"');
|
|
res.status(401).json({
|
|
jsonrpc: '2.0',
|
|
error: { code: -32001, message: 'Unauthorized' },
|
|
id: null,
|
|
});
|
|
return;
|
|
}
|
|
next();
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Gate for `/:secret/mcp`, the header-free way in.
|
|
*
|
|
* A wrong secret answers exactly like any other unknown path, so guessing
|
|
* learns nothing — not even that the route exists. The comparison is
|
|
* constant-time for the same reason as the bearer check's.
|
|
*/
|
|
export function pathSecret(expected: string) {
|
|
const expectedBytes = Buffer.from(expected, 'utf8');
|
|
|
|
return function checkPathSecret(req: Request, res: Response, next: NextFunction): void {
|
|
const presented = req.params.secret;
|
|
if (typeof presented !== 'string' || !constantTimeEquals(Buffer.from(presented, 'utf8'), expectedBytes)) {
|
|
res.status(404).json({ error: 'not_found' });
|
|
return;
|
|
}
|
|
next();
|
|
};
|
|
}
|
|
|
|
function extractToken(authorization: string | undefined, apiKey: string | undefined): string | undefined {
|
|
if (authorization) {
|
|
const value = authorization.trim();
|
|
const match = /^Bearer\s+(.+)$/i.exec(value);
|
|
if (match?.[1]) return match[1].trim();
|
|
// claude.ai sends a request header exactly as typed, so a token entered
|
|
// without "Bearer " arrives bare — its own docs warn most servers reject
|
|
// that. A bare credential is still the whole credential; one with another
|
|
// scheme ("Basic …") has a space in it and is not taken for one.
|
|
if (value && !/\s/.test(value)) return value;
|
|
}
|
|
// Connector UIs also offer X-Api-Key and X-Auth-Token instead of Authorization.
|
|
return apiKey?.trim() || undefined;
|
|
}
|
|
|
|
function constantTimeEquals(a: Buffer, b: Buffer): boolean {
|
|
// timingSafeEqual throws on length mismatch, which would itself leak length.
|
|
// Hash-free equalisation: compare against a padded copy of the same size.
|
|
if (a.length !== b.length) {
|
|
const padded = Buffer.alloc(b.length);
|
|
a.copy(padded, 0, 0, Math.min(a.length, b.length));
|
|
timingSafeEqual(padded, b);
|
|
return false;
|
|
}
|
|
return timingSafeEqual(a, b);
|
|
}
|