Skip to content
  1. Home
  2. workspace
Checking…
Demo view — sanitized data only. Sign in over HTTPS to create projects and manage the workspace.

AI Engineering Workspace

Partial

Chat, 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

app/qa/owner-auth.mjs

1// Owner / local-password authentication tests. Runs a TEST instance of the app on loopback :3100 (never the public edge) against the real database
2// with throw-away fixture accounts; the platform owner's real credential is only inspected (hash present, not the plaintext), never used.
3import http from "node:http"; import https from "node:https"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import crypto from "node:crypto"; import { spawn, execFileSync } from "node:child_process"; import pg from "pg";
4import * as P from "../src/lib/pwauth-core.mjs";
5const CFG = path.join(os.homedir(), ".config/zoo-cloud-studio"); const rd = f => fs.readFileSync(path.join(CFG, f), "utf8").trim();
6const owner = new pg.Pool({ connectionString: `postgres://studio:${encodeURIComponent(rd("pg-password"))}@127.0.0.1:5432/studio`, max: 2 });
7const appPool = new pg.Pool({ connectionString: `postgres://studio_app:${encodeURIComponent(rd("pg-app-password"))}@127.0.0.1:5432/studio`, max: 1 });
8const results = []; const rec = (n, ok, d = "") => { results.push({ name: n, ok: !!ok }); console.log((ok ? "PASS " : "FAIL ") + n + (ok ? "" : " -> " + d)); };
9const q = async (t, p) => (await owner.query(t, p)).rows; const ts = Date.now(); const sleep = ms => new Promise(r => setTimeout(r, ms));
10// ---- pure primitives ----
11rec("scrypt hash verifies and never contains the plaintext", (() => { const h = P.hashPassword("Correct-Horse-9!"); return P.verifyPassword("Correct-Horse-9!", h) && !P.verifyPassword("Correct-Horse-8!", h) && !h.includes("Correct") && h.startsWith("scrypt$"); })());
12rec("two hashes of one password differ (random salt)", P.hashPassword("Same-Password-1!") !== P.hashPassword("Same-Password-1!"));
13rec("generated temporary password is 32 chars with all four classes", (() => { const p = P.generatePassword(); return p.length === 32 && /[a-z]/.test(p) && /[A-Z]/.test(p) && /\d/.test(p) && /[^A-Za-z0-9]/.test(p); })());
14rec("generated passwords are unique", new Set(Array.from({ length: 200 }, () => P.generatePassword())).size === 200);
15rec("policy: short / single-class / e-mail-name / same-as-old are refused; strong accepted", P.policyError("short1A!") && P.policyError("alllowercaseletters") && P.policyError("Belayet-Riad-2026!", { email: "belayetriadbd@gmail.com" }) === null && P.policyError("Xyzzy-Plugh-4455!", { old: "Xyzzy-Plugh-4455!" }) && P.policyError("Quartz-Lantern-7421!") === null);
16rec("lockout after 5 failures for 15 minutes", (() => { let s = { failed: 0, lockedUntil: 0 }; for (let i = 0; i < 4; i++) s = P.afterFailure(s.failed, 1000); const l = P.afterFailure(s.failed, 1000); return s.lockedUntil === 0 && l.lockedUntil === 1000 + 15 * 60 * 1000; })());
17rec("TOTP matches RFC 6238 vector and accepts ±1 step only", P.totp("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", 59000) === "287082" && P.verifyTotp("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", "287082", 59000 + 30000) && !P.verifyTotp("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", "287082", 59000 + 95000) && !P.verifyTotp("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", "12345"));
18// ---- live test instance ----
19const env = { ...process.env, PORT: "3100", PUBLIC_BASE_URL: "https://cloud.zoobd.com:8443", ZCS_LOGIN_RATE: "200" };
20const app = spawn(process.execPath, ["node_modules/next/dist/bin/next", "start", "-p", "3100", "-H", "127.0.0.1"], { env, stdio: "ignore", detached: true });
21const T = "http://127.0.0.1:3100";
22for (let i = 0; i < 60; i++) { try { if ((await fetch(T + "/api/status")).status) break; } catch { await sleep(500); } }
23const HOST = "cloud.zoobd.com"; const TRUSTED = { host: HOST + ":8443", origin: "https://" + HOST + ":8443", "x-zcs-proto": "https", "x-zcs-sni": HOST, "x-zcs-cert": "trusted" };
24// the test instance sits where the edge would; these headers are what the edge sets (it overwrites any client-supplied x-zcs-*)
25const api = (path, method, ck, extra = {}) => new Promise((res, rej) => { const r = http.request({ host: "127.0.0.1", port: 3100, path, method, headers: { ...TRUSTED, ...extra, cookie: ck, "content-length": 0 } }, m => { m.resume(); res(m.statusCode); }); r.on("error", rej); r.end(); });
26const login = (body, { hdr = TRUSTED, origin } = {}) => new Promise((res, rej) => { const d = JSON.stringify(body); const r = http.request({ host: "127.0.0.1", port: 3100, path: "/api/auth/login", method: "POST", headers: { "content-type": "application/json", "content-length": Buffer.byteLength(d), ...hdr, ...(origin ? { origin } : {}) } }, m => { let t = ""; m.on("data", c => t += c); m.on("end", () => res({ s: m.statusCode, j: (() => { try { return JSON.parse(t); } catch { return {}; } })(), cookie: (m.headers["set-cookie"] ?? []).some(c => c.startsWith("zcs_session=")), raw: (m.headers["set-cookie"] ?? []).find(c => c.startsWith("zcs_session=")) })); }); r.on("error", rej); r.end(d); });
27const email = `qa-pw-${ts}@example.test`, TEMP = P.generatePassword(), NEW = "Quartz-Lantern-7421!", uid = "usr_qapw" + ts;
28const prevDev = (await q("SELECT value FROM settings WHERE key='security.dev_customer_ops'"))[0]?.value, prevTls = (await q("SELECT value FROM settings WHERE key='security.trusted_tls'"))[0]?.value;
29const setDev = async v => { if (v === null) await q("DELETE FROM settings WHERE key='security.dev_customer_ops'"); else await q("INSERT INTO settings(key,value) VALUES('security.dev_customer_ops',$1) ON CONFLICT(key) DO UPDATE SET value=excluded.value", [v]); };
30try {
31 await q("INSERT INTO users(id,email,name,platform_admin,status,created_at) VALUES($1,$2,'QA Password',1,'active',$3)", [uid, email, new Date().toISOString()]);
32 await q("INSERT INTO user_credentials(user_id,pw_hash,must_change) VALUES($1,$2,1)", [uid, P.hashPassword(TEMP)]); await q("INSERT INTO memberships(org_id,user_id,role,created_at) VALUES('org_owner',$1,'viewer',$2)", [uid, new Date().toISOString()]);
33 const nm = P.generatePassword(); const nuid = "usr_qapn" + ts, nemail = `qa-cust-${ts}@example.test`;
34 await q("INSERT INTO users(id,email,name,platform_admin,status,created_at) VALUES($1,$2,'QA Customer',0,'active',$3)", [nuid, nemail, new Date().toISOString()]); await q("INSERT INTO user_credentials(user_id,pw_hash,must_change) VALUES($1,$2,0)", [nuid, P.hashPassword(nm)]);
35 const g1 = await login({ email, password: TEMP }, { hdr: { ...TRUSTED, "x-zcs-cert": "selfsigned" } }); rec("password sign-in REFUSED when the edge served the self-signed certificate (even with the right password)", g1.s === 403 && !g1.cookie, JSON.stringify(g1));
36 rec("refused over plain HTTP", (await login({ email, password: TEMP }, { hdr: { host: HOST + ":8443", origin: "http://" + HOST } })).s === 403);
37 rec("refused on the bare IP host (the self-signed endpoint)", (await login({ email, password: TEMP }, { hdr: { ...TRUSTED, host: "77.216.132.133:8443", origin: "https://77.216.132.133:8443", "x-zcs-sni": "" } })).s === 403);
38 rec("refused when Host differs from the TLS server name", (await login({ email, password: TEMP }, { hdr: { ...TRUSTED, host: "evil.example:8443", origin: "https://evil.example:8443" } })).s === 403);
39 rec("refused for a non-canonical host even with a trusted-looking header set", (await login({ email, password: TEMP }, { hdr: { ...TRUSTED, host: "other.zoobd.com:8443", "x-zcs-sni": "other.zoobd.com", origin: "https://other.zoobd.com:8443" } })).s === 403);
40 rec("cross-origin password sign-in is refused", (await login({ email, password: TEMP }, { origin: "https://evil.example" })).s === 403);
41 rec("a customer (non-admin) cannot password-sign-in while customer operations are off", (await login({ email: nemail, password: nm })).s === 401);
42 const wrong = await login({ email, password: "wrong-password-xx" }), unknown = await login({ email: `nobody-${ts}@example.test`, password: "wrong-password-xx" });
43 rec("wrong password and unknown e-mail get the same generic 401 (no account enumeration)", wrong.s === 401 && unknown.s === 401 && wrong.j.error === unknown.j.error && !wrong.cookie);
44 const need = await login({ email, password: TEMP }); rec("temporary password alone yields 428 'change required' and NO session", need.s === 428 && need.j.mustChange && !need.cookie, JSON.stringify(need));
45 rec("weak new password refused", (await login({ email, password: TEMP, newPassword: "short" })).s === 422);
46 rec("new password equal to the temporary one refused", (await login({ email, password: TEMP, newPassword: TEMP })).s === 422);
47 const ch = await login({ email, password: TEMP, newPassword: NEW }); rec("strong new password completes first login and opens a session", ch.s === 200 && ch.cookie, JSON.stringify(ch));
48 const row = (await q("SELECT * FROM user_credentials WHERE user_id=$1", [uid]))[0];
49 rec("after the change: must_change cleared, hash replaced, plaintext never stored", row.must_change === 0 && P.verifyPassword(NEW, row.pw_hash) && !P.verifyPassword(TEMP, row.pw_hash) && !JSON.stringify(row).includes(NEW) && !JSON.stringify(row).includes(TEMP));
50 rec("the temporary credential is revoked: it no longer signs in", (await login({ email, password: TEMP })).s === 401);
51 rec("the new password signs in normally", (await login({ email, password: NEW })).s === 200);
52 const ses = await login({ email, password: NEW }); const ck = (ses.raw ?? "").split(";")[0];
53 rec("session cookie is HttpOnly, Secure, SameSite=Lax, Path=/, expires in 12 h", /HttpOnly/i.test(ses.raw) && /;\s*Secure/i.test(ses.raw) && /SameSite=Lax/i.test(ses.raw) && /Path=\//.test(ses.raw) && /Max-Age=43200/.test(ses.raw), ses.raw);
54 rec("the session cookie authorizes the owner API", (await api("/api/cloud/overview", "GET", ck)) === 200);
55 rec("logout is required to be same-origin", (await api("/api/auth/logout", "POST", ck, { origin: "https://evil.example" })) === 403);
56 await api("/api/auth/logout", "POST", ck); rec("after logout the same cookie no longer works (server-side session destroyed)", (await api("/api/cloud/overview", "GET", ck)) === 401);
57 for (let i = 0; i < 5; i++) await login({ email, password: "bad-guess-" + i });
58 const locked = await login({ email, password: NEW }); rec("5 bad guesses lock the account: even the correct password gets 429", locked.s === 429 && !locked.cookie, JSON.stringify(locked));
59 await q("UPDATE user_credentials SET failed=0, locked_until=0 WHERE user_id=$1", [uid]);
60 const SEC = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"; await q("UPDATE user_credentials SET mfa_secret=$2, mfa_enabled=1 WHERE user_id=$1", [uid, SEC]);
61 const m1 = await login({ email, password: NEW }); rec("with MFA enabled the password alone is not enough", m1.s === 401 && m1.j.mfaRequired && !m1.cookie);
62 rec("wrong authentication code refused", (await login({ email, password: NEW, totp: "000000" })).s === 401);
63 rec("correct authentication code signs in", (await login({ email, password: NEW, totp: P.totp(SEC) })).s === 200);
64 rec("login audit trail contains the lockout and password change events", (await q("SELECT action FROM audit_log WHERE resource=$1", [uid])).map(r => r.action).join().includes("auth.login.lockout") && (await q("SELECT 1 FROM audit_log WHERE resource=$1 AND action='auth.password.changed'", [uid])).length === 1);
65 rec("credentials table is invisible to the runtime role without a system scope (row-level security)", (await appPool.query("SELECT count(*)::int n FROM user_credentials")).rows[0].n === 0);
66 // ---- the real owner account (inspected, never signed in) ----
67 const o = (await q("SELECT u.email,u.name,u.platform_admin,u.status,c.pw_hash,c.must_change FROM users u LEFT JOIN user_credentials c ON c.user_id=u.id WHERE u.id='usr_owner'"))[0];
68 rec("owner account: Belayet Riad, platform admin, active", o.name === "Belayet Riad" && o.email === "belayetriadbd@gmail.com" && o.platform_admin === 1 && o.status === "active", JSON.stringify({ n: o.name, e: o.email }));
69 rec("owner has only a scrypt hash and must change the temporary password on first login", !!o.pw_hash?.startsWith("scrypt$") && o.must_change === 1);
70 const f = path.join(CFG, "owner-temp-password"); const st = fs.statSync(f); const pw = fs.readFileSync(f, "utf8").trim();
71 rec("temporary password file is mode 0600, 32+ chars, and verifies against the stored hash", (st.mode & 0o777) === 0o600 && pw.length >= 24 && P.verifyPassword(pw, o.pw_hash));
72 const root = path.resolve(".."); const hit = fs.existsSync(path.join(root, ".git")) ? (() => { try { return execFileSync("grep", ["-rIlF", "--exclude-dir=node_modules", "--exclude-dir=.next", "--exclude-dir=.git", "--", pw, root], { encoding: "utf8" }).trim(); } catch { return ""; } })() : "";
73 let gitHit = ""; try { gitHit = execFileSync("git", ["log", "--all", "-S" + pw, "--oneline"], { cwd: root, encoding: "utf8" }).trim(); } catch {}
74 rec("the temporary password appears in NO repository file, git history, log, screenshot, report or manifest", !hit && !gitHit, hit + gitHit);
75 const get = (url, opt = {}) => new Promise(r => { https.get(url, opt, m => { m.resume(); r({ s: m.statusCode, auth: m.socket.authorized }); }).on("error", e => r({ err: e.code || e.message })); });
76 const ok = await get("https://cloud.zoobd.com:8443/login"); rec("LIVE: https://cloud.zoobd.com:8443 answers with a certificate that validates against the system CA store and hostname", ok.s === 200 && ok.auth === true, JSON.stringify(ok));
77 const pub = await new Promise(r => { const d = JSON.stringify({ email: "belayetriadbd@gmail.com", password: "x".repeat(20) }); const q2 = https.request("https://77.216.132.133:8443/api/auth/login", { method: "POST", rejectUnauthorized: false, headers: { "content-type": "application/json", "content-length": d.length, origin: "https://77.216.132.133:8443" } }, m => { m.resume(); r(m.statusCode); }); q2.on("error", () => r(0)); q2.end(d); });
78 rec("LIVE: password sign-in on the self-signed IP endpoint is refused", pub === 403, String(pub));
79} finally {
80 await q("DELETE FROM sessions WHERE user_id=$1", [uid]); await q("DELETE FROM user_credentials WHERE user_id=$1", [uid]); await q("DELETE FROM users WHERE id=$1", [uid]);
81 await q("DELETE FROM user_credentials WHERE user_id=$1", ["usr_qapn" + ts]); await q("DELETE FROM users WHERE id=$1", ["usr_qapn" + ts]); if (prevTls !== undefined) await q("INSERT INTO settings(key,value) VALUES('security.trusted_tls',$1) ON CONFLICT(key) DO UPDATE SET value=excluded.value", [prevTls]);
82 try { process.kill(-app.pid, "SIGTERM"); } catch {} await owner.end(); await appPool.end();
83}
84const f = results.filter(r => !r.ok); console.log(`\n${results.length - f.length}/${results.length} owner-auth checks passed`);
85fs.mkdirSync("../design/verification", { recursive: true }); fs.writeFileSync("../design/verification/owner-auth.json", JSON.stringify({ at: new Date().toISOString(), note: "Test instance on loopback with throw-away fixture accounts; the owner's real credential is inspected only. Password sign-in on the public site stays disabled until trusted HTTPS.", total: results.length, passed: results.length - f.length, results }, null, 1));
86process.exit(f.length ? 1 : 0);
87

Conversation

Partial
Sign 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.