Skip to content

armgit / Piik

Public Imported from GitHub
0

Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

feat(room): add optional stable SQLite room authority (#271)

AAAdc1869778c73
diff --git a/.env.example b/.env.example
index 467ba0f4..a6fed96d 100644
--- a/.env.example
+++ b/.env.example
@@ -10,8 +10,12 @@ ALLOWED_ORIGINS=http://localhost:8787
# empty. A non-empty value must contain 8-128 visible ASCII bytes (0x21-0x7e).
SITE_ACCESS_PASSWORD=
# Dormant rooms remain resumable by the exact Host token for this lease.
-# Active sharing does not expire; process restart clears every room.
+# Active sharing does not expire.
ROOM_LEASE_SECONDS=86400
+# Optional stable room authority. Leave empty for process-memory rooms. Use one
+# access-restricted absolute local file path per application process; production
+# activation requires a verified writable directory and database recovery procedure.
+ROOM_DATABASE_PATH=
MAX_VIEWERS_PER_ROOM=8
# Bounded standard-WebRTC relay/SFU controller for every room when true.
# Keep false outside measured tests.
diff --git a/src/server/app.ts b/src/server/app.ts
index c7f1f366..48f7be64 100644
--- a/src/server/app.ts
+++ b/src/server/app.ts
@@ -15,6 +15,7 @@ import type { SfuFallbackOptions } from "./hybrid-media-router.js";
import type { SfuTokenIssuer } from "./livekit-token.js";
import type { SfuRoomControl } from "./sfu-room-control.js";
import { SfuResourceAdmission } from "./sfu-resource-admission.js";
+import { RoomDatabase } from "./room-database.js";
import { ROOM_CAPACITY, RoomStore, RoomStoreError } from "./room-store.js";
import { SignalingServer, type SignalingOptions } from "./signaling.js";
@@ -83,6 +84,9 @@ export async function createScreenerServer(
leaseMs: config.roomLeaseMs,
maxRooms: ROOM_CAPACITY,
maxViewersPerRoom: config.maxViewersPerRoom,
+ database: config.roomDatabasePath
+ ? new RoomDatabase(config.roomDatabasePath)
+ : undefined,
now,
});
const siteAccess = new SiteAccess({
@@ -206,6 +210,7 @@ export async function createScreenerServer(
startupOperation = (async () => {
const boundPort = await bindHttpServer(httpServer, port, host);
try {
+ roomStore.initialize();
await sfuRoomControl?.initialize();
if (!closing) {
signaling = new SignalingServer(signalingOptions);
@@ -213,11 +218,20 @@ export async function createScreenerServer(
}
return boundPort;
} catch (error) {
+ const cleanupErrors: unknown[] = [];
+ try {
+ roomStore.close();
+ } catch (closeError) {
+ cleanupErrors.push(closeError);
+ }
try {
await closeHttpServer(httpServer);
} catch (closeError) {
+ cleanupErrors.push(closeError);
+ }
+ if (cleanupErrors.length > 0) {
throw new AggregateError(
- [error, closeError],
+ [error, ...cleanupErrors],
"Screener startup reconciliation failed",
);
}
diff --git a/src/server/config.ts b/src/server/config.ts
index d98eae90..400d31e4 100644
--- a/src/server/config.ts
+++ b/src/server/config.ts
@@ -1,3 +1,5 @@
+import { isAbsolute } from "node:path";
+
import {
MAX_ICE_SERVER_URLS,
MAX_VIEWERS_PER_ROOM_LIMIT,
@@ -30,7 +32,6 @@ const REMOVED_ENVIRONMENT_VARIABLES = [
"PEER_ASSISTED_ROOM_IDS",
"HOST_ADMISSION_PASSWORD",
"MAX_PEER_RELAY_DOWNSTREAM_EDGES",
- "ROOM_DATABASE_PATH",
"ROOM_TTL_SECONDS",
] as const;
@@ -48,6 +49,7 @@ export interface ServerConfig {
publicBaseUrl: URL;
allowedOrigins: ReadonlySet<string>;
siteAccessPassword?: string;
+ roomDatabasePath?: string;
roomLeaseMs: number;
maxViewersPerRoom: number;
peerAssistedMedia: boolean;
@@ -111,6 +113,17 @@ function parseEnvironment(value: string | undefined): RuntimeEnvironment {
return environment;
}
+function parseRoomDatabasePath(value: string | undefined): string | undefined {
+ const path = value?.trim();
+ if (!path) {
+ return undefined;
+ }
+ if (path === ":memory:" || path.includes("\0") || !isAbsolute(path)) {
+ throw new Error("ROOM_DATABASE_PATH must be an absolute file path");
+ }
+ return path;
+}
+
function parseLiveKitFallback(
environment: NodeJS.ProcessEnv,
nodeEnv: RuntimeEnvironment,
@@ -254,6 +267,8 @@ export function loadConfig(
? `${name} is no longer supported; use SITE_ACCESS_PASSWORD`
: name === "PEER_ASSISTED_ROOM_IDS"
? `${name} is no longer supported; peer-assisted media applies to every room when enabled`
+ : name === "ROOM_TTL_SECONDS"
+ ? `${name} is no longer supported; use ROOM_LEASE_SECONDS`
: `${name} is no longer supported; ordinary ICE accepts STUN_URLS only`,
);
}
@@ -299,6 +314,9 @@ export function loadConfig(
environment.SITE_ACCESS_PASSWORD === ""
? undefined
: environment.SITE_ACCESS_PASSWORD;
+ const roomDatabasePath = parseRoomDatabasePath(
+ environment.ROOM_DATABASE_PATH,
+ );
const stunUrls = parseStunUrlList(environment.STUN_URLS);
const maxViewersPerRoom = parseBoundedInteger(
environment.MAX_VIEWERS_PER_ROOM,
@@ -362,6 +380,7 @@ export function loadConfig(
publicBaseUrl.origin,
),
siteAccessPassword,
+ roomDatabasePath,
roomLeaseMs:
parsePositiveInteger(
environment.ROOM_LEASE_SECONDS,
diff --git a/src/server/room-database.ts b/src/server/room-database.ts
new file mode 100644
index 00000000..57b900b4
--- /dev/null
+++ b/src/server/room-database.ts
@@ -0,0 +1,534 @@
+import { DatabaseSync } from "node:sqlite";
+
+import {
+ codeEntryPolicySchema,
+ roomCodeSchema,
+ type CodeEntryPolicy,
+} from "../shared/protocol.js";
+
+const ROOM_DATABASE_APPLICATION_ID = 0x5343524e;
+const ROOM_DATABASE_SCHEMA_VERSION = 1;
+const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
+
+export interface StoredRoomAuthority {
+ roomId: string;
+ hostTokenDigest: Buffer;
+ viewerGrantDigest: Buffer;
+ viewerAuthorizationGeneration: string;
+ codeEntryPolicy: CodeEntryPolicy;
+ viewerPasswordMaterial: Buffer | null;
+ leaseExpiresAtMs: number | null;
+}
+
+export class RoomDatabase {
+ private database: DatabaseSync | undefined;
+
+ constructor(private readonly path: string) {
+ if (!path || path === ":memory:") {
+ throw new Error("Room database path must identify a file");
+ }
+ }
+
+ initialize(
+ startupNowMs: number,
+ activeLeaseExpiresAtMs: number,
+ ): StoredRoomAuthority[] {
+ if (this.database) {
+ throw new Error("Room database is already initialized");
+ }
+ assertTimestamp(startupNowMs, "Room database startup time", true);
+ assertTimestamp(
+ activeLeaseExpiresAtMs,
+ "Room database active-room lease deadline",
+ );
+ if (activeLeaseExpiresAtMs <= startupNowMs) {
+ throw new Error("Room database active-room lease deadline must be in the future");
+ }
+
+ const database = new DatabaseSync(this.path, { timeout: 0 });
+ try {
+ const lockingMode = database
+ .prepare("PRAGMA main.locking_mode = EXCLUSIVE")
+ .get() as Record<string, unknown> | undefined;
+ if (lockingMode?.locking_mode !== "exclusive") {
+ throw new Error("Room database could not acquire exclusive locking mode");
+ }
+
+ database.exec("BEGIN EXCLUSIVE");
+ let restored: StoredRoomAuthority[];
+ try {
+ this.ensureExactSchema(database);
+ assertDatabaseIntegrity(database);
+ const stored = readStoredRooms(database);
+ const expiredCount = stored.filter(
+ (room) =>
+ room.leaseExpiresAtMs !== null &&
+ room.leaseExpiresAtMs <= startupNowMs,
+ ).length;
+ const activeCount = stored.filter(
+ (room) => room.leaseExpiresAtMs === null,
+ ).length;
+
+ const deleted = database
+ .prepare(
+ `DELETE FROM rooms
+ WHERE lease_expires_at_ms IS NOT NULL
+ AND lease_expires_at_ms <= ?`,
+ )
+ .run(startupNowMs).changes;
+ if (Number(deleted) !== expiredCount) {
+ throw new Error("Room database expiry cleanup changed an unexpected row count");
+ }
+
+ const converted = database
+ .prepare(
+ `UPDATE rooms
+ SET lease_expires_at_ms = ?
+ WHERE lease_expires_at_ms IS NULL`,
+ )
+ .run(activeLeaseExpiresAtMs).changes;
+ if (Number(converted) !== activeCount) {
+ throw new Error("Room database active-room recovery changed an unexpected row count");
+ }
+
+ restored = stored.flatMap((room) => {
+ if (
+ room.leaseExpiresAtMs !== null &&
+ room.leaseExpiresAtMs <= startupNowMs
+ ) {
+ return [];
+ }
+ return [
+ room.leaseExpiresAtMs === null
+ ? { ...room, leaseExpiresAtMs: activeLeaseExpiresAtMs }
+ : room,
+ ];
+ });
+ database.exec("COMMIT");
+ } catch (error) {
+ if (database.isTransaction) {
+ database.exec("ROLLBACK");
+ }
+ throw error;
+ }
+
+ this.database = database;
+ return restored;
+ } catch (error) {
+ database.close();
+ throw error;
+ }
+ }
+
+ insertRoom(room: StoredRoomAuthority): void {
+ assertStoredRoom(room);
+ this.transaction((database) => {
+ const changes = database
+ .prepare(
+ `INSERT INTO rooms (
+ room_id,
+ host_token_digest,
+ viewer_grant_digest,
+ viewer_authorization_generation,
+ code_entry_policy,
+ viewer_password_material,
+ lease_expires_at_ms
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run(
+ room.roomId,
+ room.hostTokenDigest,
+ room.viewerGrantDigest,
+ room.viewerAuthorizationGeneration,
+ room.codeEntryPolicy,
+ room.viewerPasswordMaterial,
+ room.leaseExpiresAtMs,
+ ).changes;
+ assertSingleChange(changes, "insert");
+ });
+ }
+
+ setLeaseDeadline(
+ roomId: string,
+ hostTokenDigest: Buffer,
+ leaseExpiresAtMs: number | null,
+ ): void {
+ assertRoomIdentity(roomId, hostTokenDigest);
+ if (leaseExpiresAtMs !== null) {
+ assertTimestamp(leaseExpiresAtMs, "Room lease deadline");
+ }
+ this.transaction((database) => {
+ const changes = database
+ .prepare(
+ `UPDATE rooms
+ SET lease_expires_at_ms = ?
+ WHERE room_id = ? AND host_token_digest = ?`,
+ )
+ .run(leaseExpiresAtMs, roomId, hostTokenDigest).changes;
+ assertSingleChange(changes, "lease update");
+ });
+ }
+
+ setViewerPassword(
+ roomId: string,
+ hostTokenDigest: Buffer,
+ viewerPasswordMaterial: Buffer | null,
+ ): void {
+ assertRoomIdentity(roomId, hostTokenDigest);
+ assertPasswordMaterial(viewerPasswordMaterial);
+ this.transaction((database) => {
+ const changes = database
+ .prepare(
+ `UPDATE rooms
+ SET viewer_password_material = ?
+ WHERE room_id = ? AND host_token_digest = ?`,
+ )
+ .run(viewerPasswordMaterial, roomId, hostTokenDigest).changes;
+ assertSingleChange(changes, "password update");
+ });
+ }
+
+ setCodeEntryPolicy(
+ roomId: string,
+ hostTokenDigest: Buffer,
+ codeEntryPolicy: CodeEntryPolicy,
+ ): void {
+ assertRoomIdentity(roomId, hostTokenDigest);
+ if (!codeEntryPolicySchema.safeParse(codeEntryPolicy).success) {
+ throw new Error("Room code-entry policy is invalid");
+ }
+ this.transaction((database) => {
+ const changes = database
+ .prepare(
+ `UPDATE rooms
+ SET code_entry_policy = ?
+ WHERE room_id = ? AND host_token_digest = ?`,
+ )
+ .run(codeEntryPolicy, roomId, hostTokenDigest).changes;
+ assertSingleChange(changes, "code-entry policy update");
+ });
+ }
+
+ setViewerGrant(
+ roomId: string,
+ hostTokenDigest: Buffer,
+ viewerGrantDigest: Buffer,
+ viewerAuthorizationGeneration: string,
+ ): void {
+ assertRoomIdentity(roomId, hostTokenDigest);
+ assertDigest(viewerGrantDigest, "Viewer grant");
+ assertAuthorizationGeneration(viewerAuthorizationGeneration);
+ this.transaction((database) => {
+ const changes = database
+ .prepare(
+ `UPDATE rooms
+ SET viewer_grant_digest = ?,
+ viewer_authorization_generation = ?
+ WHERE room_id = ? AND host_token_digest = ?`,
+ )
+ .run(
+ viewerGrantDigest,
+ viewerAuthorizationGeneration,
+ roomId,
+ hostTokenDigest,
+ ).changes;
+ assertSingleChange(changes, "Viewer grant update");
+ });
+ }
+
+ deleteRoom(roomId: string, hostTokenDigest: Buffer): void {
+ assertRoomIdentity(roomId, hostTokenDigest);
+ this.transaction((database) => {
+ const changes = database
+ .prepare(
+ "DELETE FROM rooms WHERE room_id = ? AND host_token_digest = ?",
+ )
+ .run(roomId, hostTokenDigest).changes;
+ assertSingleChange(changes, "delete");
+ });
+ }
+
+ close(): void {
+ const database = this.database;
+ this.database = undefined;
+ if (database?.isOpen) {
+ database.close();
+ }
+ }
+
+ private ensureExactSchema(database: DatabaseSync): void {
+ const applicationId = readPragmaInteger(database, "application_id");
+ const schemaVersion = readPragmaInteger(database, "user_version");
+ const schemaObjects = database
+ .prepare(
+ `SELECT type, name
+ FROM sqlite_schema
+ WHERE name NOT LIKE 'sqlite_%'
+ ORDER BY type, name`,
+ )
+ .all() as Array<Record<string, unknown>>;
+
+ if (
+ applicationId === 0 &&
+ schemaVersion === 0 &&
+ schemaObjects.length === 0
+ ) {
+ database.exec(`
+ CREATE TABLE rooms (
+ room_id TEXT PRIMARY KEY NOT NULL
+ CHECK (room_id GLOB '[1-9][0-9][0-9][0-9]'),
+ host_token_digest BLOB NOT NULL
+ CHECK (typeof(host_token_digest) = 'blob' AND length(host_token_digest) = 32),
+ viewer_grant_digest BLOB NOT NULL
+ CHECK (typeof(viewer_grant_digest) = 'blob' AND length(viewer_grant_digest) = 32),
+ viewer_authorization_generation TEXT NOT NULL
+ CHECK (
+ length(viewer_authorization_generation) = 22 AND
+ viewer_authorization_generation NOT GLOB '*[^A-Za-z0-9_-]*'
+ ),
+ code_entry_policy TEXT NOT NULL
+ CHECK (code_entry_policy IN ('open', 'private')),
+ viewer_password_material BLOB NULL
+ CHECK (
+ viewer_password_material IS NULL OR
+ (typeof(viewer_password_material) = 'blob' AND length(viewer_password_material) = 48)
+ ),
+ lease_expires_at_ms INTEGER NULL
+ CHECK (
+ lease_expires_at_ms IS NULL OR
+ (lease_expires_at_ms > 0 AND lease_expires_at_ms <= ${MAX_SAFE_INTEGER})
+ )
+ ) STRICT;
+ PRAGMA application_id = ${ROOM_DATABASE_APPLICATION_ID};
+ PRAGMA user_version = ${ROOM_DATABASE_SCHEMA_VERSION};
+ `);
+ return;
+ }
+
+ if (applicationId !== ROOM_DATABASE_APPLICATION_ID) {
+ throw new Error("Room database application identity does not match");
+ }
+ if (schemaVersion !== ROOM_DATABASE_SCHEMA_VERSION) {
+ throw new Error("Room database schema version does not match");
+ }
+ if (
+ schemaObjects.length !== 1 ||
+ schemaObjects[0]?.type !== "table" ||
+ schemaObjects[0]?.name !== "rooms"
+ ) {
+ throw new Error("Room database schema objects do not match");
+ }
+ assertExactColumns(database);
+ }
+
+ private transaction(operation: (database: DatabaseSync) => void): void {
+ const database = this.database;
+ if (!database?.isOpen) {
+ throw new Error("Room database is not initialized");
+ }
+ database.exec("BEGIN IMMEDIATE");
+ try {
+ operation(database);
+ database.exec("COMMIT");
+ } catch (error) {
+ if (database.isTransaction) {
+ database.exec("ROLLBACK");
+ }
+ throw error;
+ }
+ }
+}
+
+function readStoredRooms(database: DatabaseSync): StoredRoomAuthority[] {
+ const rows = database
+ .prepare(
+ `SELECT
+ room_id,
+ host_token_digest,
+ viewer_grant_digest,
+ viewer_authorization_generation,
+ code_entry_policy,
+ viewer_password_material,
+ lease_expires_at_ms
+ FROM rooms
+ ORDER BY room_id`,
+ )
+ .all() as Array<Record<string, unknown>>;
+ return rows.map((row) => {
+ const room: StoredRoomAuthority = {
+ roomId: readString(row.room_id, "room ID"),
+ hostTokenDigest: readDigest(row.host_token_digest, "Host token"),
+ viewerGrantDigest: readDigest(row.viewer_grant_digest, "Viewer grant"),
+ viewerAuthorizationGeneration: readString(
+ row.viewer_authorization_generation,
+ "Viewer authorization generation",
+ ),
+ codeEntryPolicy: readCodeEntryPolicy(row.code_entry_policy),
+ viewerPasswordMaterial: readPasswordMaterial(
+ row.viewer_password_material,
+ ),
+ leaseExpiresAtMs: readNullableTimestamp(row.lease_expires_at_ms),
+ };
+ assertStoredRoom(room);
+ return room;
+ });
+}
+
+function assertStoredRoom(room: StoredRoomAuthority): void {
+ if (!roomCodeSchema.safeParse(room.roomId).success) {
+ throw new Error("Room database contains an invalid room ID");
+ }
+ assertDigest(room.hostTokenDigest, "Host token");
+ assertDigest(room.viewerGrantDigest, "Viewer grant");
+ assertAuthorizationGeneration(room.viewerAuthorizationGeneration);
+ if (!codeEntryPolicySchema.safeParse(room.codeEntryPolicy).success) {
+ throw new Error("Room database contains an invalid code-entry policy");
+ }
+ assertPasswordMaterial(room.viewerPasswordMaterial);
+ if (room.leaseExpiresAtMs !== null) {
+ assertTimestamp(room.leaseExpiresAtMs, "Room database lease deadline");
+ }
+}
+
+function assertRoomIdentity(roomId: string, hostTokenDigest: Buffer): void {
+ if (!roomCodeSchema.safeParse(roomId).success) {
+ throw new Error("Room ID is invalid");
+ }
+ assertDigest(hostTokenDigest, "Host token");
+}
+
+function assertDigest(value: Uint8Array, name: string): void {
+ if (!(value instanceof Uint8Array) || value.byteLength !== 32) {
+ throw new Error(`${name} digest must contain 32 bytes`);
+ }
+}
+
+function assertPasswordMaterial(value: Uint8Array | null): void {
+ if (value !== null && (!(value instanceof Uint8Array) || value.byteLength !== 48)) {
+ throw new Error("Viewer password material must contain 48 bytes");
+ }
+}
+
+function assertAuthorizationGeneration(value: string): void {
+ let decoded: Buffer;
+ try {
+ decoded = Buffer.from(value, "base64url");
+ } catch {
+ throw new Error("Viewer authorization generation is invalid");
+ }
+ if (
+ decoded.byteLength !== 16 ||
+ decoded.toString("base64url") !== value
+ ) {
+ throw new Error("Viewer authorization generation is invalid");
+ }
+}
+
+function assertTimestamp(value: number, name: string, allowZero = false): void {
+ if (
+ !Number.isSafeInteger(value) ||
+ (allowZero ? value < 0 : value <= 0)
+ ) {
+ throw new Error(`${name} must be a safe positive integer`);
+ }
+}
+
+function assertSingleChange(
+ changes: number | bigint,
+ operation: string,
+): void {
+ if (Number(changes) !== 1) {
+ throw new Error(`Room database ${operation} did not match current authority`);
+ }
+}
+
+function assertDatabaseIntegrity(database: DatabaseSync): void {
+ const rows = database.prepare("PRAGMA quick_check").all() as Array<
+ Record<string, unknown>
+ >;
+ if (rows.length !== 1 || rows[0]?.quick_check !== "ok") {
+ throw new Error("Room database integrity check failed");
+ }
+}
+
+function assertExactColumns(database: DatabaseSync): void {
+ const columns = database.prepare("PRAGMA table_info(rooms)").all() as Array<
+ Record<string, unknown>
+ >;
+ const expected = [
+ ["room_id", "TEXT", 1, 1],
+ ["host_token_digest", "BLOB", 1, 0],
+ ["viewer_grant_digest", "BLOB", 1, 0],
+ ["viewer_authorization_generation", "TEXT", 1, 0],
+ ["code_entry_policy", "TEXT", 1, 0],
+ ["viewer_password_material", "BLOB", 0, 0],
+ ["lease_expires_at_ms", "INTEGER", 0, 0],
+ ] as const;
+ if (
+ columns.length !== expected.length ||
+ columns.some((column, index) => {
+ const [name, type, notNull, primaryKey] = expected[index]!;
+ return (
+ column.name !== name ||
+ column.type !== type ||
+ column.notnull !== notNull ||
+ column.pk !== primaryKey
+ );
+ })
+ ) {
+ throw new Error("Room database columns do not match the current schema");
+ }
+}
+
+function readPragmaInteger(database: DatabaseSync, name: string): number {
+ const row = database.prepare(`PRAGMA ${name}`).get() as
+ | Record<string, unknown>
+ | undefined;
+ const value = row?.[name];
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
+ throw new Error(`Room database ${name} is invalid`);
+ }
+ return value;
+}
+
+function readString(value: unknown, name: string): string {
+ if (typeof value !== "string") {
+ throw new Error(`Room database contains an invalid ${name}`);
+ }
+ return value;
+}
+
+function readDigest(value: unknown, name: string): Buffer {
+ if (!(value instanceof Uint8Array) || value.byteLength !== 32) {
+ throw new Error(`Room database contains an invalid ${name} digest`);
+ }
+ return Buffer.from(value);
+}
+
+function readCodeEntryPolicy(value: unknown): CodeEntryPolicy {
+ const parsed = codeEntryPolicySchema.safeParse(value);
+ if (!parsed.success) {
+ throw new Error("Room database contains an invalid code-entry policy");
+ }
+ return parsed.data;
+}
+
+function readPasswordMaterial(value: unknown): Buffer | null {
+ if (value === null) {
+ return null;
+ }
+ if (!(value instanceof Uint8Array) || value.byteLength !== 48) {
+ throw new Error("Room database contains invalid Viewer password material");
+ }
+ return Buffer.from(value);
+}
+
+function readNullableTimestamp(value: unknown): number | null {
+ if (value === null) {
+ return null;
+ }
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
+ throw new Error("Room database contains an invalid lease deadline");
+ }
+ return value;
+}
diff --git a/src/server/room-store.ts b/src/server/room-store.ts
index 812ded42..9cdac263 100644
--- a/src/server/room-store.ts
+++ b/src/server/room-store.ts
@@ -12,6 +12,10 @@ import {
type CodeEntryPolicy,
type Role,
} from "../shared/protocol.js";
+import {
+ type RoomDatabase,
+ type StoredRoomAuthority,
+} from "./room-database.js";
export type RoomStoreErrorCode =
| "INVALID_TOKEN"
@@ -148,6 +152,7 @@ export interface RoomStoreOptions {
leaseMs: number;
maxRooms: number;
maxViewersPerRoom: number;
+ database?: RoomDatabase;
now?: () => number;
random?: (size: number) => Buffer;
}
@@ -160,6 +165,7 @@ export class RoomStore {
);
private readonly now: () => number;
private readonly random: (size: number) => Buffer;
+ private initialized: boolean;
readonly maxViewersPerRoom: number;
constructor(private readonly options: RoomStoreOptions) {
@@ -186,18 +192,69 @@ export class RoomStore {
}
this.now = options.now ?? Date.now;
this.random = options.random ?? randomBytes;
+ this.initialized = options.database === undefined;
this.maxViewersPerRoom = options.maxViewersPerRoom;
}
+ initialize(): void {
+ if (this.initialized) {
+ return;
+ }
+ const database = this.options.database;
+ if (!database) {
+ this.initialized = true;
+ return;
+ }
+
+ const startupNowMs = this.now();
+ try {
+ const storedRooms = database.initialize(
+ startupNowMs,
+ this.leaseDeadline(startupNowMs),
+ );
+ if (storedRooms.length > this.options.maxRooms) {
+ throw new Error("Room database exceeds the configured room limit");
+ }
+ const roomIds = new Set(storedRooms.map((room) => room.roomId));
+ if (roomIds.size !== storedRooms.length) {
+ throw new Error("Room database contains duplicate room IDs");
+ }
+ for (const stored of storedRooms) {
+ this.rooms.set(stored.roomId, {
+ ...stored,
+ hostTokenDigest: Buffer.from(stored.hostTokenDigest),
+ viewerGrantDigest: Buffer.from(stored.viewerGrantDigest),
+ viewerPasswordMaterial:
+ stored.viewerPasswordMaterial === null
+ ? null
+ : Buffer.from(stored.viewerPasswordMaterial),
+ sharingActive: false,
+ viewers: new Map(),
+ });
+ }
+ const availableCodes = this.freeRoomCodes.filter(
+ (roomId) => !roomIds.has(roomId),
+ );
+ this.freeRoomCodes.splice(0, this.freeRoomCodes.length, ...availableCodes);
+ this.initialized = true;
+ } catch (error) {
+ this.rooms.clear();
+ database.close();
+ throw error;
+ }
+ }
+
async createRoom(
codeEntryPolicy: CodeEntryPolicy = "open",
roomPassword?: string | null,
preferredRoomId?: string,
): Promise<CreatedRoom> {
+ this.ensureInitialized();
if (this.rooms.size >= this.options.maxRooms) {
throw new RoomStoreError("ROOM_LIMIT");
}
const createdAtMs = this.now();
+ const leaseExpiresAtMs = this.leaseDeadline(createdAtMs);
const viewerPasswordMaterial = roomPassword
? await this.createViewerPasswordMaterial(roomPassword)
: null;
@@ -214,7 +271,7 @@ export class RoomStore {
const viewerGrant = this.createViewerGrant();
const viewerAuthorizationGeneration = this.newAuthorizationGeneration();
- this.rooms.set(roomId, {
+ const room: Room = {
roomId,
hostTokenDigest: digest(hostToken),
viewerGrantDigest: digest(viewerGrant),
@@ -222,16 +279,18 @@ export class RoomStore {
viewerAuthorizationGeneration,
codeEntryPolicy,
sharingActive: false,
- leaseExpiresAtMs: createdAtMs + this.options.leaseMs,
+ leaseExpiresAtMs,
viewers: new Map(),
- });
+ };
+ this.options.database?.insertRoom(storedRoomAuthority(room));
+ this.rooms.set(roomId, room);
return {
roomId,
hostToken,
codeEntryPolicy,
viewerGrant,
- expiresAt: formatExpiresAt(createdAtMs + this.options.leaseMs),
+ expiresAt: formatExpiresAt(leaseExpiresAtMs),
};
} catch (error) {
this.releaseRoomCode(roomId);
@@ -240,6 +299,7 @@ export class RoomStore {
}
connectParticipant(input: ConnectParticipantInput): ConnectedParticipant {
+ this.ensureInitialized();
let room: Room;
try {
room = this.getAvailableRoom(input.roomId);
@@ -274,6 +334,7 @@ export class RoomStore {
}
viewerGrantMayEnter(roomId: string, grant: string | undefined): boolean {
+ this.ensureInitialized();
try {
return this.viewerGrantIsValid(this.getAvailableRoom(roomId), grant);
} catch (error) {
@@ -288,6 +349,7 @@ export class RoomStore {
input: ConnectViewerWithPasswordInput,
mayConnect: () => boolean = () => true,
): Promise<ConnectedParticipant> {
+ this.ensureInitialized();
if (!viewerPasswordSchema.safeParse(input.password).success) {
throw new RoomStoreError("INVALID_TOKEN");
}
@@ -351,6 +413,7 @@ export class RoomStore {
password: string | null,
hostToken: string,
): Promise<boolean> {
+ this.ensureInitialized();
const room = this.getHostManagedRoom(roomId, hostToken);
const nextPasswordMaterial = password
@@ -370,6 +433,11 @@ export class RoomStore {
) {
throw new RoomStoreError("ROOM_ACCESS_DENIED");
}
+ this.options.database?.setViewerPassword(
+ roomId,
+ currentRoom.hostTokenDigest,
+ nextPasswordMaterial,
+ );
currentRoom.viewerPasswordMaterial = nextPasswordMaterial;
return nextPasswordMaterial !== null;
}
@@ -379,7 +447,13 @@ export class RoomStore {
policy: CodeEntryPolicy,
hostToken: string,
): CodeEntryUpdate {
+ this.ensureInitialized();
const room = this.getHostManagedRoom(roomId, hostToken);
+ this.options.database?.setCodeEntryPolicy(
+ roomId,
+ room.hostTokenDigest,
+ policy,
+ );
room.codeEntryPolicy = policy;
return {
codeEntryPolicy: policy,
@@ -392,6 +466,7 @@ export class RoomStore {
action: "rotate" | "revoke",
hostToken: string,
): ViewerGrantUpdate {
+ this.ensureInitialized();
const room = this.getHostManagedRoom(roomId, hostToken);
const previousViewerAuthorizationGeneration =
room.viewerAuthorizationGeneration;
@@ -407,6 +482,12 @@ export class RoomStore {
? digest(viewerGrant)
: this.randomDigest();
const viewerAuthorizationGeneration = this.newAuthorizationGeneration();
+ this.options.database?.setViewerGrant(
+ roomId,
+ room.hostTokenDigest,
+ viewerGrantDigest,
+ viewerAuthorizationGeneration,
+ );
room.viewerGrantDigest = viewerGrantDigest;
room.viewerAuthorizationGeneration = viewerAuthorizationGeneration;
for (const [clientId, viewer] of room.viewers) {
@@ -427,6 +508,7 @@ export class RoomStore {
peerId: string,
sessionId: string,
): DisconnectedParticipant | undefined {
+ this.ensureInitialized();
const room = this.rooms.get(roomId);
if (!room) {
return undefined;
@@ -436,9 +518,15 @@ export class RoomStore {
if (room.host.sessionId !== sessionId) {
return undefined;
}
+ const leaseExpiresAtMs = this.leaseDeadline(this.now());
+ this.options.database?.setLeaseDeadline(
+ roomId,
+ room.hostTokenDigest,
+ leaseExpiresAtMs,
+ );
room.host.sessionId = undefined;
room.sharingActive = false;
- room.leaseExpiresAtMs = this.now() + this.options.leaseMs;
+ room.leaseExpiresAtMs = leaseExpiresAtMs;
return { roomId, role: "host", peerId };
}
@@ -493,22 +581,26 @@ export class RoomStore {
}
abandonRoom(roomId: string): ClosedRoom | undefined {
+ this.ensureInitialized();
const room = this.rooms.get(roomId);
if (!room) {
return undefined;
}
const sessionIds = connectedSessionIds(room);
+ this.options.database?.deleteRoom(roomId, room.hostTokenDigest);
this.rooms.delete(roomId);
this.releaseRoomCode(roomId);
return { roomId, sessionIds };
}
expireRooms(nowMs = this.now()): ClosedRoom[] {
+ this.ensureInitialized();
const expired: ClosedRoom[] = [];
for (const [roomId, room] of this.rooms) {
if (!roomIsExpired(room, nowMs)) {
continue;
}
+ this.options.database?.deleteRoom(roomId, room.hostTokenDigest);
expired.push({ roomId, sessionIds: connectedSessionIds(room) });
this.rooms.delete(roomId);
this.releaseRoomCode(roomId);
@@ -521,7 +613,7 @@ export class RoomStore {
}
close(): void {
- // Room state is process-memory only and disappears with the process.
+ this.options.database?.close();
}
private connectHost(
@@ -542,6 +634,11 @@ export class RoomStore {
}
: current;
const replacedSessionId = participant.sessionId;
+ this.options.database?.setLeaseDeadline(
+ room.roomId,
+ room.hostTokenDigest,
+ null,
+ );
participant.sessionId = input.sessionId;
room.host = participant;
room.sharingActive = true;
@@ -740,6 +837,32 @@ export class RoomStore {
}
return value.toString("base64url");
}
+
+ private leaseDeadline(nowMs: number): number {
+ const deadline = nowMs + this.options.leaseMs;
+ if (!Number.isSafeInteger(deadline) || deadline <= nowMs) {
+ throw new Error("Room lease deadline exceeds the supported time range");
+ }
+ return deadline;
+ }
+
+ private ensureInitialized(): void {
+ if (!this.initialized) {
+ throw new Error("RoomStore stable authority is not initialized");
+ }
+ }
+}
+
+function storedRoomAuthority(room: Room): StoredRoomAuthority {
+ return {
+ roomId: room.roomId,
+ hostTokenDigest: room.hostTokenDigest,
+ viewerGrantDigest: room.viewerGrantDigest,
+ viewerAuthorizationGeneration: room.viewerAuthorizationGeneration,
+ codeEntryPolicy: room.codeEntryPolicy,
+ viewerPasswordMaterial: room.viewerPasswordMaterial,
+ leaseExpiresAtMs: room.leaseExpiresAtMs,
+ };
}
function roomIsExpired(room: Room, nowMs: number): boolean {
diff --git a/tests/room-database.test.ts b/tests/room-database.test.ts
new file mode 100644
index 00000000..096722f8
--- /dev/null
+++ b/tests/room-database.test.ts
@@ -0,0 +1,337 @@
+import { createHash } from "node:crypto";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { DatabaseSync } from "node:sqlite";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import { RoomDatabase } from "../src/server/room-database.ts";
+import { RoomStore, RoomStoreError } from "../src/server/room-store.ts";
+
+interface MutableClock {
+ nowMs: number;
+}
+
+const temporaryDirectories: string[] = [];
+const stores: RoomStore[] = [];
+
+afterEach(() => {
+ for (const store of stores.splice(0).reverse()) {
+ store.close();
+ }
+ for (const directory of temporaryDirectories.splice(0).reverse()) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+function databasePath(): string {
+ const directory = mkdtempSync(join(tmpdir(), "screener-room-db-"));
+ temporaryDirectories.push(directory);
+ return join(directory, "rooms.sqlite");
+}
+
+function stableStore(
+ path: string,
+ clock: MutableClock,
+ options: { maxRooms?: number; leaseMs?: number } = {},
+): RoomStore {
+ const store = new RoomStore({
+ leaseMs: options.leaseMs ?? 1_000,
+ maxRooms: options.maxRooms ?? 8,
+ maxViewersPerRoom: 8,
+ now: () => clock.nowMs,
+ database: new RoomDatabase(path),
+ });
+ store.initialize();
+ stores.push(store);
+ return store;
+}
+
+function hostInput(
+ roomId: string,
+ hostToken: string,
+ sessionId = "host-session",
+) {
+ return {
+ roomId,
+ role: "host" as const,
+ token: hostToken,
+ clientId: "host-client",
+ sessionId,
+ };
+}
+
+function viewerInput(
+ roomId: string,
+ sessionId: string,
+ viewerGrant?: string,
+) {
+ return {
+ roomId,
+ role: "viewer" as const,
+ ...(viewerGrant ? { viewerGrant } : {}),
+ clientId: `client-${sessionId}`,
+ sessionId,
+ };
+}
+
+function closeStore(store: RoomStore): void {
+ store.close();
+ const index = stores.indexOf(store);
+ if (index >= 0) {
+ stores.splice(index, 1);
+ }
+}
+
+describe("SQLite stable room authority", () => {
+ it("restores the exact authority aggregate without participants", async () => {
+ const path = databasePath();
+ const clock = { nowMs: 1_000 };
+ const first = stableStore(path, clock);
+ const room = await first.createRoom("open", null, "4321");
+ first.setCodeEntryPolicy(room.roomId, "private", room.hostToken);
+ await first.setViewerPassword(
+ room.roomId,
+ "room-password",
+ room.hostToken,
+ );
+ const rotated = first.setViewerGrant(
+ room.roomId,
+ "rotate",
+ room.hostToken,
+ );
+ const host = first.connectParticipant(
+ hostInput(room.roomId, room.hostToken),
+ );
+ const oldViewer = first.connectParticipant(
+ viewerInput(room.roomId, "old-viewer", rotated.viewerGrant!),
+ );
+ expect(first.getConnectedHost(room.roomId)).toMatchObject({
+ peerId: host.peerId,
+ });
+ expect(first.getConnectedViewer(room.roomId, oldViewer.peerId)).toBeDefined();
+ closeStore(first);
+
+ clock.nowMs = 2_000;
+ const second = stableStore(path, clock);
+ expect(second.size).toBe(1);
+ expect(second.getConnectedHost(room.roomId)).toBeUndefined();
+ expect(second.getConnectedViewers(room.roomId)).toEqual([]);
+ expect(() =>
+ second.connectParticipant(
+ viewerInput(room.roomId, "revoked-grant", room.viewerGrant!),
+ ),
+ ).toThrow(new RoomStoreError("INVALID_TOKEN"));
+
+ const granted = second.connectParticipant(
+ viewerInput(room.roomId, "current-grant", rotated.viewerGrant!),
+ );
+ expect(granted.expiresAt).toBe(new Date(3_000).toISOString());
+ expect(granted.viewerAuthorizationGeneration).toBe(
+ rotated.viewerAuthorizationGeneration,
+ );
+ await expect(
+ second.connectViewerWithPassword({
+ roomId: room.roomId,
+ password: "room-password",
+ clientId: "password-client",
+ sessionId: "password-session",
+ }),
+ ).resolves.toMatchObject({ codeEntryPolicy: "private" });
+ expect(() =>
+ second.connectParticipant(hostInput(room.roomId, "wrong-token")),
+ ).toThrow(new RoomStoreError("INVALID_TOKEN"));
+ expect(
+ second.connectParticipant(
+ hostInput(room.roomId, room.hostToken, "recovered-host"),
+ ).expiresAt,
+ ).toBeNull();
+ closeStore(second);
+
+ const raw = new DatabaseSync(path);
+ try {
+ const row = raw.prepare("SELECT * FROM rooms").get() as Record<
+ string,
+ unknown
+ >;
+ expect(Object.keys(row).sort()).toEqual(
+ [
+ "room_id",
+ "host_token_digest",
+ "viewer_grant_digest",
+ "viewer_authorization_generation",
+ "code_entry_policy",
+ "viewer_password_material",
+ "lease_expires_at_ms",
+ ].sort(),
+ );
+ expect(Buffer.from(row.host_token_digest as Uint8Array)).toEqual(
+ createHash("sha256").update(room.hostToken).digest(),
+ );
+ expect(Buffer.from(row.viewer_grant_digest as Uint8Array)).toEqual(
+ createHash("sha256").update(rotated.viewerGrant!).digest(),
+ );
+ expect(row.viewer_password_material).toBeInstanceOf(Uint8Array);
+ expect(Buffer.from(row.viewer_password_material as Uint8Array)).toHaveLength(
+ 48,
+ );
+ expect(JSON.stringify(row)).not.toContain(room.hostToken);
+ expect(JSON.stringify(row)).not.toContain(rotated.viewerGrant!);
+ expect(JSON.stringify(row)).not.toContain("room-password");
+ } finally {
+ raw.close();
+ }
+ });
+
+ it("converts an active marker once and preserves dormant deadlines", async () => {
+ const path = databasePath();
+ const clock = { nowMs: 100 };
+ const first = stableStore(path, clock);
+ const room = await first.createRoom("open", null, "5678");
+ first.connectParticipant(hostInput(room.roomId, room.hostToken));
+ closeStore(first);
+
+ clock.nowMs = 500;
+ const second = stableStore(path, clock);
+ const firstRestart = second.connectParticipant(
+ viewerInput(room.roomId, "first-restart", room.viewerGrant!),
+ );
+ expect(firstRestart.expiresAt).toBe(new Date(1_500).toISOString());
+ closeStore(second);
+
+ clock.nowMs = 700;
+ const third = stableStore(path, clock);
+ const secondRestart = third.connectParticipant(
+ viewerInput(room.roomId, "second-restart", room.viewerGrant!),
+ );
+ expect(secondRestart.expiresAt).toBe(new Date(1_500).toISOString());
+ closeStore(third);
+
+ clock.nowMs = 1_501;
+ const fourth = stableStore(path, clock);
+ expect(fourth.size).toBe(0);
+ const replacement = await fourth.createRoom("open", null, room.roomId);
+ expect(replacement.roomId).toBe(room.roomId);
+ expect(() =>
+ fourth.connectParticipant(hostInput(room.roomId, room.hostToken)),
+ ).toThrow(new RoomStoreError("INVALID_TOKEN"));
+ expect(() =>
+ fourth.connectParticipant(
+ viewerInput(room.roomId, "stale-grant", room.viewerGrant!),
+ ),
+ ).toThrow(new RoomStoreError("INVALID_TOKEN"));
+ });
+
+ it("preserves the exact Host disconnect deadline", async () => {
+ const path = databasePath();
+ const clock = { nowMs: 100 };
+ const first = stableStore(path, clock);
+ const room = await first.createRoom("open", null, "5890");
+ const host = first.connectParticipant(
+ hostInput(room.roomId, room.hostToken),
+ );
+ clock.nowMs = 250;
+ first.disconnectParticipant(room.roomId, host.peerId, "host-session");
+ closeStore(first);
+
+ clock.nowMs = 500;
+ const second = stableStore(path, clock);
+ expect(
+ second.connectParticipant(
+ viewerInput(room.roomId, "dormant-viewer", room.viewerGrant!),
+ ).expiresAt,
+ ).toBe(new Date(1_250).toISOString());
+ });
+
+ it("persists explicit room deletion before recycling its code", async () => {
+ const path = databasePath();
+ const clock = { nowMs: 10 };
+ const first = stableStore(path, clock);
+ const room = await first.createRoom("open", null, "6789");
+ expect(first.abandonRoom(room.roomId)?.roomId).toBe(room.roomId);
+ closeStore(first);
+
+ const second = stableStore(path, clock);
+ expect(second.size).toBe(0);
+ const replacement = await second.createRoom("open", null, room.roomId);
+ expect(replacement.roomId).toBe(room.roomId);
+ expect(replacement.hostToken).not.toBe(room.hostToken);
+ expect(replacement.viewerGrant).not.toBe(room.viewerGrant);
+ });
+
+ it("rejects another owner of the same database", () => {
+ const path = databasePath();
+ const first = new RoomDatabase(path);
+ first.initialize(0, 1_000);
+ try {
+ const contender = new RoomDatabase(path);
+ expect(() => contender.initialize(0, 1_000)).toThrow(/locked/i);
+ contender.close();
+ } finally {
+ first.close();
+ }
+
+ const successor = new RoomDatabase(path);
+ expect(successor.initialize(0, 1_000)).toEqual([]);
+ successor.close();
+ });
+
+ it.each([
+ ["application identity", "PRAGMA application_id = 1"],
+ ["schema version", "PRAGMA user_version = 2"],
+ ])("rejects an unknown %s", (_name, mutation) => {
+ const path = databasePath();
+ const initial = new RoomDatabase(path);
+ initial.initialize(0, 1_000);
+ initial.close();
+
+ const raw = new DatabaseSync(path);
+ raw.exec(mutation);
+ raw.close();
+
+ const reopened = new RoomDatabase(path);
+ expect(() => reopened.initialize(0, 1_000)).toThrow(/does not match/);
+ reopened.close();
+ });
+
+ it("rejects an altered current-version schema", () => {
+ const path = databasePath();
+ const initial = new RoomDatabase(path);
+ initial.initialize(0, 1_000);
+ initial.close();
+
+ const raw = new DatabaseSync(path);
+ raw.exec("ALTER TABLE rooms ADD COLUMN unexpected TEXT");
+ raw.close();
+
+ const reopened = new RoomDatabase(path);
+ expect(() => reopened.initialize(0, 1_000)).toThrow(
+ "Room database columns do not match the current schema",
+ );
+ reopened.close();
+ });
+
+ it("rejects corrupt authority rows instead of partially restoring them", async () => {
+ const path = databasePath();
+ const clock = { nowMs: 100 };
+ const initial = stableStore(path, clock);
+ await initial.createRoom("open", null, "7890");
+ closeStore(initial);
+
+ const raw = new DatabaseSync(path);
+ raw.exec("PRAGMA ignore_check_constraints = ON");
+ raw.prepare("UPDATE rooms SET host_token_digest = zeroblob(31)").run();
+ raw.close();
+
+ const reopened = new RoomStore({
+ leaseMs: 1_000,
+ maxRooms: 8,
+ maxViewersPerRoom: 8,
+ now: () => clock.nowMs,
+ database: new RoomDatabase(path),
+ });
+ expect(() => reopened.initialize()).toThrow(/integrity|Host token/i);
+ reopened.close();
+ });
+});
diff --git a/tests/server-config.test.ts b/tests/server-config.test.ts
index 89c5d6c8..dd3e5e02 100644
--- a/tests/server-config.test.ts
+++ b/tests/server-config.test.ts
@@ -1,3 +1,5 @@
+import { resolve } from "node:path";
+
import { describe, expect, it } from "vitest";
import { MAX_VIEWERS_PER_ROOM_LIMIT } from "../src/shared/protocol.ts";
@@ -14,6 +16,7 @@ describe("server configuration", () => {
expect(config.listenHost).toBe("0.0.0.0");
expect(config.publicBaseUrl.href).toBe("http://localhost:9123/");
expect(config.allowedOrigins).toEqual(new Set(["http://localhost:9123"]));
+ expect(config.roomDatabasePath).toBeUndefined();
expect(config.stunUrls).toEqual([]);
expect(config.maxViewersPerRoom).toBe(8);
expect(config.peerAssistedMedia).toBe(false);
@@ -401,15 +404,40 @@ describe("server configuration", () => {
);
});
- it.each(["ROOM_DATABASE_PATH", "ROOM_TTL_SECONDS"] as const)(
- "rejects removed room persistence configuration even when %s is blank",
- (name) => {
- expect(() => loadConfig({ [name]: "" })).toThrow(
- `${name} is no longer supported`,
- );
+ it("accepts optional file-backed room authority in development and production", () => {
+ const developmentPath = resolve("state", "rooms.sqlite");
+ expect(
+ loadConfig({ ROOM_DATABASE_PATH: ` ${developmentPath} ` })
+ .roomDatabasePath,
+ ).toBe(developmentPath);
+ expect(loadConfig({ ROOM_DATABASE_PATH: "" }).roomDatabasePath).toBeUndefined();
+ const productionPath = resolve("production-state", "rooms.sqlite");
+ expect(
+ loadConfig({
+ NODE_ENV: "production",
+ PUBLIC_BASE_URL: "https://share.test",
+ SITE_ACCESS_PASSWORD: "host-password-12",
+ STUN_URLS: "stun:stun.test:3478",
+ ROOM_DATABASE_PATH: productionPath,
+ }).roomDatabasePath,
+ ).toBe(productionPath);
+ });
+
+ it.each([":memory:", "rooms\0.sqlite", "rooms.sqlite", "./state/rooms.sqlite"])(
+ "rejects a non-absolute room database path",
+ (roomDatabasePath) => {
+ expect(() =>
+ loadConfig({ ROOM_DATABASE_PATH: roomDatabasePath }),
+ ).toThrow("ROOM_DATABASE_PATH must be an absolute file path");
},
);
+ it("rejects the removed room TTL configuration", () => {
+ expect(() => loadConfig({ ROOM_TTL_SECONDS: "" })).toThrow(
+ "ROOM_TTL_SECONDS is no longer supported; use ROOM_LEASE_SECONDS",
+ );
+ });
+
it.each(["x".repeat(7), "密码密码密码密码", "contains spaces", "x".repeat(129)])(
"rejects a site access password outside the visible ASCII boundary",
(siteAccessPassword) => {
diff --git a/tests/server-http.test.ts b/tests/server-http.test.ts
index 42c2f79b..73abe274 100644
--- a/tests/server-http.test.ts
+++ b/tests/server-http.test.ts
@@ -1,3 +1,8 @@
+import { existsSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { DatabaseSync } from "node:sqlite";
+
import { afterEach, describe, expect, it, vi } from "vitest";
import {
@@ -17,11 +22,24 @@ import { FakeSfuRoomControl } from "./fake-sfu-room-control.ts";
const allowedOrigin = "http://allowed.test";
const siteAccessPassword = "instance-access-password";
let runningServer: ScreenerServer | undefined;
+const temporaryDirectories: string[] = [];
afterEach(async () => {
- await runningServer?.close();
- runningServer = undefined;
+ try {
+ await runningServer?.close();
+ runningServer = undefined;
+ } finally {
+ for (const directory of temporaryDirectories.splice(0).reverse()) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+ }
});
+function temporaryRoomDatabasePath(): string {
+ const directory = mkdtempSync(join(tmpdir(), "screener-server-room-db-"));
+ temporaryDirectories.push(directory);
+ return join(directory, "rooms.sqlite");
+}
+
function testConfig(overrides: Partial<ServerConfig> = {}): ServerConfig {
return {
nodeEnv: "test",
@@ -579,6 +597,54 @@ describe("room HTTP API", () => {
});
describe("server HTTP listener and health", () => {
+ it("restores stable room authority across an application restart", async () => {
+ const roomDatabasePath = temporaryRoomDatabasePath();
+ let nowMs = 100;
+ const config = testConfig({
+ siteAccessPassword: undefined,
+ roomDatabasePath,
+ roomLeaseMs: 1_000,
+ });
+ const first = await createScreenerServer({
+ config,
+ serveFrontend: false,
+ now: () => nowMs,
+ });
+ let second: ScreenerServer | undefined;
+ try {
+ const firstPort = await first.listen(0, "127.0.0.1");
+ const created = createRoomResponseSchema.parse(
+ await (
+ await createRoom(`http://127.0.0.1:${firstPort}`, undefined, "private")
+ ).json(),
+ );
+ await first.close();
+
+ nowMs = 200;
+ second = await createScreenerServer({
+ config,
+ serveFrontend: false,
+ now: () => nowMs,
+ });
+ const secondPort = await second.listen(0, "127.0.0.1");
+ expect(second.roomStore.size).toBe(1);
+ const update = await updateRoomAccess(
+ `http://127.0.0.1:${secondPort}`,
+ created.roomId,
+ created.hostToken,
+ { action: "set-code-entry-policy", policy: "open" },
+ );
+ expect(update.status).toBe(200);
+ expect(await update.json()).toMatchObject({
+ type: "code-entry-policy-updated",
+ codeEntryPolicy: "open",
+ });
+ } finally {
+ await second?.close();
+ await first.close();
+ }
+ });
+
it("starts with an injected optional SFU token issuer", async () => {
const baseUrl = await start(
testConfig({
@@ -684,9 +750,15 @@ describe("server HTTP listener and health", () => {
serveFrontend: false,
});
const ownerPort = await owner.listen(0, "127.0.0.1");
+ const unavailableDatabasePath = join(
+ temporaryRoomDatabasePath(),
+ "missing-parent",
+ "rooms.sqlite",
+ );
const roomControl = new FakeSfuRoomControl();
const contender = await createScreenerServer({
config: testConfig({
+ roomDatabasePath: unavailableDatabasePath,
peerAssistedMedia: true,
livekitFallback: {
url: "ws://livekit.test:7880",
@@ -707,12 +779,116 @@ describe("server HTTP listener and health", () => {
code: "EADDRINUSE",
});
expect(roomControl.initializeCalls).toBe(0);
+ expect(existsSync(unavailableDatabasePath)).toBe(false);
} finally {
await contender.close();
await owner.close();
}
});
+ it("rejects a second database owner before LiveKit reconciliation", async () => {
+ const roomDatabasePath = temporaryRoomDatabasePath();
+ const owner = await createScreenerServer({
+ config: testConfig({ roomDatabasePath }),
+ serveFrontend: false,
+ });
+ await owner.listen(0, "127.0.0.1");
+ const roomControl = new FakeSfuRoomControl();
+ const contender = await createScreenerServer({
+ config: testConfig({
+ roomDatabasePath,
+ peerAssistedMedia: true,
+ livekitFallback: {
+ url: "ws://livekit.test:7880",
+ apiUrl: "http://127.0.0.1:7880",
+ apiKey: "test-key",
+ apiSecret: "s".repeat(32),
+ },
+ }),
+ serveFrontend: false,
+ sfuRoomControl: roomControl,
+ sfuTokenIssuer: {
+ issueToken: async () => "unused-test-token",
+ },
+ });
+
+ try {
+ await expect(contender.listen(0, "127.0.0.1")).rejects.toThrow(
+ /locked/i,
+ );
+ expect(roomControl.initializeCalls).toBe(0);
+ expect(contender.httpServer.listening).toBe(false);
+ expect(contender.httpServer.listenerCount("upgrade")).toBe(0);
+ } finally {
+ await contender.close();
+ await owner.close();
+ }
+ });
+
+ it("rejects a mismatched database before LiveKit reconciliation", async () => {
+ const roomDatabasePath = temporaryRoomDatabasePath();
+ const raw = new DatabaseSync(roomDatabasePath);
+ raw.exec("CREATE TABLE unrelated(value TEXT) STRICT");
+ raw.close();
+ const roomControl = new FakeSfuRoomControl();
+ runningServer = await createScreenerServer({
+ config: testConfig({
+ roomDatabasePath,
+ peerAssistedMedia: true,
+ livekitFallback: {
+ url: "ws://livekit.test:7880",
+ apiUrl: "http://127.0.0.1:7880",
+ apiKey: "test-key",
+ apiSecret: "s".repeat(32),
+ },
+ }),
+ serveFrontend: false,
+ sfuRoomControl: roomControl,
+ sfuTokenIssuer: {
+ issueToken: async () => "unused-test-token",
+ },
+ });
+
+ await expect(runningServer.listen(0, "127.0.0.1")).rejects.toThrow(
+ "Room database application identity does not match",
+ );
+ expect(roomControl.initializeCalls).toBe(0);
+ expect(runningServer.httpServer.listening).toBe(false);
+ expect(runningServer.httpServer.listenerCount("upgrade")).toBe(0);
+ });
+
+ it("rejects an inaccessible database path before LiveKit reconciliation", async () => {
+ const roomDatabasePath = join(
+ temporaryRoomDatabasePath(),
+ "missing-parent",
+ "rooms.sqlite",
+ );
+ const roomControl = new FakeSfuRoomControl();
+ runningServer = await createScreenerServer({
+ config: testConfig({
+ roomDatabasePath,
+ peerAssistedMedia: true,
+ livekitFallback: {
+ url: "ws://livekit.test:7880",
+ apiUrl: "http://127.0.0.1:7880",
+ apiKey: "test-key",
+ apiSecret: "s".repeat(32),
+ },
+ }),
+ serveFrontend: false,
+ sfuRoomControl: roomControl,
+ sfuTokenIssuer: {
+ issueToken: async () => "unused-test-token",
+ },
+ });
+
+ await expect(runningServer.listen(0, "127.0.0.1")).rejects.toThrow();
+ expect(roomControl.initializeCalls).toBe(0);
+ expect(existsSync(roomDatabasePath)).toBe(false);
+ expect(runningServer.httpServer.listening).toBe(false);
+ expect(runningServer.httpServer.listenerCount("upgrade")).toBe(0);
+ });
+
it("holds listener ownership until an in-flight startup reconciliation settles", async () => {
let releaseInitialization!: () => void;
const roomControl = new FakeSfuRoomControl();