Add admin identity module: better-auth, per-app permissions, invitations
Introduces src/models/admin/, a dedicated identity and permissions module on its own nachklang_admin database, and the shared authenticator that feedback and tickets will move onto in the cutover step. Nothing swaps over yet: feedback.auth.ts and tickets.auth.ts still authenticate against the legacy calendar sessions, so production behaviour is unchanged. - better-auth 1.7 mounted at /admin/auth/*, sessions as httpOnly cookies scoped to .nachklang.art so one sign-in covers every *.nachklang.art app. - Accounts are invite-only: public sign-up is disabled, and the invitations plugin is the only code that creates users. Tokens are stored as SHA-256 hashes and travel in the request body, never in a URL. - Per-app permissions in user_app_permissions; requireAppAccess(app) queries the database on every request (no cookie cache) so disabling a user or revoking a session takes effect immediately. - ADMIN_BOOTSTRAP_EMAIL guarantees a way in on an empty database, idempotently and without crashing the API if the database is unreachable at boot. - Guards prevent an admin from removing their own admin permission, disabling themselves, or stripping the last active admin. The admin pool uses the callback-style mysql2, not mysql2/promise: Kysely's MysqlDialect drives the pool with callbacks, and the promise wrapper ignores them, so every query hangs silently. Only the integration tests caught this. Schema in sql/admin/001_init.sql, derived from getAuthTables() on the installed better-auth rather than the published CLI, which lags the library and omits account.issuer. app.ts is split into src/app.factory.ts so the integration tests drive the real middleware order rather than a copy of it. Tests: 131 unit, plus 41 integration tests against a throwaway MariaDB started by test/integration/setup.ts (docker or podman). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,107 @@
|
||||
import {execFile} from 'child_process';
|
||||
import {promisify} from 'util';
|
||||
import {createRequire} from 'module';
|
||||
|
||||
const run = promisify(execFile);
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
/**
|
||||
* vitest globalSetup for the admin integration tests: starts a throwaway
|
||||
* MariaDB before the suite and removes it afterwards, so a run leaves nothing
|
||||
* behind and never touches a shared database.
|
||||
*
|
||||
* The container is started directly rather than through compose, because
|
||||
* `podman compose` needs a separate compose provider that neither podman nor
|
||||
* docker ships. One container needs no orchestration, and this works with
|
||||
* whichever of the two runtimes is installed.
|
||||
*/
|
||||
|
||||
export const CONTAINER_NAME = 'nachklang-admin-test-db';
|
||||
export const TEST_DB_PORT = 3307;
|
||||
|
||||
const IMAGE = 'docker.io/library/mariadb:11';
|
||||
|
||||
const runtime = async (): Promise<string> => {
|
||||
for (const candidate of ['docker', 'podman']) {
|
||||
try {
|
||||
await run(candidate, ['info'], {timeout: 60_000});
|
||||
return candidate;
|
||||
} catch {
|
||||
// Not installed, or its daemon/machine is not running - try the next.
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
'The admin integration tests need a container runtime. Install docker or podman ' +
|
||||
'(with podman: `podman machine start`), then re-run npm run test:integration.'
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Ready means "the entrypoint has applied 001_init.sql", not just "the port
|
||||
* answers": MariaDB accepts connections while it is still running its init
|
||||
* scripts, and a test that started then would fail on a missing table.
|
||||
*/
|
||||
const waitForSchema = async (): Promise<void> => {
|
||||
const mysql = require('mysql2/promise');
|
||||
const deadline = Date.now() + 120_000;
|
||||
let lastError: unknown;
|
||||
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const connection = await mysql.createConnection({
|
||||
host: '127.0.0.1',
|
||||
port: TEST_DB_PORT,
|
||||
user: 'nachklang',
|
||||
password: 'testpassword',
|
||||
database: 'nachklang_admin',
|
||||
connectTimeout: 5_000
|
||||
});
|
||||
const [rows] = await connection.query(
|
||||
"SELECT COUNT(*) AS n FROM information_schema.tables " +
|
||||
"WHERE table_schema = 'nachklang_admin' AND table_name IN ('user', 'user_app_permissions', 'invitations')"
|
||||
);
|
||||
await connection.end();
|
||||
if (Number((rows as any[])[0]?.n) === 3) {
|
||||
return;
|
||||
}
|
||||
lastError = new Error('schema not applied yet');
|
||||
} catch (e) {
|
||||
lastError = e;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 1_000));
|
||||
}
|
||||
|
||||
throw new Error(`Test database never became ready: ${(lastError as any)?.message}`);
|
||||
};
|
||||
|
||||
export const setup = async () => {
|
||||
const engine = await runtime();
|
||||
|
||||
// A container left behind by an interrupted run would still hold the old
|
||||
// schema and rows, so always start from scratch.
|
||||
await run(engine, ['rm', '-f', CONTAINER_NAME], {timeout: 60_000}).catch(() => undefined);
|
||||
|
||||
await run(engine, [
|
||||
'run', '-d',
|
||||
'--name', CONTAINER_NAME,
|
||||
'-e', 'MARIADB_ROOT_PASSWORD=roottestpassword',
|
||||
'-e', 'MARIADB_DATABASE=nachklang_admin',
|
||||
'-e', 'MARIADB_USER=nachklang',
|
||||
'-e', 'MARIADB_PASSWORD=testpassword',
|
||||
'-p', `${TEST_DB_PORT}:3306`,
|
||||
// The very migration production runs, applied by the entrypoint on first
|
||||
// boot - so a mistake in it fails the test run rather than the deploy.
|
||||
'-v', `${process.cwd()}/sql/admin/001_init.sql:/docker-entrypoint-initdb.d/001_init.sql:ro`,
|
||||
// Data lives in the container layer and dies with it.
|
||||
IMAGE
|
||||
], {timeout: 300_000});
|
||||
|
||||
await waitForSchema();
|
||||
};
|
||||
|
||||
export const teardown = async () => {
|
||||
const engine = await runtime().catch(() => null);
|
||||
if (engine) {
|
||||
await run(engine, ['rm', '-f', CONTAINER_NAME], {timeout: 60_000}).catch(() => undefined);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user