@cabn/cli 0.1.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 (222) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +36 -0
  3. package/dist/assets/originals/cabin_256.webp +0 -0
  4. package/dist/assets/originals/cabinet_256.webp +0 -0
  5. package/dist/assets/originals/file_256.webp +0 -0
  6. package/dist/assets/originals/key_256.webp +0 -0
  7. package/dist/assets/originals/letter_opener_256.webp +0 -0
  8. package/dist/assets/placeholders/bonfire_frame0_soft.png +0 -0
  9. package/dist/assets/placeholders/bonfire_frame1_soft.png +0 -0
  10. package/dist/assets/placeholders/bonfire_frame2_soft.png +0 -0
  11. package/dist/assets/placeholders/bonfire_frame3_soft.png +0 -0
  12. package/dist/assets/placeholders/bramble_defeat0_soft.png +0 -0
  13. package/dist/assets/placeholders/bramble_defeat1_soft.png +0 -0
  14. package/dist/assets/placeholders/bramble_defeat2_soft.png +0 -0
  15. package/dist/assets/placeholders/bramble_hit_soft.png +0 -0
  16. package/dist/assets/placeholders/bramble_idle0_soft.png +0 -0
  17. package/dist/assets/placeholders/bramble_idle1_soft.png +0 -0
  18. package/dist/assets/placeholders/character_idle_back_soft.png +0 -0
  19. package/dist/assets/placeholders/character_idle_soft.png +0 -0
  20. package/dist/assets/placeholders/decals_soft.png +0 -0
  21. package/dist/assets/placeholders/fx_spark.png +0 -0
  22. package/dist/assets/placeholders/ghost_defeat0_soft.png +0 -0
  23. package/dist/assets/placeholders/ghost_defeat1_soft.png +0 -0
  24. package/dist/assets/placeholders/ghost_defeat2_soft.png +0 -0
  25. package/dist/assets/placeholders/ghost_hit_soft.png +0 -0
  26. package/dist/assets/placeholders/ghost_soft.png +0 -0
  27. package/dist/assets/placeholders/glade_tiles_soft.png +0 -0
  28. package/dist/assets/placeholders/gremlin_defeat0_soft.png +0 -0
  29. package/dist/assets/placeholders/gremlin_defeat1_soft.png +0 -0
  30. package/dist/assets/placeholders/gremlin_defeat2_soft.png +0 -0
  31. package/dist/assets/placeholders/gremlin_hit_soft.png +0 -0
  32. package/dist/assets/placeholders/gremlin_idle0_soft.png +0 -0
  33. package/dist/assets/placeholders/gremlin_idle1_soft.png +0 -0
  34. package/dist/assets/placeholders/grove_tiles_soft.png +0 -0
  35. package/dist/assets/placeholders/imp_defeat0_soft.png +0 -0
  36. package/dist/assets/placeholders/imp_defeat1_soft.png +0 -0
  37. package/dist/assets/placeholders/imp_defeat2_soft.png +0 -0
  38. package/dist/assets/placeholders/imp_hit_soft.png +0 -0
  39. package/dist/assets/placeholders/imp_idle0_soft.png +0 -0
  40. package/dist/assets/placeholders/imp_idle1_soft.png +0 -0
  41. package/dist/assets/placeholders/magpie_defeat0_soft.png +0 -0
  42. package/dist/assets/placeholders/magpie_defeat1_soft.png +0 -0
  43. package/dist/assets/placeholders/magpie_defeat2_soft.png +0 -0
  44. package/dist/assets/placeholders/magpie_hit_soft.png +0 -0
  45. package/dist/assets/placeholders/magpie_idle0_soft.png +0 -0
  46. package/dist/assets/placeholders/magpie_idle1_soft.png +0 -0
  47. package/dist/assets/placeholders/meadow_tiles_soft.png +0 -0
  48. package/dist/assets/placeholders/npc_guide_bubble_soft.png +0 -0
  49. package/dist/assets/placeholders/npc_guide_portrait_soft.png +0 -0
  50. package/dist/assets/placeholders/npc_guide_strip_soft.png +0 -0
  51. package/dist/assets/placeholders/ouroboros_defeat0_soft.png +0 -0
  52. package/dist/assets/placeholders/ouroboros_defeat1_soft.png +0 -0
  53. package/dist/assets/placeholders/ouroboros_defeat2_soft.png +0 -0
  54. package/dist/assets/placeholders/ouroboros_hit_soft.png +0 -0
  55. package/dist/assets/placeholders/ouroboros_idle0_soft.png +0 -0
  56. package/dist/assets/placeholders/ouroboros_idle1_soft.png +0 -0
  57. package/dist/assets/placeholders/path_bed_disc_soft.png +0 -0
  58. package/dist/assets/placeholders/path_cobble_0_soft.png +0 -0
  59. package/dist/assets/placeholders/path_cobble_1_soft.png +0 -0
  60. package/dist/assets/placeholders/path_cobble_2_soft.png +0 -0
  61. package/dist/assets/placeholders/path_cobble_3_soft.png +0 -0
  62. package/dist/assets/placeholders/path_edge_disc_soft.png +0 -0
  63. package/dist/assets/placeholders/path_stamp_0_soft.png +0 -0
  64. package/dist/assets/placeholders/path_stamp_1_soft.png +0 -0
  65. package/dist/assets/placeholders/path_stamp_2_soft.png +0 -0
  66. package/dist/assets/placeholders/pet_bird_portrait_soft.png +0 -0
  67. package/dist/assets/placeholders/pet_bird_strip_soft.png +0 -0
  68. package/dist/assets/placeholders/pet_cat_portrait_soft.png +0 -0
  69. package/dist/assets/placeholders/pet_cat_strip_soft.png +0 -0
  70. package/dist/assets/placeholders/pet_ferret_portrait_soft.png +0 -0
  71. package/dist/assets/placeholders/pet_ferret_strip_soft.png +0 -0
  72. package/dist/assets/placeholders/pet_llama_portrait_soft.png +0 -0
  73. package/dist/assets/placeholders/pet_llama_strip_soft.png +0 -0
  74. package/dist/assets/placeholders/pet_owl_portrait_soft.png +0 -0
  75. package/dist/assets/placeholders/pet_owl_strip_soft.png +0 -0
  76. package/dist/assets/placeholders/pet_whale_portrait_soft.png +0 -0
  77. package/dist/assets/placeholders/pet_whale_strip_soft.png +0 -0
  78. package/dist/assets/placeholders/portal_arch_soft.png +0 -0
  79. package/dist/assets/placeholders/portal_arch_strip_soft.png +0 -0
  80. package/dist/assets/placeholders/portal_arch_variants_soft.png +0 -0
  81. package/dist/assets/placeholders/prop_bench_soft.png +0 -0
  82. package/dist/assets/placeholders/prop_bush_soft.png +0 -0
  83. package/dist/assets/placeholders/prop_castle_keep_soft.png +0 -0
  84. package/dist/assets/placeholders/prop_cottage_soft.png +0 -0
  85. package/dist/assets/placeholders/prop_fence_soft.png +0 -0
  86. package/dist/assets/placeholders/prop_flower_bed_soft.png +0 -0
  87. package/dist/assets/placeholders/prop_flower_pot_soft.png +0 -0
  88. package/dist/assets/placeholders/prop_hedge_soft.png +0 -0
  89. package/dist/assets/placeholders/prop_lamp_post_soft.png +0 -0
  90. package/dist/assets/placeholders/prop_seyn_sign_soft.png +0 -0
  91. package/dist/assets/placeholders/prop_shelf_cabin_soft.png +0 -0
  92. package/dist/assets/placeholders/prop_signpost_soft.png +0 -0
  93. package/dist/assets/placeholders/prop_stone_wall_soft.png +0 -0
  94. package/dist/assets/placeholders/prop_tree_large_soft.png +0 -0
  95. package/dist/assets/placeholders/prop_tree_small_soft.png +0 -0
  96. package/dist/assets/placeholders/prop_well_soft.png +0 -0
  97. package/dist/assets/placeholders/prop_world_fountain_gem_soft.png +0 -0
  98. package/dist/assets/placeholders/prop_world_fountain_strip_soft.png +0 -0
  99. package/dist/assets/placeholders/rot_sprite_defeat0_soft.png +0 -0
  100. package/dist/assets/placeholders/rot_sprite_defeat1_soft.png +0 -0
  101. package/dist/assets/placeholders/rot_sprite_defeat2_soft.png +0 -0
  102. package/dist/assets/placeholders/rot_sprite_hit_soft.png +0 -0
  103. package/dist/assets/placeholders/rot_sprite_idle0_soft.png +0 -0
  104. package/dist/assets/placeholders/rot_sprite_idle1_soft.png +0 -0
  105. package/dist/assets/placeholders/scenery_berry_shrub_soft.png +0 -0
  106. package/dist/assets/placeholders/scenery_blossom_oak_soft.png +0 -0
  107. package/dist/assets/placeholders/scenery_boulder_soft.png +0 -0
  108. package/dist/assets/placeholders/scenery_fallen_log_soft.png +0 -0
  109. package/dist/assets/placeholders/scenery_flower_patch_soft.png +0 -0
  110. package/dist/assets/placeholders/scenery_mushroom_soft.png +0 -0
  111. package/dist/assets/placeholders/scenery_oak_soft.png +0 -0
  112. package/dist/assets/placeholders/scenery_pine_soft.png +0 -0
  113. package/dist/assets/placeholders/scenery_pond_soft.png +0 -0
  114. package/dist/assets/placeholders/scenery_reeds_soft.png +0 -0
  115. package/dist/assets/placeholders/scenery_rock_small_soft.png +0 -0
  116. package/dist/assets/placeholders/scenery_ruin_soft.png +0 -0
  117. package/dist/assets/placeholders/scenery_shrub_soft.png +0 -0
  118. package/dist/assets/placeholders/scenery_stump_soft.png +0 -0
  119. package/dist/assets/placeholders/scenery_waymarker_soft.png +0 -0
  120. package/dist/assets/placeholders/scenery_windmill_sails_soft.png +0 -0
  121. package/dist/assets/placeholders/scenery_windmill_soft.png +0 -0
  122. package/dist/assets/placeholders/shade_defeat0_soft.png +0 -0
  123. package/dist/assets/placeholders/shade_defeat1_soft.png +0 -0
  124. package/dist/assets/placeholders/shade_defeat2_soft.png +0 -0
  125. package/dist/assets/placeholders/shade_hit_soft.png +0 -0
  126. package/dist/assets/placeholders/shade_idle0_soft.png +0 -0
  127. package/dist/assets/placeholders/shade_idle1_soft.png +0 -0
  128. package/dist/assets/placeholders/skeleton_defeat0_soft.png +0 -0
  129. package/dist/assets/placeholders/skeleton_defeat1_soft.png +0 -0
  130. package/dist/assets/placeholders/skeleton_defeat2_soft.png +0 -0
  131. package/dist/assets/placeholders/skeleton_hit_soft.png +0 -0
  132. package/dist/assets/placeholders/skeleton_idle0_soft.png +0 -0
  133. package/dist/assets/placeholders/skeleton_idle1_soft.png +0 -0
  134. package/dist/assets/placeholders/sky_day.png +0 -0
  135. package/dist/assets/placeholders/sky_moon_soft.png +0 -0
  136. package/dist/assets/placeholders/sky_night.png +0 -0
  137. package/dist/assets/placeholders/sky_star_soft.png +0 -0
  138. package/dist/assets/placeholders/skyline_castle_day_soft.png +0 -0
  139. package/dist/assets/placeholders/skyline_castle_night_soft.png +0 -0
  140. package/dist/assets/placeholders/skyline_hill_day_soft.png +0 -0
  141. package/dist/assets/placeholders/skyline_hill_night_soft.png +0 -0
  142. package/dist/assets/placeholders/skyline_treeline_day_soft.png +0 -0
  143. package/dist/assets/placeholders/skyline_treeline_night_soft.png +0 -0
  144. package/dist/assets/placeholders/skyline_village_day_soft.png +0 -0
  145. package/dist/assets/placeholders/skyline_village_night_soft.png +0 -0
  146. package/dist/assets/placeholders/skyline_watchtower_day_soft.png +0 -0
  147. package/dist/assets/placeholders/skyline_watchtower_night_soft.png +0 -0
  148. package/dist/assets/placeholders/ui_icon_bag_soft.png +0 -0
  149. package/dist/assets/placeholders/ui_icon_key_soft.png +0 -0
  150. package/dist/assets/placeholders/ui_icon_orb_soft.png +0 -0
  151. package/dist/assets/placeholders/ui_icon_owner_soft.png +0 -0
  152. package/dist/assets/placeholders/ui_icon_quill_soft.png +0 -0
  153. package/dist/assets/placeholders/ui_icon_sign_soft.png +0 -0
  154. package/dist/assets/placeholders/ui_icon_spyglass_soft.png +0 -0
  155. package/dist/assets/placeholders/ui_icon_wand_soft.png +0 -0
  156. package/dist/assets/placeholders/ui_screen_orb_soft.png +0 -0
  157. package/dist/assets/placeholders/ui_screen_satchel_flap_soft.png +0 -0
  158. package/dist/assets/placeholders/ui_screen_satchel_soft.png +0 -0
  159. package/dist/assets/placeholders/ui_screen_spyglass_soft.png +0 -0
  160. package/dist/assets/placeholders/ui_sparkle_cyan@8x.png +0 -0
  161. package/dist/assets/placeholders/ui_sparkle_gold@8x.png +0 -0
  162. package/dist/assets/placeholders/ui_sparkle_violet@8x.png +0 -0
  163. package/dist/assets/placeholders/ui_tool_comment_soft.png +0 -0
  164. package/dist/assets/placeholders/ui_tool_find_soft.png +0 -0
  165. package/dist/assets/placeholders/ui_tool_fold_soft.png +0 -0
  166. package/dist/assets/placeholders/ui_tool_format_soft.png +0 -0
  167. package/dist/assets/placeholders/ui_tool_goto_soft.png +0 -0
  168. package/dist/assets/placeholders/ui_tool_rename_soft.png +0 -0
  169. package/dist/assets/placeholders/ui_tool_replace_soft.png +0 -0
  170. package/dist/assets/placeholders/ui_tool_save_soft.png +0 -0
  171. package/dist/assets/placeholders/ui_tool_symbol_soft.png +0 -0
  172. package/dist/assets/placeholders/ui_tool_unfold_soft.png +0 -0
  173. package/dist/assets/placeholders/warded_mimic_defeat0_soft.png +0 -0
  174. package/dist/assets/placeholders/warded_mimic_defeat1_soft.png +0 -0
  175. package/dist/assets/placeholders/warded_mimic_defeat2_soft.png +0 -0
  176. package/dist/assets/placeholders/warded_mimic_hit_soft.png +0 -0
  177. package/dist/assets/placeholders/warded_mimic_idle0_soft.png +0 -0
  178. package/dist/assets/placeholders/warded_mimic_idle1_soft.png +0 -0
  179. package/dist/assets/placeholders/will_o_wisp_defeat0_soft.png +0 -0
  180. package/dist/assets/placeholders/will_o_wisp_defeat1_soft.png +0 -0
  181. package/dist/assets/placeholders/will_o_wisp_defeat2_soft.png +0 -0
  182. package/dist/assets/placeholders/will_o_wisp_hit_soft.png +0 -0
  183. package/dist/assets/placeholders/will_o_wisp_idle0_soft.png +0 -0
  184. package/dist/assets/placeholders/will_o_wisp_idle1_soft.png +0 -0
  185. package/dist/assets/placeholders/wizard_tower_soft.png +0 -0
  186. package/dist/build.d.ts +84 -0
  187. package/dist/build.js +185 -0
  188. package/dist/cli.d.ts +1 -0
  189. package/dist/cli.js +163 -0
  190. package/dist/help.d.ts +2 -0
  191. package/dist/help.js +35 -0
  192. package/dist/index.d.ts +6 -0
  193. package/dist/index.js +6 -0
  194. package/dist/inspect.d.ts +3 -0
  195. package/dist/inspect.js +35 -0
  196. package/dist/main.d.ts +2 -0
  197. package/dist/main.js +3 -0
  198. package/dist/serve/execRunner.d.ts +43 -0
  199. package/dist/serve/execRunner.js +113 -0
  200. package/dist/serve/hostPage.d.ts +15 -0
  201. package/dist/serve/hostPage.js +100 -0
  202. package/dist/serve/ownerAuth.d.ts +80 -0
  203. package/dist/serve/ownerAuth.js +241 -0
  204. package/dist/serve/ownerGit.d.ts +40 -0
  205. package/dist/serve/ownerGit.js +265 -0
  206. package/dist/serve/ownerShadow.d.ts +52 -0
  207. package/dist/serve/ownerShadow.js +250 -0
  208. package/dist/serve/ownerSigns.d.ts +30 -0
  209. package/dist/serve/ownerSigns.js +224 -0
  210. package/dist/serve/pyTracer.d.ts +33 -0
  211. package/dist/serve/pyTracer.js +76 -0
  212. package/dist/serve/runtime.d.ts +8 -0
  213. package/dist/serve/runtime.js +35 -0
  214. package/dist/serve/security.d.ts +47 -0
  215. package/dist/serve/security.js +106 -0
  216. package/dist/serve/server.d.ts +52 -0
  217. package/dist/serve/server.js +490 -0
  218. package/dist/serve/shadowArt.d.ts +10 -0
  219. package/dist/serve/shadowArt.js +29 -0
  220. package/dist/shelf.d.ts +10 -0
  221. package/dist/shelf.js +23 -0
  222. package/package.json +60 -0
@@ -0,0 +1,113 @@
1
+ import { spawn } from "node:child_process";
2
+ import { flushTraceCarry, parseTraceChunk } from "./pyTracer.js";
3
+ export const DEFAULT_TIMEOUT_MS = 10_000;
4
+ export const DEFAULT_OUTPUT_CAP_BYTES = 256 * 1024;
5
+ /**
6
+ * Spawns exactly `command`/`args` with `child_process.spawn` (never a shell —
7
+ * no string ever gets shell-interpreted, so there's no injection surface
8
+ * beyond the allowlisted interpreter itself) in a detached process group on
9
+ * POSIX so a runaway child's own children die with it, a minimal env (PATH +
10
+ * HOME only — no inherited secrets from this server's own process env), and
11
+ * hard per-stream output caps that stop accumulating (and kill the process,
12
+ * see below) once reached.
13
+ */
14
+ export function runScript(command, args, opts) {
15
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
16
+ const capBytes = opts.outputCapBytes ?? DEFAULT_OUTPUT_CAP_BYTES;
17
+ const env = {};
18
+ if (process.env.PATH)
19
+ env.PATH = process.env.PATH;
20
+ if (process.env.HOME)
21
+ env.HOME = process.env.HOME;
22
+ const child = spawn(command, args, {
23
+ cwd: opts.cwd,
24
+ env,
25
+ detached: process.platform !== "win32",
26
+ stdio: ["ignore", "pipe", "pipe"],
27
+ });
28
+ let stdoutBytes = 0;
29
+ let stderrBytes = 0;
30
+ let stderrCarry = "";
31
+ let settled = false;
32
+ const killTree = (signal) => {
33
+ if (child.pid === undefined)
34
+ return;
35
+ try {
36
+ if (process.platform !== "win32")
37
+ process.kill(-child.pid, signal);
38
+ else
39
+ child.kill(signal);
40
+ }
41
+ catch {
42
+ // Already exited between the caller's decision to kill and this call.
43
+ }
44
+ };
45
+ const timer = setTimeout(() => {
46
+ opts.onEvent({ type: "timeout" });
47
+ killTree("SIGKILL");
48
+ }, timeoutMs);
49
+ child.stdout?.on("data", (chunk) => {
50
+ if (stdoutBytes >= capBytes)
51
+ return;
52
+ const slice = chunk.subarray(0, capBytes - stdoutBytes);
53
+ stdoutBytes += slice.length;
54
+ opts.onEvent({ type: "stdout", text: slice.toString("utf8") });
55
+ if (stdoutBytes >= capBytes) {
56
+ opts.onEvent({
57
+ type: "stdout",
58
+ text: "\n[stdout truncated: output cap reached]\n",
59
+ });
60
+ killTree("SIGKILL");
61
+ }
62
+ });
63
+ child.stderr?.on("data", (chunk) => {
64
+ if (stderrBytes >= capBytes)
65
+ return;
66
+ const slice = chunk.subarray(0, capBytes - stderrBytes);
67
+ stderrBytes += slice.length;
68
+ const raw = slice.toString("utf8");
69
+ if (opts.traced) {
70
+ const parsed = parseTraceChunk(stderrCarry, raw);
71
+ stderrCarry = parsed.carry;
72
+ for (const event of parsed.events)
73
+ opts.onEvent({ type: "line", line: event.line });
74
+ if (parsed.text)
75
+ opts.onEvent({ type: "stderr", text: parsed.text });
76
+ }
77
+ else if (raw) {
78
+ opts.onEvent({ type: "stderr", text: raw });
79
+ }
80
+ if (stderrBytes >= capBytes) {
81
+ opts.onEvent({
82
+ type: "stderr",
83
+ text: "\n[stderr truncated: output cap reached]\n",
84
+ });
85
+ killTree("SIGKILL");
86
+ }
87
+ });
88
+ const done = new Promise((resolveDone) => {
89
+ const finish = (code) => {
90
+ if (settled)
91
+ return;
92
+ settled = true;
93
+ clearTimeout(timer);
94
+ if (opts.traced) {
95
+ const rest = flushTraceCarry(stderrCarry);
96
+ if (rest)
97
+ opts.onEvent({ type: "stderr", text: rest });
98
+ }
99
+ opts.onEvent({ type: "exit", code });
100
+ resolveDone();
101
+ };
102
+ child.on("error", (err) => {
103
+ if (settled)
104
+ return;
105
+ settled = true;
106
+ clearTimeout(timer);
107
+ opts.onEvent({ type: "error", message: err.message });
108
+ resolveDone();
109
+ });
110
+ child.on("close", finish);
111
+ });
112
+ return { done, kill: killTree };
113
+ }
@@ -0,0 +1,15 @@
1
+ export interface HostPageOptions {
2
+ token: string;
3
+ allowExec: boolean;
4
+ /** `cabn serve --owner`: wires @cabn/engine/owner (signs + git clients) into CabnGame. Off, the bundle never references that module. */
5
+ owner?: boolean;
6
+ }
7
+ /** Bundles the tiny host entry (React + `@cabn/engine`, optionally the local-exec wiring) into one browser-ready ESM file, entirely in memory — no build artifact ever touches disk, so a fresh `cabn serve` in any checkout just works once `pnpm install` has run. */
8
+ export declare function bundleHostApp(opts: HostPageOptions): Promise<string>;
9
+ /**
10
+ * The owner token goes only into this page's inline script — never the URL
11
+ * (unlike the exec token, it isn't printed, so it doesn't end up in terminal
12
+ * scrollback or browser history). JSON.stringify of a hex string can't close
13
+ * the <script> element.
14
+ */
15
+ export declare function hostPageHtml(token: string, ownerToken?: string): string;
@@ -0,0 +1,100 @@
1
+ import { dirname, resolve } from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ import * as esbuild from "esbuild";
4
+ /**
5
+ * `React.createElement` directly rather than JSX — this string is bundled by
6
+ * esbuild at `cabn serve` startup (see bundleHostApp), and skipping a JSX
7
+ * loader/runtime means one less resolution edge (no `react/jsx-runtime`) for
8
+ * that bundle to depend on. `installLocalRunProvider` is only ever imported
9
+ * here when `--allow-exec` was passed; every other build of this page (and
10
+ * every hosted/demo build of `@cabn/engine` itself, which never imports
11
+ * `@cabn/engine/local-exec` at all) has no reference to it whatsoever — see
12
+ * that module's own docs for why that's the actual dead-code guarantee, not
13
+ * just the `__CABN_ALLOW_LOCAL_EXEC__` constant baked in below.
14
+ */
15
+ function entrySource(opts) {
16
+ const localExecWiring = opts.allowExec
17
+ ? [
18
+ 'import { installLocalRunProvider } from "@cabn/engine/local-exec";',
19
+ "installLocalRunProvider({ baseUrl: window.location.origin, token: window.__CABN_TOKEN__ });",
20
+ ].join("\n")
21
+ : "";
22
+ const ownerWiring = opts.owner
23
+ ? [
24
+ 'import { createOwnerGitClient, createServeOwnerSigns, createShadowLayer } from "@cabn/engine/owner";',
25
+ "const ownerOpts = { baseUrl: window.location.origin, token: window.__CABN_OWNER_TOKEN__ };",
26
+ "const owner = { git: createOwnerGitClient(ownerOpts), signs: createServeOwnerSigns(ownerOpts), layers: [createShadowLayer(ownerOpts)] };",
27
+ ].join("\n")
28
+ : "const owner = undefined;";
29
+ // Same opt-in hook as the demo's App.tsx: only a page loaded with ?e2e=1
30
+ // (the owner and spellbook-serve e2es) gets the store on window — a real
31
+ // serve host has no other way to reach a portal, since world layout is
32
+ // computed client-side. The owner token is already a page global, so this
33
+ // exposes nothing a script on the page couldn't read.
34
+ return `
35
+ import React from "react";
36
+ import { createRoot } from "react-dom/client";
37
+ import { CabnGame } from "@cabn/engine";
38
+ ${localExecWiring}
39
+ ${ownerWiring}
40
+ const onGameReady = new URLSearchParams(window.location.search).get("e2e") === "1"
41
+ ? (handle) => { window.__cabnStore = handle?.store; window.__cabnBus = handle?.bus; window.__cabnGame = handle?.game; }
42
+ : undefined;
43
+ const root = createRoot(document.getElementById("root"));
44
+ root.render(React.createElement(CabnGame, { worldUrl: "/world/world.json", pdfWorkerUrl: "/pdfjs/pdf.worker.min.mjs", owner, onGameReady }));
45
+ `;
46
+ }
47
+ // This file lives at packages/cli/dist/serve/hostPage.js once built — two
48
+ // levels up is the package root, where pnpm's per-package node_modules
49
+ // (containing @cabn/engine, react, react-dom, esbuild's own resolution
50
+ // target) actually lives.
51
+ const CLI_PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
52
+ /** Bundles the tiny host entry (React + `@cabn/engine`, optionally the local-exec wiring) into one browser-ready ESM file, entirely in memory — no build artifact ever touches disk, so a fresh `cabn serve` in any checkout just works once `pnpm install` has run. */
53
+ export async function bundleHostApp(opts) {
54
+ const result = await esbuild.build({
55
+ stdin: {
56
+ contents: entrySource(opts),
57
+ resolveDir: CLI_PACKAGE_ROOT,
58
+ loader: "js",
59
+ },
60
+ bundle: true,
61
+ write: false,
62
+ minify: true,
63
+ format: "esm",
64
+ platform: "browser",
65
+ target: "es2022",
66
+ define: {
67
+ "process.env.NODE_ENV": '"production"',
68
+ __CABN_ALLOW_LOCAL_EXEC__: opts.allowExec ? "true" : "false",
69
+ },
70
+ logLevel: "silent",
71
+ });
72
+ const output = result.outputFiles[0];
73
+ if (!output)
74
+ throw new Error("esbuild produced no output for the host page");
75
+ return output.text;
76
+ }
77
+ /**
78
+ * The owner token goes only into this page's inline script — never the URL
79
+ * (unlike the exec token, it isn't printed, so it doesn't end up in terminal
80
+ * scrollback or browser history). JSON.stringify of a hex string can't close
81
+ * the <script> element.
82
+ */
83
+ export function hostPageHtml(token, ownerToken) {
84
+ const ownerScript = ownerToken
85
+ ? `\n<script>window.__CABN_OWNER_TOKEN__ = ${JSON.stringify(ownerToken)};</script>`
86
+ : "";
87
+ return `<!doctype html>
88
+ <html lang="en">
89
+ <head>
90
+ <meta charset="utf-8" />
91
+ <title>cabn serve</title>
92
+ <style>html,body,#root{margin:0;height:100%;width:100%;background:#1f2a17;}</style>
93
+ </head>
94
+ <body>
95
+ <div id="root"></div>
96
+ <script>window.__CABN_TOKEN__ = ${JSON.stringify(token)};</script>${ownerScript}
97
+ <script type="module" src="/app.js?token=${encodeURIComponent(token)}"></script>
98
+ </body>
99
+ </html>`;
100
+ }
@@ -0,0 +1,80 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import type { z } from "zod";
3
+ export declare const OWNER_TOKEN_HEADER = "x-cabn-owner-token";
4
+ export declare const OWNER_BODY_MAX_BYTES: number;
5
+ /** 256 bits from the OS CSPRNG, hex — new every `cabn serve` start. */
6
+ export declare function generateOwnerToken(): string;
7
+ export declare function ownerTokenMatches(presented: unknown, expected: string): boolean;
8
+ /** Exactly `127.0.0.1:<port>` or `localhost:<port>`. */
9
+ export declare function isLoopbackHostHeader(host: string | undefined, port: number): boolean;
10
+ /** Exactly `http://127.0.0.1:<port>` or `http://localhost:<port>` — required, not optional as it is for page loads. */
11
+ export declare function isLoopbackOrigin(origin: string | undefined, port: number): boolean;
12
+ export type OwnerCheck = {
13
+ ok: true;
14
+ } | {
15
+ ok: false;
16
+ status: number;
17
+ reason: string;
18
+ };
19
+ /**
20
+ * `method` is the one the route expects (POST by default). A GET is only
21
+ * for read-only routes: browsers send no Origin on a same-origin GET, so
22
+ * there `Sec-Fetch-Site: same-origin` stands in for it; a present Origin
23
+ * must still be this server's. Writes always need the Origin.
24
+ */
25
+ export declare function checkOwnerRequest(req: IncomingMessage, opts: {
26
+ port: number;
27
+ token: string;
28
+ method?: "GET" | "POST";
29
+ }): OwnerCheck;
30
+ export declare function sendOwnerJson(res: ServerResponse, status: number, body: unknown): void;
31
+ export type OwnerBody<T> = {
32
+ ok: true;
33
+ data: T;
34
+ } | {
35
+ ok: false;
36
+ status: number;
37
+ reason: string;
38
+ };
39
+ /** Reads, size-caps, JSON-parses and schema-checks a request body. Never throws. */
40
+ export declare function readOwnerJson<T>(req: IncomingMessage, schema: z.ZodType<T>, maxBytes?: number): Promise<OwnerBody<T>>;
41
+ export declare class OwnerPathError extends Error {
42
+ readonly status: number;
43
+ constructor(message: string, status?: number);
44
+ }
45
+ export interface OwnerTarget {
46
+ /** Real (symlink-free) absolute path to write/delete. */
47
+ absolute: string;
48
+ /** Whether a regular file is already there. */
49
+ exists: boolean;
50
+ }
51
+ /**
52
+ * Confines a relative path from a request to `root`, for a file that may not
53
+ * exist yet: rejects absolute paths, backslashes, NUL/control characters,
54
+ * empty/`.`/`..` segments, any `.git` segment (case-folded, for
55
+ * case-insensitive file systems) and a wrong extension up front; then
56
+ * resolves the parent folder's *real* path (it must already exist and still
57
+ * be inside the real root, so a symlinked folder pointing outside is
58
+ * refused) and refuses a final component that is a symlink or not a regular
59
+ * file.
60
+ */
61
+ export declare function resolveOwnerTarget(root: string, relPath: string, opts?: {
62
+ extension?: string;
63
+ }): Promise<OwnerTarget>;
64
+ /**
65
+ * resolveOwnerTarget plus what an edit to an existing file needs on top: the
66
+ * file must exist and be a regular file, be reached with no symlink hop at
67
+ * all (resolveOwnerTarget allows a folder symlink that stays inside the
68
+ * root), and not sit inside the git directory (`gitdir` may live anywhere,
69
+ * e.g. `--git-dir`). Returns the real absolute path.
70
+ */
71
+ export declare function resolveExistingOwnerFile(root: string, relPath: string, gitdir?: string): Promise<string>;
72
+ /**
73
+ * Replaces a file's contents atomically: write a fresh temp file beside it,
74
+ * then rename over it — a reader never sees half a file, and rename replaces
75
+ * the directory entry itself rather than following whatever it points at.
76
+ * The original permission bits are carried over (a `.husky` hook keeps its
77
+ * exec bit); chmod after the write because writeFile's mode is filtered by
78
+ * the umask.
79
+ */
80
+ export declare function overwriteFileAtomic(target: string, content: string | Uint8Array): Promise<void>;
@@ -0,0 +1,241 @@
1
+ /**
2
+ * The one gate for `cabn serve --owner`'s owner API: every loopback-only
3
+ * route that reads hidden files or writes into the served folder
4
+ * (`/owner/signs/*` in ownerSigns.ts, `/owner/git/*` in ownerGit.ts,
5
+ * `/owner/shadow/*` in ownerShadow.ts) shares this session token
6
+ * and these checks. Self-contained on purpose (node built-ins + zod only).
7
+ * Every owner request must pass all of: exact loopback Host (DNS
8
+ * rebinding), no cross-site Sec-Fetch-Site, the per-session owner token in a
9
+ * header (constant-time compared), and — for writes — a present loopback
10
+ * Origin (the browser always sends one on a POST; a missing one means a
11
+ * non-browser or a stripped request) and a JSON content type (a plain HTML
12
+ * form can't send one). Bodies are size-capped and schema-checked; paths
13
+ * are confined to the served root with symlinks refused.
14
+ */
15
+ import { randomBytes, timingSafeEqual } from "node:crypto";
16
+ import { chmod, lstat, realpath, rename, rm, writeFile, } from "node:fs/promises";
17
+ import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
18
+ export const OWNER_TOKEN_HEADER = "x-cabn-owner-token";
19
+ export const OWNER_BODY_MAX_BYTES = 128 * 1024;
20
+ /** 256 bits from the OS CSPRNG, hex — new every `cabn serve` start. */
21
+ export function generateOwnerToken() {
22
+ return randomBytes(32).toString("hex");
23
+ }
24
+ export function ownerTokenMatches(presented, expected) {
25
+ if (typeof presented !== "string" || expected.length === 0)
26
+ return false;
27
+ const a = Buffer.from(presented, "utf8");
28
+ const b = Buffer.from(expected, "utf8");
29
+ // Length first: timingSafeEqual throws on unequal lengths, and the
30
+ // length of a fixed-size token isn't a secret.
31
+ return a.length === b.length && timingSafeEqual(a, b);
32
+ }
33
+ function isLoopbackName(hostname) {
34
+ const lower = hostname.toLowerCase();
35
+ return lower === "127.0.0.1" || lower === "localhost";
36
+ }
37
+ /** Exactly `127.0.0.1:<port>` or `localhost:<port>`. */
38
+ export function isLoopbackHostHeader(host, port) {
39
+ if (typeof host !== "string")
40
+ return false;
41
+ const m = /^([^:/\s]+):(\d{1,5})$/.exec(host);
42
+ return Boolean(m && isLoopbackName(m[1] ?? "") && Number(m[2]) === port);
43
+ }
44
+ /** Exactly `http://127.0.0.1:<port>` or `http://localhost:<port>` — required, not optional as it is for page loads. */
45
+ export function isLoopbackOrigin(origin, port) {
46
+ if (typeof origin !== "string")
47
+ return false;
48
+ const m = /^http:\/\/([^:/\s]+):(\d{1,5})$/.exec(origin);
49
+ return Boolean(m && isLoopbackName(m[1] ?? "") && Number(m[2]) === port);
50
+ }
51
+ function header(req, name) {
52
+ const v = req.headers[name];
53
+ return Array.isArray(v) ? v[0] : v;
54
+ }
55
+ /**
56
+ * `method` is the one the route expects (POST by default). A GET is only
57
+ * for read-only routes: browsers send no Origin on a same-origin GET, so
58
+ * there `Sec-Fetch-Site: same-origin` stands in for it; a present Origin
59
+ * must still be this server's. Writes always need the Origin.
60
+ */
61
+ export function checkOwnerRequest(req, opts) {
62
+ const method = opts.method ?? "POST";
63
+ if (req.method !== method)
64
+ return { ok: false, status: 405, reason: `use ${method}` };
65
+ if (!isLoopbackHostHeader(header(req, "host"), opts.port))
66
+ return { ok: false, status: 403, reason: "invalid host" };
67
+ const site = header(req, "sec-fetch-site");
68
+ if (site !== undefined && site !== "same-origin")
69
+ return { ok: false, status: 403, reason: "cross-site request" };
70
+ const origin = header(req, "origin");
71
+ const originOk = origin === undefined
72
+ ? method === "GET" && site === "same-origin"
73
+ : isLoopbackOrigin(origin, opts.port);
74
+ if (!originOk)
75
+ return { ok: false, status: 403, reason: "invalid origin" };
76
+ if (method === "POST") {
77
+ const type = (header(req, "content-type") ?? "").split(";")[0]?.trim();
78
+ if (type?.toLowerCase() !== "application/json")
79
+ return { ok: false, status: 415, reason: "expected application/json" };
80
+ }
81
+ if (!ownerTokenMatches(header(req, OWNER_TOKEN_HEADER), opts.token))
82
+ return { ok: false, status: 403, reason: "invalid owner token" };
83
+ return { ok: true };
84
+ }
85
+ export function sendOwnerJson(res, status, body) {
86
+ res.writeHead(status, {
87
+ "content-type": "application/json; charset=utf-8",
88
+ "cache-control": "no-store",
89
+ });
90
+ res.end(JSON.stringify(body));
91
+ }
92
+ /** Reads, size-caps, JSON-parses and schema-checks a request body. Never throws. */
93
+ export async function readOwnerJson(req, schema, maxBytes = OWNER_BODY_MAX_BYTES) {
94
+ const declared = Number(header(req, "content-length"));
95
+ if (Number.isFinite(declared) && declared > maxBytes)
96
+ return { ok: false, status: 413, reason: "request body too large" };
97
+ const chunks = [];
98
+ let total = 0;
99
+ try {
100
+ for await (const chunk of req) {
101
+ total += chunk.length;
102
+ if (total > maxBytes)
103
+ return { ok: false, status: 413, reason: "request body too large" };
104
+ chunks.push(chunk);
105
+ }
106
+ }
107
+ catch {
108
+ return { ok: false, status: 400, reason: "could not read request body" };
109
+ }
110
+ let json;
111
+ try {
112
+ json = JSON.parse(Buffer.concat(chunks).toString("utf8"));
113
+ }
114
+ catch {
115
+ return { ok: false, status: 400, reason: "invalid JSON" };
116
+ }
117
+ const parsed = schema.safeParse(json);
118
+ if (!parsed.success)
119
+ return {
120
+ ok: false,
121
+ status: 400,
122
+ reason: `invalid request: ${parsed.error.issues[0]?.message ?? "bad shape"}`,
123
+ };
124
+ return { ok: true, data: parsed.data };
125
+ }
126
+ export class OwnerPathError extends Error {
127
+ status;
128
+ constructor(message, status = 403) {
129
+ super(message);
130
+ this.status = status;
131
+ }
132
+ }
133
+ function inside(root, candidate) {
134
+ return candidate === root || candidate.startsWith(root + sep);
135
+ }
136
+ /**
137
+ * Confines a relative path from a request to `root`, for a file that may not
138
+ * exist yet: rejects absolute paths, backslashes, NUL/control characters,
139
+ * empty/`.`/`..` segments, any `.git` segment (case-folded, for
140
+ * case-insensitive file systems) and a wrong extension up front; then
141
+ * resolves the parent folder's *real* path (it must already exist and still
142
+ * be inside the real root, so a symlinked folder pointing outside is
143
+ * refused) and refuses a final component that is a symlink or not a regular
144
+ * file.
145
+ */
146
+ export async function resolveOwnerTarget(root, relPath, opts = {}) {
147
+ if (typeof relPath !== "string" ||
148
+ relPath.length === 0 ||
149
+ relPath.length > 512 ||
150
+ isAbsolute(relPath) ||
151
+ relPath.startsWith("/") ||
152
+ /^[A-Za-z]:/.test(relPath) ||
153
+ relPath.includes("\\") ||
154
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting them is the point
155
+ /[\u0000-\u001F\u007F]/.test(relPath))
156
+ throw new OwnerPathError("path must be relative to the served folder");
157
+ const segments = relPath.split("/");
158
+ if (segments.some((s) => s === "" || s === "." || s === ".."))
159
+ throw new OwnerPathError("path must not contain empty, . or .. segments");
160
+ if (segments.some((s) => s.toLowerCase() === ".git"))
161
+ throw new OwnerPathError("path must not be inside .git");
162
+ // Any segment, not just the first: "src/C:x" is drive-relative on Windows,
163
+ // the same per-segment rule sanitizeZipPath applies.
164
+ if (segments.some((s) => /^[A-Za-z]:/.test(s)))
165
+ throw new OwnerPathError("path must not contain a drive letter");
166
+ if (opts.extension !== undefined && !relPath.endsWith(opts.extension))
167
+ throw new OwnerPathError(`only ${opts.extension} files can be written`);
168
+ const realRoot = await realpath(root);
169
+ let realParent;
170
+ try {
171
+ realParent = await realpath(join(realRoot, dirname(relPath)));
172
+ }
173
+ catch {
174
+ throw new OwnerPathError("that folder does not exist", 404);
175
+ }
176
+ if (!inside(realRoot, realParent))
177
+ throw new OwnerPathError("path escapes the served folder");
178
+ const absolute = join(realParent, basename(relPath));
179
+ if (!inside(realRoot, absolute))
180
+ throw new OwnerPathError("path escapes the served folder");
181
+ try {
182
+ const stat = await lstat(absolute);
183
+ if (stat.isSymbolicLink())
184
+ throw new OwnerPathError("refusing to follow a symlink");
185
+ if (!stat.isFile())
186
+ throw new OwnerPathError("not a regular file");
187
+ return { absolute, exists: true };
188
+ }
189
+ catch (err) {
190
+ if (err instanceof OwnerPathError)
191
+ throw err;
192
+ if (err.code === "ENOENT")
193
+ return { absolute, exists: false };
194
+ throw err;
195
+ }
196
+ }
197
+ /**
198
+ * resolveOwnerTarget plus what an edit to an existing file needs on top: the
199
+ * file must exist and be a regular file, be reached with no symlink hop at
200
+ * all (resolveOwnerTarget allows a folder symlink that stays inside the
201
+ * root), and not sit inside the git directory (`gitdir` may live anywhere,
202
+ * e.g. `--git-dir`). Returns the real absolute path.
203
+ */
204
+ export async function resolveExistingOwnerFile(root, relPath, gitdir) {
205
+ const target = await resolveOwnerTarget(root, relPath);
206
+ if (!target.exists)
207
+ throw new OwnerPathError(`"${relPath}" does not exist`, 404);
208
+ const realRoot = await realpath(root);
209
+ if (relative(realRoot, target.absolute).split(sep).join("/") !== relPath)
210
+ throw new OwnerPathError(`"${relPath}" is reached through a symlink`);
211
+ if (gitdir !== undefined) {
212
+ const realGitdir = await realpath(gitdir).catch(() => gitdir);
213
+ if (inside(realGitdir, target.absolute))
214
+ throw new OwnerPathError(`"${relPath}" is inside the git directory`);
215
+ }
216
+ const stat = await lstat(target.absolute);
217
+ if (!stat.isFile())
218
+ throw new OwnerPathError(`"${relPath}" is not a regular file`);
219
+ return target.absolute;
220
+ }
221
+ /**
222
+ * Replaces a file's contents atomically: write a fresh temp file beside it,
223
+ * then rename over it — a reader never sees half a file, and rename replaces
224
+ * the directory entry itself rather than following whatever it points at.
225
+ * The original permission bits are carried over (a `.husky` hook keeps its
226
+ * exec bit); chmod after the write because writeFile's mode is filtered by
227
+ * the umask.
228
+ */
229
+ export async function overwriteFileAtomic(target, content) {
230
+ const mode = (await lstat(target)).mode & 0o7777;
231
+ const temp = join(dirname(target), `.${basename(target)}.${randomBytes(6).toString("hex")}.tmp`);
232
+ try {
233
+ await writeFile(temp, content, { flag: "wx", mode: 0o600 });
234
+ await chmod(temp, mode);
235
+ await rename(temp, target);
236
+ }
237
+ catch (err) {
238
+ await rm(temp, { force: true });
239
+ throw err;
240
+ }
241
+ }
@@ -0,0 +1,40 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { z } from "zod";
3
+ export declare const OWNER_GIT_ROUTES: {
4
+ readonly status: "/owner/git/status";
5
+ readonly commit: "/owner/git/commit";
6
+ readonly branch: "/owner/git/branch";
7
+ readonly checkout: "/owner/git/checkout";
8
+ };
9
+ export interface OwnerGitContext {
10
+ dir: string;
11
+ gitdir?: string;
12
+ port(): number;
13
+ /** The serve session's one owner token (shared with the signs routes). */
14
+ ownerToken: string;
15
+ /** World path -> the text the current world was converted from (text portals only). */
16
+ worldText(): ReadonlyMap<string, string>;
17
+ /** Re-converts the served world after a write, so the page reloads into it. */
18
+ reconvert(): Promise<void>;
19
+ }
20
+ export declare const BranchNameSchema: z.ZodString;
21
+ export declare const CommitBodySchema: z.ZodObject<{
22
+ message: z.ZodString;
23
+ author: z.ZodOptional<z.ZodObject<{
24
+ name: z.ZodString;
25
+ email: z.ZodString;
26
+ }, z.core.$strip>>;
27
+ files: z.ZodArray<z.ZodObject<{
28
+ path: z.ZodString;
29
+ content: z.ZodString;
30
+ }, z.core.$strict>>;
31
+ }, z.core.$strict>;
32
+ export declare const BranchBodySchema: z.ZodObject<{
33
+ name: z.ZodString;
34
+ checkout: z.ZodOptional<z.ZodBoolean>;
35
+ }, z.core.$strict>;
36
+ export declare const CheckoutBodySchema: z.ZodObject<{
37
+ branch: z.ZodString;
38
+ }, z.core.$strict>;
39
+ /** Returns false when the path isn't an owner-git route (the caller 404s). */
40
+ export declare function handleOwnerGit(req: IncomingMessage, res: ServerResponse, pathname: string, ctx: OwnerGitContext): Promise<boolean>;