cajonzero 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/scaffold.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { readFileSync, existsSync, statSync, mkdirSync, writeFileSync, readdirSync } from 'fs';
2
2
  import path from 'path';
3
3
  import { fileURLToPath } from 'url';
4
+ import { randomBytes } from 'crypto';
4
5
 
5
6
  // src/scaffold/templates.ts
6
7
  var SCAFFOLD_ENTRY_PATH = "src/index.ts";
@@ -50,7 +51,7 @@ var SCAFFOLD_ENTRY_CONTENT = [
50
51
  " };",
51
52
  " },",
52
53
  "});",
53
- 'export { Room } from "cajonzero";',
54
+ 'export { Room } from "cajonzero/serve";',
54
55
  ""
55
56
  ].join("\n");
56
57
  var SCAFFOLD_CONFIG_CONTENT = `${JSON.stringify(
@@ -155,82 +156,49 @@ function readme(options) {
155
156
  return [
156
157
  `# ${options.packageName}`,
157
158
  "",
158
- "A serverless (Cloudflare Workers) BOX3 **play** server, scaffolded by",
159
- "[`cajonzero`](https://www.npmjs.com/package/cajonzero).",
159
+ "\u7531 cajonzero \u751F\u6210\u7684 Cloudflare Workers \u670D\u52A1\u3002\u9879\u76EE\u53EA\u6709\u914D\u7F6E\u548C\u4E00\u4E2A\u5F88\u8584\u7684 worker",
160
+ "\u5165\u53E3\uFF0C\u6CA1\u6709\u5F15\u64CE\u6E90\u7801\u3002",
160
161
  "",
161
- "This project contains **no engine source code** \u2014 configuration plus a short",
162
- "worker entry that hands `cajonzero/config.json` and `cajonzero/maps.json` to the",
163
- "runtime:",
164
- "",
165
- "```ts",
166
- 'import config from "../cajonzero/config.json";',
167
- 'import maps from "../cajonzero/maps.json";',
168
- 'import { serve } from "cajonzero/serve";',
169
- "",
170
- "export default serve({",
171
- " config,",
172
- " maps,",
173
- " storage: (env) => /* any unstorage driver over env bindings */,",
174
- " sessionSecret: (env) => env.CAJONZERO_SESSION_SECRET,",
175
- " // adminToken / environment / rooms / settings \u2026",
176
- "});",
177
- 'export { Room } from "cajonzero";',
178
- "```",
179
- "",
180
- "## Quick start",
162
+ "## \u5FEB\u901F\u5F00\u59CB",
181
163
  "",
182
164
  "```bash",
183
- "npm install # also syncs cajonzero's prebuilt lobby/console into dist/ui",
184
- "npm run dev # wrangler dev \u2192 http://localhost:8787",
165
+ "npm install",
166
+ "npx cj0 setup # \u4EA4\u4E92\u5F0F\u914D\u7F6E\u5FC5\u9700/\u53EF\u9009\u7684 ENV",
167
+ "npm run dev # http://localhost:8787",
185
168
  "```",
186
169
  "",
187
- "`npm run build` validates the deploy by bundling the worker without",
188
- "publishing (`wrangler deploy --dry-run`).",
189
- "",
190
- "## Environment",
170
+ "## \u73AF\u5883\u53D8\u91CF",
191
171
  "",
192
- "Every value the runtime consumes is passed explicitly in `src/index.ts`;",
193
- "the package never guesses env var names.",
194
- "",
195
- "| Name | Kind | Required | Purpose |",
196
- "|---|---|---|---|",
197
- "| `CAJONZERO_KV` | KV binding | yes | player/account data + map-script KV |",
198
- "| `ROOMS` | Durable Object binding | yes | room actors |",
199
- "| `CAJONZERO_SESSION_SECRET` | secret | yes | signs session proofs and login cookies |",
200
- "| `BOX_PLAY_ADMIN_TOKEN` | secret | yes | owner console and `/api/admin/*` |",
201
- "| `CAJONZERO_ENV` | var | no | deployment label (`development` relaxes cookie `Secure`) |",
202
- "| `CAJONZERO_PLAYER_LIMIT` | var | no | maximum players per room |",
203
- "| `CAJONZERO_ZERO_PLAYER_TIMEOUT_MS` | var | no | empty-room grace window |",
204
- "| `CAJONZERO_AUTOSAVE_INTERVAL_MS` | var | no | snapshot cadence |",
205
- "| `CAJONZERO_DEBUG` | var | no | verbose logging |",
206
- "| `CAJONZERO_TELEPORT_ACCESS` | var | no | allow non-team containers |",
207
- "| `CAJONZERO_PAID_ACCESS` | var | no | restrict joins to paid containers |",
208
- "| `CAJONZERO_SCRIPT_HEAP_MB` | var | no | QuickJS heap per script host |",
209
- "| `CAJONZERO_SCRIPT_TIMEOUT_MS` | var | no | script invocation timeout |",
210
- "| `CAJONZERO_DB_SIZE_LIMIT` | var | no | map-script storage budget |",
211
- "",
212
- "Create the namespace and set the secrets before deploying:",
172
+ "`cj0 setup` \u628A\u975E\u5BC6\u94A5\u5199\u5165 `wrangler.jsonc` \u7684 `vars`\uFF0C\u628A\u5BC6\u94A5\u5199\u5165 `.dev.vars`\uFF08\u672C\u5730\uFF09\u3002",
173
+ "\u90E8\u7F72\u65F6\u5BC6\u94A5\u8981\u5355\u72EC\u8BBE\u7F6E\uFF1A",
213
174
  "",
214
175
  "```bash",
215
- "npx wrangler kv namespace create CAJONZERO_KV # paste the id into wrangler.jsonc",
176
+ "npx wrangler kv namespace create CAJONZERO_KV # id \u586B\u8FDB wrangler.jsonc",
216
177
  "npx wrangler secret put CAJONZERO_SESSION_SECRET",
217
178
  "npx wrangler secret put BOX_PLAY_ADMIN_TOKEN",
218
179
  "```",
219
180
  "",
220
- "## Maps (object storage)",
221
- "",
222
- "Maps are **not** uploaded with the worker and are never unpacked at runtime.",
223
- "Unpack the `.boxplay` yourself and upload the resulting directory to OSS/S3/CDN",
224
- "with the archive layout preserved:",
181
+ "| \u540D\u79F0 | \u7C7B\u578B | \u5FC5\u9700 | \u8BF4\u660E |",
182
+ "|---|---|---|---|",
183
+ "| `CAJONZERO_KV` | KV \u7ED1\u5B9A | \u662F | \u8D26\u53F7/\u73A9\u5BB6\u6570\u636E + \u5730\u56FE\u811A\u672C KV |",
184
+ "| `ROOMS` | Durable Object \u7ED1\u5B9A | \u662F | \u623F\u95F4\u5B9E\u4F8B |",
185
+ "| `CAJONZERO_SESSION_SECRET` | \u5BC6\u94A5 | \u662F | \u4F1A\u8BDD\u51ED\u8BC1\u4E0E Cookie \u7B7E\u540D |",
186
+ "| `BOX_PLAY_ADMIN_TOKEN` | \u5BC6\u94A5 | \u662F | \u7BA1\u7406\u540E\u53F0\u4EE4\u724C |",
187
+ "| `CAJONZERO_ENV` | \u53D8\u91CF | \u5426 | \u90E8\u7F72\u540D\u79F0\uFF08`development` \u65F6 Cookie \u4E0D\u52A0 Secure\uFF09 |",
188
+ "| `CAJONZERO_PLAYER_LIMIT` | \u53D8\u91CF | \u5426 | \u5355\u623F\u95F4\u73A9\u5BB6\u4E0A\u9650 |",
189
+ "| `CAJONZERO_ZERO_PLAYER_TIMEOUT_MS` | \u53D8\u91CF | \u5426 | \u7A7A\u623F\u95F4\u4FDD\u7559\u65F6\u95F4 |",
190
+ "| `CAJONZERO_AUTOSAVE_INTERVAL_MS` | \u53D8\u91CF | \u5426 | \u81EA\u52A8\u5B58\u6863\u95F4\u9694 |",
191
+ "| `CAJONZERO_DEBUG` | \u53D8\u91CF | \u5426 | \u8C03\u8BD5\u65E5\u5FD7 |",
192
+ "| `CAJONZERO_TELEPORT_ACCESS` | \u53D8\u91CF | \u5426 | \u5141\u8BB8\u4F20\u9001\u7C7B\u5BB9\u5668 |",
193
+ "| `CAJONZERO_PAID_ACCESS` | \u53D8\u91CF | \u5426 | \u4EC5\u4ED8\u8D39\u5BB9\u5668\u53EF\u52A0\u5165 |",
194
+ "| `CAJONZERO_SCRIPT_HEAP_MB` | \u53D8\u91CF | \u5426 | \u811A\u672C\u5806\u4E0A\u9650 |",
195
+ "| `CAJONZERO_SCRIPT_TIMEOUT_MS` | \u53D8\u91CF | \u5426 | \u5355\u6B21\u811A\u672C\u8D85\u65F6 |",
196
+ "| `CAJONZERO_DB_SIZE_LIMIT` | \u53D8\u91CF | \u5426 | \u5730\u56FE\u811A\u672C\u5B58\u50A8\u4E0A\u9650 |",
225
197
  "",
226
- "```text",
227
- "<root>/bundle.json",
228
- "<root>/worlds/<worldId>/manifest.json",
229
- "<root>/worlds/<worldId>/data/project-state.json",
230
- "<root>/worlds/<worldId>/data/blobs/<cid>",
231
- "```",
198
+ "## \u5730\u56FE",
232
199
  "",
233
- "Then add an entry to `cajonzero/maps.json`:",
200
+ "\u5730\u56FE\u4E0D\u968F worker \u4E0A\u4F20\u3002\u628A\u89E3\u5305\u540E\u7684 `.boxplay` \u76EE\u5F55\u4F20\u5230 OSS/S3/CDN\uFF08\u9700\u5141\u8BB8 CORS\uFF09\uFF0C",
201
+ "\u518D\u5728 `cajonzero/maps.json` \u767B\u8BB0\uFF1A",
234
202
  "",
235
203
  "```json",
236
204
  "{",
@@ -240,30 +208,21 @@ function readme(options) {
240
208
  ' "slug": "omega",',
241
209
  ' "root": "https://cdn.example.com/cajonzero/omega/",',
242
210
  ' "worldId": "project-omega",',
243
- ' "name": "Omega City Reloaded",',
244
- ' "version": "1.0.4"',
211
+ ' "name": "Omega City Reloaded"',
245
212
  " }",
246
213
  " ]",
247
214
  "}",
248
215
  "```",
249
216
  "",
250
- "- `root` must be the unpacked map directory and end with `/`.",
251
- "- The browser loads the map files directly, so the bucket must allow CORS",
252
- " (`Access-Control-Allow-Origin`) for this deployment's origin.",
253
- "- Re-uploaded maps need a CDN cache refresh (or a versioned path).",
254
- "",
255
- "## Where things live",
217
+ "`root` \u5FC5\u987B\u4EE5 `/` \u7ED3\u5C3E\uFF1B\u66F4\u65B0\u5730\u56FE\u540E\u5237\u65B0 CDN \u7F13\u5B58\u6216\u6362\u8DEF\u5F84\u3002",
256
218
  "",
257
- "- **Play lobby** \u2014 the worker serves the lobby at `/`.",
258
- "- **Admin console** \u2014 at `/admin` (sign in with `BOX_PLAY_ADMIN_TOKEN`) for",
259
- " player bans and runtime settings; its JSON API is under `/api/admin/*`.",
260
- "- **Map catalog** \u2014 `GET /api/maps` returns the entries from `maps.json`.",
261
- "",
262
- "## Deploy",
219
+ "## \u90E8\u7F72",
263
220
  "",
264
221
  "```bash",
265
- "npm run deploy # wrangler deploy",
222
+ "npm run deploy",
266
223
  "```",
224
+ "",
225
+ "\u5927\u5385\u5728 `/`\uFF0C\u7BA1\u7406\u540E\u53F0\u5728 `/admin`\u3002",
267
226
  ""
268
227
  ].join("\n");
269
228
  }
@@ -349,7 +308,275 @@ function createProject(folder, options = {}) {
349
308
  }
350
309
  return { target, files: files.map((file) => file.path) };
351
310
  }
311
+ var SETTING_FIELDS = [
312
+ {
313
+ name: "CAJONZERO_PLAYER_LIMIT",
314
+ label: "\u5355\u623F\u95F4\u73A9\u5BB6\u4E0A\u9650",
315
+ kind: "var",
316
+ required: false,
317
+ hint: "\u9ED8\u8BA4 100"
318
+ },
319
+ {
320
+ name: "CAJONZERO_ZERO_PLAYER_TIMEOUT_MS",
321
+ label: "\u7A7A\u623F\u95F4\u4FDD\u7559\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09",
322
+ kind: "var",
323
+ required: false,
324
+ hint: "\u9ED8\u8BA4 480000\uFF088 \u5206\u949F\uFF09"
325
+ },
326
+ {
327
+ name: "CAJONZERO_AUTOSAVE_INTERVAL_MS",
328
+ label: "\u81EA\u52A8\u5B58\u6863\u95F4\u9694\uFF08\u6BEB\u79D2\uFF09",
329
+ kind: "var",
330
+ required: false,
331
+ hint: "\u9ED8\u8BA4 300000"
332
+ },
333
+ {
334
+ name: "CAJONZERO_DEBUG",
335
+ label: "\u8C03\u8BD5\u65E5\u5FD7\uFF08true/false\uFF09",
336
+ kind: "var",
337
+ required: false,
338
+ hint: "\u9ED8\u8BA4 false"
339
+ },
340
+ {
341
+ name: "CAJONZERO_TELEPORT_ACCESS",
342
+ label: "\u5141\u8BB8\u4F20\u9001\u7C7B\u5BB9\u5668\uFF08true/false\uFF09",
343
+ kind: "var",
344
+ required: false,
345
+ hint: "\u9ED8\u8BA4 false"
346
+ },
347
+ {
348
+ name: "CAJONZERO_PAID_ACCESS",
349
+ label: "\u4EC5\u4ED8\u8D39\u5BB9\u5668\u53EF\u52A0\u5165\uFF08true/false\uFF09",
350
+ kind: "var",
351
+ required: false,
352
+ hint: "\u9ED8\u8BA4 false"
353
+ },
354
+ {
355
+ name: "CAJONZERO_SCRIPT_HEAP_MB",
356
+ label: "\u811A\u672C\u5806\u4E0A\u9650\uFF08MB\uFF09",
357
+ kind: "var",
358
+ required: false,
359
+ hint: "\u9ED8\u8BA4 256"
360
+ },
361
+ {
362
+ name: "CAJONZERO_SCRIPT_TIMEOUT_MS",
363
+ label: "\u5355\u6B21\u811A\u672C\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",
364
+ kind: "var",
365
+ required: false,
366
+ hint: "\u9ED8\u8BA4 10000"
367
+ },
368
+ {
369
+ name: "CAJONZERO_DB_SIZE_LIMIT",
370
+ label: "\u5730\u56FE\u811A\u672C\u5B58\u50A8\u4E0A\u9650\uFF08\u5B57\u8282\uFF09",
371
+ kind: "var",
372
+ required: false,
373
+ hint: "\u9ED8\u8BA4 134217728"
374
+ }
375
+ ];
376
+ var SETUP_FIELDS = [
377
+ {
378
+ name: "CAJONZERO_SESSION_SECRET",
379
+ label: "\u4F1A\u8BDD\u7B7E\u540D\u5BC6\u94A5",
380
+ kind: "secret",
381
+ required: true,
382
+ hint: "\u7559\u7A7A\u81EA\u52A8\u751F\u6210\uFF1B\u672C\u5730\u5199\u5165 .dev.vars"
383
+ },
384
+ {
385
+ name: "BOX_PLAY_ADMIN_TOKEN",
386
+ label: "\u7BA1\u7406\u540E\u53F0\u4EE4\u724C",
387
+ kind: "secret",
388
+ required: true,
389
+ hint: "\u7559\u7A7A\u81EA\u52A8\u751F\u6210\uFF1B\u672C\u5730\u5199\u5165 .dev.vars"
390
+ },
391
+ {
392
+ name: "CAJONZERO_ENV",
393
+ label: "\u90E8\u7F72\u540D\u79F0",
394
+ kind: "var",
395
+ required: true,
396
+ default: "development",
397
+ hint: "development \u65F6 Cookie \u4E0D\u52A0 Secure"
398
+ },
399
+ ...SETTING_FIELDS
400
+ ];
401
+ function generateSecret() {
402
+ return randomBytes(32).toString("hex");
403
+ }
404
+ function generateAdminToken() {
405
+ return randomBytes(24).toString("base64url");
406
+ }
407
+ function suggestedValue(field) {
408
+ if (field.default !== void 0) return field.default;
409
+ if (field.kind === "secret") {
410
+ return field.name === "BOX_PLAY_ADMIN_TOKEN" ? generateAdminToken() : generateSecret();
411
+ }
412
+ return void 0;
413
+ }
414
+ function parseDevVars(text) {
415
+ const out = {};
416
+ for (const line of text.split(/\r?\n/)) {
417
+ const trimmed = line.trim();
418
+ if (trimmed.length === 0 || trimmed.startsWith("#")) continue;
419
+ const eq = trimmed.indexOf("=");
420
+ if (eq <= 0) continue;
421
+ const key = trimmed.slice(0, eq).trim();
422
+ let value = trimmed.slice(eq + 1).trim();
423
+ if (value.length >= 2 && (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'"))) {
424
+ value = value.slice(1, -1);
425
+ }
426
+ out[key] = value;
427
+ }
428
+ return out;
429
+ }
430
+ function encodeDevVar(value) {
431
+ return /[\s#'"]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value;
432
+ }
433
+ function serializeDevVars(values) {
434
+ const lines = Object.entries(values).map(([key, value]) => `${key}=${encodeDevVar(value)}`);
435
+ return `${lines.join("\n")}
436
+ `;
437
+ }
438
+ function findVarsBlock(raw) {
439
+ const match = /"vars"\s*:\s*\{/.exec(raw);
440
+ if (match === null) return null;
441
+ const open = raw.indexOf("{", match.index);
442
+ let depth = 0;
443
+ let inString = false;
444
+ let escaped = false;
445
+ for (let i = open; i < raw.length; i += 1) {
446
+ const ch = raw[i];
447
+ if (inString) {
448
+ if (escaped) escaped = false;
449
+ else if (ch === "\\") escaped = true;
450
+ else if (ch === '"') inString = false;
451
+ continue;
452
+ }
453
+ if (ch === '"') inString = true;
454
+ else if (ch === "{") depth += 1;
455
+ else if (ch === "}") {
456
+ depth -= 1;
457
+ if (depth === 0) {
458
+ const lineStart = raw.lastIndexOf("\n", match.index) + 1;
459
+ const indent = /^\s*/.exec(raw.slice(lineStart, match.index))?.[0] ?? " ";
460
+ return { start: match.index, open, close: i, indent };
461
+ }
462
+ }
463
+ }
464
+ return null;
465
+ }
466
+ function parseJsoncObject(text) {
467
+ let out = "";
468
+ let inString = false;
469
+ let escaped = false;
470
+ for (let i = 0; i < text.length; i += 1) {
471
+ const ch = text[i];
472
+ if (inString) {
473
+ out += ch;
474
+ if (escaped) escaped = false;
475
+ else if (ch === "\\") escaped = true;
476
+ else if (ch === '"') inString = false;
477
+ continue;
478
+ }
479
+ if (ch === '"') {
480
+ inString = true;
481
+ out += ch;
482
+ continue;
483
+ }
484
+ if (ch === "/" && text[i + 1] === "/") {
485
+ while (i < text.length && text[i] !== "\n") i += 1;
486
+ out += "\n";
487
+ continue;
488
+ }
489
+ if (ch === "/" && text[i + 1] === "*") {
490
+ i += 2;
491
+ while (i < text.length && !(text[i] === "*" && text[i + 1] === "/")) i += 1;
492
+ i += 1;
493
+ continue;
494
+ }
495
+ out += ch;
496
+ }
497
+ out = out.replace(/,(\s*[}\]])/g, "$1");
498
+ try {
499
+ const parsed = JSON.parse(out);
500
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
501
+ } catch {
502
+ return {};
503
+ }
504
+ }
505
+ function setWranglerVars(raw, vars) {
506
+ const managed = new Set(SETUP_FIELDS.filter((f) => f.kind === "var").map((f) => f.name));
507
+ const block = findVarsBlock(raw);
508
+ const existing = block === null ? {} : parseJsoncObject(`{${raw.slice(block.open + 1, block.close)}}`);
509
+ const merged = {};
510
+ for (const [key, value] of Object.entries(existing)) {
511
+ if (!managed.has(key)) merged[key] = value;
512
+ }
513
+ for (const field of SETUP_FIELDS) {
514
+ if (field.kind !== "var") continue;
515
+ const value = vars[field.name];
516
+ if (value !== void 0 && value.length > 0) merged[field.name] = value;
517
+ }
518
+ const indent = block?.indent ?? " ";
519
+ const inner = `${indent} `;
520
+ const body = Object.entries(merged).map(([key, value]) => `${inner}${JSON.stringify(key)}: ${JSON.stringify(value)}`).join(",\n");
521
+ const bodyText = `"vars": {
522
+ ${body}${body.length > 0 ? "\n" : ""}${indent}}`;
523
+ if (block !== null) {
524
+ return `${raw.slice(0, block.start)}${bodyText}${raw.slice(block.close + 1)}`;
525
+ }
526
+ const open = raw.indexOf("{");
527
+ if (open < 0) throw new Error("wrangler config is not a JSON object");
528
+ return `${raw.slice(0, open + 1)}
529
+ ${indent}${bodyText},
530
+ ${raw.slice(open + 1)}`;
531
+ }
532
+ function readSetupValues(cwd, configPath, devVarsPath) {
533
+ const out = {};
534
+ if (existsSync(devVarsPath)) {
535
+ Object.assign(out, parseDevVars(readFileSync(devVarsPath, "utf8")));
536
+ }
537
+ if (existsSync(configPath)) {
538
+ const raw = readFileSync(configPath, "utf8");
539
+ const block = findVarsBlock(raw);
540
+ if (block !== null) {
541
+ const parsed = parseJsoncObject(`{${raw.slice(block.open + 1, block.close)}}`);
542
+ for (const [key, value] of Object.entries(parsed)) {
543
+ if (typeof value === "string") out[key] = value;
544
+ }
545
+ }
546
+ }
547
+ return out;
548
+ }
549
+ function applySetup(options) {
550
+ const cwd = options.cwd ?? process.cwd();
551
+ const configPath = path.resolve(cwd, options.configPath ?? "wrangler.jsonc");
552
+ const devVarsPath = path.join(path.dirname(configPath), ".dev.vars");
553
+ if (!existsSync(configPath)) {
554
+ throw new Error(`\u627E\u4E0D\u5230 ${path.basename(configPath)}\uFF0C\u8BF7\u5728 cj0 create \u751F\u6210\u7684\u9879\u76EE\u76EE\u5F55\u4E2D\u8FD0\u884C`);
555
+ }
556
+ const vars = {};
557
+ const secrets = {};
558
+ for (const field of SETUP_FIELDS) {
559
+ const value = options.values[field.name]?.trim();
560
+ if (value === void 0 || value.length === 0) continue;
561
+ if (field.kind === "secret") secrets[field.name] = value;
562
+ else vars[field.name] = value;
563
+ }
564
+ const raw = readFileSync(configPath, "utf8");
565
+ const next = setWranglerVars(raw, vars);
566
+ if (next !== raw) writeFileSync(configPath, next, "utf8");
567
+ const existingDev = existsSync(devVarsPath) ? parseDevVars(readFileSync(devVarsPath, "utf8")) : {};
568
+ const managedSecrets = new Set(
569
+ SETUP_FIELDS.filter((f) => f.kind === "secret").map((f) => f.name)
570
+ );
571
+ const mergedDev = {};
572
+ for (const [key, value] of Object.entries(existingDev)) {
573
+ if (!managedSecrets.has(key)) mergedDev[key] = value;
574
+ }
575
+ Object.assign(mergedDev, secrets);
576
+ writeFileSync(devVarsPath, serializeDevVars(mergedDev), "utf8");
577
+ return { configPath, devVarsPath, vars, secrets };
578
+ }
352
579
 
353
- export { SCAFFOLD_COMPATIBILITY_DATE, SCAFFOLD_CONFIG_CONTENT, SCAFFOLD_ENTRY_CONTENT, SCAFFOLD_ENTRY_PATH, SCAFFOLD_KV_PLACEHOLDER_ID, SCAFFOLD_MAPS_CONTENT, ScaffoldError, buildScaffoldFiles, createProject, readCajonzeroPackage, toPackageName };
580
+ export { SCAFFOLD_COMPATIBILITY_DATE, SCAFFOLD_CONFIG_CONTENT, SCAFFOLD_ENTRY_CONTENT, SCAFFOLD_ENTRY_PATH, SCAFFOLD_KV_PLACEHOLDER_ID, SCAFFOLD_MAPS_CONTENT, SETUP_FIELDS, ScaffoldError, applySetup, buildScaffoldFiles, createProject, generateAdminToken, generateSecret, parseDevVars, readCajonzeroPackage, readSetupValues, serializeDevVars, setWranglerVars, suggestedValue, toPackageName };
354
581
  //# sourceMappingURL=scaffold.js.map
355
582
  //# sourceMappingURL=scaffold.js.map
package/dist/serve.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ExecutionContext } from 'hono';
2
- import { R as Room, D as DurableObjectNamespace, b as Env } from './providers-Dh-umPQ6.js';
2
+ import { R as Room, D as DurableObjectNamespace, b as Env } from './providers-BX7e4pNW.js';
3
3
  import { StorageSource, EnvProvider, SettingDefaults } from './core.js';
4
4
  import 'unstorage';
5
5
  import 'gl-matrix';
@@ -21,7 +21,7 @@ import 'zod';
21
21
  * import { serve } from "cajonzero/serve";
22
22
  *
23
23
  * export default serve({ config, maps });
24
- * export { Room } from "cajonzero";
24
+ * export { Room } from "cajonzero/serve";
25
25
  *
26
26
  * 2. Programmatic factory (`serve(options?)`), for module-hosted runtimes
27
27
  * (a custom entry, a Bun/Deno host) that call a function instead of
package/dist/serve.js CHANGED
@@ -5343,7 +5343,6 @@ var KEY_PREFIX = {
5343
5343
  account: "account",
5344
5344
  session: "session",
5345
5345
  ban: "ban",
5346
- ratelimit: "ratelimit",
5347
5346
  settings: "settings",
5348
5347
  mapStorage: "mapstorage"
5349
5348
  };
@@ -5375,9 +5374,6 @@ function banAccountKey(subjectId) {
5375
5374
  function banIdentityKey(kind, hash) {
5376
5375
  return `ban:identity:${kind}:${seg2(hash)}`;
5377
5376
  }
5378
- function ratelimitKey(scope, hash) {
5379
- return `ratelimit:${seg2(scope)}:${seg2(hash)}`;
5380
- }
5381
5377
  function settingsKey(key) {
5382
5378
  return `settings:${seg2(key)}`;
5383
5379
  }
@@ -5420,12 +5416,6 @@ function parseKey(key) {
5420
5416
  }
5421
5417
  return void 0;
5422
5418
  }
5423
- case KEY_PREFIX.ratelimit: {
5424
- if (parts2.length !== 3) return void 0;
5425
- const scope = decode(parts2[1]);
5426
- const hash = decode(parts2[2]);
5427
- return scope === void 0 || hash === void 0 ? void 0 : { kind: "ratelimit", scope, hash };
5428
- }
5429
5419
  case KEY_PREFIX.settings: {
5430
5420
  if (parts2.length !== 2) return void 0;
5431
5421
  const settingKey = decode(parts2[1]);
@@ -15573,34 +15563,6 @@ function banDetails(input, at) {
15573
15563
  const expiresAt = input.expiresAt ?? (input.durationSeconds === void 0 ? void 0 : at + input.durationSeconds * 1e3);
15574
15564
  return { reason: input.reason, expiresAt, createdBy: input.createdBy };
15575
15565
  }
15576
- function createRateLimitsRepo(store, now) {
15577
- const repo = {
15578
- async increment(scope, hash, options = {}) {
15579
- const windowSeconds = Math.max(1, options.windowSeconds ?? 60);
15580
- const amount = options.amount ?? 1;
15581
- const at = now();
15582
- const current = await repo.get(scope, hash);
15583
- const windowStart = current !== void 0 && current.expiresAt > at ? current.windowStart : at;
15584
- const expiresAt = windowStart + windowSeconds * 1e3;
15585
- const next = {
15586
- count: (current !== void 0 && current.expiresAt > at ? current.count : 0) + amount,
15587
- windowStart,
15588
- expiresAt
15589
- };
15590
- const ttl = Math.max(1, Math.ceil((expiresAt - at) / 1e3));
15591
- await store.setItem(ratelimitKey(scope, hash), next, { ttl });
15592
- return next;
15593
- },
15594
- async get(scope, hash) {
15595
- const record = await store.getItem(ratelimitKey(scope, hash));
15596
- return record ?? void 0;
15597
- },
15598
- async reset(scope, hash) {
15599
- await store.removeItem(ratelimitKey(scope, hash));
15600
- }
15601
- };
15602
- return repo;
15603
- }
15604
15566
  function createSettingsRepo(store) {
15605
15567
  return {
15606
15568
  async get(key) {
@@ -15865,7 +15827,6 @@ function createRepos(store, options = {}) {
15865
15827
  accounts: createAccountsRepo(store, now),
15866
15828
  sessions: createSessionsRepo(store, now),
15867
15829
  bans: createBansRepo(store, now),
15868
- ratelimits: createRateLimitsRepo(store, now),
15869
15830
  settings: createSettingsRepo(store),
15870
15831
  mapStorage: (scope, namespace) => createMapStorageRepo(store, {
15871
15832
  scope,
@@ -23660,6 +23621,8 @@ var Room = class {
23660
23621
  mapLoading;
23661
23622
  worldReady = false;
23662
23623
  snapshotRestored = false;
23624
+ /** One-shot guard for the "proof without sessionSecret" diagnostic. */
23625
+ guestWarningLogged = false;
23663
23626
  persistence;
23664
23627
  socketsStarted = false;
23665
23628
  perf = { minPing: 0, maxPing: 0, avgPing: 0, pingCount: 0 };
@@ -24005,6 +23968,13 @@ var Room = class {
24005
23968
  this.pendingIdentities.set(sessionId, identity2);
24006
23969
  }
24007
23970
  } else {
23971
+ const proof = extractSessionProof(request.headers.get("sec-websocket-protocol"));
23972
+ if (proof !== void 0 && !this.guestWarningLogged) {
23973
+ this.guestWarningLogged = true;
23974
+ this.logger.error(
23975
+ "cajonzero: a session proof was supplied but no sessionSecret is configured; players join as guest. Pass serve({ sessionSecret: (env) => env.<SECRET> })."
23976
+ );
23977
+ }
24008
23978
  identity2 = guestIdentity(sessionId);
24009
23979
  }
24010
23980
  const ip = resolveClientIp(request);
@@ -26313,8 +26283,6 @@ function validationHook(code, status = 400) {
26313
26283
 
26314
26284
  // src/core/identity/account-routes.ts
26315
26285
  var SESSION_COOKIE_NAME = "cajonzero_session";
26316
- var RATE_LIMIT_MAX_ATTEMPTS = 5;
26317
- var RATE_LIMIT_WINDOW_SECONDS = 300;
26318
26286
  var USERNAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]{2,31}$/;
26319
26287
  var MIN_PASSWORD_LENGTH = 10;
26320
26288
  var MAX_PASSWORD_LENGTH = 128;
@@ -26383,22 +26351,6 @@ function clientIp(request) {
26383
26351
  }
26384
26352
  return "unknown";
26385
26353
  }
26386
- async function enforceAttempts(c, deps, attempts) {
26387
- let retryAfter = null;
26388
- for (const attempt of attempts) {
26389
- const state = await deps.ratelimits.increment(attempt.scope, attempt.key, {
26390
- windowSeconds: RATE_LIMIT_WINDOW_SECONDS
26391
- });
26392
- if (state.count > RATE_LIMIT_MAX_ATTEMPTS) {
26393
- const seconds = Math.max(1, Math.ceil((state.expiresAt - deps.now()) / 1e3));
26394
- retryAfter = retryAfter === null ? seconds : Math.max(retryAfter, seconds);
26395
- }
26396
- }
26397
- if (retryAfter !== null) {
26398
- c.header("Retry-After", String(retryAfter));
26399
- throw new HttpError(429, "rate_limited");
26400
- }
26401
- }
26402
26354
  async function issueSession(c, deps, account, ip) {
26403
26355
  const minted = await mintSessionToken(
26404
26356
  {
@@ -26431,10 +26383,6 @@ function accountRoutes(deps) {
26431
26383
  const username = body.username;
26432
26384
  const password = body.password;
26433
26385
  const ip = clientIp(c.req.raw);
26434
- await enforceAttempts(c, deps, [
26435
- { scope: "register-ip", key: ip },
26436
- { scope: "register-account", key: username.toLowerCase() }
26437
- ]);
26438
26386
  const saltBytes = randomSalt();
26439
26387
  const passwordHash = await derivePassword(password, saltBytes);
26440
26388
  let account;
@@ -26459,11 +26407,6 @@ function accountRoutes(deps) {
26459
26407
  const username = body.username;
26460
26408
  const password = body.password;
26461
26409
  const ip = clientIp(c.req.raw);
26462
- const attempts = [{ scope: "login-ip", key: ip }];
26463
- if (username.length > 0) {
26464
- attempts.push({ scope: "login-account", key: username.toLowerCase() });
26465
- }
26466
- await enforceAttempts(c, deps, attempts);
26467
26410
  const account = username.length > 0 ? await deps.accounts.getByUsername(username) : void 0;
26468
26411
  if (account === void 0 || account.disabled) {
26469
26412
  await dummyVerify(password);
@@ -26900,7 +26843,7 @@ function mountMapRoutes(app, catalog) {
26900
26843
  }
26901
26844
 
26902
26845
  // src/version.ts
26903
- var VERSION = "0.1.0";
26846
+ var VERSION = "0.1.1";
26904
26847
 
26905
26848
  // src/core/server/room-gateway.ts
26906
26849
  var CONTAINER_PATTERN3 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
@@ -27024,7 +26967,6 @@ function registerRoutes(app, deps) {
27024
26967
  now: deps.now,
27025
26968
  accounts: repos.accounts,
27026
26969
  sessions: repos.sessions,
27027
- ratelimits: repos.ratelimits,
27028
26970
  getSession,
27029
26971
  sessionSecret: deps.sessionSecret,
27030
26972
  environment: deps.environment,