@t3b/hub-guard 0.11.0 → 0.13.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.
package/README.md CHANGED
@@ -269,6 +269,26 @@ const lines = guard.appMenu(session);
269
269
  - A session opened before 0.8.0 (or by an older Hub) has no list: the button then holds the Hub line only.
270
270
  - `appMenu(session, { hubUrl, moduleId })` is the same without a Guard; `readApps(raw)` reads a list defensively.
271
271
 
272
+ ## The top bar: one door, `/hub/bar` (0.12.0, WORKFLOWS §24)
273
+
274
+ Every app draws the same top bar - `<t3b-topbar>` from `@t3b/hub-ui` 0.4.0 - and the bar reads everything it shows
275
+ from one door on the app. Answer it where you answer `/hub/signout`, after `check` let the request through:
276
+
277
+ ```ts
278
+ const r = await guard.check(req);
279
+ if (!r.allow) return r.response;
280
+ if (url.pathname === BAR_PATH && req.method === "GET") return guard.barResponse(r.session, r.setCookie);
281
+ if (url.pathname === SIGNOUT_PATH && req.method === "POST") return guard.signOut();
282
+ // { person: { name, role, initial }, apps: AppMenuItem[] (with `icon`), memos, hub, signOut: "/hub/signout", stale }
283
+ ```
284
+
285
+ - `check` asks the Hub **at once** for `/hub/bar` and for every page the person opens (the browser's navigation, or a
286
+ Next.js page move); anything else at least **every minute** (was 15). A person who signed out anywhere is refused
287
+ on the next page, and the bar closes an open tab when it comes back into view.
288
+ - `signOut()` clears this app's cookie and goes to the Hub's `/sign-out`, which ends the Hub and every other app.
289
+ - `appMenu` lines carry the `icon` the Hub set for each app (`APP_ICONS`; the Hub's line a house; the grid when none).
290
+ - The adoption steps per app: `docs/S24-TOPBAR-ADOPTION.md` in t3b-hub.
291
+
272
292
  ## Memos: the bell and the window (0.10.0, WORKFLOWS §22)
273
293
 
274
294
  HR holds the memos; the Hub carries them. Your app shows a bell on its top bar and one page, `/memos`, that every
@@ -298,16 +318,42 @@ const r2 = await guard.memoAct(session, "reply", id, { text, lang: "ar" });
298
318
  Hub's pass - person, app and action named, bound to the exact bytes - and `memosRefusal(reason)` answers a refusal;
299
319
  name the door in the manifest as `memos` and in `healthResponse(..., { memos })`.
300
320
 
321
+ ## A sale from another app: `verifySaleCall` (0.13.0, WORKFLOWS §25)
322
+
323
+ For the till (Beez POS) only. Another app (Beez AI) sells through the Hub; the Hub asks the till's `sales` door (named in
324
+ its manifest) with its own pass. Read the body as raw bytes first:
325
+
326
+ ```ts
327
+ const bytes = req.method === "POST" ? new Uint8Array(await req.arrayBuffer()) : null;
328
+ const c = await verifySaleCall(req, bytes, { moduleId: "beez-pos", keys: hubKeys(hubUrl), environment });
329
+ if (!c.ok) return saleRefusal(c.reason);
330
+ // c.from = the selling app ("beez-ai"), c.saleId = its sale id, c.jti = a one-use number
331
+ ```
332
+
333
+ - Keep `c.jti` once; a second time is a replay.
334
+ - On a POST, the body's `id` must equal `c.saleId`; on a GET, the id in your path must. Never make two sales for one id:
335
+ the same id again answers with the first sale (the Hub tells the app to retry that way after a silence).
336
+ - A new sale's pass (bound to a body) used for a read, or another kind of Hub token, is `wrong_use`.
337
+
301
338
  ## What it enforces
302
339
 
303
340
  - `/hub/enter?ticket=…`: an EdDSA ticket signed by the Hub's published key, for this module, from this environment's Hub, 60 seconds, single use - spent at the Hub, so once across all servers (0.9.0) → sets the module session (HttpOnly, Secure, SameSite=Strict) and answers a short "Opening …" page that moves on to the page (0.4.0: a SameSite=Strict cookie set on a redirect ending a navigation from another site is not sent on it). `appName` names the app on that page; `landing(path)` maps the pass's page (e.g. `"/"` → `"/app"`), never off the module's own address.
304
- - Every other request: no session → 403 (HTML for browsers, JSON for APIs), on **every host** the module answers on. Idle 180 minutes (0.5.0), absolute 8 hours. Every 15 minutes the Hub is asked (with the app's Vercel ID) whether the person's session still stands, and refreshes their pages, apps and stores (0.9.0). A Hub blip keeps the session until the next check; after **180 minutes** without an answer (`maxStaleMs`) the module still opens and reads, but every change waits - a POST/PUT/PATCH/DELETE answers 503 `hub_unreachable` and `allows(…, "write")` / `pageAllowed` say no (0.9.0).
341
+ - Every other request: no session → 403 (HTML for browsers, JSON for APIs), on **every host** the module answers on. Idle 180 minutes (0.5.0), absolute 8 hours. On every page the person opens, and at least every minute (0.12.0; was every 15 minutes), the Hub is asked (with the app's Vercel ID) whether the person's session still stands, and refreshes their pages, apps and stores (0.9.0). A Hub blip keeps the session until the next check; after **180 minutes** without an answer (`maxStaleMs`) the module still opens and reads, but every change waits - a POST/PUT/PATCH/DELETE answers 503 `hub_unreachable` and `allows(…, "write")` / `pageAllowed` say no (0.9.0).
305
342
  - Open paths (`/hub/enter`, `/api/hub/manifest`, `/api/hub/health`, `/api/hub/activity` and what you add) never need a session — they carry their own locks (the Hub's pass, a cron secret).
306
343
  - Cloudflare Access proof checked first when the team and audience are set.
307
344
  - `verifyRelay`, `manifestResponse`, `healthResponse`, `activityResponse`, `verifyStationCall`: the Hub's pass, for this module, for this purpose, from this environment's Hub; a relay and a station pack also for these exact bytes; a relay at most 5 minutes old; a call at most 60 seconds old.
308
345
 
309
346
  ## Changes
310
347
 
348
+ - **0.12.0** (WORKFLOWS §24, D-092; owner 2026-10-25: *"each one is built differently"*, then *"Yes to section 24 as
349
+ drawn: ship it inside hub-guard 0.12.0 together with HR's features (one release)"*) - **published 2026-10-25 on his
350
+ later word (D-094), without HR's features; HR's leave line goes into 0.13.0.** The top bar's door: `guard.bar(session)`, `guard.barResponse(session,
351
+ setCookie)`, `BAR_PATH`, `SIGNOUT_PATH`, the `BarData` type. A page the person opens (`isPageLoad`) and `/hub/bar`
352
+ ask the Hub at once (`PAGE_RECHECK_MS`, 5 seconds); anything else every minute (`RECHECK_MS` 60 s, was 15 minutes).
353
+ `signOut()` goes to the Hub's `/sign-out` (was the Hub's home - the Hub stayed signed in, B-058). `appMenu` lines
354
+ carry `icon` (`APP_ICONS`, `isAppIcon`; the Hub's line `house`, else the grid). The guard's own pages (the refusal,
355
+ "No access", "Changes paused") carry `GUARD_PAGE_CSP` and `X-Content-Type-Options: nosniff`, the JSON answers nosniff
356
+ (O-3), and draw as one centred card at any width.
311
357
  - **0.11.0** (HR WORKFLOWS §3, the Hub's §22.8; owner 2026-10-11: *"give me powerful tools"*): a memo may carry
312
358
  **formatted text, pictures and files**. `cleanMemoDoc` is the one rule for what a memo's document may hold (paragraphs,
313
359
  two heading sizes, bulleted and numbered lists, quotes, pictures by file id; bold, italic, underline, highlight, red,
package/dist/apps.d.ts CHANGED
@@ -1,8 +1,13 @@
1
- /** One app the person may open, as the Hub sends it. */
1
+ /** §24: the icons the shared top bar can draw for an app (`@t3b/hub-ui` js/topbar.js draws exactly these). */
2
+ export declare const APP_ICONS: readonly ["house", "grid", "receipt", "truck", "globe", "sync", "users", "book", "megaphone", "sparkles", "package", "store", "fileText", "history", "send", "currency"];
3
+ export type AppIcon = (typeof APP_ICONS)[number];
4
+ export declare function isAppIcon(x: unknown): x is AppIcon;
5
+ /** One app the person may open, as the Hub sends it. `icon`: from a Hub of §24 on. */
2
6
  export type HubApp = {
3
7
  id: string;
4
8
  nameEn: string;
5
9
  nameAr: string;
10
+ icon?: AppIcon;
6
11
  };
7
12
  /** One line of the Apps button. `current`: this is the app the person is in. */
8
13
  export type AppMenuItem = {
@@ -11,14 +16,15 @@ export type AppMenuItem = {
11
16
  nameAr: string;
12
17
  href: string;
13
18
  current: boolean;
19
+ icon: AppIcon;
14
20
  };
15
21
  export declare const APP_ID_RE: RegExp;
16
- /** A pass's or check's `apps`, read defensively: anything malformed is dropped, never widened. */
22
+ /** A pass's or check's `apps`, read defensively: anything malformed is dropped, never widened; an unknown icon is left out. */
17
23
  export declare function readApps(raw: unknown): HubApp[];
18
24
  /**
19
- * The Apps button's lines for this person, in order: the Hub first (its Home), then every app they may open; the app
20
- * they are in is marked `current`. A session from a Hub before 0.8.0 carries no list - the button then holds the Hub
21
- * only, which is the way back as before.
25
+ * The Apps button's lines for this person, in order: the Hub first (its Home, a house), then every app they may open
26
+ * with its icon (the grid when the Hub sent none); the app they are in is marked `current`. A session from a Hub before
27
+ * 0.8.0 carries no list - the button then holds the Hub only, which is the way back as before.
22
28
  */
23
29
  export declare function appMenu(session: {
24
30
  apps?: HubApp[];
package/dist/apps.js CHANGED
@@ -1,10 +1,16 @@
1
- // WORKFLOWS §18 (0.8.0, D-069): the Apps button. The Hub's pass and its 15-minute check carry the apps this person may
2
- // open (the same list as the Hub's sidebar); every app shows them in one button in its top bar, with the Hub first and
3
- // the current app marked. A pick goes to `<hub>/go/<app>`, where the Hub mints that app's pass and goes straight on.
1
+ // WORKFLOWS §18 (0.8.0, D-069): the Apps button. The Hub's pass and its check carry the apps this person may open (the
2
+ // same list as the Hub's sidebar); every app shows them in one button in its top bar, with the Hub first and the
3
+ // current app marked. A pick goes to `<hub>/go/<app>`, where the Hub mints that app's pass and goes straight on.
4
+ // §24 (0.12.0): each app carries the icon the Hub set for it; the top bar draws only icons from this closed list.
5
+ /** §24: the icons the shared top bar can draw for an app (`@t3b/hub-ui` js/topbar.js draws exactly these). */
6
+ export const APP_ICONS = ["house", "grid", "receipt", "truck", "globe", "sync", "users", "book", "megaphone", "sparkles", "package", "store", "fileText", "history", "send", "currency"];
7
+ export function isAppIcon(x) {
8
+ return typeof x === "string" && APP_ICONS.includes(x);
9
+ }
4
10
  export const APP_ID_RE = /^[a-z][a-z0-9-]{1,30}$/;
5
11
  const MAX_APPS = 30;
6
12
  const MAX_NAME = 60;
7
- /** A pass's or check's `apps`, read defensively: anything malformed is dropped, never widened. */
13
+ /** A pass's or check's `apps`, read defensively: anything malformed is dropped, never widened; an unknown icon is left out. */
8
14
  export function readApps(raw) {
9
15
  if (!Array.isArray(raw))
10
16
  return [];
@@ -13,25 +19,25 @@ export function readApps(raw) {
13
19
  for (const a of raw.slice(0, MAX_APPS)) {
14
20
  if (!a || typeof a !== "object")
15
21
  continue;
16
- const { id, nameEn, nameAr } = a;
22
+ const { id, nameEn, nameAr, icon } = a;
17
23
  if (typeof id !== "string" || !APP_ID_RE.test(id) || seen.has(id))
18
24
  continue;
19
25
  const en = typeof nameEn === "string" && nameEn.trim() ? nameEn.trim().slice(0, MAX_NAME) : id;
20
26
  const ar = typeof nameAr === "string" && nameAr.trim() ? nameAr.trim().slice(0, MAX_NAME) : en;
21
27
  seen.add(id);
22
- out.push({ id, nameEn: en, nameAr: ar });
28
+ out.push(isAppIcon(icon) ? { id, nameEn: en, nameAr: ar, icon } : { id, nameEn: en, nameAr: ar });
23
29
  }
24
30
  return out;
25
31
  }
26
32
  /**
27
- * The Apps button's lines for this person, in order: the Hub first (its Home), then every app they may open; the app
28
- * they are in is marked `current`. A session from a Hub before 0.8.0 carries no list - the button then holds the Hub
29
- * only, which is the way back as before.
33
+ * The Apps button's lines for this person, in order: the Hub first (its Home, a house), then every app they may open
34
+ * with its icon (the grid when the Hub sent none); the app they are in is marked `current`. A session from a Hub before
35
+ * 0.8.0 carries no list - the button then holds the Hub only, which is the way back as before.
30
36
  */
31
37
  export function appMenu(session, cfg) {
32
38
  const hub = cfg.hubUrl.replace(/\/$/, "");
33
39
  return [
34
- { id: "hub", nameEn: "The Hub", nameAr: "الـHub", href: `${hub}/home`, current: false },
35
- ...(session.apps ?? []).map((a) => ({ id: a.id, nameEn: a.nameEn, nameAr: a.nameAr, href: `${hub}/go/${a.id}`, current: a.id === cfg.moduleId })),
40
+ { id: "hub", nameEn: "The Hub", nameAr: "الـHub", href: `${hub}/home`, current: false, icon: "house" },
41
+ ...(session.apps ?? []).map((a) => ({ id: a.id, nameEn: a.nameEn, nameAr: a.nameAr, href: `${hub}/go/${a.id}`, current: a.id === cfg.moduleId, icon: a.icon ?? "grid" })),
36
42
  ];
37
43
  }
package/dist/guard.d.ts CHANGED
@@ -35,6 +35,34 @@ export type GuardConfig = {
35
35
  fetchImpl?: typeof fetch;
36
36
  now?: () => Date;
37
37
  };
38
+ /** §24 (0.12.0): the shared top bar's door on every app - its data, and the check that ends an open tab after a sign-out. */
39
+ export declare const BAR_PATH = "/hub/bar";
40
+ /** The app's sign-out door (POST): clears the app's own cookie, then the Hub's /sign-out ends everything (§24). */
41
+ export declare const SIGNOUT_PATH = "/hub/signout";
42
+ /**
43
+ * O-3 (0.12.0): the guard's own pages - the refusal, "No access", "Changes paused" - load nothing and run nothing: their
44
+ * one inline style is all they need. The JSON answers carry nosniff too.
45
+ */
46
+ export declare const GUARD_PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'";
47
+ /**
48
+ * §24 (0.12.0): a page the person opens - the browser's own navigation (Sec-Fetch-Dest: document; or, from an older
49
+ * browser, a GET that asks for HTML), or a Next.js page move (RSC: 1). Such a request asks the Hub at once.
50
+ */
51
+ export declare function isPageLoad(req: Request): boolean;
52
+ /** §24 (0.12.0): what the shared top bar draws, from the session - nothing the app types in itself. */
53
+ export type BarData = {
54
+ person: {
55
+ name: string;
56
+ role: string;
57
+ initial: string;
58
+ };
59
+ apps: AppMenuItem[];
60
+ memos: number;
61
+ hub: string;
62
+ signOut: string;
63
+ /** the Hub has not answered for a while (H08): the bar still draws, changes wait */
64
+ stale: boolean;
65
+ };
38
66
  export type CheckResult = {
39
67
  allow: true;
40
68
  session: ModuleSession;
@@ -88,8 +116,18 @@ export declare class Guard {
88
116
  text?: string;
89
117
  lang?: MemoLang;
90
118
  }): Promise<MemoActResult>;
91
- /** Signs out of the module only (the Hub session is untouched). */
119
+ /**
120
+ * §24 (0.12.0): Sign out - this app's own cookie is cleared, then the Hub's /sign-out ends the person everywhere: the
121
+ * Hub and every other open app (was: this app only, and back to the Hub's home).
122
+ */
92
123
  signOut(): Response;
124
+ /** §24 (0.12.0): the top bar's data for this session - the person, the Apps lines with their icons, the bell's number. */
125
+ bar(session: ModuleSession): BarData;
126
+ /**
127
+ * §24 (0.12.0): the answer at /hub/bar (GET), once `check` let the request through - `check` asked the Hub at once for
128
+ * this path, so a person who signed out anywhere gets the refusal (403) there and the bar closes the page.
129
+ */
130
+ barResponse(session: ModuleSession, setCookie?: string): Response;
93
131
  }
94
132
  /** 0.4.0: the step between the Hub's pass and the module's page (see `enter`). No script: a meta refresh and a link. */
95
133
  export declare function openingPage(target: string, appName: string): string;
package/dist/guard.js CHANGED
@@ -4,9 +4,44 @@ import { sessionCheckPages, spendTicket } from "./hub-client.js";
4
4
  import { memoAct, memoBell, memoData } from "./memos.js";
5
5
  import { pageAllowed } from "./pages.js";
6
6
  import { hubKeys } from "./identity.js";
7
- import { clearCookieHeader, cookieHeader, cookieValue, readSession, signSession, MAX_STALE_MS, RECHECK_MS, SESSION_COOKIE } from "./session.js";
7
+ import { clearCookieHeader, cookieHeader, cookieValue, readSession, signSession, MAX_STALE_MS, PAGE_RECHECK_MS, RECHECK_MS, SESSION_COOKIE } from "./session.js";
8
8
  import { JtiMemory, verifyTicket } from "./ticket.js";
9
9
  import { hmacSha256, toHex } from "./webcrypto.js";
10
+ /** §24 (0.12.0): the shared top bar's door on every app - its data, and the check that ends an open tab after a sign-out. */
11
+ export const BAR_PATH = "/hub/bar";
12
+ /** The app's sign-out door (POST): clears the app's own cookie, then the Hub's /sign-out ends everything (§24). */
13
+ export const SIGNOUT_PATH = "/hub/signout";
14
+ /**
15
+ * O-3 (0.12.0): the guard's own pages - the refusal, "No access", "Changes paused" - load nothing and run nothing: their
16
+ * one inline style is all they need. The JSON answers carry nosniff too.
17
+ */
18
+ export const GUARD_PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'";
19
+ function htmlHeaders(extra = {}) {
20
+ return { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "Content-Security-Policy": GUARD_PAGE_CSP, "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", ...extra };
21
+ }
22
+ function jsonHeaders(extra = {}) {
23
+ return { "Content-Type": "application/json", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", ...extra };
24
+ }
25
+ /** The guard's plain card page, centred at any width (0.12.0: the refusal drew off-centre in one browser, 2026-10-25). */
26
+ function cardPage(title, heading, text, link) {
27
+ const a = link ? `<a href="${escapeAttr(link.href)}">${escapeHtml(link.label)}</a>` : "";
28
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(title)}</title><style>*,*::before,*::after{box-sizing:border-box}html,body{margin:0;min-height:100%}body{font-family:system-ui,-apple-system,sans-serif;background:#F6F5F3;color:#231F20;display:grid;place-items:center;min-height:100vh;min-height:100dvh;padding:16px}.card{inline-size:min(440px,100%);background:#fff;border:1px solid #E7E5E2;border-radius:12px;padding:40px 32px;text-align:center}h1{font-size:22px;margin:0 0 12px}p{color:#3C3733;line-height:1.5;margin:0 0 24px}p:last-child{margin:0}a{display:inline-block;background:#231F20;color:#fff;text-decoration:none;padding:14px 26px;border-radius:12px;font-size:13px;letter-spacing:.08em;text-transform:uppercase;font-weight:600}</style></head><body><main class="card"><h1>${escapeHtml(heading)}</h1><p>${escapeHtml(text)}</p>${a}</main></body></html>`;
29
+ }
30
+ /**
31
+ * §24 (0.12.0): a page the person opens - the browser's own navigation (Sec-Fetch-Dest: document; or, from an older
32
+ * browser, a GET that asks for HTML), or a Next.js page move (RSC: 1). Such a request asks the Hub at once.
33
+ */
34
+ export function isPageLoad(req) {
35
+ const method = req.method.toUpperCase();
36
+ if (method !== "GET" && method !== "HEAD")
37
+ return false;
38
+ if (req.headers.get("rsc") === "1")
39
+ return true;
40
+ const dest = req.headers.get("sec-fetch-dest");
41
+ if (dest)
42
+ return dest === "document";
43
+ return (req.headers.get("accept") ?? "").includes("text/html");
44
+ }
10
45
  export class Guard {
11
46
  cfg;
12
47
  jti = new JtiMemory();
@@ -37,10 +72,10 @@ export class Guard {
37
72
  const accept = req.headers.get("accept") ?? "";
38
73
  const home = this.cfg.hubHomeUrl ?? this.cfg.hubUrl;
39
74
  if (!accept.includes("text/html")) {
40
- return new Response(JSON.stringify({ error: "open_from_hub", reason }), { status, headers: { "Content-Type": "application/json", "Cache-Control": "no-store", "Set-Cookie": clearCookieHeader() } });
75
+ return new Response(JSON.stringify({ error: "open_from_hub", reason }), { status, headers: jsonHeaders({ "Set-Cookie": clearCookieHeader() }) });
41
76
  }
42
- const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Open this from The3Beez</title><style>body{margin:0;font-family:system-ui,-apple-system,sans-serif;background:#F6F5F3;color:#231F20;display:flex;align-items:center;justify-content:center;min-height:100vh}.card{background:#fff;border:1px solid #E7E5E2;border-radius:12px;padding:40px;max-width:440px;text-align:center}h1{font-size:22px;margin:0 0 12px}p{color:#6B6866;line-height:1.5;margin:0 0 24px}a{display:inline-block;background:#231F20;color:#fff;text-decoration:none;padding:14px 26px;border-radius:12px;font-size:13px;letter-spacing:.08em;text-transform:uppercase;font-weight:600}</style></head><body><div class="card"><h1>Open this from The3Beez</h1><p>This app opens only from the Hub. ${escapeHtml(reason)}</p><a href="${escapeAttr(home)}">Go to the Hub</a></div></body></html>`;
43
- return new Response(html, { status, headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "Set-Cookie": clearCookieHeader() } });
77
+ const html = cardPage("Open this from The3Beez", "Open this from The3Beez", `This app opens only from the Hub. ${reason}`.trim(), { href: home, label: "Go to the Hub" });
78
+ return new Response(html, { status, headers: htmlHeaders({ "Set-Cookie": clearCookieHeader() }) });
44
79
  }
45
80
  /**
46
81
  * /hub/enter?ticket=… : verify, open the module session, then a short "Opening …" page that moves on
@@ -102,10 +137,12 @@ export class Guard {
102
137
  return { allow: false, response: this.refuse(req, words[r.reason] ?? "") };
103
138
  }
104
139
  let s = r.session;
105
- if (nowMs - s.checkedAt >= RECHECK_MS) {
140
+ // §24 (0.12.0): a page the person opens, and the top bar's check, ask the Hub at once; anything else once a minute
141
+ const ask = isPageLoad(req) || url.pathname === BAR_PATH ? PAGE_RECHECK_MS : RECHECK_MS;
142
+ if (nowMs - s.checkedAt >= ask) {
106
143
  const r2 = await sessionCheckPages(this.hubClient(), s.personId, s.sv);
107
144
  if (r2.verdict === "refused")
108
- return { allow: false, response: this.refuse(req, "The Hub ended this session (signed out everywhere, or access changed).") };
145
+ return { allow: false, response: this.refuse(req, "You signed out, or the Hub ended this session.") };
109
146
  // §14: a change of ticks reaches the module here, within 15 minutes - §18: and so does the Apps button's list -
110
147
  // H07: and so does a store taken away (or given) - §22.2: and the bell's number
111
148
  if (r2.verdict === "ok")
@@ -124,10 +161,9 @@ export class Guard {
124
161
  const reason = "The Hub has not answered for a while, so changes are paused. You can still look; try again when the Hub is back.";
125
162
  const accept = req.headers.get("accept") ?? "";
126
163
  if (!accept.includes("text/html")) {
127
- return new Response(JSON.stringify({ error: "hub_unreachable", reason }), { status: 503, headers: { "Content-Type": "application/json", "Cache-Control": "no-store", "Retry-After": "60" } });
164
+ return new Response(JSON.stringify({ error: "hub_unreachable", reason }), { status: 503, headers: jsonHeaders({ "Retry-After": "60" }) });
128
165
  }
129
- const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Changes paused</title></head><body style="font-family:system-ui,sans-serif;display:grid;place-items:center;min-height:100vh;margin:0"><p style="max-width:440px;text-align:center">${escapeHtml(reason)}</p></body></html>`;
130
- return new Response(html, { status: 503, headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "Retry-After": "60" } });
166
+ return new Response(cardPage("Changes paused", "Changes paused", reason), { status: 503, headers: htmlHeaders({ "Retry-After": "60" }) });
131
167
  }
132
168
  /**
133
169
  * §14: may this person read (`"read"`) or change (`"write"`) this page? The owner may do everything.
@@ -140,11 +176,11 @@ export class Guard {
140
176
  refusePage(req, what = "this page") {
141
177
  const accept = req.headers.get("accept") ?? "";
142
178
  if (!accept.includes("text/html")) {
143
- return new Response(JSON.stringify({ error: "no_access", page: what }), { status: 403, headers: { "Content-Type": "application/json", "Cache-Control": "no-store" } });
179
+ return new Response(JSON.stringify({ error: "no_access", page: what }), { status: 403, headers: jsonHeaders() });
144
180
  }
145
181
  const home = this.cfg.hubHomeUrl ?? this.cfg.hubUrl;
146
- const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>No access</title><style>body{margin:0;font-family:system-ui,-apple-system,sans-serif;background:#F6F5F3;color:#231F20;display:flex;align-items:center;justify-content:center;min-height:100vh}.card{background:#fff;border:1px solid #E7E5E2;border-radius:12px;padding:40px;max-width:440px;text-align:center}h1{font-size:22px;margin:0 0 12px}p{color:#6B6866;line-height:1.5;margin:0 0 24px}a{display:inline-block;background:#231F20;color:#fff;text-decoration:none;padding:14px 26px;border-radius:12px;font-size:13px;letter-spacing:.08em;text-transform:uppercase;font-weight:600}</style></head><body><div class="card"><h1>You don't have access to ${escapeHtml(what)}</h1><p>The owner gives access in the Hub: Settings → Staff.</p><a href="${escapeAttr(home)}">Go to the Hub</a></div></body></html>`;
147
- return new Response(html, { status: 403, headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" } });
182
+ const html = cardPage("No access", `You don't have access to ${what}`, "The owner gives access in the Hub: Settings → Staff.", { href: home, label: "Go to the Hub" });
183
+ return new Response(html, { status: 403, headers: htmlHeaders() });
148
184
  }
149
185
  /** §18 (0.8.0): the Apps button's lines for this session - the Hub first, then every app this person may open. */
150
186
  appMenu(session) {
@@ -162,9 +198,31 @@ export class Guard {
162
198
  memoAct(session, action, memoId, opts = {}) {
163
199
  return memoAct(this.hubClient(), session, action, memoId, opts);
164
200
  }
165
- /** Signs out of the module only (the Hub session is untouched). */
201
+ /**
202
+ * §24 (0.12.0): Sign out - this app's own cookie is cleared, then the Hub's /sign-out ends the person everywhere: the
203
+ * Hub and every other open app (was: this app only, and back to the Hub's home).
204
+ */
166
205
  signOut() {
167
- return new Response(null, { status: 303, headers: { Location: this.cfg.hubHomeUrl ?? this.cfg.hubUrl, "Set-Cookie": clearCookieHeader() } });
206
+ return new Response(null, { status: 303, headers: { Location: `${this.cfg.hubUrl.replace(/\/$/, "")}/sign-out`, "Set-Cookie": clearCookieHeader(), "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" } });
207
+ }
208
+ /** §24 (0.12.0): the top bar's data for this session - the person, the Apps lines with their icons, the bell's number. */
209
+ bar(session) {
210
+ const name = (session.name || "").trim();
211
+ return {
212
+ person: { name, role: session.role, initial: (Array.from(name)[0] ?? "·").toUpperCase() },
213
+ apps: this.appMenu(session),
214
+ memos: typeof session.memos === "number" ? session.memos : 0,
215
+ hub: this.cfg.hubUrl.replace(/\/$/, ""),
216
+ signOut: SIGNOUT_PATH,
217
+ stale: session.stale === true,
218
+ };
219
+ }
220
+ /**
221
+ * §24 (0.12.0): the answer at /hub/bar (GET), once `check` let the request through - `check` asked the Hub at once for
222
+ * this path, so a person who signed out anywhere gets the refusal (403) there and the bar closes the page.
223
+ */
224
+ barResponse(session, setCookie) {
225
+ return new Response(JSON.stringify(this.bar(session)), { status: 200, headers: jsonHeaders(setCookie ? { "Set-Cookie": setCookie } : {}) });
168
226
  }
169
227
  }
170
228
  /** 0.4.0: the step between the Hub's pass and the module's page (see `enter`). No script: a meta refresh and a link. */
package/dist/index.d.ts CHANGED
@@ -1,14 +1,15 @@
1
- export { Guard, openingPage, type GuardConfig, type CheckResult } from "./guard.js";
2
- export { appMenu, readApps, APP_ID_RE, type AppMenuItem, type HubApp } from "./apps.js";
1
+ export { Guard, openingPage, isPageLoad, BAR_PATH, SIGNOUT_PATH, GUARD_PAGE_CSP, type GuardConfig, type CheckResult, type BarData } from "./guard.js";
2
+ export { appMenu, readApps, isAppIcon, APP_ID_RE, APP_ICONS, type AppMenuItem, type HubApp, type AppIcon } from "./apps.js";
3
3
  export { pageAllowed, pageAccess, pagesFingerprint, readPages, PAGE_KEY_RE, type PageAccess, type PageDef, type Pages } from "./pages.js";
4
4
  export { verifyTicket, JtiMemory, readMemoCount, TICKET_ISSUER, TICKET_TTL_S, TICKET_ALG, type TicketClaims, type VerifyResult } from "./ticket.js";
5
5
  export { memoBell, memoData, memoAct, memoFragment, memoText, memoWhen, readMemo, readMemos, verifyMemosCall, memosRefusal, MEMO_TEXTS, MEMO_ID_RE, REPLY_MAX, MEMO_TEXT_MAX, type MemoLang, type MemoTextKey, type MemoView, type MemoReply, type MemoBell, type MemoData, type MemoActResult, type MemoFragmentOptions, type MemosCallCheck, } from "./memos.js";
6
6
  export { cleanMemoDoc, memoDocHtml, memoDocText, memoDocImages, memoDocIsRich, readMemoFile, readMemoFiles, escHtml, MEMO_DOC_LIMITS, MEMO_LINK_RE, MEMO_FILE_URL_RE, type MemoDoc, type MemoBlock, type MemoInline, type MemoListItem, type MemoMark, type MemoFile, type MemoAlign, type MemoDir, } from "./memo-doc.js";
7
- export { readSession, signSession, cookieHeader, clearCookieHeader, cookieValue, SESSION_COOKIE, IDLE_MS, ABSOLUTE_MS, RECHECK_MS, MAX_STALE_MS, type ModuleSession } from "./session.js";
7
+ export { readSession, signSession, cookieHeader, clearCookieHeader, cookieValue, SESSION_COOKIE, IDLE_MS, ABSOLUTE_MS, RECHECK_MS, PAGE_RECHECK_MS, MAX_STALE_MS, type ModuleSession } from "./session.js";
8
8
  export { sessionCheck, sessionCheckPages, spendTicket, memosCall, tokenBroker, audit, alert, verifyHubCall, manifestResponse, healthResponse, healthAnswer, activityResponse, readActivityQuery, cleanActivityLine, ACTIVITY_AT_RE, ACTIVITY_ID_RE, ACTIVITY_MAX_LIMIT, type ActivityLine, type ActivityQuery, type HubClientConfig, type HubCallCheck, type AnswerConfig, type BrokerToken, type Connection, } from "./hub-client.js";
9
9
  export { checkCloudflareAccess } from "./cf-access.js";
10
10
  export { verifyRelay, RELAY_HEADERS, RELAY_MAX_AGE_S, type RelayCheck } from "./relay.js";
11
11
  export { verifyStationCall, stationRefusal, stationJson, STATION_ID_RE, STATION_NAME_MAX, type StationCheck, type StationAnswer, type StationOrder, type StationItem, type PackAnswer, } from "./station.js";
12
+ export { verifySaleCall, saleRefusal, SALE_ID_RE, type SaleCheck } from "./sale.js";
12
13
  export { ownVercelToken, ownEnvironment, hubKeys, APP_ID_HEADER, OIDC_HEADER, type TokenProvider } from "./identity.js";
13
14
  /**
14
15
  * Reads the guard's settings from a module's environment. Nothing secret: the Hub's address
package/dist/index.js CHANGED
@@ -1,14 +1,16 @@
1
- export { Guard, openingPage } from "./guard.js";
2
- export { appMenu, readApps, APP_ID_RE } from "./apps.js";
1
+ export { Guard, openingPage, isPageLoad, BAR_PATH, SIGNOUT_PATH, GUARD_PAGE_CSP } from "./guard.js";
2
+ export { appMenu, readApps, isAppIcon, APP_ID_RE, APP_ICONS } from "./apps.js";
3
3
  export { pageAllowed, pageAccess, pagesFingerprint, readPages, PAGE_KEY_RE } from "./pages.js";
4
4
  export { verifyTicket, JtiMemory, readMemoCount, TICKET_ISSUER, TICKET_TTL_S, TICKET_ALG } from "./ticket.js";
5
5
  export { memoBell, memoData, memoAct, memoFragment, memoText, memoWhen, readMemo, readMemos, verifyMemosCall, memosRefusal, MEMO_TEXTS, MEMO_ID_RE, REPLY_MAX, MEMO_TEXT_MAX, } from "./memos.js";
6
6
  export { cleanMemoDoc, memoDocHtml, memoDocText, memoDocImages, memoDocIsRich, readMemoFile, readMemoFiles, escHtml, MEMO_DOC_LIMITS, MEMO_LINK_RE, MEMO_FILE_URL_RE, } from "./memo-doc.js";
7
- export { readSession, signSession, cookieHeader, clearCookieHeader, cookieValue, SESSION_COOKIE, IDLE_MS, ABSOLUTE_MS, RECHECK_MS, MAX_STALE_MS } from "./session.js";
7
+ export { readSession, signSession, cookieHeader, clearCookieHeader, cookieValue, SESSION_COOKIE, IDLE_MS, ABSOLUTE_MS, RECHECK_MS, PAGE_RECHECK_MS, MAX_STALE_MS } from "./session.js";
8
8
  export { sessionCheck, sessionCheckPages, spendTicket, memosCall, tokenBroker, audit, alert, verifyHubCall, manifestResponse, healthResponse, healthAnswer, activityResponse, readActivityQuery, cleanActivityLine, ACTIVITY_AT_RE, ACTIVITY_ID_RE, ACTIVITY_MAX_LIMIT, } from "./hub-client.js";
9
9
  export { checkCloudflareAccess } from "./cf-access.js";
10
10
  export { verifyRelay, RELAY_HEADERS, RELAY_MAX_AGE_S } from "./relay.js";
11
11
  export { verifyStationCall, stationRefusal, stationJson, STATION_ID_RE, STATION_NAME_MAX, } from "./station.js";
12
+ // §25 (0.13.0): a sale from another app (Beez AI), passed to the till by the Hub
13
+ export { verifySaleCall, saleRefusal, SALE_ID_RE } from "./sale.js";
12
14
  export { ownVercelToken, ownEnvironment, hubKeys, APP_ID_HEADER, OIDC_HEADER } from "./identity.js";
13
15
  /**
14
16
  * Reads the guard's settings from a module's environment. Nothing secret: the Hub's address
package/dist/sale.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { type JWTVerifyGetKey } from "jose";
2
+ /** The calling app's own sale id: the same for every retry of one sale. */
3
+ export declare const SALE_ID_RE: RegExp;
4
+ export type SaleCheck = {
5
+ ok: true;
6
+ from: string;
7
+ saleId: string;
8
+ jti: string;
9
+ } | {
10
+ ok: false;
11
+ reason: "missing" | "bad_signature" | "expired" | "wrong_module" | "wrong_use" | "wrong_environment" | "body_changed";
12
+ };
13
+ /**
14
+ * Is this the Hub passing a sale from another app? `body` is the request's raw bytes for a POST (read it with
15
+ * `await req.arrayBuffer()` before parsing - the pass covers the exact bytes) and null for a GET. On a GET the till also
16
+ * checks that the sale id in its own path equals `saleId`; on a POST, that the body's `id` does. Keep `jti` once.
17
+ */
18
+ export declare function verifySaleCall(req: Request, body: Uint8Array | string | null, opts: {
19
+ moduleId: string;
20
+ keys: JWTVerifyGetKey;
21
+ now?: Date;
22
+ environment?: string;
23
+ }): Promise<SaleCheck>;
24
+ /** The refusal the till's sales door answers with: 401 and only the reason word (the Hub passes it back by name). */
25
+ export declare function saleRefusal(reason: Extract<SaleCheck, {
26
+ ok: false;
27
+ }>["reason"]): Response;
package/dist/sale.js ADDED
@@ -0,0 +1,63 @@
1
+ import { jwtVerify } from "jose";
2
+ import { APP_ID_RE } from "./apps.js";
3
+ import { HUB_ISSUER, TYP } from "./identity.js";
4
+ import { b64urlEncode, constantTimeEqual, sha256 } from "./webcrypto.js";
5
+ // WORKFLOWS §25 (D-095): a sale from another app (Beez AI) reaches the till only through the Hub. The Hub has checked the
6
+ // calling app's Vercel ID, that the owner accepted its "sell through Beez POS" door and that his switch is on; then it asks
7
+ // the till's sales door with its own 60-second pass for "sale", naming the calling app, the sale id and a one-use number
8
+ // (`jti`). On a new sale (POST) the pass also carries the SHA-256 of the exact body, so it cannot be lifted onto another
9
+ // sale. The till keeps each one-use number once, and never makes two sales for one sale id.
10
+ /** The calling app's own sale id: the same for every retry of one sale. */
11
+ export const SALE_ID_RE = /^[A-Za-z0-9_-]{8,64}$/;
12
+ /**
13
+ * Is this the Hub passing a sale from another app? `body` is the request's raw bytes for a POST (read it with
14
+ * `await req.arrayBuffer()` before parsing - the pass covers the exact bytes) and null for a GET. On a GET the till also
15
+ * checks that the sale id in its own path equals `saleId`; on a POST, that the body's `id` does. Keep `jti` once.
16
+ */
17
+ export async function verifySaleCall(req, body, opts) {
18
+ const auth = req.headers.get("authorization") ?? "";
19
+ const token = auth.startsWith("Bearer ") ? auth.slice(7).trim() : "";
20
+ if (!token || token.length > 4096)
21
+ return { ok: false, reason: "missing" };
22
+ let p;
23
+ try {
24
+ ({ payload: p } = await jwtVerify(token, opts.keys, { issuer: HUB_ISSUER, audience: opts.moduleId, algorithms: ["EdDSA"], typ: TYP.call, currentDate: opts.now, clockTolerance: 5, maxTokenAge: 65 }));
25
+ }
26
+ catch (e) {
27
+ const code = e.code ?? "";
28
+ if (code === "ERR_JWT_EXPIRED")
29
+ return { ok: false, reason: "expired" };
30
+ if (code === "ERR_JWT_CLAIM_VALIDATION_FAILED" && /"aud"/.test(e.message))
31
+ return { ok: false, reason: "wrong_module" };
32
+ // another kind of Hub token (a ticket, a relayed event) is named as such, not as a clock problem
33
+ if (code === "ERR_JWT_CLAIM_VALIDATION_FAILED" && /"typ"/.test(e.message))
34
+ return { ok: false, reason: "wrong_use" };
35
+ if (code === "ERR_JWT_CLAIM_VALIDATION_FAILED")
36
+ return { ok: false, reason: "expired" };
37
+ return { ok: false, reason: "bad_signature" };
38
+ }
39
+ if (p.use !== "sale")
40
+ return { ok: false, reason: "wrong_use" };
41
+ if (opts.environment && p.env !== opts.environment)
42
+ return { ok: false, reason: "wrong_environment" };
43
+ const from = typeof p.from === "string" ? p.from : "";
44
+ const saleId = typeof p.sale_id === "string" ? p.sale_id : "";
45
+ const jti = typeof p.jti === "string" ? p.jti : "";
46
+ if (!APP_ID_RE.test(from) || !SALE_ID_RE.test(saleId) || !/^[A-Za-z0-9_-]{16,64}$/.test(jti))
47
+ return { ok: false, reason: "bad_signature" };
48
+ if (body !== null) {
49
+ const want = typeof p.body_sha256 === "string" ? p.body_sha256 : "";
50
+ const bytes = typeof body === "string" ? new TextEncoder().encode(body) : body;
51
+ if (!want || !constantTimeEqual(b64urlEncode(await sha256(bytes)), want))
52
+ return { ok: false, reason: "body_changed" };
53
+ }
54
+ else if (p.body_sha256 !== undefined) {
55
+ // a new sale's pass (bound to a body) is never good for a read
56
+ return { ok: false, reason: "wrong_use" };
57
+ }
58
+ return { ok: true, from, saleId, jti };
59
+ }
60
+ /** The refusal the till's sales door answers with: 401 and only the reason word (the Hub passes it back by name). */
61
+ export function saleRefusal(reason) {
62
+ return new Response(JSON.stringify({ error: "hub_only", reason }), { status: 401, headers: { "Content-Type": "application/json", "Cache-Control": "no-store" } });
63
+ }
package/dist/session.d.ts CHANGED
@@ -3,7 +3,14 @@ import type { Pages } from "./pages.js";
3
3
  export declare const SESSION_COOKIE = "t3b_module_session";
4
4
  export declare const IDLE_MS: number;
5
5
  export declare const ABSOLUTE_MS: number;
6
- export declare const RECHECK_MS: number;
6
+ /** §24 (0.12.0): any request re-asks the Hub once the last answer is a minute old (was 15 minutes). */
7
+ export declare const RECHECK_MS = 60000;
8
+ /**
9
+ * §24 (0.12.0): a page the person opens (and the top bar's own check, /hub/bar) asks the Hub at once - a sign-out
10
+ * anywhere ends the app on its next page, not 15 minutes later. Answers younger than this are reused, so a page that
11
+ * loads in several requests asks once.
12
+ */
13
+ export declare const PAGE_RECHECK_MS = 5000;
7
14
  /**
8
15
  * H08 (0.9.0): how long a module keeps allowing changes while the Hub does not answer its check - the same 180 minutes
9
16
  * as the idle rule. Past it the module still opens and reads, but every change waits until the Hub answers again (a
package/dist/session.js CHANGED
@@ -2,11 +2,18 @@ import { b64urlDecodeText, b64urlEncode, constantTimeEqual, hmacSha256, utf8 } f
2
2
  // The module's own session (WORKFLOWS 2.2, 2.4): set at /hub/enter from a verified ticket,
3
3
  // carried in an HttpOnly cookie signed with a key derived from the module key, 180 minutes idle (0.5.0, A-509),
4
4
  // 8 hours absolute for admin surfaces (a module may set shift-long for a till), re-checked with
5
- // the Hub every 15 minutes.
5
+ // the Hub on every page the person opens and at least every minute (§24, 0.12.0; was every 15 minutes).
6
6
  export const SESSION_COOKIE = "t3b_module_session";
7
7
  export const IDLE_MS = 180 * 60_000;
8
8
  export const ABSOLUTE_MS = 8 * 3_600_000;
9
- export const RECHECK_MS = 15 * 60_000;
9
+ /** §24 (0.12.0): any request re-asks the Hub once the last answer is a minute old (was 15 minutes). */
10
+ export const RECHECK_MS = 60_000;
11
+ /**
12
+ * §24 (0.12.0): a page the person opens (and the top bar's own check, /hub/bar) asks the Hub at once - a sign-out
13
+ * anywhere ends the app on its next page, not 15 minutes later. Answers younger than this are reused, so a page that
14
+ * loads in several requests asks once.
15
+ */
16
+ export const PAGE_RECHECK_MS = 5_000;
10
17
  /**
11
18
  * H08 (0.9.0): how long a module keeps allowing changes while the Hub does not answer its check - the same 180 minutes
12
19
  * as the idle rule. Past it the module still opens and reads, but every change waits until the Hub answers again (a
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@t3b/hub-guard",
3
- "version": "0.11.0",
4
- "description": "The3Beez Hub guard: a module opens only by a Hub-signed ticket and refuses everything else. No key from the Hub: towards the Hub the app shows its own Vercel ID; from the Hub it accepts only what is signed by the key the Hub publishes. Entry route, refusal page, module session, idle rule, 15-minute re-check, Cloudflare Access proof, broker and audit clients, manifest and health answers for the Hub only, the memo bell and window (0.10.0). Web Crypto only: runs in Node 20+ and in edge runtimes.",
3
+ "version": "0.13.0",
4
+ "description": "The3Beez Hub guard: a module opens only by a Hub-signed ticket and refuses everything else. No key from the Hub: towards the Hub the app shows its own Vercel ID; from the Hub it accepts only what is signed by the key the Hub publishes. Entry route, refusal page, module session, idle rule, re-check with the Hub on every page and every minute, Cloudflare Access proof, broker and audit clients, manifest and health answers for the Hub only, the memo bell and window (0.10.0), the shared top bar's door and one Sign out for every app (0.12.0), the till's check of a sale another app passes through the Hub (0.13.0). Web Crypto only: runs in Node 20+ and in edge runtimes.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",