@t3b/hub-guard 0.10.1 → 0.11.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
@@ -308,6 +308,17 @@ const r2 = await guard.memoAct(session, "reply", id, { text, lang: "ar" });
308
308
 
309
309
  ## Changes
310
310
 
311
+ - **0.11.0** (HR WORKFLOWS §3, the Hub's §22.8; owner 2026-10-11: *"give me powerful tools"*): a memo may carry
312
+ **formatted text, pictures and files**. `cleanMemoDoc` is the one rule for what a memo's document may hold (paragraphs,
313
+ two heading sizes, bulleted and numbered lists, quotes, pictures by file id; bold, italic, underline, highlight, red,
314
+ links that are https / mailto / tel; start / centre / end and the paragraph's direction; 20,000 characters) -
315
+ anything else is dropped, never HTML. `memoDocHtml` draws it with every word escaped and a picture only from the
316
+ memo's own files; `readMemoFiles` keeps a file only with HR's `/f/<token>` link. `MemoView` gains `doc`, `files`,
317
+ `version` and `updated` (an update after the person read it: an **Updated** badge and a note). `memoFragment` draws
318
+ all of it; a plain memo looks exactly as before. Also `memoDocText` (the plain copy), `memoDocImages`,
319
+ `memoDocIsRich`. **An app that takes 0.11.0 also allows pictures from HR's address** in its page rules
320
+ (`img-src https://t3b-hr.vercel.app`). An app on 0.10.x keeps working and shows the plain copy.
321
+
311
322
  - **0.10.1** (owner, 2026-10-11): the memo window's Arabic button reads **تمت القراءة و تم إبلاغي** (was "قرأت وأوافق"). Nothing else
312
323
  changes but one fix: the accept button wraps onto a second line on a narrow screen instead of running past its card
313
324
  (found by the Stores Sync session at 390 px). An app on 0.10.0 keeps working and shows the old words until it takes 0.10.1.
package/dist/index.d.ts CHANGED
@@ -2,7 +2,8 @@ export { Guard, openingPage, type GuardConfig, type CheckResult } from "./guard.
2
2
  export { appMenu, readApps, APP_ID_RE, type AppMenuItem, type HubApp } 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
- export { memoBell, memoData, memoAct, memoFragment, memoText, memoWhen, readMemo, readMemos, verifyMemosCall, memosRefusal, MEMO_TEXTS, MEMO_ID_RE, REPLY_MAX, type MemoLang, type MemoTextKey, type MemoView, type MemoReply, type MemoBell, type MemoData, type MemoActResult, type MemoFragmentOptions, type MemosCallCheck, } from "./memos.js";
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
+ 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";
6
7
  export { readSession, signSession, cookieHeader, clearCookieHeader, cookieValue, SESSION_COOKIE, IDLE_MS, ABSOLUTE_MS, RECHECK_MS, MAX_STALE_MS, type ModuleSession } from "./session.js";
7
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";
8
9
  export { checkCloudflareAccess } from "./cf-access.js";
package/dist/index.js CHANGED
@@ -2,7 +2,8 @@ export { Guard, openingPage } from "./guard.js";
2
2
  export { appMenu, readApps, APP_ID_RE } 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
- export { memoBell, memoData, memoAct, memoFragment, memoText, memoWhen, readMemo, readMemos, verifyMemosCall, memosRefusal, MEMO_TEXTS, MEMO_ID_RE, REPLY_MAX, } from "./memos.js";
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
+ export { cleanMemoDoc, memoDocHtml, memoDocText, memoDocImages, memoDocIsRich, readMemoFile, readMemoFiles, escHtml, MEMO_DOC_LIMITS, MEMO_LINK_RE, MEMO_FILE_URL_RE, } from "./memo-doc.js";
6
7
  export { readSession, signSession, cookieHeader, clearCookieHeader, cookieValue, SESSION_COOKIE, IDLE_MS, ABSOLUTE_MS, RECHECK_MS, MAX_STALE_MS } from "./session.js";
7
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";
8
9
  export { checkCloudflareAccess } from "./cf-access.js";
@@ -0,0 +1,103 @@
1
+ import { type MemoLang } from "./memos-shared.js";
2
+ /** The kinds of block and mark a memo may hold (HR WORKFLOWS §3.1). */
3
+ export declare const MEMO_DOC_LIMITS: {
4
+ readonly chars: 20000;
5
+ readonly nodes: 4000;
6
+ readonly depth: 8;
7
+ readonly json: 200000;
8
+ readonly files: 10;
9
+ readonly fileBytes: number;
10
+ };
11
+ export type MemoAlign = "start" | "center" | "end";
12
+ export type MemoDir = "rtl" | "ltr";
13
+ export type MemoMark = {
14
+ type: "bold" | "italic" | "underline" | "highlight" | "warn";
15
+ } | {
16
+ type: "link";
17
+ attrs: {
18
+ href: string;
19
+ };
20
+ };
21
+ export type MemoInline = {
22
+ type: "text";
23
+ text: string;
24
+ marks?: MemoMark[];
25
+ } | {
26
+ type: "hardBreak";
27
+ };
28
+ type BlockAttrs = {
29
+ textAlign?: MemoAlign;
30
+ dir?: MemoDir;
31
+ };
32
+ export type MemoBlock = {
33
+ type: "paragraph";
34
+ attrs?: BlockAttrs;
35
+ content?: MemoInline[];
36
+ } | {
37
+ type: "heading";
38
+ attrs: BlockAttrs & {
39
+ level: 2 | 3;
40
+ };
41
+ content?: MemoInline[];
42
+ } | {
43
+ type: "bulletList";
44
+ content: MemoListItem[];
45
+ } | {
46
+ type: "orderedList";
47
+ attrs?: {
48
+ start?: number;
49
+ };
50
+ content: MemoListItem[];
51
+ } | {
52
+ type: "blockquote";
53
+ content: MemoBlock[];
54
+ } | {
55
+ type: "image";
56
+ attrs: {
57
+ file: string;
58
+ alt?: string;
59
+ };
60
+ };
61
+ export type MemoListItem = {
62
+ type: "listItem";
63
+ content: MemoBlock[];
64
+ };
65
+ export type MemoDoc = {
66
+ type: "doc";
67
+ content: MemoBlock[];
68
+ };
69
+ /** One of a memo's files as an app receives it: HR's link for this person (it stops working after 10 minutes). */
70
+ export type MemoFile = {
71
+ id: string;
72
+ name: string;
73
+ kind: string;
74
+ size: number;
75
+ url: string;
76
+ image: boolean;
77
+ };
78
+ /** a link in a memo: https, mailto or tel only (never javascript:, data:, a relative path) */
79
+ export declare const MEMO_LINK_RE: RegExp;
80
+ /** HR's file link as an app may draw it: HR's /f/<token> on https (or on this machine for a local run), or the same site */
81
+ export declare const MEMO_FILE_URL_RE: RegExp;
82
+ /**
83
+ * A memo's document as the editor sent it (or as HR sent it through the Hub), cleaned: only the kinds above, at most
84
+ * 20,000 characters, 4,000 parts, 8 levels deep. Null when nothing is left (or it was not a document at all).
85
+ */
86
+ export declare function cleanMemoDoc(raw: unknown): MemoDoc | null;
87
+ /** The ids of the pictures placed in the text, in order. */
88
+ export declare function memoDocImages(doc: MemoDoc | null): string[];
89
+ /** True when the document holds more than plain paragraphs of plain text (an app on 0.10.x cannot show it all). */
90
+ export declare function memoDocIsRich(doc: MemoDoc | null): boolean;
91
+ /** The plain copy: what search, the CSV and an app not yet on 0.11.0 read. Blocks on their own lines, list items marked. */
92
+ export declare function memoDocText(doc: MemoDoc | null): string;
93
+ /** One of a memo's files as it arrived through the Hub: kept only when every part has its shape. */
94
+ export declare function readMemoFile(raw: unknown): MemoFile | null;
95
+ export declare function readMemoFiles(raw: unknown): MemoFile[];
96
+ export declare function escHtml(s: string): string;
97
+ /**
98
+ * The memo's text as HTML for its window: the document's blocks and marks, its pictures where they were placed (from
99
+ * the memo's own files only, by id), then every other file as a download line. Nothing the document says is ever
100
+ * written into the page unescaped; a picture whose id is not one of the memo's files is not drawn.
101
+ */
102
+ export declare function memoDocHtml(doc: MemoDoc | null, files: MemoFile[], lang?: MemoLang): string;
103
+ export {};
@@ -0,0 +1,348 @@
1
+ // HR WORKFLOWS §3 / the Hub's §22.8 (0.11.0, owner 2026-10-11: "give me powerful tools"): a memo's formatted text,
2
+ // pictures and files. HR's editor saves a structured document (the editor's JSON - never HTML); this file is the one
3
+ // rule for what such a document may hold, used three times: HR cleans what the editor sent before saving it, and
4
+ // every app cleans it again when it arrives through the Hub (an app never trusts a body it did not make), then draws
5
+ // it. Only the kinds below survive; every word is escaped when drawn; a picture is only ever one of the memo's own
6
+ // files, by its id - a document cannot point anywhere else.
7
+ import { MEMO_ID_RE } from "./memos-shared.js";
8
+ /** The kinds of block and mark a memo may hold (HR WORKFLOWS §3.1). */
9
+ export const MEMO_DOC_LIMITS = { chars: 20_000, nodes: 4_000, depth: 8, json: 200_000, files: 10, fileBytes: 25 * 1024 * 1024 };
10
+ const CTRL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u2028\u2029]/g;
11
+ const ALIGN = new Set(["start", "center", "end"]);
12
+ const DIR = new Set(["rtl", "ltr"]);
13
+ const MARKS = new Set(["bold", "italic", "underline", "highlight", "warn"]);
14
+ /** a link in a memo: https, mailto or tel only (never javascript:, data:, a relative path) */
15
+ export const MEMO_LINK_RE = /^(https:\/\/[^\s"'<>\\]{1,2000}|mailto:[^\s"'<>\\]{3,320}|tel:\+?[0-9 ()-]{3,30})$/i;
16
+ /** HR's file link as an app may draw it: HR's /f/<token> on https (or on this machine for a local run), or the same site */
17
+ export const MEMO_FILE_URL_RE = /^(https:\/\/[a-z0-9.-]{1,253}(:\d{1,5})?|http:\/\/(127\.0\.0\.1|localhost)(:\d{1,5})?)?\/f\/[A-Za-z0-9._~-]{16,600}$/;
18
+ const FILE_NAME_MAX = 120;
19
+ function cleanText(v, budget) {
20
+ if (typeof v !== "string")
21
+ return null;
22
+ const t = v.replace(/\r\n?/g, "\n").replace(/\n/g, " ").replace(CTRL, " ");
23
+ if (!t)
24
+ return null;
25
+ const room = MEMO_DOC_LIMITS.chars - budget.chars;
26
+ if (room <= 0)
27
+ return null;
28
+ const out = t.slice(0, room);
29
+ budget.chars += out.length;
30
+ return out;
31
+ }
32
+ function cleanMarks(v) {
33
+ if (!Array.isArray(v))
34
+ return undefined;
35
+ const out = [];
36
+ const seen = new Set();
37
+ for (const m of v.slice(0, 8)) {
38
+ const o = (m ?? {});
39
+ const type = typeof o.type === "string" ? o.type : "";
40
+ if (seen.has(type))
41
+ continue;
42
+ if (MARKS.has(type)) {
43
+ out.push({ type });
44
+ seen.add(type);
45
+ }
46
+ else if (type === "link") {
47
+ const href = typeof o.attrs?.href === "string" ? String(o.attrs.href).trim() : "";
48
+ if (MEMO_LINK_RE.test(href)) {
49
+ out.push({ type: "link", attrs: { href } });
50
+ seen.add(type);
51
+ }
52
+ }
53
+ }
54
+ return out.length ? out : undefined;
55
+ }
56
+ function cleanInline(v, budget) {
57
+ if (!Array.isArray(v))
58
+ return undefined;
59
+ const out = [];
60
+ for (const n of v) {
61
+ if (--budget.nodes < 0)
62
+ break;
63
+ const o = (n ?? {});
64
+ if (o.type === "hardBreak")
65
+ out.push({ type: "hardBreak" });
66
+ else if (o.type === "text") {
67
+ const text = cleanText(o.text, budget);
68
+ if (!text)
69
+ continue;
70
+ const marks = cleanMarks(o.marks);
71
+ out.push(marks ? { type: "text", text, marks } : { type: "text", text });
72
+ }
73
+ }
74
+ return out.length ? out : undefined;
75
+ }
76
+ function blockAttrs(v) {
77
+ const o = (v ?? {});
78
+ const a = {};
79
+ if (typeof o.textAlign === "string" && ALIGN.has(o.textAlign) && o.textAlign !== "start")
80
+ a.textAlign = o.textAlign;
81
+ if (typeof o.dir === "string" && DIR.has(o.dir))
82
+ a.dir = o.dir;
83
+ return a;
84
+ }
85
+ function cleanBlocks(v, budget, depth) {
86
+ if (!Array.isArray(v) || depth > MEMO_DOC_LIMITS.depth)
87
+ return [];
88
+ const out = [];
89
+ for (const n of v) {
90
+ if (--budget.nodes < 0)
91
+ break;
92
+ const o = (n ?? {});
93
+ switch (o.type) {
94
+ case "paragraph": {
95
+ const attrs = blockAttrs(o.attrs);
96
+ const content = cleanInline(o.content, budget);
97
+ out.push({ type: "paragraph", ...(Object.keys(attrs).length ? { attrs } : {}), ...(content ? { content } : {}) });
98
+ break;
99
+ }
100
+ case "heading": {
101
+ const raw = (o.attrs ?? {});
102
+ const level = raw.level === 3 || raw.level === 4 || raw.level === 5 || raw.level === 6 ? 3 : 2;
103
+ const content = cleanInline(o.content, budget);
104
+ if (content)
105
+ out.push({ type: "heading", attrs: { ...blockAttrs(o.attrs), level }, content });
106
+ break;
107
+ }
108
+ case "bulletList":
109
+ case "orderedList": {
110
+ const items = [];
111
+ for (const li of Array.isArray(o.content) ? o.content : []) {
112
+ if (--budget.nodes < 0)
113
+ break;
114
+ const x = (li ?? {});
115
+ if (x.type !== "listItem")
116
+ continue;
117
+ const content = cleanBlocks(x.content, budget, depth + 1).filter((b) => b.type !== "image");
118
+ if (content.length)
119
+ items.push({ type: "listItem", content });
120
+ }
121
+ if (!items.length)
122
+ break;
123
+ if (o.type === "bulletList")
124
+ out.push({ type: "bulletList", content: items });
125
+ else {
126
+ const start = Number(o.attrs?.start);
127
+ out.push({ type: "orderedList", ...(Number.isInteger(start) && start > 1 && start < 1000 ? { attrs: { start } } : {}), content: items });
128
+ }
129
+ break;
130
+ }
131
+ case "blockquote": {
132
+ const content = cleanBlocks(o.content, budget, depth + 1);
133
+ if (content.length)
134
+ out.push({ type: "blockquote", content });
135
+ break;
136
+ }
137
+ case "image": {
138
+ const a = (o.attrs ?? {});
139
+ const file = typeof a.file === "string" && MEMO_ID_RE.test(a.file) ? a.file : null;
140
+ if (!file)
141
+ break;
142
+ const alt = typeof a.alt === "string" ? a.alt.replace(CTRL, " ").trim().slice(0, 200) : "";
143
+ out.push({ type: "image", attrs: alt ? { file, alt } : { file } });
144
+ break;
145
+ }
146
+ default:
147
+ break; // anything else - a script, a table, an iframe, a style - is dropped
148
+ }
149
+ }
150
+ return out;
151
+ }
152
+ const hasWords = (blocks) => blocks.some((b) => b.type === "image" ? true : b.type === "blockquote" ? hasWords(b.content) : b.type === "bulletList" || b.type === "orderedList" ? b.content.some((li) => hasWords(li.content)) : (b.content ?? []).some((i) => i.type === "text" && i.text.trim()));
153
+ /**
154
+ * A memo's document as the editor sent it (or as HR sent it through the Hub), cleaned: only the kinds above, at most
155
+ * 20,000 characters, 4,000 parts, 8 levels deep. Null when nothing is left (or it was not a document at all).
156
+ */
157
+ export function cleanMemoDoc(raw) {
158
+ if (!raw || typeof raw !== "object")
159
+ return null;
160
+ let size = 0;
161
+ try {
162
+ size = JSON.stringify(raw).length;
163
+ }
164
+ catch {
165
+ return null;
166
+ }
167
+ if (size > MEMO_DOC_LIMITS.json)
168
+ return null;
169
+ const o = raw;
170
+ if (o.type !== "doc")
171
+ return null;
172
+ const content = cleanBlocks(o.content, { nodes: MEMO_DOC_LIMITS.nodes, chars: 0 }, 0);
173
+ return content.length && hasWords(content) ? { type: "doc", content } : null;
174
+ }
175
+ /** The ids of the pictures placed in the text, in order. */
176
+ export function memoDocImages(doc) {
177
+ const out = [];
178
+ const walk = (blocks) => {
179
+ for (const b of blocks) {
180
+ if (b.type === "image")
181
+ out.push(b.attrs.file);
182
+ else if (b.type === "blockquote")
183
+ walk(b.content);
184
+ else if (b.type === "bulletList" || b.type === "orderedList")
185
+ for (const li of b.content)
186
+ walk(li.content);
187
+ }
188
+ };
189
+ if (doc)
190
+ walk(doc.content);
191
+ return out;
192
+ }
193
+ /** True when the document holds more than plain paragraphs of plain text (an app on 0.10.x cannot show it all). */
194
+ export function memoDocIsRich(doc) {
195
+ if (!doc)
196
+ return false;
197
+ const plain = (blocks) => blocks.every((b) => b.type === "paragraph" && !b.attrs && (b.content ?? []).every((i) => i.type === "hardBreak" || !i.marks));
198
+ return !plain(doc.content);
199
+ }
200
+ /** The plain copy: what search, the CSV and an app not yet on 0.11.0 read. Blocks on their own lines, list items marked. */
201
+ export function memoDocText(doc) {
202
+ if (!doc)
203
+ return "";
204
+ const lines = [];
205
+ const inline = (c) => (c ?? []).map((i) => (i.type === "text" ? i.text : "\n")).join("");
206
+ const walk = (blocks, prefix) => {
207
+ for (const b of blocks) {
208
+ if (b.type === "paragraph" || b.type === "heading")
209
+ lines.push(prefix + inline(b.content));
210
+ else if (b.type === "blockquote")
211
+ walk(b.content, `${prefix}> `);
212
+ else if (b.type === "bulletList")
213
+ for (const li of b.content)
214
+ walk(li.content, `${prefix}• `);
215
+ else if (b.type === "orderedList")
216
+ b.content.forEach((li, i) => walk(li.content, `${prefix}${(b.attrs?.start ?? 1) + i}. `));
217
+ }
218
+ };
219
+ walk(doc.content, "");
220
+ return lines.join("\n").replace(/\n{3,}/g, "\n\n").trim().slice(0, MEMO_DOC_LIMITS.chars);
221
+ }
222
+ /** One of a memo's files as it arrived through the Hub: kept only when every part has its shape. */
223
+ export function readMemoFile(raw) {
224
+ const o = (raw ?? {});
225
+ if (typeof o.id !== "string" || !MEMO_ID_RE.test(o.id))
226
+ return null;
227
+ const name = typeof o.name === "string" ? o.name.replace(CTRL, " ").replace(/[\\/]/g, "-").trim().slice(0, FILE_NAME_MAX) : "";
228
+ const kind = typeof o.kind === "string" && /^[A-Za-z0-9 ]{1,16}$/.test(o.kind) ? o.kind : "";
229
+ const size = typeof o.size === "number" && Number.isInteger(o.size) && o.size > 0 && o.size <= MEMO_DOC_LIMITS.fileBytes ? o.size : 0;
230
+ const url = typeof o.url === "string" && MEMO_FILE_URL_RE.test(o.url) ? o.url : "";
231
+ if (!name || !kind || !size || !url)
232
+ return null;
233
+ return { id: o.id, name, kind, size, url, image: o.image === true };
234
+ }
235
+ export function readMemoFiles(raw) {
236
+ const out = [];
237
+ const seen = new Set();
238
+ for (const f of (Array.isArray(raw) ? raw : []).slice(0, MEMO_DOC_LIMITS.files)) {
239
+ const m = readMemoFile(f);
240
+ if (m && !seen.has(m.id)) {
241
+ out.push(m);
242
+ seen.add(m.id);
243
+ }
244
+ }
245
+ return out;
246
+ }
247
+ // ---- drawing it (the same in every app; the design system's tokens; every word escaped) ----
248
+ export function escHtml(s) {
249
+ return s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
250
+ }
251
+ const blockStyle = (a, base) => `${base}${a?.textAlign ? ` text-align: ${a.textAlign};` : ""}`;
252
+ const blockDir = (a) => ` dir="${a?.dir ?? "auto"}"`;
253
+ /** The direction of a text's first strong letter (Arabic and Hebrew script → rtl, a Latin letter → ltr), else null. */
254
+ function firstStrongDir(s) {
255
+ for (const ch of s) {
256
+ const cp = ch.codePointAt(0) ?? 0;
257
+ if ((cp >= 0x0590 && cp <= 0x08ff) || (cp >= 0xfb1d && cp <= 0xfdff) || (cp >= 0xfe70 && cp <= 0xfefc))
258
+ return "rtl";
259
+ if (/[A-Za-z]/.test(ch))
260
+ return "ltr";
261
+ }
262
+ return null;
263
+ }
264
+ /** A list's direction: its first item's own direction if the writer set one, else its first words' (the browser's
265
+ * dir="auto" on a list skips the paragraphs inside it, which carry their own dir - so it is worked out here). */
266
+ function listDir(items) {
267
+ const first = items[0]?.content[0];
268
+ if (first && (first.type === "paragraph" || first.type === "heading") && first.attrs?.dir)
269
+ return ` dir="${first.attrs.dir}"`;
270
+ const d = firstStrongDir(memoDocText({ type: "doc", content: items.flatMap((li) => li.content) }));
271
+ return d ? ` dir="${d}"` : "";
272
+ }
273
+ /** The short label on a file's square (the kind HR names it by). */
274
+ const KIND_SHORT = { Word: "DOC", Excel: "XLS", PowerPoint: "PPT", Text: "TXT" };
275
+ const kindShort = (f) => (f.image ? "IMG" : KIND_SHORT[f.kind] ?? f.kind.slice(0, 4).toUpperCase());
276
+ function inlineHtml(c) {
277
+ return (c ?? [])
278
+ .map((i) => {
279
+ if (i.type === "hardBreak")
280
+ return "<br>";
281
+ let h = escHtml(i.text);
282
+ for (const m of i.marks ?? []) {
283
+ if (m.type === "bold")
284
+ h = `<strong>${h}</strong>`;
285
+ else if (m.type === "italic")
286
+ h = `<em>${h}</em>`;
287
+ else if (m.type === "underline")
288
+ h = `<u>${h}</u>`;
289
+ else if (m.type === "highlight")
290
+ h = `<mark style="background: color-mix(in srgb, var(--honey) 38%, transparent); color: inherit; padding-inline: 2px; border-radius: 2px">${h}</mark>`;
291
+ else if (m.type === "warn")
292
+ h = `<span style="color: var(--danger); font-weight: 600">${h}</span>`;
293
+ else if (m.type === "link")
294
+ h = `<a href="${escHtml(m.attrs.href)}" target="_blank" rel="noopener noreferrer nofollow" style="color: inherit; text-decoration: underline; text-underline-offset: 3px">${h}</a>`;
295
+ }
296
+ return h;
297
+ })
298
+ .join("");
299
+ }
300
+ const sizeText = (n) => (n >= 1024 * 1024 ? `${(n / (1024 * 1024)).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1024))} KB`);
301
+ const DOC_TEXTS = {
302
+ en: { files: "Attachments", download: "Download", picture: "Picture", open_picture: "Tap to open full size" },
303
+ ar: { files: "المرفقات", download: "تنزيل", picture: "صورة", open_picture: "اضغط على الصورة لتكبيرها" },
304
+ };
305
+ /**
306
+ * The memo's text as HTML for its window: the document's blocks and marks, its pictures where they were placed (from
307
+ * the memo's own files only, by id), then every other file as a download line. Nothing the document says is ever
308
+ * written into the page unescaped; a picture whose id is not one of the memo's files is not drawn.
309
+ */
310
+ export function memoDocHtml(doc, files, lang = "en") {
311
+ const t = DOC_TEXTS[lang === "ar" ? "ar" : "en"];
312
+ const byId = new Map(files.map((f) => [f.id, f]));
313
+ const placed = new Set();
314
+ const blocks = (bs) => bs
315
+ .map((b) => {
316
+ switch (b.type) {
317
+ case "paragraph":
318
+ return `<p${blockDir(b.attrs)} style="${blockStyle(b.attrs, "margin: 0 0 var(--s-3); line-height: 1.8;")}">${inlineHtml(b.content) || "<br>"}</p>`;
319
+ case "heading":
320
+ return b.attrs.level === 2
321
+ ? `<h3${blockDir(b.attrs)} style="${blockStyle(b.attrs, "margin: 0 0 var(--s-3); font-size: var(--fs-h3); line-height: var(--lh-h3);")}">${inlineHtml(b.content)}</h3>`
322
+ : `<h4${blockDir(b.attrs)} style="${blockStyle(b.attrs, "margin: var(--s-4) 0 var(--s-2); font-size: var(--fs-body); font-weight: 700;")}">${inlineHtml(b.content)}</h4>`;
323
+ case "bulletList":
324
+ return `<ul${listDir(b.content)} style="margin: 0 0 var(--s-3); padding-inline-start: var(--s-5); line-height: 1.8">${b.content.map((li) => `<li>${blocks(li.content).replace(/margin: 0 0 var\(--s-3\)/g, "margin: 0")}</li>`).join("")}</ul>`;
325
+ case "orderedList":
326
+ return `<ol${listDir(b.content)}${b.attrs?.start ? ` start="${b.attrs.start}"` : ""} style="margin: 0 0 var(--s-3); padding-inline-start: var(--s-5); line-height: 1.8">${b.content.map((li) => `<li>${blocks(li.content).replace(/margin: 0 0 var\(--s-3\)/g, "margin: 0")}</li>`).join("")}</ol>`;
327
+ case "blockquote":
328
+ return `<blockquote style="margin: 0 0 var(--s-3); padding: var(--s-2) var(--s-4); border-inline-start: 3px solid var(--honey); background: var(--paper-2); border-radius: var(--r-sm)">${blocks(b.content)}</blockquote>`;
329
+ case "image": {
330
+ const f = byId.get(b.attrs.file);
331
+ if (!f || !f.image)
332
+ return "";
333
+ placed.add(f.id);
334
+ const alt = escHtml(b.attrs.alt || f.name);
335
+ return `<figure style="margin: var(--s-2) 0 var(--s-4)"><a href="${escHtml(f.url)}" target="_blank" rel="noopener noreferrer" title="${escHtml(t.open_picture)}" style="display: block"><img src="${escHtml(f.url)}" alt="${alt}" loading="lazy" decoding="async" style="display: block; max-inline-size: 100%; block-size: auto; border: 1px solid var(--line); border-radius: var(--r-sm)"></a></figure>`;
336
+ }
337
+ }
338
+ })
339
+ .join("");
340
+ const body = doc ? blocks(doc.content) : "";
341
+ const rest = files.filter((f) => !placed.has(f.id));
342
+ const list = rest.length
343
+ ? `<div style="margin-block-start: var(--s-3)"><div style="font-weight: 600; font-size: var(--fs-body-sm); margin-block-end: var(--s-2)">${escHtml(t.files)}</div><ul class="files" style="margin: 0">${rest
344
+ .map((f) => `<li class="file"><span class="ft">${escHtml(kindShort(f))}</span><div style="min-inline-size: 0"><div class="nm" dir="auto">${escHtml(f.name)}</div><div class="mt">${escHtml(f.kind)} · ${sizeText(f.size)}</div></div><a class="btn btn-ghost" href="${escHtml(f.url)}" target="_blank" rel="noopener noreferrer" download>${escHtml(t.download)}</a></li>`)
345
+ .join("")}</ul></div>`
346
+ : "";
347
+ return `${body}${list}`;
348
+ }
@@ -0,0 +1,2 @@
1
+ export type MemoLang = "ar" | "en";
2
+ export declare const MEMO_ID_RE: RegExp;
@@ -0,0 +1,2 @@
1
+ // The two facts the memo window (memos.ts) and the memo document (memo-doc.ts) share, kept apart so neither imports the other.
2
+ export const MEMO_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
package/dist/memos.d.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  import { type JWTVerifyGetKey } from "jose";
2
2
  import { type HubClientConfig } from "./hub-client.js";
3
- export type MemoLang = "ar" | "en";
4
- export declare const MEMO_ID_RE: RegExp;
3
+ import { type MemoDoc, type MemoFile } from "./memo-doc.js";
4
+ import { MEMO_ID_RE, type MemoLang } from "./memos-shared.js";
5
+ export { MEMO_ID_RE, type MemoLang };
5
6
  export declare const REPLY_MAX = 2000;
7
+ /** a memo's plain text, as HR sends it (0.11.0: 20,000 - the editor's limit; was 4,000) */
8
+ export declare const MEMO_TEXT_MAX = 20000;
6
9
  /** Every word on the window, in both languages (the owner's rule: Arabic and English everywhere). */
7
10
  export declare const MEMO_TEXTS: {
8
11
  readonly en: {
@@ -31,6 +34,8 @@ export declare const MEMO_TEXTS: {
31
34
  readonly not_yours: "That memo is not yours.";
32
35
  readonly too_long: "A reply is 1 to 2,000 characters.";
33
36
  readonly new_answer: "New answer";
37
+ readonly updated: "Updated";
38
+ readonly updated_note: "Changed after you read it - read it again and accept.";
34
39
  };
35
40
  readonly ar: {
36
41
  readonly title: "التعاميم";
@@ -58,6 +63,8 @@ export declare const MEMO_TEXTS: {
58
63
  readonly not_yours: "هذا التعميم ليس لك.";
59
64
  readonly too_long: "الرد من حرف واحد إلى 2,000 حرف.";
60
65
  readonly new_answer: "رد جديد";
66
+ readonly updated: "مُحدَّث";
67
+ readonly updated_note: "عُدِّل بعد قراءتك - اقرأه من جديد ووافق عليه.";
61
68
  };
62
69
  };
63
70
  export type MemoTextKey = keyof (typeof MEMO_TEXTS)["en"];
@@ -83,6 +90,13 @@ export type MemoView = {
83
90
  accepted_at: string | null;
84
91
  replies: MemoReply[];
85
92
  unseen_answer: boolean;
93
+ /** 0.11.0 (HR §3): the formatted text, cleaned again here; null for a plain memo (then `text` is shown) */
94
+ doc: MemoDoc | null;
95
+ /** its pictures and files, each with HR's link for this person */
96
+ files: MemoFile[];
97
+ /** the memo's version (an update makes the next one) and whether it changed after this person read it */
98
+ version: number;
99
+ updated: boolean;
86
100
  };
87
101
  export declare function readMemo(raw: unknown): MemoView | null;
88
102
  export declare function readMemos(raw: unknown): MemoView[];
package/dist/memos.js CHANGED
@@ -2,8 +2,21 @@ import { jwtVerify } from "jose";
2
2
  import { memosCall } from "./hub-client.js";
3
3
  import { HUB_ISSUER, TYP } from "./identity.js";
4
4
  import { b64urlEncode, constantTimeEqual, sha256 } from "./webcrypto.js";
5
- export const MEMO_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
5
+ import { cleanMemoDoc, memoDocHtml, readMemoFiles } from "./memo-doc.js";
6
+ import { MEMO_ID_RE } from "./memos-shared.js";
7
+ // WORKFLOWS §22.4 (0.10.0, D-088, D-090): the bell and the memo window every app shows. HR holds the memos; the app
8
+ // asks the Hub (its own Vercel ID, the person from its own session), the Hub asks HR with its signed pass and passes
9
+ // the answer back. Nothing is kept in the app. Texts in Arabic and English, chosen by the app; Latin digits.
10
+ //
11
+ // An app mounts it in three places: the bell in its top bar (`memoBell`), its /memos page (`memoData` → draws the
12
+ // list and the open memo with `memoFragment`, or its own markup from the same data), and two POST handlers
13
+ // (`memoAct` for accept and reply). `/memos` is every signed-in person's: no page tick - a person's own memos are theirs.
14
+ //
15
+ // The module that holds the memos (HR) checks the Hub's pass on its own door with `verifyMemosCall`.
16
+ export { MEMO_ID_RE };
6
17
  export const REPLY_MAX = 2_000;
18
+ /** a memo's plain text, as HR sends it (0.11.0: 20,000 - the editor's limit; was 4,000) */
19
+ export const MEMO_TEXT_MAX = 20_000;
7
20
  /** Every word on the window, in both languages (the owner's rule: Arabic and English everywhere). */
8
21
  export const MEMO_TEXTS = {
9
22
  en: {
@@ -32,6 +45,8 @@ export const MEMO_TEXTS = {
32
45
  not_yours: "That memo is not yours.",
33
46
  too_long: "A reply is 1 to 2,000 characters.",
34
47
  new_answer: "New answer",
48
+ updated: "Updated",
49
+ updated_note: "Changed after you read it - read it again and accept.",
35
50
  },
36
51
  ar: {
37
52
  title: "التعاميم",
@@ -59,6 +74,8 @@ export const MEMO_TEXTS = {
59
74
  not_yours: "هذا التعميم ليس لك.",
60
75
  too_long: "الرد من حرف واحد إلى 2,000 حرف.",
61
76
  new_answer: "رد جديد",
77
+ updated: "مُحدَّث",
78
+ updated_note: "عُدِّل بعد قراءتك - اقرأه من جديد ووافق عليه.",
62
79
  },
63
80
  };
64
81
  export function memoText(lang, key) {
@@ -90,7 +107,8 @@ export function readMemo(raw) {
90
107
  const answer = a && clip(a.text, REPLY_MAX) && when(a.at) && clip(a.by, 80) ? { text: clip(a.text, REPLY_MAX), at: when(a.at), by: clip(a.by, 80) } : null;
91
108
  return [{ id, text, at, answer }];
92
109
  });
93
- return { id: o.id, title, text: clip(o.text, 4_000), from, sent_at: sent, state, read_at: when(o.read_at), accepted_at: when(o.accepted_at), replies, unseen_answer: o.unseen_answer === true };
110
+ const version = typeof o.version === "number" && Number.isInteger(o.version) && o.version >= 1 && o.version <= 9_999 ? o.version : 1;
111
+ return { id: o.id, title, text: clip(o.text, MEMO_TEXT_MAX), from, sent_at: sent, state, read_at: when(o.read_at), accepted_at: when(o.accepted_at), replies, unseen_answer: o.unseen_answer === true, doc: cleanMemoDoc(o.doc), files: readMemoFiles(o.files), version, updated: o.updated === true && state !== "accepted" };
94
112
  }
95
113
  export function readMemos(raw) {
96
114
  return (Array.isArray(raw) ? raw : []).slice(0, 200).map(readMemo).filter((m) => m !== null);
@@ -157,7 +175,7 @@ export function memoWhen(iso) {
157
175
  function stateBadge(m, lang) {
158
176
  const tone = m.state === "accepted" ? "badge-success" : m.state === "new" ? "badge-warning" : m.state === "withdrawn" ? "badge-muted" : "badge-info";
159
177
  const key = `state_${m.state}`;
160
- const extra = m.unseen_answer ? ` <span class="badge badge-honey">${esc(memoText(lang, "new_answer"))}</span>` : "";
178
+ const extra = (m.updated ? ` <span class="badge badge-honey">${esc(memoText(lang, "updated"))}</span>` : "") + (m.unseen_answer ? ` <span class="badge badge-honey">${esc(memoText(lang, "new_answer"))}</span>` : "");
161
179
  return `<span class="badge ${tone}">${esc(memoText(lang, key))}</span>${extra}`;
162
180
  }
163
181
  /**
@@ -185,7 +203,9 @@ export function memoFragment(data, opts = {}) {
185
203
  const opened = !o
186
204
  ? ""
187
205
  : `<div class="card"><div class="card-head"><h2 class="card-title">${esc(o.title)}</h2><div class="help-2" style="display: flex; gap: var(--s-3); flex-wrap: wrap"><span>${t("from")} ${esc(o.from)}</span><span>${t("sent")} ${esc(memoWhen(o.sent_at))}</span></div></div>` +
188
- `<p style="white-space: pre-line; line-height: 1.7; margin: 0 0 var(--s-4)">${esc(o.text ?? "")}</p>` +
206
+ (o.updated ? `<div class="alert info" role="status" style="margin-block-end: var(--s-3)"><div class="txt">${t("updated_note")}</div></div>` : "") +
207
+ // 0.11.0: the formatted text with its pictures and files (HR §3); a plain memo as before
208
+ (o.doc ? `<div style="margin: 0 0 var(--s-4)">${memoDocHtml(o.doc, o.files, lang)}</div>` : `<p dir="auto" style="white-space: pre-line; line-height: 1.7; margin: 0 0 var(--s-4)">${esc(o.text ?? "")}</p>${o.files.length ? `<div style="margin: 0 0 var(--s-4)">${memoDocHtml(null, o.files, lang)}</div>` : ""}`) +
189
209
  (o.state === "accepted"
190
210
  ? `<div class="alert success" role="status"><div class="txt"><b>${t("accepted_on")} · ${esc(memoText(lang === "ar" ? "en" : "ar", "accept"))}</b>${o.accepted_at ? esc(memoWhen(o.accepted_at)) : ""}</div></div>`
191
211
  : o.state === "withdrawn"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@t3b/hub-guard",
3
- "version": "0.10.1",
3
+ "version": "0.11.0",
4
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.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",