@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,224 @@
1
+ /**
2
+ * `cabn serve`'s owner routes for signs: create/overwrite and delete `.seyn`
3
+ * files in the served folder, then update the in-memory bundle's signs.json
4
+ * so a reload shows the change without restarting. Only the host page, which
5
+ * carries the per-session owner token, can call these — see ownerAuth.ts for
6
+ * the gate every request passes first. No shell, no other file types.
7
+ * `realm: "shadow"` signs live in hidden folders and only ever update the
8
+ * shadow realm's cached layer (ownerShadow.ts), never signs.json.
9
+ */
10
+ import { unlink, writeFile } from "node:fs/promises";
11
+ import { buildSignEntry, DEFAULT_IGNORES, isHiddenPath, } from "@cabn/converter";
12
+ import { parseSignIndex, SEYN_EXTENSION, SEYN_MAX_BYTES, SIGN_INDEX_FILENAME, SIGN_INDEX_VERSION, } from "@cabn/world-schema";
13
+ import { z } from "zod";
14
+ import { checkOwnerRequest, OwnerPathError, overwriteFileAtomic, readOwnerJson, resolveOwnerTarget, } from "./ownerAuth.js";
15
+ export const OWNER_SIGNS_SAVE_ROUTE = "/owner/signs/save";
16
+ export const OWNER_SIGNS_DELETE_ROUTE = "/owner/signs/delete";
17
+ const IGNORED_SEGMENTS = new Set(DEFAULT_IGNORES);
18
+ const IGNORED_SEGMENTS_FOLDED = new Set(DEFAULT_IGNORES.map((s) => s.toLowerCase()));
19
+ /**
20
+ * Stricter than ownerAuth's generic confinement: plain names only (the same
21
+ * rule the engine's editor checks, systems/signs.ts isValidSignFileName), no
22
+ * hidden folders (.git and friends), and nothing inside a folder the
23
+ * converter ignores — a sign saved there would vanish on the next start.
24
+ */
25
+ export function isAllowedSignPath(path) {
26
+ if (path.length === 0 || path.length > 512)
27
+ return false;
28
+ const segments = path.split("/");
29
+ const file = segments.pop() ?? "";
30
+ if (!/^[A-Za-z0-9][A-Za-z0-9._ -]{0,100}\.seyn$/.test(file))
31
+ return false;
32
+ return segments.every((s) => /^[A-Za-z0-9_][A-Za-z0-9._ -]{0,100}$/.test(s) &&
33
+ !IGNORED_SEGMENTS.has(s));
34
+ }
35
+ /**
36
+ * The shadow realm's rule: the sign must sit in a hidden folder — that is
37
+ * what makes it a shadow sign — but never in `.git` or a folder the
38
+ * converter ignores (`.venv`, `node_modules`, ...), both case-folded for
39
+ * case-insensitive file systems. The file name still starts with a letter
40
+ * or digit.
41
+ */
42
+ export function isAllowedShadowSignPath(path) {
43
+ if (path.length === 0 || path.length > 512)
44
+ return false;
45
+ const segments = path.split("/");
46
+ const file = segments.pop() ?? "";
47
+ if (!/^[A-Za-z0-9][A-Za-z0-9._ -]{0,100}\.seyn$/.test(file))
48
+ return false;
49
+ if (!segments.some((s) => s.startsWith(".")))
50
+ return false;
51
+ return segments.every((s) => /^[A-Za-z0-9_.][A-Za-z0-9._ -]{0,100}$/.test(s) &&
52
+ s !== "." &&
53
+ s !== ".." &&
54
+ s.toLowerCase() !== ".git" &&
55
+ !IGNORED_SEGMENTS_FOLDED.has(s.toLowerCase()));
56
+ }
57
+ function signPathAllowed(path, realm) {
58
+ return realm === "shadow"
59
+ ? isAllowedShadowSignPath(path) && isHiddenPath(path)
60
+ : isAllowedSignPath(path);
61
+ }
62
+ const RealmField = z.enum(["normal", "shadow"]).optional();
63
+ const SaveBodySchema = z
64
+ .strictObject({
65
+ path: z.string(),
66
+ content: z.string(),
67
+ create: z.boolean(),
68
+ realm: RealmField,
69
+ })
70
+ .refine((b) => signPathAllowed(b.path, b.realm), {
71
+ message: "not an allowed .seyn path",
72
+ });
73
+ const DeleteBodySchema = z
74
+ .strictObject({ path: z.string(), realm: RealmField })
75
+ .refine((b) => signPathAllowed(b.path, b.realm), {
76
+ message: "not an allowed .seyn path",
77
+ });
78
+ function sendJson(res, status, body) {
79
+ res.writeHead(status, {
80
+ "content-type": "application/json; charset=utf-8",
81
+ "cache-control": "no-store",
82
+ });
83
+ res.end(JSON.stringify(body));
84
+ }
85
+ function currentSigns(bundle) {
86
+ const raw = bundle.get(SIGN_INDEX_FILENAME);
87
+ if (typeof raw !== "string")
88
+ return [];
89
+ try {
90
+ return parseSignIndex(JSON.parse(raw));
91
+ }
92
+ catch {
93
+ return [];
94
+ }
95
+ }
96
+ function writeSigns(bundle, signs) {
97
+ const file = {
98
+ signsVersion: SIGN_INDEX_VERSION,
99
+ signs: [...signs].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0),
100
+ };
101
+ bundle.set(SIGN_INDEX_FILENAME, JSON.stringify(file, null, 2));
102
+ }
103
+ function worldIndex(bundle) {
104
+ const raw = bundle.get("world.json");
105
+ const manifest = (typeof raw === "string" ? JSON.parse(raw) : { clusters: [], portals: [] });
106
+ return {
107
+ portalIds: new Set(manifest.portals.map((p) => p.id)),
108
+ clusters: manifest.clusters,
109
+ };
110
+ }
111
+ /** Returns true when it handled the request (any owner-signs route); false for every other path, which the caller routes as before. */
112
+ export async function handleOwnerSignsRoute(req, res, pathname, ctx) {
113
+ if (pathname !== OWNER_SIGNS_SAVE_ROUTE &&
114
+ pathname !== OWNER_SIGNS_DELETE_ROUTE)
115
+ return false;
116
+ const gate = checkOwnerRequest(req, {
117
+ port: ctx.port,
118
+ token: ctx.ownerToken,
119
+ });
120
+ if (!gate.ok) {
121
+ sendJson(res, gate.status, { error: gate.reason });
122
+ return true;
123
+ }
124
+ try {
125
+ if (pathname === OWNER_SIGNS_SAVE_ROUTE)
126
+ await save(req, res, ctx);
127
+ else
128
+ await remove(req, res, ctx);
129
+ }
130
+ catch (err) {
131
+ if (err instanceof OwnerPathError) {
132
+ sendJson(res, err.status, { error: err.message });
133
+ return true;
134
+ }
135
+ // No absolute paths or stack in the response — the page only needs to know it failed.
136
+ console.error("cabn serve: owner sign request failed", err);
137
+ sendJson(res, 500, { error: "could not write the sign" });
138
+ }
139
+ return true;
140
+ }
141
+ async function save(req, res, ctx) {
142
+ const body = await readOwnerJson(req, SaveBodySchema);
143
+ if (!body.ok) {
144
+ sendJson(res, body.status, { error: body.reason });
145
+ return;
146
+ }
147
+ const { path, content, create, realm } = body.data;
148
+ const shadow = realm === "shadow" ? ctx.shadow : undefined;
149
+ if (realm === "shadow" && !shadow) {
150
+ sendJson(res, 404, { error: "there is no shadow realm here" });
151
+ return;
152
+ }
153
+ if (Buffer.byteLength(content, "utf8") > SEYN_MAX_BYTES) {
154
+ sendJson(res, 413, { error: `a sign is at most ${SEYN_MAX_BYTES} bytes` });
155
+ return;
156
+ }
157
+ const target = await resolveOwnerTarget(ctx.dir, path, {
158
+ extension: SEYN_EXTENSION,
159
+ });
160
+ if (create && target.exists) {
161
+ sendJson(res, 409, { error: `${path} already exists` });
162
+ return;
163
+ }
164
+ if (!create && !target.exists) {
165
+ sendJson(res, 404, { error: `${path} does not exist` });
166
+ return;
167
+ }
168
+ if (create) {
169
+ try {
170
+ // wx: fails if anything (a file, a symlink, even a dangling one)
171
+ // appeared at the path since resolveOwnerTarget looked.
172
+ await writeFile(target.absolute, content, { flag: "wx", mode: 0o644 });
173
+ }
174
+ catch (err) {
175
+ if (err.code === "EEXIST") {
176
+ sendJson(res, 409, { error: `${path} already exists` });
177
+ return;
178
+ }
179
+ throw err;
180
+ }
181
+ }
182
+ else {
183
+ await overwriteFileAtomic(target.absolute, content);
184
+ }
185
+ const entry = shadow
186
+ ? await shadow.putSign(path, content)
187
+ : buildSignEntry(path, content, worldIndex(ctx.bundle))?.entry;
188
+ if (!entry) {
189
+ sendJson(res, 500, { error: "this world has nowhere to put a sign" });
190
+ return;
191
+ }
192
+ if (!shadow)
193
+ writeSigns(ctx.bundle, [
194
+ ...currentSigns(ctx.bundle).filter((s) => s.path !== path),
195
+ entry,
196
+ ]);
197
+ sendJson(res, 200, { sign: entry });
198
+ }
199
+ async function remove(req, res, ctx) {
200
+ const body = await readOwnerJson(req, DeleteBodySchema);
201
+ if (!body.ok) {
202
+ sendJson(res, body.status, { error: body.reason });
203
+ return;
204
+ }
205
+ const { path, realm } = body.data;
206
+ const shadow = realm === "shadow" ? ctx.shadow : undefined;
207
+ if (realm === "shadow" && !shadow) {
208
+ sendJson(res, 404, { error: "there is no shadow realm here" });
209
+ return;
210
+ }
211
+ const target = await resolveOwnerTarget(ctx.dir, path, {
212
+ extension: SEYN_EXTENSION,
213
+ });
214
+ if (!target.exists) {
215
+ sendJson(res, 404, { error: `${path} does not exist` });
216
+ return;
217
+ }
218
+ await unlink(target.absolute);
219
+ if (shadow)
220
+ shadow.dropSign(path);
221
+ else
222
+ writeSigns(ctx.bundle, currentSigns(ctx.bundle).filter((s) => s.path !== path));
223
+ sendJson(res, 200, { ok: true });
224
+ }
@@ -0,0 +1,33 @@
1
+ export declare const LINE_MARKER_PREFIX = "\u001ELINE ";
2
+ /**
3
+ * `sys.settrace`, restricted to frames whose `co_filename` is exactly the
4
+ * target file — a module the target imports (even a local sibling file) is
5
+ * never traced, only the entry script itself, matching the milestone's "line
6
+ * tracing ... restricted to the target file". Markers go to stderr (a
7
+ * separate stream from the script's own stdout) so the server-side parser
8
+ * only ever has to disentangle one stream's worth of interleaving. `argv[1]`
9
+ * is the absolute, already-path-confined file the exec runner resolved —
10
+ * this script never does its own path handling.
11
+ */
12
+ export declare const PYTHON_TRACER_SOURCE: string;
13
+ export interface LineEvent {
14
+ line: number;
15
+ }
16
+ export interface TraceChunkResult {
17
+ events: LineEvent[];
18
+ /** Stderr text with every complete marker stripped out — the target script's own stderr, forwarded to the client as-is. */
19
+ text: string;
20
+ /** Held-back tail that might be the start of a marker split across two stream chunks — pass back in as `carry` on the next call. */
21
+ carry: string;
22
+ }
23
+ /**
24
+ * Pure, stateless per call (all state is the `carry` the caller threads
25
+ * through) — parses complete `\x1eLINE n\n` markers out of a stderr chunk,
26
+ * emitting each as a structured line event and returning the rest of the
27
+ * text untouched. A marker split across a chunk boundary (the process wrote
28
+ * the prefix but not the trailing newline yet) is held back in `carry`
29
+ * rather than emitted as garbled text or a missed event.
30
+ */
31
+ export declare function parseTraceChunk(carry: string, chunk: string): TraceChunkResult;
32
+ /** Called once the stream ends — any held-back `carry` was never going to complete, so it's real (if odd) text rather than a marker after all. */
33
+ export declare function flushTraceCarry(carry: string): string;
@@ -0,0 +1,76 @@
1
+ // U+001E (record separator) prefixes each line marker so it can never be
2
+ // confused with the target script's own stdout/stderr output, which is
3
+ // vanishingly unlikely to contain a control character no keyboard produces.
4
+ export const LINE_MARKER_PREFIX = "\x1eLINE ";
5
+ /**
6
+ * `sys.settrace`, restricted to frames whose `co_filename` is exactly the
7
+ * target file — a module the target imports (even a local sibling file) is
8
+ * never traced, only the entry script itself, matching the milestone's "line
9
+ * tracing ... restricted to the target file". Markers go to stderr (a
10
+ * separate stream from the script's own stdout) so the server-side parser
11
+ * only ever has to disentangle one stream's worth of interleaving. `argv[1]`
12
+ * is the absolute, already-path-confined file the exec runner resolved —
13
+ * this script never does its own path handling.
14
+ */
15
+ export const PYTHON_TRACER_SOURCE = `
16
+ import runpy
17
+ import sys
18
+
19
+ _target = sys.argv[1]
20
+
21
+ def _cabn_trace(frame, event, arg):
22
+ if event == "line" and frame.f_code.co_filename == _target:
23
+ sys.stderr.write(${JSON.stringify(LINE_MARKER_PREFIX)} + str(frame.f_lineno) + "\\n")
24
+ sys.stderr.flush()
25
+ return _cabn_trace
26
+
27
+ sys.settrace(_cabn_trace)
28
+ try:
29
+ runpy.run_path(_target, run_name="__main__")
30
+ finally:
31
+ sys.settrace(None)
32
+ `;
33
+ // A RegExp built from a string, not a `/.../ ` literal — Biome's
34
+ // noControlCharactersInRegex rule flags a literal control character in a
35
+ // regex literal specifically; the constructor form is the accepted escape
36
+ // hatch for a genuinely-intentional one (see LINE_MARKER_PREFIX's own doc for
37
+ // why U+001E is the right choice here).
38
+ const MARKER_RE = new RegExp(`${LINE_MARKER_PREFIX}(\\d+)\n`, "g");
39
+ /**
40
+ * Pure, stateless per call (all state is the `carry` the caller threads
41
+ * through) — parses complete `\x1eLINE n\n` markers out of a stderr chunk,
42
+ * emitting each as a structured line event and returning the rest of the
43
+ * text untouched. A marker split across a chunk boundary (the process wrote
44
+ * the prefix but not the trailing newline yet) is held back in `carry`
45
+ * rather than emitted as garbled text or a missed event.
46
+ */
47
+ export function parseTraceChunk(carry, chunk) {
48
+ const combined = carry + chunk;
49
+ const events = [];
50
+ let text = "";
51
+ let lastIndex = 0;
52
+ MARKER_RE.lastIndex = 0;
53
+ let match = MARKER_RE.exec(combined);
54
+ while (match !== null) {
55
+ text += combined.slice(lastIndex, match.index);
56
+ const line = Number(match[1]);
57
+ if (Number.isFinite(line))
58
+ events.push({ line });
59
+ lastIndex = MARKER_RE.lastIndex;
60
+ match = MARKER_RE.exec(combined);
61
+ }
62
+ const rest = combined.slice(lastIndex);
63
+ const prefixIndex = rest.indexOf("\x1e");
64
+ if (prefixIndex === -1) {
65
+ text += rest;
66
+ return { events, text, carry: "" };
67
+ }
68
+ // Everything before a trailing, not-yet-complete marker is real text;
69
+ // everything from the marker prefix onward waits for the next chunk.
70
+ text += rest.slice(0, prefixIndex);
71
+ return { events, text, carry: rest.slice(prefixIndex) };
72
+ }
73
+ /** Called once the stream ends — any held-back `carry` was never going to complete, so it's real (if odd) text rather than a marker after all. */
74
+ export function flushTraceCarry(carry) {
75
+ return carry;
76
+ }
@@ -0,0 +1,8 @@
1
+ export interface RuntimeConfig {
2
+ /** True for python: the exec runner injects PYTHON_TRACER_SOURCE and swaps `command`/`buildArgs` for the tracer wrapper instead of running the file directly. */
3
+ traced: boolean;
4
+ command: string;
5
+ buildArgs: (absoluteFilePath: string) => string[];
6
+ }
7
+ export declare function runtimeForPath(absoluteFilePath: string): RuntimeConfig | undefined;
8
+ export declare function isRunnableExtension(absoluteFilePath: string): boolean;
@@ -0,0 +1,35 @@
1
+ import { extname } from "node:path";
2
+ import { PYTHON_TRACER_SOURCE } from "./pyTracer.js";
3
+ // Extension -> interpreter, nothing else — never derived from client input
4
+ // beyond "which of these four extensions does the path end in", so there's
5
+ // no way for a request to smuggle an arbitrary command. See CHANGELOG for why
6
+ // each interpreter is what it is (Node 22's own `--experimental-strip-types`
7
+ // covers .ts without a bundler).
8
+ const RUNTIME_BY_EXT = {
9
+ ".py": {
10
+ traced: true,
11
+ command: "python3",
12
+ buildArgs: (file) => ["-c", PYTHON_TRACER_SOURCE, file],
13
+ },
14
+ ".js": {
15
+ traced: false,
16
+ command: "node",
17
+ buildArgs: (file) => [file],
18
+ },
19
+ ".mjs": {
20
+ traced: false,
21
+ command: "node",
22
+ buildArgs: (file) => [file],
23
+ },
24
+ ".ts": {
25
+ traced: false,
26
+ command: "node",
27
+ buildArgs: (file) => ["--experimental-strip-types", file],
28
+ },
29
+ };
30
+ export function runtimeForPath(absoluteFilePath) {
31
+ return RUNTIME_BY_EXT[extname(absoluteFilePath).toLowerCase()];
32
+ }
33
+ export function isRunnableExtension(absoluteFilePath) {
34
+ return runtimeForPath(absoluteFilePath) !== undefined;
35
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Constant-time token compare — a plain `===` leaks timing information
3
+ * proportional to the number of matching leading bytes, which is exactly the
4
+ * kind of side channel a local exec token (the only thing standing between a
5
+ * page load and running the visitor's code) can't afford. Length is checked
6
+ * first (an unavoidable, low-value leak — token length is fixed and public
7
+ * anyway) so `timingSafeEqual` never has to see mismatched buffer lengths,
8
+ * which it throws on rather than treating as "unequal".
9
+ */
10
+ export declare function constantTimeEqual(a: string, b: string): boolean;
11
+ /**
12
+ * True only for an exact `127.0.0.1:<port>` or `localhost:<port>` Host
13
+ * header — defeats DNS rebinding (an attacker's page pointing a public
14
+ * domain's DNS at 127.0.0.1 would still send that domain as the Host header,
15
+ * not "localhost"/"127.0.0.1"). Case-insensitive on the hostname per the Host
16
+ * header's own grammar; the port must match exactly, no default-port
17
+ * shorthand accepted since this server is never on 80/443.
18
+ */
19
+ export declare function isLoopbackHost(hostHeader: string | undefined, port: number): boolean;
20
+ /** `Origin` is optional (curl and most non-browser clients never send it) — only checked when present, per the milestone's own wording ("Origin (if present) matches"). */
21
+ export declare function isAllowedOrigin(originHeader: string | undefined, port: number): boolean;
22
+ export declare class PathConfinementError extends Error {
23
+ }
24
+ /**
25
+ * Resolves `relPath` against `rootDir` and guarantees the *real* (symlinks
26
+ * resolved) result is still inside the *real* root — the two-step check a
27
+ * naive `path.resolve` + `startsWith` misses: a same-directory symlink
28
+ * pointing outside `rootDir` would pass a plain string-prefix check on the
29
+ * unresolved path but must still be rejected. Absolute input paths are
30
+ * rejected outright before ever reaching `path.resolve` — `path.resolve(root,
31
+ * "/etc/passwd")` discards `root` entirely per Node's own path.resolve
32
+ * semantics (a later absolute segment wins), which would otherwise turn this
33
+ * into the exact traversal bug it exists to prevent.
34
+ */
35
+ export declare function resolveConfinedPath(rootDir: string, relPath: string): Promise<string>;
36
+ /**
37
+ * The host page's CSP: only `frame-src`, naming exactly the world's
38
+ * allowedEmbedOrigins (`'none'` when it has none). Frames are the only thing
39
+ * restricted — script/style/connect stay unrestricted because the page runs
40
+ * an inline token script and an esbuild bundle whose needs (blob: workers,
41
+ * inline styles from React) a broader policy would have to enumerate and
42
+ * could silently break. No `'self'`: nothing on this page frames its own
43
+ * origin. Entries that aren't a bare https origin are dropped rather than
44
+ * trusted, so a hand-edited world.json can't smuggle `*` or a second
45
+ * directive (`; script-src ...`) into the header.
46
+ */
47
+ export declare function frameSrcPolicy(allowedEmbedOrigins: readonly unknown[]): string;
@@ -0,0 +1,106 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ import { realpath } from "node:fs/promises";
3
+ import { isAbsolute, resolve, sep } from "node:path";
4
+ import { HttpsOriginSchema } from "@cabn/world-schema";
5
+ /**
6
+ * Constant-time token compare — a plain `===` leaks timing information
7
+ * proportional to the number of matching leading bytes, which is exactly the
8
+ * kind of side channel a local exec token (the only thing standing between a
9
+ * page load and running the visitor's code) can't afford. Length is checked
10
+ * first (an unavoidable, low-value leak — token length is fixed and public
11
+ * anyway) so `timingSafeEqual` never has to see mismatched buffer lengths,
12
+ * which it throws on rather than treating as "unequal".
13
+ */
14
+ export function constantTimeEqual(a, b) {
15
+ const bufA = Buffer.from(a, "utf8");
16
+ const bufB = Buffer.from(b, "utf8");
17
+ if (bufA.length !== bufB.length)
18
+ return false;
19
+ return timingSafeEqual(bufA, bufB);
20
+ }
21
+ /**
22
+ * True only for an exact `127.0.0.1:<port>` or `localhost:<port>` Host
23
+ * header — defeats DNS rebinding (an attacker's page pointing a public
24
+ * domain's DNS at 127.0.0.1 would still send that domain as the Host header,
25
+ * not "localhost"/"127.0.0.1"). Case-insensitive on the hostname per the Host
26
+ * header's own grammar; the port must match exactly, no default-port
27
+ * shorthand accepted since this server is never on 80/443.
28
+ */
29
+ export function isLoopbackHost(hostHeader, port) {
30
+ if (!hostHeader)
31
+ return false;
32
+ const match = /^([^:]+):(\d+)$/.exec(hostHeader.trim());
33
+ if (!match)
34
+ return false;
35
+ const [, hostname, portStr] = match;
36
+ if (Number(portStr) !== port)
37
+ return false;
38
+ const lower = (hostname ?? "").toLowerCase();
39
+ return lower === "127.0.0.1" || lower === "localhost";
40
+ }
41
+ /** `Origin` is optional (curl and most non-browser clients never send it) — only checked when present, per the milestone's own wording ("Origin (if present) matches"). */
42
+ export function isAllowedOrigin(originHeader, port) {
43
+ if (originHeader === undefined)
44
+ return true;
45
+ const match = /^http:\/\/([^:/]+):(\d+)\/?$/.exec(originHeader.trim());
46
+ if (!match)
47
+ return false;
48
+ const [, hostname, portStr] = match;
49
+ if (Number(portStr) !== port)
50
+ return false;
51
+ const lower = (hostname ?? "").toLowerCase();
52
+ return lower === "127.0.0.1" || lower === "localhost";
53
+ }
54
+ export class PathConfinementError extends Error {
55
+ }
56
+ /**
57
+ * Resolves `relPath` against `rootDir` and guarantees the *real* (symlinks
58
+ * resolved) result is still inside the *real* root — the two-step check a
59
+ * naive `path.resolve` + `startsWith` misses: a same-directory symlink
60
+ * pointing outside `rootDir` would pass a plain string-prefix check on the
61
+ * unresolved path but must still be rejected. Absolute input paths are
62
+ * rejected outright before ever reaching `path.resolve` — `path.resolve(root,
63
+ * "/etc/passwd")` discards `root` entirely per Node's own path.resolve
64
+ * semantics (a later absolute segment wins), which would otherwise turn this
65
+ * into the exact traversal bug it exists to prevent.
66
+ */
67
+ export async function resolveConfinedPath(rootDir, relPath) {
68
+ if (relPath === "" || isAbsolute(relPath) || relPath.includes("\0")) {
69
+ throw new PathConfinementError(`refusing to resolve "${relPath}"`);
70
+ }
71
+ const realRoot = await realpath(rootDir);
72
+ const candidate = resolve(realRoot, relPath);
73
+ if (candidate !== realRoot && !candidate.startsWith(realRoot + sep)) {
74
+ throw new PathConfinementError(`"${relPath}" escapes the served directory`);
75
+ }
76
+ let realCandidate;
77
+ try {
78
+ realCandidate = await realpath(candidate);
79
+ }
80
+ catch (err) {
81
+ throw new PathConfinementError(`"${relPath}" does not resolve to a real file`, {
82
+ cause: err,
83
+ });
84
+ }
85
+ if (realCandidate !== realRoot && !realCandidate.startsWith(realRoot + sep)) {
86
+ throw new PathConfinementError(`"${relPath}" escapes the served directory via a symlink`);
87
+ }
88
+ return realCandidate;
89
+ }
90
+ /**
91
+ * The host page's CSP: only `frame-src`, naming exactly the world's
92
+ * allowedEmbedOrigins (`'none'` when it has none). Frames are the only thing
93
+ * restricted — script/style/connect stay unrestricted because the page runs
94
+ * an inline token script and an esbuild bundle whose needs (blob: workers,
95
+ * inline styles from React) a broader policy would have to enumerate and
96
+ * could silently break. No `'self'`: nothing on this page frames its own
97
+ * origin. Entries that aren't a bare https origin are dropped rather than
98
+ * trusted, so a hand-edited world.json can't smuggle `*` or a second
99
+ * directive (`; script-src ...`) into the header.
100
+ */
101
+ export function frameSrcPolicy(allowedEmbedOrigins) {
102
+ const origins = allowedEmbedOrigins.filter((o) => typeof o === "string" &&
103
+ HttpsOriginSchema.safeParse(o).success &&
104
+ /^https:\/\/[A-Za-z0-9.:[\]-]+$/.test(o));
105
+ return `frame-src ${origins.length > 0 ? [...new Set(origins)].join(" ") : "'none'"}`;
106
+ }
@@ -0,0 +1,52 @@
1
+ import { type Server } from "node:http";
2
+ import { type GithubFetch, type WorldBundle } from "@cabn/converter";
3
+ export interface ServeOptions {
4
+ port?: number;
5
+ /** Deliberately not exposed as a real CLI flag — see the refusal check below. Only present so tests can exercise the "refuses a non-loopback host" path without a fake --host flag existing in the CLI's own argv parsing. */
6
+ host?: string;
7
+ allowExec?: boolean;
8
+ timeoutMs?: number;
9
+ outputCapBytes?: number;
10
+ /** Skip the build-time framability check for url previews and the GitHub releases request. */
11
+ offline?: boolean;
12
+ /**
13
+ * Owner mode (`--owner`, off by default, loopback only like
14
+ * --allow-exec): one per-session owner token, and the token-gated owner
15
+ * routes — signs (`/owner/signs/*`: write/delete .seyn files) and git
16
+ * (`/owner/git/*`: commit in-game edits, create/switch branches in the
17
+ * real repository, never push or fetch). Off, neither route group exists
18
+ * and the host page carries no owner client.
19
+ */
20
+ owner?: boolean;
21
+ /** false: serve without git history (`--no-history`). */
22
+ history?: boolean;
23
+ gitDir?: string;
24
+ /** Tests only: replaces the GitHub releases fetch. */
25
+ githubFetch?: GithubFetch;
26
+ /** Tests only: replaces resolveShadowArtDir; null means no art anywhere. */
27
+ shadowArtDir?: string | null;
28
+ }
29
+ export interface ServeHandle {
30
+ server: Server;
31
+ url: string;
32
+ token: string;
33
+ /** Undefined with owner mode off. Never printed — it lives only in the host page. */
34
+ ownerToken: string | undefined;
35
+ port: number;
36
+ close(): Promise<void>;
37
+ }
38
+ export declare const DEFAULT_SERVE_PORT = 5178;
39
+ export declare const PDF_WORKER_ROUTE = "/pdfjs/pdf.worker.min.mjs";
40
+ /** `shadow/...` under the asset root, however spelled (case-insensitive filesystems, `./`, doubled slashes). */
41
+ export declare function isShadowAssetPath(relPath: string): boolean;
42
+ /** Top-level chunks only (universes/ has its own): the text each world portal was converted from. */
43
+ export declare function worldTextFromBundle(bundle: WorldBundle): Map<string, string>;
44
+ /**
45
+ * Converts `dir` in memory and starts serving it — binds to 127.0.0.1 only
46
+ * (never configurable to 0.0.0.0 from the CLI surface; `opts.host` exists
47
+ * solely so tests can exercise the refusal path below without a real
48
+ * flag). See handleExec/isExecRequestAuthorized for the exec endpoint's own
49
+ * gate, and REPO_ASSETS_DIR's doc for why sprites are best-effort outside
50
+ * this monorepo.
51
+ */
52
+ export declare function startServe(dir: string, opts?: ServeOptions): Promise<ServeHandle>;