@netnodeag/kraftwerk 0.95.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.
Files changed (83) hide show
  1. package/README.md +47 -7
  2. package/dist/acp.d.ts +31 -3
  3. package/dist/acp.js +63 -2
  4. package/dist/cli/boards.js +6 -5
  5. package/dist/cli/create-brief.js +2 -2
  6. package/dist/cli/daemon-login.d.ts +1 -1
  7. package/dist/cli/daemon-login.js +1 -1
  8. package/dist/cli/doctor.js +6 -3
  9. package/dist/cli/init.js +2 -0
  10. package/dist/cli/knowledge.js +9 -6
  11. package/dist/cli/presentations.js +8 -4
  12. package/dist/cli/projects.js +3 -3
  13. package/dist/client/index.d.ts +2 -0
  14. package/dist/client/index.js +3 -0
  15. package/dist/client/routes.d.ts +2 -0
  16. package/dist/client/routes.js +2 -0
  17. package/dist/config.d.ts +34 -0
  18. package/dist/config.js +28 -1
  19. package/dist/core/agents.js +1 -1
  20. package/dist/core/board-wake.d.ts +1 -1
  21. package/dist/core/boards.d.ts +1 -1
  22. package/dist/core/boards.js +10 -6
  23. package/dist/core/chat/acp.d.ts +6 -0
  24. package/dist/core/chat/acp.js +33 -7
  25. package/dist/core/chat/permissions.d.ts +2 -2
  26. package/dist/core/chat/permissions.js +4 -1
  27. package/dist/core/chat/pi.d.ts +12 -0
  28. package/dist/core/chat/pi.js +56 -5
  29. package/dist/core/chat/sessions.d.ts +13 -5
  30. package/dist/core/chat/sessions.js +34 -9
  31. package/dist/core/chat/types.d.ts +3 -1
  32. package/dist/core/cloud.d.ts +45 -0
  33. package/dist/core/cloud.js +35 -0
  34. package/dist/core/knowledge.d.ts +0 -7
  35. package/dist/core/knowledge.js +6 -6
  36. package/dist/core/person.d.ts +41 -0
  37. package/dist/core/person.js +47 -0
  38. package/dist/core/projects.d.ts +1 -1
  39. package/dist/core/projects.js +3 -2
  40. package/dist/harness.d.ts +3 -2
  41. package/dist/harnesses/acp.js +3 -1
  42. package/dist/harnesses/registry.js +2 -1
  43. package/dist/server/api/agents.js +2 -2
  44. package/dist/server/api/boards.js +1 -1
  45. package/dist/server/api/chats.d.ts +4 -1
  46. package/dist/server/api/chats.js +30 -12
  47. package/dist/server/api/cloud.d.ts +8 -0
  48. package/dist/server/api/index.d.ts +25 -3
  49. package/dist/server/api/presentations.js +2 -2
  50. package/dist/server/api/projects.d.ts +1 -1
  51. package/dist/server/api/projects.js +1 -1
  52. package/dist/server/api/router.js +5 -2
  53. package/dist/server/api/workspace.d.ts +14 -1
  54. package/dist/server/api/workspace.js +21 -1
  55. package/dist/server/cloud.d.ts +3 -0
  56. package/dist/server/cloud.js +20 -4
  57. package/dist/server/person.d.ts +9 -0
  58. package/dist/server/person.js +14 -0
  59. package/dist/server/server.js +60 -4
  60. package/dist/server/trust.d.ts +5 -1
  61. package/dist/server/users.d.ts +55 -0
  62. package/dist/server/users.js +258 -0
  63. package/package.json +1 -1
  64. package/schema/kraftwerk.schema.json +8 -0
  65. package/schema/workflow.schema.json +4 -3
  66. package/web/dist/assets/{dist--oB2_FQJ.js → dist-BD4ooe-Y.js} +1 -1
  67. package/web/dist/assets/{dist-WA1PTY07.js → dist-BduOHHOY.js} +1 -1
  68. package/web/dist/assets/{dist-CRqkyR9b.js → dist-BoajTxbz.js} +1 -1
  69. package/web/dist/assets/{dist-FlDPUw_l.js → dist-DGLb7wE6.js} +1 -1
  70. package/web/dist/assets/{dist-SHAE_oEQ.js → dist-DJACzcZZ.js} +1 -1
  71. package/web/dist/assets/{dist-SL9iU_p4.js → dist-DY6QplYX.js} +1 -1
  72. package/web/dist/assets/{dist-Tdda9sK7.js → dist-D_uWSMLk.js} +1 -1
  73. package/web/dist/assets/{dist-Ys1tb91R.js → dist-P7JCq9c3.js} +1 -1
  74. package/web/dist/assets/dist-ajNgHt2Q.js +1 -0
  75. package/web/dist/assets/{dist-BlxwNXF3.js → dist-lcPkaK4d.js} +1 -1
  76. package/web/dist/assets/{dist-DB33yOhN.js → dist-oRcLByHn.js} +1 -1
  77. package/web/dist/assets/{editor-Clx4xAh9.js → editor-hTceN7Iz.js} +3 -3
  78. package/web/dist/assets/index-BGgQaaA9.css +2 -0
  79. package/web/dist/assets/index-BOkjCxut.js +488 -0
  80. package/web/dist/index.html +2 -2
  81. package/web/dist/assets/dist-C3zyJ_nA.js +0 -1
  82. package/web/dist/assets/index-BJml45iw.js +0 -488
  83. package/web/dist/assets/index-CWopPK15.css +0 -2
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
  import * as z from "zod";
3
- import { absolutePath, resolveWorkspace, slugFromFolder, workspaceSlug } from "../../config.js";
3
+ import { absolutePath, resolveWorkspace, slugFromFolder, usersMode, workspaceSlug } from "../../config.js";
4
4
  import { disposeAllBackends } from "../../core/chat/sessions.js";
5
5
  import { cloudStatus } from "../cloud.js";
6
6
  import { workspaceRoot } from "../../core/context.js";
@@ -12,6 +12,7 @@ import { canSelfUpdate, startUpdate, updateStatus } from "../../core/update.js";
12
12
  import { getDiskVersion, getPkgName, getPkgVersion, RESTART_EXIT_CODE, supervised } from "../version.js";
13
13
  import { disposeAllDevs } from "../../core/vibeables.js";
14
14
  import { identityString, readIdentity } from "../../core/identity.js";
15
+ import { currentPerson, humanActor } from "../../core/person.js";
15
16
  import { fail, reply, route } from "./router.js";
16
17
  /** A feature block with a folder (repos, vibeables, projects); saveSettings checks the root. Nested blocks are plain objects: saveSettings reads only these fields. */
17
18
  const RootBlock = z.object({ enabled: z.boolean(), root: z.string().optional() });
@@ -126,6 +127,25 @@ export const workspaceRoutes = [
126
127
  const id = await readIdentity();
127
128
  return { handle: id.handle, machine: id.machine, identity: identityString(id), previous: id.previous };
128
129
  }),
130
+ // The person asking, in this workspace's users mode (kraftwerk.yml `users:`, core/person.ts).
131
+ route({ name: "me.get", method: "GET", path: "/api/me", summary: "who you are here: users mode (local | cloud), your handle, and with cloud your account (uuid, email) and how to sign out" }, async (c) => {
132
+ const ws = await resolveWorkspace(workspaceRoot()).catch(() => null);
133
+ const mode = ws ? usersMode(ws.config) : "local";
134
+ const p = await currentPerson();
135
+ const signedIn = c.trust.kind === "local" && !!c.trust.user;
136
+ return {
137
+ mode,
138
+ handle: p.handle,
139
+ actor: humanActor(p),
140
+ ...(p.id ? { id: p.id } : {}),
141
+ ...(p.email ? { email: p.email } : {}),
142
+ /** A browser signed in with its cloud account (users: cloud); false for this machine's own shell, a device, a member. */
143
+ signedIn,
144
+ ...(signedIn && c.trust.kind === "local" ? { role: c.trust.user.role } : {}),
145
+ /** How the signed-in person got here: through the relay as a member, or on this machine. */
146
+ via: c.trust.kind === "member" ? "member" : c.trust.kind === "device" ? "device" : "local",
147
+ };
148
+ }),
129
149
  route({ name: "settings.get", method: "GET", path: "/api/settings", summary: "kraftwerk.yml, parsed, with resolved paths" }, async () => getSettings()),
130
150
  route({ name: "settings.save", method: "PUT", path: "/api/settings", summary: "write the UI-editable subset of kraftwerk.yml", errors: 400, body: SettingsFields }, async (c) => saveSettings((await c.body()))),
131
151
  route({ name: "workspaces.list", method: "GET", path: "/api/workspaces", summary: "every known workspace incl. this one, with state and counts" }, async () => placeInHub(await listWorkspacesDetailed())),
@@ -44,6 +44,9 @@ export interface CloudStatus {
44
44
  machine?: string;
45
45
  /** Email of the account that claimed the machine; null while unclaimed. */
46
46
  account?: string | null;
47
+ /** That account's uuid and handle (what the machine's own shell acts as; ~/.kraftwerk/account.json). */
48
+ accountId?: string | null;
49
+ accountHandle?: string | null;
47
50
  /** Effective seconds between heartbeats (what the cloud asked for). */
48
51
  interval?: number;
49
52
  /** Last successful register or heartbeat. */
@@ -2,7 +2,7 @@ import { promises as fs } from "node:fs";
2
2
  import { log } from "../core/log.js";
3
3
  import os from "node:os";
4
4
  import { resolveWorkspace } from "../config.js";
5
- import { claimUrlFor, machineCloud, machineGoodbye, machineHeartbeat, machineRegister, machineUnlink, MAX_REPORTED_ROUTINES, retiredCloudDir, unknownMachine, workspaceInvite, } from "../core/cloud.js";
5
+ import { claimUrlFor, machineCloud, machineGoodbye, machineHeartbeat, machineRegister, machineUnlink, MAX_REPORTED_ROUTINES, retiredCloudDir, unknownMachine, workspaceInvite, writeAccountFile, } from "../core/cloud.js";
6
6
  import { identityString, readIdentity } from "../core/identity.js";
7
7
  import { routineReport } from "../core/routines.js";
8
8
  import { machineCredentials } from "./relay.js";
@@ -47,6 +47,19 @@ async function entries(withRoots) {
47
47
  return { list, ymlUrls };
48
48
  }
49
49
  const claimed = () => typeof m.status.account === "string" && m.status.account.length > 0;
50
+ /**
51
+ * Keep ~/.kraftwerk/account.json in step with the claim: the account the
52
+ * cloud names (uuid, email, handle), or none once unclaimed. A cloud that
53
+ * names no uuid (older) leaves the file as it is.
54
+ */
55
+ async function noteAccount(r) {
56
+ if (r.account === undefined)
57
+ return;
58
+ if (!r.account)
59
+ return writeAccountFile(null);
60
+ if (r.accountId && r.accountHandle)
61
+ await writeAccountFile({ id: r.accountId, email: r.account, handle: r.accountHandle }).catch(() => { });
62
+ }
50
63
  /** The routines that ran here, per served workspace with a ws_ id (vetoed ones left out), capped. */
51
64
  async function routineEntries() {
52
65
  const out = [];
@@ -112,8 +125,9 @@ async function register() {
112
125
  m.routines = "";
113
126
  // An unclaimed register carries no roots: the list counts as reported only when that is all the cloud should know.
114
127
  m.reported = r.account ? "" : JSON.stringify(list);
128
+ await noteAccount(r);
115
129
  m.status = {
116
- ...base, state: "connected", account: r.account ?? null, interval: r.interval || DEFAULT_INTERVAL, lastSeen: new Date().toISOString(),
130
+ ...base, state: "connected", account: r.account ?? null, accountId: r.accountId ?? null, accountHandle: r.accountHandle ?? null, interval: r.interval || DEFAULT_INTERVAL, lastSeen: new Date().toISOString(),
117
131
  claimCode: r.claimCode ?? null, claimUrl: claimUrlFor(cloud.url, r.claimCode), workspaces: list.length,
118
132
  };
119
133
  // Already claimed: the roots follow at once.
@@ -144,9 +158,10 @@ async function heartbeat() {
144
158
  });
145
159
  m.reported = now;
146
160
  m.routines = ran;
161
+ await noteAccount(r);
147
162
  m.status = {
148
163
  ...m.status, state: "connected", error: undefined, interval: r.interval || m.status.interval || DEFAULT_INTERVAL, lastSeen: new Date().toISOString(),
149
- ...(r.account !== undefined ? { account: r.account } : {}),
164
+ ...(r.account !== undefined ? { account: r.account, accountId: r.accountId ?? null, accountHandle: r.accountHandle ?? null } : {}),
150
165
  ...(r.claimCode !== undefined ? { claimCode: r.claimCode, claimUrl: claimUrlFor(m.status.url, r.claimCode) } : {}),
151
166
  workspaces: list.length,
152
167
  };
@@ -259,7 +274,8 @@ export async function unlinkMachineCloud() {
259
274
  // The next heartbeat sends the list again — without roots now.
260
275
  m.reported = "";
261
276
  m.routines = "";
262
- m.status = { ...m.status, account: null, claimCode: r.claimCode ?? null, claimUrl: claimUrlFor(m.status.url, r.claimCode) };
277
+ await writeAccountFile(null);
278
+ m.status = { ...m.status, account: null, accountId: null, accountHandle: null, claimCode: r.claimCode ?? null, claimUrl: claimUrlFor(m.status.url, r.claimCode) };
263
279
  return m.status;
264
280
  });
265
281
  }
@@ -0,0 +1,9 @@
1
+ import { type Person } from "../core/person.js";
2
+ import type { Trust } from "./trust.js";
3
+ /**
4
+ * The person behind a caller (core/person.ts): the account a browser signed
5
+ * in with (`users: cloud`), a remote member as the cloud vouched for them,
6
+ * else this machine's person — a paired device, this machine's own shell,
7
+ * any request in a `users: local` workspace.
8
+ */
9
+ export declare function personOf(trust: Trust): Promise<Person>;
@@ -0,0 +1,14 @@
1
+ import { machinePerson } from "../core/person.js";
2
+ /**
3
+ * The person behind a caller (core/person.ts): the account a browser signed
4
+ * in with (`users: cloud`), a remote member as the cloud vouched for them,
5
+ * else this machine's person — a paired device, this machine's own shell,
6
+ * any request in a `users: local` workspace.
7
+ */
8
+ export async function personOf(trust) {
9
+ if (trust.kind === "local" && trust.user)
10
+ return { handle: trust.user.user.handle, id: trust.user.user.id, email: trust.user.user.email };
11
+ if (trust.kind === "member")
12
+ return { handle: trust.member.handle, email: trust.member.email };
13
+ return machinePerson();
14
+ }
@@ -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 trust = await trustOf(req, url, trustOpts);
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 trust = await trustOf(req, url, trustOpts, true);
305
- if (trust.kind === "none")
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
- runInHub(hub, () => serveSocket(conn, resolve, version, trust, () => trustOf(req, url, trustOpts, true), hub));
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));
@@ -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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[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.95.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
  }
@@ -37,7 +37,7 @@
37
37
  "cli",
38
38
  "acp"
39
39
  ],
40
- "description": "How agents are driven: cli (default) spawns the harness CLI per phase; acp keeps one Agent Client Protocol adapter (bundled claude-agent-acp / codex-acp, no CLI needed) alive for the run. Per-agent `protocol` overrides. runs-on: pi has no adapter."
40
+ "description": "How agents are driven: cli (default) spawns the harness CLI per phase; acp keeps one Agent Client Protocol adapter (bundled claude-agent-acp / codex-acp, no CLI needed) alive for the run. Per-agent `protocol` overrides. runs-on: pi has no adapter; antigravity (agy acp, needs the agy CLI) has only the adapter."
41
41
  },
42
42
  "mcp": {
43
43
  "type": "object",
@@ -117,9 +117,10 @@
117
117
  "enum": [
118
118
  "claude",
119
119
  "codex",
120
- "pi"
120
+ "pi",
121
+ "antigravity"
121
122
  ],
122
- "description": "Harness that executes this agent (default: claude)"
123
+ "description": "Harness that executes this agent (default: claude). antigravity always runs over the agent protocol (agy acp)."
123
124
  },
124
125
  "protocol": {
125
126
  "enum": [