@netnodeag/kraftwerk 0.102.0 → 0.103.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 CHANGED
@@ -566,6 +566,28 @@ machine (*Install on a machine*). Running it again on a folder that holds the
566
566
  workspace just opens it. `POST /api/cloud/join {link, cwd, dir?}` on the
567
567
  daemon does the work.
568
568
 
569
+ #### Run in the cloud: a sandbox on kraftwerk cloud
570
+
571
+ A workspace can also run on kraftwerk cloud itself: *Run in the cloud →
572
+ Launch* on its page there. The cloud starts a sandbox (a container with
573
+ kraftwerk's daemon), and that daemon does the same `kraftwerk join` as a
574
+ laptop would. Afterwards it is one more machine of the workspace: kraftwerk
575
+ sync, remote boards, and agents working cloud board tasks while no laptop
576
+ is on.
577
+
578
+ - **Reaching it.** People open its UI on an origin of its own
579
+ (`https://<id>.run.…`), which the cloud forwards to the daemon.
580
+ - **Sandbox mode.** The cloud sets `KRAFTWERK_PUBLIC_ORIGIN` to that
581
+ origin, and the daemon then runs in sandbox mode (`server/sandbox.ts`):
582
+ - Everyone coming in from outside signs in with their cloud account,
583
+ whatever `users:` says, browser or not. The sign-in returns to the
584
+ public origin, starting at the cloud as the browser reaches it
585
+ (`KRAFTWERK_PUBLIC_CLOUD_URL`, set when the sandbox reaches the cloud at
586
+ another address).
587
+ - A Host without a workspace in it reaches the sandbox's one workspace.
588
+ - Only what runs inside the sandbox on loopback (its agents' CLI) is the
589
+ machine's own shell.
590
+
569
591
  ### kraftwerk sync: the workspace's files in the cloud
570
592
 
571
593
  In cloud mode a workspace's history can live in its own repository in
@@ -68,6 +68,8 @@ export interface MachineWorkspace {
68
68
  name: string;
69
69
  slug: string;
70
70
  root?: string;
71
+ /** Who hosts its git remote: kraftwerk sync, an own provider ("custom"), or none yet. */
72
+ git?: "kraftwerk" | "custom" | "none";
71
73
  }
72
74
  export interface Credentials {
73
75
  id: string;
@@ -128,6 +128,8 @@ export declare function remoteAuthEnv(base?: NodeJS.ProcessEnv): NodeJS.ProcessE
128
128
  export declare const literal: (p: string) => string;
129
129
  /** Repo root for a directory, or null when it is not inside a git repo. */
130
130
  export declare function repoRootFor(dir: string): Promise<string | null>;
131
+ /** The workspace's remote URL (its git block's remote), credentials cut out; undefined without git, a repo or that remote. */
132
+ export declare function gitRemoteUrl(): Promise<string | undefined>;
131
133
  /** Label for a porcelain code, using whichever half is set. */
132
134
  export declare function label(code: string): string;
133
135
  /** Parse `git status --porcelain=v1 -z`, which NUL-separates and doubles up on renames and copies. */
package/dist/core/git.js CHANGED
@@ -219,6 +219,14 @@ async function openRepo() {
219
219
  return { cfg, error: `${project.root} is not inside a git repository.` };
220
220
  return { repo: { cfg, project, repoRoot } };
221
221
  }
222
+ /** The workspace's remote URL (its git block's remote), credentials cut out; undefined without git, a repo or that remote. */
223
+ export async function gitRemoteUrl() {
224
+ const { repo } = await openRepo();
225
+ if (!repo)
226
+ return undefined;
227
+ const r = await git(["remote", "get-url", repo.cfg.remote], repo.repoRoot);
228
+ return r.ok && r.stdout.trim() ? withoutCredentials(r.stdout.trim()) : undefined;
229
+ }
222
230
  /**
223
231
  * The checked-out branch, or why it cannot be synced: a detached HEAD, or a
224
232
  * configured branch that is not the one checked out. Without the second
@@ -1,11 +1,5 @@
1
1
  import * as z from "zod";
2
2
  import { type GitStatus } from "../../core/git.js";
3
- /**
4
- * Who hosts the workspace's remote: kraftwerk sync is the workspace's own
5
- * repo in kraftwerk cloud, `<cloud>/git/<id>.git` (the cloud's host when this
6
- * machine knows it); anything else is an own git provider.
7
- */
8
- export declare function hostingOf(remoteUrl: string | undefined): Promise<NonNullable<GitStatus["hosting"]>>;
9
3
  /** The workspace's own git, and the repositories cloned under its repos root. */
10
4
  export declare const gitRoutes: (import("./router.js").Route<"git.commit", import("./router.js").Reply<{
11
5
  ok: boolean;
@@ -2,7 +2,7 @@ import * as z from "zod";
2
2
  import { resolveWorkspace } from "../../config.js";
3
3
  import { workspaceRoot } from "../../core/context.js";
4
4
  import { gitCommit, gitDiff, gitFetch, gitPull, gitPush, gitStatus } from "../../core/git.js";
5
- import { cloudStatus } from "../cloud.js";
5
+ import { hostingFor } from "../cloud.js";
6
6
  import { setupSync } from "../sync-setup.js";
7
7
  import { addRepo, listRepos, openRepos, removeRepo, repoCommitDiff, repoDetail, repoDiff, updateRepo } from "../../core/repos.js";
8
8
  import { fail, reply, route, statusByMessage } from "./router.js";
@@ -12,30 +12,9 @@ const conflictUnlessOk = (result) => reply(result.ok ? 200 : 409, result);
12
12
  const Commit = z.object({ paths: z.array(z.string()).default([]), message: z.string().default("") });
13
13
  /** A clone to add; url, name, branch and depth are checked by addRepo. */
14
14
  const AddRepo = z.object({ url: z.string().default(""), name: z.string().optional(), branch: z.string().optional(), depth: z.number().optional() });
15
- /**
16
- * Who hosts the workspace's remote: kraftwerk sync is the workspace's own
17
- * repo in kraftwerk cloud, `<cloud>/git/<id>.git` (the cloud's host when this
18
- * machine knows it); anything else is an own git provider.
19
- */
20
- export async function hostingOf(remoteUrl) {
21
- if (!remoteUrl)
22
- return "none";
23
- const id = (await resolveWorkspace(workspaceRoot()).catch(() => null))?.config.id;
24
- let u;
25
- try {
26
- u = new URL(remoteUrl);
27
- }
28
- catch {
29
- return "custom"; // scp-like ssh (git@host:path) — never kraftwerk sync
30
- }
31
- const cloud = cloudStatus().url;
32
- const sameHost = !cloud || (() => { try {
33
- return new URL(cloud).host === u.host;
34
- }
35
- catch {
36
- return false;
37
- } })();
38
- return id && sameHost && u.pathname.replace(/\/+$/, "") === `/git/${encodeURIComponent(id)}.git` ? "kraftwerk" : "custom";
15
+ /** Who hosts the workspace's remote (server/cloud.ts). */
16
+ async function hostingOf(remoteUrl) {
17
+ return hostingFor((await resolveWorkspace(workspaceRoot()).catch(() => null))?.config.id, remoteUrl);
39
18
  }
40
19
  /** The workspace's own git, and the repositories cloned under its repos root. */
41
20
  export const gitRoutes = [
@@ -1,4 +1,5 @@
1
1
  import { type Credentials, type CloudUrlSource, type InviteResponse } from "../core/cloud.js";
2
+ import { type GitStatus } from "../core/git.js";
2
3
  /**
3
4
  * The machine client: the daemon registers THIS MACHINE with the kraftwerk
4
5
  * cloud once and heartbeats while it runs; the workspaces it serves ride
@@ -68,6 +69,12 @@ export type WorkspaceSource = () => Array<{
68
69
  };
69
70
  }>;
70
71
  export declare const cloudStatus: () => CloudStatus;
72
+ /**
73
+ * Who hosts a workspace's remote: kraftwerk sync is the workspace's own repo
74
+ * in kraftwerk cloud, `<cloud>/git/<id>.git` (the cloud's host when this
75
+ * machine knows it); anything else is an own git provider.
76
+ */
77
+ export declare function hostingFor(id: string | undefined, remoteUrl: string | undefined): NonNullable<GitStatus["hosting"]>;
71
78
  /**
72
79
  * Start the machine client (the daemon, once its workspaces are open).
73
80
  * Resolves after the first registration attempt; the heartbeat runs on its
@@ -6,7 +6,7 @@ import { claimUrlFor, machineCloud, machineGoodbye, machineHeartbeat, machineReg
6
6
  import { identityString, readIdentity } from "../core/identity.js";
7
7
  import { routineReport } from "../core/routines.js";
8
8
  import { machineCredentials } from "./relay.js";
9
- import { setRemoteAuth, setSyncAuthor } from "../core/git.js";
9
+ import { gitRemoteUrl, setRemoteAuth, setSyncAuthor } from "../core/git.js";
10
10
  import { installCloudEvents } from "./cloud-events.js";
11
11
  const DEFAULT_INTERVAL = 60;
12
12
  const STANDALONE = { url: "", state: "off", reason: "only the daemon registers this machine with the cloud (`kraftwerk daemon start`)" };
@@ -35,6 +35,40 @@ function serial(fn) {
35
35
  return run;
36
36
  }
37
37
  export const cloudStatus = () => m.status;
38
+ /**
39
+ * Who hosts a workspace's remote: kraftwerk sync is the workspace's own repo
40
+ * in kraftwerk cloud, `<cloud>/git/<id>.git` (the cloud's host when this
41
+ * machine knows it); anything else is an own git provider.
42
+ */
43
+ export function hostingFor(id, remoteUrl) {
44
+ if (!remoteUrl)
45
+ return "none";
46
+ let u;
47
+ try {
48
+ u = new URL(remoteUrl);
49
+ }
50
+ catch {
51
+ return "custom"; // scp-like ssh (git@host:path) — never kraftwerk sync
52
+ }
53
+ const cloud = m.status.url;
54
+ const sameHost = !cloud || (() => { try {
55
+ return new URL(cloud).host === u.host;
56
+ }
57
+ catch {
58
+ return false;
59
+ } })();
60
+ return id && sameHost && u.pathname.replace(/\/+$/, "") === `/git/${encodeURIComponent(id)}.git` ? "kraftwerk" : "custom";
61
+ }
62
+ /** A served workspace's git hosting, told to the cloud so it shows kraftwerk sync only where it is used; undefined when it cannot tell. */
63
+ async function hostingOfServed(id, ws) {
64
+ if (!ws)
65
+ return undefined;
66
+ const run = ws.run.bind(ws);
67
+ return Promise.resolve()
68
+ .then(() => run(() => gitRemoteUrl()))
69
+ .then((url) => hostingFor(id, url))
70
+ .catch(() => undefined); // a workspace closing meanwhile: nothing said
71
+ }
38
72
  /** The open workspaces as the cloud lists them: vetoed ones left out, roots only once claimed. */
39
73
  async function entries(withRoots) {
40
74
  const list = [];
@@ -46,7 +80,8 @@ async function entries(withRoots) {
46
80
  continue;
47
81
  if (c?.url)
48
82
  ymlUrls.push(c.url.replace(/\/+$/, ""));
49
- list.push({ ...(ws?.config.id ? { id: ws.config.id } : {}), name: o.name, slug: o.slug, ...(withRoots ? { root: o.root } : {}) });
83
+ const git = await hostingOfServed(ws?.config.id, o.ws);
84
+ list.push({ ...(ws?.config.id ? { id: ws.config.id } : {}), name: o.name, slug: o.slug, ...(withRoots ? { root: o.root } : {}), ...(git ? { git } : {}) });
50
85
  }
51
86
  return { list, ymlUrls };
52
87
  }
@@ -7,6 +7,7 @@ import { git, NET_TIMEOUT, remoteAuthEnv } from "../core/git.js";
7
7
  import { ApiError } from "./api/router.js";
8
8
  import { applyMachineCloud, cloudStatus, machineLink, syncMachineCloud } from "./cloud.js";
9
9
  import { currentHub } from "./hub-context.js";
10
+ import { sandboxOrigin } from "./sandbox.js";
10
11
  import { issueHandoff } from "./users.js";
11
12
  /** `<origin>/join/<code>` or a bare code (this machine's cloud). */
12
13
  export function parseJoinLink(raw) {
@@ -97,9 +98,10 @@ export async function joinWorkspace(link, dirIn, cwd) {
97
98
  const o = await currentHub().open(root);
98
99
  // The cloud learns the workspace is here now (its host list, sign-in).
99
100
  await syncMachineCloud().catch(() => { });
100
- // Signed in at once: the link proved the account (server/users.ts issueHandoff).
101
+ // Signed in at once: the link proved the account (server/users.ts issueHandoff). Not in a sandbox the
102
+ // cloud runs (server/sandbox.ts): nobody opens a browser there, and the link would only sit in its log.
101
103
  const accountId = cloudStatus().accountId;
102
- const token = accountId ? await issueHandoff(joined.workspaceId, accountId) : null;
104
+ const token = accountId && !sandboxOrigin() ? await issueHandoff(joined.workspaceId, accountId) : null;
103
105
  return {
104
106
  workspace: { id: joined.workspaceId, name: joined.workspaceName, slug: o.slug, url: o.url },
105
107
  ...(token ? { signin: `${o.url}/auth/handoff?t=${token}` } : {}),
@@ -0,0 +1,9 @@
1
+ import type http from "node:http";
2
+ /** The public origin, when this daemon is a sandbox; read each time (tests set it). */
3
+ export declare function sandboxOrigin(): URL | null;
4
+ /** Where the browser signs in: the cloud as people reach it. */
5
+ export declare const browserCloudUrl: (machineCloudUrl: string) => string;
6
+ /** The request came in on the public origin (through the cloud). */
7
+ export declare function viaPublicOrigin(req: http.IncomingMessage): boolean;
8
+ /** A sandbox, and this request is from outside it: a person, who signs in. */
9
+ export declare function fromOutside(req: http.IncomingMessage): boolean;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * A daemon that kraftwerk cloud runs for a workspace — "launch" on the
3
+ * platform: the cloud starts a sandbox (a container or microVM) on its own
4
+ * hardware with this daemon in it, which joins the workspace like any other
5
+ * machine (`kraftwerk join`). People reach its UI through the cloud, which
6
+ * forwards a public origin of the sandbox's own (e.g.
7
+ * https://<id>.run.kraftwerk-cloud…) here with the Host as the browser sent it.
8
+ *
9
+ * KRAFTWERK_PUBLIC_ORIGIN that origin; set, the daemon is a sandbox
10
+ * KRAFTWERK_PUBLIC_CLOUD_URL the cloud as the browser reaches it, when the
11
+ * sandbox reaches it at another address (locally:
12
+ * host.docker.internal) — the sign-in goes there
13
+ *
14
+ * In a sandbox, everyone arriving from outside is a person who signs in with
15
+ * their cloud account — whatever the workspace's `users:` says, and whether
16
+ * or not the request looks like a browser (users.ts fromBrowser lets the
17
+ * machine's own scripts through; here the network is not the machine's).
18
+ * Only what runs inside the sandbox itself (its agents' CLI, on loopback)
19
+ * is the machine. A request without a workspace in its Host reaches the
20
+ * sandbox's one workspace.
21
+ */
22
+ const LOOPBACK_PEER = /^(127\.|::1$|::ffff:127\.)/;
23
+ /** The public origin, when this daemon is a sandbox; read each time (tests set it). */
24
+ export function sandboxOrigin() {
25
+ const raw = process.env.KRAFTWERK_PUBLIC_ORIGIN?.trim();
26
+ if (!raw)
27
+ return null;
28
+ try {
29
+ const u = new URL(raw);
30
+ return u.protocol === "http:" || u.protocol === "https:" ? u : null;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ /** Where the browser signs in: the cloud as people reach it. */
37
+ export const browserCloudUrl = (machineCloudUrl) => sandboxOrigin() && process.env.KRAFTWERK_PUBLIC_CLOUD_URL?.trim() ? process.env.KRAFTWERK_PUBLIC_CLOUD_URL.trim().replace(/\/+$/, "") : machineCloudUrl;
38
+ /** The request came in on the public origin (through the cloud). */
39
+ export function viaPublicOrigin(req) {
40
+ const o = sandboxOrigin();
41
+ return !!o && String(req.headers.host ?? "").toLowerCase() === o.host.toLowerCase();
42
+ }
43
+ /** A sandbox, and this request is from outside it: a person, who signs in. */
44
+ export function fromOutside(req) {
45
+ if (!sandboxOrigin())
46
+ return false;
47
+ return viaPublicOrigin(req) || !LOOPBACK_PEER.test(req.socket.remoteAddress ?? "");
48
+ }
@@ -23,6 +23,7 @@ import { MIME } from "./api/mime.js";
23
23
  import { getPkgVersion, RESTART_EXIT_CODE } from "./version.js";
24
24
  import { trustOf } from "./trust.js";
25
25
  import { fromBrowser, handleAuth, signedIn } from "./users.js";
26
+ import { fromOutside, sandboxOrigin } from "./sandbox.js";
26
27
  import { configAt, usersMode } from "../config.js";
27
28
  import { targetOf } from "./target.js";
28
29
  import { isDir, resolveWorkspace, workspaceSlug } from "../config.js";
@@ -248,7 +249,8 @@ async function cloudUsers(open, prefix) {
248
249
  if (!open)
249
250
  return undefined;
250
251
  const config = await configAt(open.root);
251
- if (usersMode(config) !== "cloud")
252
+ // A sandbox's UI is reached from the internet (server/sandbox.ts): people sign in there, whatever `users:` says.
253
+ if (usersMode(config) !== "cloud" && !sandboxOrigin())
252
254
  return undefined;
253
255
  return { workspaceId: config.id, name: open.name, prefix };
254
256
  }
@@ -260,7 +262,7 @@ async function cloudUsers(open, prefix) {
260
262
  * and remote members have their own credentials.
261
263
  */
262
264
  async function withUser(req, trust, cu) {
263
- if (!cu || trust.kind !== "local" || !fromBrowser(req))
265
+ if (!cu || trust.kind !== "local" || !(fromBrowser(req) || fromOutside(req)))
264
266
  return { trust };
265
267
  const user = cu.workspaceId ? await signedIn(req, cu.workspaceId) : null;
266
268
  return user ? { trust: { kind: "local", user } } : { trust, signin: true };
@@ -278,7 +280,7 @@ export async function startHub(opts) {
278
280
  const version = await getPkgVersion();
279
281
  installExitHandlers();
280
282
  /** Which open workspace a request is for: its slug, else the port it came in on, else the default. */
281
- const pick = (target, portDefault) => target.slug !== undefined ? bySlug.get(target.slug) : portDefault;
283
+ const pick = (target, portDefault) => target.slug !== undefined ? bySlug.get(target.slug) : (portDefault ?? (sandboxOrigin() && bySlug.size === 1 ? [...bySlug.values()][0] : undefined));
282
284
  const handler = (portDefault) => async (req, res) => {
283
285
  try {
284
286
  if (!hostAllowed(req))
@@ -5,6 +5,7 @@ import path from "node:path";
5
5
  import { CloudError, signinExchange, signinUrl, signinVerify } from "../core/cloud.js";
6
6
  import { log } from "../core/log.js";
7
7
  import { machineLink } from "./cloud.js";
8
+ import { browserCloudUrl, sandboxOrigin, viaPublicOrigin } from "./sandbox.js";
8
9
  /**
9
10
  * People signing in to a workspace's UI — kraftwerk.yml `users: cloud`.
10
11
  *
@@ -109,7 +110,7 @@ export function cookieOf(req, name) {
109
110
  .find((x) => x.startsWith(`${name}=`));
110
111
  return c ? decodeURIComponent(c.slice(name.length + 1)) : undefined;
111
112
  }
112
- const cookie = (name, value, maxAgeS) => `${name}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeS}`;
113
+ const cookie = (name, value, maxAgeS) => `${name}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeS}${sandboxOrigin()?.protocol === "https:" ? "; Secure" : ""}`;
113
114
  /**
114
115
  * Whether the request comes from a browser. Browsers say where a fetch came
115
116
  * from (Sec-Fetch-Site, -Dest) and call themselves Mozilla/…; Node's fetch
@@ -205,12 +206,13 @@ export async function handleAuth(req, res, url, t) {
205
206
  }
206
207
  const host = req.headers.host ?? "localhost";
207
208
  const state = randomBytes(24).toString("base64url");
208
- const back = `http://${host}${t.prefix}/auth/callback`;
209
+ // A sandbox (server/sandbox.ts) is reached on its public origin, through the cloud.
210
+ const back = viaPublicOrigin(req) ? `${sandboxOrigin().origin}${t.prefix}/auth/callback` : `http://${host}${t.prefix}/auth/callback`;
209
211
  for (const [k, p] of pending)
210
212
  if (Date.now() - p.at > STATE_TTL_MS)
211
213
  pending.delete(k);
212
214
  pending.set(state, { workspaceId: t.workspaceId, redirect: back, next: safeNext(url.searchParams.get("next"), t.prefix), at: Date.now() });
213
- redirect(res, signinUrl(link.url, { workspace: t.workspaceId, machine: link.creds.id, redirect: back, state }), [cookie(STATE_COOKIE, state, STATE_TTL_MS / 1000)]);
215
+ redirect(res, signinUrl(browserCloudUrl(link.url), { workspace: t.workspaceId, machine: link.creds.id, redirect: back, state }), [cookie(STATE_COOKIE, state, STATE_TTL_MS / 1000)]);
214
216
  return true;
215
217
  }
216
218
  if (route === "/auth/handoff" && req.method === "GET") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netnodeag/kraftwerk",
3
- "version": "0.102.0",
3
+ "version": "0.103.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",