@netnodeag/kraftwerk 0.105.0 → 0.106.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.
@@ -86,8 +86,10 @@ export declare const ROUTES: {
86
86
  readonly "files.scopes": readonly ["GET", "/api/files"];
87
87
  readonly "files.upload": readonly ["POST", "/api/files/upload", "upload"];
88
88
  readonly "git.commit": readonly ["POST", "/api/git/commit"];
89
+ readonly "git.commitDiff": readonly ["GET", "/api/git/commits/:hash"];
89
90
  readonly "git.diff": readonly ["GET", "/api/git/diff"];
90
91
  readonly "git.fetch": readonly ["POST", "/api/git/fetch"];
92
+ readonly "git.log": readonly ["GET", "/api/git/log"];
91
93
  readonly "git.pull": readonly ["POST", "/api/git/pull"];
92
94
  readonly "git.push": readonly ["POST", "/api/git/push"];
93
95
  readonly "git.setupSync": readonly ["POST", "/api/git/sync-setup"];
@@ -87,8 +87,10 @@ export const ROUTES = {
87
87
  "files.scopes": ["GET", "/api/files"],
88
88
  "files.upload": ["POST", "/api/files/upload", "upload"],
89
89
  "git.commit": ["POST", "/api/git/commit"],
90
+ "git.commitDiff": ["GET", "/api/git/commits/:hash"],
90
91
  "git.diff": ["GET", "/api/git/diff"],
91
92
  "git.fetch": ["POST", "/api/git/fetch"],
93
+ "git.log": ["GET", "/api/git/log"],
92
94
  "git.pull": ["POST", "/api/git/pull"],
93
95
  "git.push": ["POST", "/api/git/push"],
94
96
  "git.setupSync": ["POST", "/api/git/sync-setup"],
@@ -52,6 +52,28 @@ export interface GitFile {
52
52
  /** Why it cannot be selected, when it cannot. */
53
53
  reason?: string;
54
54
  }
55
+ /** One commit in a log. */
56
+ export interface GitCommit {
57
+ hash: string;
58
+ short: string;
59
+ subject: string;
60
+ author: string;
61
+ committedAt: string;
62
+ /** On no remote yet: this machine's own work. */
63
+ local: boolean;
64
+ }
65
+ /** The workspace's history: the newest commits that touched its paths, the unpushed ones marked. */
66
+ export interface GitLog {
67
+ commits: GitCommit[];
68
+ error?: string;
69
+ }
70
+ /** One .gitignore: where it is (repo-relative) and its rules — comments and blank lines left out. */
71
+ export interface GitIgnoreFile {
72
+ path: string;
73
+ rules: string[];
74
+ /** Rules left out because the list was capped. */
75
+ more?: number;
76
+ }
55
77
  export interface GitStatus {
56
78
  enabled: boolean;
57
79
  /** Set when the feature is on but the repo cannot be used. */
@@ -93,6 +115,8 @@ export interface GitStatus {
93
115
  * someone deletes the copy. Newest first.
94
116
  */
95
117
  conflicts?: SyncConflict[];
118
+ /** The repo's .gitignore files with their rules, the root's first: what git leaves out, and so what never syncs. */
119
+ ignores?: GitIgnoreFile[];
96
120
  }
97
121
  /** One file both sides changed: the remote's version is at `path`, the other side's at `copy`, kept for `by`. */
98
122
  export interface SyncConflict {
@@ -145,6 +169,20 @@ export declare function parseStatus(out: string): {
145
169
  /** A remote URL fit to show: `https://user:secret@host/x` → `https://host/x`. */
146
170
  export declare function withoutCredentials(url: string): string;
147
171
  export declare function gitStatus(fresh?: boolean): Promise<GitStatus>;
172
+ /** The newest `n` commits of the repo at `dir` (those touching `pathspecs`, when given), the ones on no remote marked. */
173
+ export declare function commitLog(dir: string, n: number, pathspecs?: string[]): Promise<GitCommit[]>;
174
+ /**
175
+ * One commit as a patch: header, stat, then the diff. The commit's own path
176
+ * list decides what is shown: a path that is not (`hidden` gives the reason
177
+ * — by default a secret or key: a committed key, a renamed-in .env) is left
178
+ * out of both the stat and the patch by pathspec, so no header shape git
179
+ * emits can smuggle it through.
180
+ */
181
+ export declare function commitPatch(dir: string, hash: string, hidden?: (file: string) => string | undefined): Promise<GitDiff>;
182
+ /** The workspace's history: the newest commits that touched its paths, whoever made them — by hand here, kraftwerk sync, another machine. */
183
+ export declare function gitLog(): Promise<GitLog>;
184
+ /** One commit of the workspace's history as a patch, the files outside the workspace paths (and secrets) left out. */
185
+ export declare function gitCommitDiff(hash: string): Promise<GitDiff>;
148
186
  /**
149
187
  * Unified diff for one changed file. Reading is as sensitive as writing
150
188
  * here: this endpoint has no auth of its own, and a diff of an untracked
package/dist/core/git.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { createWriteStream, existsSync, realpathSync, statSync } from "node:fs";
2
+ import { createWriteStream, existsSync, promises as fsp, realpathSync, statSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { boardsRootFor, presentationsRootFor, ENTITY_KINDS, entitiesRootFor, projectsRootFor, reposRootFor, resolveWorkspace, vibeablesRootFor, isSafeGitName } from "../config.js";
5
5
  import { ENV_FILE } from "../runner/docker.js";
@@ -56,6 +56,27 @@ export const DENY = [
56
56
  /(^|\/)credentials\.json$/,
57
57
  ];
58
58
  const DEFAULTS = { remote: "origin", interval: 300, autosync: "pull" };
59
+ const MAX_IGNORE_FILES = 30;
60
+ const MAX_IGNORE_RULES = 200;
61
+ /** Every .gitignore git itself reads in the repo (tracked or not, none inside an ignored folder), the root's first. */
62
+ async function ignoreFiles(repoRoot) {
63
+ const ls = await git(["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ":(glob)**/.gitignore"], repoRoot);
64
+ if (!ls.ok)
65
+ return [];
66
+ const paths = [...new Set(ls.stdout.split("\0").filter(Boolean))].sort((a, b) => a.split("/").length - b.split("/").length || a.localeCompare(b)).slice(0, MAX_IGNORE_FILES);
67
+ const out = [];
68
+ for (const rel of paths) {
69
+ const text = await fsp.readFile(path.join(repoRoot, rel), "utf8").catch(() => null);
70
+ if (text === null)
71
+ continue;
72
+ const rules = text
73
+ .split(/\r?\n/)
74
+ .map((l) => l.trim())
75
+ .filter((l) => l && !l.startsWith("#"));
76
+ out.push({ path: rel, rules: rules.slice(0, MAX_IGNORE_RULES), ...(rules.length > MAX_IGNORE_RULES ? { more: rules.length - MAX_IGNORE_RULES } : {}) });
77
+ }
78
+ return out;
79
+ }
59
80
  /** Local operations are quick; anything touching the network gets longer. */
60
81
  const LOCAL_TIMEOUT = 15_000;
61
82
  export const NET_TIMEOUT = 60_000;
@@ -495,6 +516,7 @@ export async function gitStatus(fresh = false) {
495
516
  ? "A configured root points at the repository root, which would put the whole repo in scope. Narrow workflows/knowledge/agents/skills/vibeables/projects in kraftwerk.yml."
496
517
  : undefined;
497
518
  const conflicts = repo.cfg.autosync === "sync" ? await conflictCopies(repoRoot) : [];
519
+ const ignores = await ignoreFiles(repoRoot);
498
520
  const value = {
499
521
  ...base,
500
522
  error: head.error ?? scopeError,
@@ -502,6 +524,7 @@ export async function gitStatus(fresh = false) {
502
524
  blockedHidden: blockedHidden || undefined,
503
525
  scope: scope.include,
504
526
  ...(conflicts.length ? { conflicts } : {}),
527
+ ...(ignores.length ? { ignores } : {}),
505
528
  };
506
529
  // A commit that finished while this status was running already emptied
507
530
  // the cache; caching the pre-commit list on top of that would show the
@@ -510,6 +533,101 @@ export async function gitStatus(fresh = false) {
510
533
  gitState().statusCache = { at: Date.now(), value };
511
534
  return value;
512
535
  }
536
+ /** The newest `n` commits of the repo at `dir` (those touching `pathspecs`, when given), the ones on no remote marked. */
537
+ export async function commitLog(dir, n, pathspecs = []) {
538
+ const only = pathspecs.length ? ["--", ...pathspecs] : [];
539
+ const [log, local] = await Promise.all([
540
+ git(["log", `-${n}`, "--format=%H%x00%h%x00%s%x00%an%x00%cI", ...only], dir),
541
+ // Bounded like the log: the local commits among the newest N are a prefix of the first N non-remote ones.
542
+ git(["rev-list", "-n", String(n), "HEAD", "--not", "--remotes", ...only], dir),
543
+ ]);
544
+ if (!log.ok)
545
+ return [];
546
+ const localSet = new Set(local.ok ? local.stdout.split("\n").map((l) => l.trim()).filter(Boolean) : []);
547
+ return log.stdout
548
+ .split("\n")
549
+ .filter((l) => l.trim())
550
+ .map((l) => {
551
+ const [hash, short, subject, author, committedAt] = l.split("\0");
552
+ return { hash, short, subject, author, committedAt, local: localSet.has(hash) };
553
+ });
554
+ }
555
+ /**
556
+ * One commit as a patch: header, stat, then the diff. The commit's own path
557
+ * list decides what is shown: a path that is not (`hidden` gives the reason
558
+ * — by default a secret or key: a committed key, a renamed-in .env) is left
559
+ * out of both the stat and the patch by pathspec, so no header shape git
560
+ * emits can smuggle it through.
561
+ */
562
+ export async function commitPatch(dir, hash, hidden = (f) => (DENY.some((re) => re.test(f)) ? "secret or key" : undefined)) {
563
+ if (!/^[0-9a-f]{7,40}$/.test(hash))
564
+ return { diff: "", error: "invalid commit" };
565
+ if (!(await git(["rev-parse", "--verify", "-q", `${hash}^{commit}`], dir)).ok)
566
+ return { diff: "", error: "no such commit" };
567
+ // Post-image paths of the commit: "M\0path\0", renames and copies as "R100\0old\0new\0".
568
+ const tree = await git(["diff-tree", "-r", "-M", "-z", "--root", "--name-status", hash], dir);
569
+ if (!tree.ok)
570
+ return { diff: "", error: tree.stderr || "git diff-tree failed" };
571
+ const parts = tree.stdout.split("\0");
572
+ const paths = [];
573
+ for (let i = 0; i < parts.length; i++) {
574
+ const status = parts[i];
575
+ if (!status || /^[0-9a-f]{40}$/.test(status))
576
+ continue; // the leading hash line of --root
577
+ const two = /^[RC]/.test(status);
578
+ const file = two ? parts[i + 2] : parts[i + 1];
579
+ if (file)
580
+ paths.push(file);
581
+ i += two ? 2 : 1;
582
+ }
583
+ const kept = paths.filter((f) => !hidden(f));
584
+ // "(2 files not shown: secret or key)" — one line per reason.
585
+ const reasons = new Map();
586
+ for (const f of paths) {
587
+ const why = hidden(f);
588
+ if (why)
589
+ reasons.set(why, (reasons.get(why) ?? 0) + 1);
590
+ }
591
+ const notes = [...reasons].map(([why, count]) => `\n(${count} file${count === 1 ? "" : "s"} not shown: ${why})\n`).join("");
592
+ const format = "--format=commit %H%nAuthor: %an <%ae>%nDate: %cI%n%n %s%n";
593
+ if (kept.length === 0 && paths.length > 0) {
594
+ const head = await git(["show", "--no-patch", format, hash], dir);
595
+ return { diff: `${head.stdout}${notes}` };
596
+ }
597
+ const r = await git(["show", "--stat", "--patch", format, hash, "--", ...kept.map(literal)], dir);
598
+ if (!r.ok)
599
+ return { diff: "", error: r.stderr || "git show failed" };
600
+ const out = capDiff(r.stdout);
601
+ out.diff += notes;
602
+ return out;
603
+ }
604
+ const LOG_COMMITS = 50;
605
+ /** The workspace paths as pathspecs — none when a root is the whole repo. */
606
+ const scopeSpecs = (scope) => (scope.wholeRepo || scope.include.includes(".") ? [] : scope.include.map(literal));
607
+ /** Why a committed path is not shown in the workspace's history, or undefined when it is: the status list's rule, for a path that is history already. */
608
+ const hiddenIn = (scope) => (file) => DENY.some((re) => re.test(file))
609
+ ? "secret or key"
610
+ : scope.exclude.some((e) => within(file, e)) || !(scope.wholeRepo || scope.include.includes(".") || scope.include.some((r) => within(file, r)))
611
+ ? "outside the workspace paths"
612
+ : undefined;
613
+ /** The workspace's history: the newest commits that touched its paths, whoever made them — by hand here, kraftwerk sync, another machine. */
614
+ export async function gitLog() {
615
+ const opened = await openRepo();
616
+ if (opened.off)
617
+ return { commits: [], error: "git sync is off" };
618
+ if (!opened.repo)
619
+ return { commits: [], error: opened.error ?? "not a git repository" };
620
+ return { commits: await commitLog(opened.repo.repoRoot, LOG_COMMITS, scopeSpecs(scopeFor(opened.repo))) };
621
+ }
622
+ /** One commit of the workspace's history as a patch, the files outside the workspace paths (and secrets) left out. */
623
+ export async function gitCommitDiff(hash) {
624
+ const opened = await openRepo();
625
+ if (opened.off)
626
+ return { diff: "", error: "git sync is off" };
627
+ if (!opened.repo)
628
+ return { diff: "", error: opened.error ?? "not a git repository" };
629
+ return commitPatch(opened.repo.repoRoot, hash, hiddenIn(scopeFor(opened.repo)));
630
+ }
513
631
  /**
514
632
  * Unified diff for one changed file. Reading is as sensitive as writing
515
633
  * here: this endpoint has no auth of its own, and a diff of an untracked
@@ -1,5 +1,5 @@
1
1
  import { type ResolvedWorkspace } from "../config.js";
2
- import { type GitDiff } from "./git.js";
2
+ import { type GitCommit, type GitDiff } from "./git.js";
3
3
  /**
4
4
  * Repositories: the git clones an agent works on, kept under one root
5
5
  * inside the project (`repos.root` in kraftwerk.yml, default repos/). The
@@ -51,15 +51,7 @@ export interface RepoFile {
51
51
  /** modified, added, deleted, renamed, untracked, conflicted. */
52
52
  status: string;
53
53
  }
54
- export interface RepoCommit {
55
- hash: string;
56
- short: string;
57
- subject: string;
58
- author: string;
59
- committedAt: string;
60
- /** On no remote yet: the clone's own work. */
61
- local: boolean;
62
- }
54
+ export type RepoCommit = GitCommit;
63
55
  /**
64
56
  * The detail page's view of a clone: the listing's summary plus what is
65
57
  * happening inside — changed files, line counts against HEAD, the recent
@@ -4,7 +4,7 @@ import { gitignoreHas, ignoreEntryFor, reposRootFor, resolveWorkspace } from "..
4
4
  import { workspaceRoot } from "./context.js";
5
5
  import { moveToTrash } from "./trash.js";
6
6
  import { newestMtime } from "./mtime.js";
7
- import { capDiff, DENY, diffAgainstHead, git, gitNet, label, literal, parseStatus, sshCommandFor } from "./git.js";
7
+ import { commitLog, commitPatch, DENY, diffAgainstHead, git, gitNet, label, literal, parseStatus, sshCommandFor } from "./git.js";
8
8
  /**
9
9
  * A clone is the one call here that can legitimately take long: a large
10
10
  * repository on a slow link is minutes, not seconds. Prompts are already
@@ -140,26 +140,15 @@ export async function repoDetail(slug) {
140
140
  const detail = { ...info, files: [], commits: [], insertions: 0, deletions: 0 };
141
141
  if (info.error)
142
142
  return detail;
143
- const [status, log, local, stat, upstream] = await Promise.all([
143
+ const [status, commits, stat, upstream] = await Promise.all([
144
144
  git(["status", "--porcelain=v1", "-z", "--untracked-files=all"], dir),
145
- git(["log", `-${COMMITS}`, "--format=%H%x00%h%x00%s%x00%an%x00%cI"], dir),
146
- // Bounded like the log: the local commits among the newest N are a prefix of the first N non-remote ones.
147
- git(["rev-list", `-n`, String(COMMITS), "HEAD", "--not", "--remotes"], dir),
145
+ commitLog(dir, COMMITS),
148
146
  git(["diff", "HEAD", "--shortstat"], dir),
149
147
  git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], dir),
150
148
  ]);
151
149
  if (status.ok)
152
150
  detail.files = parseStatus(status.stdout).map((f) => ({ path: f.path, code: f.code, status: label(f.code) }));
153
- if (log.ok) {
154
- const localSet = new Set(local.ok ? local.stdout.split("\n").map((l) => l.trim()).filter(Boolean) : []);
155
- detail.commits = log.stdout
156
- .split("\n")
157
- .filter((l) => l.trim())
158
- .map((l) => {
159
- const [hash, short, subject, author, committedAt] = l.split("\0");
160
- return { hash, short, subject, author, committedAt, local: localSet.has(hash) };
161
- });
162
- }
151
+ detail.commits = commits;
163
152
  if (stat.ok) {
164
153
  const ins = /(\d+) insertion/.exec(stat.stdout);
165
154
  const del = /(\d+) deletion/.exec(stat.stdout);
@@ -198,38 +187,7 @@ export async function repoCommitDiff(slug, hash) {
198
187
  if (!/^[0-9a-f]{7,40}$/.test(hash))
199
188
  return { diff: "", error: "invalid commit" };
200
189
  const { dir } = await cloneDir(slug);
201
- if (!(await git(["rev-parse", "--verify", "-q", `${hash}^{commit}`], dir)).ok)
202
- return { diff: "", error: "no such commit" };
203
- // Post-image paths of the commit: "M\0path\0", renames and copies as "R100\0old\0new\0".
204
- const tree = await git(["diff-tree", "-r", "-M", "-z", "--root", "--name-status", hash], dir);
205
- if (!tree.ok)
206
- return { diff: "", error: tree.stderr || "git diff-tree failed" };
207
- const parts = tree.stdout.split("\0");
208
- const paths = [];
209
- for (let i = 0; i < parts.length; i++) {
210
- const status = parts[i];
211
- if (!status || /^[0-9a-f]{40}$/.test(status))
212
- continue; // the leading hash line of --root
213
- const two = /^[RC]/.test(status);
214
- const file = two ? parts[i + 2] : parts[i + 1];
215
- if (file)
216
- paths.push(file);
217
- i += two ? 2 : 1;
218
- }
219
- const kept = paths.filter((f) => !DENY.some((re) => re.test(f)));
220
- const hidden = paths.length - kept.length;
221
- const format = "--format=commit %H%nAuthor: %an <%ae>%nDate: %cI%n%n %s%n";
222
- if (kept.length === 0 && paths.length > 0) {
223
- const head = await git(["show", "--no-patch", format, hash], dir);
224
- return { diff: `${head.stdout}\n(${hidden} file${hidden === 1 ? "" : "s"} not shown: secret or key)\n` };
225
- }
226
- const r = await git(["show", "--stat", "--patch", format, hash, "--", ...kept.map(literal)], dir);
227
- if (!r.ok)
228
- return { diff: "", error: r.stderr || "git show failed" };
229
- const out = capDiff(r.stdout);
230
- if (hidden > 0)
231
- out.diff += `\n(${hidden} file${hidden === 1 ? "" : "s"} not shown: secret or key)\n`;
232
- return out;
190
+ return commitPatch(dir, hash);
233
191
  }
234
192
  /** Every clone under the root, alphabetically. Folders without .git are skipped. */
235
193
  export async function listRepos() {
@@ -8,10 +8,10 @@ export declare const gitRoutes: (import("./router.js").Route<"git.commit", impor
8
8
  }>, "/api/git/commit", z.ZodObject<{
9
9
  paths: z.ZodDefault<z.ZodArray<z.ZodString>>;
10
10
  message: z.ZodDefault<z.ZodString>;
11
- }, z.core.$strip>> | import("./router.js").Route<"git.diff", import("../../core/git.js").GitDiff, "/api/git/diff", undefined> | import("./router.js").Route<"git.fetch", import("./router.js").Reply<{
11
+ }, z.core.$strip>> | import("./router.js").Route<"git.commitDiff", import("./router.js").Reply<import("../../core/git.js").GitDiff>, "/api/git/commits/:hash", undefined> | import("./router.js").Route<"git.diff", import("../../core/git.js").GitDiff, "/api/git/diff", undefined> | import("./router.js").Route<"git.fetch", import("./router.js").Reply<{
12
12
  ok: boolean;
13
13
  error?: string;
14
- }>, "/api/git/fetch", undefined> | import("./router.js").Route<"git.pull", import("./router.js").Reply<{
14
+ }>, "/api/git/fetch", undefined> | import("./router.js").Route<"git.log", import("../../core/git.js").GitLog, "/api/git/log", undefined> | import("./router.js").Route<"git.pull", import("./router.js").Reply<{
15
15
  ok: boolean;
16
16
  error?: string;
17
17
  }>, "/api/git/pull", undefined> | import("./router.js").Route<"git.push", import("./router.js").Reply<{
@@ -1,7 +1,7 @@
1
1
  import * as z from "zod";
2
2
  import { resolveWorkspace } from "../../config.js";
3
3
  import { workspaceRoot } from "../../core/context.js";
4
- import { gitCommit, gitDiff, gitFetch, gitPull, gitPush, gitStatus } from "../../core/git.js";
4
+ import { gitCommit, gitCommitDiff, gitDiff, gitFetch, gitLog, gitPull, gitPush, gitStatus } from "../../core/git.js";
5
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";
@@ -29,6 +29,11 @@ export const gitRoutes = [
29
29
  fail(400, "path required");
30
30
  return gitDiff(file);
31
31
  }),
32
+ route({ name: "git.log", method: "GET", path: "/api/git/log", summary: "the newest commits that touched the workspace paths, unpushed marked" }, async () => gitLog()),
33
+ route({ name: "git.commitDiff", method: "GET", path: "/api/git/commits/:hash", summary: "one commit as a patch, the workspace paths only", errors: 400 }, async (c) => {
34
+ const d = await gitCommitDiff(c.params.hash);
35
+ return reply(d.error ? (/^no such commit/.test(d.error) ? 404 : 400) : 200, d);
36
+ }),
32
37
  // Committing stays manual: the background timer never writes history, and pushes it only with `autosync: push`.
33
38
  route({ name: "git.commit", method: "POST", path: "/api/git/commit", summary: "stage and commit {paths, message}", errors: 400, body: Commit }, async (c) => {
34
39
  const { paths, message } = await c.body();
@@ -539,10 +539,10 @@ export declare const routes: (Route<"agents.addJournal", {
539
539
  }>, "/api/git/commit", z.ZodObject<{
540
540
  paths: z.ZodDefault<z.ZodArray<z.ZodString>>;
541
541
  message: z.ZodDefault<z.ZodString>;
542
- }, z.core.$strip>> | Route<"git.diff", import("../../core/git.js").GitDiff, "/api/git/diff", undefined> | Route<"git.fetch", import("./router.js").Reply<{
542
+ }, z.core.$strip>> | Route<"git.commitDiff", import("./router.js").Reply<import("../../core/git.js").GitDiff>, "/api/git/commits/:hash", undefined> | Route<"git.diff", import("../../core/git.js").GitDiff, "/api/git/diff", undefined> | Route<"git.fetch", import("./router.js").Reply<{
543
543
  ok: boolean;
544
544
  error?: string;
545
- }>, "/api/git/fetch", undefined> | Route<"git.pull", import("./router.js").Reply<{
545
+ }>, "/api/git/fetch", undefined> | Route<"git.log", import("../../core/git.js").GitLog, "/api/git/log", undefined> | Route<"git.pull", import("./router.js").Reply<{
546
546
  ok: boolean;
547
547
  error?: string;
548
548
  }>, "/api/git/pull", undefined> | Route<"git.push", import("./router.js").Reply<{
@@ -1,5 +1,17 @@
1
1
  import http from "node:http";
2
2
  import type { Duplex } from "node:stream";
3
+ /** A pass for the app `slug` of the workspace `workspace` (its slug here), as the path segment that carries it. */
4
+ export declare function vibeablePass(workspace: string, slug: string, now?: number): string;
5
+ /**
6
+ * Take the pass out of a preview path. `pathname` is the path without it
7
+ * either way; `valid` says whether it was there and holds for this app of
8
+ * this workspace, `slug` the app it names (undefined: not an app's path).
9
+ */
10
+ export declare function takeVibeablePass(workspace: string | undefined, pathname: string, now?: number): {
11
+ pathname: string;
12
+ slug?: string;
13
+ valid: boolean;
14
+ };
3
15
  /**
4
16
  * GET /vibeables/<slug>/<file>. Dot segments (.env, .git) are never served;
5
17
  * a directory answers with its index.html, and a directory url without the
@@ -1,3 +1,4 @@
1
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
1
2
  import { createReadStream, promises as fs } from "node:fs";
2
3
  import http from "node:http";
3
4
  import net from "node:net";
@@ -58,7 +59,58 @@ const PREVIEW_HEADERS = {
58
59
  "cache-control": "no-store",
59
60
  "content-security-policy": VIBEABLE_CSP,
60
61
  "access-control-allow-origin": "*",
62
+ // A pass (below) is part of the address: it stays out of what the app tells other sites.
63
+ "referrer-policy": "same-origin",
61
64
  };
65
+ /* ---------- pass ---------- */
66
+ /**
67
+ * The sandboxed document has an opaque origin, so what it loads — its own
68
+ * style.css, app.js, images, fetch() — is a cross-site request to the
69
+ * browser: no SameSite cookie goes with it. Where a cookie is what lets the
70
+ * caller in (a signed-in user, a paired device, a member), the app's files
71
+ * would answer with the sign-in page and the app would show unstyled.
72
+ *
73
+ * So the first request, which does carry the cookie, is redirected to an
74
+ * address with a pass in it — /vibeables/<slug>/~<pass>/… — and the page's
75
+ * relative links stay under it. A pass opens one app's files of one
76
+ * workspace for PASS_TTL_MS and nothing else; it is signed with a secret
77
+ * this process made up, so none outlives a restart.
78
+ */
79
+ const PASS_TTL_MS = 12 * 60 * 60 * 1000;
80
+ const PASS_RE = /^~(\d{1,15})\.([A-Za-z0-9_-]{43})$/;
81
+ const passSecret = randomBytes(32);
82
+ const sign = (workspace, slug, exp) => createHmac("sha256", passSecret).update(`${workspace}\0${slug}\0${exp}`).digest("base64url");
83
+ /** A pass for the app `slug` of the workspace `workspace` (its slug here), as the path segment that carries it. */
84
+ export function vibeablePass(workspace, slug, now = Date.now()) {
85
+ const exp = now + PASS_TTL_MS;
86
+ return `~${exp}.${sign(workspace, slug, exp)}`;
87
+ }
88
+ /**
89
+ * Take the pass out of a preview path. `pathname` is the path without it
90
+ * either way; `valid` says whether it was there and holds for this app of
91
+ * this workspace, `slug` the app it names (undefined: not an app's path).
92
+ */
93
+ export function takeVibeablePass(workspace, pathname, now = Date.now()) {
94
+ const seg = pathname.split("/"); // ["", "vibeables", slug, maybe pass, ...rest]
95
+ let slug;
96
+ try {
97
+ slug = seg[2] ? safeVibeableSlug(decodeURIComponent(seg[2])) : undefined;
98
+ }
99
+ catch {
100
+ slug = undefined;
101
+ }
102
+ const m = PASS_RE.exec(seg[3] ?? "");
103
+ if (!m)
104
+ return { pathname, slug, valid: false };
105
+ seg.splice(3, 1);
106
+ const stripped = seg.length === 3 ? `${seg.join("/")}/` : seg.join("/");
107
+ const exp = Number(m[1]);
108
+ if (!slug || workspace === undefined || !(exp > now))
109
+ return { pathname: stripped, slug, valid: false };
110
+ const want = Buffer.from(sign(workspace, slug, exp));
111
+ const got = Buffer.from(m[2]);
112
+ return { pathname: stripped, slug, valid: want.length === got.length && timingSafeEqual(want, got) };
113
+ }
62
114
  /**
63
115
  * GET /vibeables/<slug>/<file>. Dot segments (.env, .git) are never served;
64
116
  * a directory answers with its index.html, and a directory url without the
@@ -8,8 +8,8 @@ import { stopMachineCloud } from "./cloud.js";
8
8
  import { disposeAllBackends, disposeWorkspaceBackends } from "../core/chat/sessions.js";
9
9
  import { markWorkspaceStopped, registerInstance, registerWorkspace, unregisterInstance } from "../core/instances.js";
10
10
  import { startGitSync, stopGitSync } from "../core/git.js";
11
- import { disposeAllDevs, disposeWorkspaceDevs } from "../core/vibeables.js";
12
- import { proxyUpgrade, serveVibeable } from "./preview.js";
11
+ import { disposeAllDevs, disposeWorkspaceDevs, safeVibeableSlug } from "../core/vibeables.js";
12
+ import { proxyUpgrade, serveVibeable, takeVibeablePass, vibeablePass } from "./preview.js";
13
13
  import { startRoutineScheduler, stopRoutineScheduler } from "../core/routines.js";
14
14
  import { startBoardWake, stopBoardWake } from "../core/board-wake.js";
15
15
  import { readWorkspaceDotenv } from "../core/env.js";
@@ -291,6 +291,14 @@ export async function startHub(opts) {
291
291
  return json(res, { error: `no workspace "${target.slug}" here` }, 404);
292
292
  const { url } = target;
293
293
  const prefix = prefixOf(req, target);
294
+ // An app's files under a pass (preview.ts): the pass is what lets the request in — the sandboxed page sends no cookie.
295
+ const isVibeable = url.pathname === "/vibeables" || url.pathname.startsWith("/vibeables/");
296
+ if (isVibeable) {
297
+ const pass = takeVibeablePass(open?.slug, url.pathname);
298
+ url.pathname = pass.pathname;
299
+ if (pass.valid && open)
300
+ return await runInHub(hub, () => open.ws.run(() => serveVibeable(req, res, url)));
301
+ }
294
302
  const cu = await cloudUsers(open, prefix);
295
303
  const gate = await withUser(req, await trustOf(req, url, trustOpts), cu);
296
304
  const { trust } = gate;
@@ -326,11 +334,27 @@ export async function startHub(opts) {
326
334
  return await run(() => apiRouter.handle(req, res, url, trust));
327
335
  }
328
336
  // /vibeables/<slug>/… is an app's own files, served for the preview pane — workspace data, so not for unpaired callers.
329
- if (url.pathname === "/vibeables" || url.pathname.startsWith("/vibeables/")) {
337
+ if (isVibeable) {
330
338
  if (trust.kind === "none")
331
339
  return json(res, { error: "pair this device first", pair: true }, 401);
332
340
  if (!open)
333
341
  return json(res, { error: "name a workspace: <slug>.localhost or /w/<slug>/" }, 404);
342
+ // Let in by a cookie (a signed-in user, a device, a member): on to the address with a pass, so the page's own files load too.
343
+ const app = url.pathname.split("/")[2];
344
+ if (app && (trust.kind !== "local" || trust.user) && (req.method === "GET" || req.method === "HEAD")) {
345
+ let slug;
346
+ try {
347
+ slug = safeVibeableSlug(decodeURIComponent(app));
348
+ }
349
+ catch {
350
+ /* not an app's name: serveVibeable says so */
351
+ }
352
+ if (slug) {
353
+ const rest = url.pathname.split("/").slice(3).join("/");
354
+ res.writeHead(302, { location: `${prefix}/vibeables/${encodeURIComponent(slug)}/${vibeablePass(open.slug, slug)}/${rest}${url.search}`, "cache-control": "no-store" });
355
+ return void res.end();
356
+ }
357
+ }
334
358
  return await run(() => serveVibeable(req, res, url));
335
359
  }
336
360
  // A daemon's own address lists its workspaces; anywhere else, the web UI's shell (public: an unpaired browser needs it to pair).
@@ -352,6 +376,15 @@ export async function startHub(opts) {
352
376
  if (target.slug !== undefined && !open)
353
377
  return void socket.end("HTTP/1.1 404 Not Found\r\nconnection: close\r\n\r\n");
354
378
  const { url } = target;
379
+ // A dev server's HMR socket under a pass (preview.ts), opened by the sandboxed page: no cookie comes with it.
380
+ if (url.pathname.startsWith("/vibeables/")) {
381
+ const pass = takeVibeablePass(open?.slug, url.pathname);
382
+ url.pathname = pass.pathname;
383
+ if (pass.valid && open) {
384
+ req.url = url.pathname + url.search;
385
+ return runInHub(hub, () => open.ws.run(() => proxyUpgrade(req, socket, head)));
386
+ }
387
+ }
355
388
  const cu = await cloudUsers(open, prefixOf(req, target));
356
389
  const gate = await withUser(req, await trustOf(req, url, trustOpts, true), cu);
357
390
  const { trust } = gate;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netnodeag/kraftwerk",
3
- "version": "0.105.0",
3
+ "version": "0.106.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",