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-only- ..
- apple-touch-icon.png
- brand-guidelines-v2.md
- brand-manifest-v2.json
- favicon-16.png
- favicon-32.png
- favicon-48.png
- favicon.ico
- icon-192.png
- icon-512.png
- maskable-192.png
- maskable-512.png
- source-brand-board.png
- source-crop-icon-fullcolor.png
- source-crop-lockup-dark.png
- source-crop-wordmark-light.png
- zloud-app-icon-1024.png
- zloud-app-icon.svg
- zloud-favicon.svg
- zloud-mark-1024.png
- zloud-mark-512.png
- zloud-mark-mono-512.png
- zloud-mark-mono.svg
- zloud-mark-reversed.svg
- zloud-mark-white-512.png
- zloud-mark-white.svg
- zloud-mark.svg
- zloud-maskable.svg
- zloud-wordmark-dark.svg
- zloud-wordmark-light.svg
- zloud-wordmark-mono.svg
app/src/lib/auth.ts
1import { allowedOrigins, cookieConfig, resolveConfig } from "./config";2import crypto from "node:crypto";3import fs from "node:fs";4import os from "node:os";5import path from "node:path";6import { cookies, headers } from "next/headers";7import { db, asSystem, enterScope } from "./db";89// Interim local access gate until Zoo IAM client credentials exist (see docs/SPEC.md §7).10// The token lives in a 0600 file outside the repo; it is never logged or served.11const TOKEN_FILE = process.env.STUDIO_ADMIN_TOKEN_FILE || path.join(os.homedir(), ".config/zoo-cloud-studio/admin-token");12const COOKIE = "zcs_session";13const TTL_MS = 12 * 3600 * 1000;1415function adminToken(): string | null {16 try { return fs.readFileSync(TOKEN_FILE, "utf8").trim() || null; } catch { return null; }17}1819const attempts: number[] = [];20export function loginAllowed(): boolean {21 const t = Date.now();22 while (attempts.length && t - attempts[0] > 60_000) attempts.shift();23 if (attempts.length >= (Number(process.env.ZCS_LOGIN_RATE) || 8)) return false;24 attempts.push(t);25 return true;26}2728export function checkToken(candidate: string): boolean {29 const real = adminToken();30 if (!real || !candidate) return false;31 const a = crypto.createHash("sha256").update(candidate).digest();32 const b = crypto.createHash("sha256").update(real).digest();33 return crypto.timingSafeEqual(a, b);34}3536export type Idp = { iss: string; sid: string | null; acr: string | null };37export const createSession = (userId = "usr_owner", idp?: Idp): Promise<void> => asSystem(() => createSessionInner(userId, idp));38async function createSessionInner(userId: string, idp?: Idp): Promise<void> {39 const id = crypto.randomBytes(32).toString("hex");40 const t = Date.now();41 await db().prepare("DELETE FROM sessions WHERE expires_at < ?").run(t);42 const m = await db().prepare("SELECT org_id FROM memberships WHERE user_id=? ORDER BY (org_id='org_owner') DESC, created_at LIMIT 1").get(userId) as { org_id: string } | undefined;43 await db().prepare("INSERT INTO sessions(id,created_at,expires_at,user_id,org_id,idp_iss,idp_sid,idp_acr) VALUES(?,?,?,?,?,?,?,?)").run(id, t, t + TTL_MS, userId, m?.org_id ?? null, idp?.iss ?? null, idp?.sid ?? null, idp?.acr ?? null);44 (await cookies()).set(COOKIE, id, { ...(await cookieConfig()), maxAge: TTL_MS / 1000 });45}4647export async function destroySession() {48 const c = await cookies();49 const id = c.get(COOKIE)?.value;50 if (id) await asSystem(() => db().prepare("DELETE FROM sessions WHERE id=?").run(id));51 c.delete(COOKIE);52}5354/** True only when the edge proxy terminated TLS (it overwrites x-zcs-proto, so clients cannot spoof it). */55export async function isSecure(): Promise<boolean> { return (await headers()).get("x-zcs-proto") === "https"; }56/** Public https origin hint for sign-in links (edge HTTPS port). */57export async function httpsBase(): Promise<string> {58 const cfg = (await resolveConfig()).PUBLIC_BASE_URL; if (cfg.source !== "derived") return cfg.value.replace(/\/$/, "");59 const host = ((await headers()).get("host") || "localhost").replace(/:\d+$/, "");60 return `https://${host}:${process.env.STUDIO_HTTPS_PORT || 8443}`;61}6263export async function isAuthed(): Promise<boolean> {64 if (!(await isSecure())) return false; // sensitive state is never available over plain HTTP65 const id = (await cookies()).get(COOKIE)?.value;66 if (!id) return false;67 const r = await asSystem(() => db().prepare("SELECT expires_at FROM sessions WHERE id=?").get(id)) as { expires_at: number } | undefined;68 return !!r && r.expires_at > Date.now();69}7071/** CSRF defence for cookie-authenticated writes: same-origin only. */72export async function sameOrigin(): Promise<boolean> {73 const h = await headers();74 const origin = h.get("origin");75 if (!origin) return false;76 try { const o = new URL(origin); return o.host === h.get("host") || (await allowedOrigins()).includes(o.origin); } catch { return false; }77}7879export async function requireWrite(): Promise<Response | null> {80 const sc = enterScope(); // see getCtx(): scope must be bound before the first await81 if (!(await isSecure())) return Response.json({ error: "HTTPS required for this operation" }, { status: 403 });82 if (!(await sameOrigin())) return Response.json({ error: "cross-origin write rejected" }, { status: 403 });83 if (!(await isAuthed())) return Response.json({ error: "authentication required" }, { status: 401 });84 const { getCtx } = await import("./tenant"); const c = await getCtx(sc);85 if (!c?.platformAdmin) return Response.json({ error: "platform administrator required" }, { status: 403 });86 return null;87}8889export const tokenConfigured = () => adminToken() !== null;90
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 1c27633 on master.
Approval requests
None pending.