@ignitionai/cogitator 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -2
- package/dist/extensions/index.js +21 -3
- package/dist/src/agents.js +5 -4
- package/dist/src/auth-cli.js +113 -0
- package/dist/src/auth-http.js +203 -0
- package/dist/src/auth-state.js +289 -0
- package/dist/src/board.js +3 -0
- package/dist/src/cli.js +78 -54
- package/dist/src/config.js +7 -0
- package/dist/src/conversations.js +8 -5
- package/dist/src/db.js +9 -3
- package/dist/src/file-changes.js +1 -1
- package/dist/src/history.js +3 -3
- package/dist/src/mcp-server.js +3 -14
- package/dist/src/native-auth.js +277 -0
- package/dist/src/owner-transport.js +127 -0
- package/dist/src/pool.js +4 -4
- package/dist/src/request-authorization.js +4 -0
- package/dist/src/schemas.js +1 -0
- package/dist/src/server.js +164 -39
- package/dist/src/skills-import.js +8 -0
- package/dist/src/spawner.js +3 -1
- package/package.json +5 -2
- package/web/dist/assets/index-D3Q54zLM.js +83 -0
- package/web/dist/assets/index-Kj5NVQYi.css +1 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-2i_5DnXg.js +0 -80
- package/web/dist/assets/index-BjIxsyOx.css +0 -1
package/README.md
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
**A web control panel for [pi](https://pi.dev)** — composable agents, workspaces, GitHub-native kanban, and scheduled tasks.
|
|
8
8
|
|
|
9
|
+
[](https://github.com/IgnitionAI/cogitator)
|
|
9
10
|
[](https://www.npmjs.com/package/@ignitionai/cogitator)
|
|
10
11
|
[](https://pi.dev/packages)
|
|
11
12
|
[](#license)
|
|
@@ -14,7 +15,9 @@
|
|
|
14
15
|
|
|
15
16
|
Cogitator lets you orchestrate pi processes from your browser: compose agents from a provider, model, thinking level, skills, MCP servers, and subagents; manage project workspaces; and dispatch work through a kanban board backed by **GitHub Issues**. Track the work through modified files, diffs, and a chronological activity feed.
|
|
16
17
|
|
|
17
|
-
The application
|
|
18
|
+
The entire application interface is available in **English and French**. Use the **Language / Langue** selector in the sidebar (inside the menu on mobile). The first visit follows the browser’s supported language preference, falling back to English; your choice is remembered locally and updates open screens without losing drafts. Dates and numbers follow the selected language, without changing the scheduling timezone.
|
|
19
|
+
|
|
20
|
+
User content, agent responses, editable agent presets, code, files, and technical identifiers are preserved as authored. Cogitator’s controls and diagnostic explanations are translated; external diagnostic details remain available in their original form. The documentation is in English.
|
|
18
21
|
|
|
19
22
|
## Installation
|
|
20
23
|
|
|
@@ -30,6 +33,14 @@ Then, in pi:
|
|
|
30
33
|
|
|
31
34
|
Or run it standalone: `npx @ignitionai/cogitator` (Node.js ≥ 22.19.0).
|
|
32
35
|
|
|
36
|
+
## VPS access preparation (experimental)
|
|
37
|
+
|
|
38
|
+
The default application remains a **trusted, loopback-only local service**, not a secured remote deployment. Do not expose it through a public proxy.
|
|
39
|
+
|
|
40
|
+
The local [native single-owner login and MFA implementation](https://github.com/IgnitionAI/cogitator/blob/dev/docs/native-auth.md) has passed independent code re-reviews and bounded local verification, including Node 22/26 and real local HTTPS/browser journeys. It is independent of a particular VPS or identity provider, but authentication is **not agent execution isolation**. See the [evidence and remaining gates](https://github.com/IgnitionAI/cogitator/blob/dev/docs/native-auth-verification.md). This working-tree increment is not a new published release. Public remote operation, autonomous recovery and the remaining Durable work are not approved by it.
|
|
41
|
+
|
|
42
|
+
The earlier [identity-service inventory](https://github.com/IgnitionAI/cogitator/blob/dev/docs/vps-access-setup.md) is historical, suspended repository tooling; its administrator handoff is no longer requested. No remote deployment or recovery gate is certified by these documents.
|
|
43
|
+
|
|
33
44
|
## Features
|
|
34
45
|
|
|
35
46
|
- **Composable agents** — each preset combines a provider, model, thinking level, explicit skill set, MCP servers, scope prompt, and subagents. These become native pi flags when the process starts (`--model id:thinking`, `--no-skills --skill …`, `--append-system-prompt`).
|
|
@@ -44,7 +55,7 @@ Or run it standalone: `npx @ignitionai/cogitator` (Node.js ≥ 22.19.0).
|
|
|
44
55
|
|
|
45
56
|
## Architecture
|
|
46
57
|
|
|
47
|
-
Specifications live in [`docs/`](https://github.com/IgnitionAI/cogitator/tree/dev/docs): [domain model](https://github.com/IgnitionAI/cogitator/blob/dev/docs/architecture/domain-model.md), [blueprint](https://github.com/IgnitionAI/cogitator/blob/dev/docs/architecture/blueprint.md), [API contract](https://github.com/IgnitionAI/cogitator/blob/dev/docs/architecture/api-contract.md), and [architecture decisions](https://github.com/IgnitionAI/cogitator/tree/dev/docs/context/decisions/). They cover apply-on-spawn configuration, MCP registration through `registerMcpServer`, and the GitHub-backed board's single-writer model. The project uses strict TypeScript, Zod validation at boundaries, and
|
|
58
|
+
Specifications live in [`docs/`](https://github.com/IgnitionAI/cogitator/tree/dev/docs): [domain model](https://github.com/IgnitionAI/cogitator/blob/dev/docs/architecture/domain-model.md), [blueprint](https://github.com/IgnitionAI/cogitator/blob/dev/docs/architecture/blueprint.md), [API contract](https://github.com/IgnitionAI/cogitator/blob/dev/docs/architecture/api-contract.md), and [architecture decisions](https://github.com/IgnitionAI/cogitator/tree/dev/docs/context/decisions/). They cover apply-on-spawn configuration, MCP registration through `registerMcpServer`, and the GitHub-backed board's single-writer model. The project uses strict TypeScript, Zod validation at boundaries, and a regression test suite.
|
|
48
59
|
|
|
49
60
|
```text
|
|
50
61
|
Browser (React) → REST + SSE → Node server → pool of `pi --mode rpc` processes
|
package/dist/extensions/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { getPaths } from "../src/paths.js";
|
|
1
3
|
import { spawn } from "node:child_process";
|
|
2
4
|
import { dirname, join } from "node:path";
|
|
3
5
|
import { fileURLToPath } from "node:url";
|
|
@@ -10,7 +12,7 @@ const STARTUP_ATTEMPTS = 50;
|
|
|
10
12
|
const STARTUP_POLL_MS = 100;
|
|
11
13
|
async function isUp() {
|
|
12
14
|
try {
|
|
13
|
-
const res = await fetch(`${BASE_URL}/api/
|
|
15
|
+
const res = await fetch(`${BASE_URL}/api/status`);
|
|
14
16
|
return res.ok;
|
|
15
17
|
}
|
|
16
18
|
catch {
|
|
@@ -56,8 +58,24 @@ export default function (pi) {
|
|
|
56
58
|
await new Promise((resolve) => setTimeout(resolve, STARTUP_POLL_MS));
|
|
57
59
|
}
|
|
58
60
|
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
+
if (!(await isUp())) {
|
|
62
|
+
ctx.ui.notify("Cogitator unavailable: check the server/auth state and stop incompatible previous instances.", "error");
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
let browserUrl = BASE_URL;
|
|
66
|
+
if (process.env.COGITATOR_URL === undefined) {
|
|
67
|
+
try {
|
|
68
|
+
const config = JSON.parse(readFileSync(join(getPaths().home, "auth", "config.json"), "utf8"));
|
|
69
|
+
if (config && typeof config === "object" && "origin" in config && typeof config.origin === "string") {
|
|
70
|
+
const url = new URL(config.origin);
|
|
71
|
+
if (url.protocol === "https:" && url.origin === config.origin)
|
|
72
|
+
browserUrl = url.origin;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
catch { /* Existing local mode has no auth configuration. */ }
|
|
76
|
+
}
|
|
77
|
+
openBrowser(browserUrl);
|
|
78
|
+
ctx.ui.notify(`Cogitator — ${browserUrl}`, "info");
|
|
61
79
|
},
|
|
62
80
|
});
|
|
63
81
|
}
|
package/dist/src/agents.js
CHANGED
|
@@ -47,6 +47,7 @@ function rowToPreset(row, subs) {
|
|
|
47
47
|
created_at: row.created_at,
|
|
48
48
|
updated_at: row.updated_at,
|
|
49
49
|
is_default: row.is_default,
|
|
50
|
+
default_workspace_id: row.default_workspace_id ?? null,
|
|
50
51
|
subagents: subs.map((s) => ({
|
|
51
52
|
id: s.id,
|
|
52
53
|
name: s.name,
|
|
@@ -103,8 +104,8 @@ export function createAgent(db, input) {
|
|
|
103
104
|
const id = randomUUID();
|
|
104
105
|
const slug = uniqueSlug(db, input.name);
|
|
105
106
|
const now = new Date().toISOString();
|
|
106
|
-
db.prepare(`INSERT INTO agent_preset (id, slug, name, description, provider, model, thinking, system_prompt, skills, tools_allowlist, mcp_servers, created_at, updated_at)
|
|
107
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, slug, input.name, input.description ?? "", input.provider, input.model, input.thinking ?? null, input.system_prompt ?? "", JSON.stringify(input.skills ?? []), input.tools_allowlist ? JSON.stringify(input.tools_allowlist) : null, JSON.stringify(input.mcp_servers ?? []), now, now);
|
|
107
|
+
db.prepare(`INSERT INTO agent_preset (id, slug, name, description, provider, model, thinking, system_prompt, skills, tools_allowlist, mcp_servers, created_at, updated_at, default_workspace_id)
|
|
108
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, slug, input.name, input.description ?? "", input.provider, input.model, input.thinking ?? null, input.system_prompt ?? "", JSON.stringify(input.skills ?? []), input.tools_allowlist ? JSON.stringify(input.tools_allowlist) : null, JSON.stringify(input.mcp_servers ?? []), now, now, input.default_workspace_id ?? null);
|
|
108
109
|
replaceSubagents(db, id, input.subagents ?? []);
|
|
109
110
|
return getAgent(db, id);
|
|
110
111
|
}
|
|
@@ -113,8 +114,8 @@ export function updateAgent(db, id, input) {
|
|
|
113
114
|
if (!existing)
|
|
114
115
|
return null;
|
|
115
116
|
db.prepare(`UPDATE agent_preset SET slug = ?, name = ?, description = ?, provider = ?, model = ?, thinking = ?,
|
|
116
|
-
system_prompt = ?, skills = ?, tools_allowlist = ?, mcp_servers = ?, updated_at = ?
|
|
117
|
-
WHERE id = ?`).run(uniqueSlug(db, input.name, id), input.name, input.description ?? "", input.provider, input.model, input.thinking ?? null, input.system_prompt ?? "", JSON.stringify(input.skills ?? []), input.tools_allowlist ? JSON.stringify(input.tools_allowlist) : null, JSON.stringify(input.mcp_servers ?? []), new Date().toISOString(), id);
|
|
117
|
+
system_prompt = ?, skills = ?, tools_allowlist = ?, mcp_servers = ?, updated_at = ?, default_workspace_id = ?
|
|
118
|
+
WHERE id = ?`).run(uniqueSlug(db, input.name, id), input.name, input.description ?? "", input.provider, input.model, input.thinking ?? null, input.system_prompt ?? "", JSON.stringify(input.skills ?? []), input.tools_allowlist ? JSON.stringify(input.tools_allowlist) : null, JSON.stringify(input.mcp_servers ?? []), new Date().toISOString(), input.default_workspace_id === undefined ? existing.default_workspace_id ?? null : input.default_workspace_id, id);
|
|
118
119
|
replaceSubagents(db, id, input.subagents ?? []);
|
|
119
120
|
return getAgent(db, id);
|
|
120
121
|
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { initializeOwner, lockHome, recoverOwner, replaceSetupKey, reservePort } from "./auth-state.js";
|
|
2
|
+
import { StringDecoder } from "node:string_decoder";
|
|
3
|
+
async function ttyInput(label) {
|
|
4
|
+
return new Promise((done, reject) => {
|
|
5
|
+
const decoder = new StringDecoder("utf8");
|
|
6
|
+
let value = "";
|
|
7
|
+
let finished = false;
|
|
8
|
+
const finish = (error) => {
|
|
9
|
+
if (finished)
|
|
10
|
+
return;
|
|
11
|
+
finished = true;
|
|
12
|
+
process.stdin.off("data", onData);
|
|
13
|
+
process.stdin.off("end", onEnd);
|
|
14
|
+
process.stdin.off("error", onError);
|
|
15
|
+
process.stdin.pause();
|
|
16
|
+
process.stdout.write("\n");
|
|
17
|
+
if (error)
|
|
18
|
+
reject(error);
|
|
19
|
+
else
|
|
20
|
+
done(value);
|
|
21
|
+
};
|
|
22
|
+
const onEnd = () => finish(new Error("Terminal input ended."));
|
|
23
|
+
const onError = () => finish(new Error("Terminal input failed."));
|
|
24
|
+
const onData = (buffer) => {
|
|
25
|
+
const text = decoder.write(buffer);
|
|
26
|
+
if (text.includes("\uFFFD"))
|
|
27
|
+
return finish(new Error("Invalid UTF-8 terminal input."));
|
|
28
|
+
const lineEnd = text.search(/[\r\n]/);
|
|
29
|
+
if (lineEnd >= 0 && text.slice(lineEnd + 1).replace(/^\n/, ""))
|
|
30
|
+
return finish(new Error("Enter each value only after its prompt."));
|
|
31
|
+
for (const char of text) {
|
|
32
|
+
if (char === "\u0003" || char === "\u0004") {
|
|
33
|
+
finish(new Error("Cancelled"));
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (char === "\r" || char === "\n") {
|
|
37
|
+
finish();
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (char === "\u007f" || char === "\b")
|
|
41
|
+
value = Array.from(value).slice(0, -1).join("");
|
|
42
|
+
else if (char === "\u0015")
|
|
43
|
+
value = "";
|
|
44
|
+
else if (char >= " " && value.length < 256)
|
|
45
|
+
value += char;
|
|
46
|
+
else {
|
|
47
|
+
finish(new Error("Unsupported terminal input or value too long."));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
// Raw/no-echo is already active for the whole command, including gaps between prompts.
|
|
53
|
+
process.stdin.on("data", onData);
|
|
54
|
+
process.stdin.once("end", onEnd);
|
|
55
|
+
process.stdin.once("error", onError);
|
|
56
|
+
process.stdout.write(label);
|
|
57
|
+
process.stdin.resume();
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
export async function authCommand(home, port, args) {
|
|
61
|
+
if (process.platform === "win32")
|
|
62
|
+
throw new Error("Protected authentication currently requires a Unix server platform.");
|
|
63
|
+
const [command, ...flags] = args;
|
|
64
|
+
if (!["init", "recover", "setup-key"].includes(command ?? ""))
|
|
65
|
+
throw new Error("Usage: cogitator auth init --origin https://host --email owner@example.org | recover | setup-key");
|
|
66
|
+
const values = new Map();
|
|
67
|
+
for (let i = 0; i < flags.length; i += 2) {
|
|
68
|
+
const name = flags[i];
|
|
69
|
+
const value = flags[i + 1];
|
|
70
|
+
if (command !== "init" || !name || !["--origin", "--email"].includes(name) || !value || values.has(name))
|
|
71
|
+
throw new Error("Invalid auth arguments; passwords and setup keys are never command-line arguments.");
|
|
72
|
+
values.set(name, value);
|
|
73
|
+
}
|
|
74
|
+
if (command === "init" && (!values.get("--origin") || !values.get("--email")))
|
|
75
|
+
throw new Error("init requires --origin and --email");
|
|
76
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
77
|
+
throw new Error("Authentication administration requires an interactive local TTY.");
|
|
78
|
+
const wasRaw = process.stdin.isRaw;
|
|
79
|
+
const restoreTerminal = () => { process.stdin.pause(); process.stdin.setRawMode(wasRaw); };
|
|
80
|
+
const interrupt = () => { restoreTerminal(); process.exit(130); };
|
|
81
|
+
process.stdin.setRawMode(true);
|
|
82
|
+
process.once("SIGINT", interrupt);
|
|
83
|
+
process.once("SIGTERM", interrupt);
|
|
84
|
+
try {
|
|
85
|
+
if (await ttyInput("Stop and verify ALL previous Cogitator instances for this data home, including custom ports. Old binaries cannot observe the new guard. Type STOPPED: ") !== "STOPPED")
|
|
86
|
+
throw new Error("Offline administration cancelled.");
|
|
87
|
+
const unlock = lockHome(home);
|
|
88
|
+
let releasePort;
|
|
89
|
+
try {
|
|
90
|
+
releasePort = await reservePort(port);
|
|
91
|
+
let password = "";
|
|
92
|
+
if (command !== "setup-key") {
|
|
93
|
+
password = await ttyInput("New owner password (12–128 characters): ");
|
|
94
|
+
const confirmation = await ttyInput("Confirm password: ");
|
|
95
|
+
if (password !== confirmation)
|
|
96
|
+
throw new Error("Passwords do not match.");
|
|
97
|
+
}
|
|
98
|
+
const key = command === "init" ? await initializeOwner(home, values.get("--origin"), values.get("--email"), password) :
|
|
99
|
+
command === "recover" ? await recoverOwner(home, password) : replaceSetupKey(home);
|
|
100
|
+
password = "";
|
|
101
|
+
process.stdout.write(`Setup key (expires in 30 minutes; save privately): ${key}\nStart Cogitator, open the configured HTTPS origin, sign in, and enter this key during authenticator enrollment.\n`);
|
|
102
|
+
}
|
|
103
|
+
finally {
|
|
104
|
+
await releasePort?.();
|
|
105
|
+
unlock();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
finally {
|
|
109
|
+
process.off("SIGINT", interrupt);
|
|
110
|
+
process.off("SIGTERM", interrupt);
|
|
111
|
+
restoreTerminal();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { protectedRequired } from "./auth-state.js";
|
|
3
|
+
import { AuthError, authMutationAuthorization, ownerSession, policy, requireApproved, requireEnrollment, selectEnrollment, sessionById, verifyEnrollment } from "./native-auth.js";
|
|
4
|
+
const password = z.string().min(1).max(128);
|
|
5
|
+
const schemas = {
|
|
6
|
+
"/api/auth/sign-in/email": z.object({ email: z.email().max(254), password }).strict(),
|
|
7
|
+
"/api/auth/sign-out": z.object({}).strict(),
|
|
8
|
+
"/api/auth/two-factor/enable": z.object({ password, setupKey: z.string().max(128).optional() }).strict(),
|
|
9
|
+
"/api/auth/two-factor/verify-totp": z.object({ code: z.string().regex(/^\d{6}$/) }).strict(),
|
|
10
|
+
"/api/auth/two-factor/verify-backup-code": z.object({ code: z.string().min(1).max(128) }).strict(),
|
|
11
|
+
"/api/auth/two-factor/generate-backup-codes": z.object({ password }).strict(),
|
|
12
|
+
};
|
|
13
|
+
export function authJson(res, status, body) {
|
|
14
|
+
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
|
|
15
|
+
res.end(JSON.stringify(body));
|
|
16
|
+
}
|
|
17
|
+
export function authFailure(res, error) {
|
|
18
|
+
if (res.headersSent) {
|
|
19
|
+
res.end();
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
const failure = error instanceof AuthError ? error : new AuthError("AUTH_UNAVAILABLE", 503);
|
|
23
|
+
authJson(res, failure.status, { error: failure.code, ...(failure.retryAt ? { retryAt: failure.retryAt } : {}) });
|
|
24
|
+
}
|
|
25
|
+
export function browserHeaders(req) {
|
|
26
|
+
const headers = new Headers();
|
|
27
|
+
for (const name of ["cookie", "origin", "content-type", "user-agent"]) {
|
|
28
|
+
const value = req.headers[name];
|
|
29
|
+
if (typeof value === "string")
|
|
30
|
+
headers.set(name, value);
|
|
31
|
+
}
|
|
32
|
+
// Never copy forwarding headers. This bucket is deliberately shared behind a loopback TLS proxy.
|
|
33
|
+
headers.set("x-cogitator-peer", req.socket.remoteAddress ?? "unknown");
|
|
34
|
+
const cookie = headers.get("cookie");
|
|
35
|
+
if (cookie)
|
|
36
|
+
headers.set("cookie", cookie.split(";").filter(c => !c.split("=")[0]?.includes("trust_device")).join(";"));
|
|
37
|
+
return headers;
|
|
38
|
+
}
|
|
39
|
+
export function validateBoundary(req, state) {
|
|
40
|
+
const raw = req.url ?? "";
|
|
41
|
+
const pathname = raw.split("?")[0] ?? "";
|
|
42
|
+
if (!raw.startsWith("/") || pathname.includes("%") || pathname.includes("#") || pathname.includes("\\") || pathname.includes("//") || /\/(?:\.|\.\.)(?:\/|$)/.test(pathname) || (pathname.length > 1 && pathname.endsWith("/")))
|
|
43
|
+
throw new AuthError("INVALID_INPUT", 400);
|
|
44
|
+
const localLiveness = req.method === "GET" && raw === "/api/status" && req.headers.host === `127.0.0.1:${req.socket.localPort}`;
|
|
45
|
+
if (req.headers.host !== new URL(state.config.origin).host && !localLiveness)
|
|
46
|
+
throw new AuthError("FORBIDDEN", 403);
|
|
47
|
+
const origin = req.headers.origin;
|
|
48
|
+
if ((origin && origin !== state.config.origin) || (req.headers["sec-fetch-site"] === "cross-site"))
|
|
49
|
+
throw new AuthError("FORBIDDEN", 403);
|
|
50
|
+
if (!["GET", "HEAD"].includes(req.method ?? "") && origin !== state.config.origin)
|
|
51
|
+
throw new AuthError("FORBIDDEN", 403);
|
|
52
|
+
if (!["GET", "HEAD"].includes(req.method ?? "") && !/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(String(req.headers["content-type"] ?? "")))
|
|
53
|
+
throw new AuthError("INVALID_INPUT", 400);
|
|
54
|
+
}
|
|
55
|
+
async function authBody(req) {
|
|
56
|
+
const chunks = [];
|
|
57
|
+
let length = 0;
|
|
58
|
+
for await (const chunk of req) {
|
|
59
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
60
|
+
length += bytes.length;
|
|
61
|
+
if (length > 8192)
|
|
62
|
+
throw new AuthError("INVALID_INPUT", 413);
|
|
63
|
+
chunks.push(bytes);
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
throw new AuthError("INVALID_INPUT", 400);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function libraryError(status, data, path) {
|
|
73
|
+
if (data.code === "CODE_ALREADY_USED")
|
|
74
|
+
return "CODE_ALREADY_USED";
|
|
75
|
+
if (status === 429)
|
|
76
|
+
return "RATE_LIMITED";
|
|
77
|
+
if (status >= 500)
|
|
78
|
+
return "AUTH_UNAVAILABLE";
|
|
79
|
+
if (status === 409)
|
|
80
|
+
return "CONFLICT";
|
|
81
|
+
if (path.endsWith("sign-in/email") || data.code === "INVALID_PASSWORD")
|
|
82
|
+
return "INVALID_CREDENTIALS";
|
|
83
|
+
if (data.code === "INVALID_TWO_FACTOR_COOKIE")
|
|
84
|
+
return "REAUTH_REQUIRED";
|
|
85
|
+
if (path.includes("verify-"))
|
|
86
|
+
return "INVALID_CODE";
|
|
87
|
+
if (status === 401)
|
|
88
|
+
return "AUTH_REQUIRED";
|
|
89
|
+
return "INVALID_INPUT";
|
|
90
|
+
}
|
|
91
|
+
const factorMutations = new WeakSet();
|
|
92
|
+
function throttle(state, path) {
|
|
93
|
+
const now = Date.now();
|
|
94
|
+
const window = path.includes("two-factor") ? 10_000 : 60_000;
|
|
95
|
+
const max = path.includes("two-factor") ? 3 : path.endsWith("sign-in/email") ? 10 : 60;
|
|
96
|
+
const row = state.db.prepare(`INSERT INTO authThrottle(path,count,until) VALUES (?,1,?)
|
|
97
|
+
ON CONFLICT(path) DO UPDATE SET count=CASE WHEN until<=? THEN 1 ELSE count+1 END,
|
|
98
|
+
until=CASE WHEN until<=? THEN excluded.until ELSE until END RETURNING count,until`).get(path, now + window, now, now);
|
|
99
|
+
if (row.count > max)
|
|
100
|
+
throw new AuthError("RATE_LIMITED", 429, new Date(row.until).toISOString());
|
|
101
|
+
}
|
|
102
|
+
/** Handles the exact public auth surface. No raw library JSON or headers escape. */
|
|
103
|
+
export async function authRoute(req, res, state) {
|
|
104
|
+
const path = req.url ?? "";
|
|
105
|
+
if (path === "/api/auth/status" && req.method === "GET") {
|
|
106
|
+
state.assertAvailable();
|
|
107
|
+
const session = await ownerSession(state.auth, state.db, state.config, browserHeaders(req));
|
|
108
|
+
state.assertAvailable();
|
|
109
|
+
if (!session)
|
|
110
|
+
return authJson(res, 200, { mode: "protected", state: "anonymous" });
|
|
111
|
+
const fresh = sessionById(state.db, state.config, session.id);
|
|
112
|
+
if (!fresh)
|
|
113
|
+
throw new AuthError("AUTH_REQUIRED", 401);
|
|
114
|
+
const p = policy(state.db);
|
|
115
|
+
const liveClaim = p.claimId && p.claimExpires > Date.now() && sessionById(state.db, state.config, p.claimId);
|
|
116
|
+
const selected = liveClaim && p.claimId === fresh.id;
|
|
117
|
+
authJson(res, 200, { mode: "protected", state: fresh.enrolled ? (fresh.approved ? "authenticated" : "reauthenticate") : "enrollment",
|
|
118
|
+
email: fresh.email, expiresAt: new Date(fresh.expiresAt).toISOString(), ...(!fresh.enrolled ? { enrollment: {
|
|
119
|
+
requiresSetupKey: !selected, pending: Boolean(selected && state.db.prepare("SELECT 1 FROM twoFactor WHERE userId=?").get(state.config.ownerId)),
|
|
120
|
+
...(liveClaim && !selected ? { busyUntil: new Date(p.claimExpires).toISOString() } : {}),
|
|
121
|
+
} } : {}) });
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
if (req.method !== "POST" || !Object.hasOwn(schemas, path))
|
|
125
|
+
throw new AuthError("NOT_FOUND", 404);
|
|
126
|
+
const parsed = schemas[path].safeParse(await authBody(req));
|
|
127
|
+
if (!parsed.success)
|
|
128
|
+
throw new AuthError("INVALID_INPUT", 400);
|
|
129
|
+
state.assertAvailable();
|
|
130
|
+
throttle(state, path);
|
|
131
|
+
const headers = browserHeaders(req);
|
|
132
|
+
const session = await ownerSession(state.auth, state.db, state.config, headers);
|
|
133
|
+
state.assertAvailable();
|
|
134
|
+
const fresh = session ? sessionById(state.db, state.config, session.id) : null;
|
|
135
|
+
const mutateFactor = Boolean(fresh && path.includes("/two-factor/"));
|
|
136
|
+
if (mutateFactor && factorMutations.has(state))
|
|
137
|
+
throw new AuthError("ENROLLMENT_BUSY", 409, new Date(Date.now() + 1000).toISOString());
|
|
138
|
+
if (mutateFactor)
|
|
139
|
+
factorMutations.add(state);
|
|
140
|
+
try {
|
|
141
|
+
const body = { ...parsed.data };
|
|
142
|
+
if (path.endsWith("/enable")) {
|
|
143
|
+
selectEnrollment(state.db, state.config, fresh, typeof body.setupKey === "string" ? body.setupKey : undefined);
|
|
144
|
+
delete body.setupKey;
|
|
145
|
+
body.method = "totp";
|
|
146
|
+
}
|
|
147
|
+
else if (path.endsWith("/verify-totp") && fresh)
|
|
148
|
+
requireEnrollment(state.db, fresh);
|
|
149
|
+
else if (path.endsWith("/verify-backup-code") && fresh)
|
|
150
|
+
throw new AuthError("REAUTH_REQUIRED", 403);
|
|
151
|
+
else if (path.endsWith("/generate-backup-codes"))
|
|
152
|
+
requireApproved(fresh);
|
|
153
|
+
const invoke = () => state.auth.handler(new Request(`${state.config.origin}${path}`, { method: "POST", headers, body: JSON.stringify(body) }));
|
|
154
|
+
const activation = fresh && path.endsWith("/verify-totp");
|
|
155
|
+
const response = activation ? await verifyEnrollment(state.db, fresh.id, invoke) : fresh && (path.endsWith("/enable") || path.endsWith("/generate-backup-codes"))
|
|
156
|
+
? await authMutationAuthorization.run({ sessionId: fresh.id, mode: path.endsWith("/enable") ? "enrollment" : "approved" }, invoke)
|
|
157
|
+
: await invoke();
|
|
158
|
+
// 1.7.7 sign-out catches deletion errors and still clears cookies. Do not forward that false
|
|
159
|
+
// success: retain the browser cookie for retry until its validated session is durably absent.
|
|
160
|
+
if (path.endsWith("/sign-out") && session && (state.db.inTransaction || state.db.prepare("SELECT 1 FROM session WHERE id=?").get(session.id)))
|
|
161
|
+
throw new AuthError("AUTH_UNAVAILABLE", 503);
|
|
162
|
+
const raw = await response.json().catch(() => ({}));
|
|
163
|
+
const data = raw && typeof raw === "object" ? raw : {};
|
|
164
|
+
// Set-Cookie is multi-valued, never split on commas (Expires contains a comma).
|
|
165
|
+
const cookies = response.headers.getSetCookie();
|
|
166
|
+
if (cookies.length && (!activation || response.ok))
|
|
167
|
+
res.setHeader("set-cookie", cookies);
|
|
168
|
+
if (!response.ok) {
|
|
169
|
+
const retry = Number(response.headers.get("retry-after"));
|
|
170
|
+
return authJson(res, response.status, { error: libraryError(response.status, data, path), ...(retry > 0 ? { retryAfter: retry } : {}) });
|
|
171
|
+
}
|
|
172
|
+
state.assertAvailable();
|
|
173
|
+
if (path.endsWith("/sign-out") && fresh)
|
|
174
|
+
state.db.prepare("UPDATE authPolicy SET claimId=NULL, claimExpires=0 WHERE claimId=?").run(fresh.id);
|
|
175
|
+
if (path.endsWith("/verify-totp")) {
|
|
176
|
+
const enrolled = state.db.prepare("SELECT twoFactorEnabled FROM user WHERE id=?").get(state.config.ownerId);
|
|
177
|
+
if (enrolled.twoFactorEnabled)
|
|
178
|
+
state.db.prepare("UPDATE authPolicy SET setupDigest=NULL, setupExpires=0, claimId=NULL, claimExpires=0").run();
|
|
179
|
+
}
|
|
180
|
+
if (path.endsWith("/enable") || path.endsWith("/generate-backup-codes")) {
|
|
181
|
+
if (path.endsWith("/enable"))
|
|
182
|
+
requireEnrollment(state.db, fresh ? sessionById(state.db, state.config, fresh.id) : null);
|
|
183
|
+
else
|
|
184
|
+
requireApproved(fresh ? sessionById(state.db, state.config, fresh.id) : null);
|
|
185
|
+
if (!Array.isArray(data.backupCodes) || !data.backupCodes.every(c => typeof c === "string"))
|
|
186
|
+
throw new AuthError("AUTH_UNAVAILABLE", 503);
|
|
187
|
+
if (path.endsWith("/enable") && typeof data.totpURI !== "string")
|
|
188
|
+
throw new AuthError("AUTH_UNAVAILABLE", 503);
|
|
189
|
+
return authJson(res, 200, { ...(path.endsWith("/enable") ? { totpURI: data.totpURI } : {}), backupCodes: data.backupCodes });
|
|
190
|
+
}
|
|
191
|
+
authJson(res, 200, path.endsWith("/sign-in/email") ? { twoFactorRequired: data.twoFactorRedirect === true } : { ok: true });
|
|
192
|
+
}
|
|
193
|
+
finally {
|
|
194
|
+
if (mutateFactor)
|
|
195
|
+
factorMutations.delete(state);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
export const responseChecks = new WeakMap();
|
|
199
|
+
export function checkResponse(res) { responseChecks.get(res)?.(); }
|
|
200
|
+
export function localCheck(home) {
|
|
201
|
+
if (protectedRequired(home))
|
|
202
|
+
throw new AuthError("AUTH_UNAVAILABLE", 503);
|
|
203
|
+
}
|