Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
refactor(access): separate password derivation outcomes (#281)
AAAe31e6250fcfe
diff --git a/src/server/app.ts b/src/server/app.tsindex f68e4163..93258a3d 100644--- a/src/server/app.ts+++ b/src/server/app.ts@@ -397,7 +397,7 @@ async function handleRequest(}if (error instanceof RoomStoreError &&- error.code === "ROOM_ACCESS_DENIED"+ (error.code === "ROOM_ACCESS_DENIED" || error.code === "ROOM_BUSY")) {sendJson(response, 503, { error: "Room replacement unavailable" });return;@@ -467,6 +467,10 @@ async function handleRequest(),);} catch (error) {+ if (error instanceof RoomStoreError && error.code === "ROOM_BUSY") {+ sendJson(response, 503, { error: "Room access update unavailable" });+ return;+ }if (error instanceof RoomStoreError &&error.code === "ROOM_ACCESS_DENIED"@@ -536,6 +540,10 @@ async function handleRequest(sendJson(response, 503, { error: "Room capacity reached" });return;}+ if (error instanceof RoomStoreError && error.code === "ROOM_BUSY") {+ sendJson(response, 503, { error: "Room creation unavailable" });+ return;+ }if (error instanceof RoomStoreError && error.code === "INVALID_TOKEN") {sendJson(response, 400, { error: "Invalid room request" });return;diff --git a/src/server/room-store.ts b/src/server/room-store.tsindex 690365b8..81f35ea3 100644--- a/src/server/room-store.ts+++ b/src/server/room-store.ts@@ -20,6 +20,7 @@ import {export type RoomStoreErrorCode =| "INVALID_TOKEN"| "ROOM_ACCESS_DENIED"+ | "ROOM_BUSY"| "ROOM_NOT_FOUND"| "ROOM_EXPIRED"| "ROOM_FULL"@@ -44,6 +45,11 @@ const DUMMY_VIEWER_PASSWORD_MATERIAL = Buffer.alloc(VIEWER_PASSWORD_MATERIAL_BYTES,);+type AsyncGateOutcome<T> =+ | { kind: "value"; value: T }+ | { kind: "busy" }+ | { kind: "cancelled" };+export class RoomStoreError extends Error {constructor(public readonly code: RoomStoreErrorCode) {super(code);@@ -260,12 +266,20 @@ export class RoomStore {}const createdAtMs = this.now();const leaseExpiresAtMs = this.leaseDeadline(createdAtMs);- const viewerPasswordMaterial = roomPassword+ const passwordOutcome = roomPassword? await this.createViewerPasswordMaterial(roomPassword): null;if (this.rooms.size >= this.options.maxRooms) {throw new RoomStoreError("ROOM_LIMIT");}+ if (passwordOutcome?.kind === "busy") {+ throw new RoomStoreError("ROOM_BUSY");+ }+ if (passwordOutcome?.kind === "cancelled") {+ throw new Error("Room creation password derivation was cancelled");+ }+ const viewerPasswordMaterial =+ passwordOutcome?.kind === "value" ? passwordOutcome.value : null;const roomId = this.takeRoomCode(preferredRoomId);try {const { room, created } = this.newRoom(@@ -291,7 +305,7 @@ export class RoomStore {): Promise<ReplacedRoom> {this.ensureInitialized();const current = this.getHostManagedRoom(roomId, hostToken);- const viewerPasswordMaterial = roomPassword+ const passwordOutcome = roomPassword? await this.createViewerPasswordMaterial(roomPassword, () => {const room = this.rooms.get(roomId);return (@@ -301,9 +315,14 @@ export class RoomStore {}): null;const owned = this.getHostManagedRoom(roomId, hostToken);- if (owned !== current || (roomPassword && !viewerPasswordMaterial)) {+ if (owned !== current || passwordOutcome?.kind === "cancelled") {throw new RoomStoreError("ROOM_ACCESS_DENIED");}+ if (passwordOutcome?.kind === "busy") {+ throw new RoomStoreError("ROOM_BUSY");+ }+ const viewerPasswordMaterial =+ passwordOutcome?.kind === "value" ? passwordOutcome.value : null;const replacementRoomId = this.takeRoomCode();try {@@ -408,10 +427,10 @@ export class RoomStore {expectedSalt,mayConnect,);- if (derived === null) {+ if (derived.kind !== "value") {throw new RoomStoreError("INVALID_TOKEN");}- const matches = timingSafeEqual(derived, expectedVerifier);+ const matches = timingSafeEqual(derived.value, expectedVerifier);let currentRoom: Room;try {@@ -451,7 +470,7 @@ export class RoomStore {this.ensureInitialized();const room = this.getHostManagedRoom(roomId, hostToken);- const nextPasswordMaterial = password+ const passwordOutcome = password? await this.createViewerPasswordMaterial(password, () => {const currentRoom = this.rooms.get(roomId);return (@@ -462,12 +481,14 @@ export class RoomStore {: null;const currentRoom = this.getHostManagedRoom(roomId, hostToken);- if (- currentRoom !== room ||- (password !== null && nextPasswordMaterial === null)- ) {+ if (currentRoom !== room || passwordOutcome?.kind === "cancelled") {throw new RoomStoreError("ROOM_ACCESS_DENIED");}+ if (passwordOutcome?.kind === "busy") {+ throw new RoomStoreError("ROOM_BUSY");+ }+ const nextPasswordMaterial =+ passwordOutcome?.kind === "value" ? passwordOutcome.value : null;this.options.database?.setViewerPassword(roomId,currentRoom.hostTokenDigest,@@ -878,7 +899,7 @@ export class RoomStore {private async createViewerPasswordMaterial(password: string,mayStart: () => boolean = () => true,- ): Promise<Buffer | null> {+ ): Promise<AsyncGateOutcome<Buffer>> {if (!viewerPasswordSchema.safeParse(password).success) {throw new RoomStoreError("INVALID_TOKEN");}@@ -887,7 +908,9 @@ export class RoomStore {throw new Error("Viewer password salt source must return 16 bytes");}const verifier = await deriveViewerPassword(password, salt, mayStart);- return verifier && Buffer.concat([salt, verifier]);+ return verifier.kind === "value"+ ? { kind: "value", value: Buffer.concat([salt, verifier.value]) }+ : verifier;}private randomDigest(): Buffer {@@ -980,7 +1003,7 @@ function deriveViewerPassword(password: string,salt: Buffer,mayStart: () => boolean = () => true,-): Promise<Buffer | null> {+): Promise<AsyncGateOutcome<Buffer>> {return viewerPasswordKdfGate.run(() =>new Promise<Buffer>((resolve, reject) => {@@ -1009,12 +1032,15 @@ class AsyncGate {async run<T>(task: () => Promise<T>,mayStart: () => boolean,- ): Promise<T | null> {+ ): Promise<AsyncGateOutcome<T>> {if (!(await this.acquire())) {- return null;+ return { kind: "busy" };}try {- return mayStart() ? await task() : null;+ if (!mayStart()) {+ return { kind: "cancelled" };+ }+ return { kind: "value", value: await task() };} finally {this.release();}diff --git a/src/server/signaling.ts b/src/server/signaling.tsindex 1ff17dbb..5147e1fc 100644--- a/src/server/signaling.ts+++ b/src/server/signaling.ts@@ -2069,6 +2069,9 @@ function authenticationErrorCode(if (!(error instanceof RoomStoreError) || error.code === "ROOM_LIMIT") {return "SERVER_ERROR";}+ if (error.code === "ROOM_BUSY") {+ return message.role === "viewer" ? "ROOM_ACCESS_DENIED" : "SERVER_ERROR";+ }if (message.role !== "viewer") {return error.code;}diff --git a/tests/room-database.test.ts b/tests/room-database.test.tsindex 741a9f26..cf7bb36e 100644--- a/tests/room-database.test.ts+++ b/tests/room-database.test.ts@@ -85,6 +85,38 @@ function closeStore(store: RoomStore): void {}describe("SQLite stable room authority", () => {+ it("does not persist a room when password derivation is busy", async () => {+ const path = databasePath();+ const clock = { nowMs: 1_000 };+ const first = stableStore(path, clock, { maxRooms: 1 });+ const attempts = Array.from({ length: 18 }, (_, index) =>+ first.connectViewerWithPassword(+ {+ roomId: "9999",+ password: "gate-password",+ clientId: `gate-client-${index}`,+ sessionId: `gate-session-${index}`,+ },+ () => index < 2,+ ),+ );+ try {+ await expect(+ first.createRoom("private", "room-password", "4321"),+ ).rejects.toEqual(new RoomStoreError("ROOM_BUSY"));+ } finally {+ await Promise.allSettled(attempts);+ }+ expect(first.size).toBe(0);+ closeStore(first);++ const second = stableStore(path, clock, { maxRooms: 1 });+ expect(second.size).toBe(0);+ expect((await second.createRoom("private", null, "4321")).roomId).toBe(+ "4321",+ );+ });+it("restores the exact authority aggregate without participants", async () => {const path = databasePath();const clock = { nowMs: 1_000 };diff --git a/tests/room-store.test.ts b/tests/room-store.test.tsindex 7d9b23ac..e8a201ed 100644--- a/tests/room-store.test.ts+++ b/tests/room-store.test.ts@@ -53,6 +53,28 @@ function expectRoomError(run: () => unknown, code: string) {expect(run).toThrow(new RoomStoreError(code as never));}+async function withSaturatedPasswordGate<Result>(+ roomStore: RoomStore,+ operation: () => Promise<Result>,+): Promise<Result> {+ const attempts = Array.from({ length: 18 }, (_, index) =>+ roomStore.connectViewerWithPassword(+ {+ roomId: "9999",+ password: "gate-password",+ clientId: `gate-client-${index}`,+ sessionId: `gate-session-${index}`,+ },+ () => index < 2,+ ),+ );+ try {+ return await operation();+ } finally {+ await Promise.allSettled(attempts);+ }+}+describe("RoomStore", () => {it("allocates every free four-digit room code and recycles releases", async () => {const { store: roomStore } = store({@@ -314,6 +336,69 @@ describe("RoomStore", () => {).toMatchObject({ role: "viewer" });});+ it("does not create a passwordless room when the password gate is busy", async () => {+ const { store: roomStore } = store({ maxRooms: 1 });++ await expect(+ withSaturatedPasswordGate(roomStore, () =>+ roomStore.createRoom("private", "room-password", "4321"),+ ),+ ).rejects.toEqual(new RoomStoreError("ROOM_BUSY"));+ expect(roomStore.size).toBe(0);+ expect((await roomStore.createRoom("private", null, "4321")).roomId).toBe(+ "4321",+ );+ });++ it("keeps room replacement and password updates unchanged when busy", async () => {+ const { store: roomStore } = store({+ maxRooms: 3,+ });+ const room = await roomStore.createRoom(+ "private",+ "old-password",+ "4321",+ );++ await expect(+ withSaturatedPasswordGate(roomStore, () =>+ roomStore.replaceRoom(+ room.roomId,+ room.hostToken,+ "private",+ "replacement-password",+ ),+ ),+ ).rejects.toEqual(new RoomStoreError("ROOM_BUSY"));+ expect(roomStore.size).toBe(1);+ await expect(+ roomStore.connectViewerWithPassword({+ roomId: room.roomId,+ password: "old-password",+ clientId: "after-replacement-client",+ sessionId: "after-replacement-session",+ }),+ ).resolves.toMatchObject({ roomId: room.roomId });++ await expect(+ withSaturatedPasswordGate(roomStore, () =>+ roomStore.setViewerPassword(+ room.roomId,+ "updated-password",+ room.hostToken,+ ),+ ),+ ).rejects.toEqual(new RoomStoreError("ROOM_BUSY"));+ await expect(+ roomStore.connectViewerWithPassword({+ roomId: room.roomId,+ password: "old-password",+ clientId: "after-update-client",+ sessionId: "after-update-session",+ }),+ ).resolves.toMatchObject({ roomId: room.roomId });+ });+it("bounds password derivations and uses the same path for unknown rooms", async () => {const { store: roomStore } = store();let mayStartCalls = 0;@@ -348,6 +433,13 @@ describe("RoomStore", () => {result.reason.code === "ROOM_NOT_FOUND",),).toHaveLength(2);+ expect(+ results.filter(+ (result) =>+ result.status === "rejected" &&+ result.reason.code === "INVALID_TOKEN",+ ),+ ).toHaveLength(38);});it("rotates and revokes Viewer grants without changing code entry", async () => {diff --git a/tests/server-http.test.ts b/tests/server-http.test.tsindex 462cfaf1..5fc4e178 100644--- a/tests/server-http.test.ts+++ b/tests/server-http.test.ts@@ -522,6 +522,63 @@ describe("room HTTP API", () => {).toBe(original.roomId);});+ it("maps a busy password gate to 503 for every HTTP mutation", async () => {+ const config = testConfig();+ const roomStore = new RoomStore({+ leaseMs: config.roomLeaseMs,+ maxRooms: ROOM_CAPACITY,+ maxViewersPerRoom: config.maxViewersPerRoom,+ });+ const original = await roomStore.createRoom("private", "room-password");+ const baseUrl = await start(config, { roomStore });+ const cookie = cookiePair(await login(baseUrl));++ vi.spyOn(roomStore, "createRoom").mockRejectedValueOnce(+ new RoomStoreError("ROOM_BUSY"),+ );+ const creation = await createRoom(+ baseUrl,+ cookie,+ "private",+ "room-password",+ );+ expect(creation.status).toBe(503);+ expect(await creation.json()).toEqual({+ error: "Room creation unavailable",+ });++ vi.spyOn(roomStore, "replaceRoom").mockRejectedValueOnce(+ new RoomStoreError("ROOM_BUSY"),+ );+ const replacement = await replaceRoom(+ baseUrl,+ original.roomId,+ original.hostToken,+ { codeEntryPolicy: "private", roomPassword: "room-password" },+ cookie,+ );+ expect(replacement.status).toBe(503);+ expect(await replacement.json()).toEqual({+ error: "Room replacement unavailable",+ });++ vi.spyOn(roomStore, "setViewerPassword").mockRejectedValueOnce(+ new RoomStoreError("ROOM_BUSY"),+ );+ const update = await updateRoomAccess(+ baseUrl,+ original.roomId,+ original.hostToken,+ { action: "set-viewer-password", password: "room-password" },+ { cookie },+ );+ expect(update.status).toBe(503);+ expect(await update.json()).toEqual({+ error: "Room access update unavailable",+ });+ expect(roomStore.size).toBe(1);+ });+it("manages dormant room access without starting sharing or renewing", async () => {let nowMs = 0;const baseUrl = await start(