⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(admin): preserve archived workspace state across realtime revocation
Tindf26925b6b21
diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.tsindex 612482e9c..5a74c94b9 100644--- a/apps/api/src/ws/index.ts+++ b/apps/api/src/ws/index.ts@@ -1,7 +1,8 @@+import { workspaceIsActive } from "../workspace/archive/active-workspace-sql";import { hasWorkspaceAccess, syncWorkspaceAccess } from "./workspace-access";import { createRevocationDelivery } from "./revocation-delivery";import { randomUUID } from "node:crypto";-import { and, eq, inArray } from "drizzle-orm";+import { and, eq, inArray, sql } from "drizzle-orm";import type { WSContext } from "hono/ws";import db from "../database";import {@@ -9,7 +10,6 @@ import {projectTable,sessionTable,userTable,- workspaceTable,workspaceUserTable,} from "../database/schema";import { subscribeToEvent } from "../events";@@ -185,7 +185,11 @@ function deliverToLocalUserConnections(message.type === "WORKSPACE_ACCESS_REVOKED" &&typeof message.workspaceId === "string") {- revokeLocalWorkspaceConnections(userId, message.workspaceId);+ revokeLocalWorkspaceConnections(+ userId,+ message.workspaceId,+ message.reason === "archived" ? "Workspace archived" : undefined,+ );}if (message.type === "PROJECT_ACCESS_CHANGED" &&@@ -417,13 +421,17 @@ export async function closeProjectConnections(projectId: string) {}}-function revokeLocalWorkspaceConnections(userId: string, workspaceId: string) {+function revokeLocalWorkspaceConnections(+ userId: string,+ workspaceId: string,+ reason = "Workspace access revoked",+) {for (const [projectId, connections] of projectConnections) {for (const conn of [...connections]) {if (conn.userId !== userId || conn.workspaceId !== workspaceId) continue;removeConnection(projectId, conn);try {- conn.ws.close(1008, "Workspace access revoked");+ conn.ws.close(1008, reason);} catch {/* Already closed. */}@@ -656,18 +664,14 @@ function currentProjectWorkspace(projectId: string) {pending = db.select({workspaceId: projectTable.workspaceId,- archivedAt: workspaceTable.archivedAt,+ archived: sql<boolean>`not ${workspaceIsActive(projectTable.workspaceId)}`,}).from(projectTable)- .innerJoin(- workspaceTable,- eq(workspaceTable.id, projectTable.workspaceId),- ).where(eq(projectTable.id, projectId)).limit(1).then(([project]) => ({workspaceId: project?.workspaceId ?? null,- archived: !!project?.archivedAt,+ archived: !!project?.archived,})).finally(() => workspaceLookups.delete(projectId));workspaceLookups.set(projectId, pending);@@ -679,6 +683,7 @@ const authorizationLookups = new Map<string,Promise<{workspaceId: string | null;+ archived: boolean;members: Set<string>;restricted: Set<string>;readers: Set<string>;@@ -763,7 +768,7 @@ function currentBroadcastAccess(return null;}}- return { workspaceId, members, restricted, readers, apiKeys };+ return { workspaceId, archived, members, restricted, readers, apiKeys };})().finally(() => authorizationLookups.delete(key));authorizationLookups.set(key, pending);}@@ -789,7 +794,8 @@ async function deliverToLocalConnections(authorizationBatch,);if (!access) return;- const { workspaceId, members, restricted, readers, apiKeys } = access;+ const { workspaceId, archived, members, restricted, readers, apiKeys } =+ access;const payload = JSON.stringify(message);for (const conn of recipients) {// A move may have closed these connections while the lookup was in flight.@@ -797,14 +803,16 @@ async function deliverToLocalConnections(const revoked =conn.workspaceId !== workspaceId? "Project workspace changed"- : !members.has(conn.userId)- ? "Workspace access revoked"- : restricted.has(conn.userId)- ? "Project access revoked"- : !readers.has(conn.userId) ||- (conn.apiKeyId && apiKeys.get(conn.apiKeyId) !== conn.userId)- ? "Read permission revoked"- : null;+ : archived+ ? "Workspace archived"+ : !members.has(conn.userId)+ ? "Workspace access revoked"+ : restricted.has(conn.userId)+ ? "Project access revoked"+ : !readers.has(conn.userId) ||+ (conn.apiKeyId && apiKeys.get(conn.apiKeyId) !== conn.userId)+ ? "Read permission revoked"+ : null;if (revoked) {removeConnection(projectId, conn);try {diff --git a/apps/docs/openapi.json b/apps/docs/openapi.jsonindex 96cbe27ae..f1dd13f09 100644--- a/apps/docs/openapi.json+++ b/apps/docs/openapi.json@@ -5572,6 +5572,37 @@"email"]}+ },+ "archivedAt": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time",+ "description": "When an administrator archived the workspace, or null when it is active."+ },+ "archivedBy": {+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "email": {+ "type": "string"+ }+ },+ "required": [+ "id",+ "name",+ "email"+ ],+ "description": "The administrator who archived it. Null when active or when that account was deleted."}},"required": [@@ -5581,7 +5612,9 @@"createdAt","memberCount","projectCount",- "owners"+ "owners",+ "archivedAt",+ "archivedBy"]},"AdminWorkspaceMember": {@@ -5988,6 +6021,36 @@"to"]},+ "AdminWorkspaceArchiveState": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "archivedAt": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time"+ }+ },+ "required": [+ "id",+ "archivedAt"+ ]+ },+ "AdminDeletedWorkspace": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ },"AdminAuditLog": {"type": "object","properties": {@@ -22806,7 +22869,7 @@"Workspaces"],"summary": "List workspaces",- "description": "List the workspaces where one of the caller's roles grants workspace:read, with the caller's role, sorted by name. Instance admins get every workspace they are a member of, and only those.",+ "description": "List the workspaces where one of the caller's roles grants workspace:read, with the caller's role, sorted by name. Instance admins get every workspace they are a member of, and only those. Archived workspaces are left out.","responses": {"200": {"description": "The caller's workspaces",@@ -22854,7 +22917,7 @@"Workspaces"],"summary": "Get workspace",- "description": "Get a workspace where one of the caller's roles grants workspace:read, with the caller's role. Instance admins can get any workspace, with a null role when they are not a member.",+ "description": "Get a workspace where one of the caller's roles grants workspace:read, with the caller's role. Instance admins can get any workspace, with a null role when they are not a member. An archived workspace returns 403 with the code WORKSPACE_ARCHIVED to anyone who could otherwise read it.","parameters": [{"schema": {@@ -22887,7 +22950,7 @@}},"403": {- "description": "The API key lacks workspace:read",+ "description": "The API key lacks workspace:read, or the workspace is archived (code WORKSPACE_ARCHIVED)","content": {"application/json": {"schema": {@@ -25070,7 +25133,7 @@"Admin"],"summary": "List instance workspaces",- "description": "Page through every workspace on this instance with its owners, member count and project count, optionally filtered by a case-insensitive name or slug search. Requires an instance administrator session; API keys are rejected.",+ "description": "Page through every workspace on this instance with its owners, member count, project count and archive state, optionally filtered by a case-insensitive name or slug search. Requires an instance administrator session; API keys are rejected.","parameters": [{"schema": {@@ -25820,6 +25883,231 @@}}},+ "/admin/workspaces/{workspaceId}/archive": {+ "post": {+ "operationId": "archiveAdminWorkspace",+ "tags": [+ "Admin"+ ],+ "summary": "Archive a workspace",+ "description": "Disable a workspace without deleting anything. Its members, API keys, MCP clients, public links, calendar feeds, notifications, and integrations stop working, and requests for it return 403 with the code WORKSPACE_ARCHIVED. Open realtime connections are closed. Restore it to undo. Requires an instance administrator session; API keys are rejected.",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "workspaceId",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "The workspace's archive state",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AdminWorkspaceArchiveState"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "403": {+ "description": "The caller is not an instance administrator or is authenticated with an API key",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "404": {+ "description": "Workspace not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "409": {+ "description": "The workspace is already archived (code WORKSPACE_ALREADY_ARCHIVED)",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"+ }+ }+ }+ },+ "/admin/workspaces/{workspaceId}/restore": {+ "post": {+ "operationId": "restoreAdminWorkspace",+ "tags": [+ "Admin"+ ],+ "summary": "Restore an archived workspace",+ "description": "Make an archived workspace usable again, with all of its data, members, and integrations as they were. Requires an instance administrator session; API keys are rejected.",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "workspaceId",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "The workspace's archive state",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AdminWorkspaceArchiveState"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "403": {+ "description": "The caller is not an instance administrator or is authenticated with an API key",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "404": {+ "description": "Workspace not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "409": {+ "description": "The workspace is not archived (code WORKSPACE_NOT_ARCHIVED)",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"+ }+ }+ }+ },+ "/admin/workspaces/{workspaceId}": {+ "delete": {+ "operationId": "deleteAdminWorkspace",+ "tags": [+ "Admin"+ ],+ "summary": "Delete a workspace",+ "description": "Permanently delete a workspace and everything in it, archived or not, the same way its owner can: projects, tasks, members, invitations and uploaded files go, and open realtime connections are closed. The administrator does not need to be a member. Requires an instance administrator session; API keys are rejected.",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "workspaceId",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "The deleted workspace",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AdminDeletedWorkspace"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "403": {+ "description": "The caller is not an instance administrator or is authenticated with an API key",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "404": {+ "description": "Workspace not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "409": {+ "description": "The workspace still has an active subscription (code WORKSPACE_HAS_ACTIVE_SUBSCRIPTION)",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"+ }+ }+ }+ },"/admin/audit-log": {"get": {"operationId": "listAdminAuditLog",diff --git a/apps/web/src/hooks/use-project-websocket-access.test.tsx b/apps/web/src/hooks/use-project-websocket-access.test.tsxindex 5c2b0d8c6..720fb9e1b 100644--- a/apps/web/src/hooks/use-project-websocket-access.test.tsx+++ b/apps/web/src/hooks/use-project-websocket-access.test.tsx@@ -106,6 +106,26 @@ describe("project WebSocket access", () => {expect(vi.getTimerCount()).toBe(0);});+ it("keeps the archived workspace route and refreshes its state without reconnecting", () => {+ renderHook(() => useProjectWebSocket("project-a"));+ act(() => {+ TestSocket.instances[0].open();+ TestSocket.instances[0].onclose?.({+ code: 1008,+ reason: "Workspace archived",+ });+ vi.advanceTimersByTime(60_000);+ });+ expect(evictProjectCache).toHaveBeenCalledWith(client, "project-a");+ expect(client.invalidateQueries).toHaveBeenCalledWith({+ queryKey: ["workspace-status"],+ });+ expect(navigate).not.toHaveBeenCalled();+ expect(client.clear).not.toHaveBeenCalled();+ expect(TestSocket.instances).toHaveLength(1);+ expect(vi.getTimerCount()).toBe(0);+ });+it("evicts only the revoked project and returns to its workspace dashboard", async () => {cached.queries = [{ queryKey: ["projects", "workspace-a"] },diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.tsindex 5137ac70c..f7496c089 100644--- a/apps/web/src/hooks/use-project-websocket.ts+++ b/apps/web/src/hooks/use-project-websocket.ts@@ -577,6 +577,15 @@ export function useProjectWebSocket(projectId: string) {return;}+ if (event?.code === 1008 && event.reason === "Workspace archived") {+ disposed = true;+ evictProjectCache(queryClient, projectId);+ void queryClient.invalidateQueries({+ queryKey: ["workspace-status"],+ });+ return;+ }+if (event?.code === 1008 &&event.reason === "Workspace access revoked"diff --git a/apps/web/src/hooks/use-user-websocket.ts b/apps/web/src/hooks/use-user-websocket.tsindex 450e3ae5a..1e7ae9aa5 100644--- a/apps/web/src/hooks/use-user-websocket.ts+++ b/apps/web/src/hooks/use-user-websocket.ts@@ -164,6 +164,9 @@ export function useUserWebSocket() {void navigate({ to: "/dashboard" });}if (message.type === "WORKSPACE_RESTORED" && message.workspaceId) {+ void queryClient.invalidateQueries({+ queryKey: ["admin", "workspaces"],+ });void queryClient.invalidateQueries({queryKey: workspaceStatusQueryKey(message.workspaceId),});diff --git a/tests/api-integration/admin-workspace-lifecycle.test.ts b/tests/api-integration/admin-workspace-lifecycle.test.tsindex bd53ea063..699611fd1 100644--- a/tests/api-integration/admin-workspace-lifecycle.test.ts+++ b/tests/api-integration/admin-workspace-lifecycle.test.ts@@ -1,3 +1,4 @@+import * as billing from "../../apps/api/src/billing/controllers/find-billable-workspaces";import { randomUUID } from "node:crypto";import { eq } from "drizzle-orm";import type { WSContext } from "hono/ws";@@ -145,7 +146,7 @@ describe("archiving and restoring a workspace", () => {expect(boardSocket.close).toHaveBeenCalledWith(1008,- "Workspace access revoked",+ "Workspace archived",);expect(sentMessages(userSocket)).toContainEqual({type: "WORKSPACE_ACCESS_REVOKED",@@ -376,6 +377,70 @@ describe("deleting a workspace", () => {});});+ it("keeps subscribed workspaces and their audit history unchanged", async () => {+ const { workspace } = await workspaceFixture();+ mockAuthenticatedSession(await createInstanceAdmin());+ vi.spyOn(billing, "findBillableWorkspaces").mockResolvedValue([+ { workspaceId: workspace.id, name: workspace.name },+ ]);+ const response = await projectAccessApi()(+ `/admin/workspaces/${workspace.id}`,+ { method: "DELETE" },+ );+ expect(response.status).toBe(409);+ expect(await response.json()).toMatchObject({+ code: "WORKSPACE_HAS_ACTIVE_SUBSCRIPTION",+ });+ expect(await readWorkspace(workspace.id)).toBeDefined();+ expect(await readAuditLog()).toEqual([]);+ });++ it("preserves the native owner's key authentication and consumes its request quota", async () => {+ const { owner, workspace } = await workspaceFixture();+ const { key, id } = await auth.api.createApiKey({+ body: { userId: owner.id, name: "Owner deletion" },+ });+ const { app } = createApp();+ const response = await app.request("/api/auth/organization/delete", {+ method: "POST",+ headers: { "content-type": "application/json", "x-api-key": key },+ body: JSON.stringify({ organizationId: workspace.id }),+ });+ expect(response.status).toBe(200);+ expect(await readWorkspace(workspace.id)).toBeUndefined();+ const [stored] = await db+ .select()+ .from(schema.apikeyTable)+ .where(eq(schema.apikeyTable.id, id));+ expect(stored.requestCount).toBe(1);+ });++ it("retains native deletion permissions and the subscription guard", async () => {+ const { owner, workspace } = await workspaceFixture();+ const outsider = await createWorkspaceMember();+ const { app } = createApp();+ const call = (key: string) =>+ app.request("/api/auth/organization/delete", {+ method: "POST",+ headers: { "content-type": "application/json", "x-api-key": key },+ body: JSON.stringify({ organizationId: workspace.id }),+ });+ const denied = await auth.api.createApiKey({+ body: { userId: outsider.user.id },+ });+ expect((await call(denied.key)).status).toBe(403);+ const allowed = await auth.api.createApiKey({ body: { userId: owner.id } });+ vi.spyOn(billing, "findBillableWorkspaces").mockResolvedValue([+ { workspaceId: workspace.id, name: workspace.name },+ ]);+ const response = await call(allowed.key);+ expect(response.status).toBe(409);+ expect(await response.json()).toMatchObject({+ code: "WORKSPACE_HAS_ACTIVE_SUBSCRIPTION",+ });+ expect(await readWorkspace(workspace.id)).toBeDefined();+ });+it("deletes an archived workspace", async () => {const { workspace } = await workspaceFixture();mockAuthenticatedSession(await createInstanceAdmin());diff --git a/tests/api-integration/websocket-security.test.ts b/tests/api-integration/websocket-security.test.tsindex 146c75c55..1e1ef3fb1 100644--- a/tests/api-integration/websocket-security.test.ts+++ b/tests/api-integration/websocket-security.test.ts@@ -415,7 +415,9 @@ describe("archived workspaces", () => {projectId,taskId: "private-task",});- expect((await closed)[0]).toBe(1008);+ const [code, reason] = await closed;+ expect(code).toBe(1008);+ expect(reason.toString()).toBe("Workspace archived");expect(leaked).not.toHaveBeenCalled();});});diff --git a/tests/api-integration/workspace-archive-access.test.ts b/tests/api-integration/workspace-archive-access.test.tsindex 54746767b..3b867c34a 100644--- a/tests/api-integration/workspace-archive-access.test.ts+++ b/tests/api-integration/workspace-archive-access.test.ts@@ -1,3 +1,6 @@+import { replayDeferredIssueEdits } from "../../apps/api/src/plugins/github/services/deferred-issue-edits";+import { replayDeferredLabelFields } from "../../apps/api/src/plugins/sync/replay-deferred-label-fields";+import { createNextOccurrence } from "../../apps/api/src/task/recurrence/create-next-occurrence";import { randomBytes, randomUUID } from "node:crypto";import { eq } from "drizzle-orm";import { beforeEach, describe, expect, it, vi } from "vite-plus/test";@@ -47,6 +50,10 @@ async function seed() {.insert(schema.taskTable).values({ projectId: project.id, title: "Task", number: 1 }).returning();+ await db+ .update(schema.projectTable)+ .set({ lastTaskNumber: 1 })+ .where(eq(schema.projectTable.id, project.id));return { member, workspace, project, task };}@@ -201,6 +208,66 @@ describe("an archived workspace's public links", () => {});describe("an archived workspace's integrations", () => {+ it("pauses deferred jobs without discarding their pending work", async () => {+ const { workspace, project, task } = await seed();+ const [integration] = await db+ .insert(schema.integrationTable)+ .values({+ projectId: project.id,+ type: "gitea",+ isActive: true,+ config: "{}",+ })+ .returning();+ const metadata = JSON.stringify({+ deferredIssueEdit: { id: "pending" },+ syncLabelFieldsDeferred: "pending",+ });+ const [link] = await db+ .insert(schema.externalLinkTable)+ .values({+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "issue",+ externalId: "1",+ url: "https://gitea.example.com/acme/app/issues/1",+ metadata,+ })+ .returning();+ await setArchived(workspace.id, true);+ expect(await replayDeferredIssueEdits()).toMatchObject({ degraded: false });+ expect(await replayDeferredLabelFields()).toMatchObject({+ degraded: false,+ });+ const [stored] = await db+ .select()+ .from(schema.externalLinkTable)+ .where(eq(schema.externalLinkTable.id, link.id));+ expect(stored.metadata).toBe(metadata);+ });++ it("leaves recurring tasks intact while archived", async () => {+ const { workspace, project, task } = await seed();+ await db+ .update(schema.taskTable)+ .set({+ status: "done",+ recurrence: { frequency: "weekly", interval: 1, timeZone: "UTC" },+ dueDate: new Date("2026-10-26T12:00:00Z"),+ })+ .where(eq(schema.taskTable.id, task.id));+ await setArchived(workspace.id, true);+ expect(await createNextOccurrence(task.id, null)).toBeNull();+ const tasks = await db+ .select()+ .from(schema.taskTable)+ .where(eq(schema.taskTable.projectId, project.id));+ expect(tasks).toHaveLength(1);+ expect(tasks[0].recurrence).not.toBeNull();+ await setArchived(workspace.id, false);+ expect(await createNextOccurrence(task.id, null)).not.toBeNull();+ });+it("are skipped by webhook and sync lookups", async () => {const { workspace, project } = await seed();await db.insert(schema.integrationTable).values({@@ -366,6 +433,14 @@ describe("an archived workspace through Better Auth organization endpoints", ()expect(await codeOf(response)).toBe("WORKSPACE_ARCHIVED");}+ const alternate = await createWorkspaceMember();+ const mixed = await call(+ member.cookies,+ `/auth/organization/get-full-organization?organizationId=${alternate.workspace.id}&organizationSlug=${workspace.slug}`,+ );+ expect(mixed.status).toBe(403);+ expect(await codeOf(mixed)).toBe("WORKSPACE_ARCHIVED");+// Outsiders cannot tell an archived workspace from one they cannot read.const probe = await call(outsider.cookies,