nish-ui 3.0.0 → 3.2.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 (89) hide show
  1. package/README.md +11 -8
  2. package/dist/chart.d.ts +8 -3
  3. package/dist/chart.js +4 -419
  4. package/dist/elements-all.js +70 -69
  5. package/dist/elements-charts.d.ts +8 -2
  6. package/dist/elements-charts.js +23 -23
  7. package/dist/elements-data.d.ts +7 -1
  8. package/dist/elements-data.js +5 -5
  9. package/dist/elements-forms.d.ts +7 -1
  10. package/dist/elements-forms.js +20 -19
  11. package/dist/elements.d.ts +7 -1
  12. package/dist/elements.js +4 -4
  13. package/dist/esm/chart-values.js +2 -1
  14. package/dist/esm/combobox-filter.js +6 -5
  15. package/dist/esm/command-filter.js +32 -0
  16. package/dist/esm/components/accordion.js +2 -1
  17. package/dist/esm/components/app-shell.js +1 -1
  18. package/dist/esm/components/avatar.js +2 -2
  19. package/dist/esm/components/breadcrumbs.js +1 -1
  20. package/dist/esm/components/calendar-base.js +1 -1
  21. package/dist/esm/components/canvas/legend.js +4 -4
  22. package/dist/esm/components/canvas/system-canvas.js +24 -1
  23. package/dist/esm/components/carousel.js +21 -3
  24. package/dist/esm/components/charts.js +21 -13
  25. package/dist/esm/components/combobox.js +3 -3
  26. package/dist/esm/components/command.js +5 -5
  27. package/dist/esm/components/data-classes.js +23 -8
  28. package/dist/esm/components/data.js +1 -5
  29. package/dist/esm/components/date-picker.js +1 -0
  30. package/dist/esm/components/date-range-picker.js +1 -0
  31. package/dist/esm/components/display.js +7 -7
  32. package/dist/esm/components/feedback.js +1 -1
  33. package/dist/esm/components/file-dropzone.js +44 -2
  34. package/dist/esm/components/filters.js +3 -1
  35. package/dist/esm/components/flow.js +16 -15
  36. package/dist/esm/components/forms-classes.js +1 -1
  37. package/dist/esm/components/forms.js +30 -6
  38. package/dist/esm/components/hooks.js +20 -17
  39. package/dist/esm/components/inbox.js +13 -8
  40. package/dist/esm/components/layout-vars.js +10 -7
  41. package/dist/esm/components/menu.js +11 -4
  42. package/dist/esm/components/multi-select.js +9 -6
  43. package/dist/esm/components/nav-classes.js +9 -0
  44. package/dist/esm/components/nav.js +2 -1
  45. package/dist/esm/components/overlay-core.js +31 -10
  46. package/dist/esm/components/overlay-dialog.js +17 -2
  47. package/dist/esm/components/pagination.js +4 -1
  48. package/dist/esm/components/popover.js +15 -9
  49. package/dist/esm/components/primitives-classes.js +4 -4
  50. package/dist/esm/components/primitives.js +2 -2
  51. package/dist/esm/components/progress.js +2 -0
  52. package/dist/esm/components/radio-group.js +1 -1
  53. package/dist/esm/components/resource-classes.js +41 -19
  54. package/dist/esm/components/resource.js +8 -6
  55. package/dist/esm/components/settings.js +9 -3
  56. package/dist/esm/components/slider.js +1 -0
  57. package/dist/esm/components/strings.js +9 -1
  58. package/dist/esm/components/tabs.js +3 -2
  59. package/dist/esm/components/tag-input.js +15 -7
  60. package/dist/esm/components/time-field-classes.js +5 -2
  61. package/dist/esm/components/time-field.js +15 -7
  62. package/dist/esm/components/toast-store.js +16 -4
  63. package/dist/esm/components/tooltip.js +1 -1
  64. package/dist/esm/components/url-state.js +3 -1
  65. package/dist/esm/components/virtual-table.js +8 -2
  66. package/dist/esm/components/virtual.js +16 -2
  67. package/dist/esm/format.js +41 -16
  68. package/dist/esm/runtime.js +9 -2
  69. package/dist/esm/server/inbox/client.js +1 -1
  70. package/dist/esm/split-layout.js +2 -1
  71. package/dist/esm/theme.js +66 -6
  72. package/dist/format.js +50 -19
  73. package/dist/inbox-client.d.ts +5 -1
  74. package/dist/inbox-client.js +1 -2
  75. package/dist/index.d.ts +39 -11
  76. package/dist/nish-components.css +52 -3
  77. package/dist/nish-components.min.css +1 -1
  78. package/dist/node/th-check.js +12 -3
  79. package/dist/server/hono.d.ts +2 -2
  80. package/dist/server/hono.js +111 -8
  81. package/dist/server/index.d.ts +20 -12
  82. package/dist/server/index.js +136 -32
  83. package/dist/{spa-BLlMc0eI.d.ts → spa-BfRDo38r.d.ts} +35 -6
  84. package/dist/split-layout.js +2 -2
  85. package/dist/system-canvas.d.ts +0 -4
  86. package/dist/theme.d.ts +20 -2
  87. package/dist/theme.global.js +75 -10
  88. package/dist/theme.js +75 -9
  89. package/package.json +1 -1
@@ -43,11 +43,11 @@ function isCrossSiteWrite(method, header, opts = {}) {
43
43
 
44
44
  // src/server/inbox/action.ts
45
45
  import { createHash, randomBytes, timingSafeEqual } from "crypto";
46
- var INBOX_ACTION_PATH = "/api/inbox/action";
46
+
47
+ // src/server/direct-call.ts
47
48
  var LOOPBACK_PEERS = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
48
49
  var FORBIDDEN_HEADERS = ["forwarded", "via", "x-real-ip", "true-client-ip", "cdn-loop", "origin"];
49
50
  var FORBIDDEN_PREFIXES = ["x-forwarded-", "cf-"];
50
- var ACTION_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
51
51
  function headerNames(headers) {
52
52
  if (typeof headers.forEach === "function" && typeof headers.get === "function") {
53
53
  const names = [];
@@ -63,7 +63,7 @@ function headerValue(headers, name) {
63
63
  }
64
64
  return void 0;
65
65
  }
66
- function isInboxCall(req) {
66
+ function isDirectCall(req) {
67
67
  if (!req.remoteAddress || !LOOPBACK_PEERS.has(req.remoteAddress)) return false;
68
68
  if (headerValue(req.headers, "host") !== `127.0.0.1:${req.port}`) return false;
69
69
  for (const name of headerNames(req.headers)) {
@@ -71,7 +71,29 @@ function isInboxCall(req) {
71
71
  if (FORBIDDEN_PREFIXES.some((p) => name.startsWith(p))) return false;
72
72
  if (name.startsWith("sec-fetch-") && !(name === "sec-fetch-mode" && headerValue(req.headers, name) === "cors")) return false;
73
73
  }
74
- return headerValue(req.headers, "x-inbox-action") === "1";
74
+ return true;
75
+ }
76
+
77
+ // src/server/inbox/action.ts
78
+ var INBOX_ACTION_PATH = "/api/inbox/action";
79
+ var ACTION_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
80
+ function inboxHeader(headers) {
81
+ if (typeof headers.get === "function") return headers.get("x-inbox-action") ?? void 0;
82
+ for (const [k, v] of Object.entries(headers)) {
83
+ if (k.toLowerCase() === "x-inbox-action") return Array.isArray(v) ? v[0] : v;
84
+ }
85
+ return void 0;
86
+ }
87
+ function isInboxCall(req) {
88
+ return isDirectCall(req) && inboxHeader(req.headers) === "1";
89
+ }
90
+ function validDedupeKey(k) {
91
+ if (typeof k !== "string" || k.length < 1 || k.length > 200) return false;
92
+ for (let i = 0; i < k.length; i++) {
93
+ const c = k.charCodeAt(i);
94
+ if (c < 32 || c === 127) return false;
95
+ }
96
+ return true;
75
97
  }
76
98
  function parseInboxActionCall(body, source) {
77
99
  if (typeof body !== "object" || body === null || Array.isArray(body)) return null;
@@ -80,7 +102,7 @@ function parseInboxActionCall(body, source) {
80
102
  if (typeof b.actionId !== "string" || !ACTION_ID_RE.test(b.actionId)) return null;
81
103
  if (b.source !== source) return null;
82
104
  if (typeof b.kind !== "string") return null;
83
- if (b.dedupeKey !== null && typeof b.dedupeKey !== "string") return null;
105
+ if (b.dedupeKey !== null && !validDedupeKey(b.dedupeKey)) return null;
84
106
  const data = b.data;
85
107
  if (typeof data !== "object" || data === null || Array.isArray(data)) return null;
86
108
  return {
@@ -115,6 +137,7 @@ function passwordMatches(expected, provided, opts = {}) {
115
137
  }
116
138
 
117
139
  // src/server/spa.ts
140
+ import { createHash as createHash3 } from "crypto";
118
141
  import { readFile, stat } from "fs/promises";
119
142
  import { resolve, sep } from "path";
120
143
  var SECURITY_HEADERS = {
@@ -152,6 +175,35 @@ async function isFile(path) {
152
175
  return false;
153
176
  }
154
177
  }
178
+ function checkSources(list) {
179
+ const out = list ?? [];
180
+ for (const v of out) {
181
+ if (/[;,\r\n]/.test(v)) throw new Error(`@nish/ui/server: bad csp source: ${v}`);
182
+ }
183
+ return out;
184
+ }
185
+ function inlineScriptHashes(html) {
186
+ const lower = html.toLowerCase();
187
+ const hashes = /* @__PURE__ */ new Set();
188
+ let i = lower.indexOf("<script");
189
+ while (i >= 0) {
190
+ const tagEnd = lower.indexOf(">", i);
191
+ if (tagEnd < 0) break;
192
+ const next = lower.charAt(i + 7);
193
+ const isTag = next === ">" || next === "/" || /\s/.test(next);
194
+ const close = lower.indexOf("</script", tagEnd + 1);
195
+ if (isTag) {
196
+ const attrs = lower.slice(i + 7, tagEnd);
197
+ if (!/(?:^|[\s"'/])src\s*=/.test(attrs) && close >= 0) {
198
+ const content = html.slice(tagEnd + 1, close);
199
+ if (content.length > 0) hashes.add(`'sha256-${createHash3("sha256").update(content, "utf8").digest("base64")}'`);
200
+ }
201
+ }
202
+ if (close < 0) break;
203
+ i = lower.indexOf("<script", close);
204
+ }
205
+ return [...hashes];
206
+ }
155
207
  function createSpaHandler(o) {
156
208
  const dir = resolve(o.dir);
157
209
  const indexName = o.index ?? "index.html";
@@ -161,10 +213,42 @@ function createSpaHandler(o) {
161
213
  const indexPath = resolve(dir, indexName);
162
214
  const safety = { ...SECURITY_HEADERS };
163
215
  if (o.frameOptions !== false) safety["X-Frame-Options"] = "SAMEORIGIN";
216
+ const cspOpt = o.csp === "strict" ? {} : o.csp;
217
+ const cspConnect = checkSources(cspOpt?.connect);
218
+ const cspImg = checkSources(cspOpt?.img);
219
+ const cspScript = checkSources(cspOpt?.script);
220
+ const cspFrame = checkSources(cspOpt?.frameAncestors);
221
+ const cspHeader = cspOpt?.reportOnly ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy";
222
+ const policies = /* @__PURE__ */ new Map();
223
+ const buildPolicy = (html) => [
224
+ "default-src 'self'",
225
+ ["script-src", "'self'", ...inlineScriptHashes(html), ...cspScript].join(" "),
226
+ "style-src 'self' 'unsafe-inline'",
227
+ ["img-src", "'self'", "data:", ...cspImg].join(" "),
228
+ ["connect-src", "'self'", ...cspConnect].join(" "),
229
+ "font-src 'self'",
230
+ "object-src 'none'",
231
+ "base-uri 'none'",
232
+ "form-action 'self'",
233
+ ["frame-ancestors", ...cspFrame.length ? cspFrame : ["'self'"]].join(" ")
234
+ ].join("; ");
164
235
  const text = (body, status) => new Response(body, { status, headers: { "Content-Type": "text/plain; charset=utf-8", ...safety } });
165
236
  const send = async (file, cache, head) => {
237
+ const type = contentType(file);
238
+ const headers = { "Content-Type": type, "Cache-Control": cache, ...safety };
239
+ if (cspOpt && type.startsWith("text/html")) {
240
+ const mtimeMs = (await stat(file)).mtimeMs;
241
+ const html = await readFile(file);
242
+ let hit = policies.get(file);
243
+ if (!hit || hit.mtimeMs !== mtimeMs) {
244
+ hit = { mtimeMs, policy: buildPolicy(html.toString("utf8")) };
245
+ policies.set(file, hit);
246
+ }
247
+ headers[cspHeader] = hit.policy;
248
+ return new Response(head ? null : html, { status: 200, headers });
249
+ }
166
250
  const body = head ? null : await readFile(file);
167
- return new Response(body, { status: 200, headers: { "Content-Type": contentType(file), "Cache-Control": cache, ...safety } });
251
+ return new Response(body, { status: 200, headers });
168
252
  };
169
253
  return async (req) => {
170
254
  const head = req.method === "HEAD";
@@ -202,6 +286,24 @@ function remoteAddressOf(c) {
202
286
  function clientIpOf(c, trust = "none") {
203
287
  return clientIp((name) => c.req.header(name), remoteAddressOf(c), { trust });
204
288
  }
289
+ function limiterBucket(address) {
290
+ let a = address.trim().toLowerCase();
291
+ const zone = a.indexOf("%");
292
+ if (zone >= 0) a = a.slice(0, zone);
293
+ const mapped = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(a);
294
+ if (mapped) return mapped[1];
295
+ if (!a.includes(":") || !/^[0-9a-f:.]+$/.test(a) || a.includes(":::")) return address;
296
+ const halves = a.split("::");
297
+ if (halves.length > 2) return address;
298
+ const head = halves[0] === "" ? [] : halves[0].split(":");
299
+ const tail = halves.length === 2 && halves[1] !== "" ? halves[1].split(":") : [];
300
+ const groups = (list) => list.reduce((n, g) => n + (g.includes(".") ? 2 : 1), 0);
301
+ const missing = 8 - groups(head) - groups(tail);
302
+ if (halves.length === 2 ? missing < 1 : missing !== 0) return address;
303
+ const full = [...head, ...Array(halves.length === 2 ? missing : 0).fill("0"), ...tail];
304
+ if (full.slice(0, 4).some((g) => !/^[0-9a-f]{1,4}$/.test(g))) return address;
305
+ return full.slice(0, 4).map((g) => g.replace(/^0+(?=.)/, "")).join(":") + "::/64";
306
+ }
205
307
  var NO_ADDRESS_KEY = "no-address";
206
308
  function isAuthed(c, auth) {
207
309
  return auth.isAuthed(c.req.header("cookie"));
@@ -224,7 +326,8 @@ function loginHandler(o) {
224
326
  const wrong = o.messages?.wrong ?? "That password is not right.";
225
327
  const errorBody = o.errorBody ?? ((_kind, message) => ({ error: message }));
226
328
  return async (c) => {
227
- const key = clientIpOf(c, o.trustProxy) ?? NO_ADDRESS_KEY;
329
+ const ip = clientIpOf(c, o.trustProxy);
330
+ const key = ip === null ? NO_ADDRESS_KEY : limiterBucket(ip);
228
331
  if (!o.limiter.hit(key)) return c.json(errorBody("tooMany", tooMany), 429);
229
332
  let body = {};
230
333
  try {
@@ -288,7 +391,7 @@ function mountInboxAction(app, o) {
288
391
  const call = parseInboxActionCall(body, o.source);
289
392
  if (!call) return c.json({ error: `Not an inbox action from ${o.source}.` }, 400);
290
393
  if (!await o.verify(call)) {
291
- o.log(`inbox action ${call.actionId} on ${call.dedupeKey}: refused (no current action token)`);
394
+ o.log(`inbox action ${call.actionId}: refused (no current action token)`);
292
395
  return c.json(refused, 401);
293
396
  }
294
397
  const result = await o.run(call);
@@ -1,5 +1,5 @@
1
- import { c as InboxEventInput, d as InboxIngestAction, e as InboxEvent, f as InboxAction, I as InboxActionCall, a as InboxData } from '../spa-BLlMc0eI.js';
2
- export { g as ClientIpOptions, C as CrossSiteOptions, h as INBOX_ACTION_HEADER, i as INBOX_ACTION_TIMEOUT_MS, j as INBOX_DEFAULT_SETTINGS, k as INBOX_SOURCE_LABELS, l as InboxActionResult, m as InboxItem, n as InboxListResponse, o as InboxSettings, p as InboxSeverity, q as InboxView, L as Limiter, r as MIN_SECRET_BYTES, M as ManagedServiceTokens, R as RevocationStore, s as RevokedToken, t as SESSION_DAYS, u as ServiceTokenEntry, v as ServiceTokenView, w as ServiceTokens, S as SessionAuth, b as SpaOptions, T as TrustProxy, V as VerifyOptions, x as VerifyResult, y as checkServiceRequest, z as clientIp, A as createLimiter, B as createServiceTokens, D as createSessionAuth, E as createSessionToken, F as createSpaHandler, G as hashServiceToken, H as isCrossSiteWrite, J as isDirectLoopback, K as isLoopback, N as jsonRevocationStore, O as loadManagedServiceTokens, P as loadServiceTokens, Q as mintServiceToken, U as passwordMatches, W as readCookie, X as verifySessionToken } from '../spa-BLlMc0eI.js';
1
+ import { c as InboxEventInput, d as InboxIngestAction, e as InboxEvent, f as InboxAction, I as InboxActionCall, a as InboxData } from '../spa-BfRDo38r.js';
2
+ export { g as ClientIpOptions, C as CrossSiteOptions, h as INBOX_ACTION_HEADER, i as INBOX_ACTION_TIMEOUT_MS, j as INBOX_DEFAULT_SETTINGS, k as INBOX_SOURCE_LABELS, l as InboxActionResult, m as InboxItem, n as InboxListResponse, o as InboxSettings, p as InboxSeverity, q as InboxView, L as Limiter, r as MIN_SECRET_BYTES, M as ManagedServiceTokens, R as RevocationStore, s as RevokedToken, t as SESSION_DAYS, u as ServiceTokenEntry, v as ServiceTokenView, w as ServiceTokens, S as SessionAuth, b as SpaOptions, T as TrustProxy, V as VerifyOptions, x as VerifyResult, y as checkServiceRequest, z as clientIp, A as createLimiter, B as createServiceTokens, D as createSessionAuth, E as createSessionToken, F as createSpaHandler, G as hashServiceToken, H as isCrossSiteWrite, J as isDirectLoopback, K as isLoopback, N as jsonRevocationStore, O as loadManagedServiceTokens, P as loadServiceTokens, Q as mintServiceToken, U as passwordMatches, W as readCookie, X as verifySessionToken } from '../spa-BfRDo38r.js';
3
3
 
4
4
  /** Folder `up` levels above the directory of `importMetaUrl` (dist/server/env.js, up 2 = repo root). */
5
5
  declare function appRoot(importMetaUrl: string, up?: number): string;
@@ -50,6 +50,19 @@ declare function errorResponse(err: unknown, req: {
50
50
  };
51
51
  };
52
52
 
53
+ type HeaderBag = Headers | Record<string, string | string[] | undefined>;
54
+ /** The one shared "direct call to this app on this PC" check. True only when every rule holds:
55
+ * remoteAddress is 127.0.0.1, ::1 or ::ffff:127.0.0.1; header host === `127.0.0.1:${port}`;
56
+ * none of these headers is present: forwarded, via, x-real-ip, true-client-ip, cdn-loop, origin, and any name
57
+ * starting with x-forwarded- or cf-; no sec-fetch-* header (site, dest, user: browsers only) except
58
+ * sec-fetch-mode with the exact value 'cors', which Node's own fetch (undici) always sends.
59
+ * Header names compared lowercase; Headers and Node IncomingHttpHeaders both accepted. */
60
+ declare function isDirectCall(req: {
61
+ headers: HeaderBag;
62
+ remoteAddress: string | null | undefined;
63
+ port: number;
64
+ }): boolean;
65
+
53
66
  /** Whether `target` is an allowed action target: http://127.0.0.1 with an explicit port, no credentials,
54
67
  * no #hash, at most 2000 characters. The inbox service re-checks this before every call. */
55
68
  declare function isInboxActionTarget(target: unknown): target is string;
@@ -103,21 +116,16 @@ declare function createInboxClient(options: InboxClientOptions): InboxClient;
103
116
  declare const INBOX_ACTION_PATH = "/api/inbox/action";
104
117
  declare const ACTION_TOKEN_FIELD = "actionToken";
105
118
  declare const inboxActionTarget: (port: number, path?: string) => string;
106
- type HeaderBag = Headers | Record<string, string | string[] | undefined>;
107
- /** True only when every rule holds:
108
- * remoteAddress is 127.0.0.1, ::1 or ::ffff:127.0.0.1; header host === `127.0.0.1:${port}`;
109
- * none of these headers is present: forwarded, via, x-real-ip, true-client-ip, cdn-loop, origin, and any name
110
- * starting with x-forwarded- or cf-; no sec-fetch-* header (site, dest, user: browsers only) except
111
- * sec-fetch-mode with the exact value 'cors', which Node's own fetch (undici) always sends;
112
- * header x-inbox-action === '1'.
113
- * Header names compared lowercase; Headers and Node IncomingHttpHeaders both accepted. */
119
+
120
+ /** True only when isDirectCall holds (loopback peer, Host 127.0.0.1:port, no proxy/Origin/browser fetch-metadata
121
+ * headers; see isDirectCall for the full rules) and header x-inbox-action === '1'. */
114
122
  declare function isInboxCall(req: {
115
123
  headers: HeaderBag;
116
124
  remoteAddress: string | null | undefined;
117
125
  port: number;
118
126
  }): boolean;
119
127
  /** The body as an InboxActionCall for `source`, or null: itemId a positive safe integer, actionId
120
- * matching /^[a-z0-9][a-z0-9-]{0,31}$/, source === `source`, kind a string, dedupeKey string or null,
128
+ * matching /^[a-z0-9][a-z0-9-]{0,31}$/, source === `source`, kind a string, dedupeKey null or a string of 1..200 chars with no control characters (below 0x20 or 0x7f),
121
129
  * data a plain object. */
122
130
  declare function parseInboxActionCall(body: unknown, source: string): (InboxActionCall & {
123
131
  data: InboxData;
@@ -131,5 +139,5 @@ declare function actionTokenMatches(token: unknown, storedHash: string | null |
131
139
  /** An action button; throws Error(`not an inbox action target: ${target}`) when isInboxActionTarget fails. */
132
140
  declare function inboxAction(id: string, label: string, target: string): InboxAction;
133
141
 
134
- export { ACTION_TOKEN_FIELD, INBOX_ACTION_PATH, InboxAction, InboxActionCall, InboxData, InboxEvent, InboxEventInput, InboxIngestAction, actionTokenMatches, appRoot, createInboxClient, envNumber, errorResponse, hashActionToken, inboxAction, inboxActionTarget, installProcessHandlers, isInboxActionTarget, isInboxCall, loadAppEnv, newActionToken, parseInboxActionCall, parseInboxEvent };
142
+ export { ACTION_TOKEN_FIELD, INBOX_ACTION_PATH, InboxAction, InboxActionCall, InboxData, InboxEvent, InboxEventInput, InboxIngestAction, actionTokenMatches, appRoot, createInboxClient, envNumber, errorResponse, hashActionToken, inboxAction, inboxActionTarget, installProcessHandlers, isDirectCall, isInboxActionTarget, isInboxCall, loadAppEnv, newActionToken, parseInboxActionCall, parseInboxEvent };
135
143
  export type { HeaderBag, InboxClient, InboxClientOptions, InboxSendResult, ProcessHandlerOptions };
@@ -120,12 +120,17 @@ function createLimiter(o = {}) {
120
120
  const cap = o.cap ?? 1e4;
121
121
  const entries = /* @__PURE__ */ new Map();
122
122
  const makeRoom = (now) => {
123
+ if (cap <= 0) return false;
123
124
  if (entries.size < cap) return true;
124
125
  for (const [k, v] of entries) if (v.reset <= now) entries.delete(k);
125
126
  for (const [k, v] of entries) {
126
127
  if (entries.size < cap) break;
127
128
  if (v.count < max) entries.delete(k);
128
129
  }
130
+ for (const k of entries.keys()) {
131
+ if (entries.size < cap) break;
132
+ entries.delete(k);
133
+ }
129
134
  return entries.size < cap;
130
135
  };
131
136
  const touch = (key, now) => {
@@ -246,6 +251,7 @@ function errorResponse(err, req, log = (line) => console.error(line)) {
246
251
  }
247
252
 
248
253
  // src/server/spa.ts
254
+ import { createHash as createHash2 } from "crypto";
249
255
  import { readFile, stat } from "fs/promises";
250
256
  import { resolve as resolve2, sep } from "path";
251
257
  var SECURITY_HEADERS = {
@@ -283,6 +289,35 @@ async function isFile(path) {
283
289
  return false;
284
290
  }
285
291
  }
292
+ function checkSources(list) {
293
+ const out = list ?? [];
294
+ for (const v of out) {
295
+ if (/[;,\r\n]/.test(v)) throw new Error(`@nish/ui/server: bad csp source: ${v}`);
296
+ }
297
+ return out;
298
+ }
299
+ function inlineScriptHashes(html) {
300
+ const lower = html.toLowerCase();
301
+ const hashes = /* @__PURE__ */ new Set();
302
+ let i = lower.indexOf("<script");
303
+ while (i >= 0) {
304
+ const tagEnd = lower.indexOf(">", i);
305
+ if (tagEnd < 0) break;
306
+ const next = lower.charAt(i + 7);
307
+ const isTag = next === ">" || next === "/" || /\s/.test(next);
308
+ const close = lower.indexOf("</script", tagEnd + 1);
309
+ if (isTag) {
310
+ const attrs = lower.slice(i + 7, tagEnd);
311
+ if (!/(?:^|[\s"'/])src\s*=/.test(attrs) && close >= 0) {
312
+ const content = html.slice(tagEnd + 1, close);
313
+ if (content.length > 0) hashes.add(`'sha256-${createHash2("sha256").update(content, "utf8").digest("base64")}'`);
314
+ }
315
+ }
316
+ if (close < 0) break;
317
+ i = lower.indexOf("<script", close);
318
+ }
319
+ return [...hashes];
320
+ }
286
321
  function createSpaHandler(o) {
287
322
  const dir = resolve2(o.dir);
288
323
  const indexName = o.index ?? "index.html";
@@ -292,10 +327,42 @@ function createSpaHandler(o) {
292
327
  const indexPath = resolve2(dir, indexName);
293
328
  const safety = { ...SECURITY_HEADERS };
294
329
  if (o.frameOptions !== false) safety["X-Frame-Options"] = "SAMEORIGIN";
330
+ const cspOpt = o.csp === "strict" ? {} : o.csp;
331
+ const cspConnect = checkSources(cspOpt?.connect);
332
+ const cspImg = checkSources(cspOpt?.img);
333
+ const cspScript = checkSources(cspOpt?.script);
334
+ const cspFrame = checkSources(cspOpt?.frameAncestors);
335
+ const cspHeader = cspOpt?.reportOnly ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy";
336
+ const policies = /* @__PURE__ */ new Map();
337
+ const buildPolicy = (html) => [
338
+ "default-src 'self'",
339
+ ["script-src", "'self'", ...inlineScriptHashes(html), ...cspScript].join(" "),
340
+ "style-src 'self' 'unsafe-inline'",
341
+ ["img-src", "'self'", "data:", ...cspImg].join(" "),
342
+ ["connect-src", "'self'", ...cspConnect].join(" "),
343
+ "font-src 'self'",
344
+ "object-src 'none'",
345
+ "base-uri 'none'",
346
+ "form-action 'self'",
347
+ ["frame-ancestors", ...cspFrame.length ? cspFrame : ["'self'"]].join(" ")
348
+ ].join("; ");
295
349
  const text = (body, status) => new Response(body, { status, headers: { "Content-Type": "text/plain; charset=utf-8", ...safety } });
296
350
  const send = async (file, cache, head) => {
351
+ const type = contentType(file);
352
+ const headers = { "Content-Type": type, "Cache-Control": cache, ...safety };
353
+ if (cspOpt && type.startsWith("text/html")) {
354
+ const mtimeMs = (await stat(file)).mtimeMs;
355
+ const html = await readFile(file);
356
+ let hit = policies.get(file);
357
+ if (!hit || hit.mtimeMs !== mtimeMs) {
358
+ hit = { mtimeMs, policy: buildPolicy(html.toString("utf8")) };
359
+ policies.set(file, hit);
360
+ }
361
+ headers[cspHeader] = hit.policy;
362
+ return new Response(head ? null : html, { status: 200, headers });
363
+ }
297
364
  const body = head ? null : await readFile(file);
298
- return new Response(body, { status: 200, headers: { "Content-Type": contentType(file), "Cache-Control": cache, ...safety } });
365
+ return new Response(body, { status: 200, headers });
299
366
  };
300
367
  return async (req) => {
301
368
  const head = req.method === "HEAD";
@@ -324,6 +391,36 @@ function createSpaHandler(o) {
324
391
  };
325
392
  }
326
393
 
394
+ // src/server/direct-call.ts
395
+ var LOOPBACK_PEERS = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
396
+ var FORBIDDEN_HEADERS = ["forwarded", "via", "x-real-ip", "true-client-ip", "cdn-loop", "origin"];
397
+ var FORBIDDEN_PREFIXES = ["x-forwarded-", "cf-"];
398
+ function headerNames(headers) {
399
+ if (typeof headers.forEach === "function" && typeof headers.get === "function") {
400
+ const names = [];
401
+ headers.forEach((_v, k) => names.push(k.toLowerCase()));
402
+ return names;
403
+ }
404
+ return Object.entries(headers).filter(([, v]) => v !== void 0).map(([k]) => k.toLowerCase());
405
+ }
406
+ function headerValue(headers, name) {
407
+ if (typeof headers.get === "function") return headers.get(name) ?? void 0;
408
+ for (const [k, v] of Object.entries(headers)) {
409
+ if (k.toLowerCase() === name) return Array.isArray(v) ? v[0] : v;
410
+ }
411
+ return void 0;
412
+ }
413
+ function isDirectCall(req) {
414
+ if (!req.remoteAddress || !LOOPBACK_PEERS.has(req.remoteAddress)) return false;
415
+ if (headerValue(req.headers, "host") !== `127.0.0.1:${req.port}`) return false;
416
+ for (const name of headerNames(req.headers)) {
417
+ if (FORBIDDEN_HEADERS.includes(name)) return false;
418
+ if (FORBIDDEN_PREFIXES.some((p) => name.startsWith(p))) return false;
419
+ if (name.startsWith("sec-fetch-") && !(name === "sec-fetch-mode" && headerValue(req.headers, name) === "cors")) return false;
420
+ }
421
+ return true;
422
+ }
423
+
327
424
  // src/server/inbox/types.ts
328
425
  var INBOX_ACTION_HEADER = "X-Inbox-Action";
329
426
  var INBOX_ACTION_TIMEOUT_MS = 8e3;
@@ -609,7 +706,7 @@ function createInboxClient(options) {
609
706
  if (disabled) return { ok: false, error: "disabled", queued: false };
610
707
  if (queue.length > 0) {
611
708
  enqueue(parsed.value);
612
- void flush();
709
+ if (timer === null) void flush();
613
710
  return { ok: false, error: "queued behind earlier events", queued: true };
614
711
  }
615
712
  const result = await attempt(parsed.value);
@@ -636,39 +733,29 @@ function createInboxClient(options) {
636
733
  }
637
734
 
638
735
  // src/server/inbox/action.ts
639
- import { createHash as createHash2, randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual2 } from "crypto";
736
+ import { createHash as createHash3, randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual2 } from "crypto";
640
737
  var INBOX_ACTION_PATH = "/api/inbox/action";
641
738
  var ACTION_TOKEN_FIELD = "actionToken";
642
739
  var inboxActionTarget = (port, path) => `http://127.0.0.1:${port}${path ?? INBOX_ACTION_PATH}`;
643
- var LOOPBACK_PEERS = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
644
- var FORBIDDEN_HEADERS = ["forwarded", "via", "x-real-ip", "true-client-ip", "cdn-loop", "origin"];
645
- var FORBIDDEN_PREFIXES = ["x-forwarded-", "cf-"];
646
740
  var ACTION_ID_RE2 = /^[a-z0-9][a-z0-9-]{0,31}$/;
647
741
  var HASH_RE = /^[0-9a-f]{64}$/;
648
- function headerNames(headers) {
649
- if (typeof headers.forEach === "function" && typeof headers.get === "function") {
650
- const names = [];
651
- headers.forEach((_v, k) => names.push(k.toLowerCase()));
652
- return names;
653
- }
654
- return Object.entries(headers).filter(([, v]) => v !== void 0).map(([k]) => k.toLowerCase());
655
- }
656
- function headerValue(headers, name) {
657
- if (typeof headers.get === "function") return headers.get(name) ?? void 0;
742
+ function inboxHeader(headers) {
743
+ if (typeof headers.get === "function") return headers.get("x-inbox-action") ?? void 0;
658
744
  for (const [k, v] of Object.entries(headers)) {
659
- if (k.toLowerCase() === name) return Array.isArray(v) ? v[0] : v;
745
+ if (k.toLowerCase() === "x-inbox-action") return Array.isArray(v) ? v[0] : v;
660
746
  }
661
747
  return void 0;
662
748
  }
663
749
  function isInboxCall(req) {
664
- if (!req.remoteAddress || !LOOPBACK_PEERS.has(req.remoteAddress)) return false;
665
- if (headerValue(req.headers, "host") !== `127.0.0.1:${req.port}`) return false;
666
- for (const name of headerNames(req.headers)) {
667
- if (FORBIDDEN_HEADERS.includes(name)) return false;
668
- if (FORBIDDEN_PREFIXES.some((p) => name.startsWith(p))) return false;
669
- if (name.startsWith("sec-fetch-") && !(name === "sec-fetch-mode" && headerValue(req.headers, name) === "cors")) return false;
750
+ return isDirectCall(req) && inboxHeader(req.headers) === "1";
751
+ }
752
+ function validDedupeKey(k) {
753
+ if (typeof k !== "string" || k.length < 1 || k.length > 200) return false;
754
+ for (let i = 0; i < k.length; i++) {
755
+ const c = k.charCodeAt(i);
756
+ if (c < 32 || c === 127) return false;
670
757
  }
671
- return headerValue(req.headers, "x-inbox-action") === "1";
758
+ return true;
672
759
  }
673
760
  function parseInboxActionCall(body, source) {
674
761
  if (typeof body !== "object" || body === null || Array.isArray(body)) return null;
@@ -677,7 +764,7 @@ function parseInboxActionCall(body, source) {
677
764
  if (typeof b.actionId !== "string" || !ACTION_ID_RE2.test(b.actionId)) return null;
678
765
  if (b.source !== source) return null;
679
766
  if (typeof b.kind !== "string") return null;
680
- if (b.dedupeKey !== null && typeof b.dedupeKey !== "string") return null;
767
+ if (b.dedupeKey !== null && !validDedupeKey(b.dedupeKey)) return null;
681
768
  const data = b.data;
682
769
  if (typeof data !== "object" || data === null || Array.isArray(data)) return null;
683
770
  return {
@@ -693,7 +780,7 @@ function newActionToken() {
693
780
  return randomBytes2(32).toString("base64url");
694
781
  }
695
782
  function hashActionToken(token) {
696
- return createHash2("sha256").update(token, "utf8").digest("hex");
783
+ return createHash3("sha256").update(token, "utf8").digest("hex");
697
784
  }
698
785
  function actionTokenMatches(token, storedHash) {
699
786
  if (typeof token !== "string" || token.length < 1 || token.length > 128) return false;
@@ -706,12 +793,12 @@ function inboxAction(id, label, target) {
706
793
  }
707
794
 
708
795
  // src/server/service-tokens.ts
709
- import { createHash as createHash3, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual3 } from "crypto";
796
+ import { createHash as createHash4, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual3 } from "crypto";
710
797
  import { mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "fs";
711
798
  import { dirname as dirname2 } from "path";
712
799
  var TOKEN_RE = /^nish_[a-z][a-z0-9-]*_[A-Za-z0-9_-]{43}$/;
713
800
  var HEX_RE2 = /^[0-9a-f]{64}$/;
714
- var hashServiceToken = (token) => createHash3("sha256").update(token, "utf8").digest("hex");
801
+ var hashServiceToken = (token) => createHash4("sha256").update(token, "utf8").digest("hex");
715
802
  function mintServiceToken(app) {
716
803
  if (!/^[a-z][a-z0-9-]*$/.test(app)) throw new Error(`bad app name: ${app}`);
717
804
  const token = `nish_${app}_${randomBytes3(32).toString("base64url")}`;
@@ -779,16 +866,25 @@ function jsonRevocationStore(file) {
779
866
  if (err.code === "ENOENT") return [];
780
867
  throw err;
781
868
  }
782
- const setAside = (why) => {
869
+ const salvage = (source) => [...new Set((source.match(/[0-9a-fA-F]{64}/g) ?? []).map((h) => h.toLowerCase()))].map((sha256) => ({
870
+ sha256,
871
+ id: "unknown",
872
+ at: ""
873
+ }));
874
+ const setAside = (why, failIfNoHash = false) => {
875
+ const found = salvage(text);
876
+ if (failIfNoHash && found.length === 0 && text.trim() !== "") {
877
+ throw new Error(`[service-tokens] ${file}: ${why} and no revoked token hash could be read; fix or remove the file`);
878
+ }
783
879
  warn(why);
784
880
  renameSync(file, `${file}.bad-${Date.now()}`);
785
- return [];
881
+ return found;
786
882
  };
787
883
  let raw;
788
884
  try {
789
885
  raw = JSON.parse(text);
790
886
  } catch {
791
- return setAside("not valid JSON");
887
+ return setAside("not valid JSON", true);
792
888
  }
793
889
  const list = raw?.revoked;
794
890
  if (!raw || typeof raw !== "object" || !Array.isArray(list)) return setAside("unexpected shape");
@@ -798,7 +894,12 @@ function jsonRevocationStore(file) {
798
894
  out.push({ sha256: r.sha256, id: r.id, at: r.at });
799
895
  } else {
800
896
  warn("unexpected shape");
801
- kept.push(r);
897
+ const hash = r && typeof r === "object" && typeof r.sha256 === "string" ? salvage(r.sha256)[0] : void 0;
898
+ if (hash) {
899
+ out.push({ sha256: hash.sha256, id: typeof r.id === "string" ? r.id : "unknown", at: typeof r.at === "string" ? r.at : "" });
900
+ } else {
901
+ kept.push(r);
902
+ }
802
903
  }
803
904
  }
804
905
  return out;
@@ -874,8 +975,10 @@ function isDirectLoopback(get, port) {
874
975
  if (get("origin") !== void 0) return false;
875
976
  return PROXY_HEADERS.every((h) => get(h) === void 0);
876
977
  }
978
+ var LOOPBACK_PEERS2 = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
877
979
  function checkServiceRequest(get, o) {
878
980
  if (!isDirectLoopback(get, o.port)) return { status: 403, error: "Forbidden" };
981
+ if ("remoteAddress" in o && (!o.remoteAddress || !LOOPBACK_PEERS2.has(o.remoteAddress))) return { status: 403, error: "Forbidden" };
879
982
  const r = o.tokens.verify(get("authorization"), o.scope);
880
983
  if (!r.ok) return { status: r.status, error: r.status === 401 ? "Unauthorized" : "Forbidden" };
881
984
  return null;
@@ -933,6 +1036,7 @@ export {
933
1036
  inboxActionTarget,
934
1037
  installProcessHandlers,
935
1038
  isCrossSiteWrite,
1039
+ isDirectCall,
936
1040
  isDirectLoopback,
937
1041
  isInboxActionTarget,
938
1042
  isInboxCall,
@@ -103,7 +103,11 @@ interface InboxEventInput {
103
103
  resolve?: boolean;
104
104
  /** ISO 8601 time the event happened. Defaults to now; future times are clamped to now. */
105
105
  occurredAt?: string;
106
- /** Flat extra data, JSON-encoded at most 4096 bytes. */
106
+ /**
107
+ * Flat extra data, JSON-encoded at most 4096 bytes. Only data.actionToken (ACTION_TOKEN_FIELD) is private
108
+ * (stripped before the browser and /api/v1 see the item); every other key is visible in the inbox UI and API.
109
+ * /ingest trusts every local caller, so action routes must verify actionToken (actionTokenMatches) on every call.
110
+ */
107
111
  data?: InboxData;
108
112
  /** Up to 3 buttons shown on the item, ids unique. A repeat with the same dedupeKey replaces them. */
109
113
  actions?: Array<Omit<InboxAction, 'method'> & {
@@ -209,8 +213,9 @@ interface InboxListResponse {
209
213
  interface Limiter {
210
214
  /** Counts one attempt for key and says whether it may go ahead: true for the first `max`
211
215
  * attempts inside the current window, false after. Synchronous, so check it before any
212
- * `await` and parallel requests cannot all pass. A new key when the limiter is full of locked
213
- * keys gets false. */
216
+ * `await` and parallel requests cannot all pass. When the table is full, expired keys go first,
217
+ * then the oldest unlocked keys, then the oldest locked keys, so a flood of locked keys can
218
+ * never lock out a new client. */
214
219
  hit(key: string, now?: number): boolean;
215
220
  /** False once `max` failures happened inside the current window for key. */
216
221
  allowed(key: string, now?: number): boolean;
@@ -280,8 +285,9 @@ interface RevocationStore {
280
285
  save(list: RevokedToken[]): void;
281
286
  }
282
287
  /** JSON file store: missing file = []; any other read error throws (fail closed); invalid JSON or
283
- * shape = warn once, file renamed to `<file>.bad-<timestamp>`, [] (if that rename fails it throws);
284
- * invalid records are kept and written back unchanged on save.
288
+ * shape = warn once, file renamed to `<file>.bad-<timestamp>`, and every 64-hex hash found in it stays
289
+ * revoked (a corrupt, unparseable file with none to find, or a failed rename, throws and the file stays);
290
+ * invalid records without a readable hash are kept and written back unchanged on save.
285
291
  * save writes `<file>.tmp` then renames, creating the directory. File shape:
286
292
  * { "version": 1, "revoked": RevokedToken[] }. */
287
293
  declare function jsonRevocationStore(file: string): RevocationStore;
@@ -302,13 +308,18 @@ declare function createServiceTokens(entries: ServiceTokenEntry[]): ServiceToken
302
308
  /**
303
309
  * True only for a request made straight to the app on loopback: Host is 127.0.0.1, localhost or
304
310
  * [::1] with the app's port, there are no proxy headers and no Origin (browsers never get in).
311
+ * @deprecated Checks only headers; prefer isDirectCall, which also checks the socket peer.
305
312
  */
306
313
  declare function isDirectLoopback(get: (name: string) => string | undefined, port: number): boolean;
307
- /** Framework-free check: the status and body a guard should answer with, or null to continue. */
314
+ /** Framework-free check: the status and body a guard should answer with, or null to continue.
315
+ * Apps should pass `remoteAddress`, the socket peer (hono: `remoteAddressOf(c)`): when the property is present
316
+ * the request is also refused with 403 unless the peer is 127.0.0.1, ::1 or ::ffff:127.0.0.1 (null or empty is
317
+ * refused). Omitting it keeps the old header-only check. */
308
318
  declare function checkServiceRequest(get: (name: string) => string | undefined, o: {
309
319
  tokens: ServiceTokens;
310
320
  scope: string;
311
321
  port: number;
322
+ remoteAddress?: string | null;
312
323
  }): {
313
324
  status: 401 | 403;
314
325
  error: string;
@@ -367,7 +378,25 @@ interface SpaOptions {
367
378
  notBuilt?: string;
368
379
  /** Sends `X-Frame-Options: SAMEORIGIN` unless false (for an app that is meant to be framed). */
369
380
  frameOptions?: false;
381
+ /** Sends a Content-Security-Policy on HTML answers. Off by default. 'strict' or an object builds
382
+ * default-src 'self'; script-src 'self' <sha256 of every inline <script> in the HTML>; style-src 'self' 'unsafe-inline'; img-src 'self' data: <img>; connect-src 'self' <connect>; font-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self' (or <frameAncestors>).
383
+ * reportOnly sends Content-Security-Policy-Report-Only instead, to try a policy first. */
384
+ csp?: 'strict' | {
385
+ connect?: string[];
386
+ img?: string[];
387
+ script?: string[];
388
+ frameAncestors?: string[];
389
+ reportOnly?: boolean;
390
+ };
370
391
  }
392
+ /**
393
+ * Serves a built single-page app: files under `dir`, the index for any other extensionless path.
394
+ *
395
+ * `csp` adds a Content-Security-Policy to HTML answers only. Every inline script in the HTML being
396
+ * served is hashed automatically, so the theme-init script that nishThemeInit() injects into the
397
+ * built index.html is allowed without copying its hash. An app that uses the nonce placeholder
398
+ * setup (`__NISH_CSP_NONCE__`) should leave `csp` off and send its own header.
399
+ */
371
400
  declare function createSpaHandler(o: SpaOptions): (req: Request) => Promise<Response>;
372
401
 
373
402
  export { createLimiter as A, createServiceTokens as B, createSessionAuth as D, createSessionToken as E, createSpaHandler as F, hashServiceToken as G, isCrossSiteWrite as H, isDirectLoopback as J, isLoopback as K, jsonRevocationStore as N, loadManagedServiceTokens as O, loadServiceTokens as P, mintServiceToken as Q, passwordMatches as U, readCookie as W, verifySessionToken as X, INBOX_ACTION_HEADER as h, INBOX_ACTION_TIMEOUT_MS as i, INBOX_DEFAULT_SETTINGS as j, INBOX_SOURCE_LABELS as k, MIN_SECRET_BYTES as r, SESSION_DAYS as t, checkServiceRequest as y, clientIp as z };
@@ -361,7 +361,8 @@ function swapSlots(slots, a, b) {
361
361
  function narrowLayout(count, n, aspect) {
362
362
  if (count === 1) return leaf(0);
363
363
  const dir = n.dir === "auto" ? aspect >= 1.2 ? "row" : "col" : n.dir;
364
- const split = Math.min(0.8, Math.max(0.2, n.split));
364
+ const s = Number.isFinite(n.split) ? n.split : 0.5;
365
+ const split = Math.min(0.8, Math.max(0.2, s));
365
366
  return {
366
367
  type: "split",
367
368
  dir,
@@ -417,4 +418,3 @@ export {
417
418
  resizeAt,
418
419
  swapSlots
419
420
  };
420
- //# sourceMappingURL=split-layout.js.map