Skip to main content
This page documents the actual workspace and permission model used by apps/web today. It focuses on the implementation that page components, route handlers, and the internal API helpers actually consume:
  • packages/utils/src/workspace-helper.ts
  • packages/ui/src/components/ui/custom/workspace-wrapper.tsx
  • apps/web/src/proxy.ts
  • packages/utils/src/permissions.tsx
  • apps/web/src/lib/api-middleware.ts

Workspace user merge phases

Every resumable workspace-user merge phase requires a signed-in actor with both delete_users and update_users in the selected workspace. The target profile must belong to that workspace, and source and target must differ. A completed merge remains resumable for an authorized caller. The web and Contacts shared merge route uses the request-scoped user client for these RPCs; privileged clients without an authenticated subject do not bypass the actor check. The same rule covers the single-call merge, phase 1/1a, the phased orchestrator and the batched phase 1 helpers: a missing actor or a permission result that is not TRUE (including NULL) returns the existing success: false denial. Phase 5 locks the source and target rows in id order before merging, so a concurrent or swapped merge cannot delete both profiles. Phase 4 locks both platform-link rows before transferring a link. The two dynamic-identifier helpers the batched phases call, merge_workspace_users_batch_update and merge_workspace_users_table_batch, are not client entry points: only service_role and the definer phase functions may execute them, and both raise 22023 for any (table, column) outside the fixed phase 1a–1d merge references. Both pin search_path to pg_catalog, pg_temp: the allowlist carries each reference’s owning schema (public or private) and the dynamic SQL uses schema-qualified identifiers, so no relation lookup depends on the caller or on the path. Regression coverage: apps/database/supabase/tests/merge-phase-workspace-guards.sql, apps/database/supabase/tests/merge-workspace-users-null-guards.sql, and apps/database/supabase/tests/merge-batch-helper-search-path.sql. Manual reversal is in the matching apps/database/rollbacks/20261029050400–20261029050430 rollback files. A rollback removes these guards and reopens an internal security finding for authenticated callers of the phase functions; it never re-grants PUBLIC or anon, and the two helpers stay service_role-only.

Mental Model

There are four layers, and most bugs come from mixing them together:
  1. Workspace identity personal, internal, and UUIDs all describe the same underlying workspaces.id shape, but only UUIDs are stored in the database.
  2. Membership workspace_members answers “is this signed-in user allowed inside this workspace at all?”
  3. Effective permissions workspace_role_members, workspace_role_permissions, workspace_default_permissions, and creator fallback answer “what may this member do?”
  4. Surface enforcement Pages, navigation, and API routes decide whether to hide, redirect, 403, or allow the action.

Workspace Vocabulary

Membership Is Not The Same Thing As A Workspace User Record

apps/web uses two different “user-ish” concepts:
  • workspace_members This is the access-control boundary. Most auth checks read this table.
  • workspace_users This is domain data used by product features such as user management, attendance, reports, and directory-style views.
Do not treat workspace_users as evidence that a signed-in platform user has workspace access. In the web app, access checks consistently use workspace_members.

Canonical Workspace Identifiers

The web app accepts three route forms:
  • a raw workspace UUID
  • personal
  • internal
The database only stores UUID workspace IDs. The slugs are convenience identifiers used at the edge and in page params.

Resolution Rules

  • personal resolves to the signed-in user’s personal workspace UUID.
  • internal resolves to ROOT_WORKSPACE_ID.
  • a personal workspace UUID in the URL is redirected back to /personal/....
  • the root workspace UUID in the URL is redirected back to /internal/....
This canonicalization happens before most page rendering so the browser settles on stable, human-friendly URLs.

How Proxy Routing Works

apps/web/src/proxy.ts is the entry point for workspace-aware URL normalization. The proxy is responsible for:
  • locale-aware path parsing
  • redirecting root visits to the user’s default workspace
  • rewriting raw root UUIDs to internal
  • rewriting personal workspace UUIDs to personal
  • preserving auth cookies while issuing those redirects
It also uses getUserDefaultWorkspace() from packages/utils/src/user-helper.ts to decide where an authenticated user lands when they hit /.

Default Workspace Behavior

The default workspace is stored in user_private_details.default_workspace_id. When the stored default workspace is missing or no longer accessible, the helper falls back to the user’s personal workspace. That fallback is used both for root-path redirect behavior and for other flows that need a stable “start workspace” concept.

Server-Page Workspace Resolution

For server-rendered pages under apps/web/src/app/[locale]/(dashboard)/[wsId]/..., the normal entry point is WorkspaceWrapper. WorkspaceWrapper delegates to getWorkspace(wsId), which:
  1. validates that the incoming identifier is a supported direct lookup form
  2. authenticates the current user
  3. resolves personal / internal into a concrete workspace ID
  4. queries workspaces joined through workspace_members!inner(user_id)
  5. returns the workspace plus:
    • joined
    • tier
    • normalized workspace.id
If that lookup fails, the wrapper calls notFound().

Important Consequence

Page components that use WorkspaceWrapper already know:
  • the user is authenticated
  • the user has a workspace_members row for the workspace
  • the child callback receives the canonical UUID as wsId
That does not mean the user has feature-level permissions. Fine-grained authorization still needs getPermissions(). It also does not mean the user is a full member. Guests can have workspace_members.type = 'GUEST', so non-guest-capable pages and APIs must explicitly require MEMBER.

Route-Handler Workspace Resolution

API routes cannot depend on WorkspaceWrapper, so they use normalizeWorkspaceId(). normalizeWorkspaceId():
  • accepts the route param
  • optionally accepts a request-scoped Supabase client
  • preserves mobile/Bearer-token auth by using createClient(request) when needed
  • returns the canonical workspace UUID
  • throws when personal is requested but no authenticated personal workspace exists
App-session and CLI routes that call normalizeWorkspaceId() with an admin Supabase client should first attach the verified actor with attachSupabaseAuthUser() from @tuturuuu/auth/app-session. Do not duplicate manual personal workspace fallback lookups inside each route. Use it whenever a route param may contain personal or internal but the query must operate on concrete workspace IDs.

Effective Permission Evaluation

The main evaluator is getPermissions({ wsId, request? }) in packages/utils/src/workspace-helper.ts. Its behavior is the key thing to understand.

Inputs

  • authenticated current user
  • workspace identifier from the page or route

Data sources

  • workspace_role_members
  • workspace_roles
  • workspace_role_permissions
  • workspace_default_permissions.member_type
  • workspaces.creator_id

Evaluation algorithm

  1. Authenticate the current user.
  2. Normalize the workspace ID.
  3. Verify whether the caller is a MEMBER or GUEST.
  4. For MEMBER, load role-derived permissions for the current user in that workspace.
  5. Load workspace-wide default permissions where member_type matches the caller.
  6. Load the workspace creator ID.
  7. If the user is the creator and a MEMBER, return the full permission catalog from packages/utils/src/permissions.tsx.
  8. Otherwise return the deduplicated union of role-derived and default permissions.
  9. If the user is not the creator and the union is empty, return null.
MEMBER defaults are the backward-compatible default. Existing rows became member_type = 'MEMBER', and /api/v1/workspaces/[wsId]/roles/default still defaults to memberType=MEMBER when the query parameter is omitted. GUEST defaults use the same full permission catalog as members, but the default is deny: a missing guest row means no permission. The dashboard proxy applies this as a route guard for guests: members keep existing behavior, while guests may open only routes that map to an enabled guest default permission. Routes without a permission mapping are denied for guests even when the guest has admin.

Why creator fallback matters

A newly created workspace may exist before any roles or defaults are configured. The creator fallback prevents the creator from locking themselves out. The dashboard permission-setup banner exists because everyone else would otherwise have no effective permissions until defaults or roles are configured.

Member defaults never include admin

Product decision, all workspaces on every app surface that reads getPermissions() or has_workspace_permission():
  • New workspaces seed only the drive and chat MEMBER defaults (view_drive, manage_drive_tasks_directory, view_chat, create_chat; listed in packages/utils/src/member-default-permissions.ts). An invited member with no role holds only those.
  • admin reaches members only through an explicit role. Workspaces whose MEMBER defaults enabled admin keep their members’ access through a Workspace Admin (preserved) role holding the members who belonged at migration time, their role-less API keys are assigned that role, and their MEMBER admin default is disabled, so later invitees and invite-link joiners do not inherit it. An existing role with that name is reused only when it holds no creator-grant or explicit-grant permission and is not the recorded Mastermind role. API keys that already hold a role keep only that role plus the remaining defaults, so they lose the access the MEMBER admin default implied; give such a key an admin role explicitly when it needs that access. Personal workspaces keep their creator-only access.
  • A role manager can still enable admin as a MEMBER default in settings, but the permission-setup banner treats neither that nor the seeded baseline as configured access; only a role or another enabled default does.
  • Role memberships end with workspace membership. Removing a member (members API, RPC or SQL), or moving the membership row to another workspace or user, deletes their workspace_role_members rows for that workspace’s roles in the same statement, so a re-invited member starts with no roles and does not regain a preserved admin role. Demoting a MEMBER to GUEST ends their roles in that workspace the same way, and promoting them back does not restore them. Ending a root member’s recorded Mastermind role membership this way writes a revoke row to private.mastermind_access_audit. A guard on workspace_role_members refuses any role membership unless the user holds a MEMBER row in the role’s workspace, so guests and non-members never hold roles. Moving a role to another workspace (workspace_roles.ws_id) is refused for every database role, owners and service_role included, while any holder lacks a MEMBER row in the destination; API roles cannot move roles at all. Coverage: apps/database/supabase/tests/role-workspace-move-requires-members.sql, apps/database/supabase/tests/member-removal-role-memberships.sql and apps/database/supabase/tests/role-membership-requires-member.sql.
Regression coverage: apps/database/supabase/tests/member-default-admin-least-privilege.sql, apps/database/supabase/tests/member-default-admin-backfill.sql (replays the migration from a verbatim copy in tests/helpers/, which scripts/ci/pgtap-migration-copies.test.js keeps identical), packages/utils/src/__tests__/workspace-helper-seeded-member-defaults.test.ts and the setup-status route test in apps/web/src/legacy-api-routes/v1/workspaces/[wsId]/settings/permissions/setup-status/route.test.ts.

Ownership and personal status

workspaces.creator_id and workspaces.personal are protected columns. Settings managers (including admin) keep table-level UPDATE for ordinary settings such as name, handle and avatar, but a BEFORE UPDATE trigger applies these rules:
  • creator_id never changes for anon or authenticated statements, including upserts. Ownership moves only through public.transfer_workspace_ownership(ws_id, new_owner_id): the caller must be the current creator, the new owner must already be a MEMBER (not a GUEST), personal, root and deleted workspaces cannot be transferred, and the function is not executable by service_role (it has no end user to authorize).
  • Other roles may change creator_id only in these cases: the transaction has no end-user identity (migrations, cron and admin SQL, or service_role); transfer_workspace_ownership() set its transaction-local flag for that workspace id; or the change is the workspaces_creator_id_fkey ON UPDATE CASCADE follow-up of a users.id change. A SECURITY DEFINER function running under a user JWT is rejected unless it is the transfer function, so a future helper cannot reintroduce an ownership claim path.
  • Every creator_id change, whatever issued it, is recorded in public.workspace_ownership_transfers (readable by the service role only) with the actor, role and source. Audit rows keep the workspace id without a foreign key, so they survive workspace deletion.
  • personal changes only when the caller is the workspace’s current creator, and marking a workspace personal also requires exactly one member (the same rule the /api/v1/workspaces/personal route applies, now enforced for direct data-API updates too). Turning personal off is not subject to the member count. The route keeps its one-personal-workspace check on top of this.
Not yet covered: the new owner does not accept a transfer, and the transfer function does not check the new owner’s account status. Regression coverage: apps/database/supabase/tests/workspace-ownership-protection.sql.

Last member-manager self-removal

Product decision, 22 Nov 2026. The last member manager cannot leave while other full members remain.
Yes, block it (recommended) — Workspace product owner
The standard members API refuses a last member manager who tries to leave while other full members remain. The database function enforces the same rule for every removal. The API returns HTTP 409 with WORKSPACE_LAST_MANAGER before revoking seats, invitations, or board access. Web, Workspace, and mobile show the localized refusal, including “Give another member that access first” in English. The floor does not block a departure that would leave zero full members. Existing cleanup applies when the workspace has no membership rows. Creator protection still applies. CMS removals apply their manager floor to self-removal. The external-app members API refuses self-removal with HTTP 403. Regression coverage lives in the standard members API tests and database removal tests.

Members can leave a workspace

Product default, 22 Nov 2026. Any member, full member or guest, can leave a workspace without manage_workspace_members. This is the standard expectation; the workspace product owner can override it.
ordinary members must be able to leave a workspace themselves, without the manage-members permission — Platform orchestrator (Iris), product default
  • Scope: the standard members API (DELETE /api/v1/workspaces/:wsId/members?id=<self>) in Web, Workspace and Tasks. A request names the caller’s own id and no invitation email. Removing anyone else, or revoking an invitation by email, still needs manage_workspace_members.
  • Enforcement: public.remove_workspace_member_guarded_in_mode in workspace mode admits the caller’s own removal when they hold a membership row, and answers forbidden for a non-member. The creator protection and the last member-manager floor above still apply.
  • Exceptions: CMS mode is unchanged. External apps still cannot remove themselves.
Regression coverage: the self-leave without manage_workspace_members cases in the standard members API tests.

Permission edits keep a member manager

Product decision, 22 Nov 2026.
Permission edits: refuse switching off manage_workspace_members on a role or on the defaults when it would leave no manager. Return 409 WORKSPACE_LAST_MANAGER with the same EN/VI message. — Workspace product owner (“Both as recommended”)
  • Scope: role edits and default-permission edits in the standard settings (PUT /api/v1/workspaces/:wsId/roles/:roleId, PUT /api/v1/workspaces/:wsId/roles/default) and in the CMS team settings.
  • Enforcement: private.update_workspace_role_guarded and private.update_workspace_default_permissions_guarded take the workspace removal lock, recheck the actor, apply the whole edit, and roll it back with last_manager when a workspace that had a member manager would have none while a full member remains. The route answers HTTP 409 with WORKSPACE_LAST_MANAGER. Edits that do not reduce the floor behave as before. The functions also drop manage_mastermind and operate_mira_channels, and manage_subscription unless the actor is the creator; a rename of the Mastermind role or of a creator-grant role by a non-owner is refused with HTTP 403.
  • Surfaces: the Web and Workspace role editors show the same localized sentence as a refused removal.
Regression coverage: the role and default-permission route tests in apps/web/src/legacy-api-routes/v1/workspaces/[wsId]/roles/ and apps/database/supabase/tests/guarded-workspace-manager-reducers.sql.

workspace_members.role Is Not The Current Permission Source

This is the most important corrective note for anyone reading older docs or legacy schema assumptions. apps/web permission checks do not currently derive access from workspace_members.role. Modern member permission evaluation reads:
  • role memberships from workspace_role_members
  • permission definitions from workspace_role_permissions
  • workspace-wide defaults from workspace_default_permissions.member_type = 'MEMBER'
Guest permission evaluation reads workspace_default_permissions.member_type = 'GUEST' for dashboard route defaults and keeps workspace_guest_permissions for resource-specific grants such as course:view. If you document or implement new authorization behavior against workspace_members.role, you will diverge from the real app behavior.

Workspace membership and permission writes

Authorized server routes and service-role functions own writes to workspace_members, workspace_roles, workspace_role_members, workspace_role_permissions, and workspace_default_permissions. Direct Data API writes using a signed-in user’s token return PostgreSQL 42501 (HTTP 403). This applies to Web, satellite apps, mobile, and external integrations. Existing row visibility and MFA requirements still apply to reads. A creator can insert their own first membership into an empty workspace. Workspace creation triggers add the creator membership and seed Drive and Chat defaults. Signed-in callers can also manage workspace_invites and workspace_email_invites within their existing row policies. Pending invitations do not confer active workspace access. To restore the client write policies and the signed-in write privileges, use the rollback SQL as a new forward migration through the gated database workflow. Anonymous row writes and both client roles’ TRUNCATE, TRIGGER, and REFERENCES privileges stay revoked. The pgTAP suite covers client access and workspace creation. The rollback check compares the policy and privilege catalogs on a disposable replay.

Member manager postcondition

On 22 Nov 2026, Iris adopted the guarded postcondition and its self-departure exception. Postcondition. No guarded operation may finish leaving a workspace with at least one full member and no member manager, whatever the state was before the operation. An operation is allowed when, after it, the workspace has a member manager, or has no full member. One exception, self-departure. A person removing their own membership from a workspace that ALREADY had no member manager before the operation is allowed. It cannot make the workspace worse, and nobody may be trapped in a workspace they cannot leave. Under the membership rule, the last member manager cannot leave while other full members remain. A departure leaving no full member is allowed.
A person may remove their own membership from a workspace that already had no member manager. — Iris, 22 Nov 2026
In an already-managerless workspace, removing someone else, removing a role assignment, deleting a role, editing permissions, or reducing external-app access must leave a manager or leave no full members. The existing authorization and creator rules still apply. Legacy CMS removal also refuses the loss of an existing manager even when no full member would remain. Guarded functions require READ COMMITTED and refuse other isolation levels because they decide after waiting on a lock and only READ COMMITTED sees changes committed while they waited. Repair an already-managerless workspace by assigning member-management access through a role held by a full member or by enabling it in the MEMBER defaults. The Admin orphaned-workspace report lists shared workspaces that need a manager. The postcondition tests cover refusal, repair, self-departure, and the legacy CMS rule.

Account deletion and workspaces without a member manager

Product decision, 2026-11-22. Self-service account deletion is blocked while the account is the last member manager of any workspace that still has other members.
Account deletion: BLOCK deleting your own account while you’re the last member-manager of any workspace that still has other members. Show a clear message: ‘Give another member member-management access, or delete the workspace first’. — Workspace product owner, 22 Nov 2026
Scope. The rule applies to the self-service flow at /account/delete in Web, served by GET and POST /api/v1/users/me/delete. Settings in Web and Workspace link to that page. The route resolves the actor from the verified session and ignores any identity in the request body. It calls the service-role function private.account_deletion_blocking_workspaces(p_actor_id) through the admin client. Default. Deletion is refused whenever the function returns a row. POST checks before any billing, seat or workspace cleanup and again after cleanup, immediately before the Auth deletion and the Meet attendance erasure intent. A refusal returns HTTP 409:
A failed lookup refuses with HTTP 500 and deletes nothing. The GET pre-check returns the same workspaces as lastManagerWorkspaces and sets canDelete to false. deleteCurrentUserAccount in @tuturuuu/internal-api raises AccountDeletionLastManagerError, which carries the workspace list. The page shows the localized sentence with the blocking workspace names and hides the confirmation form. The Vietnamese text reads “Hãy cấp quyền quản lý thành viên cho một thành viên khác, hoặc xóa không gian làm việc trước”. Exceptions. A personal workspace never blocks deletion. A workspace with no other full member never blocks deletion; the existing cleanup removes it. Operator deletion paths, such as QA test-user cleanup and direct Auth administration by platform operators, do not run this check. Residual race. Each check reads a snapshot, and the Auth service removes the account in a separate transaction. The second check narrows the window to the Auth call itself. If two managers delete their accounts at the same time, both can pass the final check before either account is removed. A concurrent leave or permission edit can also change who manages the workspace before Auth completes. The Admin orphaned-workspace report and the repair steps under Member manager postcondition cover that case. The detector supports a read-only orphaned-workspace report for Admin. The report checks current data when opened. It lists shared workspaces that have full members and lack a member manager, with no automatic repairs. Regression coverage:

Permission Catalog

The permission catalog is defined in packages/utils/src/permissions.tsx. The catalog is grouped for UI presentation and creator fallback. The main groups currently cover:
  • workspace administration
  • AI
  • calendar
  • projects
  • documents
  • time tracking
  • drive
  • users
  • user groups
  • leads
  • inventory
  • finance
  • workforce
  • transactions
  • invoices
When the current workspace is the root workspace, an additional infrastructure group is available.

admin semantics

admin is just another permission ID in the catalog, but containsPermission() treats it as a near-full bypass:
  • creator => all permissions
  • admin => ordinary permissions. Creator-grant permissions require the workspace creator or a permitted grant.
  • explicit permission match => specific permission granted
That means admin is a permission bit, not a separate role engine.

Creator-grant permissions

manage_subscription controls billing and manage_courses controls course publication and management. The SQL has_workspace_permission() and application getPermissions() evaluate both grants independently of admin. The list lives in packages/utils/src/creator-grant-permissions.ts. Only the workspace creator (or an authorized service path) can enable a creator-grant permission on a role or add members to a role that holds one. The creator can enable manage_subscription as a default permission. Course managers are delegated through workspace roles. Role and default-permission routes (including the external-project team routes) drop these entries from non-creator payloads and keep their stored state; the role members routes return 403. Database triggers apply the same rule to direct API writes. Role managers can disable a subscription grant. The creator controls changes to a course management grant, and its role membership stays protected while the grant is disabled. Invitations follow the same rule. Only the creator can put a role holding a creator-grant permission on a pending invitation; the invite routes return 403 for anyone else. A manager editing an invitation may keep such a role when the invitation already has it. Pending invitation roles record who assigned them (assigned_by), and both private.set_workspace_invitation_roles and the invitation finalizers reject a creator-grant role the creator did not assign, so service callers cannot bypass the routes. Accepting fails with 42501 in that case rather than silently dropping the role. Re-saving an enabled grant through INSERT ... ON CONFLICT DO UPDATE preserves that grant. Invitation finalization and POS role preparation are service-only functions; API roles cannot execute them, and finalization applies the invitation rule above. Workspace creation seeds a fixed list of default permissions that excludes manage_subscription. A member joining through the service invitation flow inherits defaults explicitly enabled by the creator, including manage_subscription. Billing records (workspace_subscriptions, workspace_orders) are read-only for API users: manage_subscription holders can read them, and only the service role (Polar webhooks, sync jobs and server routes using the admin client) writes them. Regression coverage: apps/database/supabase/tests/subscription-write-scope.sql, apps/database/supabase/tests/subscription-invite-scope.sql, apps/database/supabase/tests/lms-course-publication-permissions.sql, packages/utils/src/__tests__/workspace-helper-admin-subscription.test.ts, the role route tests under apps/web/src/legacy-api-routes/v1/workspaces/[wsId]/roles/, apps/web/src/app/api/workspaces/[wsId]/members/invite/route.creator-grant.test.ts and apps/web/src/lib/external-projects/team-creator-grant.test.ts.

Where Permissions Affect The UI

apps/web/src/app/[locale]/(dashboard)/[wsId]/navigation.tsx is the broadest consumer of getPermissions(). It uses withoutPermission(...) to:
  • disable whole sidebar sections
  • disable specific children under a section
  • expose root-only capabilities only when the current user also has root-workspace permissions
  • combine permissions with workspace secrets and product-tier checks
This is why a missing permission often appears first as a disabled nav item, not as a late 403 from the clicked page.

Workspace secrets page

Web’s workspace secrets page, including /personal/secrets, resolves the workspace before applying the same getWorkspaceSecretsAccess check as the secrets API. Access requires manage_workspace_secrets or manage_workspace_roles in the root workspace, the same rule as the root-only RLS policy on public.workspace_secrets. The target workspace’s own manage_workspace_secrets does not grant access, because workspace creators and admin members imply it for their own workspace and the credential Worker writes with the service role. Denied access returns not found, rather than throwing a render error. Allowed callers read and write through the admin client. Returned rows keep the edit and delete menu. Regression coverage: the secrets page.test.tsx, row-actions.test.tsx, and the API’s access.test.ts cover resolved aliases, denied access before data reads, row controls, and database-client selection.

Secret value visibility

@tuturuuu/utils/workspace-secret-policy assigns every secret name a tier. Flags and configuration (ENABLE_*, DISABLE_*, limits, DRIVE_STORAGE_PROVIDER) are config. AI agent and external app registry rows are config only for an allowlist of exact field shapes (agent meta and instructions, channel meta, identity links, and the listed external app fields). Keys, tokens, webhook secrets, secretHash, any other registry field and every unregistered name are credential. Server code that needs a credential reads it directly through its existing server path (storage-core, AI agent and external-app stores, managed cron). The registry scan in workspace-secret-policy.test.ts fails on a new direct workspace_secrets reader (quoted table names and PostgREST embeds), on a credential name, secretHash literal or channel secret key referenced outside the listed server paths, and on a SQL comparison (=, IN, ANY (ARRAY[...]), any case) against a non-config name. Both allowlists have pinned maximum sizes and may only shrink. Encrypting the stored values is designed separately. Regression coverage: workspace-secret-policy.test.ts, the web and admin secrets route.test.ts files, and the web and workspace secrets page.test.tsx.

Mobile module flags

The mobile app applies per-workspace module visibility through secrets exposed by /api/v1/workspaces/[wsId]/mobile/module-flags. The route authenticates the mobile session, verifies workspace membership with the request-scoped client, then reads only the mobile module flag secrets with an admin client. Supported secrets:
  • MOBILE_HIDE_EXPERIMENTAL_MODULES: truthy values (1, true, yes, on) hide the legacy module set defined by the endpoint. The flag name remains supported for configured workspaces.
  • MOBILE_HIDDEN_MODULES: JSON array or comma-separated module IDs for explicit hidden modules. The documents and notes IDs control their respective views. Mobile shows the Documents launcher destination when either view is available.
Keep these flags as display controls. API routes that expose protected module data must still perform their own workspace membership and permission checks.

Settings pages

Workspace settings pages usually follow this pattern:
  1. resolve the workspace with WorkspaceWrapper
  2. call getPermissions({ wsId })
  3. redirect away or notFound() if the required permission is missing
Examples:
  • members page requires manage_workspace_members
  • roles page requires manage_workspace_roles
  • settings page checks manage_workspace_settings and manage_workspace_security

Members UI

The members settings surfaces use workspace_members_and_invites so joined members and pending invites can be shown together. The enhanced members route also merges:
  • role memberships
  • enabled role permissions
  • default permissions
  • creator flag
  • privacy-related workspace secrets like HIDE_MEMBER_EMAIL and HIDE_MEMBER_NAME
That is why the members page can show a permission breakdown per person without recomputing everything in the browser. Member-removal APIs accept canonical UUID syntax, including uppercase input, and normalize it to lowercase before member protection checks and scoped deletion. Unsupported UUID spellings return 400. Creator protection applies to the shared web/Tasks route; external-app removal also retains self and last-admin checks. Email-only invitation removal keeps its existing behavior. Regression coverage: packages/apis/src/members/route.remove-authorization.test.ts and apps/web/src/lib/external-apps/workspace-members.removal.test.ts.

Where Permissions Affect API Routes

There are two broad families in apps/web.

Session-authenticated browser/mobile routes

These routes use:
  • createClient(request) or withSessionAuth(...) for authentication
  • normalizeWorkspaceId() for canonical workspace lookup
  • getPermissions() when a privileged capability is involved
Examples:
  • apps/web/src/app/api/workspaces/[wsId]/route.ts
  • apps/web/src/app/api/workspaces/[wsId]/members/route.ts
  • many apps/web/src/app/api/.../workspaces/[wsId]/... handlers

Workspace API key routes

SDK-facing routes use withApiAuth(...) from apps/web/src/lib/api-middleware.ts. The middleware:
  1. extracts the API key from Authorization
  2. validates it against workspace_api_keys
  3. loads role-derived and default permissions for that key
  4. enforces rate limits and IP bans
  5. rejects requests whose [wsId] does not match the API key’s bound workspace
That keeps the permission vocabulary identical between browser/session access and API-key access.

Split Between Session Client And Admin Client

A recurring pattern in the helpers is:
  • authenticate with the request-scoped or cookie-scoped Supabase client
  • then read supporting tables with an admin client when richer joins or privileged reads are needed
Examples:
  • getPermissions() authenticates with a normal client but reads role/default data through an admin client.
  • getWorkspace() authenticates first, then may use an admin client for the workspace fetch when requested.
This is intentional. It preserves the caller identity while still allowing the app to assemble permission state that would be awkward to fetch purely through RLS-limited joins. Name every createAdminClient() local sbAdmin, not supabase, so reviewers can immediately distinguish service-role access from request-scoped clients.

Special Workspace Rules

Personal workspaces

Personal workspaces are special in several places:
  • canonical URL slug is always personal
  • roles management is effectively bypassed in the UI
  • invitations are blocked
  • manual deletion is blocked
  • many workspace settings pages simplify or redirect for personal mode

Root/internal workspace

The root workspace is the internal control plane. Common patterns:
  • canonical URL slug is internal
  • extra infrastructure permissions exist only here
  • some features compare target-workspace permissions with root-workspace permissions
  • root membership is often treated as the gate for platform-wide admin tooling

Account security administration

Infrastructure exposes Platform Admin → Account Security only when the operator has the root-only manage_internal_accounts permission. The server rechecks that permission against the root workspace on every request and requires the actor to use an exact @tuturuuu.com email address. Use Platform account recovery to force-set a temporary password for any Tuturuuu platform account by its exact email address. The internal directory limits profile, Drive, and per-account password/MFA controls to exact @tuturuuu.com accounts. Disable-access and enable-access are an explicit exception: they also accept strictly validated managed subdomains such as @xwf.tuturuuu.com, with matching email confirmation and the same target UUID. External addresses and suffix lookalikes remain ineligible; actors still require an exact-root address and manage_internal_accounts. Self-service access and password mutations are rejected to reduce accidental lockouts. Passwords must never be copied into logs, tickets, or coordination notes; share a temporary password only through an approved secure channel. Disabling access applies an Auth ban and does not implicitly revoke every already-issued session. If an incident also requires session revocation, handle that as a separate authenticated operation and verify the target carefully.

Current Enforcement Patterns In The Codebase

Today the codebase uses a mix of patterns:
  • newer surfaces centralize on WorkspaceWrapper, normalizeWorkspaceId(), and getPermissions()
  • internal API client helpers call web routes instead of letting client components query arbitrary tables directly
  • some older routes still hand-query role/default permission tables instead of calling getPermissions()
  • some routes still rely mostly on membership + RLS and do not add a second explicit permission layer
That means the architecture is clear, but the implementation is still partly transitional. When adding new routes, prefer the shared helpers instead of reimplementing the joins manually. For a new workspace-scoped server page:
  1. Use WorkspaceWrapper.
  2. Use the normalized wsId from the wrapper callback for all DB reads.
  3. Call getPermissions({ wsId }) before rendering privileged content.
  4. Gate or redirect from containsPermission(...) / withoutPermission(...).
For a new workspace-scoped API route:
  1. Authenticate with createClient(request) or withSessionAuth(...).
  2. Normalize the route param with normalizeWorkspaceId(...).
  3. Verify membership when needed.
  4. Call getPermissions({ wsId, request }) for privileged behavior.
  5. Use packages/internal-api on the client instead of ad hoc browser fetch() contracts when the route is meant to be reused.
For a new SDK/API-key route:
  1. Wrap the handler with withApiAuth(...).
  2. Require specific permission IDs in the middleware options when possible.
  3. Reject workspace mismatches instead of trying to remap the requested workspace.

Quick Reference

Practical Rules To Keep In Mind

  • A member can exist without any effective permissions.
  • The creator always has the full catalog, even if no roles/defaults exist yet.
  • admin grants ordinary permissions. Course management and subscription access use their creator-grant rules.
  • workspace_users is not the access-control table.
  • Browser URLs prefer personal and internal, but DB queries should use canonical UUIDs.
  • New privileged routes should reuse the shared helpers instead of reimplementing role/default joins.

Employee creation preparation

Infrastructure uses the registered satellite session id infra. Employee creation requires a fresh root-workspace MEMBER, manage_internal_accounts, and a current confirmed, unbanned administrator with an exact @tuturuuu.com identity. Directory subdomains do not grant staff mutation privileges. The first-class web /api/v1/infrastructure/internal-accounts/employees boundary currently reports available: false and refuses authenticated creation with503. The UI exposes a disabled preparation form. No journal, provider or SQL connector is installed by this source change. The shared client strictly validates the request and acknowledgement, binds an operation key, and never retries creation. A durable journal is a separate prerequisite: atomically bind the administrator, operation key and canonical payload fingerprint to one server-allocated target UUID; preserve that UUID and exact email/name tuple across re-entry. A conflicting payload or known pending/unknown result requires inspection. A caller header, in-memory map or the existing per-invocation UUID orchestration is not this journal. Temporary passwords must remain transient and must not enter journal payloads, logs, browser storage or receipts. Actual172-assertion disposable-schema qualification is distinct from current-main schema composition, correct-project applied ledger/catalog/ACL proofs, real provider ownership and runtime qualification. Keep creation unavailable until the durable journal and bounded transport satisfy those gates. No blind provider create retry, compensation deletion, mailbox change or named-account creation is authorized by the preparation form.

Workspace deletion failures

The Web settings UI disables deletion for personal and root workspaces and requires an exact workspace-name confirmation for other workspaces. A failed request uses the mounted Sonner toaster, preserves the confirmation, and leaves navigation unchanged. Pending requests disable the confirmation action and do not retry automatically. HTTP errors retain the API message; transport failures use a localized message that asks the user to check the workspace before another attempt. The DELETE handler keeps its permission and prevention-secret checks. A returned database error produces HTTP 500 and logs only its code under Workspace deletion failed; raw database messages, row details and identifiers must not be added to that log or response. Use that code to distinguish constraint failures from other causes before proposing schema changes. Two retained schema definitions can block deletion when their child rows exist: realtime_log_aggregations.ws_id is NOT NULL while its workspace FK uses ON DELETE SET NULL (23502), and workspace_documents_ws_id_fkey has no cascade (23503). Correcting these requires a separately authorized migration. Do not work around them with client-side child deletions or weaken their constraints. Regression coverage: settings security.test.tsx, the workspace detail API’s route.test.ts, and internal-api workspaces-delete.test.ts cover error display, confirmation state, one pending dispatch, HTTP propagation and safe diagnostics.

Role permission workspace binding

Permission readers that join workspace_role_permissions through a role scope both the role and its permission rows to the requested workspace (workspace_roles.ws_id and workspace_roles.workspace_role_permissions.ws_id). This includes the encryption manage_e2ee check, the web and Tasks member-role summaries, and the Mira time-tracking approval-bypass check. Role-management listings that embed a role’s permissions under a ws_id-filtered workspace_roles query are display-only and are not covered by this rule. workspace-role-reader-scoping.test.ts (web), workspace-members.test.ts (Tasks) and timer-helpers.test.ts (AI) cover foreign and local permission rows.

Infrastructure workspace secrets

Infrastructure workspace-secret APIs require root MEMBER membership and either manage_workspace_secrets or manage_workspace_roles before using an admin client (an internal security review). Tenant permissions alone do not grant infrastructure access. Creating, renaming, updating, or deleting MANAGED_CRON_ENABLED also requires a current subject-bound verified Auth user and verified Tuturuuu staff session. A matching email alone does not grant access. Regression coverage: infrastructure’s infrastructure-admin-access.test.ts, rate-limits workspace-secrets/route.test.ts, and workspace secrets managed-cron.test.ts (which also covers renaming a normal secret into MANAGED_CRON_ENABLED and the workspace and id binding of the lookup).

Workspace deletion and retained history

For non-personal workspaces, deletion removes workspace-owned realtime log aggregations, documents including their meeting-document links, and team membership rows. Team member user accounts and memberships in other workspaces survive. Migration 20261030112010 repairs those three foreign keys with ON DELETE CASCADE NOT VALID; 20261030112020 validates them separately. New writes and cascading deletes are enforced immediately during the NOT VALID phase. The document ws_id index is created concurrently by 20261030112000 before the guarded foreign-key swap. Validation has a 15-minute statement timeout for the unpruned realtime log table, whose production size must be checked before release; its SHARE UPDATE EXCLUSIVE lock allows ordinary writes. Rollback first commits a NOT VALID swap, then validates the original definitions in a separate transaction using the rollback-validate.sql file, after swap/index locks are released. These database rules apply to all app surfaces using the shared workspace deletion path. Documents without a workspace, documents in another workspace, and the creator’s account survive. This is not a blanket history-deletion policy. Immutable topic delivery receipts, billing reservations, provider-operation journals, bank events, cross-workspace chat attachments, healthcare measurements, and other retained references keep their existing guards. Their populated workspaces may still reject hard deletion. Mastermind must decide whether to retain a soft-deleted workspace or approve a durable archive and scoped reference migration before changing those rules. Personal-workspace deletion restrictions also remain in force. Regression coverage is apps/database/supabase/tests/workspace-delete-fk-cascade.sql: populated deletion, no document/log/meeting/membership orphans, surviving member accounts and unrelated data, immediate rejection of new FK orphans, and continued rejection for retained delivery/personal workspaces. The catalog audit and full-schema up/down/up verifier live under apps/database/verification/workspace-delete-*. These checks exercise local SQL and database roles; they do not establish HTTP, staging, or production acceptance.

Permission predicate caller scope

has_workspace_permission, is_org_member, can_manage_workspace_external_projects, can_publish_workspace_external_projects, and is_root_external_project_admin answer only for auth.uid() under anonymous/authenticated JWT roles outside triggers; other-user queries return false. Service-role, owner and trigger evaluation retain their scope. Invites check the actual target membership row. Role-bearing invites require MEMBER type, member- and role-management permissions, and a same-workspace role. Rollbacks retain caller binding and grant helper execution only to authenticated/service roles. manage_mastermind requires the recorded root role and its enabled explicit grant. Creator/admin/default permissions never imply it. Only the audited owner procedure admits a member; this migration grants nobody access. The storage-limit RPC requires authenticated or service-role EXECUTE. operate_mira_channels (the Mira channels operator permission) is also an explicit grant: has_workspace_permission(), getPermissions(), API-key checks and the mobile mirror answer it only from an enabled grant on a root role the user holds. It has no dedicated role or audited grant procedure; database triggers let only a database-owner session that sets tuturuuu.mira_operator_grant = 'owner' enable it or add members to a role holding it (see Mira cloud channels). Regression coverage: has-workspace-permission-caller-scope.sql, manage-mastermind-*.sql, mira-channel-operator-and-usage.sql, workspace-invite-role-binding.sql, meet-audio-chunk-read-boundary.sql, workspace-storage-limit-execute.sql, and workspace-permission-*.sql. Apply the actual rollback before running verification/workspace-permission-rollback.sql and the invitation-role suite. The same JWT and trigger scope applies to is_workspace_owner, is_member_invited, user_is_in_channel, is_hive_member, is_hive_platform_admin, can_create_workspace, and count_user_workspaces. Non-self boolean checks return false; workspace counts return zero. Workspace creation limits query the caller’s own count. is_task_plan_intended_workspace returns false for nonmembers. is_personal_workspace returns NULL for nonmembers outside triggers: neither a personal-only nor a nonpersonal-only predicate can authorize with a hidden value. Trigger checks retain the real personal flag. Analytics growth and retention RPCs are executable only by service_role. Regression coverage: remaining-membership-helpers-caller-bound.sql and external-project-helpers-caller-bound.sql; anonymous EXECUTE stays revoked.

Role workspace ownership

Role permission rows reference the role’s workspace through a composite foreign key. API database roles cannot move a role to another workspace. Service-role maintenance may move it, cascading its permission rows to the destination. Across Web role editors, external project teams and external app member tools, renaming a role with a subscription grant (including a disabled grant) requires the creator of every workspace holding that grant. Adding members checks enabled grants. Plain roles remain editable by role managers. Name-selected POS and external-app administrator roles cannot silently reuse subscription-granted roles. Explicit Mastermind permissions continue to be filtered from ordinary role writes. Regression coverage: role-workspace-consistency.sql, name-based-role-creator-grant.sql, workspace-creator-grant-permissions.test.ts, the role route tests, and external project/app member tests. Database checks must run against the applied migration chain; route mocks alone do not qualify SQL.