Private
Public Access
1
0

Phase 2: Enforce Row-Level Security at the PostgreSQL level

- Rewrite rls.ts with withTenant()/withBypassRLS() using parameterized
  set_config() in interactive Prisma transactions (no SQL injection)
- Add FORCE ROW LEVEL SECURITY on all 15 tenant-scoped tables
- Add __bypass__ sentinel and WITH CHECK clauses to every RLS policy
- Explicitly DISABLE RLS on tenants, tenant_hostnames, sessions
- Wrap all API route and page loader queries in withTenant()
- Wrap validateSession() in withBypassRLS() (joins RLS-protected users)
- Keep existing tenantId where-clause filters as optimization layer
- Add postgresql-client to Dockerfile and auto-apply RLS via entrypoint

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Catherine Renelle
2026-02-25 22:54:26 -05:00
parent f6ddfcfc62
commit bd12160ebb
15 changed files with 625 additions and 424 deletions
+2
View File
@@ -29,7 +29,9 @@ RUN npx prisma generate
COPY --from=builder /app/build ./build COPY --from=builder /app/build ./build
COPY --from=builder /app/server.js ./server.js COPY --from=builder /app/server.js ./server.js
COPY scripts ./scripts
RUN apk add --no-cache postgresql-client
RUN apk del python3 make g++ && rm -rf /var/cache/apk/* RUN apk del python3 make g++ && rm -rf /var/cache/apk/*
RUN mkdir -p /app/uploads RUN mkdir -p /app/uploads
+7
View File
@@ -20,5 +20,12 @@ if [ $RETRY -ge $MAX_RETRIES ]; then
exit 1 exit 1
fi fi
echo "Applying RLS policies..."
if psql "$DATABASE_URL" -f ./scripts/setup-rls.sql; then
echo "RLS policies applied successfully."
else
echo "WARNING: Failed to apply RLS policies. Continuing anyway..."
fi
echo "Starting server..." echo "Starting server..."
exec node server.js exec node server.js
+210 -40
View File
@@ -1,65 +1,144 @@
-- Row-Level Security (RLS) Policies -- Row-Level Security (RLS) Policies
-- Run this after migrations to enable tenant isolation at the DB level. -- Run this after migrations to enable tenant isolation at the DB level.
-- Idempotent: safe to re-run on every deploy.
-- Helper: current tenant context (set via SET LOCAL in Prisma extension) -- Helper: current tenant context (set via set_config() in Prisma transaction)
-- Usage: SET LOCAL app.current_tenant_id = '<uuid>'; -- Usage: SELECT set_config('app.current_tenant_id', '<uuid>', true);
-- ─── Enable RLS ────────────────────────────────────────── -- ─── Tables WITHOUT RLS (cross-tenant by design) ──────
ALTER TABLE tenants DISABLE ROW LEVEL SECURITY;
ALTER TABLE tenant_hostnames DISABLE ROW LEVEL SECURITY;
ALTER TABLE sessions DISABLE ROW LEVEL SECURITY;
-- ─── Enable + Force RLS ────────────────────────────────
ALTER TABLE users ENABLE ROW LEVEL SECURITY; ALTER TABLE users ENABLE ROW LEVEL SECURITY;
ALTER TABLE boards ENABLE ROW LEVEL SECURITY; ALTER TABLE users FORCE ROW LEVEL SECURITY;
ALTER TABLE board_members ENABLE ROW LEVEL SECURITY;
ALTER TABLE columns ENABLE ROW LEVEL SECURITY;
ALTER TABLE cards ENABLE ROW LEVEL SECURITY;
ALTER TABLE card_assignees ENABLE ROW LEVEL SECURITY;
ALTER TABLE tags ENABLE ROW LEVEL SECURITY;
ALTER TABLE card_labels ENABLE ROW LEVEL SECURITY;
ALTER TABLE categories ENABLE ROW LEVEL SECURITY;
ALTER TABLE checklists ENABLE ROW LEVEL SECURITY;
ALTER TABLE checklist_items ENABLE ROW LEVEL SECURITY;
ALTER TABLE comments ENABLE ROW LEVEL SECURITY;
ALTER TABLE attachments ENABLE ROW LEVEL SECURITY;
ALTER TABLE activities ENABLE ROW LEVEL SECURITY;
ALTER TABLE notifications ENABLE ROW LEVEL SECURITY;
ALTER TABLE board_templates ENABLE ROW LEVEL SECURITY;
-- ─── Tenant-scoped tables (direct tenant_id) ──────────── ALTER TABLE boards ENABLE ROW LEVEL SECURITY;
ALTER TABLE boards FORCE ROW LEVEL SECURITY;
ALTER TABLE board_members ENABLE ROW LEVEL SECURITY;
ALTER TABLE board_members FORCE ROW LEVEL SECURITY;
ALTER TABLE columns ENABLE ROW LEVEL SECURITY;
ALTER TABLE columns FORCE ROW LEVEL SECURITY;
ALTER TABLE cards ENABLE ROW LEVEL SECURITY;
ALTER TABLE cards FORCE ROW LEVEL SECURITY;
ALTER TABLE card_assignees ENABLE ROW LEVEL SECURITY;
ALTER TABLE card_assignees FORCE ROW LEVEL SECURITY;
ALTER TABLE tags ENABLE ROW LEVEL SECURITY;
ALTER TABLE tags FORCE ROW LEVEL SECURITY;
ALTER TABLE card_labels ENABLE ROW LEVEL SECURITY;
ALTER TABLE card_labels FORCE ROW LEVEL SECURITY;
ALTER TABLE categories ENABLE ROW LEVEL SECURITY;
ALTER TABLE categories FORCE ROW LEVEL SECURITY;
ALTER TABLE checklists ENABLE ROW LEVEL SECURITY;
ALTER TABLE checklists FORCE ROW LEVEL SECURITY;
ALTER TABLE checklist_items ENABLE ROW LEVEL SECURITY;
ALTER TABLE checklist_items FORCE ROW LEVEL SECURITY;
ALTER TABLE comments ENABLE ROW LEVEL SECURITY;
ALTER TABLE comments FORCE ROW LEVEL SECURITY;
ALTER TABLE attachments ENABLE ROW LEVEL SECURITY;
ALTER TABLE attachments FORCE ROW LEVEL SECURITY;
ALTER TABLE activities ENABLE ROW LEVEL SECURITY;
ALTER TABLE activities FORCE ROW LEVEL SECURITY;
ALTER TABLE notifications ENABLE ROW LEVEL SECURITY;
ALTER TABLE notifications FORCE ROW LEVEL SECURITY;
ALTER TABLE board_templates ENABLE ROW LEVEL SECURITY;
ALTER TABLE board_templates FORCE ROW LEVEL SECURITY;
-- ─── Tenant-scoped tables (direct tenant_id) ──────────
-- Users -- Users
DROP POLICY IF EXISTS users_tenant_isolation ON users; DROP POLICY IF EXISTS users_tenant_isolation ON users;
CREATE POLICY users_tenant_isolation ON users CREATE POLICY users_tenant_isolation ON users
USING (tenant_id::text = current_setting('app.current_tenant_id', true)); USING (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR tenant_id::text = current_setting('app.current_tenant_id', true)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR tenant_id::text = current_setting('app.current_tenant_id', true)
);
-- Boards -- Boards
DROP POLICY IF EXISTS boards_tenant_isolation ON boards; DROP POLICY IF EXISTS boards_tenant_isolation ON boards;
CREATE POLICY boards_tenant_isolation ON boards CREATE POLICY boards_tenant_isolation ON boards
USING (tenant_id::text = current_setting('app.current_tenant_id', true)); USING (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR tenant_id::text = current_setting('app.current_tenant_id', true)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR tenant_id::text = current_setting('app.current_tenant_id', true)
);
-- Tags -- Tags
DROP POLICY IF EXISTS tags_tenant_isolation ON tags; DROP POLICY IF EXISTS tags_tenant_isolation ON tags;
CREATE POLICY tags_tenant_isolation ON tags CREATE POLICY tags_tenant_isolation ON tags
USING (tenant_id::text = current_setting('app.current_tenant_id', true)); USING (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR tenant_id::text = current_setting('app.current_tenant_id', true)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR tenant_id::text = current_setting('app.current_tenant_id', true)
);
-- Categories -- Categories
DROP POLICY IF EXISTS categories_tenant_isolation ON categories; DROP POLICY IF EXISTS categories_tenant_isolation ON categories;
CREATE POLICY categories_tenant_isolation ON categories CREATE POLICY categories_tenant_isolation ON categories
USING (tenant_id::text = current_setting('app.current_tenant_id', true)); USING (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR tenant_id::text = current_setting('app.current_tenant_id', true)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR tenant_id::text = current_setting('app.current_tenant_id', true)
);
-- Board Templates (null tenant_id = system template, visible to all) -- Board Templates (null tenant_id = system template, visible to all)
DROP POLICY IF EXISTS board_templates_tenant_isolation ON board_templates; DROP POLICY IF EXISTS board_templates_tenant_isolation ON board_templates;
CREATE POLICY board_templates_tenant_isolation ON board_templates CREATE POLICY board_templates_tenant_isolation ON board_templates
USING ( USING (
tenant_id IS NULL current_setting('app.current_tenant_id', true) = '__bypass__'
OR tenant_id IS NULL
OR tenant_id::text = current_setting('app.current_tenant_id', true)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR tenant_id IS NULL
OR tenant_id::text = current_setting('app.current_tenant_id', true) OR tenant_id::text = current_setting('app.current_tenant_id', true)
); );
-- ─── Board-scoped tables (via join to boards) ─────────── -- ─── Board-scoped tables (via join to boards) ─────────
-- Board Members -- Board Members
DROP POLICY IF EXISTS board_members_tenant_isolation ON board_members; DROP POLICY IF EXISTS board_members_tenant_isolation ON board_members;
CREATE POLICY board_members_tenant_isolation ON board_members CREATE POLICY board_members_tenant_isolation ON board_members
USING ( USING (
board_id IN ( current_setting('app.current_tenant_id', true) = '__bypass__'
OR board_id IN (
SELECT id FROM boards
WHERE tenant_id::text = current_setting('app.current_tenant_id', true)
)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR board_id IN (
SELECT id FROM boards SELECT id FROM boards
WHERE tenant_id::text = current_setting('app.current_tenant_id', true) WHERE tenant_id::text = current_setting('app.current_tenant_id', true)
) )
@@ -69,7 +148,15 @@ CREATE POLICY board_members_tenant_isolation ON board_members
DROP POLICY IF EXISTS columns_tenant_isolation ON columns; DROP POLICY IF EXISTS columns_tenant_isolation ON columns;
CREATE POLICY columns_tenant_isolation ON columns CREATE POLICY columns_tenant_isolation ON columns
USING ( USING (
board_id IN ( current_setting('app.current_tenant_id', true) = '__bypass__'
OR board_id IN (
SELECT id FROM boards
WHERE tenant_id::text = current_setting('app.current_tenant_id', true)
)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR board_id IN (
SELECT id FROM boards SELECT id FROM boards
WHERE tenant_id::text = current_setting('app.current_tenant_id', true) WHERE tenant_id::text = current_setting('app.current_tenant_id', true)
) )
@@ -79,7 +166,15 @@ CREATE POLICY columns_tenant_isolation ON columns
DROP POLICY IF EXISTS activities_tenant_isolation ON activities; DROP POLICY IF EXISTS activities_tenant_isolation ON activities;
CREATE POLICY activities_tenant_isolation ON activities CREATE POLICY activities_tenant_isolation ON activities
USING ( USING (
board_id IN ( current_setting('app.current_tenant_id', true) = '__bypass__'
OR board_id IN (
SELECT id FROM boards
WHERE tenant_id::text = current_setting('app.current_tenant_id', true)
)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR board_id IN (
SELECT id FROM boards SELECT id FROM boards
WHERE tenant_id::text = current_setting('app.current_tenant_id', true) WHERE tenant_id::text = current_setting('app.current_tenant_id', true)
) )
@@ -91,7 +186,16 @@ CREATE POLICY activities_tenant_isolation ON activities
DROP POLICY IF EXISTS cards_tenant_isolation ON cards; DROP POLICY IF EXISTS cards_tenant_isolation ON cards;
CREATE POLICY cards_tenant_isolation ON cards CREATE POLICY cards_tenant_isolation ON cards
USING ( USING (
column_id IN ( current_setting('app.current_tenant_id', true) = '__bypass__'
OR column_id IN (
SELECT c.id FROM columns c
JOIN boards b ON c.board_id = b.id
WHERE b.tenant_id::text = current_setting('app.current_tenant_id', true)
)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR column_id IN (
SELECT c.id FROM columns c SELECT c.id FROM columns c
JOIN boards b ON c.board_id = b.id JOIN boards b ON c.board_id = b.id
WHERE b.tenant_id::text = current_setting('app.current_tenant_id', true) WHERE b.tenant_id::text = current_setting('app.current_tenant_id', true)
@@ -102,7 +206,17 @@ CREATE POLICY cards_tenant_isolation ON cards
DROP POLICY IF EXISTS card_assignees_tenant_isolation ON card_assignees; DROP POLICY IF EXISTS card_assignees_tenant_isolation ON card_assignees;
CREATE POLICY card_assignees_tenant_isolation ON card_assignees CREATE POLICY card_assignees_tenant_isolation ON card_assignees
USING ( USING (
card_id IN ( current_setting('app.current_tenant_id', true) = '__bypass__'
OR card_id IN (
SELECT ca.id FROM cards ca
JOIN columns c ON ca.column_id = c.id
JOIN boards b ON c.board_id = b.id
WHERE b.tenant_id::text = current_setting('app.current_tenant_id', true)
)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR card_id IN (
SELECT ca.id FROM cards ca SELECT ca.id FROM cards ca
JOIN columns c ON ca.column_id = c.id JOIN columns c ON ca.column_id = c.id
JOIN boards b ON c.board_id = b.id JOIN boards b ON c.board_id = b.id
@@ -114,7 +228,17 @@ CREATE POLICY card_assignees_tenant_isolation ON card_assignees
DROP POLICY IF EXISTS card_labels_tenant_isolation ON card_labels; DROP POLICY IF EXISTS card_labels_tenant_isolation ON card_labels;
CREATE POLICY card_labels_tenant_isolation ON card_labels CREATE POLICY card_labels_tenant_isolation ON card_labels
USING ( USING (
card_id IN ( current_setting('app.current_tenant_id', true) = '__bypass__'
OR card_id IN (
SELECT ca.id FROM cards ca
JOIN columns c ON ca.column_id = c.id
JOIN boards b ON c.board_id = b.id
WHERE b.tenant_id::text = current_setting('app.current_tenant_id', true)
)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR card_id IN (
SELECT ca.id FROM cards ca SELECT ca.id FROM cards ca
JOIN columns c ON ca.column_id = c.id JOIN columns c ON ca.column_id = c.id
JOIN boards b ON c.board_id = b.id JOIN boards b ON c.board_id = b.id
@@ -126,7 +250,17 @@ CREATE POLICY card_labels_tenant_isolation ON card_labels
DROP POLICY IF EXISTS checklists_tenant_isolation ON checklists; DROP POLICY IF EXISTS checklists_tenant_isolation ON checklists;
CREATE POLICY checklists_tenant_isolation ON checklists CREATE POLICY checklists_tenant_isolation ON checklists
USING ( USING (
card_id IN ( current_setting('app.current_tenant_id', true) = '__bypass__'
OR card_id IN (
SELECT ca.id FROM cards ca
JOIN columns c ON ca.column_id = c.id
JOIN boards b ON c.board_id = b.id
WHERE b.tenant_id::text = current_setting('app.current_tenant_id', true)
)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR card_id IN (
SELECT ca.id FROM cards ca SELECT ca.id FROM cards ca
JOIN columns c ON ca.column_id = c.id JOIN columns c ON ca.column_id = c.id
JOIN boards b ON c.board_id = b.id JOIN boards b ON c.board_id = b.id
@@ -138,7 +272,18 @@ CREATE POLICY checklists_tenant_isolation ON checklists
DROP POLICY IF EXISTS checklist_items_tenant_isolation ON checklist_items; DROP POLICY IF EXISTS checklist_items_tenant_isolation ON checklist_items;
CREATE POLICY checklist_items_tenant_isolation ON checklist_items CREATE POLICY checklist_items_tenant_isolation ON checklist_items
USING ( USING (
checklist_id IN ( current_setting('app.current_tenant_id', true) = '__bypass__'
OR checklist_id IN (
SELECT ch.id FROM checklists ch
JOIN cards ca ON ch.card_id = ca.id
JOIN columns c ON ca.column_id = c.id
JOIN boards b ON c.board_id = b.id
WHERE b.tenant_id::text = current_setting('app.current_tenant_id', true)
)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR checklist_id IN (
SELECT ch.id FROM checklists ch SELECT ch.id FROM checklists ch
JOIN cards ca ON ch.card_id = ca.id JOIN cards ca ON ch.card_id = ca.id
JOIN columns c ON ca.column_id = c.id JOIN columns c ON ca.column_id = c.id
@@ -151,7 +296,17 @@ CREATE POLICY checklist_items_tenant_isolation ON checklist_items
DROP POLICY IF EXISTS comments_tenant_isolation ON comments; DROP POLICY IF EXISTS comments_tenant_isolation ON comments;
CREATE POLICY comments_tenant_isolation ON comments CREATE POLICY comments_tenant_isolation ON comments
USING ( USING (
card_id IN ( current_setting('app.current_tenant_id', true) = '__bypass__'
OR card_id IN (
SELECT ca.id FROM cards ca
JOIN columns c ON ca.column_id = c.id
JOIN boards b ON c.board_id = b.id
WHERE b.tenant_id::text = current_setting('app.current_tenant_id', true)
)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR card_id IN (
SELECT ca.id FROM cards ca SELECT ca.id FROM cards ca
JOIN columns c ON ca.column_id = c.id JOIN columns c ON ca.column_id = c.id
JOIN boards b ON c.board_id = b.id JOIN boards b ON c.board_id = b.id
@@ -163,7 +318,17 @@ CREATE POLICY comments_tenant_isolation ON comments
DROP POLICY IF EXISTS attachments_tenant_isolation ON attachments; DROP POLICY IF EXISTS attachments_tenant_isolation ON attachments;
CREATE POLICY attachments_tenant_isolation ON attachments CREATE POLICY attachments_tenant_isolation ON attachments
USING ( USING (
card_id IN ( current_setting('app.current_tenant_id', true) = '__bypass__'
OR card_id IN (
SELECT ca.id FROM cards ca
JOIN columns c ON ca.column_id = c.id
JOIN boards b ON c.board_id = b.id
WHERE b.tenant_id::text = current_setting('app.current_tenant_id', true)
)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR card_id IN (
SELECT ca.id FROM cards ca SELECT ca.id FROM cards ca
JOIN columns c ON ca.column_id = c.id JOIN columns c ON ca.column_id = c.id
JOIN boards b ON c.board_id = b.id JOIN boards b ON c.board_id = b.id
@@ -171,17 +336,22 @@ CREATE POLICY attachments_tenant_isolation ON attachments
) )
); );
-- ─── User-scoped tables ───────────────────────────────── -- ─── User-scoped tables ───────────────────────────────
-- Notifications -- Notifications
DROP POLICY IF EXISTS notifications_tenant_isolation ON notifications; DROP POLICY IF EXISTS notifications_tenant_isolation ON notifications;
CREATE POLICY notifications_tenant_isolation ON notifications CREATE POLICY notifications_tenant_isolation ON notifications
USING ( USING (
user_id IN ( current_setting('app.current_tenant_id', true) = '__bypass__'
OR user_id IN (
SELECT id FROM users
WHERE tenant_id::text = current_setting('app.current_tenant_id', true)
)
)
WITH CHECK (
current_setting('app.current_tenant_id', true) = '__bypass__'
OR user_id IN (
SELECT id FROM users SELECT id FROM users
WHERE tenant_id::text = current_setting('app.current_tenant_id', true) WHERE tenant_id::text = current_setting('app.current_tenant_id', true)
) )
); );
-- Sessions (no RLS - cross-tenant by design for session validation)
-- Sessions are validated in application code with tenant check
+7 -2
View File
@@ -1,5 +1,6 @@
import bcrypt from 'bcrypt'; import bcrypt from 'bcrypt';
import { prisma } from './db.js'; import { prisma } from './db.js';
import { withBypassRLS } from './rls.js';
const SALT_ROUNDS = 12; const SALT_ROUNDS = 12;
const SESSION_DURATION_MS = 30 * 24 * 60 * 60 * 1000; // 30 days const SESSION_DURATION_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
@@ -21,7 +22,10 @@ export async function createSession(userId: string): Promise<{ id: string; expir
} }
export async function validateSession(sessionId: string) { export async function validateSession(sessionId: string) {
const session = await prisma.session.findUnique({ // Uses withBypassRLS because this joins to the users table (RLS-protected)
// and runs before tenant context is established in hooks.server.ts.
return withBypassRLS(async (tx) => {
const session = await tx.session.findUnique({
where: { id: sessionId }, where: { id: sessionId },
include: { include: {
user: { user: {
@@ -40,11 +44,12 @@ export async function validateSession(sessionId: string) {
if (!session) return null; if (!session) return null;
if (session.expiresAt < new Date()) { if (session.expiresAt < new Date()) {
await prisma.session.delete({ where: { id: sessionId } }); await tx.session.delete({ where: { id: sessionId } });
return null; return null;
} }
return session; return session;
});
} }
export async function deleteSession(sessionId: string) { export async function deleteSession(sessionId: string) {
+25 -45
View File
@@ -1,56 +1,36 @@
import { PrismaClient } from '@prisma/client'; import type { Prisma } from '@prisma/client';
import { prisma } from './db.js';
type TxClient = Prisma.TransactionClient;
/** /**
* Prisma client extension for Row-Level Security. * Executes a callback within an interactive Prisma transaction
* with the RLS tenant context set to the given tenantId.
* *
* Usage: * All queries inside the callback are scoped to that tenant
* const db = forTenant(tenantId); * by PostgreSQL RLS policies.
* const boards = await db.board.findMany(); // automatically filtered
*
* const db = bypassRLS();
* const allBoards = await db.board.findMany(); // no RLS
*/ */
export async function withTenant<T>(
const basePrisma = new PrismaClient(); tenantId: string,
callback: (tx: TxClient) => Promise<T>
/** ): Promise<T> {
* Returns a Prisma client that sets the tenant context for RLS policies. return prisma.$transaction(async (tx) => {
* All queries through this client will be filtered to the specified tenant. await tx.$executeRaw`SELECT set_config('app.current_tenant_id', ${tenantId}, true)`;
*/ return callback(tx);
export function forTenant(tenantId: string): PrismaClient {
return basePrisma.$extends({
query: {
$allOperations({ args, query }) {
return basePrisma.$transaction(async (tx) => {
await tx.$executeRawUnsafe(
`SET LOCAL app.current_tenant_id = '${tenantId}'`
);
return query(args);
}); });
}
}
}) as unknown as PrismaClient;
} }
/** /**
* Returns a Prisma client that bypasses RLS. * Executes a callback that bypasses RLS.
* Use for Site Admin operations that need cross-tenant access. * Uses the '__bypass__' sentinel recognized by RLS policies.
*
* Use for cross-tenant operations like session validation.
*/ */
export function bypassRLS(): PrismaClient { export async function withBypassRLS<T>(
return basePrisma.$extends({ callback: (tx: TxClient) => Promise<T>
query: { ): Promise<T> {
$allOperations({ args, query }) { return prisma.$transaction(async (tx) => {
return basePrisma.$transaction(async (tx) => { await tx.$executeRaw`SELECT set_config('app.current_tenant_id', ${'__bypass__'}, true)`;
await tx.$executeRawUnsafe( return callback(tx);
`SET LOCAL app.current_tenant_id = ''`
);
// With RLS, setting an empty tenant_id effectively shows nothing.
// For bypass, we need to use a superuser or disable RLS.
// In practice, the app Prisma client (db.ts) doesn't enable RLS
// on the connection, so this is used when RLS is fully enabled.
return query(args);
}); });
}
}
}) as unknown as PrismaClient;
} }
+6 -2
View File
@@ -1,8 +1,8 @@
import { json, error } from '@sveltejs/kit'; import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types.js'; import type { RequestHandler } from './$types.js';
import { prisma } from '$lib/server/db.js';
import { verifyPassword, createSession, sessionCookieName, sessionCookieOptions } from '$lib/server/auth.js'; import { verifyPassword, createSession, sessionCookieName, sessionCookieOptions } from '$lib/server/auth.js';
import { loginSchema } from '$lib/server/validation.js'; import { loginSchema } from '$lib/server/validation.js';
import { withTenant } from '$lib/server/rls.js';
export const POST: RequestHandler = async ({ request, locals, cookies }) => { export const POST: RequestHandler = async ({ request, locals, cookies }) => {
const tenant = locals.tenant; const tenant = locals.tenant;
@@ -16,13 +16,17 @@ export const POST: RequestHandler = async ({ request, locals, cookies }) => {
const { email, password } = result.data; const { email, password } = result.data;
const user = await prisma.user.findUnique({ const user = await withTenant(tenant.id, async (tx) => {
return tx.user.findUnique({
where: { tenantId_email: { tenantId: tenant.id, email } } where: { tenantId_email: { tenantId: tenant.id, email } }
}); });
});
if (!user) { if (!user) {
return json({ error: 'Invalid email or password' }, { status: 401 }); return json({ error: 'Invalid email or password' }, { status: 401 });
} }
// Verify password outside transaction
const valid = await verifyPassword(password, user.passwordHash); const valid = await verifyPassword(password, user.passwordHash);
if (!valid) { if (!valid) {
return json({ error: 'Invalid email or password' }, { status: 401 }); return json({ error: 'Invalid email or password' }, { status: 401 });
+13 -5
View File
@@ -1,8 +1,8 @@
import { json, error } from '@sveltejs/kit'; import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types.js'; import type { RequestHandler } from './$types.js';
import { prisma } from '$lib/server/db.js';
import { hashPassword, createSession, sessionCookieName, sessionCookieOptions } from '$lib/server/auth.js'; import { hashPassword, createSession, sessionCookieName, sessionCookieOptions } from '$lib/server/auth.js';
import { registerSchema } from '$lib/server/validation.js'; import { registerSchema } from '$lib/server/validation.js';
import { withTenant } from '$lib/server/rls.js';
export const POST: RequestHandler = async ({ request, locals, cookies }) => { export const POST: RequestHandler = async ({ request, locals, cookies }) => {
const tenant = locals.tenant; const tenant = locals.tenant;
@@ -16,16 +16,19 @@ export const POST: RequestHandler = async ({ request, locals, cookies }) => {
const { email, name, password } = result.data; const { email, name, password } = result.data;
// Hash password outside transaction to avoid holding DB connection during bcrypt
const passwordHash = await hashPassword(password);
const user = await withTenant(tenant.id, async (tx) => {
// Check if user already exists in this tenant // Check if user already exists in this tenant
const existing = await prisma.user.findUnique({ const existing = await tx.user.findUnique({
where: { tenantId_email: { tenantId: tenant.id, email } } where: { tenantId_email: { tenantId: tenant.id, email } }
}); });
if (existing) { if (existing) {
return json({ error: 'An account with this email already exists' }, { status: 409 }); return null;
} }
const passwordHash = await hashPassword(password); return tx.user.create({
const user = await prisma.user.create({
data: { data: {
tenantId: tenant.id, tenantId: tenant.id,
email, email,
@@ -33,6 +36,11 @@ export const POST: RequestHandler = async ({ request, locals, cookies }) => {
passwordHash passwordHash
} }
}); });
});
if (!user) {
return json({ error: 'An account with this email already exists' }, { status: 409 });
}
const session = await createSession(user.id); const session = await createSession(user.id);
cookies.set(sessionCookieName(), session.id, sessionCookieOptions(session.expiresAt)); cookies.set(sessionCookieName(), session.id, sessionCookieOptions(session.expiresAt));
+8 -5
View File
@@ -1,13 +1,14 @@
import { json, error } from '@sveltejs/kit'; import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types.js'; import type { RequestHandler } from './$types.js';
import { prisma } from '$lib/server/db.js';
import { boardSchema } from '$lib/server/validation.js'; import { boardSchema } from '$lib/server/validation.js';
import { withTenant } from '$lib/server/rls.js';
// List boards for current tenant // List boards for current tenant
export const GET: RequestHandler = async ({ locals }) => { export const GET: RequestHandler = async ({ locals }) => {
const tenant = locals.tenant; const tenant = locals.tenant;
if (!tenant) throw error(400, 'Unknown tenant'); if (!tenant) throw error(400, 'Unknown tenant');
const boards = await withTenant(tenant.id, async (tx) => {
const where: Record<string, unknown> = { tenantId: tenant.id, archived: false }; const where: Record<string, unknown> = { tenantId: tenant.id, archived: false };
// If not logged in, only show public boards // If not logged in, only show public boards
@@ -19,10 +20,9 @@ export const GET: RequestHandler = async ({ locals }) => {
{ visibility: 'PUBLIC' }, { visibility: 'PUBLIC' },
{ members: { some: { userId: locals.user.id } } } { members: { some: { userId: locals.user.id } } }
]; ];
delete where.visibility;
} }
const boards = await prisma.board.findMany({ return tx.board.findMany({
where, where,
include: { include: {
members: { members: {
@@ -32,6 +32,7 @@ export const GET: RequestHandler = async ({ locals }) => {
}, },
orderBy: { updatedAt: 'desc' } orderBy: { updatedAt: 'desc' }
}); });
});
return json({ boards }); return json({ boards });
}; };
@@ -50,7 +51,8 @@ export const POST: RequestHandler = async ({ request, locals }) => {
const { title, description, visibility } = result.data; const { title, description, visibility } = result.data;
const board = await prisma.board.create({ const board = await withTenant(tenant.id, async (tx) => {
return tx.board.create({
data: { data: {
tenantId: tenant.id, tenantId: tenant.id,
title, title,
@@ -58,7 +60,7 @@ export const POST: RequestHandler = async ({ request, locals }) => {
visibility, visibility,
members: { members: {
create: { create: {
userId: locals.user.id, userId: locals.user!.id,
role: 'OWNER' role: 'OWNER'
} }
} }
@@ -69,6 +71,7 @@ export const POST: RequestHandler = async ({ request, locals }) => {
} }
} }
}); });
});
return json({ board }, { status: 201 }); return json({ board }, { status: 201 });
}; };
+20 -14
View File
@@ -1,14 +1,15 @@
import { json, error } from '@sveltejs/kit'; import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types.js'; import type { RequestHandler } from './$types.js';
import { prisma } from '$lib/server/db.js';
import { boardSchema } from '$lib/server/validation.js'; import { boardSchema } from '$lib/server/validation.js';
import { withTenant } from '$lib/server/rls.js';
// Get single board with all columns and cards // Get single board with all columns and cards
export const GET: RequestHandler = async ({ params, locals }) => { export const GET: RequestHandler = async ({ params, locals }) => {
const tenant = locals.tenant; const tenant = locals.tenant;
if (!tenant) throw error(400, 'Unknown tenant'); if (!tenant) throw error(400, 'Unknown tenant');
const board = await prisma.board.findFirst({ const board = await withTenant(tenant.id, async (tx) => {
return tx.board.findFirst({
where: { id: params.boardId, tenantId: tenant.id }, where: { id: params.boardId, tenantId: tenant.id },
include: { include: {
columns: { columns: {
@@ -32,6 +33,7 @@ export const GET: RequestHandler = async ({ params, locals }) => {
} }
} }
}); });
});
if (!board) throw error(404, 'Board not found'); if (!board) throw error(404, 'Board not found');
@@ -53,7 +55,14 @@ export const PATCH: RequestHandler = async ({ params, request, locals }) => {
if (!tenant) throw error(400, 'Unknown tenant'); if (!tenant) throw error(400, 'Unknown tenant');
if (!locals.user) throw error(401, 'Not authenticated'); if (!locals.user) throw error(401, 'Not authenticated');
const board = await prisma.board.findFirst({ const body = await request.json();
const result = boardSchema.partial().safeParse(body);
if (!result.success) {
return json({ error: result.error.issues[0].message }, { status: 400 });
}
const updated = await withTenant(tenant.id, async (tx) => {
const board = await tx.board.findFirst({
where: { id: params.boardId, tenantId: tenant.id }, where: { id: params.boardId, tenantId: tenant.id },
include: { members: true } include: { members: true }
}); });
@@ -61,20 +70,15 @@ export const PATCH: RequestHandler = async ({ params, request, locals }) => {
const member = board.members.find((m) => m.userId === locals.user!.id); const member = board.members.find((m) => m.userId === locals.user!.id);
const isAdmin = const isAdmin =
locals.user.globalRole === 'SITE_ADMIN' || locals.user.tenantRole === 'ADMIN'; locals.user!.globalRole === 'SITE_ADMIN' || locals.user!.tenantRole === 'ADMIN';
if (!member && !isAdmin) throw error(403, 'Access denied'); if (!member && !isAdmin) throw error(403, 'Access denied');
if (member && member.role === 'VIEWER') throw error(403, 'Viewers cannot edit boards'); if (member && member.role === 'VIEWER') throw error(403, 'Viewers cannot edit boards');
const body = await request.json(); return tx.board.update({
const result = boardSchema.partial().safeParse(body);
if (!result.success) {
return json({ error: result.error.issues[0].message }, { status: 400 });
}
const updated = await prisma.board.update({
where: { id: params.boardId }, where: { id: params.boardId },
data: result.data data: result.data
}); });
});
return json({ board: updated }); return json({ board: updated });
}; };
@@ -85,7 +89,8 @@ export const DELETE: RequestHandler = async ({ params, locals }) => {
if (!tenant) throw error(400, 'Unknown tenant'); if (!tenant) throw error(400, 'Unknown tenant');
if (!locals.user) throw error(401, 'Not authenticated'); if (!locals.user) throw error(401, 'Not authenticated');
const board = await prisma.board.findFirst({ await withTenant(tenant.id, async (tx) => {
const board = await tx.board.findFirst({
where: { id: params.boardId, tenantId: tenant.id }, where: { id: params.boardId, tenantId: tenant.id },
include: { members: true } include: { members: true }
}); });
@@ -93,10 +98,11 @@ export const DELETE: RequestHandler = async ({ params, locals }) => {
const member = board.members.find((m) => m.userId === locals.user!.id); const member = board.members.find((m) => m.userId === locals.user!.id);
const isAdmin = const isAdmin =
locals.user.globalRole === 'SITE_ADMIN' || locals.user.tenantRole === 'ADMIN'; locals.user!.globalRole === 'SITE_ADMIN' || locals.user!.tenantRole === 'ADMIN';
if (member?.role !== 'OWNER' && !isAdmin) throw error(403, 'Only owners can delete boards'); if (member?.role !== 'OWNER' && !isAdmin) throw error(403, 'Only owners can delete boards');
await prisma.board.delete({ where: { id: params.boardId } }); await tx.board.delete({ where: { id: params.boardId } });
});
return json({ ok: true }); return json({ ok: true });
}; };
@@ -1,8 +1,8 @@
import { json, error } from '@sveltejs/kit'; import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types.js'; import type { RequestHandler } from './$types.js';
import { prisma } from '$lib/server/db.js';
import { columnSchema } from '$lib/server/validation.js'; import { columnSchema } from '$lib/server/validation.js';
import { generatePosition } from '$lib/utils/fractional-index.js'; import { generatePosition } from '$lib/utils/fractional-index.js';
import { withTenant } from '$lib/server/rls.js';
// Create column // Create column
export const POST: RequestHandler = async ({ params, request, locals }) => { export const POST: RequestHandler = async ({ params, request, locals }) => {
@@ -10,32 +10,33 @@ export const POST: RequestHandler = async ({ params, request, locals }) => {
if (!tenant) throw error(400, 'Unknown tenant'); if (!tenant) throw error(400, 'Unknown tenant');
if (!locals.user) throw error(401, 'Not authenticated'); if (!locals.user) throw error(401, 'Not authenticated');
const board = await prisma.board.findFirst({
where: { id: params.boardId, tenantId: tenant.id },
include: { members: true }
});
if (!board) throw error(404, 'Board not found');
const member = board.members.find((m) => m.userId === locals.user!.id);
const isAdmin = locals.user.globalRole === 'SITE_ADMIN' || locals.user.tenantRole === 'ADMIN';
if (!member && !isAdmin) throw error(403, 'Access denied');
if (member && member.role === 'VIEWER') throw error(403, 'Viewers cannot add columns');
const body = await request.json(); const body = await request.json();
const result = columnSchema.safeParse(body); const result = columnSchema.safeParse(body);
if (!result.success) { if (!result.success) {
return json({ error: result.error.issues[0].message }, { status: 400 }); return json({ error: result.error.issues[0].message }, { status: 400 });
} }
const column = await withTenant(tenant.id, async (tx) => {
const board = await tx.board.findFirst({
where: { id: params.boardId, tenantId: tenant.id },
include: { members: true }
});
if (!board) throw error(404, 'Board not found');
const member = board.members.find((m) => m.userId === locals.user!.id);
const isAdmin = locals.user!.globalRole === 'SITE_ADMIN' || locals.user!.tenantRole === 'ADMIN';
if (!member && !isAdmin) throw error(403, 'Access denied');
if (member && member.role === 'VIEWER') throw error(403, 'Viewers cannot add columns');
// Get the last column position // Get the last column position
const lastColumn = await prisma.column.findFirst({ const lastColumn = await tx.column.findFirst({
where: { boardId: params.boardId }, where: { boardId: params.boardId },
orderBy: { position: 'desc' } orderBy: { position: 'desc' }
}); });
const position = generatePosition(lastColumn?.position, null); const position = generatePosition(lastColumn?.position, null);
const column = await prisma.column.create({ return tx.column.create({
data: { data: {
boardId: params.boardId, boardId: params.boardId,
title: result.data.title, title: result.data.title,
@@ -45,6 +46,7 @@ export const POST: RequestHandler = async ({ params, request, locals }) => {
cards: true cards: true
} }
}); });
});
return json({ column }, { status: 201 }); return json({ column }, { status: 201 });
}; };
@@ -1,7 +1,7 @@
import { json, error } from '@sveltejs/kit'; import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types.js'; import type { RequestHandler } from './$types.js';
import { prisma } from '$lib/server/db.js';
import { columnSchema, moveColumnSchema } from '$lib/server/validation.js'; import { columnSchema, moveColumnSchema } from '$lib/server/validation.js';
import { withTenant } from '$lib/server/rls.js';
// Update column title // Update column title
export const PATCH: RequestHandler = async ({ params, request, locals }) => { export const PATCH: RequestHandler = async ({ params, request, locals }) => {
@@ -9,41 +9,42 @@ export const PATCH: RequestHandler = async ({ params, request, locals }) => {
if (!tenant) throw error(400, 'Unknown tenant'); if (!tenant) throw error(400, 'Unknown tenant');
if (!locals.user) throw error(401, 'Not authenticated'); if (!locals.user) throw error(401, 'Not authenticated');
const column = await prisma.column.findFirst({ const body = await request.json();
const updated = await withTenant(tenant.id, async (tx) => {
const column = await tx.column.findFirst({
where: { id: params.columnId, board: { id: params.boardId, tenantId: tenant.id } }, where: { id: params.columnId, board: { id: params.boardId, tenantId: tenant.id } },
include: { board: { include: { members: true } } } include: { board: { include: { members: true } } }
}); });
if (!column) throw error(404, 'Column not found'); if (!column) throw error(404, 'Column not found');
const member = column.board.members.find((m) => m.userId === locals.user!.id); const member = column.board.members.find((m) => m.userId === locals.user!.id);
const isAdmin = locals.user.globalRole === 'SITE_ADMIN' || locals.user.tenantRole === 'ADMIN'; const isAdmin = locals.user!.globalRole === 'SITE_ADMIN' || locals.user!.tenantRole === 'ADMIN';
if (!member && !isAdmin) throw error(403, 'Access denied'); if (!member && !isAdmin) throw error(403, 'Access denied');
if (member && member.role === 'VIEWER') throw error(403, 'Viewers cannot edit columns'); if (member && member.role === 'VIEWER') throw error(403, 'Viewers cannot edit columns');
const body = await request.json();
// Allow both title update and position update // Allow both title update and position update
if (body.position !== undefined) { if (body.position !== undefined) {
const result = moveColumnSchema.safeParse(body); const result = moveColumnSchema.safeParse(body);
if (!result.success) { if (!result.success) {
return json({ error: result.error.issues[0].message }, { status: 400 }); throw error(400, result.error.issues[0].message);
} }
const updated = await prisma.column.update({ return tx.column.update({
where: { id: params.columnId }, where: { id: params.columnId },
data: { position: result.data.position } data: { position: result.data.position }
}); });
return json({ column: updated });
} }
const result = columnSchema.safeParse(body); const result = columnSchema.safeParse(body);
if (!result.success) { if (!result.success) {
return json({ error: result.error.issues[0].message }, { status: 400 }); throw error(400, result.error.issues[0].message);
} }
const updated = await prisma.column.update({ return tx.column.update({
where: { id: params.columnId }, where: { id: params.columnId },
data: { title: result.data.title } data: { title: result.data.title }
}); });
});
return json({ column: updated }); return json({ column: updated });
}; };
@@ -54,18 +55,20 @@ export const DELETE: RequestHandler = async ({ params, locals }) => {
if (!tenant) throw error(400, 'Unknown tenant'); if (!tenant) throw error(400, 'Unknown tenant');
if (!locals.user) throw error(401, 'Not authenticated'); if (!locals.user) throw error(401, 'Not authenticated');
const column = await prisma.column.findFirst({ await withTenant(tenant.id, async (tx) => {
const column = await tx.column.findFirst({
where: { id: params.columnId, board: { id: params.boardId, tenantId: tenant.id } }, where: { id: params.columnId, board: { id: params.boardId, tenantId: tenant.id } },
include: { board: { include: { members: true } } } include: { board: { include: { members: true } } }
}); });
if (!column) throw error(404, 'Column not found'); if (!column) throw error(404, 'Column not found');
const member = column.board.members.find((m) => m.userId === locals.user!.id); const member = column.board.members.find((m) => m.userId === locals.user!.id);
const isAdmin = locals.user.globalRole === 'SITE_ADMIN' || locals.user.tenantRole === 'ADMIN'; const isAdmin = locals.user!.globalRole === 'SITE_ADMIN' || locals.user!.tenantRole === 'ADMIN';
if (member?.role === 'VIEWER' && !isAdmin) throw error(403, 'Viewers cannot delete columns'); if (member?.role === 'VIEWER' && !isAdmin) throw error(403, 'Viewers cannot delete columns');
if (!member && !isAdmin) throw error(403, 'Access denied'); if (!member && !isAdmin) throw error(403, 'Access denied');
await prisma.column.delete({ where: { id: params.columnId } }); await tx.column.delete({ where: { id: params.columnId } });
});
return json({ ok: true }); return json({ ok: true });
}; };
@@ -1,8 +1,8 @@
import { json, error } from '@sveltejs/kit'; import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types.js'; import type { RequestHandler } from './$types.js';
import { prisma } from '$lib/server/db.js';
import { cardSchema } from '$lib/server/validation.js'; import { cardSchema } from '$lib/server/validation.js';
import { generatePosition } from '$lib/utils/fractional-index.js'; import { generatePosition } from '$lib/utils/fractional-index.js';
import { withTenant } from '$lib/server/rls.js';
// Create card in column // Create card in column
export const POST: RequestHandler = async ({ params, request, locals }) => { export const POST: RequestHandler = async ({ params, request, locals }) => {
@@ -10,32 +10,33 @@ export const POST: RequestHandler = async ({ params, request, locals }) => {
if (!tenant) throw error(400, 'Unknown tenant'); if (!tenant) throw error(400, 'Unknown tenant');
if (!locals.user) throw error(401, 'Not authenticated'); if (!locals.user) throw error(401, 'Not authenticated');
const column = await prisma.column.findFirst({
where: { id: params.columnId, board: { id: params.boardId, tenantId: tenant.id } },
include: { board: { include: { members: true } } }
});
if (!column) throw error(404, 'Column not found');
const member = column.board.members.find((m) => m.userId === locals.user!.id);
const isAdmin = locals.user.globalRole === 'SITE_ADMIN' || locals.user.tenantRole === 'ADMIN';
if (!member && !isAdmin) throw error(403, 'Access denied');
if (member && member.role === 'VIEWER') throw error(403, 'Viewers cannot add cards');
const body = await request.json(); const body = await request.json();
const result = cardSchema.safeParse(body); const result = cardSchema.safeParse(body);
if (!result.success) { if (!result.success) {
return json({ error: result.error.issues[0].message }, { status: 400 }); return json({ error: result.error.issues[0].message }, { status: 400 });
} }
const card = await withTenant(tenant.id, async (tx) => {
const column = await tx.column.findFirst({
where: { id: params.columnId, board: { id: params.boardId, tenantId: tenant.id } },
include: { board: { include: { members: true } } }
});
if (!column) throw error(404, 'Column not found');
const member = column.board.members.find((m) => m.userId === locals.user!.id);
const isAdmin = locals.user!.globalRole === 'SITE_ADMIN' || locals.user!.tenantRole === 'ADMIN';
if (!member && !isAdmin) throw error(403, 'Access denied');
if (member && member.role === 'VIEWER') throw error(403, 'Viewers cannot add cards');
// Get the last card position in this column // Get the last card position in this column
const lastCard = await prisma.card.findFirst({ const lastCard = await tx.card.findFirst({
where: { columnId: params.columnId }, where: { columnId: params.columnId },
orderBy: { position: 'desc' } orderBy: { position: 'desc' }
}); });
const position = generatePosition(lastCard?.position, null); const position = generatePosition(lastCard?.position, null);
const card = await prisma.card.create({ return tx.card.create({
data: { data: {
columnId: params.columnId, columnId: params.columnId,
title: result.data.title, title: result.data.title,
@@ -50,6 +51,7 @@ export const POST: RequestHandler = async ({ params, request, locals }) => {
_count: { select: { comments: true, checklists: true, attachments: true } } _count: { select: { comments: true, checklists: true, attachments: true } }
} }
}); });
});
return json({ card }, { status: 201 }); return json({ card }, { status: 201 });
}; };
@@ -1,14 +1,15 @@
import { json, error } from '@sveltejs/kit'; import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types.js'; import type { RequestHandler } from './$types.js';
import { prisma } from '$lib/server/db.js';
import { cardSchema, moveCardSchema } from '$lib/server/validation.js'; import { cardSchema, moveCardSchema } from '$lib/server/validation.js';
import { withTenant } from '$lib/server/rls.js';
// Get single card with full details // Get single card with full details
export const GET: RequestHandler = async ({ params, locals }) => { export const GET: RequestHandler = async ({ params, locals }) => {
const tenant = locals.tenant; const tenant = locals.tenant;
if (!tenant) throw error(400, 'Unknown tenant'); if (!tenant) throw error(400, 'Unknown tenant');
const card = await prisma.card.findFirst({ const card = await withTenant(tenant.id, async (tx) => {
return tx.card.findFirst({
where: { where: {
id: params.cardId, id: params.cardId,
column: { id: params.columnId, board: { id: params.boardId, tenantId: tenant.id } } column: { id: params.columnId, board: { id: params.boardId, tenantId: tenant.id } }
@@ -30,6 +31,7 @@ export const GET: RequestHandler = async ({ params, locals }) => {
column: { select: { id: true, title: true } } column: { select: { id: true, title: true } }
} }
}); });
});
if (!card) throw error(404, 'Card not found'); if (!card) throw error(404, 'Card not found');
@@ -42,7 +44,10 @@ export const PATCH: RequestHandler = async ({ params, request, locals }) => {
if (!tenant) throw error(400, 'Unknown tenant'); if (!tenant) throw error(400, 'Unknown tenant');
if (!locals.user) throw error(401, 'Not authenticated'); if (!locals.user) throw error(401, 'Not authenticated');
const card = await prisma.card.findFirst({ const body = await request.json();
const updated = await withTenant(tenant.id, async (tx) => {
const card = await tx.card.findFirst({
where: { where: {
id: params.cardId, id: params.cardId,
column: { board: { id: params.boardId, tenantId: tenant.id } } column: { board: { id: params.boardId, tenantId: tenant.id } }
@@ -52,19 +57,17 @@ export const PATCH: RequestHandler = async ({ params, request, locals }) => {
if (!card) throw error(404, 'Card not found'); if (!card) throw error(404, 'Card not found');
const member = card.column.board.members.find((m) => m.userId === locals.user!.id); const member = card.column.board.members.find((m) => m.userId === locals.user!.id);
const isAdmin = locals.user.globalRole === 'SITE_ADMIN' || locals.user.tenantRole === 'ADMIN'; const isAdmin = locals.user!.globalRole === 'SITE_ADMIN' || locals.user!.tenantRole === 'ADMIN';
if (!member && !isAdmin) throw error(403, 'Access denied'); if (!member && !isAdmin) throw error(403, 'Access denied');
if (member && member.role === 'VIEWER') throw error(403, 'Viewers cannot edit cards'); if (member && member.role === 'VIEWER') throw error(403, 'Viewers cannot edit cards');
const body = await request.json();
// Handle move (column change + position) // Handle move (column change + position)
if (body.columnId !== undefined || body.position !== undefined) { if (body.columnId !== undefined || body.position !== undefined) {
const data: Record<string, unknown> = {}; const data: Record<string, unknown> = {};
if (body.columnId) data.columnId = body.columnId; if (body.columnId) data.columnId = body.columnId;
if (body.position) data.position = body.position; if (body.position) data.position = body.position;
const updated = await prisma.card.update({ return tx.card.update({
where: { id: params.cardId }, where: { id: params.cardId },
data, data,
include: { include: {
@@ -75,20 +78,19 @@ export const PATCH: RequestHandler = async ({ params, request, locals }) => {
_count: { select: { comments: true, checklists: true, attachments: true } } _count: { select: { comments: true, checklists: true, attachments: true } }
} }
}); });
return json({ card: updated });
} }
// Handle content update // Handle content update
const result = cardSchema.partial().safeParse(body); const result = cardSchema.partial().safeParse(body);
if (!result.success) { if (!result.success) {
return json({ error: result.error.issues[0].message }, { status: 400 }); throw error(400, result.error.issues[0].message);
} }
const updateData: Record<string, unknown> = { ...result.data }; const updateData: Record<string, unknown> = { ...result.data };
if (body.dueDate !== undefined) updateData.dueDate = body.dueDate ? new Date(body.dueDate) : null; if (body.dueDate !== undefined) updateData.dueDate = body.dueDate ? new Date(body.dueDate) : null;
if (body.archived !== undefined) updateData.archived = body.archived; if (body.archived !== undefined) updateData.archived = body.archived;
const updated = await prisma.card.update({ return tx.card.update({
where: { id: params.cardId }, where: { id: params.cardId },
data: updateData, data: updateData,
include: { include: {
@@ -99,6 +101,7 @@ export const PATCH: RequestHandler = async ({ params, request, locals }) => {
_count: { select: { comments: true, checklists: true, attachments: true } } _count: { select: { comments: true, checklists: true, attachments: true } }
} }
}); });
});
return json({ card: updated }); return json({ card: updated });
}; };
@@ -109,7 +112,8 @@ export const DELETE: RequestHandler = async ({ params, locals }) => {
if (!tenant) throw error(400, 'Unknown tenant'); if (!tenant) throw error(400, 'Unknown tenant');
if (!locals.user) throw error(401, 'Not authenticated'); if (!locals.user) throw error(401, 'Not authenticated');
const card = await prisma.card.findFirst({ await withTenant(tenant.id, async (tx) => {
const card = await tx.card.findFirst({
where: { where: {
id: params.cardId, id: params.cardId,
column: { board: { id: params.boardId, tenantId: tenant.id } } column: { board: { id: params.boardId, tenantId: tenant.id } }
@@ -119,11 +123,12 @@ export const DELETE: RequestHandler = async ({ params, locals }) => {
if (!card) throw error(404, 'Card not found'); if (!card) throw error(404, 'Card not found');
const member = card.column.board.members.find((m) => m.userId === locals.user!.id); const member = card.column.board.members.find((m) => m.userId === locals.user!.id);
const isAdmin = locals.user.globalRole === 'SITE_ADMIN' || locals.user.tenantRole === 'ADMIN'; const isAdmin = locals.user!.globalRole === 'SITE_ADMIN' || locals.user!.tenantRole === 'ADMIN';
if (!member && !isAdmin) throw error(403, 'Access denied'); if (!member && !isAdmin) throw error(403, 'Access denied');
if (member && member.role === 'VIEWER') throw error(403, 'Viewers cannot delete cards'); if (member && member.role === 'VIEWER') throw error(403, 'Viewers cannot delete cards');
await prisma.card.delete({ where: { id: params.cardId } }); await tx.card.delete({ where: { id: params.cardId } });
});
return json({ ok: true }); return json({ ok: true });
}; };
+4 -2
View File
@@ -1,10 +1,11 @@
import type { PageServerLoad } from './$types.js'; import type { PageServerLoad } from './$types.js';
import { prisma } from '$lib/server/db.js'; import { withTenant } from '$lib/server/rls.js';
export const load: PageServerLoad = async ({ locals }) => { export const load: PageServerLoad = async ({ locals }) => {
const tenant = locals.tenant; const tenant = locals.tenant;
if (!tenant) return { boards: [] }; if (!tenant) return { boards: [] };
const boards = await withTenant(tenant.id, async (tx) => {
const where: any = { tenantId: tenant.id, archived: false }; const where: any = { tenantId: tenant.id, archived: false };
if (!locals.user) { if (!locals.user) {
@@ -16,7 +17,7 @@ export const load: PageServerLoad = async ({ locals }) => {
]; ];
} }
const boards = await prisma.board.findMany({ return tx.board.findMany({
where, where,
include: { include: {
members: { members: {
@@ -26,6 +27,7 @@ export const load: PageServerLoad = async ({ locals }) => {
}, },
orderBy: { updatedAt: 'desc' } orderBy: { updatedAt: 'desc' }
}); });
});
return { boards }; return { boards };
}; };
+4 -2
View File
@@ -1,12 +1,13 @@
import { error } from '@sveltejs/kit'; import { error } from '@sveltejs/kit';
import type { PageServerLoad } from './$types.js'; import type { PageServerLoad } from './$types.js';
import { prisma } from '$lib/server/db.js'; import { withTenant } from '$lib/server/rls.js';
export const load: PageServerLoad = async ({ params, locals }) => { export const load: PageServerLoad = async ({ params, locals }) => {
const tenant = locals.tenant; const tenant = locals.tenant;
if (!tenant) throw error(400, 'Unknown tenant'); if (!tenant) throw error(400, 'Unknown tenant');
const board = await prisma.board.findFirst({ const board = await withTenant(tenant.id, async (tx) => {
return tx.board.findFirst({
where: { id: params.boardId, tenantId: tenant.id }, where: { id: params.boardId, tenantId: tenant.id },
include: { include: {
columns: { columns: {
@@ -30,6 +31,7 @@ export const load: PageServerLoad = async ({ params, locals }) => {
} }
} }
}); });
});
if (!board) throw error(404, 'Board not found'); if (!board) throw error(404, 'Board not found');