@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,490 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import { createServer, } from "node:http";
4
+ import { createRequire } from "node:module";
5
+ import { basename, extname, posix, resolve as resolvePath } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { convert, DirSource, } from "@cabn/converter";
8
+ import { cliEmbedNetwork, cliGitInput } from "../build.js";
9
+ import { DEFAULT_OUTPUT_CAP_BYTES, DEFAULT_TIMEOUT_MS, runScript, } from "./execRunner.js";
10
+ import { bundleHostApp, hostPageHtml } from "./hostPage.js";
11
+ import { generateOwnerToken } from "./ownerAuth.js";
12
+ import { handleOwnerGit } from "./ownerGit.js";
13
+ import { handleOwnerShadow, ShadowRealm } from "./ownerShadow.js";
14
+ import { handleOwnerSignsRoute } from "./ownerSigns.js";
15
+ import { runtimeForPath } from "./runtime.js";
16
+ import { constantTimeEqual, frameSrcPolicy, isAllowedOrigin, isLoopbackHost, PathConfinementError, resolveConfinedPath, } from "./security.js";
17
+ import { resolveShadowArtDir, SHADOW_ART_HINT } from "./shadowArt.js";
18
+ export const DEFAULT_SERVE_PORT = 5178;
19
+ // A published @cabn/cli has scripts/copy-assets.mjs bundle the fixed sprite
20
+ // subset `cabn serve` actually uses into dist/assets at build time (dist/
21
+ // serve/server.js -> dist/assets) — this is what makes sprites work via
22
+ // `npx @cabn/cli serve` outside this monorepo.
23
+ const BUNDLED_ASSETS_DIR = resolvePath(fileURLToPath(import.meta.url), "../../assets");
24
+ // Falls back to this monorepo's own assets/generated/ (packages/cli/dist/
25
+ // serve/server.js -> repo root), same "hardcoded relative walk" apps/demo's
26
+ // build-world.mjs already does — covers running from source before a build
27
+ // (no dist/assets yet) and any sprite copy-assets.mjs doesn't bundle (e.g.
28
+ // art still on a parallel branch — see serveRepoAsset below).
29
+ const REPO_ASSETS_DIR = resolvePath(fileURLToPath(import.meta.url), "../../../../../assets/generated");
30
+ // pdf.js's worker, resolved through @cabn/engine (whose exact-pinned
31
+ // pdfjs-dist it must match) and served from this same loopback origin — the
32
+ // host page never loads it from a CDN.
33
+ export const PDF_WORKER_ROUTE = "/pdfjs/pdf.worker.min.mjs";
34
+ function resolvePdfWorkerPath() {
35
+ try {
36
+ const enginePath = fileURLToPath(import.meta.resolve("@cabn/engine"));
37
+ return createRequire(enginePath).resolve("pdfjs-dist/build/pdf.worker.min.mjs");
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ }
43
+ const MEDIA_CONTENT_TYPES = {
44
+ ".jpg": "image/jpeg",
45
+ ".gif": "image/gif",
46
+ ".mp3": "audio/mpeg",
47
+ ".wav": "audio/wav",
48
+ ".ogg": "audio/ogg",
49
+ ".pdf": "application/pdf",
50
+ };
51
+ function contentTypeFor(path) {
52
+ const ext = extname(path).toLowerCase();
53
+ if (ext === ".json")
54
+ return "application/json; charset=utf-8";
55
+ if (ext === ".webp")
56
+ return "image/webp";
57
+ if (ext === ".png")
58
+ return "image/png";
59
+ const media = MEDIA_CONTENT_TYPES[ext];
60
+ if (media)
61
+ return media;
62
+ if (ext === ".js" || ext === ".mjs")
63
+ return "text/javascript; charset=utf-8";
64
+ if (ext === ".html")
65
+ return "text/html; charset=utf-8";
66
+ return "application/octet-stream";
67
+ }
68
+ async function readJsonBody(req, maxBytes = 8 * 1024) {
69
+ const chunks = [];
70
+ let total = 0;
71
+ for await (const chunk of req) {
72
+ total += chunk.length;
73
+ if (total > maxBytes)
74
+ throw new Error("request body too large");
75
+ chunks.push(chunk);
76
+ }
77
+ const text = Buffer.concat(chunks).toString("utf8");
78
+ return text ? JSON.parse(text) : {};
79
+ }
80
+ function serveWorldAsset(res, bundle, key) {
81
+ const value = bundle.get(key);
82
+ if (value === undefined) {
83
+ res.writeHead(404);
84
+ res.end("not found");
85
+ return;
86
+ }
87
+ res.writeHead(200, { "content-type": contentTypeFor(key) });
88
+ res.end(value);
89
+ }
90
+ /** `shadow/...` under the asset root, however spelled (case-insensitive filesystems, `./`, doubled slashes). */
91
+ export function isShadowAssetPath(relPath) {
92
+ const first = posix
93
+ .normalize(relPath)
94
+ .split("/")
95
+ .find((s) => s !== "" && s !== ".");
96
+ return first?.toLowerCase() === "shadow";
97
+ }
98
+ // What the engine loads from /assets/: images, plus room for audio and fonts.
99
+ // Anything else in those trees (the UI mockup's .html, manifests, notes) would
100
+ // otherwise be served from this origin, html as a live page beside the token.
101
+ const REPO_ASSET_TYPES = {
102
+ ".png": "image/png",
103
+ ".webp": "image/webp",
104
+ ".gif": "image/gif",
105
+ ".jpg": "image/jpeg",
106
+ ".jpeg": "image/jpeg",
107
+ ".mp3": "audio/mpeg",
108
+ ".ogg": "audio/ogg",
109
+ ".wav": "audio/wav",
110
+ ".woff": "font/woff",
111
+ ".woff2": "font/woff2",
112
+ };
113
+ // The host page carries the session token and drives owner writes, so no
114
+ // other page may frame it (clickjacking). Only cabn serve's own page; the
115
+ // demo and hosted builds set their own headers.
116
+ function hostPagePolicy(frameSrc) {
117
+ return `${frameSrc}; frame-ancestors 'none'`;
118
+ }
119
+ async function serveRepoAsset(res, relPath,
120
+ // Bundled dist/assets checked first so a published install wins even if
121
+ // this happens to also be running inside the monorepo checkout.
122
+ bases = [BUNDLED_ASSETS_DIR, REPO_ASSETS_DIR]) {
123
+ const contentType = REPO_ASSET_TYPES[extname(relPath).toLowerCase()];
124
+ if (!contentType) {
125
+ res.writeHead(404);
126
+ res.end("not found");
127
+ return;
128
+ }
129
+ for (const base of bases) {
130
+ try {
131
+ const real = await resolveConfinedPath(base, relPath);
132
+ // A symlinked name mustn't relabel some other file type.
133
+ if (REPO_ASSET_TYPES[extname(real).toLowerCase()] !== contentType)
134
+ continue;
135
+ const data = await readFile(real);
136
+ res.writeHead(200, { "content-type": contentType });
137
+ res.end(data);
138
+ return;
139
+ }
140
+ catch {
141
+ // try the next candidate
142
+ }
143
+ }
144
+ // Best-effort: neither location has this sprite — the engine's own
145
+ // PreloadScene already falls back to tinted placeholders for any sprite
146
+ // that 404s, so this degrades rather than breaks.
147
+ res.writeHead(404);
148
+ res.end("not found");
149
+ }
150
+ /**
151
+ * Every request's gate, checked before any routing (see handleRequest) — not
152
+ * just /exec. A GET on `/`, `/app.js`, `/world/*`, or `/assets/*` answered
153
+ * over a rebound hostname would hand a hostile page the full world bundle
154
+ * (source code, via world.json + its chunks) and the session token embedded
155
+ * in the host page HTML; the token then being exec-only-checked would be
156
+ * defense-in-depth against the wrong threat. Host is checked unconditionally;
157
+ * Origin only when the request actually carries one (most non-browser
158
+ * clients never send it, and a same-origin navigation to `/` won't either).
159
+ */
160
+ function isRequestFromLoopback(req, ctx) {
161
+ if (!isLoopbackHost(req.headers.host, ctx.port)) {
162
+ return { ok: false, reason: "invalid host" };
163
+ }
164
+ const origin = req.headers.origin;
165
+ if (origin !== undefined &&
166
+ !isAllowedOrigin(Array.isArray(origin) ? origin[0] : origin, ctx.port)) {
167
+ return { ok: false, reason: "invalid origin" };
168
+ }
169
+ return { ok: true };
170
+ }
171
+ /** Token check only — Host/Origin are already gated for every request by isRequestFromLoopback before handleRequest ever routes here. */
172
+ function isExecTokenValid(req, ctx) {
173
+ const tokenHeader = req.headers["x-cabn-token"];
174
+ const presented = Array.isArray(tokenHeader) ? tokenHeader[0] : tokenHeader;
175
+ return (Boolean(presented) && constantTimeEqual(presented, ctx.token));
176
+ }
177
+ function isPageTokenValid(url, ctx) {
178
+ const presented = url.searchParams.get("token");
179
+ return presented !== null && constantTimeEqual(presented, ctx.token);
180
+ }
181
+ async function handleExec(req, res, ctx) {
182
+ if (!isExecTokenValid(req, ctx)) {
183
+ res.writeHead(403, { "content-type": "text/plain" });
184
+ res.end("invalid token");
185
+ return;
186
+ }
187
+ let body;
188
+ try {
189
+ body = await readJsonBody(req);
190
+ }
191
+ catch {
192
+ res.writeHead(400);
193
+ res.end("invalid request body");
194
+ return;
195
+ }
196
+ const relPath = typeof body === "object" && body !== null && "path" in body
197
+ ? body.path
198
+ : undefined;
199
+ if (typeof relPath !== "string") {
200
+ res.writeHead(400);
201
+ res.end('expected { "path": string }');
202
+ return;
203
+ }
204
+ let absolutePath;
205
+ try {
206
+ absolutePath = await resolveConfinedPath(ctx.dir, relPath);
207
+ }
208
+ catch (err) {
209
+ if (err instanceof PathConfinementError) {
210
+ res.writeHead(403);
211
+ res.end("path is outside the served directory");
212
+ return;
213
+ }
214
+ throw err;
215
+ }
216
+ const runtime = runtimeForPath(absolutePath);
217
+ if (!runtime) {
218
+ res.writeHead(400);
219
+ res.end("unsupported file extension");
220
+ return;
221
+ }
222
+ res.writeHead(200, {
223
+ "content-type": "application/x-ndjson; charset=utf-8",
224
+ "cache-control": "no-store",
225
+ });
226
+ const running = runScript(runtime.command, runtime.buildArgs(absolutePath), {
227
+ cwd: ctx.dir,
228
+ traced: runtime.traced,
229
+ timeoutMs: ctx.timeoutMs ?? DEFAULT_TIMEOUT_MS,
230
+ outputCapBytes: ctx.outputCapBytes ?? DEFAULT_OUTPUT_CAP_BYTES,
231
+ onEvent: (event) => {
232
+ if (!res.writableEnded)
233
+ res.write(`${JSON.stringify(event)}\n`);
234
+ },
235
+ });
236
+ const onDisconnect = () => running.kill("SIGKILL");
237
+ req.once("close", onDisconnect);
238
+ res.once("close", onDisconnect);
239
+ await running.done;
240
+ req.off("close", onDisconnect);
241
+ res.off("close", onDisconnect);
242
+ if (!res.writableEnded)
243
+ res.end();
244
+ }
245
+ async function handleRequest(req, res, ctx) {
246
+ // Applied to every response regardless of route or outcome — nosniff and
247
+ // no-referrer cost nothing on a 403/404 either, and the token lives in
248
+ // both the page HTML and the printed URL's query string, so no-referrer
249
+ // matters even off the "/" route (an asset load from the host page is
250
+ // still a request "from" a page whose URL contains the token).
251
+ res.setHeader("X-Content-Type-Options", "nosniff");
252
+ res.setHeader("Referrer-Policy", "no-referrer");
253
+ const loopback = isRequestFromLoopback(req, ctx);
254
+ if (!loopback.ok) {
255
+ res.writeHead(403, { "content-type": "text/plain" });
256
+ res.end(loopback.reason);
257
+ return;
258
+ }
259
+ const url = new URL(req.url ?? "/", `http://${ctx.host}:${ctx.port}`);
260
+ if (req.method === "GET" && url.pathname === "/") {
261
+ // Host/Origin alone don't stop another local process from reading the
262
+ // page and lifting both tokens out of it; only whoever saw the printed
263
+ // URL gets it. 404 rather than 403, as for the absent routes below.
264
+ if (!isPageTokenValid(url, ctx)) {
265
+ res.writeHead(404);
266
+ res.end("not found");
267
+ return;
268
+ }
269
+ // The page embeds the session token in a <script> — never cacheable,
270
+ // including by an intermediary that might otherwise serve it back to a
271
+ // different origin's request.
272
+ res.writeHead(200, {
273
+ "content-type": "text/html; charset=utf-8",
274
+ "cache-control": "no-store",
275
+ "content-security-policy": hostPagePolicy(ctx.csp),
276
+ });
277
+ res.end(ctx.html);
278
+ return;
279
+ }
280
+ if (req.method === "GET" && url.pathname === "/app.js") {
281
+ res.writeHead(200, { "content-type": "text/javascript; charset=utf-8" });
282
+ res.end(ctx.hostAppJs);
283
+ return;
284
+ }
285
+ if (req.method === "GET" && url.pathname.startsWith("/world/")) {
286
+ serveWorldAsset(res, ctx.bundle, url.pathname.slice("/world/".length));
287
+ return;
288
+ }
289
+ if (req.method === "GET" && url.pathname.startsWith("/assets/")) {
290
+ const rel = url.pathname.slice("/assets/".length);
291
+ if (isShadowAssetPath(rel)) {
292
+ // The shadow realm's art exists only for the owner, like its routes.
293
+ if (!ctx.ownerToken || !ctx.shadowArtDir) {
294
+ res.writeHead(404);
295
+ res.end("not found");
296
+ return;
297
+ }
298
+ const inShadow = posix
299
+ .normalize(rel)
300
+ .split("/")
301
+ .filter((s) => s !== "" && s !== ".")
302
+ .slice(1)
303
+ .join("/");
304
+ await serveRepoAsset(res, inShadow, [ctx.shadowArtDir]);
305
+ return;
306
+ }
307
+ await serveRepoAsset(res, rel);
308
+ return;
309
+ }
310
+ if (req.method === "GET" && url.pathname === PDF_WORKER_ROUTE) {
311
+ const workerPath = resolvePdfWorkerPath();
312
+ if (workerPath) {
313
+ res.writeHead(200, { "content-type": contentTypeFor(workerPath) });
314
+ res.end(await readFile(workerPath));
315
+ return;
316
+ }
317
+ }
318
+ // Registered only when --allow-exec was passed at all — with it absent,
319
+ // this falls through to the generic 404 below exactly as if the route
320
+ // never existed, not a 403 that would confirm the capability is merely
321
+ // gated rather than genuinely absent.
322
+ if (req.method === "POST" && url.pathname === "/exec" && ctx.allowExec) {
323
+ await handleExec(req, res, ctx);
324
+ return;
325
+ }
326
+ // Same "absent, not forbidden" rule as /exec: without --owner these routes don't exist.
327
+ if (ctx.ownerToken && url.pathname.startsWith("/owner/")) {
328
+ const handled = (ctx.owner &&
329
+ (await handleOwnerGit(req, res, url.pathname, ctx.owner))) ||
330
+ (ctx.shadow &&
331
+ (await handleOwnerShadow(req, res, url.pathname, {
332
+ dir: ctx.dir,
333
+ port: () => ctx.port,
334
+ ownerToken: ctx.ownerToken,
335
+ shadow: ctx.shadow,
336
+ }))) ||
337
+ (await handleOwnerSignsRoute(req, res, url.pathname, {
338
+ dir: ctx.dir,
339
+ port: ctx.port,
340
+ ownerToken: ctx.ownerToken,
341
+ bundle: ctx.bundle,
342
+ ...(ctx.shadow ? { shadow: ctx.shadow } : {}),
343
+ }));
344
+ if (handled)
345
+ return;
346
+ }
347
+ res.writeHead(404);
348
+ res.end("not found");
349
+ }
350
+ /** Top-level chunks only (universes/ has its own): the text each world portal was converted from. */
351
+ export function worldTextFromBundle(bundle) {
352
+ const text = new Map();
353
+ for (const [key, value] of bundle) {
354
+ if (!key.startsWith("chunks/") || typeof value !== "string")
355
+ continue;
356
+ const chunk = JSON.parse(value);
357
+ for (const [path, file] of Object.entries(chunk.files ?? {})) {
358
+ if (typeof file.content === "string")
359
+ text.set(path, file.content);
360
+ }
361
+ }
362
+ return text;
363
+ }
364
+ function worldEmbedOrigins(bundle) {
365
+ const raw = bundle.get("world.json");
366
+ if (typeof raw !== "string")
367
+ return [];
368
+ const origins = JSON.parse(raw)
369
+ .allowedEmbedOrigins;
370
+ return Array.isArray(origins) ? origins : [];
371
+ }
372
+ /**
373
+ * Converts `dir` in memory and starts serving it — binds to 127.0.0.1 only
374
+ * (never configurable to 0.0.0.0 from the CLI surface; `opts.host` exists
375
+ * solely so tests can exercise the refusal path below without a real
376
+ * flag). See handleExec/isExecRequestAuthorized for the exec endpoint's own
377
+ * gate, and REPO_ASSETS_DIR's doc for why sprites are best-effort outside
378
+ * this monorepo.
379
+ */
380
+ export async function startServe(dir, opts = {}) {
381
+ const host = opts.host ?? "127.0.0.1";
382
+ const port = opts.port ?? DEFAULT_SERVE_PORT;
383
+ const allowExec = opts.allowExec ?? false;
384
+ if (allowExec && host !== "127.0.0.1") {
385
+ throw new Error(`cabn serve --allow-exec refuses a non-loopback host ("${host}") — real code execution is only ever offered on 127.0.0.1.`);
386
+ }
387
+ if (opts.owner && host !== "127.0.0.1") {
388
+ throw new Error(`cabn serve --owner refuses a non-loopback host ("${host}") — repository writes are only ever offered on 127.0.0.1.`);
389
+ }
390
+ const resolvedDir = resolvePath(dir);
391
+ const token = randomBytes(32).toString("hex");
392
+ const convertWorld = () => convert(new DirSource(resolvedDir), {
393
+ name: basename(resolvedDir),
394
+ source: resolvedDir,
395
+ embedNetwork: cliEmbedNetwork(opts.offline),
396
+ git: cliGitInput(resolvedDir, opts),
397
+ onWarning: (message) => console.warn(`cabn serve: ${message}`),
398
+ });
399
+ const bundle = await convertWorld();
400
+ const ownerToken = opts.owner ? generateOwnerToken() : undefined;
401
+ const hostAppJs = await bundleHostApp({
402
+ token,
403
+ allowExec,
404
+ owner: ownerToken !== undefined,
405
+ });
406
+ const html = hostPageHtml(token, ownerToken);
407
+ const ctx = {
408
+ dir: resolvedDir,
409
+ host,
410
+ port,
411
+ token,
412
+ ownerToken,
413
+ allowExec,
414
+ bundle,
415
+ hostAppJs,
416
+ html,
417
+ csp: frameSrcPolicy(worldEmbedOrigins(bundle)),
418
+ timeoutMs: opts.timeoutMs,
419
+ outputCapBytes: opts.outputCapBytes,
420
+ owner: undefined,
421
+ shadow: undefined,
422
+ shadowArtDir: undefined,
423
+ };
424
+ let worldText = worldTextFromBundle(bundle);
425
+ if (ownerToken) {
426
+ ctx.shadowArtDir =
427
+ opts.shadowArtDir === undefined
428
+ ? await resolveShadowArtDir(resolvePath(REPO_ASSETS_DIR, "shadow"))
429
+ : (opts.shadowArtDir ?? undefined);
430
+ ctx.shadow = new ShadowRealm({
431
+ dir: resolvedDir,
432
+ ...(opts.gitDir ? { gitdir: resolvePath(opts.gitDir) } : {}),
433
+ bundle: () => ctx.bundle,
434
+ });
435
+ ctx.owner = {
436
+ dir: resolvedDir,
437
+ ...(opts.gitDir ? { gitdir: resolvePath(opts.gitDir) } : {}),
438
+ port: () => ctx.port,
439
+ ownerToken,
440
+ worldText: () => worldText,
441
+ reconvert: async () => {
442
+ const next = await convertWorld();
443
+ ctx.bundle = next;
444
+ ctx.csp = frameSrcPolicy(worldEmbedOrigins(next));
445
+ worldText = worldTextFromBundle(next);
446
+ ctx.shadow?.clear();
447
+ },
448
+ };
449
+ }
450
+ const server = createServer((req, res) => {
451
+ handleRequest(req, res, ctx).catch((err) => {
452
+ if (!res.writableEnded) {
453
+ res.writeHead(500);
454
+ res.end("internal error");
455
+ }
456
+ console.error("cabn serve: request handler error", err);
457
+ });
458
+ });
459
+ await new Promise((resolveListen, rejectListen) => {
460
+ server.once("error", rejectListen);
461
+ server.listen(port, host, () => resolveListen());
462
+ });
463
+ // `port: 0` (tests only — never a real CLI flag value) asks the OS for an
464
+ // ephemeral port; ctx.port must reflect whatever it actually picked, since
465
+ // every Host/Origin check below compares against it.
466
+ const boundAddress = server.address();
467
+ if (boundAddress && typeof boundAddress === "object") {
468
+ ctx.port = boundAddress.port;
469
+ }
470
+ const url = `http://${host}:${ctx.port}/?token=${token}`;
471
+ if (allowExec) {
472
+ console.log(`\n\u001b[31m\u001b[1mREAL CODE EXECUTION ENABLED for ${resolvedDir} — only use with code you trust.\u001b[0m\n`);
473
+ }
474
+ if (ownerToken) {
475
+ console.log(`\u001b[33mOwner mode: this page can edit signs, commit edits and create/switch branches in ${resolvedDir} (never push or fetch).\u001b[0m`);
476
+ if (!ctx.shadowArtDir)
477
+ console.log(SHADOW_ART_HINT);
478
+ }
479
+ console.log(`cabn serve: ${url}`);
480
+ return {
481
+ server,
482
+ url,
483
+ token,
484
+ ownerToken,
485
+ port: ctx.port,
486
+ close: () => new Promise((resolveClose) => {
487
+ server.close(() => resolveClose());
488
+ }),
489
+ };
490
+ }
@@ -0,0 +1,10 @@
1
+ export declare const SHADOW_ART_HINT = "cabn serve: install @cabn/shadow-art for the full nether look (npm i -g @cabn/shadow-art, or beside @cabn/cli). The shadow realm works without it, tint only.";
2
+ /**
3
+ * Where `cabn serve --owner` reads `/assets/shadow/*` from: the optional
4
+ * `@cabn/shadow-art` package when it's installed and built, else this
5
+ * monorepo's `assets/generated/shadow/`, else nowhere (the engine's
6
+ * resolveSkin then drops every texture group and the realm shows tint only).
7
+ * The art is a separate package so a default `@cabn/cli` install doesn't
8
+ * carry ~14MB that only owner mode uses.
9
+ */
10
+ export declare function resolveShadowArtDir(repoShadowDir: string): Promise<string | undefined>;
@@ -0,0 +1,29 @@
1
+ import { stat } from "node:fs/promises";
2
+ export const SHADOW_ART_HINT = "cabn serve: install @cabn/shadow-art for the full nether look (npm i -g @cabn/shadow-art, or beside @cabn/cli). The shadow realm works without it, tint only.";
3
+ async function isDir(path) {
4
+ try {
5
+ return (await stat(path)).isDirectory();
6
+ }
7
+ catch {
8
+ return false;
9
+ }
10
+ }
11
+ /**
12
+ * Where `cabn serve --owner` reads `/assets/shadow/*` from: the optional
13
+ * `@cabn/shadow-art` package when it's installed and built, else this
14
+ * monorepo's `assets/generated/shadow/`, else nowhere (the engine's
15
+ * resolveSkin then drops every texture group and the realm shows tint only).
16
+ * The art is a separate package so a default `@cabn/cli` install doesn't
17
+ * carry ~14MB that only owner mode uses.
18
+ */
19
+ export async function resolveShadowArtDir(repoShadowDir) {
20
+ try {
21
+ const { shadowAssetsDir } = await import("@cabn/shadow-art");
22
+ if (await isDir(shadowAssetsDir))
23
+ return shadowAssetsDir;
24
+ }
25
+ catch {
26
+ // Not installed: an optional peer dependency.
27
+ }
28
+ return (await isDir(repoShadowDir)) ? repoShadowDir : undefined;
29
+ }
@@ -0,0 +1,10 @@
1
+ export interface ShelfSummary {
2
+ outDir: string;
3
+ worlds: number;
4
+ }
5
+ export interface ShelfOptions {
6
+ outDir?: string;
7
+ /** Shelf display name (meta.name). Defaults to "My Worlds". */
8
+ name?: string;
9
+ }
10
+ export declare function runShelf(bundleDirs: string[], opts?: ShelfOptions): Promise<ShelfSummary>;
package/dist/shelf.js ADDED
@@ -0,0 +1,23 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { join, relative, resolve, sep } from "node:path";
3
+ import { buildShelf } from "@cabn/converter";
4
+ import { validateManifest } from "@cabn/world-schema";
5
+ // Windows path separators would otherwise leak into a URL the browser has to
6
+ // fetch relative to shelf.json's own location.
7
+ function toUrlPath(path) {
8
+ return sep === "/" ? path : path.split(sep).join("/");
9
+ }
10
+ export async function runShelf(bundleDirs, opts = {}) {
11
+ const outDir = resolve(opts.outDir ?? "./shelf");
12
+ await mkdir(outDir, { recursive: true });
13
+ const worlds = await Promise.all(bundleDirs.map(async (bundleDir) => {
14
+ const resolvedBundleDir = resolve(bundleDir);
15
+ const raw = await readFile(join(resolvedBundleDir, "world.json"), "utf8");
16
+ const manifest = validateManifest(JSON.parse(raw));
17
+ const worldUrl = `${toUrlPath(relative(outDir, resolvedBundleDir))}/world.json`;
18
+ return { name: manifest.meta.name, worldUrl, manifest };
19
+ }));
20
+ const shelf = buildShelf(worlds, { name: opts.name });
21
+ await writeFile(join(outDir, "shelf.json"), `${JSON.stringify(shelf, null, 2)}\n`);
22
+ return { outDir, worlds: shelf.worlds.length };
23
+ }
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@cabn/cli",
3
+ "version": "0.1.0",
4
+ "description": "The cabn CLI: build/inspect a world bundle, build a shelf of worlds, and cabn serve for a local walkable game with optional real code execution.",
5
+ "keywords": [
6
+ "cabn",
7
+ "cli"
8
+ ],
9
+ "license": "MIT",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/SebastianFrazier26/cabn.git",
13
+ "directory": "packages/cli"
14
+ },
15
+ "homepage": "https://github.com/SebastianFrazier26/cabn/tree/main/packages/cli#readme",
16
+ "type": "module",
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "bin": {
21
+ "cabn": "dist/main.js"
22
+ },
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ }
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
34
+ "dependencies": {
35
+ "@cabn/converter": "0.1.0",
36
+ "@cabn/engine": "0.1.0",
37
+ "@cabn/world-schema": "0.1.0",
38
+ "esbuild": "^0.27.0",
39
+ "isomorphic-git": "1.42.2",
40
+ "react": "^19.3.0",
41
+ "react-dom": "^19.3.0",
42
+ "zod": "^4.6.5"
43
+ },
44
+ "peerDependencies": {
45
+ "@cabn/shadow-art": "^0.1.0"
46
+ },
47
+ "peerDependenciesMeta": {
48
+ "@cabn/shadow-art": {
49
+ "optional": true
50
+ }
51
+ },
52
+ "devDependencies": {
53
+ "@cabn/shadow-art": "0.1.0",
54
+ "@types/node": "^22.20.4"
55
+ },
56
+ "scripts": {
57
+ "build": "tsc -p tsconfig.json && node scripts/copy-assets.mjs",
58
+ "test": "vitest run"
59
+ }
60
+ }