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- ..
- assets
- basic-languages
- editor
- language
- nls
- abap-D-t0cyap.js
- apex-CcIm7xu6.js
- azcli-BA0tQDCg.js
- bat-C397hTD6.js
- bicep-DF5aW17k.js
- cameligo-plsz8qhj.js
- clojure-Y2auQMzK.js
- coffee-Bu45yuWE.js
- cpp-CkKPQIni.js
- csharp-CX28MZyh.js
- csp-D8uWnyxW.js
- css-CaeNmE3S.js
- css.worker-C7XcYe5x.js
- cssMode-DpEkhVlW.js
- cypher-DVThT8BS.js
- dart-CmGfCvrO.js
- dockerfile-CZqqYdch.js
- ecl-30fUercY.js
- editor-CG9c2pE-.js
- editor.js
- elixir-O3PRlgxO.js
- flow9-DqtmStfK.js
- freemarker2-DTUDMAl2.js
- fsharp-BOMdg4U1.js
- go-D_hbi-Jt.js
- graphql-CKUU4kLG.js
- handlebars-qLqoXa-4.js
- hcl-DTaboeZW.js
- html-DTxBj26n.js
- html.worker-VIR_LTyv.js
- htmlMode-DFBg6CMj.js
- index-BVflv2uG.js
- index.js
- ini--YXggpAu.js
- java-CI4ZMsH9.js
- javascript-BiL3JN6i.js
- json.worker-DzWXGkG8.js
- jsonMode-Dz4r0pwo.js
- julia-BwzEvaQw.js
- kotlin-IUYPiTV8.js
- less-C0eDYdqa.js
- lexon-iON-Kj97.js
- liquid-lXEUQRVn.js
- loader.js
- lspLanguageFeatures-IeRAvoKK.js
- lua-DtygF91M.js
- m3-CsR4AuFi.js
- markdown-C_rD0bIw.js
- mdx-Dtr248s4.js
- mips-CiYP61RB.js
- monaco.contribution-BRs4bdz5.js
- monaco.contribution-ChoOM5Gg.js
- monaco.contribution-DbKqsbmO.js
- monaco.contribution-DKFaWvum.js
- msdax-C38-sJlp.js
- mysql-CdtbpvbG.js
- nls.messages-loader.js
- objective-c-CntZFaHX.js
- pascal-r6kuqfl_.js
- pascaligo-BiXoTmXh.js
- perl-DABw_TcH.js
- pgsql-me_jFXeX.js
- php-D_kh-9LK.js
- pla-VfZjczW0.js
- postiats-BBSzz8Pk.js
- powerquery-Dt-g_2cc.js
- powershell-B-7ap1zc.js
- protobuf-BmtuEB1A.js
- pug-BRpRNeEb.js
- python-Cma5OvNe.js
- qsharp-BzsFaUU9.js
- r-f8dDdrp4.js
- razor-C8pOqqry.js
- redis-fvZQY4PI.js
- redshift-45Et0LQi.js
- restructuredtext-C7UUFKFD.js
- ruby-CZO8zYTz.js
- rust-Bfetafyc.js
- sb-3GYllVck.js
- scala-foMgrKo1.js
- scheme-CHdMtr7p.js
- scss-C1cmLt9V.js
- shell-ClXCKCEW.js
- solidity-MZ6ExpPy.js
- sophia-DWkuSsPQ.js
- sparql-AUGFYSyk.js
- sql-32GpJSV2.js
- st-CuDFIVZ_.js
- swift-t-PfMj7W.js
- systemverilog-Ch4vA8Yt.js
- tcl-D74tq1nH.js
- toggleHighContrast-CmI6H2gJ.js
- ts.worker-Dp2_QI6H.js
- tsMode-DgC3tGu_.js
- twig-C6taOxMV.js
- typescript-PjDChiYw.js
- typespec-D-PIh9Xw.js
- vb-Dyb2648j.js
- wgsl-BhLXMOR0.js
- workers-B_Zs9c54.js
- xml-BgCkTIhY.js
- yaml-D0tu26m-.js
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.