A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.

9 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-browser.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-browser.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-browser.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 toolbar: Back and Forward are greyed out when there's nowhere to go cc08c7a 1 week, 2 days ago History
cards.ts · 18.7 KB · 339 lines
1/**
2 * Card view: a site's posts shown as dense cards in a page the browser owns. Electron-free so it is unit-tested.
3 *
4 * The split that keeps it safe:
5 * - A VIEW RULE says where a site keeps its posts: CSS selectors and which attribute to take, nothing else. It is data,
6 * not code, so it can be checked and, later, shared on gitstable like a style rule. `validateViewRule` refuses
7 * anything else.
8 * - The READER below is the browser's own code. It runs in an isolated world of the site's tab (the page's scripts
9 * can't see or change it) and returns plain strings.
10 * - What it returns is UNTRUSTED: the page controls the DOM it reads. `validatePosts` keeps a small plain-data
11 * vocabulary, clamps every size and keeps only https addresses; `buildCardsHtml` writes the page from scratch with
12 * every string escaped, under a CSP with no scripts, forms, frames or connections (images only).
13 */
14
15export type Take = "text" | "href" | "src" | "poster" | "datetime" | "aria-label" | "exists";
16export interface FieldSpec {
17 sel: string;
18 take: Take;
19 /** Every match (a list), not only the first. */
20 all?: boolean;
21 /** Only elements whose text matches this (case-sensitive regular expression). */
22 match?: string;
23}
24export const FIELDS = ["link", "author", "handle", "avatar", "time", "timeText", "text", "images", "stats", "context", "promoted"] as const;
25export type FieldName = (typeof FIELDS)[number];
26
27export interface ViewRule {
28 v: 1;
29 id: string;
30 name: string;
31 sites: string[];
32 /** One post. */
33 post: string;
34 /** Each field: one spec, or alternatives tried in order (the first that finds something wins). */
35 fields: Partial<Record<FieldName, FieldSpec | FieldSpec[]>>;
36}
37
38const TAKES: readonly Take[] = ["text", "href", "src", "poster", "datetime", "aria-label", "exists"];
39const MAX_SEL = 400;
40
41/** The rule if it is only selectors and field names; otherwise why not. */
42export function validateViewRule(raw: unknown): { ok: true; rule: ViewRule } | { ok: false; error: string } {
43 const r = raw as Partial<ViewRule> | null;
44 if (!r || typeof r !== "object" || r.v !== 1) return { ok: false, error: "not a view rule (v: 1)" };
45 if (typeof r.id !== "string" || !/^[a-z0-9-]{1,64}$/.test(r.id)) return { ok: false, error: "bad id" };
46 if (typeof r.name !== "string" || !r.name.trim() || r.name.length > 80) return { ok: false, error: "bad name" };
47 if (!Array.isArray(r.sites) || !r.sites.length || !r.sites.every((s) => typeof s === "string" && /^[a-z0-9.-]{1,253}$/.test(s))) return { ok: false, error: "bad sites" };
48 if (typeof r.post !== "string" || !r.post.trim() || r.post.length > MAX_SEL) return { ok: false, error: "bad post selector" };
49 if (!r.fields || typeof r.fields !== "object") return { ok: false, error: "no fields" };
50 const fields: ViewRule["fields"] = {};
51 for (const [k, v] of Object.entries(r.fields)) {
52 if (!(FIELDS as readonly string[]).includes(k)) return { ok: false, error: `unknown field ${k}` };
53 const specs = Array.isArray(v) ? v : [v];
54 if (!specs.length || specs.length > 6) return { ok: false, error: `bad field ${k}` };
55 for (const s of specs as FieldSpec[]) {
56 if (!s || typeof s.sel !== "string" || !s.sel.trim() || s.sel.length > MAX_SEL || !TAKES.includes(s.take)) return { ok: false, error: `bad field ${k}` };
57 if (s.match !== undefined) {
58 if (typeof s.match !== "string" || s.match.length > 200) return { ok: false, error: `bad match in ${k}` };
59 try {
60 new RegExp(s.match);
61 } catch {
62 return { ok: false, error: `bad match in ${k}` };
63 }
64 }
65 const extra = Object.keys(s).filter((x) => !["sel", "take", "all", "match"].includes(x));
66 if (extra.length) return { ok: false, error: `field ${k} has ${extra.join(", ")}` };
67 }
68 fields[k as FieldName] = specs.map((s) => ({ sel: s.sel, take: s.take, ...(s.all ? { all: true } : {}), ...(s.match !== undefined ? { match: s.match } : {}) }));
69 }
70 return { ok: true, rule: { v: 1, id: r.id, name: r.name.trim(), sites: r.sites, post: r.post, fields } };
71}
72
73/**
74 * The reader, as source to run in an isolated world of the tab. It reads at most 200 posts and returns plain strings.
75 * (A function serialised with the rule as JSON: the rule is data, so it can't add code.)
76 */
77export function readerSource(rule: ViewRule): string {
78 const reader = (r: ViewRule) => {
79 const pick = (root: Element, specs: FieldSpec | FieldSpec[] | undefined): unknown => {
80 for (const s of specs ? (Array.isArray(specs) ? specs : [specs]) : []) {
81 let els: Element[];
82 try {
83 els = [...root.querySelectorAll(s.sel)];
84 } catch {
85 continue;
86 }
87 if (s.match) {
88 const re = new RegExp(s.match);
89 els = els.filter((e) => re.test(((e as HTMLElement).innerText ?? e.textContent ?? "").trim()));
90 }
91 const val = (e: Element): unknown => {
92 if (s.take === "exists") return true;
93 if (s.take === "text") return ((e as HTMLElement).innerText ?? e.textContent ?? "").trim();
94 if (s.take === "href") return (e as HTMLAnchorElement).href || "";
95 if (s.take === "src") return (e as HTMLImageElement).currentSrc || (e as HTMLImageElement).src || "";
96 if (s.take === "poster") return (e as HTMLVideoElement).poster || "";
97 return e.getAttribute(s.take) || "";
98 };
99 if (s.all) {
100 const vals = els.map(val).filter(Boolean);
101 if (vals.length) return vals;
102 } else {
103 for (const e of els) {
104 const v = val(e);
105 if (v) return v;
106 }
107 }
108 }
109 return undefined;
110 };
111 const posts = [...document.querySelectorAll(r.post)].slice(0, 200).map((el) => {
112 const o: Record<string, unknown> = {};
113 for (const k of Object.keys(r.fields)) o[k] = pick(el, (r.fields as Record<string, FieldSpec | FieldSpec[]>)[k]);
114 return o;
115 });
116 return { url: location.href, title: document.title, posts };
117 };
118 return `(${reader.toString()})(${JSON.stringify(rule)})`;
119}
120
121export interface Post {
122 /** The post's address: what identifies it. */
123 link: string;
124 author: string;
125 handle: string;
126 avatar: string;
127 /** ISO time when the site gives one; else the site's own short text ("2h"). */
128 time: string;
129 timeText: string;
130 text: string;
131 images: string[];
132 stats: string;
133 context: string;
134 promoted: boolean;
135}
136
137const str = (v: unknown, max: number) => (typeof v === "string" ? v.replace(/\u0000/g, "").trim().slice(0, max) : "");
138function httpsUrl(v: unknown, sites?: readonly string[]): string {
139 if (typeof v !== "string" || v.length > 2000) return "";
140 try {
141 const u = new URL(v);
142 const loopback = u.hostname === "127.0.0.1" || u.hostname === "localhost";
143 if ((u.protocol !== "https:" && !(u.protocol === "http:" && loopback && sites)) || u.username || u.password) return "";
144 if (sites) {
145 const h = u.hostname.toLowerCase().replace(/^www\./, "");
146 if (!sites.some((s) => h === s || h.endsWith("." + s))) return "";
147 }
148 return u.href;
149 } catch {
150 return "";
151 }
152}
153
154/** What the reader returned, as plain posts. Posts without a link on the rule's own sites are dropped. */
155export function validatePosts(raw: unknown, rule: ViewRule): Post[] {
156 const list = (raw as { posts?: unknown })?.posts;
157 if (!Array.isArray(list)) return [];
158 const out: Post[] = [];
159 for (const p of list.slice(0, 200) as Array<Record<string, unknown>>) {
160 if (!p || typeof p !== "object") continue;
161 const link = httpsUrl(p.link, rule.sites);
162 if (!link) continue;
163 const handle = str(p.handle, 40);
164 const iso = str(p.time, 40);
165 out.push({
166 link,
167 author: str(p.author, 80).split("\n")[0] ?? "",
168 handle: /^@\w{1,30}$/.test(handle) ? handle : "",
169 avatar: httpsUrl(p.avatar),
170 time: !Number.isNaN(Date.parse(iso)) ? new Date(iso).toISOString() : "",
171 timeText: str(p.timeText, 20),
172 text: str(p.text, 4000),
173 images: (Array.isArray(p.images) ? p.images : []).map((x) => httpsUrl(x)).filter(Boolean).filter((x, i, a) => a.indexOf(x) === i).slice(0, 4),
174 stats: str(p.stats, 200),
175 context: str(p.context, 120),
176 promoted: p.promoted === true,
177 });
178 }
179 return out;
180}
181
182/** Adds what's new, keyed by the post's address, keeping the order first seen. Returns how many were new. */
183export function mergePosts(into: Map<string, Post>, posts: readonly Post[]): number {
184 let n = 0;
185 for (const p of posts) {
186 const key = p.link.replace(/[?#].*$/, "");
187 const had = into.get(key);
188 if (!had) n++;
189 // A later read of the same post may have loaded its images; keep the fuller one.
190 if (!had || p.images.length > had.images.length || p.text.length > had.text.length) into.set(key, had ? { ...had, ...p, images: p.images.length >= had.images.length ? p.images : had.images } : p);
191 }
192 return n;
193}
194
195export const escapeHtml = (s: string) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!);
196
197/** "61 replies, 223 reposts, 1554 likes, 78 bookmarks, 254134 views" → "61 replies · 223 reposts · 1.6K likes · 254K views". */
198export function shortStats(s: string): string {
199 const parts = [...s.matchAll(/(\d[\d,]*)\s+(repl(?:y|ies)|reposts?|likes?|views?|bookmarks?)/gi)].filter((m) => !/bookmark/i.test(m[2]!));
200 const k = (n: number) => (n >= 1e6 ? (n / 1e6).toFixed(n >= 1e7 ? 0 : 1) + "M" : n >= 1e3 ? (n / 1e3).toFixed(n >= 1e4 ? 0 : 1) + "K" : String(n));
201 return parts.map((m) => `${k(Number(m[1]!.replace(/,/g, "")))} ${m[2]!.toLowerCase()}`).join(" · ");
202}
203
204/** "now", "5m", "3h", "Nov 21": X's own style, from an ISO time. */
205export function shortTime(iso: string, now: Date): string {
206 const t = Date.parse(iso);
207 if (Number.isNaN(t)) return "";
208 const s = Math.max(0, (now.getTime() - t) / 1000);
209 if (s < 60) return "now";
210 if (s < 3600) return `${Math.floor(s / 60)}m`;
211 if (s < 86400) return `${Math.floor(s / 3600)}h`;
212 return new Date(t).toLocaleDateString("en-US", { month: "short", day: "numeric" });
213}
214
215export const CARDS_CSP = "default-src 'none'; img-src https:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'";
216
217/** Masonry without scripts: the page carries one layout per column count, and the window's width picks one. */
218export const COLUMN_COUNTS = [1, 2, 3, 4, 5, 6, 7] as const;
219const COL_W = 300;
220const MASONRY_CSS = COLUMN_COUNTS.map((n) => {
221 const min = n === 1 ? 0 : n * COL_W + 24;
222 const max = n === COLUMN_COUNTS[COLUMN_COUNTS.length - 1] ? 0 : (n + 1) * COL_W + 23;
223 const q = [min ? `(min-width: ${min}px)` : "", max ? `(max-width: ${max}px)` : ""].filter(Boolean).join(" and ");
224 return `@media ${q} { .m${n} { display: grid; grid-template-columns: repeat(${n}, minmax(0, 1fr)); } }`;
225}).join("\n");
226
227/** About how tall a card will be at 300px wide: enough to pick the shortest column. */
228export function estimateHeight(p: Post): number {
229 const lines = p.text ? Math.min(10, p.text.split("\n").reduce((n, l) => n + Math.max(1, Math.ceil(l.length / 40)), 0)) : 0;
230 const media = p.images.length === 0 ? 0 : p.images.length === 1 ? 230 : Math.ceil(p.images.length / 2) * 120;
231 return 64 + (p.context ? 16 : 0) + lines * 19 + media + (p.stats ? 22 : 0);
232}
233
234/** Cards into `n` columns, each to the shortest so far: newest across the top, no gaps. */
235export function masonry<T>(items: readonly T[], n: number, height: (x: T) => number): T[][] {
236 const cols: T[][] = Array.from({ length: n }, () => []);
237 const h = new Array<number>(n).fill(0);
238 for (const it of items) {
239 const i = h.indexOf(Math.min(...h));
240 cols[i]!.push(it);
241 h[i]! += height(it) + 10;
242 }
243 return cols;
244}
245
246const STYLE = `
247:root { color-scheme: light dark; --bg:#f3f4f6; --fg:#16181c; --muted:#5b6470; --card:#fff; --rule:#e3e6ea; --accent:#1d6fd8; }
248@media (prefers-color-scheme: dark) { :root { --bg:#0d0f12; --fg:#e7e9ea; --muted:#8b949e; --card:#16191e; --rule:#262b33; --accent:#6aa8ff; } }
249* { box-sizing: border-box; }
250body { margin: 0; background: var(--bg); color: var(--fg); font: 14px/1.4 -apple-system, system-ui, "Segoe UI", sans-serif; }
251header { position: sticky; top: 0; z-index: 1; display: flex; gap: 14px; align-items: baseline; flex-wrap: wrap; padding: 10px 16px; background: var(--bg); border-bottom: 1px solid var(--rule); }
252header h1 { font-size: 15px; margin: 0; }
253header .meta { color: var(--muted); font-size: 12px; }
254header a { color: var(--accent); text-decoration: none; font-size: 13px; }
255main { padding: 10px 12px 40px; }
256.m { display: none; gap: 10px; align-items: start; margin-bottom: 10px; }
257.col { display: flex; flex-direction: column; gap: 10px; min-width: 0; }
258.batch { color: var(--muted); font-size: 12px; margin: 18px 2px 8px; border-top: 1px solid var(--rule); padding-top: 10px; }
259${MASONRY_CSS}
260.card { margin: 0; background: var(--card); border: 1px solid var(--rule); border-radius: 10px; padding: 9px 11px; }
261.card.promoted { opacity: .75; }
262.top { display: flex; gap: 8px; align-items: center; margin-bottom: 4px; }
263.top img { width: 28px; height: 28px; border-radius: 50%; flex: none; }
264.who { min-width: 0; flex: 1; line-height: 1.2; }
265.who b { display: block; font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
266.who span { color: var(--muted); font-size: 12px; }
267.when { color: var(--muted); font-size: 12px; text-decoration: none; flex: none; }
268.ctx { color: var(--muted); font-size: 11px; margin-bottom: 3px; }
269.text { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13.5px; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 10; overflow: hidden; }
270.media { display: grid; gap: 3px; margin-top: 7px; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); }
271.media a { display: block; }
272.media img { width: 100%; max-height: 260px; object-fit: cover; border-radius: 6px; display: block; background: var(--rule); }
273.stats { color: var(--muted); font-size: 11.5px; margin-top: 6px; }
274.tag { font-size: 10px; text-transform: uppercase; letter-spacing: .04em; color: var(--muted); border: 1px solid var(--rule); border-radius: 4px; padding: 0 4px; }
275details { color: var(--muted); margin-bottom: 10px; }
276details summary { cursor: pointer; font-size: 12px; }
277details .inner { columns: 290px; column-gap: 10px; margin-top: 8px; }
278details .inner .card { break-inside: avoid; margin-bottom: 10px; }
279.more { display: block; text-align: center; padding: 14px; margin: 6px 0; border: 1px dashed var(--rule); border-radius: 10px; color: var(--accent); text-decoration: none; }
280.empty { padding: 40px 16px; color: var(--muted); }
281.note { margin: 0 2px 10px; padding: 8px 12px; border: 1px solid var(--rule); border-left: 3px solid var(--accent); border-radius: 6px; font-size: 13px; }
282`;
283
284function card(p: Post, now: Date, anchor: string): string {
285 const when = p.time ? shortTime(p.time, now) : p.timeText;
286 const media = p.images.length
287 ? `<div class="media">${p.images.map((src) => `<a href="${escapeHtml(p.link)}" target="_blank" rel="noopener noreferrer"><img src="${escapeHtml(src)}" alt="" loading="lazy" referrerpolicy="no-referrer"></a>`).join("")}</div>`
288 : "";
289 return `<article class="card${p.promoted ? " promoted" : ""}"${anchor ? ` id="${anchor}"` : ""}>${p.context ? `<div class="ctx">${escapeHtml(p.context)}</div>` : ""}<div class="top">${p.avatar ? `<img src="${escapeHtml(p.avatar)}" alt="" referrerpolicy="no-referrer">` : ""}<div class="who"><b>${escapeHtml(p.author || p.handle || "?")}</b><span>${escapeHtml(p.handle)}${p.promoted ? ` <span class="tag">promoted</span>` : ""}</span></div><a class="when" href="${escapeHtml(p.link)}" target="_blank" rel="noopener noreferrer">${escapeHtml(when || "open")}</a></div>${p.text ? `<div class="text">${escapeHtml(p.text)}</div>` : ""}${media}${p.stats ? `<div class="stats">${escapeHtml(shortStats(p.stats))}</div>` : ""}</article>`;
290}
291
292export interface CardsPage {
293 rule: ViewRule;
294 /** The page the posts were read from. */
295 source: string;
296 title: string;
297 posts: Post[];
298 /** dbb-cards://<id>/more: read more posts from the same tab. Empty when that tab is gone. */
299 moreUrl: string;
300 /** Where each later read ("More posts") starts, as indexes into `posts`; the newest one is the #new anchor. */
301 batches?: Array<{ from: number; at: Date }>;
302 /** A line at the top, e.g. why the last More posts found nothing new. */
303 note?: string;
304 collectedAt: Date;
305}
306
307/** One batch of cards, laid out once per column count. */
308function block(posts: Post[], now: Date): string {
309 return COLUMN_COUNTS.map((n) => `<div class="m m${n}">${masonry(posts, n, estimateHeight).map((col) => `<div class="col">${col.map((p) => card(p, now, "")).join("")}</div>`).join("")}</div>`).join("");
310}
311
312/** The card page, from validated posts only, every string escaped. No scripts. */
313export function buildCardsHtml(v: CardsPage): string {
314 const shownAll = v.posts.filter((p) => !p.promoted);
315 const hidden = v.posts.filter((p) => p.promoted);
316 const time = (d: Date) => d.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });
317 let host = "";
318 try {
319 host = new URL(v.source).host;
320 } catch {}
321 const starts = [0, ...(v.batches ?? []).map((b) => b.from)];
322 const parts = starts.map((from, i) => {
323 const to = starts[i + 1] ?? v.posts.length;
324 const posts = v.posts.slice(from, to).filter((p) => !p.promoted);
325 if (!posts.length) return "";
326 const b = i > 0 ? v.batches![i - 1]! : null;
327 const head = b ? `<div class="batch"${i === starts.length - 1 && !v.note ? ' id="new"' : ""}>${posts.length} more · read at ${escapeHtml(time(b.at))}</div>` : "";
328 return head + block(posts, v.collectedAt);
329 });
330 const promo = hidden.length
331 ? `<details><summary>${hidden.length} promoted post${hidden.length === 1 ? "" : "s"} hidden · show</summary><div class="inner">${hidden.map((p) => card(p, v.collectedAt, "")).join("")}</div></details>`
332 : "";
333 const more = v.moreUrl ? `<a class="more" href="${escapeHtml(v.moreUrl)}">More posts</a>` : `<div class="empty">The tab these came from is closed. Open the site again and choose Card view for more.</div>`;
334 return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
335<meta http-equiv="Content-Security-Policy" content="${CARDS_CSP}"><meta name="referrer" content="no-referrer">
336<title>${escapeHtml(`Cards · ${v.title || host}`)}</title><style>${STYLE}</style></head>
337<body><header><h1>${escapeHtml(v.title || host)}</h1><span class="meta">${shownAll.length} post${shownAll.length === 1 ? "" : "s"} from ${escapeHtml(host)} · read at ${escapeHtml(time(v.collectedAt))} · ${escapeHtml(v.rule.name)}</span><a href="${escapeHtml(v.source)}" target="_blank" rel="noopener noreferrer">Original</a>${v.moreUrl ? `<a href="${escapeHtml(v.moreUrl)}">More posts</a>` : ""}</header>
338<main>${v.note ? `<p class="note" id="new">${escapeHtml(v.note)}</p>` : ""}${promo}${parts.join("") || `<div class="empty">No posts were found on this page.</div>`}${more}</main></body></html>`;
339}