@niscorp/moss 0.3.2 → 0.3.3

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 (48) hide show
  1. package/CHANGELOG.md +102 -0
  2. package/DESIGN.md +84 -19
  3. package/DOCS.md +170 -35
  4. package/README.md +2 -2
  5. package/dist/{chunk-J72N3EMJ.js → chunk-4T6KAXBP.js} +45 -27
  6. package/dist/chunk-4T6KAXBP.js.map +1 -0
  7. package/dist/{chunk-ZP3C53AC.js → chunk-AUZMT3GL.js} +739 -654
  8. package/dist/chunk-AUZMT3GL.js.map +1 -0
  9. package/dist/{chunk-ZOEUEMDX.js → chunk-HOZID4EM.js} +131 -16
  10. package/dist/chunk-HOZID4EM.js.map +1 -0
  11. package/dist/chunk-NE2EXMTO.js +103 -0
  12. package/dist/chunk-NE2EXMTO.js.map +1 -0
  13. package/dist/client/node.cjs +1 -1
  14. package/dist/client/node.cjs.map +1 -1
  15. package/dist/client/node.js +1 -1
  16. package/dist/client/node.js.map +1 -1
  17. package/dist/client.cjs +60 -26
  18. package/dist/client.cjs.map +1 -1
  19. package/dist/client.d.cts +6 -1
  20. package/dist/client.d.ts +6 -1
  21. package/dist/client.js +2 -2
  22. package/dist/{document-D9khv9jI.d.cts → document-DhWxieUc.d.cts} +22 -3
  23. package/dist/{document-D9khv9jI.d.ts → document-DhWxieUc.d.ts} +22 -3
  24. package/dist/index.cjs +777 -572
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +19 -3
  27. package/dist/index.d.ts +19 -3
  28. package/dist/index.js +2 -2
  29. package/dist/node.cjs +370 -219
  30. package/dist/node.cjs.map +1 -1
  31. package/dist/node.d.cts +2 -1
  32. package/dist/node.d.ts +2 -1
  33. package/dist/node.js +3 -3
  34. package/dist/terminal/index.cjs +60 -26
  35. package/dist/terminal/index.cjs.map +1 -1
  36. package/dist/terminal/index.js +2 -2
  37. package/dist/vite.cjs +103 -28
  38. package/dist/vite.cjs.map +1 -1
  39. package/dist/vite.d.cts +1 -1
  40. package/dist/vite.d.ts +1 -1
  41. package/dist/vite.js +14 -9
  42. package/dist/vite.js.map +1 -1
  43. package/package.json +9 -9
  44. package/dist/chunk-J72N3EMJ.js.map +0 -1
  45. package/dist/chunk-SUVDISEG.js +0 -64
  46. package/dist/chunk-SUVDISEG.js.map +0 -1
  47. package/dist/chunk-ZOEUEMDX.js.map +0 -1
  48. package/dist/chunk-ZP3C53AC.js.map +0 -1
package/dist/node.cjs CHANGED
@@ -5,7 +5,7 @@ var path = require('path');
5
5
  var nodeServer = require('@hono/node-server');
6
6
  var serveStatic = require('@hono/node-server/serve-static');
7
7
  var ws = require('ws');
8
- var crypto = require('crypto');
8
+ var crypto$1 = require('crypto');
9
9
  var async_hooks = require('async_hooks');
10
10
  var hono = require('hono');
11
11
  var hono$1 = require('@niscorp/vex/hono');
@@ -16,10 +16,10 @@ var migrations$1 = require('@niscorp/nova/migrations');
16
16
  var migrations = require('@niscorp/prism/migrations');
17
17
  var charter = require('@niscorp/charter');
18
18
  var nova = require('@niscorp/nova');
19
- require('@niscorp/tide');
20
19
  var zod = require('zod');
21
20
  var reflect = require('@niscorp/nova/reflect');
22
21
  var i18n = require('@niscorp/nova/i18n');
22
+ require('@niscorp/tide');
23
23
  var prism = require('@niscorp/prism');
24
24
  var document = require('@niscorp/nova/document');
25
25
 
@@ -164,7 +164,7 @@ var devSession = (token) => {
164
164
  };
165
165
 
166
166
  // src/sessions.ts
167
- var hashSessionToken = (token) => crypto.createHash("sha256").update(token).digest("hex");
167
+ var hashSessionToken = (token) => crypto$1.createHash("sha256").update(token).digest("hex");
168
168
  var SESSIONS_SEQUENCE = {
169
169
  id: "nisc.moss.sessions",
170
170
  migrations: [
@@ -190,6 +190,11 @@ var sessionOf = async (pool, token) => {
190
190
  const principal = res.rows[0]?.principal;
191
191
  return typeof principal === "string" ? principal : null;
192
192
  };
193
+ var sessionRemainingMs = async (pool, token) => {
194
+ const res = await pool.query("SELECT extract(epoch from expires_at - now()) * 1000 AS remaining FROM sessions WHERE token_hash = $1 AND expires_at > now()", [hashSessionToken(token)]);
195
+ const remaining = Number(res.rows[0]?.["remaining"]);
196
+ return res.rows.length > 0 && Number.isFinite(remaining) ? remaining : null;
197
+ };
193
198
  var revokeAllFor = async (pool, principal) => {
194
199
  await pool.query("DELETE FROM sessions WHERE principal = $1", [principal]);
195
200
  };
@@ -212,154 +217,10 @@ var createDataLayer = async (runtime, entries = []) => {
212
217
  const cache = runtime.cache ?? vex.createPostgresCache({ pool: runtime.pool });
213
218
  await cache.init?.();
214
219
  await vex.seedCache(cache, entries);
215
- const engine = vex.createQueryEngine({ adapter, cache });
220
+ const engine = vex.createQueryEngine({ adapter, cache, ...runtime.vexConfig !== void 0 ? { config: runtime.vexConfig } : {} });
216
221
  const schema = await engine.introspect();
217
222
  return { engine, schema, grants: vex.scopeGrants(schema.entities.map((e) => e.name)) };
218
223
  };
219
- var TIDE_DDL = `
220
- CREATE TABLE IF NOT EXISTS tide_fact (
221
- id text PRIMARY KEY,
222
- kind text NOT NULL CHECK (kind IN ('write','signal','manual','run')),
223
- entity text,
224
- op text CHECK (op IN ('insert','update','delete')),
225
- row jsonb,
226
- name text,
227
- payload jsonb,
228
- reflex text,
229
- run_id text,
230
- occurrence text,
231
- stats jsonb,
232
- target text,
233
- by text,
234
- at bigint NOT NULL,
235
- not_before bigint,
236
- dedupe_key text,
237
- cause text,
238
- depth integer NOT NULL DEFAULT 0,
239
- delivered_at bigint,
240
- parked text,
241
- released boolean,
242
- -- WHOSE FACT THIS IS. The identity of the reflex that minted it, absent on
243
- -- anything the host ingested. The matcher refuses to hand a fact minted
244
- -- under one identity to a reflex running under another, which is the only
245
- -- thing standing between a carried row and somebody else's effect \u2014 tide is
246
- -- the one place a row travels without being read, so no scope policy is
247
- -- consulted on the way.
248
- as_who text
249
- );
250
-
251
- -- A PARTIAL index, because a fact with no dedupeKey is not claiming to be
252
- -- unique: it is a distinct occurrence of something, not a repeat of it.
253
- -- entity is in the key: without it, two producers over different tables
254
- -- that agreed on a key value silently ate each other's rows.
255
- CREATE UNIQUE INDEX IF NOT EXISTS tide_fact_dedupe
256
- ON tide_fact (kind, coalesce(entity,''), coalesce(name,''), dedupe_key)
257
- WHERE dedupe_key IS NOT NULL;
258
-
259
- -- The matcher's query, every advance.
260
- CREATE INDEX IF NOT EXISTS tide_fact_due
261
- ON tide_fact (at) WHERE delivered_at IS NULL AND parked IS NULL;
262
- CREATE INDEX IF NOT EXISTS tide_fact_swept ON tide_fact (delivered_at);
263
-
264
- CREATE TABLE IF NOT EXISTS tide_run (
265
- id text PRIMARY KEY,
266
- reflex_id text NOT NULL,
267
- version text NOT NULL,
268
- as_who text,
269
- cause text NOT NULL,
270
- occurrence text,
271
- fact_ids jsonb,
272
- state text NOT NULL CHECK (state IN ('pending','fanned','settled','skipped')),
273
- depth integer NOT NULL DEFAULT 0,
274
- selected integer,
275
- total integer NOT NULL DEFAULT 0,
276
- done integer NOT NULL DEFAULT 0,
277
- failed integer NOT NULL DEFAULT 0,
278
- due_at bigint NOT NULL,
279
- created_at bigint NOT NULL,
280
- settled_at bigint,
281
- drained boolean,
282
- note text,
283
- -- THE IDEMPOTENCY. One constraint, every trigger kind: an occurrence
284
- -- cannot open twice, a replayed fact cannot open twice, and two instances
285
- -- ticking at the same moment contend instead of duplicating.
286
- UNIQUE (reflex_id, cause)
287
- );
288
-
289
- CREATE INDEX IF NOT EXISTS tide_run_pending ON tide_run (state, due_at);
290
- CREATE INDEX IF NOT EXISTS tide_run_ledger ON tide_run (reflex_id, created_at DESC);
291
- CREATE INDEX IF NOT EXISTS tide_run_swept ON tide_run (settled_at);
292
-
293
- CREATE TABLE IF NOT EXISTS tide_work (
294
- id text PRIMARY KEY,
295
- -- ON DELETE CASCADE, because a run and its work are one fact about the
296
- -- world. Sweeping runs and leaving work destroys the UNIQUE(run_id, unit)
297
- -- row that IS the "this unit already ran" record \u2014 and a restore then
298
- -- re-charges the invoice.
299
- run_id text NOT NULL REFERENCES tide_run(id) ON DELETE CASCADE,
300
- reflex_id text NOT NULL,
301
- unit text NOT NULL,
302
- cause text NOT NULL,
303
- env jsonb NOT NULL,
304
- depth integer NOT NULL DEFAULT 0,
305
- state text NOT NULL CHECK (state IN ('pending','claimed','retrying','done','failed')),
306
- attempt integer NOT NULL DEFAULT 0,
307
- token text,
308
- -- Zero, never null, when unclaimed: "never claimed or lapsed" is then one
309
- -- comparison rather than a disjunction.
310
- claimed_until bigint NOT NULL DEFAULT 0,
311
- not_before bigint NOT NULL,
312
- input jsonb,
313
- output jsonb,
314
- error text,
315
- created_at bigint NOT NULL,
316
- settled_at bigint,
317
- UNIQUE (run_id, unit)
318
- );
319
-
320
- CREATE INDEX IF NOT EXISTS tide_work_claimable ON tide_work (state, not_before, claimed_until);
321
- CREATE INDEX IF NOT EXISTS tide_work_run ON tide_work (run_id);
322
- CREATE INDEX IF NOT EXISTS tide_work_swept ON tide_work (settled_at);
323
-
324
- CREATE TABLE IF NOT EXISTS tide_reflex_state (
325
- reflex_id text PRIMARY KEY,
326
- armed_at bigint NOT NULL DEFAULT 0,
327
- materialized_through bigint
328
- );
329
-
330
- -- Polls are gone (the vex bridge pushes writes \u2014 a poll could only
331
- -- re-discover them late), and their cursor state goes with them. IF EXISTS,
332
- -- so a store created after the removal is not asked to drop what it never had.
333
- ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_cursor;
334
- ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_seen;
335
- ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS polled_at;
336
- `;
337
- var statementsOf = (ddl) => ddl.split(";").map((chunk) => chunk.trim()).filter((chunk) => chunk.split("\n").some((line) => line.trim() !== "" && !line.trim().startsWith("--"))).map((sql) => ({ kind: "sql", sql }));
338
- ({
339
- migrations: [
340
- { description: "The tide store: facts, runs, work and reflex state, converged from any earlier shape", steps: statementsOf(TIDE_DDL) },
341
- {
342
- // A fact's chain: the root it belongs to, and — on a root — how many facts
343
- // the chain has minted beneath it. Nullable: every existing fact is a
344
- // root nothing has been counted against yet.
345
- description: "A fact carries its chain root, and a root counts what its chain minted (tide maxChainFacts)",
346
- steps: [
347
- { kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS root text" },
348
- { kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS descendants integer" }
349
- ]
350
- }
351
- ]
352
- });
353
- var mintWrites = async (intake, event, as, at, chain) => {
354
- for (const write of event.writes) {
355
- for (const row of write.rows) {
356
- await intake.ingest(
357
- { kind: "write", entity: write.table, op: write.op, row, at },
358
- { as, ...chain !== void 0 ? { cause: chain.cause, depth: chain.depth + 1 } : {} }
359
- );
360
- }
361
- }
362
- };
363
224
 
364
225
  // src/generation.ts
365
226
  var GENERATION_DDL = [
@@ -409,25 +270,25 @@ var createGeneration = (pool, ctx) => {
409
270
  var b64url = (buffer) => buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
410
271
  var signerFromSeed = (seed) => {
411
272
  const pkcs8 = Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), seed.subarray(0, 32)]);
412
- const privateKey = crypto.createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" });
273
+ const privateKey = crypto$1.createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" });
413
274
  const asInput = privateKey;
414
- return { privateKey, publicKey: crypto.createPublicKey(asInput) };
275
+ return { privateKey, publicKey: crypto$1.createPublicKey(asInput) };
415
276
  };
416
277
  var createAssertionSigner = (seedB64) => {
417
278
  const seed = seedB64 !== void 0 && seedB64 !== "" ? Buffer.from(seedB64, "base64") : void 0;
418
- const { publicKey, privateKey } = seed !== void 0 && seed.length >= 32 ? signerFromSeed(seed) : crypto.generateKeyPairSync("ed25519");
279
+ const { publicKey, privateKey } = seed !== void 0 && seed.length >= 32 ? signerFromSeed(seed) : crypto$1.generateKeyPairSync("ed25519");
419
280
  const verifyKey = publicKey.export({ type: "spki", format: "der" }).toString("base64");
420
281
  return {
421
282
  verifyKey,
422
283
  mint: (claims, ttlMs = 3e4) => {
423
284
  const iat = Date.now();
424
285
  const body = Buffer.from(JSON.stringify({ ...claims, iat, exp: iat + ttlMs }));
425
- return `${b64url(body)}.${b64url(crypto.sign(null, body, privateKey))}`;
286
+ return `${b64url(body)}.${b64url(crypto$1.sign(null, body, privateKey))}`;
426
287
  }
427
288
  };
428
289
  };
429
- var mintIntegrationKey = () => `ik_${crypto.randomBytes(32).toString("hex")}`;
430
- var hashIntegrationKey = (key) => crypto.createHash("sha256").update(key).digest("hex");
290
+ var mintIntegrationKey = () => `ik_${crypto$1.randomBytes(32).toString("hex")}`;
291
+ var hashIntegrationKey = (key) => crypto$1.createHash("sha256").update(key).digest("hex");
431
292
 
432
293
  // src/integrations.ts
433
294
  var configurationBase = {
@@ -1321,7 +1182,160 @@ var contractAsMarkdown = (contract, fingerprints) => [
1321
1182
  ``
1322
1183
  ].join("\n");
1323
1184
 
1324
- // src/principal.ts
1185
+ // src/migrate.ts
1186
+ var tableSequencesOf = (runtime) => {
1187
+ const cacheSequence = (runtime.cache ?? vex.createPostgresCache({ pool: runtime.pool })).sequence;
1188
+ return [
1189
+ MOSS_SEQUENCE,
1190
+ ...runtime.session === "sessions" ? [SESSIONS_SEQUENCE] : [],
1191
+ ...cacheSequence === void 0 ? [] : [cacheSequence],
1192
+ ...runtime.tables ?? []
1193
+ ];
1194
+ };
1195
+ var TIDE_DDL = `
1196
+ CREATE TABLE IF NOT EXISTS tide_fact (
1197
+ id text PRIMARY KEY,
1198
+ kind text NOT NULL CHECK (kind IN ('write','signal','manual','run')),
1199
+ entity text,
1200
+ op text CHECK (op IN ('insert','update','delete')),
1201
+ row jsonb,
1202
+ name text,
1203
+ payload jsonb,
1204
+ reflex text,
1205
+ run_id text,
1206
+ occurrence text,
1207
+ stats jsonb,
1208
+ target text,
1209
+ by text,
1210
+ at bigint NOT NULL,
1211
+ not_before bigint,
1212
+ dedupe_key text,
1213
+ cause text,
1214
+ depth integer NOT NULL DEFAULT 0,
1215
+ delivered_at bigint,
1216
+ parked text,
1217
+ released boolean,
1218
+ -- WHOSE FACT THIS IS. The identity of the reflex that minted it, absent on
1219
+ -- anything the host ingested. The matcher refuses to hand a fact minted
1220
+ -- under one identity to a reflex running under another, which is the only
1221
+ -- thing standing between a carried row and somebody else's effect \u2014 tide is
1222
+ -- the one place a row travels without being read, so no scope policy is
1223
+ -- consulted on the way.
1224
+ as_who text
1225
+ );
1226
+
1227
+ -- A PARTIAL index, because a fact with no dedupeKey is not claiming to be
1228
+ -- unique: it is a distinct occurrence of something, not a repeat of it.
1229
+ -- entity is in the key: without it, two producers over different tables
1230
+ -- that agreed on a key value silently ate each other's rows.
1231
+ CREATE UNIQUE INDEX IF NOT EXISTS tide_fact_dedupe
1232
+ ON tide_fact (kind, coalesce(entity,''), coalesce(name,''), dedupe_key)
1233
+ WHERE dedupe_key IS NOT NULL;
1234
+
1235
+ -- The matcher's query, every advance.
1236
+ CREATE INDEX IF NOT EXISTS tide_fact_due
1237
+ ON tide_fact (at) WHERE delivered_at IS NULL AND parked IS NULL;
1238
+ CREATE INDEX IF NOT EXISTS tide_fact_swept ON tide_fact (delivered_at);
1239
+
1240
+ CREATE TABLE IF NOT EXISTS tide_run (
1241
+ id text PRIMARY KEY,
1242
+ reflex_id text NOT NULL,
1243
+ version text NOT NULL,
1244
+ as_who text,
1245
+ cause text NOT NULL,
1246
+ occurrence text,
1247
+ fact_ids jsonb,
1248
+ state text NOT NULL CHECK (state IN ('pending','fanned','settled','skipped')),
1249
+ depth integer NOT NULL DEFAULT 0,
1250
+ selected integer,
1251
+ total integer NOT NULL DEFAULT 0,
1252
+ done integer NOT NULL DEFAULT 0,
1253
+ failed integer NOT NULL DEFAULT 0,
1254
+ due_at bigint NOT NULL,
1255
+ created_at bigint NOT NULL,
1256
+ settled_at bigint,
1257
+ drained boolean,
1258
+ note text,
1259
+ -- THE IDEMPOTENCY. One constraint, every trigger kind: an occurrence
1260
+ -- cannot open twice, a replayed fact cannot open twice, and two instances
1261
+ -- ticking at the same moment contend instead of duplicating.
1262
+ UNIQUE (reflex_id, cause)
1263
+ );
1264
+
1265
+ CREATE INDEX IF NOT EXISTS tide_run_pending ON tide_run (state, due_at);
1266
+ CREATE INDEX IF NOT EXISTS tide_run_ledger ON tide_run (reflex_id, created_at DESC);
1267
+ CREATE INDEX IF NOT EXISTS tide_run_swept ON tide_run (settled_at);
1268
+
1269
+ CREATE TABLE IF NOT EXISTS tide_work (
1270
+ id text PRIMARY KEY,
1271
+ -- ON DELETE CASCADE, because a run and its work are one fact about the
1272
+ -- world. Sweeping runs and leaving work destroys the UNIQUE(run_id, unit)
1273
+ -- row that IS the "this unit already ran" record \u2014 and a restore then
1274
+ -- re-charges the invoice.
1275
+ run_id text NOT NULL REFERENCES tide_run(id) ON DELETE CASCADE,
1276
+ reflex_id text NOT NULL,
1277
+ unit text NOT NULL,
1278
+ cause text NOT NULL,
1279
+ env jsonb NOT NULL,
1280
+ depth integer NOT NULL DEFAULT 0,
1281
+ state text NOT NULL CHECK (state IN ('pending','claimed','retrying','done','failed')),
1282
+ attempt integer NOT NULL DEFAULT 0,
1283
+ token text,
1284
+ -- Zero, never null, when unclaimed: "never claimed or lapsed" is then one
1285
+ -- comparison rather than a disjunction.
1286
+ claimed_until bigint NOT NULL DEFAULT 0,
1287
+ not_before bigint NOT NULL,
1288
+ input jsonb,
1289
+ output jsonb,
1290
+ error text,
1291
+ created_at bigint NOT NULL,
1292
+ settled_at bigint,
1293
+ UNIQUE (run_id, unit)
1294
+ );
1295
+
1296
+ CREATE INDEX IF NOT EXISTS tide_work_claimable ON tide_work (state, not_before, claimed_until);
1297
+ CREATE INDEX IF NOT EXISTS tide_work_run ON tide_work (run_id);
1298
+ CREATE INDEX IF NOT EXISTS tide_work_swept ON tide_work (settled_at);
1299
+
1300
+ CREATE TABLE IF NOT EXISTS tide_reflex_state (
1301
+ reflex_id text PRIMARY KEY,
1302
+ armed_at bigint NOT NULL DEFAULT 0,
1303
+ materialized_through bigint
1304
+ );
1305
+
1306
+ -- Polls are gone (the vex bridge pushes writes \u2014 a poll could only
1307
+ -- re-discover them late), and their cursor state goes with them. IF EXISTS,
1308
+ -- so a store created after the removal is not asked to drop what it never had.
1309
+ ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_cursor;
1310
+ ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS poll_seen;
1311
+ ALTER TABLE tide_reflex_state DROP COLUMN IF EXISTS polled_at;
1312
+ `;
1313
+ var statementsOf = (ddl) => ddl.split(";").map((chunk) => chunk.trim()).filter((chunk) => chunk.split("\n").some((line) => line.trim() !== "" && !line.trim().startsWith("--"))).map((sql) => ({ kind: "sql", sql }));
1314
+ ({
1315
+ migrations: [
1316
+ { description: "The tide store: facts, runs, work and reflex state, converged from any earlier shape", steps: statementsOf(TIDE_DDL) },
1317
+ {
1318
+ // A fact's chain: the root it belongs to, and — on a root — how many facts
1319
+ // the chain has minted beneath it. Nullable: every existing fact is a
1320
+ // root nothing has been counted against yet.
1321
+ description: "A fact carries its chain root, and a root counts what its chain minted (tide maxChainFacts)",
1322
+ steps: [
1323
+ { kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS root text" },
1324
+ { kind: "sql", sql: "ALTER TABLE tide_fact ADD COLUMN IF NOT EXISTS descendants integer" }
1325
+ ]
1326
+ }
1327
+ ]
1328
+ });
1329
+ var mintWrites = async (intake, event, as, at, chain) => {
1330
+ for (const write of event.writes) {
1331
+ for (const row of write.rows) {
1332
+ await intake.ingest(
1333
+ { kind: "write", entity: write.table, op: write.op, row, at },
1334
+ { as, ...chain !== void 0 ? { cause: chain.cause, depth: chain.depth + 1 } : {} }
1335
+ );
1336
+ }
1337
+ }
1338
+ };
1325
1339
  var resolveRoles = (app, principal) => principal === null ? ["public"] : app.assignments?.[principal] ?? ["public"];
1326
1340
  var wearableOf = (app) => {
1327
1341
  const declared = app.wearable;
@@ -1401,8 +1415,95 @@ var versionToken = (ids) => {
1401
1415
  }
1402
1416
  return h.toString(16).padStart(8, "0");
1403
1417
  };
1404
- var PROTOCOL = 1;
1405
- var PROTOCOL_MIN = 1;
1418
+
1419
+ // src/session-cookie.ts
1420
+ var DEFAULT_TOKEN_KEY = "nisc.token";
1421
+ var tokenFromCookie = (header, name = DEFAULT_TOKEN_KEY) => {
1422
+ if (header === void 0 || header === null) return null;
1423
+ const wanted = encodeURIComponent(name);
1424
+ for (const part of header.split(";")) {
1425
+ const at = part.indexOf("=");
1426
+ if (at < 0 || part.slice(0, at).trim() !== wanted) continue;
1427
+ try {
1428
+ const value = decodeURIComponent(part.slice(at + 1).trim());
1429
+ return value === "" ? null : value;
1430
+ } catch {
1431
+ return null;
1432
+ }
1433
+ }
1434
+ return null;
1435
+ };
1436
+ var isOwnOrigin = (origin, host, listed = []) => {
1437
+ if (origin === void 0 || origin === null || !URL.canParse(origin)) return false;
1438
+ const asked = new URL(origin);
1439
+ return asked.host === host?.toLowerCase() || listed.some((entry) => URL.canParse(entry) && new URL(entry).origin === asked.origin);
1440
+ };
1441
+ var nameOf = (key, port) => `${key}${port === "" ? "" : `.${port}`}`;
1442
+ var cookiesAt = (where, key, token, lastsMs) => {
1443
+ const name = encodeURIComponent(nameOf(key, where.port));
1444
+ const life = token === null ? "; Max-Age=0" : typeof lastsMs === "number" ? `; Max-Age=${Math.max(0, Math.floor(lastsMs / 1e3))}` : "";
1445
+ const kept = `Path=/; SameSite=Lax${where.secure ? "; Secure" : ""}${life}`;
1446
+ return [`${where.secure ? "__Host-" : ""}${name}=${encodeURIComponent(token ?? "")}; HttpOnly; ${kept}`, `${name}.held=${token === null ? "" : "1"}; ${kept}`];
1447
+ };
1448
+ var originOf = (request) => {
1449
+ const said = request.headers.get("origin");
1450
+ if (said !== null && URL.canParse(said)) return said;
1451
+ const here = new URL(request.url);
1452
+ const scheme = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim() || here.protocol.slice(0, -1);
1453
+ return `${scheme}://${request.headers.get("host") ?? here.host}`;
1454
+ };
1455
+ var sessionCookies = (page, token, options = {}) => {
1456
+ const at = new URL(typeof page === "string" ? page : originOf(page));
1457
+ return cookiesAt({ port: at.port, secure: at.protocol === "https:" }, options.key ?? DEFAULT_TOKEN_KEY, token, options.lastsMs);
1458
+ };
1459
+ var sessionTokenOf = (cookies, where, key = DEFAULT_TOKEN_KEY) => {
1460
+ const name = nameOf(key, where.port);
1461
+ for (const secure of where.secure === void 0 ? [true, false] : [where.secure]) {
1462
+ const token = tokenFromCookie(cookies, `${secure ? "__Host-" : ""}${name}`);
1463
+ if (token !== null) return { token, clear: cookiesAt({ port: where.port, secure }, key, null) };
1464
+ }
1465
+ return null;
1466
+ };
1467
+ var SEALED_FOR_MS = 6e4;
1468
+ var sealName = (secure) => `${secure ? "__Http-" : ""}nisc.seal`;
1469
+ var toBase64Url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1470
+ var fromBase64Url = (text) => Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (char) => char.charCodeAt(0));
1471
+ var keyOf = async (seal) => crypto.subtle.importKey("raw", await crypto.subtle.digest("SHA-256", new TextEncoder().encode(seal)), "AES-GCM", false, ["encrypt", "decrypt"]);
1472
+ var newSeal = () => toBase64Url(crypto.getRandomValues(new Uint8Array(32)));
1473
+ var sealOf = (cookies, secure) => tokenFromCookie(cookies, sealName(secure));
1474
+ var sealCookie = (seal, where) => `${sealName(where.secure)}=${seal}; HttpOnly; Path=${where.path}; SameSite=Lax${where.secure ? "; Secure" : ""}`;
1475
+ var sealSession = async (seal, token, forMs = SEALED_FOR_MS) => {
1476
+ const iv = crypto.getRandomValues(new Uint8Array(12));
1477
+ const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await keyOf(seal), new TextEncoder().encode(JSON.stringify({ token, until: Date.now() + forMs })));
1478
+ return toBase64Url(new Uint8Array([...iv, ...new Uint8Array(sealed)]));
1479
+ };
1480
+ var openSealed = async (seal, sealed) => {
1481
+ try {
1482
+ const bytes = fromBase64Url(sealed);
1483
+ const opened = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12) }, await keyOf(seal), bytes.slice(12));
1484
+ const { token, until } = JSON.parse(new TextDecoder().decode(opened));
1485
+ return typeof token === "string" && typeof until === "number" && until > Date.now() ? token : null;
1486
+ } catch {
1487
+ return null;
1488
+ }
1489
+ };
1490
+
1491
+ // src/socket.ts
1492
+ var PROTOCOL = 2;
1493
+ var PROTOCOL_MIN = 2;
1494
+ var SUBPROTOCOL = "nisc";
1495
+ var TOKEN_OFFER = "nisc.token.";
1496
+ var SEALED_OFFER = "nisc.sealed.";
1497
+ var offeredToken = (offered = []) => {
1498
+ const offer = offered.find((entry) => entry.startsWith(TOKEN_OFFER));
1499
+ if (offer === void 0) return null;
1500
+ try {
1501
+ const bytes = atob(offer.slice(TOKEN_OFFER.length).replace(/-/g, "+").replace(/_/g, "/"));
1502
+ return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(bytes, (char) => char.charCodeAt(0))) || null;
1503
+ } catch {
1504
+ return null;
1505
+ }
1506
+ };
1406
1507
  var CLOSE_INVALID_TOKEN = 4401;
1407
1508
  var CLOSE_SIGNED_OUT = 4403;
1408
1509
  var CLOSE_SHELL_FAILED = 4500;
@@ -1418,6 +1519,7 @@ var parse = (text) => {
1418
1519
  };
1419
1520
  var createSocket = (ctx) => {
1420
1521
  const emit = emitterOf(ctx.telemetry);
1522
+ let saidNotOwn = false;
1421
1523
  const live = /* @__PURE__ */ new Map();
1422
1524
  const expire = (connection) => {
1423
1525
  connection.send(JSON.stringify({ type: "error", code: "invalid_token", message: "The session token no longer resolves to this principal." }));
@@ -1474,18 +1576,40 @@ var createSocket = (ctx) => {
1474
1576
  connection.close(CLOSE_PROTOCOL_MISMATCH, "protocol mismatch");
1475
1577
  return;
1476
1578
  }
1477
- const token = params.get("token");
1478
- let principal = null;
1479
- if (token !== null && token !== "") {
1480
- principal = await ctx.session(token);
1481
- if (principal === null) {
1482
- if (emit !== void 0 && upClock !== void 0) {
1483
- emit({ name: "socket.upgrade", startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: "refused", attributes: { hasPrincipal: false } });
1484
- }
1485
- send({ type: "error", code: "invalid_token", message: "The session token did not resolve to a principal." });
1486
- connection.close(CLOSE_INVALID_TOKEN, "invalid token");
1487
- return;
1579
+ const upgrade = connection.upgrade;
1580
+ const key = /^[\w.-]{1,64}$/.test(params.get("key") ?? "") ? params.get("key") : DEFAULT_TOKEN_KEY;
1581
+ const page = upgrade !== void 0 && isOwnOrigin(upgrade.origin, upgrade.host, ctx.origins) ? new URL(upgrade.origin) : void 0;
1582
+ const secure = page?.protocol === "https:";
1583
+ const held = page === void 0 ? null : sessionTokenOf(upgrade?.cookie, { port: page.port, secure }, key);
1584
+ const sealing = page !== void 0 && params.get("sealed") === "1";
1585
+ if (page === void 0 && params.get("sealed") === "1" && typeof upgrade?.origin === "string" && !saidNotOwn) {
1586
+ saidNotOwn = true;
1587
+ console.warn(`[moss] a terminal on ${upgrade.origin} holds its own session token: this server was addressed as ${upgrade.host ?? "nothing"}, so that is not the app\u2019s own page. If the app is served there, behind a proxy that rewrites Host, list it in runtime.origins.`);
1588
+ }
1589
+ const hadSeal = sealing ? sealOf(upgrade?.cookie, secure) : null;
1590
+ const sealedOffer = upgrade?.offered.find((entry) => entry.startsWith(SEALED_OFFER))?.slice(SEALED_OFFER.length) ?? null;
1591
+ const sealLost = sealing && sealedOffer !== null && hadSeal === null;
1592
+ const seal = !sealing || sealLost ? null : hadSeal ?? (upgrade?.answer === void 0 ? null : newSeal());
1593
+ const offered = offeredToken(upgrade?.offered) ?? (sealedOffer === null || hadSeal === null ? null : await openSealed(hadSeal, sealedOffer));
1594
+ let token = offered ?? (params.get("leave") === "1" ? null : held?.token ?? null);
1595
+ let principal = token === null ? null : await ctx.session(token);
1596
+ if (offered !== null && principal === null) {
1597
+ if (emit !== void 0 && upClock !== void 0) {
1598
+ emit({ name: "socket.upgrade", startUnixNano: upClock.startUnixNano, endUnixNano: upClock.endUnixNano(), status: "refused", attributes: { hasPrincipal: false } });
1488
1599
  }
1600
+ send({ type: "error", code: "invalid_token", message: "The session token did not resolve to a principal." });
1601
+ connection.close(CLOSE_INVALID_TOKEN, "invalid token");
1602
+ return;
1603
+ }
1604
+ if (principal === null) token = null;
1605
+ const answered = [
1606
+ ...page === void 0 || offered === null && (held?.token ?? null) === token ? [] : token === null ? held?.clear ?? [] : sessionCookies(page.origin, token, { key, lastsMs: await ctx.sessionLastsMs?.(token) ?? null }),
1607
+ ...seal !== null && hadSeal === null ? [sealCookie(seal, { secure, path: new URL(url, "http://nisc.local").pathname })] : []
1608
+ ];
1609
+ if (answered.length > 0) upgrade?.answer?.(answered);
1610
+ if (seal !== null) connection.seal = (granted) => sealSession(seal, granted);
1611
+ if (sealLost) {
1612
+ send({ type: "error", code: "seal_not_kept", message: "This browser did not keep the cookie a sealed sign-in is opened with. Sign in again: it will be handed over as a token." });
1489
1613
  }
1490
1614
  live.set(connection, token !== null && token !== "" && principal !== null ? { token, principal } : null);
1491
1615
  connection.onClose(() => live.delete(connection));
@@ -1691,7 +1815,9 @@ var createShellHost = (ctx) => {
1691
1815
  };
1692
1816
  const delta = ctx.delta ?? false;
1693
1817
  const DELTA_CEILING = 0.6;
1818
+ const DELTA_MAX_FRAME = 64 * 1024;
1694
1819
  const shorterAsDelta = (previous, next, canvasId) => {
1820
+ if (previous.length > DELTA_MAX_FRAME || next.length > DELTA_MAX_FRAME) return null;
1695
1821
  try {
1696
1822
  const ops = encodeDelta(previous, next);
1697
1823
  const message = { type: "render-delta", canvas: canvasId, ops, hash: frameHash(next) };
@@ -1749,7 +1875,15 @@ var createShellHost = (ctx) => {
1749
1875
  // ephemeral and dies on detach.
1750
1876
  grant: (token2) => {
1751
1877
  const message = JSON.stringify({ type: "session", token: token2 });
1752
- for (const connection of liveRef?.connections ?? []) connection.send(message);
1878
+ for (const connection of liveRef?.connections ?? []) {
1879
+ if (connection.seal === void 0) connection.send(message);
1880
+ else {
1881
+ void connection.seal(token2).then(
1882
+ (sealed) => connection.send(JSON.stringify({ type: "session", sealed })),
1883
+ (error) => console.error("[moss] a sign-in could not be sealed, and was not handed over:", error)
1884
+ );
1885
+ }
1886
+ }
1753
1887
  },
1754
1888
  // REVOKE: forget the credential, close every terminal SIGNED_OUT,
1755
1889
  // evict the durable shell. Under moss's own credential the rows go
@@ -1984,8 +2118,8 @@ var createShellHost = (ctx) => {
1984
2118
  const settle = async (live, waitMs) => {
1985
2119
  const started = Date.now();
1986
2120
  let timer;
1987
- const deadline = new Promise((resolve) => {
1988
- timer = setTimeout(() => resolve(false), waitMs);
2121
+ const deadline = new Promise((resolve2) => {
2122
+ timer = setTimeout(() => resolve2(false), waitMs);
1989
2123
  });
1990
2124
  const whole = live.seeded.then(() => nova.shellSettled(live.shell, { waitMs: Math.max(0, waitMs - (Date.now() - started)), stopped: () => live.ended }));
1991
2125
  const settled = await Promise.race([whole, deadline]);
@@ -2074,7 +2208,7 @@ var createShellHost = (ctx) => {
2074
2208
  const settled = await settle(cell.live, waitMs);
2075
2209
  return { ...read(cell.live), settled, ...needOf(cell.live, principal) };
2076
2210
  }
2077
- const seed = crypto.randomBytes(9).toString("hex");
2211
+ const seed = crypto$1.randomBytes(9).toString("hex");
2078
2212
  const live = await build(token, principal, false, seed, options?.inputs);
2079
2213
  try {
2080
2214
  const settled = await settle(live, waitMs);
@@ -2345,7 +2479,7 @@ var createIdentityCache = (ctx) => {
2345
2479
  };
2346
2480
 
2347
2481
  // src/server.ts
2348
- var secretsEqual = (a, b) => crypto.timingSafeEqual(crypto.createHash("sha256").update(a).digest(), crypto.createHash("sha256").update(b).digest());
2482
+ var secretsEqual = (a, b) => crypto$1.timingSafeEqual(crypto$1.createHash("sha256").update(a).digest(), crypto$1.createHash("sha256").update(b).digest());
2349
2483
  var guardOperator = (operator, opts) => {
2350
2484
  const gate = opts.gate;
2351
2485
  if (gate !== void 0) operator.use("*", (c, next) => Promise.resolve(gate(c, next)));
@@ -2373,12 +2507,7 @@ var createServer = async (app, runtime) => {
2373
2507
  const session = sessionVerifierOf(runtime);
2374
2508
  const emit = emitterOf(runtime.telemetry);
2375
2509
  const vexOnExecute = emit === void 0 ? void 0 : (rec) => emit(vexRecordToSpan(rec));
2376
- const cacheSequence = (runtime.cache ?? vex.createPostgresCache({ pool: runtime.pool })).sequence;
2377
- await postgres.migrate(
2378
- runtime.pool,
2379
- [MOSS_SEQUENCE, ...runtime.session === "sessions" ? [SESSIONS_SEQUENCE] : [], ...cacheSequence === void 0 ? [] : [cacheSequence]],
2380
- { mode: runtime.migrations ?? "apply" }
2381
- );
2510
+ await postgres.migrate(runtime.pool, tableSequencesOf(runtime), { mode: runtime.migrations ?? "apply" });
2382
2511
  const grammars = await createGrammarUpgrader(app);
2383
2512
  await postgres.upgradeStore(runtime.pool, INTEGRATION_ACTIONS_STORE, grammars);
2384
2513
  const data = await createDataLayer(runtime, app.entries ?? []);
@@ -2455,7 +2584,7 @@ ${variantErrors.map((e) => ` ${e}`).join("\n")}`);
2455
2584
  revalidateMs: runtime.sessionRevalidateMs ?? DEFAULT_REVALIDATE_MS
2456
2585
  }) : void 0;
2457
2586
  const keys = /* @__PURE__ */ new WeakMap();
2458
- const keyOf = (record) => {
2587
+ const keyOf2 = (record) => {
2459
2588
  const hit = keys.get(record);
2460
2589
  if (hit !== void 0) return hit;
2461
2590
  const key = memoKey(record.roles, record.installed);
@@ -2471,7 +2600,7 @@ ${variantErrors.map((e) => ` ${e}`).join("\n")}`);
2471
2600
  const resolveIdentity = async (principal) => {
2472
2601
  if (identities !== void 0 && principal !== null) {
2473
2602
  const record = await identities.get(principal);
2474
- return { roles: record.roles, scope: record.scope, installed: record.installed, key: keyOf(record), record };
2603
+ return { roles: record.roles, scope: record.scope, installed: record.installed, key: keyOf2(record), record };
2475
2604
  }
2476
2605
  return fromSeams(principal);
2477
2606
  };
@@ -2871,7 +3000,7 @@ ${variantErrors.map((e) => ` ${e}`).join("\n")}`);
2871
3000
  if (!frameAdmits(found.frames ?? {}, path, held)) return c.json({ message: "No such frame." }, 404);
2872
3001
  const now = Date.now();
2873
3002
  sweepGrants(now);
2874
- const token = crypto.randomBytes(24).toString("hex");
3003
+ const token = crypto$1.randomBytes(24).toString("hex");
2875
3004
  grants.set(token, { integration: id, principal, path, expires: now + GRANT_TTL_MS });
2876
3005
  return c.json({ src: `/integrations/${id}/frame/${token}`, expiresIn: GRANT_TTL_MS });
2877
3006
  });
@@ -3078,7 +3207,7 @@ ${variantErrors.map((e) => ` ${e}`).join("\n")}`);
3078
3207
  if (host === void 0 || manifest === void 0) return void 0;
3079
3208
  return { name: matched.name, host, inputs: manifest.params === void 0 ? {} : { [manifest.params]: matched.params } };
3080
3209
  };
3081
- const fabricOrigin = crypto.randomBytes(8).toString("hex");
3210
+ const fabricOrigin = crypto$1.randomBytes(8).toString("hex");
3082
3211
  const applyInvalidateIdentity = (principal) => {
3083
3212
  const held = identities?.invalidate(principal) ?? false;
3084
3213
  shells?.reset(principal);
@@ -3142,7 +3271,9 @@ ${nextVariantErrors.map((e) => ` ${e}`).join("\n")}`);
3142
3271
  ...shells !== void 0 ? { shells } : {},
3143
3272
  page: pageAt,
3144
3273
  ...runtime.sessionRevalidateMs !== void 0 ? { revalidateMs: runtime.sessionRevalidateMs } : {},
3145
- ...runtime.telemetry !== void 0 ? { telemetry: runtime.telemetry } : {}
3274
+ ...runtime.telemetry !== void 0 ? { telemetry: runtime.telemetry } : {},
3275
+ ...runtime.origins !== void 0 ? { origins: runtime.origins } : {},
3276
+ ...runtime.session === "sessions" ? { sessionLastsMs: (token) => sessionRemainingMs(runtime.pool, token) } : {}
3146
3277
  });
3147
3278
  return Object.assign(server, {
3148
3279
  socket,
@@ -3187,23 +3318,7 @@ ${nextVariantErrors.map((e) => ` ${e}`).join("\n")}`);
3187
3318
  });
3188
3319
  };
3189
3320
  var SNAPSHOT_ELEMENT_ID = "nisc-snapshot";
3190
- var DEFAULT_TOKEN_KEY = "nisc.token";
3191
3321
  var DEFAULT_ROOT = '<div id="root"></div>';
3192
- var tokenFromCookie = (header, tokenKey = DEFAULT_TOKEN_KEY) => {
3193
- if (header === void 0 || header === null) return null;
3194
- const wanted = encodeURIComponent(tokenKey);
3195
- for (const part of header.split(";")) {
3196
- const at = part.indexOf("=");
3197
- if (at < 0 || part.slice(0, at).trim() !== wanted) continue;
3198
- try {
3199
- const value = decodeURIComponent(part.slice(at + 1).trim());
3200
- return value === "" ? null : value;
3201
- } catch {
3202
- return null;
3203
- }
3204
- }
3205
- return null;
3206
- };
3207
3322
  var embedSnapshot = (snapshot, principal, path) => {
3208
3323
  const { frame, trees, seed, live } = snapshot;
3209
3324
  const text = JSON.stringify({ frame, trees, principal: principal !== null, live, ...seed !== void 0 ? { seed } : {}, ...path !== void 0 ? { path } : {} }).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
@@ -3218,7 +3333,8 @@ var renderDocument = async (config) => {
3218
3333
  const undrawn = { html: template, headers: documentHeaders(null), drawn: false, principal: null };
3219
3334
  if (!template.includes(root)) return undrawn;
3220
3335
  try {
3221
- const token = tokenFromCookie(request.cookie, tokenKey);
3336
+ const ports = [/:(\d+)$/.exec(request.host ?? "")?.[1] ?? "", ...config.site !== void 0 && URL.canParse(config.site) ? [new URL(config.site).port] : []];
3337
+ const token = ports.map((port) => sessionTokenOf(request.cookie, { port }, tokenKey)?.token ?? null).find((found) => found !== null) ?? null;
3222
3338
  const principal = token === null ? null : await server.principalOf(token);
3223
3339
  const route = server.page(request.path);
3224
3340
  const host = route?.host ?? server.shells;
@@ -3236,10 +3352,7 @@ var renderDocument = async (config) => {
3236
3352
  return {
3237
3353
  html,
3238
3354
  ...head !== void 0 ? { head } : {},
3239
- headers: {
3240
- ...documentHeaders(principal),
3241
- ...token !== null && principal === null ? { "set-cookie": `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax` } : {}
3242
- },
3355
+ headers: documentHeaders(principal),
3243
3356
  drawn: true,
3244
3357
  principal,
3245
3358
  ...route !== void 0 ? { page: route.name } : {},
@@ -3255,24 +3368,62 @@ var renderDocument = async (config) => {
3255
3368
  };
3256
3369
 
3257
3370
  // src/node.ts
3371
+ var MAX_MESSAGE_BYTES = 256 * 1024;
3258
3372
  var attachSocket = (httpServer, accept, path = "/socket", options) => {
3259
- const wss = new ws.WebSocketServer({ noServer: true, perMessageDeflate: options?.compression ?? true });
3373
+ const wss = new ws.WebSocketServer({
3374
+ noServer: true,
3375
+ perMessageDeflate: options?.compression ?? true,
3376
+ maxPayload: options?.maxMessageBytes ?? MAX_MESSAGE_BYTES,
3377
+ // Of what a terminal offers, `nisc` is answered and nothing else: the
3378
+ // other entry is its token (socket.ts), which is not said back.
3379
+ handleProtocols: (offered) => offered.has(SUBPROTOCOL) ? SUBPROTOCOL : false
3380
+ });
3381
+ const answers = /* @__PURE__ */ new WeakMap();
3382
+ wss.on("headers", (headers, req) => {
3383
+ for (const cookie of answers.get(req) ?? []) headers.push(`Set-Cookie: ${cookie}`);
3384
+ });
3260
3385
  httpServer.on("upgrade", (req, socket, head) => {
3261
3386
  const url = req.url ?? "/";
3262
3387
  if (new URL(url, "http://nisc.local").pathname !== path) return;
3263
- wss.handleUpgrade(req, socket, head, (ws) => {
3264
- accept(url, {
3265
- send: (text) => ws.send(text),
3266
- close: (code, reason) => ws.close(code, reason),
3267
- onMessage: (fn) => ws.on("message", (data) => fn(String(data))),
3268
- onClose: (fn) => ws.on("close", () => fn())
3269
- }).catch((error) => {
3270
- console.error("[moss/node] a connection escaped accept:", error);
3271
- try {
3272
- ws.close(1011, "accept failed");
3273
- } catch {
3274
- }
3388
+ socket.on("error", () => {
3389
+ });
3390
+ let ws;
3391
+ let answered = false;
3392
+ let cookies = [];
3393
+ const answer = () => {
3394
+ if (answered) return ws;
3395
+ answered = true;
3396
+ answers.set(req, cookies);
3397
+ wss.handleUpgrade(req, socket, head, (opened) => {
3398
+ ws = opened;
3399
+ opened.on("error", (error) => {
3400
+ console.warn(`[moss/node] a connection was closed on what it sent: ${error.message}`);
3401
+ });
3275
3402
  });
3403
+ return ws;
3404
+ };
3405
+ accept(url, {
3406
+ send: (text) => void answer()?.send(text),
3407
+ close: (code, reason) => void answer()?.close(code, reason),
3408
+ onMessage: (fn) => void answer()?.on("message", (data) => fn(String(data))),
3409
+ onClose: (fn) => {
3410
+ const opened = answer();
3411
+ if (opened === void 0) queueMicrotask(fn);
3412
+ else opened.on("close", () => fn());
3413
+ },
3414
+ upgrade: {
3415
+ offered: String(req.headers["sec-websocket-protocol"] ?? "").split(",").map((entry) => entry.trim()),
3416
+ origin: req.headers.origin ?? null,
3417
+ host: req.headers.host ?? null,
3418
+ cookie: req.headers.cookie ?? null,
3419
+ answer: (given) => void (cookies = given)
3420
+ }
3421
+ }).catch((error) => {
3422
+ console.error("[moss/node] a connection escaped accept:", error);
3423
+ try {
3424
+ answer()?.close(1011, "accept failed");
3425
+ } catch {
3426
+ }
3276
3427
  });
3277
3428
  });
3278
3429
  };
@@ -3294,7 +3445,7 @@ var mountSite = (server, config) => {
3294
3445
  ...drawing,
3295
3446
  server,
3296
3447
  template,
3297
- request: { path: c.req.path === "/index.html" ? "/" : c.req.path, cookie: c.req.header("cookie") ?? null }
3448
+ request: { path: c.req.path === "/index.html" ? "/" : c.req.path, cookie: c.req.header("cookie") ?? null, host: c.req.header("host") ?? null }
3298
3449
  });
3299
3450
  return c.html(page.html, 200, page.headers);
3300
3451
  });