AI Engineering Workspace
PartialChat, files, terminal and preview in one place. Chat sessions run on a durable Postgres-backed queue (chat only: no tools or shell). Live models need an API key; the terminal is unavailable.
Project files
read-onlyapp/src/lib/tenant.ts
1// Tenant context, RBAC and the customer-operations gate. Every tenant-scoped API goes through tenant(); nothing reads a tenant id from the request body.2import crypto from "node:crypto";3import { cookies } from "next/headers";4import { cache } from "react";5import { db, getSetting, enterScope, asSystem, type DbScope } from "./db";6import { audit } from "./audit";7import { isSecure, sameOrigin } from "./auth";89export type Role = "viewer" | "developer" | "admin" | "owner";10export const ROLE_LEVEL: Record<Role, number> = { viewer: 1, developer: 2, admin: 3, owner: 4 };11export const ROLES = Object.keys(ROLE_LEVEL) as Role[];12/** What each role may do — shown on the Team & Access page. */13export const ROLE_DOC: Record<Role, string> = { viewer: "Read resources", developer: "Viewer + create/edit projects, files, AI sessions", admin: "Developer + instances, servers, credentials, members", owner: "Admin + organization settings and ownership" };14export type Ctx = { userId: string; email: string; name: string; platformAdmin: boolean; orgId: string; orgName: string; role: Role; orgs: { id: string; name: string; role: Role }[] };15export const hashToken = (t: string) => crypto.createHash("sha256").update(t).digest("hex");1617/** Customer (non-platform) operations stay disabled until trusted HTTPS exists (owner attests it) or the owner enables the explicit development override. */18import { orgAdmitted } from "./gates";19export async function customerOpsEnabled(): Promise<{ on: boolean; mode: "trusted-tls" | "dev-override" | "off" }> {20 if ((await getSetting("security.trusted_tls", "0")) === "1") return { on: true, mode: "trusted-tls" };21 if ((await getSetting("security.dev_customer_ops", "0")) === "1") return { on: true, mode: "dev-override" };22 return { on: false, mode: "off" };23}24export const GATE_MSG = "Customer operations are disabled until trusted HTTPS is configured (the preview certificate is self-signed).";2526const resolveCtx = cache(async (): Promise<Ctx | null> => asSystem(async () => {27 if (!(await isSecure())) return null;28 const sid = (await cookies()).get("zcs_session")?.value; if (!sid) return null;29 const s = await db().prepare("SELECT user_id,org_id,expires_at FROM sessions WHERE id=?").get(sid) as { user_id: string; org_id: string; expires_at: number } | undefined;30 if (!s || s.expires_at <= Date.now() || !s.user_id) return null;31 const u = await db().prepare("SELECT id,email,name,platform_admin,status FROM users WHERE id=?").get(s.user_id) as any; if (!u || u.status !== "active") return null;32 if (!u.platform_admin && !(await customerOpsEnabled()).on) return null;33 const orgs = await db().prepare("SELECT o.id,o.name,m.role FROM memberships m JOIN organizations o ON o.id=m.org_id WHERE m.user_id=? AND o.status='active' ORDER BY o.created_at").all(u.id) as { id: string; name: string; role: Role }[];34 const cur = orgs.find(o => o.id === s.org_id) ?? orgs[0]; if (!cur) return null;35 if (!u.platform_admin && !(await orgAdmitted(cur.id))) return null; // controlled activation: only explicitly authorized organizations36 return { userId: u.id, email: u.email, name: u.name, platformAdmin: !!u.platform_admin, orgId: cur.id, orgName: cur.name, role: cur.role, orgs: orgs.map(o => ({ id: String(o.id), name: String(o.name), role: o.role })) };37}));38/** Resolves the caller AND binds the database row-level-security scope for the rest of this request (tenant, or read-only demo when anonymous). */39export function fillScope(scope: DbScope, c: Ctx | null) { if (c) { scope.org = c.orgId; scope.mode = c.platformAdmin ? "platform" : "tenant"; } else { scope.org = "org_owner"; scope.mode = "demo"; } }40/** NOTE: the default argument runs synchronously in the CALLER's async chain. A guard that awaits anything before calling getCtx() must call enterScope() first and pass it in. */41export function getCtx(scope: DbScope = enterScope()): Promise<Ctx | null> {42 return resolveCtx().then(c => { fillScope(scope, c); return c; });43}4445type Gate = { ctx: Ctx; res?: undefined } | { ctx?: undefined; res: Response };46const deny = (status: number, error: string): Gate => ({ res: Response.json({ error }, { status }) });47/** Reads need a session; writes additionally need HTTPS + same-origin. min = lowest role allowed. */48export async function tenant(min: Role, opts: { write?: boolean } = {}): Promise<Gate> {49 const sc = enterScope(); // bound synchronously to the route handler's async chain; fail closed until identity is resolved50 if (!(await isSecure())) return deny(403, "HTTPS required for this operation");51 if (opts.write && !(await sameOrigin())) return deny(403, "cross-origin write rejected");52 const ctx = await getCtx(sc); if (!ctx) return deny(401, "authentication required");53 if (ROLE_LEVEL[ctx.role] < ROLE_LEVEL[min]) return deny(403, `requires ${min} role`);54 return { ctx };55}56/** Platform administration (super admin). Separate from any tenant role. */57export async function platform(opts: { write?: boolean } = {}): Promise<Gate> {58 const sc = enterScope();59 if (!(await isSecure())) return deny(403, "HTTPS required for this operation");60 if (opts.write && !(await sameOrigin())) return deny(403, "cross-origin write rejected");61 const ctx = await getCtx(sc); if (!ctx) return deny(401, "authentication required");62 if (!ctx.platformAdmin) return deny(403, "platform administrator required");63 return { ctx };64}65/** Audit entry attributed to the user and stamped with the tenant so tenant activity views can be filtered. */66export const auditT = (ctx: Ctx, action: string, resource = "", detail: Record<string, unknown> = {}) => audit(ctx.email, action, resource, { ...detail, org: ctx.orgId });6768// ---- resource ownership helpers: always 404 (never 403) for other tenants' resources, so existence is not leaked ----69export async function projectOf(ctx: Ctx, id: string) { return await db().prepare("SELECT * FROM projects WHERE id=? AND org_id=?").get(id, ctx.orgId) as any | undefined; }70export async function sessionOf(ctx: Ctx, id: string) { return await db().prepare("SELECT * FROM ai_sessions WHERE id=? AND org_id=?").get(id, ctx.orgId) as any | undefined; }71export async function instanceOf(ctx: Ctx, id: string) { return await db().prepare("SELECT * FROM instances WHERE id=? AND org_id=?").get(id, ctx.orgId) as any | undefined; }72export async function nodeOf(ctx: Ctx, id: string) { return await db().prepare("SELECT * FROM nodes WHERE id=? AND org_id=?").get(id, ctx.orgId) as any | undefined; }73export const notFound = () => Response.json({ error: "not found" }, { status: 404 });74
Conversation
PartialSign in to start AI sessions.
Task checklist
- Application shell deployed
- Persistent projects
- Agent runtime
- Sandboxed terminal
Execution activity
No agent sessions. Git HEAD 548ed73 on master.
Approval requests
None pending.