ubiquitous-invention/apps/web/server/routers/workspaces.ts

388 lines
12 KiB
TypeScript
Raw Normal View History

import { TRPCError } from "@trpc/server";
import { z } from "zod";
multi-tenancy: promote workspaces to top-level table Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`, which made it impossible to put a real RLS-friendly tenant boundary on the schema or to give each workspace a stable URL slug. This commit: - Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook). - Migrates the 8 anchor tables (objects, workspace_members, object_type_defs, property_definitions, templates, forms, markdown_backlog_items, cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`, with a hand-augmented data-copy migration that preserves IDs and slug-collision- proofs on backfill. - Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All tenant-scoped routers (objects, types, properties, templates, forms, search, ai, relations, favorites) now flow through it. - Updates the web app to pass `workspace` slugs from the URL (or store) instead of the old `workspaceId`, including a workspace-sync layer that rewrites /<UUID>/... links to /<slug>/... - Updates the MCP tools (list_objects, create_object, search_objects) and the workspace://{handle}/tree resource to accept either a slug or UUID so existing agents keep working. - Adds a Create Workspace dialog and a Workspace Settings page (rename + slug rename with redirect, owner-only archive). Verified locally against a fresh Postgres: migration applies cleanly, slug uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution works in both directions, and ON DELETE CASCADE cleans up child rows in the correct workspace only. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-07 00:02:55 -04:00
import { and, desc, eq, isNull, ne } from "drizzle-orm";
import {
workspaces,
workspaceMembers,
users,
} from "@tasks/database/schema";
import { router, protectedProcedure, workspaceProcedure } from "@/server/trpc";
import { findWorkspaceByHandle } from "@/server/lib/resolve-workspace";
const slugSchema = z
.string()
.min(2)
.max(60)
.regex(/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/, "Slug must be lowercase, alphanumeric, hyphen-separated");
function makeSlug(name: string): string {
return (
name
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60) || "workspace"
);
}
export const workspacesRouter = router({
multi-tenancy: promote workspaces to top-level table Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`, which made it impossible to put a real RLS-friendly tenant boundary on the schema or to give each workspace a stable URL slug. This commit: - Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook). - Migrates the 8 anchor tables (objects, workspace_members, object_type_defs, property_definitions, templates, forms, markdown_backlog_items, cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`, with a hand-augmented data-copy migration that preserves IDs and slug-collision- proofs on backfill. - Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All tenant-scoped routers (objects, types, properties, templates, forms, search, ai, relations, favorites) now flow through it. - Updates the web app to pass `workspace` slugs from the URL (or store) instead of the old `workspaceId`, including a workspace-sync layer that rewrites /<UUID>/... links to /<slug>/... - Updates the MCP tools (list_objects, create_object, search_objects) and the workspace://{handle}/tree resource to accept either a slug or UUID so existing agents keep working. - Adds a Create Workspace dialog and a Workspace Settings page (rename + slug rename with redirect, owner-only archive). Verified locally against a fresh Postgres: migration applies cleanly, slug uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution works in both directions, and ON DELETE CASCADE cleans up child rows in the correct workspace only. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-07 00:02:55 -04:00
/**
* Resolve a UUID-or-slug handle to a workspace the caller can see. Used by
* the app shell to redirect / hydrate the workspace switcher.
*/
resolve: protectedProcedure
.input(z.object({ handle: z.string().min(1) }))
.query(async ({ ctx, input }) => {
multi-tenancy: promote workspaces to top-level table Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`, which made it impossible to put a real RLS-friendly tenant boundary on the schema or to give each workspace a stable URL slug. This commit: - Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook). - Migrates the 8 anchor tables (objects, workspace_members, object_type_defs, property_definitions, templates, forms, markdown_backlog_items, cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`, with a hand-augmented data-copy migration that preserves IDs and slug-collision- proofs on backfill. - Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All tenant-scoped routers (objects, types, properties, templates, forms, search, ai, relations, favorites) now flow through it. - Updates the web app to pass `workspace` slugs from the URL (or store) instead of the old `workspaceId`, including a workspace-sync layer that rewrites /<UUID>/... links to /<slug>/... - Updates the MCP tools (list_objects, create_object, search_objects) and the workspace://{handle}/tree resource to accept either a slug or UUID so existing agents keep working. - Adds a Create Workspace dialog and a Workspace Settings page (rename + slug rename with redirect, owner-only archive). Verified locally against a fresh Postgres: migration applies cleanly, slug uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution works in both directions, and ON DELETE CASCADE cleans up child rows in the correct workspace only. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-07 00:02:55 -04:00
const ws = await findWorkspaceByHandle(input.handle, ctx.db);
if (!ws) {
throw new TRPCError({ code: "NOT_FOUND", message: "Workspace not found" });
}
const userId = ctx.session.user.id;
const [membership] = await ctx.db
.select({ role: workspaceMembers.role })
.from(workspaceMembers)
.where(
and(
eq(workspaceMembers.workspaceId, ws.id),
eq(workspaceMembers.userId, userId),
),
)
.limit(1);
multi-tenancy: promote workspaces to top-level table Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`, which made it impossible to put a real RLS-friendly tenant boundary on the schema or to give each workspace a stable URL slug. This commit: - Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook). - Migrates the 8 anchor tables (objects, workspace_members, object_type_defs, property_definitions, templates, forms, markdown_backlog_items, cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`, with a hand-augmented data-copy migration that preserves IDs and slug-collision- proofs on backfill. - Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All tenant-scoped routers (objects, types, properties, templates, forms, search, ai, relations, favorites) now flow through it. - Updates the web app to pass `workspace` slugs from the URL (or store) instead of the old `workspaceId`, including a workspace-sync layer that rewrites /<UUID>/... links to /<slug>/... - Updates the MCP tools (list_objects, create_object, search_objects) and the workspace://{handle}/tree resource to accept either a slug or UUID so existing agents keep working. - Adds a Create Workspace dialog and a Workspace Settings page (rename + slug rename with redirect, owner-only archive). Verified locally against a fresh Postgres: migration applies cleanly, slug uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution works in both directions, and ON DELETE CASCADE cleans up child rows in the correct workspace only. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-07 00:02:55 -04:00
const [owner] = await ctx.db
.select({ ownerUserId: workspaces.ownerUserId })
.from(workspaces)
.where(eq(workspaces.id, ws.id))
.limit(1);
if (!membership && owner?.ownerUserId !== userId) {
throw new TRPCError({ code: "FORBIDDEN" });
}
multi-tenancy: promote workspaces to top-level table Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`, which made it impossible to put a real RLS-friendly tenant boundary on the schema or to give each workspace a stable URL slug. This commit: - Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook). - Migrates the 8 anchor tables (objects, workspace_members, object_type_defs, property_definitions, templates, forms, markdown_backlog_items, cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`, with a hand-augmented data-copy migration that preserves IDs and slug-collision- proofs on backfill. - Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All tenant-scoped routers (objects, types, properties, templates, forms, search, ai, relations, favorites) now flow through it. - Updates the web app to pass `workspace` slugs from the URL (or store) instead of the old `workspaceId`, including a workspace-sync layer that rewrites /<UUID>/... links to /<slug>/... - Updates the MCP tools (list_objects, create_object, search_objects) and the workspace://{handle}/tree resource to accept either a slug or UUID so existing agents keep working. - Adds a Create Workspace dialog and a Workspace Settings page (rename + slug rename with redirect, owner-only archive). Verified locally against a fresh Postgres: migration applies cleanly, slug uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution works in both directions, and ON DELETE CASCADE cleans up child rows in the correct workspace only. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-07 00:02:55 -04:00
return ws;
}),
multi-tenancy: promote workspaces to top-level table Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`, which made it impossible to put a real RLS-friendly tenant boundary on the schema or to give each workspace a stable URL slug. This commit: - Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook). - Migrates the 8 anchor tables (objects, workspace_members, object_type_defs, property_definitions, templates, forms, markdown_backlog_items, cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`, with a hand-augmented data-copy migration that preserves IDs and slug-collision- proofs on backfill. - Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All tenant-scoped routers (objects, types, properties, templates, forms, search, ai, relations, favorites) now flow through it. - Updates the web app to pass `workspace` slugs from the URL (or store) instead of the old `workspaceId`, including a workspace-sync layer that rewrites /<UUID>/... links to /<slug>/... - Updates the MCP tools (list_objects, create_object, search_objects) and the workspace://{handle}/tree resource to accept either a slug or UUID so existing agents keep working. - Adds a Create Workspace dialog and a Workspace Settings page (rename + slug rename with redirect, owner-only archive). Verified locally against a fresh Postgres: migration applies cleanly, slug uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution works in both directions, and ON DELETE CASCADE cleans up child rows in the correct workspace only. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-07 00:02:55 -04:00
/**
* Create a new workspace owned by the caller. Auto-mints a slug from `name`
* unless one is provided. Caller is added as the owner+initial member.
*/
create: protectedProcedure
.input(
z.object({
name: z.string().min(1).max(200),
slug: slugSchema.optional(),
}),
)
.mutation(async ({ ctx, input }) => {
const userId = ctx.session.user.id;
let slug = input.slug ?? makeSlug(input.name);
const [collision] = await ctx.db
.select({ id: workspaces.id })
.from(workspaces)
.where(eq(workspaces.slug, slug))
.limit(1);
if (collision) {
if (input.slug) {
throw new TRPCError({ code: "CONFLICT", message: "Slug already in use" });
}
slug = `${slug}-${Math.random().toString(36).slice(2, 8)}`;
}
const [ws] = await ctx.db
.insert(workspaces)
.values({
name: input.name,
slug,
ownerUserId: userId,
})
.returning();
await ctx.db.insert(workspaceMembers).values({
workspaceId: ws.id,
userId,
role: "owner",
});
return ws;
}),
/** All workspaces the caller owns or is a member of, owned-first then alpha. */
listForUser: protectedProcedure.query(async ({ ctx }) => {
const userId = ctx.session.user.id;
multi-tenancy: promote workspaces to top-level table Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`, which made it impossible to put a real RLS-friendly tenant boundary on the schema or to give each workspace a stable URL slug. This commit: - Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook). - Migrates the 8 anchor tables (objects, workspace_members, object_type_defs, property_definitions, templates, forms, markdown_backlog_items, cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`, with a hand-augmented data-copy migration that preserves IDs and slug-collision- proofs on backfill. - Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All tenant-scoped routers (objects, types, properties, templates, forms, search, ai, relations, favorites) now flow through it. - Updates the web app to pass `workspace` slugs from the URL (or store) instead of the old `workspaceId`, including a workspace-sync layer that rewrites /<UUID>/... links to /<slug>/... - Updates the MCP tools (list_objects, create_object, search_objects) and the workspace://{handle}/tree resource to accept either a slug or UUID so existing agents keep working. - Adds a Create Workspace dialog and a Workspace Settings page (rename + slug rename with redirect, owner-only archive). Verified locally against a fresh Postgres: migration applies cleanly, slug uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution works in both directions, and ON DELETE CASCADE cleans up child rows in the correct workspace only. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-07 00:02:55 -04:00
const owned = await ctx.db
.select({
id: workspaces.id,
slug: workspaces.slug,
name: workspaces.name,
role: workspaceMembers.role,
archivedAt: workspaces.archivedAt,
})
.from(workspaces)
.leftJoin(
workspaceMembers,
and(
eq(workspaceMembers.workspaceId, workspaces.id),
eq(workspaceMembers.userId, userId),
),
)
.where(
and(eq(workspaces.ownerUserId, userId), isNull(workspaces.archivedAt)),
)
.orderBy(workspaces.name);
const memberOnly = await ctx.db
.select({
id: workspaces.id,
slug: workspaces.slug,
name: workspaces.name,
role: workspaceMembers.role,
archivedAt: workspaces.archivedAt,
})
.from(workspaceMembers)
.innerJoin(workspaces, eq(workspaceMembers.workspaceId, workspaces.id))
.where(
and(
eq(workspaceMembers.userId, userId),
ne(workspaces.ownerUserId, userId),
isNull(workspaces.archivedAt),
),
)
.orderBy(workspaces.name);
return [...owned, ...memberOnly].map((row) => ({
id: row.id,
slug: row.slug,
name: row.name,
role: row.role ?? "owner",
archivedAt: row.archivedAt,
}));
}),
/** Members of a workspace the caller can see. */
listMembers: workspaceProcedure.query(async ({ ctx }) => {
return ctx.db
.select({
multi-tenancy: promote workspaces to top-level table Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`, which made it impossible to put a real RLS-friendly tenant boundary on the schema or to give each workspace a stable URL slug. This commit: - Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook). - Migrates the 8 anchor tables (objects, workspace_members, object_type_defs, property_definitions, templates, forms, markdown_backlog_items, cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`, with a hand-augmented data-copy migration that preserves IDs and slug-collision- proofs on backfill. - Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All tenant-scoped routers (objects, types, properties, templates, forms, search, ai, relations, favorites) now flow through it. - Updates the web app to pass `workspace` slugs from the URL (or store) instead of the old `workspaceId`, including a workspace-sync layer that rewrites /<UUID>/... links to /<slug>/... - Updates the MCP tools (list_objects, create_object, search_objects) and the workspace://{handle}/tree resource to accept either a slug or UUID so existing agents keep working. - Adds a Create Workspace dialog and a Workspace Settings page (rename + slug rename with redirect, owner-only archive). Verified locally against a fresh Postgres: migration applies cleanly, slug uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution works in both directions, and ON DELETE CASCADE cleans up child rows in the correct workspace only. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-07 00:02:55 -04:00
id: users.id,
name: users.name,
email: users.email,
avatarUrl: users.avatarUrl,
role: workspaceMembers.role,
})
.from(workspaceMembers)
multi-tenancy: promote workspaces to top-level table Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`, which made it impossible to put a real RLS-friendly tenant boundary on the schema or to give each workspace a stable URL slug. This commit: - Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook). - Migrates the 8 anchor tables (objects, workspace_members, object_type_defs, property_definitions, templates, forms, markdown_backlog_items, cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`, with a hand-augmented data-copy migration that preserves IDs and slug-collision- proofs on backfill. - Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All tenant-scoped routers (objects, types, properties, templates, forms, search, ai, relations, favorites) now flow through it. - Updates the web app to pass `workspace` slugs from the URL (or store) instead of the old `workspaceId`, including a workspace-sync layer that rewrites /<UUID>/... links to /<slug>/... - Updates the MCP tools (list_objects, create_object, search_objects) and the workspace://{handle}/tree resource to accept either a slug or UUID so existing agents keep working. - Adds a Create Workspace dialog and a Workspace Settings page (rename + slug rename with redirect, owner-only archive). Verified locally against a fresh Postgres: migration applies cleanly, slug uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution works in both directions, and ON DELETE CASCADE cleans up child rows in the correct workspace only. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-07 00:02:55 -04:00
.innerJoin(users, eq(workspaceMembers.userId, users.id))
.where(eq(workspaceMembers.workspaceId, ctx.workspace.id));
}),
multi-tenancy: promote workspaces to top-level table Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`, which made it impossible to put a real RLS-friendly tenant boundary on the schema or to give each workspace a stable URL slug. This commit: - Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook). - Migrates the 8 anchor tables (objects, workspace_members, object_type_defs, property_definitions, templates, forms, markdown_backlog_items, cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`, with a hand-augmented data-copy migration that preserves IDs and slug-collision- proofs on backfill. - Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All tenant-scoped routers (objects, types, properties, templates, forms, search, ai, relations, favorites) now flow through it. - Updates the web app to pass `workspace` slugs from the URL (or store) instead of the old `workspaceId`, including a workspace-sync layer that rewrites /<UUID>/... links to /<slug>/... - Updates the MCP tools (list_objects, create_object, search_objects) and the workspace://{handle}/tree resource to accept either a slug or UUID so existing agents keep working. - Adds a Create Workspace dialog and a Workspace Settings page (rename + slug rename with redirect, owner-only archive). Verified locally against a fresh Postgres: migration applies cleanly, slug uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution works in both directions, and ON DELETE CASCADE cleans up child rows in the correct workspace only. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-07 00:02:55 -04:00
/**
* Update workspace metadata (name and/or slug). Slug renames are validated
* for uniqueness; the caller must be the workspace owner.
*/
update: workspaceProcedure
.input(
z.object({
name: z.string().min(1).max(200).optional(),
slug: slugSchema.optional(),
}),
)
.mutation(async ({ ctx, input }) => {
if (ctx.workspace.role !== "owner") {
throw new TRPCError({ code: "FORBIDDEN", message: "Only the owner can rename the workspace" });
}
if (input.slug && input.slug !== ctx.workspace.slug) {
const [collision] = await ctx.db
.select({ id: workspaces.id })
.from(workspaces)
.where(eq(workspaces.slug, input.slug))
.limit(1);
if (collision) {
throw new TRPCError({ code: "CONFLICT", message: "Slug already in use" });
}
}
const [updated] = await ctx.db
.update(workspaces)
.set({
...(input.name ? { name: input.name } : {}),
...(input.slug ? { slug: input.slug } : {}),
updatedAt: new Date(),
})
multi-tenancy: promote workspaces to top-level table Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`, which made it impossible to put a real RLS-friendly tenant boundary on the schema or to give each workspace a stable URL slug. This commit: - Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook). - Migrates the 8 anchor tables (objects, workspace_members, object_type_defs, property_definitions, templates, forms, markdown_backlog_items, cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`, with a hand-augmented data-copy migration that preserves IDs and slug-collision- proofs on backfill. - Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All tenant-scoped routers (objects, types, properties, templates, forms, search, ai, relations, favorites) now flow through it. - Updates the web app to pass `workspace` slugs from the URL (or store) instead of the old `workspaceId`, including a workspace-sync layer that rewrites /<UUID>/... links to /<slug>/... - Updates the MCP tools (list_objects, create_object, search_objects) and the workspace://{handle}/tree resource to accept either a slug or UUID so existing agents keep working. - Adds a Create Workspace dialog and a Workspace Settings page (rename + slug rename with redirect, owner-only archive). Verified locally against a fresh Postgres: migration applies cleanly, slug uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution works in both directions, and ON DELETE CASCADE cleans up child rows in the correct workspace only. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-07 00:02:55 -04:00
.where(eq(workspaces.id, ctx.workspace.id))
.returning();
return updated;
}),
multi-tenancy: promote workspaces to top-level table Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`, which made it impossible to put a real RLS-friendly tenant boundary on the schema or to give each workspace a stable URL slug. This commit: - Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook). - Migrates the 8 anchor tables (objects, workspace_members, object_type_defs, property_definitions, templates, forms, markdown_backlog_items, cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`, with a hand-augmented data-copy migration that preserves IDs and slug-collision- proofs on backfill. - Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All tenant-scoped routers (objects, types, properties, templates, forms, search, ai, relations, favorites) now flow through it. - Updates the web app to pass `workspace` slugs from the URL (or store) instead of the old `workspaceId`, including a workspace-sync layer that rewrites /<UUID>/... links to /<slug>/... - Updates the MCP tools (list_objects, create_object, search_objects) and the workspace://{handle}/tree resource to accept either a slug or UUID so existing agents keep working. - Adds a Create Workspace dialog and a Workspace Settings page (rename + slug rename with redirect, owner-only archive). Verified locally against a fresh Postgres: migration applies cleanly, slug uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution works in both directions, and ON DELETE CASCADE cleans up child rows in the correct workspace only. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-07 00:02:55 -04:00
feat(invites): workspace_invites schema + tRPC router + role management (Task 2, part 1/2) Schema half of Task-workspace-invites-and-roles. Lands the table, the invites router (create/list/revoke/accept), and the two new workspaces procedures (updateMemberRole/removeMember). UI ships in part 2/2. This is a stable checkpoint for Task 3 (invite-recipient-autocomplete) to start building against — the procedure surface area is frozen and the new identity helper from Task 1 is in the accept path. Schema: * workspace_invites: id, workspace_id, email (lowercased), role (owner/admin/member), invited_by_user_id, token (base64url 32B), expires_at (DEFAULT now() + 14d), accepted_at, revoked_at, created_at. * Indexes: workspace_id, UNIQUE(token), and a PARTIAL UNIQUE on (workspace_id, email) WHERE accepted_at IS NULL AND revoked_at IS NULL. An open invite is unique per (workspace, email); closed invites (accepted or revoked) fall out of the constraint so re-invites work. * Drizzle relations wired: workspaceInvites.workspace, workspaceInvites.invitedBy, workspaces.invites. * Migration 0006_broad_lethal_legion applied to dev DB. invites router: * create({email, role}) on workspaceProcedure (owner/admin only). Generates a base64url token from 32 random bytes via node:crypto. Idempotent on (workspace, email) — if an open invite already exists, returns it instead of inserting (the partial unique would block it anyway). Refuses self-invite. Refuses if the email is already a member. * list() returns pending (non-accepted, non-revoked) invites with inviter name/email joined for UI display. * revoke({inviteId}) authorizes against the invite's workspace, not the caller's input (the inviteId carries its own tenant scope). * accept({token}) is protectedProcedure (no workspace handle). Calls userOwnsEmail() from Task 1 — if the caller doesn't own the invited email under any of their verified identities, throws FORBIDDEN with a structured cause ({reason: "email_not_owned", invitedEmail}) so the redeem page can render the "link this email" explainer. Handles expiry, revoked, already-accepted states with clear messages. Idempotent on existing membership — if you've already been added by another flow, accept just closes the invite without re-inserting. workspaces additions: * updateMemberRole: admin/owner only. Three guards: 1. Can't change your own role (avoids accidental lockout). 2. Can't demote the only owner-role member (would leave the membership-level ownership empty even though workspaces.owner_user_id still points there — see ADR-pragmatic decision documented in the Task-multi-email-identity convoy discussion). 3. Only owners can promote to owner; admins move people between admin/member but cannot create a new owner. * removeMember: admin/owner OR self (the leave-workspace affordance). Same last-owner guard. Admins can't remove owners (only owners can, via demote-then-remove). Wired both new routers into root.ts as `invites` and `identity` (identity was landed in Task 1; this commit just keeps the registration visible alongside invites). All three CI gates green: 0 lint errors, 14 unchanged warnings, 6/6 type-check, 14/14 tests (no new tests yet — apps/web vitest harness is filed as Task-bootstrap-vitest-for-apps-web P2). Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 11:27:44 -04:00
/**
* Change a member's role. Admin/owner only. Cannot demote the last owner
* (the workspace would lose the ability to manage members).
*/
updateMemberRole: workspaceProcedure
.input(
z.object({
userId: z.string().uuid(),
role: z.enum(["owner", "admin", "member"]),
}),
)
.mutation(async ({ ctx, input }) => {
if (ctx.workspace.role !== "owner" && ctx.workspace.role !== "admin") {
throw new TRPCError({
code: "FORBIDDEN",
message: "Only owners and admins can change member roles.",
});
}
if (input.userId === ctx.session.user.id && input.role !== ctx.workspace.role) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "You can't change your own role. Ask another owner or admin.",
});
}
const [target] = await ctx.db
.select({ role: workspaceMembers.role })
.from(workspaceMembers)
.where(
and(
eq(workspaceMembers.workspaceId, ctx.workspace.id),
eq(workspaceMembers.userId, input.userId),
),
)
.limit(1);
if (!target) {
throw new TRPCError({ code: "NOT_FOUND", message: "Member not found." });
}
// Last-owner guard: demoting the only owner-role member to admin/member
// would leave the workspace ownerless at the membership layer (even
// though `workspaces.owner_user_id` still points at them — see the
// ADR-pragmatic decision in Task-multi-email-identity convoy discussion).
if (target.role === "owner" && input.role !== "owner") {
const ownerCount = await ctx.db
.select({ id: workspaceMembers.id })
.from(workspaceMembers)
.where(
and(
eq(workspaceMembers.workspaceId, ctx.workspace.id),
eq(workspaceMembers.role, "owner"),
),
);
if (ownerCount.length <= 1) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Can't demote the only owner. Promote someone else first.",
});
}
}
// Only owners can promote anyone to owner; admins can move people
// between admin/member but cannot create another owner.
if (input.role === "owner" && ctx.workspace.role !== "owner") {
throw new TRPCError({
code: "FORBIDDEN",
message: "Only an owner can promote someone to owner.",
});
}
await ctx.db
.update(workspaceMembers)
.set({ role: input.role })
.where(
and(
eq(workspaceMembers.workspaceId, ctx.workspace.id),
eq(workspaceMembers.userId, input.userId),
),
);
return { ok: true as const };
}),
/**
* Remove a member from the workspace. Admin/owner only. Cannot remove the
* last owner (same rationale as the demote guard above). Members can
* remove themselves that's the "leave workspace" affordance.
*/
removeMember: workspaceProcedure
.input(z.object({ userId: z.string().uuid() }))
.mutation(async ({ ctx, input }) => {
const isSelf = input.userId === ctx.session.user.id;
const callerCanManage =
ctx.workspace.role === "owner" || ctx.workspace.role === "admin";
if (!isSelf && !callerCanManage) {
throw new TRPCError({
code: "FORBIDDEN",
message: "Only owners and admins can remove other members.",
});
}
const [target] = await ctx.db
.select({ role: workspaceMembers.role })
.from(workspaceMembers)
.where(
and(
eq(workspaceMembers.workspaceId, ctx.workspace.id),
eq(workspaceMembers.userId, input.userId),
),
)
.limit(1);
if (!target) {
throw new TRPCError({ code: "NOT_FOUND", message: "Member not found." });
}
if (target.role === "owner") {
const ownerCount = await ctx.db
.select({ id: workspaceMembers.id })
.from(workspaceMembers)
.where(
and(
eq(workspaceMembers.workspaceId, ctx.workspace.id),
eq(workspaceMembers.role, "owner"),
),
);
if (ownerCount.length <= 1) {
throw new TRPCError({
code: "BAD_REQUEST",
message:
"Can't remove the only owner. Promote someone else to owner first.",
});
}
}
// Admins cannot remove owners (only owners can de-owner an owner via
// updateMemberRole -> removeMember, in that order).
if (target.role === "owner" && ctx.workspace.role !== "owner" && !isSelf) {
throw new TRPCError({
code: "FORBIDDEN",
message: "Only an owner can remove another owner.",
});
}
await ctx.db
.delete(workspaceMembers)
.where(
and(
eq(workspaceMembers.workspaceId, ctx.workspace.id),
eq(workspaceMembers.userId, input.userId),
),
);
return { ok: true as const };
}),
multi-tenancy: promote workspaces to top-level table Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`, which made it impossible to put a real RLS-friendly tenant boundary on the schema or to give each workspace a stable URL slug. This commit: - Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook). - Migrates the 8 anchor tables (objects, workspace_members, object_type_defs, property_definitions, templates, forms, markdown_backlog_items, cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`, with a hand-augmented data-copy migration that preserves IDs and slug-collision- proofs on backfill. - Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All tenant-scoped routers (objects, types, properties, templates, forms, search, ai, relations, favorites) now flow through it. - Updates the web app to pass `workspace` slugs from the URL (or store) instead of the old `workspaceId`, including a workspace-sync layer that rewrites /<UUID>/... links to /<slug>/... - Updates the MCP tools (list_objects, create_object, search_objects) and the workspace://{handle}/tree resource to accept either a slug or UUID so existing agents keep working. - Adds a Create Workspace dialog and a Workspace Settings page (rename + slug rename with redirect, owner-only archive). Verified locally against a fresh Postgres: migration applies cleanly, slug uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution works in both directions, and ON DELETE CASCADE cleans up child rows in the correct workspace only. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-07 00:02:55 -04:00
/** Owner-only soft archive. */
archive: workspaceProcedure.mutation(async ({ ctx }) => {
if (ctx.workspace.role !== "owner") {
throw new TRPCError({ code: "FORBIDDEN" });
}
const [updated] = await ctx.db
.update(workspaces)
.set({ archivedAt: new Date() })
.where(eq(workspaces.id, ctx.workspace.id))
.returning();
return updated;
}),
});