@netnodeag/kraftwerk 0.96.0 → 0.97.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 +30 -0
- package/dist/cli/boards.js +6 -5
- package/dist/cli/init.js +2 -0
- package/dist/cli/knowledge.js +9 -6
- package/dist/cli/presentations.js +8 -4
- package/dist/cli/projects.js +1 -1
- package/dist/client/index.d.ts +2 -0
- package/dist/client/index.js +3 -0
- package/dist/client/routes.d.ts +1 -0
- package/dist/client/routes.js +1 -0
- package/dist/config.d.ts +34 -0
- package/dist/config.js +28 -1
- package/dist/core/boards.d.ts +1 -1
- package/dist/core/boards.js +10 -6
- package/dist/core/chat/sessions.d.ts +3 -3
- package/dist/core/chat/sessions.js +6 -5
- package/dist/core/chat/types.d.ts +2 -0
- package/dist/core/cloud.d.ts +45 -0
- package/dist/core/cloud.js +35 -0
- package/dist/core/knowledge.d.ts +0 -7
- package/dist/core/knowledge.js +6 -6
- package/dist/core/person.d.ts +41 -0
- package/dist/core/person.js +47 -0
- package/dist/core/projects.d.ts +1 -1
- package/dist/core/projects.js +3 -2
- package/dist/server/api/agents.js +2 -2
- package/dist/server/api/boards.js +1 -1
- package/dist/server/api/chats.js +11 -7
- package/dist/server/api/cloud.d.ts +8 -0
- package/dist/server/api/index.d.ts +21 -2
- package/dist/server/api/presentations.js +2 -2
- package/dist/server/api/projects.d.ts +1 -1
- package/dist/server/api/projects.js +1 -1
- package/dist/server/api/router.js +5 -2
- package/dist/server/api/workspace.d.ts +14 -1
- package/dist/server/api/workspace.js +21 -1
- package/dist/server/cloud.d.ts +3 -0
- package/dist/server/cloud.js +20 -4
- package/dist/server/person.d.ts +9 -0
- package/dist/server/person.js +14 -0
- package/dist/server/server.js +60 -4
- package/dist/server/trust.d.ts +5 -1
- package/dist/server/users.d.ts +55 -0
- package/dist/server/users.js +258 -0
- package/package.json +1 -1
- package/schema/kraftwerk.schema.json +8 -0
- package/web/dist/assets/{dist-BiyjchCb.js → dist-BD4ooe-Y.js} +1 -1
- package/web/dist/assets/{dist-qkoQQWNK.js → dist-BduOHHOY.js} +1 -1
- package/web/dist/assets/{dist-DkDmdJNX.js → dist-BoajTxbz.js} +1 -1
- package/web/dist/assets/{dist-wkkpVezb.js → dist-DGLb7wE6.js} +1 -1
- package/web/dist/assets/{dist-14HFV7uD.js → dist-DJACzcZZ.js} +1 -1
- package/web/dist/assets/{dist-DO04nOS3.js → dist-DY6QplYX.js} +1 -1
- package/web/dist/assets/{dist-DbBrc07-.js → dist-D_uWSMLk.js} +1 -1
- package/web/dist/assets/{dist-DKQkCBo9.js → dist-P7JCq9c3.js} +1 -1
- package/web/dist/assets/dist-ajNgHt2Q.js +1 -0
- package/web/dist/assets/{dist-BYgXVWBg.js → dist-lcPkaK4d.js} +1 -1
- package/web/dist/assets/{dist-DOW1X_nG.js → dist-oRcLByHn.js} +1 -1
- package/web/dist/assets/{editor-DvkpSp7h.js → editor-hTceN7Iz.js} +3 -3
- package/web/dist/assets/index-BGgQaaA9.css +2 -0
- package/web/dist/assets/index-BOkjCxut.js +488 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/dist-CCZcAg77.js +0 -1
- package/web/dist/assets/index-B5PLhJ-C.js +0 -488
- package/web/dist/assets/index-CWopPK15.css +0 -2
package/dist/server/server.js
CHANGED
|
@@ -22,6 +22,8 @@ import { json } from "./api/router.js";
|
|
|
22
22
|
import { MIME } from "./api/mime.js";
|
|
23
23
|
import { getPkgVersion, RESTART_EXIT_CODE } from "./version.js";
|
|
24
24
|
import { trustOf } from "./trust.js";
|
|
25
|
+
import { fromBrowser, handleAuth, signedIn } from "./users.js";
|
|
26
|
+
import { configAt, usersMode } from "../config.js";
|
|
25
27
|
import { targetOf } from "./target.js";
|
|
26
28
|
import { isDir, resolveWorkspace, workspaceSlug } from "../config.js";
|
|
27
29
|
export { RESTART_EXIT_CODE };
|
|
@@ -238,6 +240,33 @@ function hubPage(req, res, open, trust) {
|
|
|
238
240
|
: "<li>No workspace is open. Run <code>kraftwerk ui</code> in a workspace folder.</li>";
|
|
239
241
|
res.end(`${head}<ul>${rows}</ul>`);
|
|
240
242
|
}
|
|
243
|
+
/**
|
|
244
|
+
* A `users: cloud` workspace (kraftwerk.yml, server/users.ts): what signing
|
|
245
|
+
* in there needs, or undefined for a `users: local` one.
|
|
246
|
+
*/
|
|
247
|
+
async function cloudUsers(open, prefix) {
|
|
248
|
+
if (!open)
|
|
249
|
+
return undefined;
|
|
250
|
+
const config = await configAt(open.root);
|
|
251
|
+
if (usersMode(config) !== "cloud")
|
|
252
|
+
return undefined;
|
|
253
|
+
return { workspaceId: config.id, name: open.name, prefix };
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* This machine's browser in a `users: cloud` workspace must be signed in:
|
|
257
|
+
* its trust names the person (`user`), or it has none yet (`signin`).
|
|
258
|
+
* Scripts and tools on this machine (not a browser, users.ts fromBrowser: the CLI,
|
|
259
|
+
* curl) are the machine's own shell and pass as before; paired devices
|
|
260
|
+
* and remote members have their own credentials.
|
|
261
|
+
*/
|
|
262
|
+
async function withUser(req, trust, cu) {
|
|
263
|
+
if (!cu || trust.kind !== "local" || !fromBrowser(req))
|
|
264
|
+
return { trust };
|
|
265
|
+
const user = cu.workspaceId ? await signedIn(req, cu.workspaceId) : null;
|
|
266
|
+
return user ? { trust: { kind: "local", user } } : { trust, signin: true };
|
|
267
|
+
}
|
|
268
|
+
/** The `/w/<slug>` a path-form request came in under, else "". */
|
|
269
|
+
const prefixOf = (req, target) => (target.slug !== undefined && /^\/w\//.test(req.url ?? "") ? `/w/${target.slug}` : "");
|
|
241
270
|
export async function startHub(opts) {
|
|
242
271
|
const trustOpts = { trustLoopback: opts.trustLoopback !== false && !REQUIRE_PAIRING, trustNetwork: TRUST_NETWORK };
|
|
243
272
|
const bySlug = new Map();
|
|
@@ -259,11 +288,31 @@ export async function startHub(opts) {
|
|
|
259
288
|
if (target.slug !== undefined && !open)
|
|
260
289
|
return json(res, { error: `no workspace "${target.slug}" here` }, 404);
|
|
261
290
|
const { url } = target;
|
|
262
|
-
const
|
|
291
|
+
const prefix = prefixOf(req, target);
|
|
292
|
+
const cu = await cloudUsers(open, prefix);
|
|
293
|
+
const gate = await withUser(req, await trustOf(req, url, trustOpts), cu);
|
|
294
|
+
const { trust } = gate;
|
|
263
295
|
// A member session (members.ts) reaches its one workspace and nothing else: not another, not the hub page.
|
|
264
296
|
if (trust.kind === "member" && open?.slug !== trust.slug) {
|
|
265
297
|
return json(res, { error: `a member session reaches only its workspace — /w/${trust.slug}/…` }, 403);
|
|
266
298
|
}
|
|
299
|
+
// Signing in (users: cloud): the way there and back is open; everything else waits for it.
|
|
300
|
+
if (cu && url.pathname.startsWith("/auth/") && trust.kind === "local") {
|
|
301
|
+
if (req.method === "POST" && !sameOrigin(req))
|
|
302
|
+
return json(res, { error: "cross-origin request refused" }, 403);
|
|
303
|
+
if (await handleAuth(req, res, url, cu))
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (gate.signin) {
|
|
307
|
+
const signin = `${prefix}/auth/signin`;
|
|
308
|
+
if (url.pathname.startsWith("/api/"))
|
|
309
|
+
return json(res, { error: "sign in first", signin }, 401);
|
|
310
|
+
// The UI's own files (hashed, no data) load on the sign-in redirect's way back; pages and app files wait.
|
|
311
|
+
if (!url.pathname.startsWith("/assets/") && !/^\/[^/]+\.(ico|png|svg|webmanifest)$/.test(url.pathname)) {
|
|
312
|
+
res.writeHead(302, { location: `${signin}?next=${encodeURIComponent(`${prefix}${url.pathname}${url.search}`)}`, "cache-control": "no-store" });
|
|
313
|
+
return void res.end();
|
|
314
|
+
}
|
|
315
|
+
}
|
|
267
316
|
const run = (fn) => runInHub(hub, () => (open ? open.ws.run(fn) : fn()));
|
|
268
317
|
if (url.pathname.startsWith("/api/")) {
|
|
269
318
|
const method = req.method ?? "GET";
|
|
@@ -301,8 +350,10 @@ export async function startHub(opts) {
|
|
|
301
350
|
if (target.slug !== undefined && !open)
|
|
302
351
|
return void socket.end("HTTP/1.1 404 Not Found\r\nconnection: close\r\n\r\n");
|
|
303
352
|
const { url } = target;
|
|
304
|
-
const
|
|
305
|
-
|
|
353
|
+
const cu = await cloudUsers(open, prefixOf(req, target));
|
|
354
|
+
const gate = await withUser(req, await trustOf(req, url, trustOpts, true), cu);
|
|
355
|
+
const { trust } = gate;
|
|
356
|
+
if (trust.kind === "none" || gate.signin)
|
|
306
357
|
return void socket.end("HTTP/1.1 401 Unauthorized\r\nconnection: close\r\n\r\n");
|
|
307
358
|
// A socket may name any workspace per message; a member session's scope is per request, so it gets none.
|
|
308
359
|
if (trust.kind === "member")
|
|
@@ -327,7 +378,12 @@ export async function startHub(opts) {
|
|
|
327
378
|
const entry = { slug: own, close: () => conn.close(4404, "workspace closed") };
|
|
328
379
|
sockets.add(entry);
|
|
329
380
|
conn.onClose(() => sockets.delete(entry));
|
|
330
|
-
|
|
381
|
+
// Re-checked per message: a person signed out (or removed in the cloud) loses the socket's rights with the next one.
|
|
382
|
+
const recheck = async () => {
|
|
383
|
+
const g = await withUser(req, await trustOf(req, url, trustOpts, true), cu);
|
|
384
|
+
return g.signin ? { kind: "none" } : g.trust;
|
|
385
|
+
};
|
|
386
|
+
runInHub(hub, () => serveSocket(conn, resolve, version, trust, recheck, hub));
|
|
331
387
|
})().catch(() => socket.destroy());
|
|
332
388
|
};
|
|
333
389
|
const server = http.createServer(handler(() => fallback));
|
package/dist/server/trust.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type http from "node:http";
|
|
2
2
|
import { type Device } from "../core/devices.js";
|
|
3
3
|
import { type Member } from "./members.js";
|
|
4
|
+
import type { SignedIn } from "./users.js";
|
|
4
5
|
/**
|
|
5
6
|
* Who is asking. Every request and socket gets one of:
|
|
6
7
|
*
|
|
@@ -28,8 +29,11 @@ import { type Member } from "./members.js";
|
|
|
28
29
|
* - `none`: anyone else. Gets the web UI's shell (to show the pairing
|
|
29
30
|
* screen), the protocol description and the pairing route — nothing else.
|
|
30
31
|
*/
|
|
31
|
-
export type Trust =
|
|
32
|
+
export type Trust =
|
|
33
|
+
/** `user`: the person signed in with their cloud account (kraftwerk.yml `users: cloud`, server/users.ts). */
|
|
34
|
+
{
|
|
32
35
|
kind: "local";
|
|
36
|
+
user?: SignedIn;
|
|
33
37
|
} | {
|
|
34
38
|
kind: "device";
|
|
35
39
|
device: Device;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type http from "node:http";
|
|
2
|
+
import { type CloudUser } from "../core/cloud.js";
|
|
3
|
+
/**
|
|
4
|
+
* People signing in to a workspace's UI — kraftwerk.yml `users: cloud`.
|
|
5
|
+
*
|
|
6
|
+
* The browser on this machine is sent to the cloud (/signin), where the
|
|
7
|
+
* account confirms; the cloud sends it back to /auth/callback with a
|
|
8
|
+
* one-time code, which this daemon redeems with the machine's own secret
|
|
9
|
+
* (core/cloud.ts signinExchange). The answer — the account's uuid, email,
|
|
10
|
+
* handle and role on the workspace — becomes a session:
|
|
11
|
+
*
|
|
12
|
+
* cookie kw_user (HttpOnly, SameSite=Lax), per origin: <slug>.localhost
|
|
13
|
+
* is its own, the path form /w/<slug>/ shares localhost's
|
|
14
|
+
* at rest ~/.kraftwerk/user-sessions.json, the cookie only as its sha256,
|
|
15
|
+
* so a daemon restart signs nobody out
|
|
16
|
+
* scope one session may hold several workspaces (the path form): each
|
|
17
|
+
* is signed in to on its own, by the same account
|
|
18
|
+
* lifetime 30 days; every 15 minutes the cloud is asked again whether
|
|
19
|
+
* the account is still on the workspace (removing a member
|
|
20
|
+
* reaches the UI they are signed in to). A cloud that cannot be
|
|
21
|
+
* reached keeps the session as it is
|
|
22
|
+
*
|
|
23
|
+
* The state of a sign-in in flight is bound to the browser that started it
|
|
24
|
+
* (the kw_signin cookie) and lives ten minutes.
|
|
25
|
+
*/
|
|
26
|
+
export declare const USER_COOKIE = "kw_user";
|
|
27
|
+
/** How often a signed-in person is checked with the cloud again — tests shorten it; no argument restores the default. */
|
|
28
|
+
export declare function setUserRecheck(ms?: number): void;
|
|
29
|
+
export interface SignedIn {
|
|
30
|
+
user: CloudUser;
|
|
31
|
+
role: "owner" | "member";
|
|
32
|
+
}
|
|
33
|
+
export declare function cookieOf(req: http.IncomingMessage, name: string): string | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* Whether the request comes from a browser. Browsers say where a fetch came
|
|
36
|
+
* from (Sec-Fetch-Site, -Dest) and call themselves Mozilla/…; Node's fetch
|
|
37
|
+
* (the CLI) sends Sec-Fetch-Mode only, curl none of them.
|
|
38
|
+
*/
|
|
39
|
+
export declare const fromBrowser: (req: http.IncomingMessage) => boolean;
|
|
40
|
+
/** Who the request's browser is signed in as on workspace `workspaceId`, or null. */
|
|
41
|
+
export declare function signedIn(req: http.IncomingMessage, workspaceId: string): Promise<SignedIn | null>;
|
|
42
|
+
export interface SigninTarget {
|
|
43
|
+
/** The workspace's ws_ id (kraftwerk.yml `id`). */
|
|
44
|
+
workspaceId: string | undefined;
|
|
45
|
+
name: string;
|
|
46
|
+
/** "/w/<slug>" in the path form, else "". */
|
|
47
|
+
prefix: string;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* /auth/signin, /auth/callback, /auth/signout for a `users: cloud`
|
|
51
|
+
* workspace. Returns false for any other path.
|
|
52
|
+
*/
|
|
53
|
+
export declare function handleAuth(req: http.IncomingMessage, res: http.ServerResponse, url: URL, t: SigninTarget): Promise<boolean>;
|
|
54
|
+
/** Forget every session in memory (tests: the next read loads the file again). */
|
|
55
|
+
export declare function forgetUserSessions(): void;
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { promises as fs } from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { CloudError, signinExchange, signinUrl, signinVerify } from "../core/cloud.js";
|
|
6
|
+
import { log } from "../core/log.js";
|
|
7
|
+
import { machineLink } from "./cloud.js";
|
|
8
|
+
/**
|
|
9
|
+
* People signing in to a workspace's UI — kraftwerk.yml `users: cloud`.
|
|
10
|
+
*
|
|
11
|
+
* The browser on this machine is sent to the cloud (/signin), where the
|
|
12
|
+
* account confirms; the cloud sends it back to /auth/callback with a
|
|
13
|
+
* one-time code, which this daemon redeems with the machine's own secret
|
|
14
|
+
* (core/cloud.ts signinExchange). The answer — the account's uuid, email,
|
|
15
|
+
* handle and role on the workspace — becomes a session:
|
|
16
|
+
*
|
|
17
|
+
* cookie kw_user (HttpOnly, SameSite=Lax), per origin: <slug>.localhost
|
|
18
|
+
* is its own, the path form /w/<slug>/ shares localhost's
|
|
19
|
+
* at rest ~/.kraftwerk/user-sessions.json, the cookie only as its sha256,
|
|
20
|
+
* so a daemon restart signs nobody out
|
|
21
|
+
* scope one session may hold several workspaces (the path form): each
|
|
22
|
+
* is signed in to on its own, by the same account
|
|
23
|
+
* lifetime 30 days; every 15 minutes the cloud is asked again whether
|
|
24
|
+
* the account is still on the workspace (removing a member
|
|
25
|
+
* reaches the UI they are signed in to). A cloud that cannot be
|
|
26
|
+
* reached keeps the session as it is
|
|
27
|
+
*
|
|
28
|
+
* The state of a sign-in in flight is bound to the browser that started it
|
|
29
|
+
* (the kw_signin cookie) and lives ten minutes.
|
|
30
|
+
*/
|
|
31
|
+
export const USER_COOKIE = "kw_user";
|
|
32
|
+
const STATE_COOKIE = "kw_signin";
|
|
33
|
+
const SESSION_TTL_MS = 30 * 24 * 3600_000;
|
|
34
|
+
const STATE_TTL_MS = 10 * 60_000;
|
|
35
|
+
const DEFAULT_RECHECK_MS = 15 * 60_000;
|
|
36
|
+
let recheckMs = DEFAULT_RECHECK_MS;
|
|
37
|
+
/** How often a signed-in person is checked with the cloud again — tests shorten it; no argument restores the default. */
|
|
38
|
+
export function setUserRecheck(ms) {
|
|
39
|
+
recheckMs = ms ?? DEFAULT_RECHECK_MS;
|
|
40
|
+
}
|
|
41
|
+
const file = () => path.join(os.homedir(), ".kraftwerk", "user-sessions.json");
|
|
42
|
+
const hash = (token) => createHash("sha256").update(token).digest("hex");
|
|
43
|
+
let sessions = null;
|
|
44
|
+
let loadedFrom = "";
|
|
45
|
+
const pending = new Map();
|
|
46
|
+
const rechecks = new Map();
|
|
47
|
+
async function load() {
|
|
48
|
+
// HOME may change between tests; a different file is a different store.
|
|
49
|
+
if (sessions && loadedFrom === file())
|
|
50
|
+
return sessions;
|
|
51
|
+
loadedFrom = file();
|
|
52
|
+
sessions = new Map();
|
|
53
|
+
try {
|
|
54
|
+
const raw = JSON.parse(await fs.readFile(loadedFrom, "utf8"));
|
|
55
|
+
const now = Date.now();
|
|
56
|
+
for (const [k, s] of Object.entries(raw))
|
|
57
|
+
if (s?.user?.id && now - s.createdAt < SESSION_TTL_MS)
|
|
58
|
+
sessions.set(k, s);
|
|
59
|
+
}
|
|
60
|
+
catch { }
|
|
61
|
+
return sessions;
|
|
62
|
+
}
|
|
63
|
+
let writing = Promise.resolve();
|
|
64
|
+
function save() {
|
|
65
|
+
const target = loadedFrom;
|
|
66
|
+
const data = JSON.stringify(Object.fromEntries(sessions ?? []), null, 2) + "\n";
|
|
67
|
+
writing = writing.then(async () => {
|
|
68
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
69
|
+
const tmp = `${target}.${process.pid}.tmp`;
|
|
70
|
+
await fs.writeFile(tmp, data, { mode: 0o600 });
|
|
71
|
+
await fs.rename(tmp, target);
|
|
72
|
+
}).catch((err) => log("warn", "users", `could not store the sign-in sessions: ${err.message}`));
|
|
73
|
+
return writing;
|
|
74
|
+
}
|
|
75
|
+
export function cookieOf(req, name) {
|
|
76
|
+
const c = req.headers.cookie
|
|
77
|
+
?.split(";")
|
|
78
|
+
.map((x) => x.trim())
|
|
79
|
+
.find((x) => x.startsWith(`${name}=`));
|
|
80
|
+
return c ? decodeURIComponent(c.slice(name.length + 1)) : undefined;
|
|
81
|
+
}
|
|
82
|
+
const cookie = (name, value, maxAgeS) => `${name}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeS}`;
|
|
83
|
+
/**
|
|
84
|
+
* Whether the request comes from a browser. Browsers say where a fetch came
|
|
85
|
+
* from (Sec-Fetch-Site, -Dest) and call themselves Mozilla/…; Node's fetch
|
|
86
|
+
* (the CLI) sends Sec-Fetch-Mode only, curl none of them.
|
|
87
|
+
*/
|
|
88
|
+
export const fromBrowser = (req) => !!(req.headers["sec-fetch-site"] || req.headers["sec-fetch-dest"]) || /^Mozilla\//.test(String(req.headers["user-agent"] ?? ""));
|
|
89
|
+
/** Re-ask the cloud about a session's workspace (once at a time); a refusal drops it, an outage keeps it. */
|
|
90
|
+
function recheck(key, s, workspaceId) {
|
|
91
|
+
const k = `${key}\0${workspaceId}`;
|
|
92
|
+
const running = rechecks.get(k);
|
|
93
|
+
if (running)
|
|
94
|
+
return running;
|
|
95
|
+
const run = (async () => {
|
|
96
|
+
const link = machineLink();
|
|
97
|
+
if (!link)
|
|
98
|
+
return;
|
|
99
|
+
try {
|
|
100
|
+
const r = await signinVerify(link.url, link.creds, workspaceId, s.user.id, link.version);
|
|
101
|
+
s.user = { id: s.user.id, email: r.user.email, handle: r.user.handle };
|
|
102
|
+
s.workspaces[workspaceId] = { role: r.role, checkedAt: Date.now() };
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
const status = err instanceof CloudError ? err.status : 0;
|
|
106
|
+
if (status === 401 || status === 403 || status === 404) {
|
|
107
|
+
delete s.workspaces[workspaceId];
|
|
108
|
+
log("info", "users", `${s.user.handle} is no longer on ${workspaceId}: signed out there`);
|
|
109
|
+
}
|
|
110
|
+
else
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
await save();
|
|
114
|
+
})();
|
|
115
|
+
rechecks.set(k, run);
|
|
116
|
+
void run.finally(() => rechecks.delete(k));
|
|
117
|
+
return run;
|
|
118
|
+
}
|
|
119
|
+
/** Who the request's browser is signed in as on workspace `workspaceId`, or null. */
|
|
120
|
+
export async function signedIn(req, workspaceId) {
|
|
121
|
+
const token = cookieOf(req, USER_COOKIE);
|
|
122
|
+
if (!token)
|
|
123
|
+
return null;
|
|
124
|
+
const all = await load();
|
|
125
|
+
const key = hash(token);
|
|
126
|
+
const s = all.get(key);
|
|
127
|
+
if (!s)
|
|
128
|
+
return null;
|
|
129
|
+
if (Date.now() - s.createdAt >= SESSION_TTL_MS) {
|
|
130
|
+
all.delete(key);
|
|
131
|
+
await save();
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
let ws = s.workspaces[workspaceId];
|
|
135
|
+
if (!ws)
|
|
136
|
+
return null;
|
|
137
|
+
if (Date.now() - ws.checkedAt >= recheckMs) {
|
|
138
|
+
await recheck(key, s, workspaceId);
|
|
139
|
+
ws = s.workspaces[workspaceId];
|
|
140
|
+
if (!ws)
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
return { user: s.user, role: ws.role };
|
|
144
|
+
}
|
|
145
|
+
function redirect(res, location, cookies = []) {
|
|
146
|
+
res.writeHead(302, { location, "cache-control": "no-store", ...(cookies.length ? { "set-cookie": cookies } : {}) });
|
|
147
|
+
res.end();
|
|
148
|
+
}
|
|
149
|
+
const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
|
150
|
+
/** A small page for what went wrong, with the way back in. */
|
|
151
|
+
function problem(res, status, title, text, retry) {
|
|
152
|
+
res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
153
|
+
res.end(`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>kraftwerk — sign in</title>` +
|
|
154
|
+
`<style>:root{color-scheme:light dark}body{font:16px/1.6 system-ui,sans-serif;max-width:560px;margin:60px auto;padding:0 16px}code{font-size:14px}a{color:#5b4bd5}</style>` +
|
|
155
|
+
`<h1>${esc(title)}</h1><p>${esc(text)}</p>${retry ? `<p><a href="${esc(retry)}">sign in again</a></p>` : ""}`);
|
|
156
|
+
}
|
|
157
|
+
/** A path on this origin to come back to: absolute, no scheme-relative trick. */
|
|
158
|
+
const safeNext = (raw, prefix) => (raw && raw.startsWith("/") && !raw.startsWith("//") && !raw.includes("\\") ? raw : `${prefix}/`);
|
|
159
|
+
/**
|
|
160
|
+
* /auth/signin, /auth/callback, /auth/signout for a `users: cloud`
|
|
161
|
+
* workspace. Returns false for any other path.
|
|
162
|
+
*/
|
|
163
|
+
export async function handleAuth(req, res, url, t) {
|
|
164
|
+
const route = url.pathname;
|
|
165
|
+
const signinPath = `${t.prefix}/auth/signin`;
|
|
166
|
+
if (route === "/auth/signin" && (req.method === "GET" || req.method === "HEAD")) {
|
|
167
|
+
if (!t.workspaceId) {
|
|
168
|
+
problem(res, 409, "This workspace has no id", "users: cloud signs people in to a workspace the cloud knows by its id. Add one with `kraftwerk doctor --fix` (it writes id: ws_… into kraftwerk.yml).");
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
const link = machineLink();
|
|
172
|
+
if (!link) {
|
|
173
|
+
problem(res, 503, "Signing in needs the kraftwerk cloud", "This workspace signs people in with their kraftwerk cloud account, and this machine is not connected to the cloud. Start the daemon (`kraftwerk daemon start`) and check `kraftwerk cloud`.", signinPath);
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
const host = req.headers.host ?? "localhost";
|
|
177
|
+
const state = randomBytes(24).toString("base64url");
|
|
178
|
+
const back = `http://${host}${t.prefix}/auth/callback`;
|
|
179
|
+
for (const [k, p] of pending)
|
|
180
|
+
if (Date.now() - p.at > STATE_TTL_MS)
|
|
181
|
+
pending.delete(k);
|
|
182
|
+
pending.set(state, { workspaceId: t.workspaceId, redirect: back, next: safeNext(url.searchParams.get("next"), t.prefix), at: Date.now() });
|
|
183
|
+
redirect(res, signinUrl(link.url, { workspace: t.workspaceId, machine: link.creds.id, redirect: back, state }), [cookie(STATE_COOKIE, state, STATE_TTL_MS / 1000)]);
|
|
184
|
+
return true;
|
|
185
|
+
}
|
|
186
|
+
if (route === "/auth/callback" && req.method === "GET") {
|
|
187
|
+
const state = url.searchParams.get("state") ?? "";
|
|
188
|
+
const code = url.searchParams.get("code") ?? "";
|
|
189
|
+
const p = pending.get(state);
|
|
190
|
+
if (!p || cookieOf(req, STATE_COOKIE) !== state || Date.now() - p.at > STATE_TTL_MS || p.workspaceId !== t.workspaceId) {
|
|
191
|
+
problem(res, 400, "This sign-in did not start here", "It was started in another browser, took longer than ten minutes, or was used already.", signinPath);
|
|
192
|
+
return true;
|
|
193
|
+
}
|
|
194
|
+
pending.delete(state);
|
|
195
|
+
const link = machineLink();
|
|
196
|
+
if (!link) {
|
|
197
|
+
problem(res, 503, "Signing in needs the kraftwerk cloud", "The machine lost its connection to the cloud meanwhile.", signinPath);
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
let r;
|
|
201
|
+
try {
|
|
202
|
+
r = await signinExchange(link.url, link.creds, code, p.redirect, link.version);
|
|
203
|
+
}
|
|
204
|
+
catch (err) {
|
|
205
|
+
problem(res, err instanceof CloudError && err.status >= 400 && err.status < 500 ? 403 : 502, "Signing in did not work", err.message, signinPath);
|
|
206
|
+
return true;
|
|
207
|
+
}
|
|
208
|
+
if (r.workspaceId !== p.workspaceId) {
|
|
209
|
+
problem(res, 400, "Signing in did not work", "The cloud answered for another workspace.", signinPath);
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
const all = await load();
|
|
213
|
+
// The same account signing in to another workspace on this origin keeps one session; anyone else starts afresh.
|
|
214
|
+
const old = cookieOf(req, USER_COOKIE);
|
|
215
|
+
let key = old ? hash(old) : "";
|
|
216
|
+
let token = old ?? "";
|
|
217
|
+
let s = key ? all.get(key) : undefined;
|
|
218
|
+
if (!s || s.user.id !== r.user.id) {
|
|
219
|
+
token = randomBytes(32).toString("base64url");
|
|
220
|
+
key = hash(token);
|
|
221
|
+
s = { user: r.user, createdAt: Date.now(), workspaces: {} };
|
|
222
|
+
all.set(key, s);
|
|
223
|
+
}
|
|
224
|
+
s.user = r.user;
|
|
225
|
+
s.workspaces[r.workspaceId] = { role: r.role, checkedAt: Date.now() };
|
|
226
|
+
await save();
|
|
227
|
+
log("info", "users", `${r.user.handle} (${r.user.email}) signed in to ${r.workspaceId}`);
|
|
228
|
+
redirect(res, p.next, [cookie(USER_COOKIE, token, SESSION_TTL_MS / 1000), cookie(STATE_COOKIE, "", 0)]);
|
|
229
|
+
return true;
|
|
230
|
+
}
|
|
231
|
+
if (route === "/auth/signout" && req.method === "POST") {
|
|
232
|
+
const token = cookieOf(req, USER_COOKIE);
|
|
233
|
+
// Out of this workspace; the cookie goes once the session holds no other (the path form shares one origin).
|
|
234
|
+
let empty = true;
|
|
235
|
+
if (token) {
|
|
236
|
+
const all = await load();
|
|
237
|
+
const key = hash(token);
|
|
238
|
+
const s = all.get(key);
|
|
239
|
+
if (s && t.workspaceId)
|
|
240
|
+
delete s.workspaces[t.workspaceId];
|
|
241
|
+
if (s && Object.keys(s.workspaces).length)
|
|
242
|
+
empty = false;
|
|
243
|
+
else
|
|
244
|
+
all.delete(key);
|
|
245
|
+
await save();
|
|
246
|
+
}
|
|
247
|
+
res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store", ...(empty ? { "set-cookie": cookie(USER_COOKIE, "", 0) } : {}) });
|
|
248
|
+
res.end(JSON.stringify({ ok: true, signin: signinPath }));
|
|
249
|
+
return true;
|
|
250
|
+
}
|
|
251
|
+
return false;
|
|
252
|
+
}
|
|
253
|
+
/** Forget every session in memory (tests: the next read loads the file again). */
|
|
254
|
+
export function forgetUserSessions() {
|
|
255
|
+
sessions = null;
|
|
256
|
+
loadedFrom = "";
|
|
257
|
+
pending.clear();
|
|
258
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netnodeag/kraftwerk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.97.0",
|
|
4
4
|
"description": "Open-source agentic workspace for teams — where people and AI agents get work done together: agents (Claude Code, Codex, Pi), skills, shared knowledge, repeatable workflows, and deterministic verification",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agents",
|
|
@@ -306,6 +306,14 @@
|
|
|
306
306
|
"description": "Deprecated and ignored: the cloud sets the heartbeat interval."
|
|
307
307
|
}
|
|
308
308
|
}
|
|
309
|
+
},
|
|
310
|
+
"users": {
|
|
311
|
+
"type": ["object", "null"],
|
|
312
|
+
"additionalProperties": false,
|
|
313
|
+
"description": "Who the people working in this workspace are. `local` (default): whoever sits at this machine, named by its handle (~/.kraftwerk/identity.json). `cloud`: people sign in with their kraftwerk cloud account before the UI opens, and what they do is signed with that account (uuid, handle) on every machine and clone. Needs the daemon connected to the cloud and the workspace's `id`; the machine's own CLI acts as the account that claimed the machine.",
|
|
314
|
+
"properties": {
|
|
315
|
+
"mode": { "type": "string", "enum": ["local", "cloud"], "description": "local (default) or cloud" }
|
|
316
|
+
}
|
|
309
317
|
}
|
|
310
318
|
}
|
|
311
319
|
}
|