Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(community): close media/session gaps and recover billing deletion (#1055)
Gustavo Ye18f9141ad197
diff --git a/src/queue-worker/src/env.d.ts b/src/queue-worker/src/env.d.tsindex 58cdc15e4..fa3df95e9 100644--- a/src/queue-worker/src/env.d.ts+++ b/src/queue-worker/src/env.d.ts@@ -1,8 +1,9 @@/* eslint-disable */-// Generated by Wrangler by running `wrangler types --config=wrangler.toml --env-file=.dev.vars.example src/env.d.ts` (hash: e972cdaeeabdfd9fec81a85171f3b3db)+// Generated by Wrangler by running `wrangler types --config=wrangler.toml --env-file=.dev.vars.example src/env.d.ts` (hash: 09c716c2992d104e1ffc47d937aba26f)// Runtime types generated with [email protected] 2026-09-07 nodejs_compatinterface __BaseEnv_Env {DB: D1Database;+ TASK_QUEUE: Queue;ENCRYPTION_KEY: string;APNS_TEAM_ID: string;APNS_KEY_ID: string;diff --git a/src/queue-worker/src/index.ts b/src/queue-worker/src/index.tsindex e6642a064..d99018dd7 100644--- a/src/queue-worker/src/index.ts+++ b/src/queue-worker/src/index.ts@@ -19,7 +19,7 @@ function dedupeQueueTasks(tasks: AlookQueueTask[]): AlookQueueTask[] {const seen = new Set<string>()return tasks.filter((task) => {const recipientId = task.kind === "bot-wake" ? task.botUserId : task.userId- const key = JSON.stringify([task.kind, task.messageId, recipientId])+ const key = JSON.stringify([task.kind, task.messageId, recipientId, task.kind === "mobile-push" ? task.installationId : null])if (seen.has(key)) return falseseen.add(key)return truediff --git a/src/queue-worker/src/mobile-push.test.ts b/src/queue-worker/src/mobile-push.test.tsindex 9c28065b8..8be79905d 100644--- a/src/queue-worker/src/mobile-push.test.ts+++ b/src/queue-worker/src/mobile-push.test.ts@@ -29,6 +29,7 @@ const task = {kind: "mobile-push" as const,messageId: "message-1",userId: "user-1",+ installationId: "installation-ios",}type Eligibility = {@@ -99,6 +100,7 @@ function dependencies() {}const env = {+ TASK_QUEUE: { sendBatch: vi.fn(async () => undefined) },ENCRYPTION_KEY: "encryption-key",APNS_TEAM_ID: "apns-team",APNS_KEY_ID: "apns-key",@@ -107,7 +109,7 @@ const env = {FCM_PROJECT_ID: "fcm-project",FCM_CLIENT_EMAIL: "[email protected]",FCM_PRIVATE_KEY: "fcm-private-key",-} as Env+} as unknown as Envdescribe("mobile-push processing", () => {beforeEach(() => vi.clearAllMocks())@@ -132,15 +134,15 @@ describe("mobile-push processing", () => {expect(deps.listDevices).not.toHaveBeenCalled()})- it("attempts every active device independently and soft-disables an invalid token", async () => {+ it("sends only the selected device and soft-disables an invalid token", async () => {const deps = dependencies()await expect(processMobilePush({} as never, env, task, deps)).resolves.toEqual({- outcome: "processed",- attempted: 2,- sent: 1,- invalidated: 1,- failed: 0,+ outcome: "processed", attempted: 1, sent: 1, invalidated: 0,+ })+ expect(deps.sendFcm).not.toHaveBeenCalled()+ await expect(processMobilePush({} as never, env, { ...task, installationId: "installation-android" }, deps)).resolves.toEqual({+ outcome: "processed", attempted: 1, sent: 0, invalidated: 1,})expect(deps.decrypt).toHaveBeenCalledTimes(2)expect(deps.sendApns).toHaveBeenCalledWith(expect.objectContaining({@@ -158,7 +160,7 @@ describe("mobile-push processing", () => {})})- it("continues siblings and returns a caught failure without logging content or tokens", async () => {+ it("retries a failed device without sending to its sibling or logging content", async () => {const deps = dependencies()deps.sendApns.mockRejectedValue(new PushProviderError("apns",@@ -167,14 +169,8 @@ describe("mobile-push processing", () => {"sensitive-provider-reason",))- await expect(processMobilePush({} as never, env, task, deps)).resolves.toMatchObject({- outcome: "processed",- attempted: 2,- sent: 0,- invalidated: 1,- failed: 1,- })- expect(deps.sendFcm).toHaveBeenCalledTimes(1)+ await expect(processMobilePush({} as never, env, task, deps)).rejects.toThrow()+ expect(deps.sendFcm).not.toHaveBeenCalled()expect(mockLogWarn).toHaveBeenCalledWith("mobile_push_device_failed", {messageId: "message-1",deviceId: "device-ios",@@ -217,13 +213,7 @@ describe("mobile-push processing", () => {rawError.stack = "sensitive-decrypt-stack"deps.decrypt.mockImplementation(() => { throw rawError })- await expect(processMobilePush({} as never, env, task, deps)).resolves.toEqual({- outcome: "processed",- attempted: 1,- sent: 0,- invalidated: 0,- failed: 1,- })+ await expect(processMobilePush({} as never, env, task, deps)).rejects.toThrow()expect(mockLogWarn).toHaveBeenCalledWith("mobile_push_device_failed", {messageId: "message-1",deviceId: "device-ios",@@ -259,7 +249,7 @@ describe("mobile-push processing", () => {"SensitiveInternalError",))- await processMobilePush({} as never, env, task, deps)+ await expect(processMobilePush({} as never, env, { ...task, installationId: "installation-android" }, deps)).rejects.toThrow()expect(mockLogWarn).toHaveBeenCalledWith("mobile_push_device_failed", {messageId: "message-1",@@ -300,11 +290,7 @@ describe("mobile-push processing", () => {)deps[dependency].mockRejectedValue(failure)- await expect(processMobilePush({} as never, env, task, deps)).resolves.toMatchObject({- outcome: "processed",- attempted: 1,- failed: 1,- })+ await expect(processMobilePush({} as never, env, { ...task, installationId: provider === "apns" ? "installation-ios" : "installation-android" }, deps)).rejects.toThrow()const expectedDetails = {messageId: "message-1",@@ -342,3 +328,15 @@ describe("mobile-push processing", () => {expect(deps.buildPayload).not.toHaveBeenCalled()})})++it("queues per-device work before delivery so a failed device does not replay its sibling", async () => {+ const deps = dependencies()+ const { installationId: _installationId, ...rootTask } = task+ expect(await processMobilePush({} as never, env, rootTask, deps)).toEqual({ outcome: "queued", devices: 2 })+ expect(env.TASK_QUEUE.sendBatch).toHaveBeenCalledWith([+ { body: { ...rootTask, installationId: "installation-ios" } },+ { body: { ...rootTask, installationId: "installation-android" } },+ ])+ expect(deps.sendApns).not.toHaveBeenCalled()+ expect(deps.sendFcm).not.toHaveBeenCalled()+})diff --git a/src/queue-worker/src/mobile-push.ts b/src/queue-worker/src/mobile-push.tsindex 6c8ec2fe2..3a26cd033 100644--- a/src/queue-worker/src/mobile-push.ts+++ b/src/queue-worker/src/mobile-push.ts@@ -24,12 +24,12 @@ type MobilePushSkipReason =export type MobilePushResult =| { outcome: "skip"; reason: MobilePushSkipReason }+ | { outcome: "queued"; devices: number }| {outcome: "processed"attempted: numbersent: numberinvalidated: number- failed: number}type MobilePushDependencies = {@@ -87,13 +87,23 @@ export async function processMobilePush(}}- const [target, devices] = await Promise.all([+ const [target, activeDevices] = await Promise.all([dependencies.getTarget(db, task.messageId),dependencies.listDevices(db, task.userId),])if (!target) return { outcome: "skip", reason: "message_missing" }+ const devices = activeDevices.filter((device) => !task.installationId || device.installationId === task.installationId)if (devices.length === 0) return { outcome: "skip", reason: "no_active_devices" }+ if (!task.installationId) {+ for (let offset = 0; offset < devices.length; offset += 100) {+ await env.TASK_QUEUE.sendBatch(devices.slice(offset, offset + 100).map((device) => ({+ body: { ...task, installationId: device.installationId },+ })))+ }+ return { outcome: "queued", devices: devices.length }+ }+const payload = await dependencies.buildPayload(target, task.userId)let fcmAccessToken: Promise<string> | undefinedconst results = await Promise.all(devices.map(async (device) => {@@ -156,7 +166,7 @@ export async function processMobilePush(...diagnostic,durationMs: Date.now() - startedAt,})- return "failed" as const+ throw error}}))@@ -165,6 +175,5 @@ export async function processMobilePush(attempted: devices.length,sent: results.filter((outcome) => outcome === "sent").length,invalidated: results.filter((outcome) => outcome === "invalid-token").length,- failed: results.filter((outcome) => outcome === "failed").length,}}diff --git a/src/queue-worker/src/task-handler.test.ts b/src/queue-worker/src/task-handler.test.tsindex 009487a3f..b1a554509 100644--- a/src/queue-worker/src/task-handler.test.ts+++ b/src/queue-worker/src/task-handler.test.ts@@ -71,7 +71,7 @@ describe("queue task handler", () => {})})- it("catches mobile processing failures so the consumer can ACK", async () => {+ it("propagates mobile processing failures so the consumer retries", async () => {const processPush = vi.fn(async () => {throw new Error("provider unavailable")})@@ -85,7 +85,7 @@ describe("queue task handler", () => {await expect(executeQueueTask({} as never, {} as Env, task, {dispatchWake: vi.fn(),processMobilePush: processPush,- })).resolves.toBeUndefined()+ })).rejects.toThrow("provider unavailable")expect(mockLogWarn).toHaveBeenCalledWith("mobile_push_task_failed", {kind: "mobile-push",messageId: "message-1",diff --git a/src/queue-worker/src/task-handler.ts b/src/queue-worker/src/task-handler.tsindex 543c9e86e..e6affdfdd 100644--- a/src/queue-worker/src/task-handler.ts+++ b/src/queue-worker/src/task-handler.ts@@ -59,5 +59,6 @@ export async function executeQueueTask(userId: task.userId,errorName: error instanceof Error ? error.name : "unknown",})+ throw error}}diff --git a/src/queue-worker/test-runtime/worker.runtime.test.ts b/src/queue-worker/test-runtime/worker.runtime.test.tsindex 8b4350a0f..2d4b20aa0 100644--- a/src/queue-worker/test-runtime/worker.runtime.test.ts+++ b/src/queue-worker/test-runtime/worker.runtime.test.ts@@ -85,7 +85,7 @@ describe("queue-worker workerd runtime", () => {expect(result.retryMessages).toEqual([])})- it("ACKs caught mobile and poison siblings while retrying only a transient bot failure", async () => {+ it("ACKs poison messages while retrying transient mobile and bot failures", async () => {const mobileId = `runtime-mobile-${crypto.randomUUID()}`const botId = `runtime-bot-${crypto.randomUUID()}`const poisonId = `runtime-poison-${crypto.randomUUID()}`@@ -125,7 +125,9 @@ describe("queue-worker workerd runtime", () => {])expect(result.outcome).toBe("ok")- expect(result.explicitAcks).toEqual(expect.arrayContaining([mobileId, poisonId]))+ expect(result.explicitAcks).toContain(poisonId)+ expect(result.explicitAcks).not.toContain(mobileId)+ expect(result.retryMessages).toContainEqual({ msgId: mobileId, delaySeconds: 5 })expect(result.explicitAcks).not.toContain(botId)expect(result.retryMessages).toContainEqual({ msgId: botId, delaySeconds: 5 })} finally {diff --git a/src/queue-worker/wrangler.toml b/src/queue-worker/wrangler.tomlindex e3f692c01..4272544d4 100644--- a/src/queue-worker/wrangler.toml+++ b/src/queue-worker/wrangler.toml@@ -41,3 +41,7 @@ queue = "alook-queue"max_batch_size = 25max_retries = 3dead_letter_queue = "alook-queue-dlq"++[[queues.producers]]+binding = "TASK_QUEUE"+queue = "alook-queue"diff --git a/src/shared/src/community/queue-task.ts b/src/shared/src/community/queue-task.tsindex c84975504..8d9d94f07 100644--- a/src/shared/src/community/queue-task.ts+++ b/src/shared/src/community/queue-task.ts@@ -10,6 +10,7 @@ export type MobilePushQueueTaskV1 = {kind: "mobile-push"messageId: stringuserId: string+ installationId?: string}export type AlookQueueTask = BotWakeQueueTaskV1 | MobilePushQueueTaskV1@@ -100,7 +101,8 @@ export function parseQueueTask(value: unknown): QueueTaskParseResult {if (value.kind === "mobile-push") {if (- !hasExactKeys(value, ["version", "kind", "messageId", "userId"])+ !hasExactKeys(value, ["version", "kind", "messageId", "userId", ...(hasOwn(value, "installationId") ? ["installationId"] : [])])+ || (hasOwn(value, "installationId") && !isNonEmptyId(value.installationId))|| !isNonEmptyId(value.messageId)|| !isNonEmptyId(value.userId)) {@@ -114,6 +116,7 @@ export function parseQueueTask(value: unknown): QueueTaskParseResult {kind: "mobile-push",messageId: value.messageId,userId: value.userId,+ ...(typeof value.installationId === "string" ? { installationId: value.installationId } : {}),},}}diff --git a/src/shared/src/db/queries/account-deletion.test.ts b/src/shared/src/db/queries/account-deletion.test.tsindex f47501791..b94a50713 100644--- a/src/shared/src/db/queries/account-deletion.test.ts+++ b/src/shared/src/db/queries/account-deletion.test.ts@@ -9,6 +9,8 @@ import * as machineSchema from "../community-machine-schema"import type { Database } from "../index"import {deleteAccountRows,+ beginAccountDeletion,+ listPendingAccountDeletions,deleteDeletionChallengeIfMatches,getAccountDeletionSnapshot,restoreDeletionChallenge,@@ -135,6 +137,24 @@ describe("account deletion snapshot and delete queries", () => {sqlite.prepare(statement).run(...bindings)}++ it("atomically disables the owner and bots, revokes sessions, and retains cleanup roots", async () => {+ run("INSERT INTO user (id, email, name, discriminator) VALUES ('owner', 'owner@test', 'Owner', '0001'), ('other', 'other@test', 'Other', '0002')")+ run("INSERT INTO user (id, email, name, discriminator, isBot, ownerUserId) VALUES ('bot', 'bot@test', 'Bot', '0003', 1, 'owner')")+ run("INSERT INTO session (id, userId, token, expiresAt) VALUES ('s1', 'owner', 'test', '2099-01-01T00:00:00.000Z')")+ await beginAccountDeletion(db, "owner")+ expect(sqlite.prepare("SELECT id FROM user WHERE deletedAt IS NOT NULL ORDER BY id").all()).toEqual([{ id: "bot" }, { id: "owner" }])+ expect(sqlite.prepare("SELECT id FROM session").all()).toEqual([])+ expect(await listPendingAccountDeletions(db)).toEqual([{ id: "owner" }])+ const snapshot = await getAccountDeletionSnapshot(db, "owner")+ expect(snapshot?.identities.map(identity => identity.id).sort()).toEqual(["bot", "owner"])+ await beginAccountDeletion(db, "owner")+ expect(await listPendingAccountDeletions(db)).toEqual([{ id: "owner" }])+ expect((await deleteAccountRows(db, snapshot!)).deleted).toBe(true)+ expect(await listPendingAccountDeletions(db)).toEqual([])+ expect(sqlite.prepare("SELECT id FROM user").all()).toEqual([{ id: "other" }])+ })+it("snapshots every attributable root and deletes it without damaging shared data", async () => {const now = "2026-09-08T00:00:00.000Z"const owner = "delete_owner"diff --git a/src/shared/src/db/queries/account-deletion.ts b/src/shared/src/db/queries/account-deletion.tsindex 7bb2a7993..bd1a454ce 100644--- a/src/shared/src/db/queries/account-deletion.ts+++ b/src/shared/src/db/queries/account-deletion.ts@@ -1,4 +1,4 @@-import { and, eq, inArray, isNull, notExists, or, sql } from "drizzle-orm"+import { and, eq, inArray, isNull, isNotNull, notExists, or, sql } from "drizzle-orm"import { sqliteTable, text } from "drizzle-orm/sqlite-core"import {account,@@ -564,3 +564,18 @@ export async function deleteAccountRows(: [],}}++export async function beginAccountDeletion(db: Database, userId: string) {+ await db.batch([+ db.update(user).set({ deletedAt: new Date().toISOString() })+ .where(and(isNull(user.deletedAt), or(eq(user.id, userId), and(eq(user.ownerUserId, userId), eq(user.isBot, true))))),+ db.delete(session).where(eq(session.userId, userId)),+ db.update(user).set({ updatedAt: new Date().toISOString() }).where(eq(user.id, userId)),+ ])+}++export async function listPendingAccountDeletions(db: Database) {+ return db.select({ id: user.id }).from(user)+ .where(and(eq(user.isBot, false), isNotNull(user.deletedAt)))+ .orderBy(user.updatedAt, user.id).limit(25)+}diff --git a/src/shared/src/db/queries/billing.ts b/src/shared/src/db/queries/billing.tsindex 2b5dbb20f..f8fc37697 100644--- a/src/shared/src/db/queries/billing.ts+++ b/src/shared/src/db/queries/billing.ts@@ -1,4 +1,4 @@-import { and, eq, exists, isNull, lt, or, sql } from "drizzle-orm";+import { and, eq, exists, isNull, isNotNull, lt, or, sql } from "drizzle-orm";import { alias } from "drizzle-orm/sqlite-core";import type { Database } from "../index";import {@@ -252,3 +252,14 @@ export async function applyBillingPlan(}export { resolveBotsMaxForUser as getEffectivePlan };++export async function listBillingOwners(db: Database) {+ return db.select({ userId: userBilling.userId }).from(userBilling)+ .innerJoin(user, eq(user.id, userBilling.userId))+ .where(and(isNotNull(userBilling.customerId), isNull(user.deletedAt)))+ .orderBy(userBilling.updatedAt, userBilling.userId).limit(25);+}++export async function recordBillingRecoveryAttempt(db: Database, userId: string) {+ await db.update(userBilling).set({ updatedAt: new Date().toISOString() }).where(eq(userBilling.userId, userId));+}diff --git a/src/shared/src/db/queries/session.ts b/src/shared/src/db/queries/session.tsindex e79f4e4fc..4a31a414c 100644--- a/src/shared/src/db/queries/session.ts+++ b/src/shared/src/db/queries/session.ts@@ -1,4 +1,4 @@-import { eq, and, gt } from "drizzle-orm";+import { eq, and, gt, isNull } from "drizzle-orm";import { session, user } from "../schema";import type { Database } from "../index";@@ -26,21 +26,34 @@ export async function getValidSession(db: Database, token: string) {export async function getValidSessionWithIdentity(db: Database,token: string-): Promise<{ userId: string; name: string; discriminator: string } | null> {+): Promise<{ userId: string; name: string; discriminator: string; sessionId: string; expiresAt: string } | null> {const rows = await db.select({userId: session.userId,name: user.name,discriminator: user.discriminator,+ sessionId: session.id,+ expiresAt: session.expiresAt,}).from(session).innerJoin(user, eq(user.id, session.userId)).where(and(eq(session.token, token),+ isNull(user.deletedAt),+ eq(user.isBot, false),gt(session.expiresAt, new Date().toISOString())));if (rows.length === 0) return null;return rows[0];}++export async function getValidSessionByIdForUser(db: Database, id: string, userId: string) {+ const [row] = await db.select({ expiresAt: session.expiresAt }).from(session)+ .innerJoin(user, eq(user.id, session.userId))+ .where(and(eq(session.id, id), eq(session.userId, userId),+ gt(session.expiresAt, new Date().toISOString()), isNull(user.deletedAt), eq(user.isBot, false)))+ .limit(1);+ return row ?? null;+}diff --git a/src/shared/src/lib/rate-limits.ts b/src/shared/src/lib/rate-limits.tsindex 771c39eee..dc830608a 100644--- a/src/shared/src/lib/rate-limits.ts+++ b/src/shared/src/lib/rate-limits.ts@@ -30,6 +30,7 @@ export const RATE_LIMITS = {*/"auth:otpSend": { windowMs: 60_000, max: 5 },"auth:nativeAttempt": { windowMs: 60_000, max: 10 },+ "community:upload": { windowMs: 60_000, max: 30, failClosed: true },} as constexport type RateLimitName = keyof typeof RATE_LIMITS@@ -37,6 +38,7 @@ export type RateLimitName = keyof typeof RATE_LIMITSexport type RateLimitPolicy = {windowMs: numbermax: number+ failClosed?: boolean}export type RateLimitResult =diff --git a/src/shared/test/community/queue-task.test.ts b/src/shared/test/community/queue-task.test.tsindex 08a8690da..5a16f925b 100644--- a/src/shared/test/community/queue-task.test.ts+++ b/src/shared/test/community/queue-task.test.ts@@ -110,3 +110,9 @@ describe("parseQueueTaskBatch", () => {.toEqual({ ok: false, reason: "malformed", itemIndex: null })})})++it("preserves an installation-scoped mobile retry and rejects empty device identity", () => {+ const task = { version: 1, kind: "mobile-push", messageId: "m", userId: "u", installationId: "device" }+ expect(parseQueueTask(task)).toMatchObject({ ok: true, task })+ expect(parseQueueTask({ ...task, installationId: "" })).toMatchObject({ ok: false })+})diff --git a/src/shared/test/queries/billing.test.ts b/src/shared/test/queries/billing.test.tsindex 41c222566..b58e50607 100644--- a/src/shared/test/queries/billing.test.ts+++ b/src/shared/test/queries/billing.test.ts@@ -312,3 +312,25 @@ describe("purchase analytics persistence", () => {await expect(db.select().from(billingPurchaseDelivery)).resolves.toEqual([]);});});++it("bounds recovery to the 25 oldest live billed owners and rotates attempted owners", async () => {+ for (let i = 0; i < 27; i++) {+ const id = `recover-${String(i).padStart(2, "0")}`;+ sqlite.prepare("INSERT INTO user(id) VALUES (?)").run(id);+ const row = (await billing.ensureBilling(db, id))!;+ await billing.updateBilling(db, row, { customerId: `cus-${id}` });+ sqlite.prepare("UPDATE user_billing SET updated_at=? WHERE user_id=?").run("2000-01-01T00:00:00.000Z", id);+ }+ sqlite.prepare("UPDATE user SET deletedAt=? WHERE id='recover-01'").run(new Date().toISOString());+ await billing.ensureBilling(db, "new-user");+ const owners = await billing.listBillingOwners(db);+ expect(owners).toHaveLength(25);+ expect(owners[0]).toEqual({ userId: "recover-00" });+ expect(owners).not.toContainEqual({ userId: "recover-01" });+ expect(owners).not.toContainEqual({ userId: "new-user" });+ await billing.recordBillingRecoveryAttempt(db, "recover-00");+ const next = await billing.listBillingOwners(db);+ expect(next[0]).toEqual({ userId: "recover-02" });+ expect(next).toContainEqual({ userId: "recover-26" });+ expect(next).not.toContainEqual({ userId: "recover-00" });+});diff --git a/src/shared/test/queries/session-identity.test.ts b/src/shared/test/queries/session-identity.test.tsnew file mode 100644index 000000000..4e892e780--- /dev/null+++ b/src/shared/test/queries/session-identity.test.ts@@ -0,0 +1,32 @@+import Sqlite from "better-sqlite3"+import { drizzle } from "drizzle-orm/better-sqlite3"+import { afterEach, beforeEach, expect, it } from "vitest"+import type { Database } from "../../src/db"+import { getValidSessionByIdForUser, getValidSessionWithIdentity } from "../../src/db/queries/session"++let sqlite: Sqlite.Database+let db: Database+beforeEach(() => {+ sqlite = new Sqlite(":memory:")+ sqlite.exec(`CREATE TABLE user(id TEXT PRIMARY KEY, name TEXT, discriminator TEXT, deletedAt TEXT, isBot INTEGER);+ CREATE TABLE session(id TEXT PRIMARY KEY, userId TEXT, token TEXT, expiresAt TEXT);+ INSERT INTO user VALUES ('owner','Owner','0001',NULL,0);+ INSERT INTO session VALUES ('session','owner','token','2999-01-01T00:00:00.000Z');`)+ db = drizzle(sqlite) as unknown as Database+})+afterEach(() => sqlite.close())+it("returns persisted identity and rejects a session reused for another owner", async () => {+ expect(await getValidSessionWithIdentity(db, "token")).toEqual({ userId: "owner", name: "Owner", discriminator: "0001", sessionId: "session", expiresAt: "2999-01-01T00:00:00.000Z" })+ expect(await getValidSessionByIdForUser(db, "session", "owner")).toEqual({ expiresAt: "2999-01-01T00:00:00.000Z" })+ expect(await getValidSessionByIdForUser(db, "session", "other")).toBeNull()+})+it.each([+ "UPDATE user SET deletedAt='2026-01-01'",+ "UPDATE user SET isBot=1",+ "UPDATE session SET expiresAt='2000-01-01T00:00:00.000Z'",+ "DELETE FROM session",+])("rejects revoked or ineligible sessions: %s", async (mutation) => {+ sqlite.exec(mutation)+ expect(await getValidSessionWithIdentity(db, "token")).toBeNull()+ expect(await getValidSessionByIdForUser(db, "session", "owner")).toBeNull()+})diff --git a/src/web/custom-worker.ts b/src/web/custom-worker.tsindex 4225a9287..e14e4c774 100644--- a/src/web/custom-worker.ts+++ b/src/web/custom-worker.ts@@ -13,4 +13,14 @@ export { DOQueueHandler } from "./.open-next/worker.js"const buildEnv = (requiredServerFiles as { config: Pick<NextConfig, "env"> }).config.envconst build = resolveObservationLabels({ release: buildEnv?.NEXT_PUBLIC_FARO_RELEASE, environment: buildEnv?.NEXT_PUBLIC_FARO_ENVIRONMENT })-export default createWebWorkerHandler(openNextHandler as ExportedHandler<CloudflareEnv>, build)+const webHandler = createWebWorkerHandler(openNextHandler as ExportedHandler<CloudflareEnv>, build)+export default {+ ...webHandler,+ async scheduled(_event: ScheduledController, env: CloudflareEnv, ctx: ExecutionContext) {+ const request = new Request("https://internal/api/internal/account-maintenance", {+ method: "POST", headers: { "X-Alook-Internal": "1" },+ })+ const response = await openNextHandler.fetch(request, env, ctx)+ if (!response.ok) throw new Error(`Account maintenance failed: ${response.status}`)+ },+} satisfies ExportedHandler<CloudflareEnv>diff --git a/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.ts b/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.tsindex cd88d17d2..17cb1a917 100644--- a/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.ts+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.ts@@ -62,6 +62,14 @@ describe("sign-in client Apple availability", () => {})) as never})+ it("does not claim removal is complete while deletion remains pending", () => {+ mocks.searchParams = new URLSearchParams("account_deleted=pending")+ render(createElement(SignInPageClient, { isProd: true, appleEnabled: false }))+ expect(screen.getByRole("status")).toHaveTextContent("Account deletion requested")+ expect(screen.getByRole("status")).toHaveTextContent("Cleanup will retry automatically")+ expect(screen.queryByText("Your account and its data were removed.")).toBeNull()+ })+it("counts login entry once and records only bounded OTP failure dimensions", async () => {render(createElement(SignInPageClient, { isProd: true, appleEnabled: false }))expect(mocks.capture).toHaveBeenCalledWith({ event: "login_page_view" })diff --git a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx b/src/web/src/app/(auth)/sign-in/sign-in-client.tsxindex 55fb1cebf..6c07659e2 100644--- a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.tsx@@ -43,11 +43,13 @@ function SignInForm({postLoginUrl,isProd,accountDeleted,+ accountDeletionPending,appleEnabled,}: {postLoginUrl: stringisProd: booleanaccountDeleted: boolean+ accountDeletionPending: booleanappleEnabled: boolean}) {useEffect(() => { void captureProductAnalytics({ event: "login_page_view" }) }, [])@@ -186,7 +188,7 @@ function SignInForm({return (<FieldGroup><ObservedStaticContent />- {accountDeleted ? (+ {accountDeleted || accountDeletionPending ? (<divclassName="flex gap-3 rounded-xl bg-muted/70 p-4 text-left"role="status"@@ -194,9 +196,11 @@ function SignInForm({><CircleCheck className="mt-0.5 size-5 shrink-0 text-muted-foreground" aria-hidden /><div>- <div className="text-sm font-medium">Account deleted</div>+ <div className="text-sm font-medium">{accountDeletionPending ? "Account deletion requested" : "Account deleted"}</div><p className="mt-0.5 text-sm text-muted-foreground">- Your account and its data were removed.+ {accountDeletionPending+ ? "Sign-in is disabled. We’re stopping billing and removing your data. Cleanup will retry automatically."+ : "Your account and its data were removed."}</p></div></div>@@ -409,6 +413,7 @@ export default function SignInPageClient({const searchParams = useSearchParams()const postLoginUrl = safeRedirectUrl(searchParams.get("redirect"))const accountDeleted = searchParams.get("account_deleted") === "1"+ const accountDeletionPending = searchParams.get("account_deleted") === "pending"return (<div className="relative flex min-h-svh flex-col items-center justify-center p-6 sm:p-10">@@ -425,6 +430,7 @@ export default function SignInPageClient({postLoginUrl={postLoginUrl}isProd={isProd}accountDeleted={accountDeleted}+ accountDeletionPending={accountDeletionPending}appleEnabled={appleEnabled}/></div>diff --git a/src/web/src/app/api/auth/[...all]/route.test.ts b/src/web/src/app/api/auth/[...all]/route.test.tsindex 7fe175751..c12e41c5b 100644--- a/src/web/src/app/api/auth/[...all]/route.test.ts+++ b/src/web/src/app/api/auth/[...all]/route.test.ts@@ -26,6 +26,9 @@ describe("Better Auth server-only endpoints", () => {["GET", "/api/auth/one-time-token/generate"],["POST", "/api/auth/one-time-token/verify"],["POST", "/api/auth/one-time-token/verify/"],+ ["POST", "/api/auth/email-otp/check-verification-otp"],+ ["POST", "/api/auth/email-otp/check-verification-otp/"],+ ["GET", "/api/auth/email-otp/check-verification-otp"],])("blocks public %s %s before Better Auth", async (method, pathname) => {const request = new NextRequest(`https://alook.ai${pathname}`, { method })const response = method === "GET" ? await GET(request) : await POST(request)diff --git a/src/web/src/app/api/auth/[...all]/route.ts b/src/web/src/app/api/auth/[...all]/route.tsindex 81b0d93e9..eacd1b0e4 100644--- a/src/web/src/app/api/auth/[...all]/route.ts+++ b/src/web/src/app/api/auth/[...all]/route.ts@@ -8,6 +8,7 @@ const SERVER_ONLY_AUTH_PREFIX = "/api/auth/one-time-token"function isServerOnlyAuthRequest(request: NextRequest): boolean {const pathname = request.nextUrl.pathname.replace(/\/+$/, "")+ if (pathname === "/api/auth/email-otp/check-verification-otp") return truereturn pathname === SERVER_ONLY_AUTH_PREFIX|| pathname.startsWith(`${SERVER_ONLY_AUTH_PREFIX}/`)}diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.tsindex 02bc27e5c..4d129eb5a 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts@@ -7,6 +7,7 @@ import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"import { authorizeAttachment } from "@/lib/community/attachment-authorization"import { ATTACHMENT_PRIVATE_IMMUTABLE_CACHE } from "@/lib/community/storage"import { resolveAttachmentPresentation, resolveMediaContentType } from "@/lib/community/attachment-presentation"+import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"const log = createLogger({ service: "community-attachments-download" })@@ -117,6 +118,8 @@ export const GET = withPrivateMediaCache(withCommunityActor(async (req: NextRequconst size = row.size ?? obj.sizeconst headers: Record<string, string> = {"Content-Type": contentType,+ "X-Content-Type-Options": "nosniff",+ "Content-Security-Policy": "sandbox; default-src 'none'","X-Alook-Filename": encodeRfc5987(row.filename),}if (typeof size === "number") headers["Content-Length"] = String(size)@@ -124,11 +127,13 @@ export const GET = withPrivateMediaCache(withCommunityActor(async (req: NextRequreturn new Response(buffer, { headers })}- const isImage = contentType.startsWith("image/")+ const isImage = isInlineAttachmentContentType(contentType)const isMedia = contentType.startsWith("audio/") || contentType.startsWith("video/")const size = knownSize ?? row.size ?? obj.sizeconst headers: Record<string, string> = {"Content-Type": contentType,+ "X-Content-Type-Options": "nosniff",+ "Content-Security-Policy": "sandbox; default-src 'none'; media-src 'self'; img-src 'self'","Content-Disposition": isImage || isMedia? "inline": contentDisposition("attachment", row.filename),diff --git a/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/route.test.tsindex 285e59811..2d5a882c0 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts@@ -1,6 +1,8 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"+vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn(async () => ({ allowed: true })) }))+const mockR2Delete = vi.fn(async () => undefined)vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(async () => ({@@ -83,6 +85,7 @@ vi.mock("@/lib/community/upload", () => ({}))import { POST } from "./route"+import { checkRateLimit } from "@/lib/rate-limit"// The path `[id]` carries the `resolve` placeholder for a bot (it addresses by// `?target=`); a human puts the real channelId there.@@ -118,6 +121,16 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attac})})+ it("shares the owner's upload cap across bots and stops before storage", async () => {+ vi.mocked(checkRateLimit).mockResolvedValueOnce({ allowed: false, retryAfterSec: 9 })+ const response = await POST(botReq(null, { Authorization: "Bearer crk_abc" }), botCtx)+ expect(response.status).toBe(429)+ expect(response.headers.get("Retry-After")).toBe("9")+ expect(checkRateLimit).toHaveBeenCalledWith(expect.anything(), "community:upload", "owner_1")+ expect(mockHandleAttachmentUpload).not.toHaveBeenCalled()+ expect(mockCreateAttachment).not.toHaveBeenCalled()+ })+it("401 without Authorization", async () => {const res = await POST(botReq("/studio#0042/general"), botCtx)expect(res.status).toBe(401)diff --git a/src/web/src/app/api/community/channels/[id]/attachments/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/route.tsindex 8d67d9ce5..5bcc26f03 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/route.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/route.ts@@ -8,6 +8,7 @@ import {requireDMCommunicationAccess,} from "@/lib/community/permissions"import { handleAttachmentUpload, runAttachmentUpload } from "@/lib/community/upload"+import { checkRateLimit } from "@/lib/rate-limit"const log = createLogger({ service: "community-attachments-upload" })@@ -17,6 +18,11 @@ const log = createLogger({ service: "community-attachments-upload" })// puts the real channelId in the path. Mirrors the channels/[id]/members// dual-actor door.export const POST = withCommunityActor(async (req: NextRequest, ctx) => {+ const ownerId = ctx.actor.kind === "bot" ? ctx.actor.ownerUserId : ctx.actor.userId+ const rate = await checkRateLimit(ctx.env, "community:upload", ownerId)+ if (!rate.allowed) return NextResponse.json({ error: "Upload limit reached. Try again shortly." }, {+ status: 429, headers: { "Retry-After": String(rate.retryAfterSec) },+ })if (ctx.actor.kind === "bot") {return handleBotAttachmentUpload(req, ctx)}diff --git a/src/web/src/app/api/community/users/me/account-deletion/route.test.ts b/src/web/src/app/api/community/users/me/account-deletion/route.test.tsindex 1e23d1077..c3b3c590a 100644--- a/src/web/src/app/api/community/users/me/account-deletion/route.test.ts+++ b/src/web/src/app/api/community/users/me/account-deletion/route.test.ts@@ -80,6 +80,15 @@ describe("account deletion submit route", () => {expect(executeAccountDeletion).not.toHaveBeenCalled()})+ it("accepts durable pending deletion and clears cookies without restoring the code", async () => {+ executeAccountDeletion.mockResolvedValue({ kind: "pending" })+ const response = await POST(request({ otp: "123456" }), {} as never)+ expect(response.status).toBe(202)+ expect(await response.json()).toEqual({ ok: true, pending: true })+ expect(response.headers.getSetCookie().join("\n")).toContain("better-auth.session_token=")+ expect(restoreVerifiedDeletionCode).not.toHaveBeenCalled()+ })+it("deletes explicitly and clears Better Auth cookies", async () => {const response = await POST(request({ otp: "123456" }), {} as never)diff --git a/src/web/src/app/api/community/users/me/account-deletion/route.ts b/src/web/src/app/api/community/users/me/account-deletion/route.tsindex daddeb331..d04a79a9c 100644--- a/src/web/src/app/api/community/users/me/account-deletion/route.ts+++ b/src/web/src/app/api/community/users/me/account-deletion/route.ts@@ -67,8 +67,8 @@ export const POST = withCookieHumanAuth(async (request, context) => {}const response = NextResponse.json(- { ok: true },- { headers: { "Cache-Control": "no-store, max-age=0" } },+ { ok: true, ...(deletion.kind === "pending" ? { pending: true } : {}) },+ { status: deletion.kind === "pending" ? 202 : 200, headers: { "Cache-Control": "no-store, max-age=0" } },)clearAuthCookies(response)try {diff --git a/src/web/src/app/api/internal/account-maintenance/route.test.ts b/src/web/src/app/api/internal/account-maintenance/route.test.tsnew file mode 100644index 000000000..516eeed6c--- /dev/null+++ b/src/web/src/app/api/internal/account-maintenance/route.test.ts@@ -0,0 +1,36 @@+import { beforeEach, expect, it, vi } from "vitest"++const mocks = vi.hoisted(() => ({+ context: vi.fn(),+ maintain: vi.fn(),+}))+vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: mocks.context }))+vi.mock("@/lib/account-maintenance", () => ({ maintainAccounts: mocks.maintain }))+import { POST } from "./route"++beforeEach(() => vi.resetAllMocks())++it("rejects requests without the internal marker before accessing bindings", async () => {+ for (const marker of [undefined, "0"]) {+ const headers = marker ? { "X-Alook-Internal": marker } : undefined+ expect((await POST(new Request("https://example.test/api/internal/account-maintenance", { method: "POST", headers }))).status).toBe(404)+ }+ expect(mocks.context).not.toHaveBeenCalled()+ expect(mocks.maintain).not.toHaveBeenCalled()+})++it("awaits maintenance with the worker bindings and execution context", async () => {+ const env = { DB: {} }+ const ctx = { waitUntil: vi.fn() }+ mocks.context.mockResolvedValue({ env, ctx })+ const response = await POST(new Request("https://example.test/api/internal/account-maintenance", { method: "POST", headers: { "X-Alook-Internal": "1" } }))+ expect(mocks.context).toHaveBeenCalledWith({ async: true })+ expect(mocks.maintain).toHaveBeenCalledWith(env, ctx)+ expect(await response.json()).toEqual({ ok: true })+})++it("does not return success when maintenance fails", async () => {+ mocks.context.mockResolvedValue({ env: {}, ctx: {} })+ mocks.maintain.mockRejectedValue(new Error("maintenance unavailable"))+ await expect(POST(new Request("https://example.test/api/internal/account-maintenance", { method: "POST", headers: { "X-Alook-Internal": "1" } }))).rejects.toThrow("maintenance unavailable")+})diff --git a/src/web/src/app/api/internal/account-maintenance/route.ts b/src/web/src/app/api/internal/account-maintenance/route.tsnew file mode 100644index 000000000..797774205--- /dev/null+++ b/src/web/src/app/api/internal/account-maintenance/route.ts@@ -0,0 +1,9 @@+import { getCloudflareContext } from "@opennextjs/cloudflare"+import { maintainAccounts } from "@/lib/account-maintenance"++export async function POST(request: Request) {+ if (request.headers.get("X-Alook-Internal") !== "1") return new Response(null, { status: 404 })+ const { env, ctx } = await getCloudflareContext({ async: true })+ await maintainAccounts(env, ctx)+ return Response.json({ ok: true })+}diff --git a/src/web/src/components/community/settings/account-deletion-flow.dom.test.tsx b/src/web/src/components/community/settings/account-deletion-flow.dom.test.tsxindex 66338ac89..89201d8be 100644--- a/src/web/src/components/community/settings/account-deletion-flow.dom.test.tsx+++ b/src/web/src/components/community/settings/account-deletion-flow.dom.test.tsx@@ -114,11 +114,11 @@ describe("AccountDeletionFlow", () => {expect(authTransition.cancel).toHaveBeenCalledTimes(1)})- it("falls back to the persistent completion URL when local cleanup rejects", async () => {+ it.each([200, 202])("preserves the accepted deletion status %s when local cleanup rejects", async (status) => {const user = setupUser({ advanceTimers: (delay) => vi.advanceTimersByTime(delay) })const fetchMock = vi.fn().mockResolvedValueOnce(Response.json({ ok: true, expires_in: 300, resend_after: 60 }))- .mockResolvedValueOnce(Response.json({ ok: true }))+ .mockResolvedValueOnce(Response.json({ ok: true }, { status }))vi.stubGlobal("fetch", fetchMock)const replace = vi.fn()vi.stubGlobal("location", { replace })@@ -133,7 +133,7 @@ describe("AccountDeletionFlow", () => {fireEvent.change(input, { target: { value: "123456" } })await user.click(screen.getByTestId(tid.accountDeletionSubmit))- await waitFor(() => expect(replace).toHaveBeenCalledWith("/sign-in?account_deleted=1"))+ await waitFor(() => expect(replace).toHaveBeenCalledWith(status === 202 ? "/sign-in?account_deleted=pending" : "/sign-in?account_deleted=1"))expect(authTransition.cancel).not.toHaveBeenCalled()})})diff --git a/src/web/src/components/community/settings/account-deletion-flow.tsx b/src/web/src/components/community/settings/account-deletion-flow.tsxindex 084769574..d02aab6e9 100644--- a/src/web/src/components/community/settings/account-deletion-flow.tsx+++ b/src/web/src/components/community/settings/account-deletion-flow.tsx@@ -148,7 +148,7 @@ export function AccountDeletionFlow({ email, onCancel, onDeleted }: Props) {await clearPersistedCache(source.registry.accountId).catch(() => undefined)if (!visible || !rootEligible()) { cancelAccountDeletionAuthTransition(lease); transition.current = undefined; return }try { await onDeleted() } catch {}- if (rootEligible()) globalThis.location.replace(ACCOUNT_DELETED_SIGN_IN_PATH)+ if (rootEligible()) globalThis.location.replace(response.status === 202 ? "/sign-in?account_deleted=pending" : ACCOUNT_DELETED_SIGN_IN_PATH)} catch (error) {cancelAccountDeletionAuthTransition(lease); transition.current = undefinedif (isAbortError(error)) returndiff --git a/src/web/src/lib/account-deletion/execution.test.ts b/src/web/src/lib/account-deletion/execution.test.tsindex 94ecb10bf..ccf0806f7 100644--- a/src/web/src/lib/account-deletion/execution.test.ts+++ b/src/web/src/lib/account-deletion/execution.test.ts@@ -2,6 +2,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest"const mocks = vi.hoisted(() => ({getSnapshot: vi.fn(),+ beginDeletion: vi.fn(),+ closeBilling: vi.fn(),deleteRows: vi.fn(),getUser: vi.fn(),deleteStorage: vi.fn(),@@ -25,6 +27,7 @@ vi.mock("@alook/shared", () => ({queries: {accountDeletion: {getAccountDeletionSnapshot: mocks.getSnapshot,+ beginAccountDeletion: mocks.beginDeletion,deleteAccountRows: mocks.deleteRows,},user: { getUserInternal: mocks.getUser },@@ -37,6 +40,7 @@ vi.mock("@/lib/cache", () => ({invalidateMany: mocks.invalidateMany,}))vi.mock("@/lib/community/community-media-cleanup", () => ({ deleteCommunityMediaObjects: vi.fn() }))+vi.mock("@/lib/billing/service", () => ({ closeAccountBilling: mocks.closeBilling }))vi.mock("./storage", () => ({ deleteAccountStorage: mocks.deleteStorage }))vi.mock("./provider-revocation", () => ({ revokeProviderAccount: mocks.revokeProvider }))vi.mock("@/lib/community/machine-disconnect", () => ({@@ -81,6 +85,8 @@ describe("account deletion execution", () => {beforeEach(() => {vi.clearAllMocks()for (const effect of [+ mocks.beginDeletion,+ mocks.closeBilling,mocks.deleteStorage,mocks.forceClose,mocks.pushBot,@@ -146,7 +152,7 @@ describe("account deletion execution", () => {{} as never,{ waitUntil: vi.fn() },"user-1",- )).resolves.toEqual({ kind: "failed" })+ )).resolves.toEqual({ kind: "pending" })expect(mocks.getSnapshot).toHaveBeenCalledTimes(2)expect(mocks.deleteRows).not.toHaveBeenCalled()expect(mocks.unsubscribe).not.toHaveBeenCalled()@@ -173,7 +179,7 @@ describe("account deletion execution", () => {{} as never,{ waitUntil: vi.fn() },"user-1",- )).resolves.toEqual({ kind: "failed" })+ )).resolves.toEqual({ kind: "pending" })expect(mocks.unsubscribe).not.toHaveBeenCalled()})@@ -193,7 +199,7 @@ describe("account deletion execution", () => {deleted: true,readStateRevisions: [{ userId: "member-1", revision: 7 }],})- mocks.forceClose.mockRejectedValue(new Error("socket unavailable"))+ mocks.broadcastDaemon.mockRejectedValue(new Error("socket unavailable"))let postCommit: Promise<unknown> | undefinedawait expect(executeAccountDeletion(@@ -264,11 +270,11 @@ describe("account deletion execution", () => {{} as never,{ waitUntil: vi.fn() },"user-1",- )).resolves.toEqual({ kind: "failed" })+ )).resolves.toEqual({ kind: "pending" })expect(mocks.deleteStorage).not.toHaveBeenCalled()expect(mocks.deleteRows).not.toHaveBeenCalled()- expect(mocks.invalidateMany).not.toHaveBeenCalled()+ expect(mocks.invalidateMany).toHaveBeenCalled()expect(mocks.unsubscribe).not.toHaveBeenCalled()})@@ -299,7 +305,7 @@ describe("account deletion execution", () => {{} as never,{ waitUntil: vi.fn() },"user-1",- )).resolves.toEqual({ kind: "failed" })+ )).resolves.toEqual({ kind: "pending" })expect(mocks.unsubscribe).not.toHaveBeenCalled()})@@ -362,4 +368,33 @@ describe("account deletion execution", () => {expect(mocks.unsubscribe.mock.invocationCallOrder[0]).toBeGreaterThan(mocks.getUser.mock.invocationCallOrder[0])expect(waitUntil).toHaveBeenCalledOnce()})+ it("keeps cleanup pending until billing and machine shutdown succeed", async () => {+ mocks.getSnapshot.mockResolvedValue(snapshot("current"))+ mocks.closeBilling.mockRejectedValueOnce(new Error("Stripe unavailable"))+ const ctx = { waitUntil: vi.fn() }+ await expect(executeAccountDeletion({} as never, {} as never, ctx, "user-1")).resolves.toEqual({ kind: "pending" })+ expect(mocks.beginDeletion).toHaveBeenCalledBefore(mocks.closeBilling)+ expect(mocks.deleteStorage).not.toHaveBeenCalled()+ expect(mocks.deleteRows).not.toHaveBeenCalled()+ mocks.deleteRows.mockResolvedValue({ deleted: true, readStateRevisions: [] })+ await expect(executeAccountDeletion({} as never, {} as never, ctx, "user-1")).resolves.toEqual({ kind: "deleted" })+ expect(mocks.closeBilling).toHaveBeenCalledBefore(mocks.deleteStorage)+ })+ it("does not erase media while an existing machine cannot be disconnected", async () => {+ mocks.getSnapshot.mockResolvedValue(snapshot("current"))+ mocks.forceClose.mockRejectedValueOnce(new Error("DO unavailable"))+ await expect(executeAccountDeletion({} as never, {} as never, { waitUntil: vi.fn() }, "user-1")).resolves.toEqual({ kind: "pending" })+ expect(mocks.deleteStorage).not.toHaveBeenCalled()+ })++})++it.each([true, false, "unavailable"])("classifies an ambiguous deletion start using persisted state: %s", async (state) => {+ vi.clearAllMocks()+ mocks.beginDeletion.mockRejectedValueOnce(new Error("D1 response lost"))+ if (state === "unavailable") mocks.getUser.mockRejectedValueOnce(new Error("D1 unavailable"))+ else mocks.getUser.mockResolvedValueOnce({ deletedAt: state ? "2026-01-01" : null })+ await expect(executeAccountDeletion({} as never, {} as never, { waitUntil: vi.fn() }, "user-1"))+ .resolves.toEqual({ kind: state === true ? "pending" : "failed" })+ expect(mocks.deleteStorage).not.toHaveBeenCalled()})diff --git a/src/web/src/lib/account-deletion/execution.ts b/src/web/src/lib/account-deletion/execution.tsindex c3d72490a..426ebc881 100644--- a/src/web/src/lib/account-deletion/execution.ts+++ b/src/web/src/lib/account-deletion/execution.ts@@ -5,6 +5,7 @@ import { broadcastToDaemon } from "@/lib/broadcast"import { pushBotEventToMachine } from "@/lib/community/bot-push"import { fanOutToUsers, broadcastToUserSafe } from "@/lib/community/fanout"import { forceCloseCommunityMachinesByDoNames } from "@/lib/community/machine-disconnect"+import { closeAccountBilling } from "@/lib/billing/service"import { deleteAccountStorage } from "./storage"import { revokeProviderAccount } from "./provider-revocation"import { unsubscribeResendContact } from "@/lib/resend-contacts"@@ -15,6 +16,7 @@ export type ExecuteAccountDeletionResult =| { kind: "deleted" }| { kind: "missing" }| { kind: "failed" }+ | { kind: "pending" }async function invalidateMachineTokens(tokens: string[]): Promise<void> {await invalidateMany(tokens.map((token) => cacheKeys.machineToken(token))).catch(() => {})@@ -28,7 +30,6 @@ function scheduleAfterCommit(): void {const work = Promise.allSettled([unsubscribeResendContact(env, snapshot.identity.email),- forceCloseCommunityMachinesByDoNames(env, snapshot.machineDoNames),...snapshot.botBindings.map((binding) => pushBotEventToMachine(env, binding.machineId, {type: "bot:removed",botId: binding.botId,@@ -66,11 +67,16 @@ export async function executeAccountDeletion(executionContext: Pick<ExecutionContext, "waitUntil">,userId: string,): Promise<ExecuteAccountDeletionResult> {+ let started = falsetry {+ const finalDb = getPrimaryDb(env.DB)+ await queries.accountDeletion.beginAccountDeletion(finalDb, userId)+ started = trueconst firstSnapshot = await queries.accountDeletion.getAccountDeletionSnapshot(db, userId)if (!firstSnapshot) return { kind: "missing" }-- const finalDb = getPrimaryDb(env.DB)+ await invalidateMachineTokens(firstSnapshot.machineTokens)+ await forceCloseCommunityMachinesByDoNames(env, firstSnapshot.machineDoNames, true)+ await closeAccountBilling(finalDb, env, userId)const finalSnapshot = await queries.accountDeletion.getAccountDeletionSnapshot(finalDb, userId)if (!finalSnapshot) {await deleteAccountStorage(env, firstSnapshot)@@ -101,7 +107,7 @@ export async function executeAccountDeletion(}if (!deletion.deleted) {const remaining = await queries.user.getUserInternal(getPrimaryDb(env.DB), userId)- if (remaining) return { kind: "failed" }+ if (remaining) return { kind: "pending" }}await invalidateMachineTokens(machineTokens)@@ -111,6 +117,10 @@ export async function executeAccountDeletion(log.warn("account_deletion_failed", {errorCategory: error instanceof Error ? error.name : "NonError",})- return { kind: "failed" }+ if (!started) {+ const remaining = await queries.user.getUserInternal(getPrimaryDb(env.DB), userId).catch(() => null)+ started = remaining?.deletedAt != null+ }+ return { kind: started ? "pending" : "failed" }}}diff --git a/src/web/src/lib/account-maintenance.test.ts b/src/web/src/lib/account-maintenance.test.tsnew file mode 100644index 000000000..c78300cfd--- /dev/null+++ b/src/web/src/lib/account-maintenance.test.ts@@ -0,0 +1,36 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+const mocks = vi.hoisted(() => ({ pending: vi.fn(), owners: vi.fn(), touch: vi.fn(), remove: vi.fn(), reconcile: vi.fn(), warn: vi.fn() }))+vi.mock("@alook/shared", () => ({ createLogger: () => ({ warn: mocks.warn }), queries: {+ accountDeletion: { listPendingAccountDeletions: mocks.pending },+ billing: { listBillingOwners: mocks.owners, recordBillingRecoveryAttempt: mocks.touch },+} }))+vi.mock("./db", () => ({ getPrimaryDb: () => ({}) }))+vi.mock("./account-deletion/execution", () => ({ executeAccountDeletion: mocks.remove }))+vi.mock("./billing/client", () => ({ billingClient: () => ({}) }))+vi.mock("./billing/reconcile", () => ({ reconcileBilling: mocks.reconcile }))+import { maintainAccounts } from "./account-maintenance"++describe("account recovery pass", () => {+ beforeEach(() => { vi.resetAllMocks(); mocks.pending.mockResolvedValue([]); mocks.owners.mockResolvedValue([]) })+ it("reuses deletion and authoritative reconciliation and advances past a failed owner", async () => {+ mocks.pending.mockResolvedValue([{ id: "deleting" }])+ mocks.owners.mockResolvedValue([{ userId: "failed" }, { userId: "paid" }])+ mocks.reconcile.mockRejectedValueOnce(new Error("Stripe outage")).mockResolvedValueOnce("applied")+ await maintainAccounts({} as Env, { waitUntil: vi.fn() })+ expect(mocks.remove).toHaveBeenCalledOnce()+ expect(mocks.touch.mock.calls.map(call => call[1])).toEqual(["failed", "paid"])+ expect(mocks.reconcile).toHaveBeenCalledTimes(2)+ expect(mocks.warn).toHaveBeenCalledWith("billing_recovery_failed", { userId: "failed" })+ })+ it("stops starting work after the time budget and still runs the other recovery pass", async () => {+ vi.useFakeTimers()+ try {+ mocks.pending.mockResolvedValue([{ id: "slow" }, { id: "later" }])+ mocks.remove.mockImplementation(async () => { vi.advanceTimersByTime(4 * 60_000); return { kind: "pending" } })+ mocks.owners.mockResolvedValue([{ userId: "paid" }])+ await maintainAccounts({} as Env, { waitUntil: vi.fn() })+ expect(mocks.remove).toHaveBeenCalledOnce()+ expect(mocks.reconcile).toHaveBeenCalledOnce()+ } finally { vi.useRealTimers() }+ })+})diff --git a/src/web/src/lib/account-maintenance.ts b/src/web/src/lib/account-maintenance.tsnew file mode 100644index 000000000..17f6f227f--- /dev/null+++ b/src/web/src/lib/account-maintenance.ts@@ -0,0 +1,26 @@+import { createLogger, queries } from "@alook/shared"+import { getPrimaryDb } from "./db"+import { executeAccountDeletion } from "./account-deletion/execution"+import { billingClient } from "./billing/client"+import { reconcileBilling } from "./billing/reconcile"++const log = createLogger({ service: "account-maintenance" })++export async function maintainAccounts(env: Env, ctx: Pick<ExecutionContext, "waitUntil">) {+ const db = getPrimaryDb(env.DB)+ const deletionDeadline = Date.now() + 4 * 60_000+ for (const { id } of await queries.accountDeletion.listPendingAccountDeletions(db)) {+ if (Date.now() >= deletionDeadline) break+ await executeAccountDeletion(db, env, ctx, id)+ }+ const billingDeadline = Date.now() + 4 * 60_000+ for (const { userId } of await queries.billing.listBillingOwners(db)) {+ if (Date.now() >= billingDeadline) break+ try {+ await queries.billing.recordBillingRecoveryAttempt(db, userId)+ await reconcileBilling(db, billingClient(env), env, userId)+ } catch {+ log.warn("billing_recovery_failed", { userId })+ }+ }+}diff --git a/src/web/src/lib/billing/close-account.test.ts b/src/web/src/lib/billing/close-account.test.tsnew file mode 100644index 000000000..abc9766ec--- /dev/null+++ b/src/web/src/lib/billing/close-account.test.ts@@ -0,0 +1,43 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+const mocks = vi.hoisted(() => ({ billing: vi.fn(), current: vi.fn(), expire: vi.fn(), cancel: vi.fn(), retrieve: vi.fn(), list: vi.fn() }))+vi.mock("@alook/shared", () => ({ queries: { billing: { getBilling: mocks.billing } } }))+vi.mock("./reconcile", () => ({ currentSubscription: mocks.current, reconcileBilling: vi.fn() }))+vi.mock("./client", async importOriginal => ({ ...await importOriginal<typeof import("./client")>(), billingClient: () => ({+ checkout: { sessions: { retrieve: mocks.retrieve, list: mocks.list, expire: mocks.expire } },+ subscriptions: { cancel: mocks.cancel },+}) }))+import { closeAccountBilling } from "./service"+const env = { STRIPE_SECRET_KEY: "sk_test_fixture" } as Env+const attempt = { id: "attempt", sessionId: "checkout", startedAt: Math.floor(Date.now() / 1000) }++describe("account billing shutdown", () => {+ beforeEach(() => { vi.resetAllMocks(); mocks.list.mockReturnValue({ async *[Symbol.asyncIterator]() {} }) })+ it("expires a payable checkout before cancelling the current subscription", async () => {+ mocks.billing.mockResolvedValue({ userId: "owner", customerId: "customer", checkoutAttempt: attempt })+ mocks.retrieve.mockResolvedValue({ id: "checkout", customer: "customer", metadata: { alook_attempt_id: "attempt" }, livemode: false, status: "open" })+ mocks.current.mockResolvedValue({ id: "subscription", status: "active" })+ await closeAccountBilling({} as never, env, "owner")+ expect(mocks.expire).toHaveBeenCalledWith("checkout")+ expect(mocks.cancel).toHaveBeenCalledWith("subscription")+ expect(mocks.expire).toHaveBeenCalledBefore(mocks.cancel)+ })+ it("retains an ambiguous in-flight checkout until its fixed payment window ends", async () => {+ mocks.billing.mockResolvedValue({ userId: "owner", customerId: "customer", checkoutAttempt: { ...attempt, sessionId: null } })+ await expect(closeAccountBilling({} as never, env, "owner")).rejects.toMatchObject({ code: "BILLING_CHECKOUT_UNRESOLVED" })+ expect(mocks.current).not.toHaveBeenCalled()+ mocks.billing.mockResolvedValue({ userId: "owner", customerId: "customer", checkoutAttempt: { ...attempt, sessionId: null, startedAt: 1 } })+ await expect(closeAccountBilling({} as never, env, "owner")).resolves.toBeUndefined()+ expect(mocks.current).toHaveBeenCalledOnce()+ })+ it("propagates a failed cancellation so the billing mapping cannot be purged", async () => {+ mocks.billing.mockResolvedValue({ userId: "owner", customerId: "customer", checkoutAttempt: null })+ mocks.current.mockResolvedValue({ id: "subscription", status: "active" })+ mocks.cancel.mockRejectedValue(new Error("unknown Stripe outcome"))+ await expect(closeAccountBilling({} as never, env, "owner")).rejects.toThrow("unknown Stripe outcome")+ })+ it("does not require Stripe for an account with no billing history", async () => {+ mocks.billing.mockResolvedValue(null)+ await expect(closeAccountBilling({} as never, {} as Env, "owner")).resolves.toBeUndefined()+ expect(mocks.current).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/lib/billing/service.test.ts b/src/web/src/lib/billing/service.test.tsindex ca9fa93af..f33428920 100644--- a/src/web/src/lib/billing/service.test.ts+++ b/src/web/src/lib/billing/service.test.ts@@ -70,6 +70,22 @@ beforeEach(() => {const checkout = (price = "studio") => createCheckout(db, stripe, env, "owner", "[email protected]", price)describe("billing summary offer loading", () => {+ it("repairs a missed webhook before reading the displayed plan", async () => {+ row.customerId = "cus_existing"+ mocked.reconcileBilling.mockImplementation(async () => {+ mocked.getEffectivePlan.mockResolvedValue({ plan: { id: "studio", displayName: "Studio" }, isFounder: false })+ })+ const result = await getBillingSummary(db, () => stripe, env, "owner")+ expect(result.plan?.id).toBe("studio")+ expect(mocked.reconcileBilling).toHaveBeenCalledExactlyOnceWith(db, stripe, env, "owner")+ })+ it("does not report a stale paid projection as verified during a Stripe outage", async () => {+ row.customerId = "cus_existing"+ mocked.reconcileBilling.mockRejectedValue(new Error("Stripe unavailable"))+ await expect(getBillingSummary(db, () => stripe, env, "owner")).rejects.toThrow("Stripe unavailable")+ expect(mocked.getEffectivePlan).not.toHaveBeenCalled()+ })+it.each([false, true])("preserves the database plan without constructing Stripe for an empty catalog, Founder=%s", async (isFounder) => {founder = isFounderconst client = vi.fn(() => { throw new BillingError("BILLING_UNAVAILABLE", 503) })@@ -170,12 +186,14 @@ describe("one unresolved Checkout per owner", () => {await expect(checkout()).resolves.toHaveProperty("url")expect(sessions).toHaveLength(1)})- it("does not rotate an aged unknown Stripe outcome", async () => {- row.checkoutAttempt = { id: "old", priceId: "studio", email: "[email protected]", origin: "http://localhost:3000", startedAt: 1, sessionId: null }+ it("recovers an unknown attempt only after its fixed payment window ends", async () => {+ row.checkoutAttempt = { id: "old", priceId: "studio", email: "[email protected]", origin: "http://localhost:3000", startedAt: Math.floor(Date.now() / 1000) - 23 * 3600, sessionId: null }await expect(checkout()).rejects.toMatchObject({ code: "BILLING_CHECKOUT_UNRESOLVED" })expect(customerCreates).not.toHaveBeenCalled()- expect(sessionCreates).not.toHaveBeenCalled()- expect(row.checkoutAttempt.id).toBe("old")+ row.checkoutAttempt.startedAt -= 3601+ await expect(checkout("house")).resolves.toHaveProperty("url")+ expect(row.checkoutAttempt?.id).not.toBe("old")+ expect(sessionCreates).toHaveBeenCalledOnce()})it("permits replacement only after Stripe confirms the previous session expired", async () => {await checkout()diff --git a/src/web/src/lib/billing/service.ts b/src/web/src/lib/billing/service.tsindex 50a51177a..e55532315 100644--- a/src/web/src/lib/billing/service.ts+++ b/src/web/src/lib/billing/service.ts@@ -1,6 +1,6 @@import { queries, type CheckoutAttempt, type Database, type BillingSummary } from "@alook/shared"import type Stripe from "stripe"-import { assertStripeMode, billingOrigin, BillingError, stripeId } from "./client"+import { assertStripeMode, billingClient, billingOrigin, BillingError, stripeId } from "./client"import { getOffers, requireOffer } from "./catalog"import { currentSubscription, reconcileBilling } from "./reconcile"import {@@ -21,9 +21,11 @@ async function requireBillingOwner(db: Database, userId: string, founderAcknowle}export async function getBillingSummary(db: Database, stripe: () => Stripe, env: Env, userId: string): Promise<BillingSummary> {+ const billing = await queries.billing.getBilling(db, userId)+ if (billing?.customerId) await reconcileBilling(db, stripe(), env, userId)const effective = await queries.billing.getEffectivePlan(db, userId)if (effective.isFounder) return { plan: effective.plan, isFounder: true, offers: await getOffers(db, stripe, env), subscription: null }- const [row, offers] = await Promise.all([queries.billing.getBilling(db, userId), getOffers(db, stripe, env)])+ const [row, offers] = await Promise.all([billing?.customerId ? queries.billing.getBilling(db, userId) : billing, getOffers(db, stripe, env)])return { plan: effective.plan, isFounder: false, offers, subscription: row?.subscription ?? null }}@@ -90,6 +92,10 @@ export async function createCheckout(if (!await queries.billing.updateBilling(db, row, { checkoutAttempt: null })) continuecontinue}+ if (!session && Date.now() / 1000 >= attempt.startedAt + 24 * 3600) {+ if (!await queries.billing.updateBilling(db, row, { checkoutAttempt: null })) continue+ continue+ }if (attempt.priceId !== priceId) {if (!session || session.status !== "open") throw new BillingError("BILLING_CHECKOUT_IN_PROGRESS")try {@@ -210,7 +216,23 @@ export async function cancelScheduledChange(db: Database, stripe: Stripe, env: Eif (!["released", "completed", "canceled"].includes(fresh.status)) throw error}}- await reconcileBilling(db, stripe, env, userId)}return getBillingSummary(db, () => stripe, env, userId)}++export async function closeAccountBilling(db: Database, env: Env, userId: string) {+ const row = await queries.billing.getBilling(db, userId)+ if (!row) return+ if (!row.customerId && !row.checkoutAttempt) return+ const stripe = billingClient(env)+ const session = await sessionForAttempt(stripe, env, row)+ if (session?.status === "open") {+ await stripe.checkout.sessions.expire(session.id)+ } else if (!session && row.checkoutAttempt && Date.now() / 1000 < row.checkoutAttempt.startedAt + 24 * 3600) {+ throw new BillingError("BILLING_CHECKOUT_UNRESOLVED", 503)+ }+ const subscription = await currentSubscription(stripe, env, row)+ if (subscription && !["canceled", "incomplete_expired"].includes(subscription.status)) {+ await stripe.subscriptions.cancel(subscription.id)+ }+}diff --git a/src/web/src/lib/community/machine-disconnect.test.ts b/src/web/src/lib/community/machine-disconnect.test.tsindex 62856d60a..3c2062a35 100644--- a/src/web/src/lib/community/machine-disconnect.test.ts+++ b/src/web/src/lib/community/machine-disconnect.test.ts@@ -1,7 +1,7 @@import { describe, it, expect, vi, beforeEach, afterAll } from "vitest"import fs from "node:fs"import path from "node:path"-import { forceCloseCommunityMachineByDoName } from "./machine-disconnect"+import { forceCloseCommunityMachineByDoName, forceCloseCommunityMachinesByDoNames } from "./machine-disconnect"const originalFetch = globalThis.fetchconst mockFetch = vi.fn<(...args: unknown[]) => Promise<Response>>()@@ -96,3 +96,30 @@ describe("forceCloseCommunityMachineByDoName", () => {expect(src).not.toMatch(/DEV_WS_DO_URL/)})})++it("requires a successful shutdown receipt when account deletion requests it", async () => {+ const env = { WS_DO_WORKER: { fetch: vi.fn(async () => new Response("unavailable", { status: 503 })) } } as unknown as Env+ mockFetch.mockResolvedValue(new Response("unavailable", { status: 503 }))+ await expect(forceCloseCommunityMachineByDoName(env, "machine", true)).rejects.toThrow("Machine disconnect failed")+})++it("propagates a transport failure for required shutdowns", async () => {+ const env = { WS_DO_WORKER: { fetch: vi.fn(async () => { throw new Error("binding unavailable") }) } } as unknown as Env+ mockFetch.mockRejectedValue(new Error("network unavailable"))+ await expect(forceCloseCommunityMachineByDoName(env, "machine", true)).rejects.toThrow()+})++it("propagates required shutdown failure across multiple machine credentials", async () => {+ const binding = vi.fn(async (url: string) => new Response(null, { status: url.includes("failed") ? 503 : 200 }))+ mockFetch.mockResolvedValue(new Response(null, { status: 503 }))+ await expect(forceCloseCommunityMachinesByDoNames({ WS_DO_WORKER: { fetch: binding } } as unknown as Env, ["healthy", "failed"], true)).rejects.toThrow()+ expect(binding).toHaveBeenCalledTimes(2)+})++it("preserves best-effort batch shutdown when no strict policy is requested", async () => {+ const binding = vi.fn(async () => new Response(null, { status: 503 }))+ mockFetch.mockImplementation(async () => new Response(null, { status: 503 }))+ await expect(forceCloseCommunityMachinesByDoNames({ WS_DO_WORKER: { fetch: binding } } as unknown as Env, ["first", "second"]))+ .resolves.toBeUndefined()+ expect(binding).toHaveBeenCalledTimes(2)+})diff --git a/src/web/src/lib/community/machine-disconnect.ts b/src/web/src/lib/community/machine-disconnect.tsindex 37047ec14..00710e816 100644--- a/src/web/src/lib/community/machine-disconnect.ts+++ b/src/web/src/lib/community/machine-disconnect.ts@@ -10,22 +10,25 @@ const log = createLogger({ service: "community-machine-disconnect" })* because the DO is keyed by that suffix — not by `machineId` — so a machine* with N historical credentials fans out N force-close calls.*/-export async function forceCloseCommunityMachineByDoName(env: Env, doName: string): Promise<void> {+export async function forceCloseCommunityMachineByDoName(env: Env, doName: string, required = false): Promise<void> {const path = `/community-machine/${encodeURIComponent(doName)}/force-close`try {const res = await wsDoFetch(env, path, { method: "POST" }, { label: doName })if (!res.ok) {log.warn("force-close non-ok", { status: res.status, doName })+ if (required) throw new Error("Machine disconnect failed")}} catch (err) {log.warn("force-close fetch failed", { err: String(err), doName })+ if (required) throw err}}/** Force-close every DO for a set of credential do_name suffixes. */export async function forceCloseCommunityMachinesByDoNames(env: Env,- doNames: string[]+ doNames: string[],+ required = false,): Promise<void> {- await Promise.all(doNames.map((n) => forceCloseCommunityMachineByDoName(env, n)))+ await Promise.all(doNames.map((n) => forceCloseCommunityMachineByDoName(env, n, required)))}diff --git a/src/web/src/lib/community/upload-body.test.ts b/src/web/src/lib/community/upload-body.test.tsnew file mode 100644index 000000000..19d21732d--- /dev/null+++ b/src/web/src/lib/community/upload-body.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it, vi } from "vitest"+import { MAX_ATTACHMENT_SIZE_BYTES } from "@alook/shared"+import { readUploadFormData, UploadTooLargeError } from "./upload-body"++describe("bounded multipart upload", () => {+ it("accepts the advertised maximum file with multipart overhead", async () => {+ const form = new FormData()+ form.set("file", new File([new Uint8Array(MAX_ATTACHMENT_SIZE_BYTES)], "max.bin"))+ const parsed = await readUploadFormData(new Request("http://upload", { method: "POST", body: form }))+ expect((parsed.get("file") as File).size).toBe(MAX_ATTACHMENT_SIZE_BYTES)+ })+ it("rejects a declared oversized body without reading it", async () => {+ const request = new Request("http://upload", { method: "POST", headers: { "Content-Length": "999999999" } })+ await expect(readUploadFormData(request)).rejects.toBeInstanceOf(UploadTooLargeError)+ })+ it.each([undefined, "1"])("bounds streamed reads despite Content-Length %s", async (declared) => {+ const cancel = vi.fn()+ let chunks = 0+ const body = new ReadableStream<Uint8Array>({+ pull(controller) { chunks++; controller.enqueue(new Uint8Array(1024 * 1024)) }, cancel,+ })+ const request = new Request("http://upload", {+ method: "POST", body, duplex: "half",+ headers: { "Content-Type": "multipart/form-data; boundary=test", ...(declared ? { "Content-Length": declared } : {}) },+ } as RequestInit)+ await expect(readUploadFormData(request)).rejects.toBeInstanceOf(UploadTooLargeError)+ await new Promise(resolve => setTimeout(resolve, 0))+ expect(chunks).toBeLessThan(30)+ expect(cancel).toHaveBeenCalled()+ })+})++it("preserves malformed multipart errors instead of reporting overflow", async () => {+ await expect(readUploadFormData(new Request("http://upload", { method: "POST", body: "not multipart" }))).rejects.not.toBeInstanceOf(UploadTooLargeError)+})diff --git a/src/web/src/lib/community/upload-body.ts b/src/web/src/lib/community/upload-body.tsnew file mode 100644index 000000000..9475c28d2--- /dev/null+++ b/src/web/src/lib/community/upload-body.ts@@ -0,0 +1,26 @@+import { MAX_ATTACHMENT_SIZE_BYTES, MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES } from "@alook/shared"++export class UploadTooLargeError extends Error {}++export async function readUploadFormData(request: Request): Promise<FormData> {+ const maxBytes = MAX_ATTACHMENT_SIZE_BYTES + MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES + 64 * 1024+ if (Number(request.headers.get("content-length")) > maxBytes) throw new UploadTooLargeError()+ let bytes = 0+ let exceeded = false+ const body = request.body?.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({+ transform(chunk, controller) {+ bytes += chunk.byteLength+ if (bytes > maxBytes) {+ exceeded = true+ throw new UploadTooLargeError()+ }+ controller.enqueue(chunk)+ },+ }))+ try {+ return await new Response(body, { headers: { "content-type": request.headers.get("content-type") ?? "" } }).formData()+ } catch (error) {+ if (exceeded) throw new UploadTooLargeError()+ throw error+ }+}diff --git a/src/web/src/lib/community/upload.test.ts b/src/web/src/lib/community/upload.test.tsindex 0962cc5fa..e041af66d 100644--- a/src/web/src/lib/community/upload.test.ts+++ b/src/web/src/lib/community/upload.test.ts@@ -1,3 +1,4 @@+vi.mock("./upload-body", () => ({ readUploadFormData: (req: Request) => req.formData(), UploadTooLargeError: class extends Error {} }))import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"import { structuredJpegFixture } from "@/test/fixtures/media"@@ -94,7 +95,7 @@ function reqWithUpload(file: unknown, thumbnail: unknown, width = "640", heightconst req = new NextRequest("http://localhost/u", { method: "POST" })req.formData = (async () => {const values: Record<string, unknown> = { file, thumbnail, width, height }- return { get: (key: string) => values[key] ?? null } as unknown as FormData+ return { keys: () => Object.keys(values), get: (key: string) => values[key] ?? null } as unknown as FormData}) as typeof req.formDatareturn req}@@ -785,3 +786,34 @@ describe("runAttachmentUpload", () => {expect(del).not.toHaveBeenCalled()})})++it.each(["extra", "file"])("rejects unexpected or repeated multipart field %s before storage writes", async (key) => {+ const put = vi.fn()+ const request = new NextRequest("http://localhost/upload", { method: "POST" })+ const form = new FormData()+ form.append("file", new File(["hello"], "a.txt"))+ form.append(key, "ignored")+ request.formData = async () => form+ const result = await handleAttachmentUpload(request, envWithR2(put))+ expect(result.ok).toBe(false)+ expect(put).not.toHaveBeenCalled()+})++it("rejects a string thumbnail before writing storage", async () => {+ const put = vi.fn()+ const result = await handleAttachmentUpload(reqWithUpload(fakeFile("a.png", "image/png", 10), "invalid"), envWithR2(put))+ expect(result.ok).toBe(false)+ if (!result.ok) expect(await result.response.json()).toMatchObject({ error: "invalid thumbnail" })+ expect(put).not.toHaveBeenCalled()+})++import { UploadTooLargeError } from "./upload-body"+it.each([[new UploadTooLargeError(), 413], [new Error("malformed"), 400]] as const)("maps multipart reader failure to status %s %s without R2 writes", async (error, status) => {+ const request = new NextRequest("http://localhost/upload", { method: "POST" })+ request.formData = async () => { throw error }+ const put = vi.fn()+ const result = await handleAttachmentUpload(request, envWithR2(put))+ expect(result.ok).toBe(false)+ if (!result.ok) expect(result.response.status).toBe(status)+ expect(put).not.toHaveBeenCalled()+})diff --git a/src/web/src/lib/community/upload.ts b/src/web/src/lib/community/upload.tsindex 8f0d2fb4e..6c3addf7e 100644--- a/src/web/src/lib/community/upload.ts+++ b/src/web/src/lib/community/upload.ts@@ -1,3 +1,4 @@+import { readUploadFormData, UploadTooLargeError } from "./upload-body"import { createHash } from "node:crypto"import { NextRequest, NextResponse } from "next/server"import {@@ -182,9 +183,16 @@ function jpegDimensions(bytes: Uint8Array): { width: number; height: number } |async function readFile(req: NextRequest): Promise<ParsedUpload | UploadErr> {let formData: FormDatatry {- formData = await req.formData()- } catch {- return { ok: false, response: writeError("invalid form data", 400) }+ formData = await readUploadFormData(req)+ } catch (error) {+ return { ok: false, response: writeError("invalid or oversized upload request", error instanceof UploadTooLargeError ? 413 : 400) }+ }+ const fields = new Set<string>()+ for (const key of formData.keys()) {+ if (!["file", "thumbnail", "width", "height"].includes(key) || fields.has(key)) {+ return { ok: false, response: writeError("unexpected or repeated upload field", 400) }+ }+ fields.add(key)}const file = formData.get("file")if (!isFileLike(file)) return { ok: false, response: writeError("no file provided", 400) }diff --git a/src/web/src/lib/middleware/auth.ts b/src/web/src/lib/middleware/auth.tsindex fefc7afdd..25b489154 100644--- a/src/web/src/lib/middleware/auth.ts+++ b/src/web/src/lib/middleware/auth.ts@@ -142,6 +142,7 @@ async function resolveSession(try {sessionResult = await observeWorkerOperation("auth.get_session", {}, () => auth.api.getSession({headers: req.headers,+ query: { disableCookieCache: new URL(req.url).pathname.startsWith("/api/community/") },returnHeaders: true,})) as { headers: Headers; response: Awaited<ReturnType<typeof auth.api.getSession>> }lastErr = undefined@@ -154,20 +155,6 @@ async function resolveSession(if (lastErr) return { kind: "error" }if (!sessionResult?.response) return { kind: "none" }- // Session guard — Better-Auth's Drizzle adapter reads user rows via- // .select() directly, so a session cookie may carry stale state after a- // user is soft-deleted or if some future flow ever mints a session for a- // bot user row. Enforce at request-time:- // - deletedAt != null → session invalid- // - isBot === true → session invalid (bots must never sign in)- // Belt-and-braces with the databaseHooks.session.create.before hook.- // isBot/deletedAt ride the session user via better-auth `additionalFields`- // (see auth.ts) — no dedicated per-request `getUserInternal` D1 read. Their- // freshness = the session cookie-cache period (prod 5min); revocation- // latency is therefore bounded by that window and is NOT loosened beyond- // today's getSession cookie cache. (Bots never mint a session — the- // session.create hook blocks them — so the isBot check is belt-and-braces;- // deletedAt is the one with a real, ≤cookie-period latency.)const guardUser = sessionResult.response.user as { isBot?: boolean | null; deletedAt?: string | null }const sessionUserIsBot = guardUser.isBot === trueif (sessionUserIsBot || (guardUser.deletedAt ?? null) !== null) {diff --git a/src/web/src/lib/observability/coverage.ts b/src/web/src/lib/observability/coverage.tsindex 0a4cf130c..0c84e9d4a 100644--- a/src/web/src/lib/observability/coverage.ts+++ b/src/web/src/lib/observability/coverage.ts@@ -157,6 +157,7 @@ export const apiRoutes = ["/api/desktop/update/[target]/[arch]/[current_version]","/api/email/notify","/api/health",+ "/api/internal/account-maintenance","/api/meeting/callback","/api/pricing","/api/privacy/analytics-consent",diff --git a/src/web/src/lib/rate-limit.test.ts b/src/web/src/lib/rate-limit.test.tsindex 368009217..b605339e0 100644--- a/src/web/src/lib/rate-limit.test.ts+++ b/src/web/src/lib/rate-limit.test.ts@@ -68,3 +68,9 @@ describe("checkRateLimit — unified rate-limit entry", () => {expect(r).toEqual({ allowed: true })})})++it("fails closed only for upload admission when the rate limiter is unavailable", async () => {+ mockWsDoFetch.mockRejectedValue(new Error("DO unavailable"))+ expect(await checkRateLimit({} as Env, "community:upload", "owner")).toEqual({ allowed: false, retryAfterSec: 60 })+ expect(await checkRateLimit({} as Env, "community:msgSend", "owner")).toEqual({ allowed: true })+})diff --git a/src/web/src/lib/rate-limit.ts b/src/web/src/lib/rate-limit.tsindex f5e7d1bfc..97b1e6eac 100644--- a/src/web/src/lib/rate-limit.ts+++ b/src/web/src/lib/rate-limit.ts@@ -18,11 +18,6 @@ export type { RateLimitName, RateLimitPolicy, RateLimitResult }* Sharding: one DO instance per (name, key) pair — different rate-limit* names never collide even with a shared key.*- * Fail-open: transport errors return `{ allowed: true }`. The DO is a- * strong-consistency counter, not a security perimeter; auth/authz above- * the rate limit is what actually gates access. Locking every user out- * because we can't reach the DO would be a worse failure mode.- ** @param env Worker env (used to reach `WS_DO_WORKER`).* @param name Registered policy name — must exist in `RATE_LIMITS`.* @param key Caller-chosen shard key. Typically userId, but any stable@@ -38,9 +33,10 @@ export async function checkRateLimit(key: string,overrides?: Partial<RateLimitPolicy>,): Promise<RateLimitResult> {- const policy = RATE_LIMITS[name]+ const policy: RateLimitPolicy = RATE_LIMITS[name]const windowMs = overrides?.windowMs ?? policy.windowMsconst max = overrides?.max ?? policy.max+ const unavailable: RateLimitResult = policy.failClosed ? { allowed: false, retryAfterSec: 60 } : { allowed: true }try {const res = await wsDoFetch(env,@@ -52,9 +48,9 @@ export async function checkRateLimit(},{ label: `${name}:${key}`, type: "rate-limit" },)- if (!res.ok) return { allowed: true }+ if (!res.ok) return unavailablereturn (await res.json()) as RateLimitResult} catch {- return { allowed: true }+ return unavailable}}diff --git a/src/web/src/lib/worker-runtime-security.test.ts b/src/web/src/lib/worker-runtime-security.test.tsnew file mode 100644index 000000000..fba27a858--- /dev/null+++ b/src/web/src/lib/worker-runtime-security.test.ts@@ -0,0 +1,17 @@+import { expect, it, vi } from "vitest"+import { createWebWorkerHandler } from "./worker-runtime"++it("strips forged internal authorization before any public request reaches OpenNext", async () => {+ const upstream = vi.fn(async (request: Request) => {+ expect(request.headers.has("X-Alook-Internal")).toBe(false)+ return new Response(null, { status: 404 })+ })+ const worker = createWebWorkerHandler({ fetch: upstream })+ for (const path of ["/api/internal/account-maintenance", "/api/internal//account-maintenance", "/api/internal/account-maintenance/"]) {+ const response = await worker.fetch!(new Request(`https://app.test${path}`, {+ method: "POST", headers: { "x-alook-internal": "1" },+ }), {} as CloudflareEnv, {} as ExecutionContext)+ expect(response.status).toBe(404)+ }+ expect(upstream).toHaveBeenCalledTimes(3)+})diff --git a/src/web/src/lib/worker-runtime.ts b/src/web/src/lib/worker-runtime.tsindex ae0e89143..002045fa5 100644--- a/src/web/src/lib/worker-runtime.ts+++ b/src/web/src/lib/worker-runtime.ts@@ -16,6 +16,8 @@ export function createWebWorkerHandler(): ExportedHandler<CloudflareEnv> {return {async fetch(request, env, ctx) {+ request = new Request(request) as typeof request+ request.headers.delete("X-Alook-Internal")const url = new URL(request.url)const invocation = ctx.tracing?.getActiveSpan?.()const isWsUpgrade = request.headers.get("Upgrade")?.toLowerCase() === "websocket"diff --git a/src/web/src/test-runtime/custom-worker.test.ts b/src/web/src/test-runtime/custom-worker.test.tsindex 20a87c750..bc55e7b96 100644--- a/src/web/src/test-runtime/custom-worker.test.ts+++ b/src/web/src/test-runtime/custom-worker.test.ts@@ -36,3 +36,22 @@ describe("custom Worker composition", () => {expect(JSON.stringify(setAttribute.mock.calls)).not.toContain("b".repeat(40))})})++it.each([200, 503])("dispatches cron through OpenNext and propagates status %s", async (status) => {+ const generated = (await import("./open-next-node-stub")).default+ const fetch = vi.spyOn(generated, "fetch").mockResolvedValue(new Response(null, { status }))+ const env = {} as CloudflareEnv+ const ctx = {} as ExecutionContext+ try {+ const task = handler.scheduled!({} as ScheduledController, env, ctx)+ if (status === 200) await expect(task).resolves.toBeUndefined()+ else await expect(task).rejects.toThrow("Account maintenance failed: 503")+ const [request] = fetch.mock.calls[0]!+ expect(request.url).toBe("https://internal/api/internal/account-maintenance")+ expect(request.method).toBe("POST")+ expect(request.headers.get("X-Alook-Internal")).toBe("1")+ expect(fetch).toHaveBeenCalledWith(request, env, ctx)+ } finally {+ fetch.mockRestore()+ }+})diff --git a/src/web/test-runtime/attachment-reuse.runtime.test.ts b/src/web/test-runtime/attachment-reuse.runtime.test.tsindex 95d3596fa..b24ddfe7b 100644--- a/src/web/test-runtime/attachment-reuse.runtime.test.ts+++ b/src/web/test-runtime/attachment-reuse.runtime.test.ts@@ -14,7 +14,7 @@ const keys = new Set<string>()const request = (name: string, bytes: Uint8Array, type = "application/pdf") => {const form = new FormData()form.set("file", new File([bytes], name, { type }))- return { formData: async () => form } as NextRequest+ return new Request("https://example.test/upload", { method: "POST", body: form }) as NextRequest}beforeEach(async () => {uploader = `file-runtime-${crypto.randomUUID()}`@@ -54,13 +54,18 @@ describe("file content storage on real D1/R2 bindings", () => {expect(await bindings.COMMUNITY_MEDIA.get(a.r2Key)).not.toBeNull()})- it("the same filename cannot merge different content or trust a client hash", async () => {+ it("rejects a client hash and keeps different content separate despite equal filenames", async () => {const upload = (bytes: Uint8Array) => {const form = new FormData()form.set("file", new File([bytes], "same.pdf", { type: "application/pdf" }))- form.set("sha256", "0".repeat(64))- return handleAttachmentUpload({ formData: async () => form } as NextRequest, bindings)+ return handleAttachmentUpload(new Request("https://example.test/upload", { method: "POST", body: form }) as NextRequest, bindings)}+ const forged = new FormData()+ forged.set("file", new File([new Uint8Array(16)], "same.pdf", { type: "application/pdf" }))+ forged.set("sha256", "0".repeat(64))+ const rejected = await handleAttachmentUpload(new Request("https://example.test/upload", { method: "POST", body: forged }) as NextRequest, bindings)+ expect(rejected.ok).toBe(false)+ if (!rejected.ok) expect(rejected.response.status).toBe(400)const a = await upload(crypto.getRandomValues(new Uint8Array(16)))const b = await upload(crypto.getRandomValues(new Uint8Array(16)))expect(a.ok && b.ok).toBe(true)@@ -77,7 +82,7 @@ describe("file content storage on real D1/R2 bindings", () => {const form = new FormData()form.set("file", new File([original], "picture.png", { type: "image/png" }))form.set("thumbnail", new File([structuredJpegFixture(width, 10)], "thumbnail.jpg", { type: "image/jpeg" }))- return { formData: async () => form } as NextRequest+ return new Request("https://example.test/upload", { method: "POST", body: form }) as NextRequest}const a = await handleAttachmentUpload(make(10), bindings)const b = await handleAttachmentUpload(make(20), bindings)diff --git a/src/web/wrangler.toml b/src/web/wrangler.tomlindex aea11613a..cb0b1bc1b 100644--- a/src/web/wrangler.toml+++ b/src/web/wrangler.toml@@ -113,3 +113,6 @@ OPENROUTER_JEV_BASE_URL = "https://openrouter.ai"OPENROUTER_JEV_MODEL = "typesafe/jev-1.13"TYPESAFE_JEV_BASE_URL = "https://api.typesafe.ai"TYPESAFE_JEV_MODEL = "jev-1.13.0"++[triggers]+crons = ["17 * * * *"]diff --git a/src/ws-do/src/ws-durable/agent-interrupt.test.ts b/src/ws-do/src/ws-durable/agent-interrupt.test.tsindex fe2196722..b626fd13a 100644--- a/src/ws-do/src/ws-durable/agent-interrupt.test.ts+++ b/src/ws-do/src/ws-durable/agent-interrupt.test.ts@@ -25,7 +25,7 @@ describe("agent running-turn interrupt WS routing", () => {function userSocket(userId = "owner_1") {const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId, authenticated: true })+ ws.serializeAttachment({ type: "user", userId, authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })return ws}diff --git a/src/ws-do/src/ws-durable/community-delivery-state.test.ts b/src/ws-do/src/ws-durable/community-delivery-state.test.tsindex 4910bf104..bb795fcae 100644--- a/src/ws-do/src/ws-durable/community-delivery-state.test.ts+++ b/src/ws-do/src/ws-durable/community-delivery-state.test.ts@@ -17,7 +17,7 @@ describe("community delivery connection attachment state", () => {type: "user",userId: "u".repeat(64),targetUserId: "t".repeat(64),- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,name: "n".repeat(128),discriminator: "1234",}@@ -64,7 +64,7 @@ describe("community delivery connection attachment state", () => {const base: UserConnectionState = {type: "user",userId: "user-1",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,communityDeliveryProgress: [[operationId, "a".repeat(64), 1, 1]],}expect(preflightCommunityConnectionState({diff --git a/src/ws-do/src/ws-durable/internal.ts b/src/ws-do/src/ws-durable/internal.tsindex ca7f2476c..fbb02b8b9 100644--- a/src/ws-do/src/ws-durable/internal.ts+++ b/src/ws-do/src/ws-durable/internal.ts@@ -16,6 +16,8 @@ export type ConnectionState =userId: stringtargetUserId?: stringauthenticated: boolean+ sessionId?: string+ sessionValidUntil?: numbername?: stringdiscriminator?: stringcommunityContract?: CommunityContractdiff --git a/src/ws-do/src/ws-durable/machine-control.test.ts b/src/ws-do/src/ws-durable/machine-control.test.tsindex 2584775e3..63f173156 100644--- a/src/ws-do/src/ws-durable/machine-control.test.ts+++ b/src/ws-do/src/ws-durable/machine-control.test.ts@@ -67,7 +67,7 @@ describe("WebSocketDurableObject", () => {supported.serializeAttachment({ type: "community-machine", authenticated: true, machineId: "cm_1", userId: "u_1", machineStop: true })legacy.serializeAttachment({ type: "community-machine", authenticated: true, machineId: "cm_1", userId: "u_1" })unauthed.serializeAttachment({ type: "community-machine", authenticated: false, machineId: "cm_1", userId: "u_1", machineStop: true })- user.serializeAttachment({ type: "user", authenticated: true, userId: "u_1" })+ user.serializeAttachment({ type: "user", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, userId: "u_1" })getWebSockets.mockReturnValue([supported, legacy, unauthed, user])const response = await durable.fetch(new Request("http://internal/stop", { method: "POST" }))expect(await response.json()).toEqual({ sent: 1, unsupported: 1 })diff --git a/src/ws-do/src/ws-durable/presence-typing.test.ts b/src/ws-do/src/ws-durable/presence-typing.test.tsindex 36dcc18d4..c5ba129e1 100644--- a/src/ws-do/src/ws-durable/presence-typing.test.ts+++ b/src/ws-do/src/ws-durable/presence-typing.test.ts@@ -71,7 +71,7 @@ describe("WebSocketDurableObject", () => {// Set up two WebSockets: one authenticated, one notconst wsAuth = createMockWebSocket()- wsAuth.serializeAttachment({ type: "user", userId: "u1", authenticated: true })+ wsAuth.serializeAttachment({ type: "user", userId: "u1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })const wsUnauth = createMockWebSocket()wsUnauth.serializeAttachment({ type: "user", userId: "", authenticated: false }); (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsAuth, wsUnauth])@@ -112,9 +112,9 @@ describe("WebSocketDurableObject", () => {const { durable, ctx } = createDO()const wsOpen = createMockWebSocket(WebSocket.OPEN)- wsOpen.serializeAttachment({ type: "user", userId: "u1", authenticated: true })+ wsOpen.serializeAttachment({ type: "user", userId: "u1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })const wsClosed = createMockWebSocket(WebSocket.CLOSED)- wsClosed.serializeAttachment({ type: "user", userId: "u1", authenticated: true })+ wsClosed.serializeAttachment({ type: "user", userId: "u1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })wsClosed.send.mockImplementation(() => { throw new Error("Connection closed") }); (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsOpen, wsClosed])@@ -134,7 +134,7 @@ describe("WebSocketDurableObject", () => {it("sweeps an authenticated historical mismatch before sending", async () => {const { durable, ctx } = createDO()const attacker = createMockWebSocket()- attacker.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })+ attacker.serializeAttachment({ type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([attacker])const res = await durable.fetch(new Request("http://internal/broadcast", {@@ -145,7 +145,7 @@ describe("WebSocketDurableObject", () => {expect(await res.json()).toEqual({ sent: 0 })expect(attacker.send).not.toHaveBeenCalled()- expect(attacker.deserializeAttachment()).toEqual({+ expect(attacker.deserializeAttachment()).toMatchObject({type: "user",userId: "attacker",authenticated: false,@@ -167,9 +167,9 @@ describe("WebSocketDurableObject", () => {it("sends only to the matching user while sweeping mixed historical sockets", async () => {const { durable, ctx } = createDO()const victim = createMockWebSocket()- victim.serializeAttachment({ type: "user", userId: "victim", authenticated: true })+ victim.serializeAttachment({ type: "user", userId: "victim", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })const attacker = createMockWebSocket()- attacker.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })+ attacker.serializeAttachment({ type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([attacker, victim])const res = await durable.fetch(new Request("http://internal/broadcast", {@@ -214,7 +214,7 @@ describe("WebSocketDurableObject", () => {const daemon = createMockWebSocket()daemon.serializeAttachment({ type: "daemon", daemonId: "daemon-1", userId: "user-1", authenticated: true })const user = createMockWebSocket()- user.serializeAttachment({ type: "user", userId: "user-1", authenticated: true })+ user.serializeAttachment({ type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([user, daemon])const response = await durable.fetch(new Request("http://internal/check-alive"))@@ -268,7 +268,7 @@ describe("WebSocketDurableObject", () => {const { durable, ctx } = createDO()mockGetUserInternal.mockResolvedValue({ isBot: false } as any)const wsAuth = createMockWebSocket()- wsAuth.serializeAttachment({ type: "user", userId: "human-1", authenticated: true })+ wsAuth.serializeAttachment({ type: "user", userId: "human-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 }); (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsAuth])const res = await durable.fetch(new Request("http://internal/check-user-online?userId=human-1"))@@ -280,13 +280,13 @@ describe("WebSocketDurableObject", () => {it("fails closed and sweeps user sockets when userId is missing entirely", async () => {const { durable, ctx } = createDO()const wsAuth = createMockWebSocket()- wsAuth.serializeAttachment({ type: "user", userId: "u1", authenticated: true })+ wsAuth.serializeAttachment({ type: "user", userId: "u1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 }); (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsAuth])const res = await durable.fetch(new Request("http://internal/check-user-online"))expect(await res.json()).toEqual({ online: false })- expect(wsAuth.deserializeAttachment()).toEqual({+ expect(wsAuth.deserializeAttachment()).toMatchObject({type: "user",userId: "u1",authenticated: false,@@ -299,7 +299,7 @@ describe("WebSocketDurableObject", () => {const { durable, ctx } = createDO()mockGetUserInternal.mockResolvedValue({ isBot: false } as any)const attacker = createMockWebSocket()- attacker.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })+ attacker.serializeAttachment({ type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([attacker])const res = await durable.fetch(@@ -307,7 +307,7 @@ describe("WebSocketDurableObject", () => {)expect(await res.json()).toEqual({ online: false })- expect(attacker.deserializeAttachment()).toEqual({+ expect(attacker.deserializeAttachment()).toMatchObject({type: "user",userId: "attacker",authenticated: false,@@ -629,7 +629,7 @@ describe("WebSocketDurableObject", () => {it("does nothing when a typing frame has no channelId", async () => {const { durable } = createDO()const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,@@ -646,7 +646,7 @@ describe("WebSocketDurableObject", () => {mockGetChannelForMember.mockResolvedValue({ id: "channel-1", serverId: "server-1" })mockResolveScopeMemberUserIds.mockResolvedValue(["sender-1", "recipient-1"])const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })const now = vi.spyOn(Date, "now")try {now.mockReturnValue(10_000)@@ -678,7 +678,7 @@ describe("WebSocketDurableObject", () => {const { durable } = createDO()mockGetChannelForMember.mockResolvedValue(null)const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })let timestamp = 100_000const now = vi.spyOn(Date, "now").mockImplementation(() => timestamp)try {@@ -709,7 +709,7 @@ describe("WebSocketDurableObject", () => {mockGetChannelForMember.mockResolvedValueOnce(null)const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,@@ -732,7 +732,7 @@ describe("WebSocketDurableObject", () => {mockResolveScopeMemberUserIds.mockResolvedValueOnce(["member-1", "member-2", "sender-1"])const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,@@ -761,7 +761,7 @@ describe("WebSocketDurableObject", () => {mockResolveScopeMemberUserIds.mockResolvedValueOnce(["sender-1", "member-1"])const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,@@ -789,7 +789,7 @@ describe("WebSocketDurableObject", () => {mockResolveScopeMemberUserIds.mockResolvedValueOnce(["sender-1", "reader-1"])const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,@@ -813,7 +813,7 @@ describe("WebSocketDurableObject", () => {let clock = 10_000const now = vi.spyOn(Date, "now").mockImplementation(() => clock)const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })const start = JSON.stringify({ type: "community:typing.start", channelId: "t-1" })try {await durable.webSocketMessage(ws as any, start)@@ -850,7 +850,7 @@ describe("WebSocketDurableObject", () => {mockGetChannelForMember.mockResolvedValueOnce(null)const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,@@ -871,7 +871,7 @@ describe("WebSocketDurableObject", () => {mockGetDMPeer.mockResolvedValueOnce({ otherUserId: "bob" })const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,@@ -892,7 +892,7 @@ describe("WebSocketDurableObject", () => {mockAreFriends.mockResolvedValue(false)const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,@@ -919,7 +919,7 @@ describe("WebSocketDurableObject", () => {mockAreFriends.mockResolvedValue(true)const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,JSON.stringify({ type: "community:typing.start", channelId: "dm-1" }),@@ -941,7 +941,7 @@ describe("WebSocketDurableObject", () => {try { return await fn() } catch { return fn() }})const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,@@ -981,7 +981,7 @@ describe("WebSocketDurableObject", () => {});(env.WS_DO.get as ReturnType<typeof vi.fn>).mockReturnValue({ fetch })const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,@@ -1000,7 +1000,7 @@ describe("WebSocketDurableObject", () => {.mockResolvedValueOnce({ id: "chan-1", serverId: "server-1" })mockResolveScopeMemberUserIds.mockResolvedValue(["sender-1", "recipient-1"])const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,@@ -1042,7 +1042,7 @@ describe("WebSocketDurableObject", () => {it("consumes a typing.stop without a channel and does not fan out", async () => {const { durable } = createDO()const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,@@ -1067,7 +1067,7 @@ describe("WebSocketDurableObject", () => {mockGetChannelForMember.mockResolvedValue({ id: "chan-1", serverId: "server-1" })mockResolveScopeMemberUserIds.mockResolvedValue(["sender-1", "recipient-1"])const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,@@ -1096,7 +1096,7 @@ describe("WebSocketDurableObject", () => {const { durable } = createDO()mockGetChannelForMember.mockResolvedValue(null)const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any,@@ -1118,7 +1118,7 @@ describe("WebSocketDurableObject", () => {mockGetChannelForMember.mockResolvedValue({ id: "chan-1", serverId: "server-1" })mockResolveScopeMemberUserIds.mockResolvedValue(["sender-1", "recipient-1"])const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })let releaseFirstFetch!: () => voidmockStubFetch.mockImplementationOnce(() => new Promise<Response>((resolve) => {releaseFirstFetch = () => resolve(new Response(null, { status: 200 }))diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.tsindex b7dca1725..a5a59d1f3 100644--- a/src/ws-do/src/ws-durable/test-harness.ts+++ b/src/ws-do/src/ws-durable/test-harness.ts@@ -79,6 +79,7 @@ vi.mock("cloudflare:workers", () => ({// Mock @alook/sharedexport const mockGetValidSession = vi.fn<(db: unknown, token: string) => Promise<string | null>>()+export const mockGetValidSessionByIdForUser = vi.fn().mockResolvedValue({ expiresAt: "2099-01-01T00:00:00.000Z" })export const mockGetValidSessionWithIdentity = vi.fn<(db: unknown, token: string) => Promise<{ userId: string; name: string; discriminator: string } | null>>()export const mockGetMachineTokenByToken = vi.fn()export const mockGetLatestTokenForUser = vi.fn()@@ -383,7 +384,11 @@ vi.mock("@alook/shared", async () => {productPlan: { ...actual.queries.productPlan, assertMachineCapacity: (...a: any[]) => mockAssertMachineCapacity(...a) },session: {getValidSession: (db: unknown, token: string) => mockGetValidSession(db, token),- getValidSessionWithIdentity: (db: unknown, token: string) => mockGetValidSessionWithIdentity(db, token),+ getValidSessionWithIdentity: async (db: unknown, token: string) => {+ const identity = await mockGetValidSessionWithIdentity(db, token)+ return identity ? { sessionId: "test-session", expiresAt: "2099-01-01T00:00:00.000Z", ...identity } : null+ },+ getValidSessionByIdForUser: (...args: unknown[]) => mockGetValidSessionByIdForUser(...args),},machineToken: {getMachineTokenByToken: (...a: any[]) => mockGetMachineTokenByToken(...a),@@ -537,6 +542,7 @@ export const flushAsyncWork = async () => {}export function resetHarness() {vi.clearAllMocks()+ mockGetValidSessionByIdForUser.mockReset().mockResolvedValue({ expiresAt: "2099-01-01T00:00:00.000Z" })mockD1WithSession.mockReturnValue({})mockAssertMachineCapacity.mockReset().mockResolvedValue(undefined)mockGetMachineByIdForUser.mockResolvedValue({ id: "cm_1", status: "online", availableRuntimes: [] })diff --git a/src/ws-do/src/ws-durable/user-auth.test.ts b/src/ws-do/src/ws-durable/user-auth.test.tsindex 21d3eb4f6..bacffc3e8 100644--- a/src/ws-do/src/ws-durable/user-auth.test.ts+++ b/src/ws-do/src/ws-durable/user-auth.test.ts@@ -37,6 +37,7 @@ import {mockGetUserInternal,mockGetValidSession,mockGetValidSessionWithIdentity,+ mockGetValidSessionByIdForUser,mockHashCredential,mockInsertBotActivityEventAndPrune,mockInsertBotAuditModelChanged,@@ -79,7 +80,7 @@ describe("WebSocketDurableObject", () => {it("delivers a validated self-event to the authenticated target socket", async () => {const { durable, ctx } = createDO()const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])const res = await durable.fetch(new Request("http://internal/community-broadcast", {@@ -96,7 +97,7 @@ describe("WebSocketDurableObject", () => {it("rejects removed-version, invalid, and oversized frames before socket delivery", async () => {const { durable, ctx } = createDO()const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])const request = (body: string) => new Request("http://internal/community-broadcast", {method: "POST",@@ -120,7 +121,7 @@ describe("WebSocketDurableObject", () => {it("gates single content, preserves removal controls, and reports transient D1 failure", async () => {const { durable, ctx } = createDO()const socket = createMockWebSocket()- socket.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ socket.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([socket])const send = (event: unknown) => durable.fetch(new Request("http://internal/community-broadcast", {method: "POST",@@ -210,7 +211,7 @@ describe("WebSocketDurableObject", () => {it("cancels revoked content without changing progress, and retries transient failures", async () => {const { durable, ctx } = createDO()const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])const request = await requestFor()const original = ws.deserializeAttachment()@@ -234,7 +235,7 @@ describe("WebSocketDurableObject", () => {it("reads current sockets and progress only after concurrent authorization awaits", async () => {const { durable, ctx } = createDO()const old = createMockWebSocket()- old.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ old.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })const sockets = ctx.getWebSockets as ReturnType<typeof vi.fn>sockets.mockReturnValue([old])const releases: Array<(rows: Array<{ id: string }>) => void> = []@@ -245,7 +246,7 @@ describe("WebSocketDurableObject", () => {const second = durable.fetch(request.clone())await vi.waitFor(() => expect(releases).toHaveLength(2))const current = createMockWebSocket()- current.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ current.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })sockets.mockReturnValue([current])releases[1]!([{ id: "ch-1" }])await second@@ -277,9 +278,9 @@ describe("WebSocketDurableObject", () => {first.serializeAttachment({type: "user",userId: "user-42",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,})- second.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ second.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([first, second])const response = await durable.fetch(await requestFor())@@ -314,8 +315,8 @@ describe("WebSocketDurableObject", () => {it("restores selected formats from attachments and retains source progress for mixed tabs", async () => {const { durable, ctx } = createDO()const old = createMockWebSocket(), current = createMockWebSocket()- old.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })- current.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, communityContract: 2 })+ old.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })+ current.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: 2 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([old, current])const change = { type: "community:channel.membership.change", channelId: "thread", serverId: "server", userId: "user-42", relation: "notify", present: true }const request = await requestFor([change])@@ -351,7 +352,7 @@ describe("WebSocketDurableObject", () => {const { durable, ctx, env } = createDO()const sockets = [1, 2, 3].map((communityContract) => {const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, communityContract })+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract })return ws});(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue(sockets)@@ -381,8 +382,8 @@ describe("WebSocketDurableObject", () => {it("retries the original three-key payload after reconstruction and rejects a rebuilt cross-version operation before any frame or progress change", async () => {const { durable, ctx, env } = createDO()const completed = createMockWebSocket(), retrying = createMockWebSocket()- completed.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, communityContract: 1 })- retrying.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, communityContract: 2 })+ completed.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: 1 })+ retrying.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: 2 })retrying.send.mockImplementationOnce(() => { throw new Error("transient send") });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([completed, retrying])const original = await requestFor()@@ -393,7 +394,7 @@ describe("WebSocketDurableObject", () => {completed.send.mockClear()retrying.send.mockClear()const unstarted = createMockWebSocket()- unstarted.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, communityContract: 3 })+ unstarted.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: 3 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([completed, retrying, unstarted])const { WebSocketDurableObject } = await import("../ws-durable")const restored = new WebSocketDurableObject(ctx, env)@@ -415,7 +416,7 @@ describe("WebSocketDurableObject", () => {it("rejects unknown bundle versions and does not upgrade original v2 summary bytes for a v3 socket", async () => {const { durable, ctx } = createDO()const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, communityContract: 3 })+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: 3 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])const request = await requestFor()const body = await request.clone().json()@@ -428,7 +429,7 @@ describe("WebSocketDurableObject", () => {it("sends zero frames when any event is invalid", async () => {const { durable, ctx } = createDO()const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])const prepared = await prepareCommunityDeliveryEvents(events)if (!prepared.ok) throw new Error("fixture must prepare")@@ -452,7 +453,7 @@ describe("WebSocketDurableObject", () => {ws.serializeAttachment({type: "user",userId: "user-42",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,});(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])@@ -475,9 +476,9 @@ describe("WebSocketDurableObject", () => {it("records a successful tab, reports a sibling batch send failure, and retries only the sibling", async () => {const { durable, ctx } = createDO()const first = createMockWebSocket()- first.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ first.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })const second = createMockWebSocket()- second.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ second.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })second.send.mockImplementationOnce(() => { throw new Error("send failed") });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([first, second])@@ -510,13 +511,13 @@ describe("WebSocketDurableObject", () => {ready.serializeAttachment({type: "user",userId: "user-42",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,})const malformed = createMockWebSocket()malformed.serializeAttachment({type: "user",userId: "user-42",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,communityDeliveryProgress: [["not-an-operation-id", "a".repeat(64), 0, 1]],});(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ready, malformed])@@ -549,7 +550,7 @@ describe("WebSocketDurableObject", () => {ws.serializeAttachment({type: "user",userId: "user-42",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,communityDeliveryProgress: [[operationId, prepared.prepared.digest, 0, 3]],});(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])@@ -593,7 +594,7 @@ describe("WebSocketDurableObject", () => {ws.serializeAttachment({type: "user",userId: "user-42",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,name: "x".repeat(COMMUNITY_CONNECTION_STATE_JSON_MAX_BYTES),});(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])@@ -611,10 +612,10 @@ describe("WebSocketDurableObject", () => {first.serializeAttachment({type: "user",userId: "user-42",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,})const second = createMockWebSocket()- second.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ second.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([first, second])mockEncodeCommunityBrowserEventBatchForContract.mockReturnValueOnce({ok: false,@@ -680,7 +681,7 @@ describe("WebSocketDurableObject", () => {await expect((await durable.fetch(request.clone())).json()).resolves.toMatchObject({ matched: 0, enqueued: 0 })expect(mockCreateDb).not.toHaveBeenCalled()const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })sockets.mockReturnValue([ws])mockListReadableChannelsForUser.mockResolvedValueOnce([])await expect((await durable.fetch(request.clone())).json()).resolves.toMatchObject({ status: "cancelled", targetUserId: "user-42" })@@ -693,7 +694,7 @@ describe("WebSocketDurableObject", () => {it("returns zero matches when the last target closes during its access query", async () => {const { durable, ctx } = createDO()const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })const sockets = ctx.getWebSockets as ReturnType<typeof vi.fn>sockets.mockReturnValue([ws])let release!: (rows: Array<{ id: string }>) => void@@ -704,7 +705,7 @@ describe("WebSocketDurableObject", () => {release([{ id: "ch-1" }])await expect((await pending).json()).resolves.toMatchObject({ matched: 0, enqueued: 0 })expect(ws.send).not.toHaveBeenCalled()- expect(ws.deserializeAttachment()).toEqual({ type: "user", userId: "user-42", authenticated: true })+ expect(ws.deserializeAttachment()).toMatchObject({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: expect.any(Number) })})it("closes a socket and reports ambiguity when attachment persistence fails after send", async () => {@@ -713,7 +714,7 @@ describe("WebSocketDurableObject", () => {ws.serializeAttachment({type: "user",userId: "user-42",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,})ws.serializeAttachment.mockImplementationOnce(() => {throw new Error("attachment failed")@@ -766,7 +767,7 @@ describe("WebSocketDurableObject", () => {const acceptCall = (ctx.acceptWebSocket as ReturnType<typeof vi.fn>).mock.calls[0]const serverWs = acceptCall[0]- expect(serverWs.deserializeAttachment()).toEqual({+ expect(serverWs.deserializeAttachment()).toMatchObject({type: "user",userId: "",targetUserId: "u1",@@ -784,7 +785,7 @@ describe("WebSocketDurableObject", () => {type: "user",userId: "user-42",targetUserId: "user-42",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,})await durable.webSocketMessage(@@ -831,7 +832,7 @@ describe("WebSocketDurableObject", () => {type: "user",userId: "user-42",targetUserId: "user-42",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,})await durable.webSocketMessage(ws as any, JSON.stringify(frame))@@ -848,7 +849,7 @@ describe("WebSocketDurableObject", () => {type: "user",userId: "user-42",targetUserId: "user-42",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,})await durable.webSocketMessage(ws as any, JSON.stringify([]))@@ -893,11 +894,11 @@ describe("WebSocketDurableObject", () => {expect(mockGetValidSessionWithIdentity).toHaveBeenCalledWith({}, "valid-token")expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))- expect(ws.deserializeAttachment()).toEqual({+ expect(ws.deserializeAttachment()).toMatchObject({type: "user",userId: "user-42",targetUserId: "user-42",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: expect.any(Number),communityContract: 1,name: "Ana",discriminator: "0012",@@ -914,7 +915,7 @@ describe("WebSocketDurableObject", () => {type: "user",userId: "user-42",targetUserId: "user-42",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,communityDeliveryProgress: progress,})@@ -923,7 +924,7 @@ describe("WebSocketDurableObject", () => {expect(ws.deserializeAttachment()).toMatchObject({type: "user",userId: "user-42",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: expect.any(Number),communityDeliveryProgress: progress,})})@@ -932,7 +933,7 @@ describe("WebSocketDurableObject", () => {const { durable } = createDO()mockGetValidSessionWithIdentity.mockResolvedValue({ userId: "user-42", name: "Ana", discriminator: "0012" })const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "user-42", targetUserId: "user-42", authenticated: true, communityContract: version })+ ws.serializeAttachment({ type: "user", userId: "user-42", targetUserId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: version })await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract: version === 1 ? 2 : 1 }))expect(ws.deserializeAttachment()).toMatchObject({ authenticated: true, communityContract: version })expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok", ...(version !== 1 ? { communityContract: version } : {}) }))@@ -1023,7 +1024,7 @@ describe("WebSocketDurableObject", () => {mockGetCoMemberUserIds.mockResolvedValue(["friend-1"])mockStubFetch.mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ online: false })))const existing = createMockWebSocket()- existing.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ existing.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([existing])const ws = createMockWebSocket()ws.serializeAttachment({@@ -1092,7 +1093,7 @@ describe("WebSocketDurableObject", () => {discriminator: "0066",})const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])await durable.webSocketMessage(@@ -1100,7 +1101,7 @@ describe("WebSocketDurableObject", () => {JSON.stringify({ type: "auth", token: "attacker-session-token" }),)- expect(ws.deserializeAttachment()).toEqual({+ expect(ws.deserializeAttachment()).toMatchObject({type: "user",userId: "attacker",authenticated: false,@@ -1130,7 +1131,7 @@ describe("WebSocketDurableObject", () => {type: "user",userId: "victim",targetUserId: "victim",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,});(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])@@ -1139,11 +1140,11 @@ describe("WebSocketDurableObject", () => {JSON.stringify({ type: "auth", token: "attacker-session-token" }),)- expect(ws.deserializeAttachment()).toEqual({+ expect(ws.deserializeAttachment()).toMatchObject({type: "user",userId: "victim",targetUserId: "victim",- authenticated: true,+ authenticated: true, sessionId: "test-session", sessionValidUntil: expect.any(Number),})await durable.webSocketClose(ws as any, 1000, "test complete", true)@@ -1219,7 +1220,7 @@ describe("WebSocketDurableObject", () => {expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")expect(ws.send).not.toHaveBeenCalled()- expect(ws.deserializeAttachment()).toEqual({ type: "user", userId: "", authenticated: false })+ expect(ws.deserializeAttachment()).toMatchObject({ type: "user", userId: "", authenticated: false })})it("closes on invalid JSON", async () => {@@ -1376,7 +1377,7 @@ describe("WebSocketDurableObject", () => {; (env.WS_DO as any).get = vi.fn().mockReturnValue(aliveStub)const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))@@ -1394,7 +1395,7 @@ describe("WebSocketDurableObject", () => {; (env.WS_DO as any).get = vi.fn().mockReturnValue(deadStub)const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))@@ -1406,7 +1407,7 @@ describe("WebSocketDurableObject", () => {mockGetLatestTokenForUser.mockResolvedValue(null)const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))@@ -1420,7 +1421,7 @@ describe("WebSocketDurableObject", () => {fetch: vi.fn().mockRejectedValue(new Error("daemon DO unavailable")),})const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))@@ -1447,9 +1448,9 @@ describe("WebSocketDurableObject", () => {it("keeps user presence online while another authenticated tab remains", async () => {const { durable, ctx } = createDO()const closing = createMockWebSocket()- closing.serializeAttachment({ type: "user", userId: "user-1", authenticated: true })+ closing.serializeAttachment({ type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })const other = createMockWebSocket()- other.serializeAttachment({ type: "user", userId: "user-1", authenticated: true })+ other.serializeAttachment({ type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([closing, other])await durable.webSocketClose(closing as any, 1000, "test complete", true)@@ -1462,9 +1463,9 @@ describe("WebSocketDurableObject", () => {it("keeps user presence online when auto-reply already removed the closing tab", async () => {const { durable, ctx } = createDO()const closing = createMockWebSocket()- closing.serializeAttachment({ type: "user", userId: "user-1", authenticated: true })+ closing.serializeAttachment({ type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })const other = createMockWebSocket()- other.serializeAttachment({ type: "user", userId: "user-1", authenticated: true })+ other.serializeAttachment({ type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([other])await durable.webSocketClose(closing as any, 1000, "test complete", true)@@ -1479,7 +1480,7 @@ describe("WebSocketDurableObject", () => {mockGetCoMemberUserIds.mockResolvedValue(["friend-1"])mockStubFetch.mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ sent: 1 })))const closing = createMockWebSocket()- closing.serializeAttachment({ type: "user", userId: "user-1", authenticated: true })+ closing.serializeAttachment({ type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([closing])await durable.webSocketClose(closing as any, 1000, "test complete", true)@@ -1515,3 +1516,36 @@ describe("WebSocketDurableObject", () => {})})})++describe("persisted user session lease", () => {+ beforeEach(() => resetHarness())+ afterEach(() => cleanupHarness())+ it.each(["revoked", "db-failure", "historical"])("does not deliver private events to a %s session", async (mode) => {+ const { durable, ctx } = createDO()+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true,+ ...(mode === "historical" ? {} : { sessionId: "old-session", sessionValidUntil: 0 }),+ })+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])+ if (mode === "db-failure") mockGetValidSessionByIdForUser.mockRejectedValue(new Error("D1 unavailable"))+ else mockGetValidSessionByIdForUser.mockResolvedValue(null)+ await durable.fetch(new Request("http://internal/community-broadcast", {+ method: "POST", headers: { [INTERNAL_USER_TARGET_HEADER]: "user-42" },+ body: JSON.stringify({ type: "community:status.update", userId: "user-42", statusEmoji: null, statusText: "private" }),+ }))+ expect(ws.send).not.toHaveBeenCalled()+ expect(ws.close).toHaveBeenCalledWith(1008, "Session expired or revoked")+ expect(ws.deserializeAttachment()).toMatchObject({ authenticated: false })+ })+ it("refreshes a hibernated valid session and caps its lease at session expiry", async () => {+ const { durable } = createDO()+ const ws = createMockWebSocket()+ const expiresAt = new Date(Date.now() + 10_000).toISOString()+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "session", sessionValidUntil: 0 })+ mockGetValidSessionByIdForUser.mockResolvedValue({ expiresAt })+ await durable.webSocketMessage(ws as unknown as WebSocket, JSON.stringify({ type: "connection.ping", nonce: "ping" }))+ expect(mockGetValidSessionByIdForUser).toHaveBeenCalledWith({}, "session", "user-42")+ expect(ws.deserializeAttachment()).toMatchObject({ sessionValidUntil: Date.parse(expiresAt) })+ expect(ws.close).not.toHaveBeenCalled()+ })+})diff --git a/src/ws-do/src/ws-durable/user-auth.ts b/src/ws-do/src/ws-durable/user-auth.tsindex b0fc3cb5d..a8a4986b1 100644--- a/src/ws-do/src/ws-durable/user-auth.ts+++ b/src/ws-do/src/ws-durable/user-auth.ts@@ -46,11 +46,39 @@ import {import { canDeliverCommunityContent } from "../community-content-access"import { handleUserAgentInterrupt } from "./agent-interrupt"+const USER_SESSION_CHECK_INTERVAL_MS = 60_000++async function refreshUserSession(context: WsDurableContext, ws: WebSocket): Promise<void> {+ const state = ws.deserializeAttachment() as ConnectionState+ if (state?.type !== "user" || !state.authenticated || (state.sessionValidUntil ?? 0) > Date.now()) return+ try {+ const session = state.sessionId+ ? await queries.session.getValidSessionByIdForUser(createDb(context.env.DB), state.sessionId, state.userId)+ : null+ if (session) {+ const current = ws.deserializeAttachment() as ConnectionState+ if (current?.type === "user" && current.sessionId === state.sessionId && current.authenticated) {+ ws.serializeAttachment({ ...current, sessionValidUntil: Math.min(Date.now() + USER_SESSION_CHECK_INTERVAL_MS, Date.parse(session.expiresAt)) })+ }+ return+ }+ } catch {+ context.log.warn("user_session_refresh_failed", { userId: state.userId })+ }+ const current = ws.deserializeAttachment() as ConnectionState+ if (current?.type !== "user" || current.sessionId !== state.sessionId) return+ ws.serializeAttachment({ ...current, authenticated: false })+ ws.close(1008, "Session expired or revoked")+}+export async function handleUserFetch(context: WsDurableContext,request: Request,url: URL,): Promise<Response | null> {+ if (["/community-broadcast-bundle", "/community-broadcast", "/broadcast", "/check-alive", "/check-user-online"].includes(url.pathname)) {+ for (const ws of context.ctx.getWebSockets()) await refreshUserSession(context, ws)+ }if (url.pathname === "/community-broadcast-bundle" && request.method === "POST") {const targetUserId = getInternalCommunityUserTarget(request)if (!isValidCommunityUserTarget(targetUserId)) {@@ -216,6 +244,8 @@ export async function handleWebSocketMessage(let parsed: unknowntry { parsed = JSON.parse(message) } catch { ws.close(1008, "Invalid JSON"); return }+ await refreshUserSession(context, ws)+const state = ws.deserializeAttachment() as ConnectionStateconst controlType = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)@@ -308,6 +338,8 @@ export async function handleWebSocketMessage(userId,targetUserId,authenticated: true,+ sessionId: identity.sessionId,+ sessionValidUntil: Math.min(Date.now() + USER_SESSION_CHECK_INTERVAL_MS, Date.parse(identity.expiresAt)),name,discriminator,communityContract,@@ -714,7 +746,7 @@ async function getDaemonIdForUser(context: WsDurableContext, userId: string): Prasync function validateToken(context: WsDurableContext,token: string,-): Promise<{ userId: string; name: string; discriminator: string } | null> {+): ReturnType<typeof queries.session.getValidSessionWithIdentity> {const db = createDb(context.env.DB)return withD1Retry(() => queries.session.getValidSessionWithIdentity(db, token),