The Atlas MikeAzureDev's documentation, bound to its code
140 documents

A request through the backend

Follow an authenticated browser request from the auth middleware, through the access checks, to the data layer — and see why @supabase/supabase-js is still the data client.

backend/src/lib/access.ts1089 lines · checkProjectAccess L373–449
Outline 40 symbols
1import type { Db } from "./supabase";
2import { chunkArray } from "./arrays";
3import {
4 hasOrgPrivateContentAccess,
5 listOrgPrivateContentAccess,
6} from "./orgPrivateContent";
7
8/**
9 * Project / document access helpers.
10 *
11 * Sharing makes the previous "scope by user_id" pattern incorrect — a doc
12 * can belong to user A's project that A has shared with B's email, and B
13 * must still be able to read/edit it. These helpers centralize the
14 * exclusive organization-or-direct scope check so every route uses the same
15 * logic instead of re-implementing the join.
16 *
17 * The creator is Owner. For personal content, access otherwise comes from one
18 * role-aware direct grant. Projects and workflows may instead belong to an
19 * organization, where they are PRIVATE BY DEFAULT: reachable by the creator,
20 * and by the members they have been shared with
21 * (a per-resource override of Owner, Editor, Viewer — or Deny, which walls a
22 * member off). Making one public gives every member Editor. Sharing never
23 * reaches outside the organization. A chat or review in a project inherits
24 * the project's access. One started on its own in an organization's
25 * workspace belongs to that organization and is private to its author
26 * (`ensureSharedRowAccess`).
27 *
28 * `resolveOrgContentRole` below is that rule; public.project_access_role and
29 * public.workflow_access_role in schema.sql are its SQL twins.
30 *
31 * Personal content is still `org_id IS NULL`: each account has a personal
32 * organization of its own (lib/personalOrgs.ts), but no work has moved into
33 * it. Content without an org is reachable through branches 1 and 2 only.
34 */
35
36import {
37 getContentGrantRole,
38 type ContentGrantKind,
39} from "./contentAccess";
40import { isPersonalOrg, teamOrgIdOf } from "./personalOrgs";
41import {
42 can,
43 isProjectRole,
44 type ProjectRole,
45} from "./permissions";
46import {
47 getOrgAccessOverrideRole,
48 isOrgAccessOverrideRole,
49 type OrgAccessOverrideRole,
50 type OrgResourceKind,
51} from "./orgAccessOverrides";
52
53export {
54 can,
55 isProjectRole,
56 type ProjectRole,
57} from "./permissions";
58
59/**
60 * Organizations have three roles, strongest first. Owners are accountable for
61 * the organization: they alone delete it and appoint or remove admins and
62 * other owners. Admins run it day to day (members, invitations, settings).
63 * Members collaborate. Owners manage public and ownerless projects/workflows.
64 * For private items still owned by another member, owners and permitted admins
65 * must explicitly open read-only access through the audited private-content path.
66 */
67export type OrgRole = "owner" | "admin" | "member";
68
69export const ORG_ROLES: OrgRole[] = ["owner", "admin", "member"];
70
71const ORG_ROLE_RANK: Record<OrgRole, number> = {
72 member: 0,
73 admin: 1,
74 owner: 2,
75};
76
77export function isOrgRole(value: unknown): value is OrgRole {
78 return typeof value === "string" && (ORG_ROLES as string[]).includes(value);
79}
80
81/** Only an org owner may delete the org or decide who administers it. */
82export function isOrgOwner(role: OrgRole | null | undefined): boolean {
83 return role === "owner";
84}
85
86/**
87 * Whether the role may administer an org (members, invitations, settings).
88 * An owner can do everything an admin can.
89 */
90export function isOrgAdmin(role: OrgRole | null | undefined): boolean {
91 return role === "owner" || role === "admin";
92}
93
94/** The stronger of two organization roles. */
95export function strongerOrgRole(a: OrgRole, b: OrgRole): OrgRole {
96 return ORG_ROLE_RANK[a] >= ORG_ROLE_RANK[b] ? a : b;
97}
98
99/**
100 * Whether `actor` may give somebody `role`, or act on somebody who holds it:
101 * invite at it, change it, remove its holder.
102 *
103 * Owners are peers and may act at every level, their own included. Everyone
104 * else acts only strictly below themselves, which is what stops an admin
105 * from appointing a second admin, promoting themselves or removing an owner.
106 */
107export function canManageOrgRole(
108 actor: OrgRole | null | undefined,
109 role: OrgRole,
110): boolean {
111 if (!actor) return false;
112 if (actor === "owner") return true;
113 return ORG_ROLE_RANK[actor] > ORG_ROLE_RANK[role];
114}
115
116/** Who may open an organization's project or workflow without being named. */
117export type ContentVisibility = "private" | "organization";
118
119export function isContentVisibility(value: unknown): value is ContentVisibility {
120 return value === "private" || value === "organization";
121}
122
123/**
124 * Read a `visibility` an API caller sent for a project or workflow.
125 *
126 * Absent means "leave it as it is" (private, for a new item). Public is only
127 * meaningful inside an organization: a personal item is shared by naming
128 * people, and has no "everyone" to be opened to.
129 */
130export function parseContentVisibility(
131 value: unknown,
132 orgId: string | null | undefined,
133):
134 | { ok: true; visibility: ContentVisibility | undefined }
135 | { ok: false; detail: string } {
136 if (value === undefined || value === null)
137 return { ok: true, visibility: undefined };
138 if (!isContentVisibility(value))
139 return {
140 ok: false,
141 detail: "visibility must be 'private' or 'organization'",
142 };
143 if (value === "organization" && !orgId)
144 return {
145 ok: false,
146 detail: "Only an organization's item can be shared with the whole organization.",
147 };
148 return { ok: true, visibility: value };
149}
150
151/**
152 * The caller's role on an organization's project or workflow, or null for no
153 * access. The caller is already known to be a CURRENT member of that
154 * organization; a non-member never reaches this.
155 *
156 * 1. the creator -> owner
157 * 2. an organization owner, when the item is
158 * public or has no Owner left -> owner
159 * 3. a member it was shared with -> the role they were given
160 * (`deny` walls a member off, a public item included)
161 * 4. everyone, when it is public -> editor
162 *
163 * An organization owner has no standing on a member's private item: private
164 * is private. They take one over only when it is `ownerless` — its creator
165 * has left the organization and nobody else was made an Owner — so the firm
166 * never loses a matter and a departure never waits on a hand-over. The
167 * database decides what is ownerless (isOrgItemOwnerless,
168 * loadOwnerlessOrgItemIds); it is false for everything else.
169 *
170 * One function, because five read paths apply this rule (the single-item
171 * checks, the accessible-project list, the document picker and the
172 * organization's own resource list) and they must never disagree. It mirrors
173 * the SQL project_access_role / workflow_access_role.
174 */
175export function resolveOrgContentRole(input: {
176 isCreator: boolean;
177 orgRole: OrgRole;
178 override: OrgAccessOverrideRole | null | undefined;
179 visibility: unknown;
180 ownerless: boolean;
181}): ProjectRole | null {
182 if (input.isCreator) return "owner";
183 if (
184 isOrgOwner(input.orgRole) &&
185 (input.visibility === "organization" || input.ownerless)
186 )
187 return "owner";
188 if (input.override === "deny") return null;
189 if (input.override) return input.override;
190 return input.visibility === "organization" ? "editor" : null;
191}
192
193/**
194 * Whether an organization's private project or workflow has no Owner left
195 * among its current members, which is when its organization's owners take
196 * it over. Asked of the database so the list RPCs and these checks reach
197 * the same answer. Fails closed: an unanswered question is "no", and an
198 * organization owner then has no more access than any other member.
199 */
200export async function isOrgItemOwnerless(
201 db: Db,
202 kind: "project" | "workflow",
203 itemId: string,
204): Promise<boolean> {
205 const { data, error } = await db.rpc("org_item_is_ownerless", {
206 p_kind: kind,
207 p_item_id: itemId,
208 });
209 return !error && data === true;
210}
211
212/**
213 * The private projects and workflows without an Owner in the given
214 * organizations, for filters over many rows. Pass only the organizations
215 * the caller OWNS: nobody else's verdict depends on it, and with none there
216 * is nothing to ask. Fails closed, like isOrgItemOwnerless.
217 */
218export async function loadOwnerlessOrgItemIds(
219 db: Db,
220 ownedOrgIds: string[],
221): Promise<{ projects: Set<string>; workflows: Set<string> }> {
222 const ownerless = { projects: new Set<string>(), workflows: new Set<string>() };
223 if (ownedOrgIds.length === 0) return ownerless;
224 const { data, error } = await db.rpc("ownerless_org_item_ids", {
225 p_org_ids: ownedOrgIds,
226 });
227 if (error || !Array.isArray(data)) return ownerless;
228 for (const row of data as { kind?: unknown; item_id?: unknown }[]) {
229 if (typeof row.item_id !== "string") continue;
230 if (row.kind === "project") ownerless.projects.add(row.item_id);
231 else if (row.kind === "workflow") ownerless.workflows.add(row.item_id);
232 }
233 return ownerless;
234}
235
236/** Normalize an email the way every grant/invitation row stores it. */
237export function normalizeEmail(
238 email: string | null | undefined,
239): string | null {
240 const normalized = (email ?? "").trim().toLowerCase();
241 return normalized || null;
242}
243
244/**
245 * The caller's role in a single org, or null if they are not a member.
246 */
247export async function getOrgRole(
248 userId: string,
249 orgId: string | null | undefined,
250 db: Db,
251): Promise<OrgRole | null> {
252 if (!orgId) return null;
253 const { data } = await db
254 .from("org_members")
255 .select("role, organizations!inner(id)")
256 .is("organizations.deleted_at", null)
257 .eq("org_id", orgId)
258 .eq("user_id", userId)
259 .maybeSingle();
260 const role = (data as { role?: string } | null)?.role;
261 return isOrgRole(role) ? role : null;
262}
263
264/**
265 * The role a direct access grant gives the caller on a project, or null when
266 * they hold no grant. Grants are keyed by normalized email so an invitation
267 * to share can be honoured before the recipient has an account.
268 */
269export async function getProjectGrantRole(
270 projectId: string,
271 userEmail: string | null | undefined,
272 db: Db,
273): Promise<ProjectRole | null> {
274 const email = normalizeEmail(userEmail);
275 if (!email) return null;
276 const { data } = await db
277 .from("project_access_grants")
278 .select("role")
279 .eq("project_id", projectId)
280 .eq("email", email)
281 .maybeSingle();
282 const role = (data as { role?: string } | null)?.role;
283 return isProjectRole(role) ? role : null;
284}
285
286/**
287 * Choose the org_id a newly created resource should carry. Content created
288 * inside a project inherits that project's org; everything else is personal
289 * (org_id null). An absent org is still the personal case: the account's
290 * personal organization exists, but nothing is filed under it yet.
291 *
292 * Result-shaped because "the lookup failed" and "this is personal" must
293 * never share a value. `null` is not a safe default here: it is the very
294 * encoding of personal content, and personal content is what account
295 * deletion destroys. A swallowed error at this seam filed a firm's upload
296 * as its uploader's private property — invisible to org inheritance today,
297 * destroyed with the uploader's account later. Callers refuse the request
298 * instead of guessing the tenant.
299 */
300export async function resolveContentOrgId(
301 db: Db,
302 params: { projectId?: string | null },
303): Promise<{ ok: true; orgId: string | null } | { ok: false; detail: string }> {
304 if (!params.projectId) return { ok: true, orgId: null };
305 const { data, error } = await db
306 .from("projects")
307 .select("org_id")
308 .eq("id", params.projectId)
309 .maybeSingle();
310 if (error)
311 return {
312 ok: false,
313 detail:
314 error.message ?? "Failed to resolve the project's organization",
315 };
316 if (!data)
317 return {
318 ok: false,
319 detail: "Project not found",
320 };
321 return {
322 ok: true,
323 orgId: (data as { org_id?: string | null }).org_id ?? null,
324 };
325}
326
327/**
328 * The org_id for a chat or review started on its own, outside any project:
329 * the organization whose workspace its author is working in, named by the
330 * client as `org_id`, or null for Personal.
331 *
332 * The caller must belong to it. A person's own organization is not named
333 * here: Personal is the absence of one.
334 */
335export async function resolveStandaloneOrgId(
336 db: Db,
337 params: { userId: string; orgId: unknown },
338): Promise<{ ok: true; orgId: string | null } | { ok: false; detail: string }> {
339 const { orgId } = params;
340 if (orgId === undefined || orgId === null || orgId === "")
341 return { ok: true, orgId: null };
342 if (typeof orgId !== "string")
343 return { ok: false, detail: "org_id must be a string" };
344 const role = await getOrgRole(params.userId, orgId, db);
345 if (!role || (await isPersonalOrg(db, orgId)))
346 return {
347 ok: false,
348 detail: "You are not a member of that organization.",
349 };
350 return { ok: true, orgId };
351}
352
353type ProjectRow = {
354 id: string;
355 user_id: string | null;
356 org_id?: string | null;
357 visibility?: string | null;
358};
359
360export type ProjectAccess =
361 | {
362 ok: true;
363 /** True when the caller created this row ("created by me"), which is
364 * provenance only — it grants no rights beyond the admin role the
365 * creator branch already derives. */
366 isCreator: boolean;
367 orgRole: OrgRole | null;
368 projectRole: ProjectRole;
369 project: ProjectRow;
370 }
371 | { ok: false };
372
373export async function checkProjectAccess(
374 projectId: string,
375 userId: string,
376 userEmail: string | null | undefined,
377 db: Db,
378): Promise<ProjectAccess> {
379 const { data: project } = await db
380 .from("projects")
381 .select("id, user_id, org_id, visibility, archived_at")
382 .eq("id", projectId)
383 .maybeSingle();
384 if (!project || project.archived_at) return { ok: false };
385 const proj = project as ProjectRow;
386
387 const isCreator = !!proj.user_id && proj.user_id === userId;
388
389 // Organization scope is exclusive, and only a current member is in it:
390 // somebody who has left the organization has no access, the creator
391 // included. Inside it the project is private until shared or made public
392 // (resolveOrgContentRole).
393 if (proj.org_id) {
394 const orgRole = await getOrgRole(userId, proj.org_id, db);
395 if (!orgRole) return { ok: false };
396 // The two verdicts that need nothing else read: the creator, and an
397 // organization owner on a public project.
398 if (
399 isCreator ||
400 (isOrgOwner(orgRole) && proj.visibility === "organization")
401 )
402 return {
403 ok: true,
404 isCreator,
405 orgRole,
406 projectRole: "owner",
407 project: proj,
408 };
409 const override = await getOrgAccessOverrideRole(
410 db,
411 "project",
412 proj.id,
413 proj.org_id,
414 userId,
415 );
416 // Fail closed: an unreadable override table must not admit a member
417 // who may have been walled off.
418 if (!override.ok) return { ok: false };
419 let projectRole = resolveOrgContentRole({
420 isCreator: false,
421 orgRole,
422 override: override.role,
423 visibility: proj.visibility,
424 // Only an organization owner's verdict on a private project
425 // turns on this, so only then is it asked.
426 ownerless:
427 isOrgOwner(orgRole) && proj.visibility !== "organization"
428 ? await isOrgItemOwnerless(db, "project", proj.id)
429 : false,
430 });
431 if (
432 !projectRole && isOrgAdmin(orgRole) &&
433 await hasOrgPrivateContentAccess(db, proj.org_id, userId, "project", proj.id)
434 ) projectRole = "viewer";
435 if (!projectRole) return { ok: false };
436 return {
437 ok: true,
438 isCreator: false,
439 orgRole,
440 projectRole,
441 project: proj,
442 };
443 }
444
445 const grantRole = await getProjectGrantRole(proj.id, userEmail, db);
446 const projectRole = isCreator ? "owner" : grantRole;
447 if (!projectRole) return { ok: false };
448 return { ok: true, isCreator, orgRole: null, projectRole, project: proj };
449}
450
451/** A personal project is private only while it has no direct grants. */
452export async function projectHasSharedAudience(
453 db: Db,
454 projectId: string,
455 orgId: string | null | undefined,
456): Promise<boolean> {
457 if (orgId) return true;
458 const { data, error } = await db
459 .from("project_access_grants")
460 .select("id")
461 .eq("project_id", projectId)
462 .limit(1);
463 if (error) throw new Error("Failed to resolve project audience");
464 return (data ?? []).length > 0;
465}
466
467type ResourceAccess =
468 | {
469 ok: true;
470 isCreator: boolean;
471 orgRole: OrgRole | null;
472 projectRole: ProjectRole;
473 }
474 | { ok: false };
475
476/**
477 * Some operations stay scoped to the person who made the row — replacing or
478 * deleting one version of a document, moving a review between projects.
479 * Those rules are about authorship, not tier, and they predate this module.
480 *
481 * They acquired a hole the moment account deletion started blanking
482 * `user_id` instead of destroying an organization's content: a row can now
483 * have no creator at all, and "only the creator may act" then means NOBODY
484 * may act. The document is stranded inside a project the organization is
485 * supposed to control — exactly the outcome detaching the row was meant to
486 * prevent. So when the creator is gone, the container's Owners inherit the
487 * operation. While a creator still exists, nothing changes: an Owner does
488 * not get to reach into a colleague's versions.
489 */
490export function creatorScopedAllowed(
491 access: { isCreator: boolean; projectRole: ProjectRole },
492 creatorId: string | null | undefined,
493): boolean {
494 if (access.isCreator) return true;
495 return !creatorId && can(access.projectRole, "container.delete");
496}
497
498/** Build the ResourceAccess for a derived project role. */
499function resourceAccessFor(
500 projectRole: ProjectRole,
501 orgRole: OrgRole | null,
502 isCreator: boolean,
503): ResourceAccess {
504 return { ok: true, isCreator, orgRole, projectRole };
505}
506
507async function organizationResourceAccess(
508 // Playbooks resolve their own access (modules/playbooks), without the
509 // ownerless take-over and audited admin access below.
510 kind: Exclude<OrgResourceKind, "playbook">,
511 row: {
512 id: string;
513 user_id: string | null;
514 org_id?: string | null;
515 visibility?: string | null;
516 },
517 userId: string,
518 db: Db,
519): Promise<ResourceAccess> {
520 if (!row.org_id) return { ok: false };
521 const orgRole = await getOrgRole(userId, row.org_id, db);
522 if (!orgRole) return { ok: false };
523 const isCreator = !!row.user_id && row.user_id === userId;
524 if (
525 isCreator ||
526 (isOrgOwner(orgRole) && row.visibility === "organization")
527 )
528 return resourceAccessFor("owner", orgRole, isCreator);
529 const override = await getOrgAccessOverrideRole(
530 db,
531 kind,
532 row.id,
533 row.org_id,
534 userId,
535 );
536 if (!override.ok) return { ok: false };
537 let role = resolveOrgContentRole({
538 isCreator: false,
539 orgRole,
540 override: override.role,
541 visibility: row.visibility,
542 ownerless:
543 isOrgOwner(orgRole) && row.visibility !== "organization"
544 ? await isOrgItemOwnerless(db, kind, row.id)
545 : false,
546 });
547 if (
548 !role && isOrgAdmin(orgRole) &&
549 await hasOrgPrivateContentAccess(db, row.org_id, userId, kind, row.id)
550 ) role = "viewer";
551 return role ? resourceAccessFor(role, orgRole, false) : { ok: false };
552}
553
554type WorkflowRow = {
555 id: string;
556 user_id: string | null;
557 org_id?: string | null;
558 visibility?: string | null;
559};
560
561export type WorkflowAccess =
562 | {
563 ok: true;
564 isCreator: boolean;
565 orgRole: OrgRole | null;
566 projectRole: ProjectRole;
567 workflow: WorkflowRow;
568 }
569 | { ok: false };
570
571/** Resolve a workflow through exactly one scope: organization or direct. */
572export async function checkWorkflowAccess(
573 workflowId: string,
574 userId: string,
575 userEmail: string | null | undefined,
576 db: Db,
577): Promise<WorkflowAccess> {
578 const { data } = await db
579 .from("workflows")
580 .select("id, user_id, org_id, visibility, archived_at")
581 .eq("id", workflowId)
582 .maybeSingle();
583 if (!data || data.archived_at) return { ok: false };
584 const workflow = data as WorkflowRow;
585 const isCreator = !!workflow.user_id && workflow.user_id === userId;
586
587 if (workflow.org_id) {
588 const access = await organizationResourceAccess(
589 "workflow",
590 workflow,
591 userId,
592 db,
593 );
594 return access.ok
595 ? { ...access, workflow }
596 : { ok: false };
597 }
598
599 if (isCreator)
600 return {
601 ok: true,
602 isCreator: true,
603 orgRole: null,
604 projectRole: "owner",
605 workflow,
606 };
607 const email = normalizeEmail(userEmail);
608 if (!email) return { ok: false };
609 // An exact match is correct because BOTH sides are canonical:
610 // normalizeEmail trims and lowercases the caller's address, and
611 // workflow_shares.shared_with_email carries a lowercase CHECK (added by
612 // migration 20260917_01, which also folded the legacy mixed-case rows).
613 // Before that constraint a mixed-case row listed for its recipient via
614 // get_workflows_overview — which lowers both sides — and then missed
615 // here, so the workflow 404'd the moment they opened it.
616 const { data: share, error } = await db
617 .from("workflow_shares")
618 .select("role")
619 .eq("workflow_id", workflowId)
620 .eq("shared_with_email", email)
621 .maybeSingle();
622 if (error) return { ok: false };
623 const role = (share as { role?: unknown } | null)?.role;
624 if (!isProjectRole(role)) return { ok: false };
625 return {
626 ok: true,
627 isCreator: false,
628 orgRole: null,
629 projectRole: role,
630 workflow,
631 };
632}
633
634/**
635 * Check whether the current user can access a document the caller has
636 * already loaded (saves a round-trip vs. having the helper re-fetch).
637 * Project and workflow documents inherit their container role exactly.
638 * `isCreator` remains row provenance: a project Owner is not the creator of a
639 * colleague's document, while that colleague does not gain extra permissions
640 * beyond the inherited container role.
641 */
642export async function ensureDocAccess(
643 doc: {
644 id?: string;
645 user_id: string | null;
646 project_id: string | null;
647 org_id?: string | null;
648 workflow_id?: string | null;
649 },
650 userId: string,
651 userEmail: string | null | undefined,
652 db: Db,
653): Promise<ResourceAccess> {
654 if (doc.project_id) {
655 const access = await checkProjectAccess(
656 doc.project_id,
657 userId,
658 userEmail,
659 db,
660 );
661 return access.ok
662 ? resourceAccessFor(
663 access.projectRole,
664 access.orgRole,
665 !!doc.user_id && doc.user_id === userId,
666 )
667 : { ok: false };
668 }
669 if (doc.workflow_id) {
670 const access = await checkWorkflowAccess(
671 doc.workflow_id,
672 userId,
673 userEmail,
674 db,
675 );
676 return access.ok
677 ? resourceAccessFor(
678 access.projectRole,
679 access.orgRole,
680 !!doc.user_id && doc.user_id === userId,
681 )
682 : { ok: false };
683 }
684 // A document that sits in no project or workflow has nothing to be
685 // shared through: it is its uploader's alone, in Personal and in an
686 // organization's workspace alike. The organization's owners have no
687 // implicit access. Departure transfers referenced files or archives
688 // unshared files. In a team organization the uploader must still be a member.
689 const isCreator = !!doc.user_id && doc.user_id === userId;
690 if (!isCreator) {
691 return await hasOrgPrivateContentAccess(db, doc.org_id, userId, "document", doc.id)
692 ? resourceAccessFor("viewer", null, false)
693 : { ok: false };
694 }
695 const teamOrgId = await teamOrgIdOf(db, doc.org_id);
696 if (!teamOrgId) return resourceAccessFor("owner", null, true);
697 const orgRole = await getOrgRole(userId, teamOrgId, db);
698 return orgRole
699 ? resourceAccessFor("owner", orgRole, true)
700 : { ok: false };
701}
702
703/**
704 * Shared derivation for tabular reviews and assistant chats. Project children
705 * inherit the project role exactly.
706 *
707 * A standalone row in a team organization belongs to that organization and
708 * is private to its author: only current members reach it at all (its author
709 * included), its author is its Owner, and a direct grant gives a member its
710 * role. Organization owners have no implicit access. Unshared work is
711 * archived when its final owner leaves and must be recovered before use.
712 * public.standalone_org_access_role is the SQL twin.
713 *
714 * Any other standalone row is personal: its creator, and whoever it is
715 * shared with by email.
716 */
717async function ensureSharedRowAccess(
718 kind: ContentGrantKind,
719 row: {
720 id: string;
721 user_id: string | null;
722 project_id: string | null;
723 org_id?: string | null;
724 },
725 userId: string,
726 userEmail: string | null | undefined,
727 db: Db,
728): Promise<ResourceAccess> {
729 if (row.project_id) {
730 const access = await checkProjectAccess(
731 row.project_id,
732 userId,
733 userEmail,
734 db,
735 );
736 return access.ok
737 ? resourceAccessFor(
738 access.projectRole,
739 access.orgRole,
740 !!row.user_id && row.user_id === userId,
741 )
742 : { ok: false };
743 }
744 const isCreator = !!row.user_id && row.user_id === userId;
745 const orgId = await teamOrgIdOf(db, row.org_id);
746 if (orgId) {
747 const orgRole = await getOrgRole(userId, orgId, db);
748 if (!orgRole) return { ok: false };
749 if (isCreator) return resourceAccessFor("owner", orgRole, true);
750 const granted = await getContentGrantRole(
751 db,
752 kind,
753 row.id,
754 userEmail,
755 );
756 const privateAccess = !granted && isOrgAdmin(orgRole)
757 && await hasOrgPrivateContentAccess(db, orgId, userId, kind, row.id);
758 return granted || privateAccess
759 ? resourceAccessFor(granted || "viewer", orgRole, false)
760 : { ok: false };
761 }
762 if (isCreator) return resourceAccessFor("owner", null, true);
763 const role = await getContentGrantRole(
764 db,
765 kind,
766 row.id,
767 userEmail,
768 );
769 return role ? resourceAccessFor(role, null, false) : { ok: false };
770}
771
772/**
773 * Same shape as `ensureDocAccess`, for tabular_reviews: creator, direct
774 * grant, or inherited project access, using one exclusive scope.
775 */
776export async function ensureReviewAccess(
777 review: {
778 id: string;
779 user_id: string | null;
780 project_id: string | null;
781 org_id?: string | null;
782 },
783 userId: string,
784 userEmail: string | null | undefined,
785 db: Db,
786): Promise<ResourceAccess> {
787 return ensureSharedRowAccess("tabular_review", review, userId, userEmail, db);
788}
789
790/**
791 * Same shape as `ensureReviewAccess`, for assistant chats. A project chat
792 * inherits the project verdict; a standalone chat is its author's, shared
793 * through direct grants, in Personal or in the organization it was started
794 * in.
795 *
796 * `get_chats_overview` mirrors this predicate branch for branch — keep the
797 * two in lockstep, or a chat becomes openable by URL while staying invisible
798 * in the list.
799 */
800export async function ensureChatAccess(
801 chat: {
802 id: string;
803 user_id: string | null;
804 project_id: string | null;
805 org_id?: string | null;
806 },
807 userId: string,
808 userEmail: string | null | undefined,
809 db: Db,
810): Promise<ResourceAccess> {
811 return ensureSharedRowAccess("chat", chat, userId, userEmail, db);
812}
813
814/**
815 * Filter a list of document IDs down to those the caller is actually
816 * authorised to read — owners pass, plus any document whose `project_id`
817 * the caller has access to (own project or `shared_with` member).
818 *
819 * The tabular-review routes accept user-supplied `document_ids` from
820 * request bodies; without this filter an attacker who has any review of
821 * their own can plant arbitrary doc UUIDs and have the server fetch + run
822 * an LLM extraction over their bytes (CWE-639).
823 */
824export async function filterAccessibleDocumentIds(
825 documentIds: string[],
826 userId: string,
827 userEmail: string | null | undefined,
828 db: Db,
829): Promise<string[]> {
830 if (documentIds.length === 0) return [];
831 type DocumentAccessRow = {
832 id: string;
833 user_id: string | null;
834 project_id: string | null;
835 workflow_id?: string | null;
836 org_id?: string | null;
837 };
838 const accessibleIds: string[] = [];
839 // Cache only within this lookup, and only container visibility. Standalone
840 // documents can have independent private-access grants.
841 const containerChecks = new Map<string, Promise<boolean>>();
842 /** Reuse container visibility without sharing standalone document grants. */
843 const readable = (doc: DocumentAccessRow): Promise<boolean> => {
844 const key = doc.project_id ? `project:${doc.project_id}`
845 : doc.workflow_id ? `workflow:${doc.workflow_id}` : null;
846 if (!key) return ensureDocAccess(doc, userId, userEmail, db).then((access) => access.ok);
847 let check = containerChecks.get(key);
848 if (!check) {
849 check = ensureDocAccess(doc, userId, userEmail, db).then((access) => access.ok);
850 containerChecks.set(key, check);
851 }
852 return check;
853 };
854 // Keep UUID filters below the gateway's request/header limits, as in the
855 // add-on asset lookup. A failed batch is not an empty permissions verdict.
856 for (const batch of chunkArray([...new Set(documentIds)], 50)) {
857 const { data, error } = await db
858 .from("documents")
859 .select("id, user_id, project_id, workflow_id, org_id")
860 .in("id", batch);
861 if (error) {
862 throw new Error("Document access lookup failed", { cause: error });
863 }
864 const verdicts = await Promise.all(
865 ((data ?? []) as DocumentAccessRow[]).map(async (doc) => ({
866 id: doc.id,
867 readable: await readable(doc),
868 })),
869 );
870 accessibleIds.push(
871 ...verdicts.filter((entry) => entry.readable).map((entry) => entry.id),
872 );
873 }
874 return accessibleIds;
875}
876
877const ACCESSIBLE_PROJECTS_PAGE_SIZE = 1000;
878/** Guards a runaway loop, not a product limit. */
879const ACCESSIBLE_PROJECTS_MAX_PAGES = 200;
880
881/**
882 * A read that fails is NOT an empty read. Every query in listAccessibleProjectIds
883 * decides what the caller may see, and PostgREST answers a failed query with
884 * `data: null` plus an `error` — which `?? []` used to turn into "no rows".
885 * For the deny-override read that meant an unreadable override table (a
886 * transient DB error, a statement timeout, a revoked grant) silently widened
887 * the scope to every org project, including the walled ones; for a paged
888 * scan it meant a firm silently lost every project past the failing page.
889 * The picker (routes/projects.ts) already refuses on a denial-read error;
890 * this helper now does the same, and its two callers handle the throw: the
891 * audit query turns it into a 500 and the memory-archive job retries.
892 */
893function accessReadFailed(
894 what: string,
895 error: { message?: string | null } | null | undefined,
896): Error {
897 // The PostgREST error rides along as `cause` so a caller that logs it
898 // still sees code/details/hint, not just this sentence.
899 return new Error(
900 `[listAccessibleProjectIds] ${what} failed: ${error?.message ?? "unknown error"}`,
901 { cause: error ?? undefined },
902 );
903}
904
905async function pageProjectRows<T>(
906 fetchPage: (
907 from: number,
908 to: number,
909 ) => PromiseLike<{
910 data: T[] | null;
911 error?: { message?: string | null } | null;
912 }>,
913 readDescription = "project page read",
914): Promise<T[]> {
915 const rows: T[] = [];
916 for (let page = 0; page < ACCESSIBLE_PROJECTS_MAX_PAGES; page += 1) {
917 const from = page * ACCESSIBLE_PROJECTS_PAGE_SIZE;
918 const { data, error } = await fetchPage(
919 from,
920 from + ACCESSIBLE_PROJECTS_PAGE_SIZE - 1,
921 );
922 if (error) throw accessReadFailed(readDescription, error);
923 const batch = (data ?? []) as T[];
924 rows.push(...batch);
925 if (batch.length < ACCESSIBLE_PROJECTS_PAGE_SIZE) return rows;
926 }
927 // Partial deny results are unsafe: an omitted denial looks like access.
928 throw accessReadFailed(readDescription, {
929 message: "Pagination limit reached",
930 });
931}
932
933/**
934 * Returns the set of project IDs the user can access — projects they created,
935 * any project they hold an access grant on, and any project in an org they
936 * belong to. Used to scope chat lists and similar collection queries.
937 *
938 * Written as bounded, paged project and override reads, and
939 * deliberately not as `checkProjectAccess` per row. The previous shape issued
940 * an unordered, unpaged `.in("org_id", …)` — silently truncated by PostgREST's
941 * db-max-rows, so a large firm's audit trail simply lost the projects past the
942 * cap — and then fanned out one verdict per org project, each of which is
943 * itself two or three round trips. A firm with a few hundred matters paid
944 * ~1000 sequential queries for one chat-list request. Paging by `id` (the
945 * primary key, so the order is total and stable across pages) makes the reads
946 * complete; re-deriving the org verdict inline from the same rules
947 * checkProjectAccess applies makes them cheap.
948 */
949export async function listAccessibleProjectIds(
950 userId: string,
951 userEmail: string | null | undefined,
952 db: Db,
953): Promise<string[]> {
954 const normalizedEmail = normalizeEmail(userEmail);
955
956 // Roles decide ordinary sharing and eligibility for explicitly logged access.
957 const { data: membershipRows, error: membershipError } = await db
958 .from("org_members")
959 .select("org_id, role, organizations!inner(id)")
960 .is("organizations.deleted_at", null)
961 .eq("user_id", userId);
962 if (membershipError)
963 throw accessReadFailed("org membership read", membershipError);
964 const orgRoleByOrgId = new Map<string, string>();
965 for (const row of (membershipRows ?? []) as {
966 org_id?: string | null;
967 role?: string | null;
968 }[]) {
969 if (row.org_id) orgRoleByOrgId.set(row.org_id, row.role ?? "");
970 }
971 const orgIds = [...orgRoleByOrgId.keys()];
972
973 const { data: grants, error: grantsError } = normalizedEmail
974 ? await db
975 .from("project_access_grants")
976 .select("project_id")
977 .eq("email", normalizedEmail)
978 : { data: [] as { project_id?: string | null }[], error: null };
979 if (grantsError) throw accessReadFailed("access grant read", grantsError);
980 const grantIds = [
981 ...new Set(
982 ((grants ?? []) as { project_id?: string | null }[])
983 .map((grant) => grant.project_id)
984 .filter((id): id is string => !!id),
985 ),
986 ];
987
988 const [personalOwned, personalGranted, orgProjects, overrides] =
989 await Promise.all([
990 // Personal projects the caller created. Their ORG projects are
991 // resolved by the org branch instead, because a creator who has
992 // left the org no longer has access to them — exactly what
993 // checkProjectAccess answers.
994 pageProjectRows<{ id: string }>((from, to) =>
995 db
996 .from("projects")
997 .select("id")
998 .eq("user_id", userId)
999 .is("org_id", null)
1000 .order("id", { ascending: true })
1001 .range(from, to),
1002 ),
1003 grantIds.length
1004 ? pageProjectRows<{ id: string }>((from, to) =>
1005 db
1006 .from("projects")
1007 .select("id")
1008 .in("id", grantIds)
1009 .is("org_id", null)
1010 .order("id", { ascending: true })
1011 .range(from, to),
1012 )
1013 : Promise.resolve([] as { id: string }[]),
1014 orgIds.length
1015 ? pageProjectRows<{
1016 id: string;
1017 user_id: string | null;
1018 org_id: string;
1019 visibility: string | null;
1020 }>((from, to) =>
1021 db
1022 .from("projects")
1023 .select("id, user_id, org_id, visibility, archived_at")
1024 .in("org_id", orgIds)
1025 .is("archived_at", null)
1026 .order("id", { ascending: true })
1027 .range(from, to),
1028 )
1029 : Promise.resolve(
1030 [] as {
1031 id: string;
1032 user_id: string | null;
1033 org_id: string;
1034 visibility: string | null;
1035 }[],
1036 ),
1037 // Every override the caller holds, not only the denials: in an
1038 // organization a project is private until shared, so a grant is
1039 // what ADMITS them as often as a denial is what excludes them.
1040 // Paged like the projects — a capped response would both drop
1041 // grants and admit walled matters beyond the first 1,000 rows.
1042 orgIds.length
1043 ? pageProjectRows<{ project_id: string; role: string }>(
1044 (from, to) =>
1045 db
1046 .from("project_org_access_overrides")
1047 .select("project_id, role")
1048 .in("org_id", orgIds)
1049 .eq("user_id", userId)
1050 .order("project_id", { ascending: true })
1051 .range(from, to),
1052 "access override read",
1053 )
1054 : Promise.resolve([] as { project_id: string; role: string }[]),
1055 ]);
1056
1057 const overrideByProjectId = new Map(
1058 overrides.map((row) => [row.project_id, row.role]),
1059 );
1060 const ownerless = await loadOwnerlessOrgItemIds(
1061 db,
1062 orgIds.filter((orgId) => orgRoleByOrgId.get(orgId) === "owner"),
1063 );
1064
1065 const privateAccess = await listOrgPrivateContentAccess(
1066 db,
1067 orgIds.filter(id => ["owner", "admin"].includes(orgRoleByOrgId.get(id) ?? "")),
1068 userId,
1069 );
1070 const ids = new Set<string>();
1071 for (const project of personalOwned) ids.add(project.id);
1072 for (const project of personalGranted) ids.add(project.id);
1073 for (const project of orgProjects) {
1074 // The same verdict checkProjectAccess reaches, re-derived inline.
1075 const orgRole = orgRoleByOrgId.get(project.org_id);
1076 if (!isOrgRole(orgRole)) continue;
1077 const override = overrideByProjectId.get(project.id);
1078 const role = resolveOrgContentRole({
1079 isCreator: !!project.user_id && project.user_id === userId,
1080 orgRole,
1081 override: isOrgAccessOverrideRole(override) ? override : null,
1082 visibility: project.visibility,
1083 ownerless: ownerless.projects.has(project.id),
1084 });
1085 if (role || privateAccess.get("project")?.has(project.id)) ids.add(project.id);
1086 }
1087 return [...ids];
1088}
1089