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
downloads.mjs · 11.2 KB · 146 lines
1// Downloads: tracked, announced, saved safely, linked to the payment that unlocked them.
2// (The e2e runner sets DBB_DOWNLOAD_DIR so nothing blocks on the native Save dialog.)
3import { execFileSync } from "node:child_process";
4import { existsSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
5import { join } from "node:path";
6import { sleep } from "./lib.mjs";
7
8export default async function (ctx) {
9 const { call: T, check, base } = ctx;
10 const dir = ctx.downloadDir;
11 const c = await ctx.chrome();
12 const list = () => T("downloads.list");
13 const finished = async (name, ms = 15000) => {
14 const end = Date.now() + ms;
15 for (;;) {
16 const d = (await list()).find((x) => x.name === name && x.state !== "progressing");
17 if (d || Date.now() > end) return d;
18 await sleep(100);
19 }
20 };
21
22 check((await list()).length === 0, "no downloads at the start");
23
24 // ---- a small attachment ----
25 const e0 = (await T("x402.events", { since: 0 })).next;
26 T("page.goto", { url: base + "/download", wait: false }).catch(() => {});
27 let d = await finished("hello-report.txt");
28 check(d?.state === "completed", "a download completes", `${d?.name} ${d?.received} B`);
29 check(d && existsSync(d.path) && d.path.startsWith(dir), "…and the file was saved where we said", d?.path?.replace(dir, "<dir>"));
30 check(d && readFileSync(d.path, "utf8").startsWith("hello from the demo server"), "…with the right content");
31 check(d && statSync(d.path).size === d.received && d.received > 1000, "…and the recorded size matches the file");
32 const evs = (await T("x402.events", { since: e0 })).events.filter((e) => e.kind === "download");
33 check(evs.length >= 2 && evs[0].state === "progressing" && evs.at(-1).state === "completed", "it was announced: started, then completed", evs.map((e) => e.state).join(" → "));
34 check(((await T("tabs.list")).find((t) => t.active).url || "").startsWith(base), "the tab stays on the page it was on (a download doesn't navigate away)");
35
36 // ---- the same file again: never overwrite ----
37 T("page.goto", { url: base + "/download", wait: false }).catch(() => {});
38 await sleep(1500);
39 const names = readdirSync(dir).sort();
40 check(names.includes("hello-report.txt") && names.includes("hello-report (1).txt"), "a second download of the same name gets a new name instead of overwriting", names.join(", "));
41
42 // ---- a hostile filename cannot escape the folder ----
43 T("page.goto", { url: base + "/download/evil", wait: false }).catch(() => {});
44 d = (await (async () => { for (let i = 0; i < 100; i++) { const x = (await list()).find((r) => /pwned/.test(r.name)); if (x && x.state !== "progressing") return x; await sleep(100); } })());
45 check(!!d && !/[\\/]/.test(d.name) && d.path.startsWith(dir + "/"), "a '../../../../tmp/…' filename is neutralized and stays inside the folder", d?.name);
46 check(!existsSync("/tmp/dbb-pwned.txt"), "nothing was written outside the download folder");
47
48 // ---- progress on a big, slow file ----
49 const seen = [];
50 let sawStatus = "";
51 T("page.goto", { url: base + "/download/big", wait: false }).catch(() => {});
52 const t0 = Date.now();
53 while (Date.now() - t0 < 20000) {
54 const r = (await list()).find((x) => x.name === "big.bin");
55 if (r) {
56 if (!seen.length || seen.at(-1) !== r.received) seen.push(r.received);
57 if (r.state === "progressing" && !sawStatus) sawStatus = (await c.ev(`(() => { const s = document.getElementById('status'); return s.classList.contains('show') ? s.innerText.replace(/\\s+/g, ' ').trim() : '' })()`)) || "";
58 if (r.state !== "progressing") break;
59 }
60 await sleep(120);
61 }
62 const big = (await list()).find((x) => x.name === "big.bin");
63 check(big?.state === "completed" && big.received === 3 * 1024 * 1024, "a 3 MB trickling file completes with exactly the right size", `${big?.received} B`);
64 check(seen.length >= 3 && seen.every((v, i) => i === 0 || v >= seen[i - 1]), "progress was reported while it ran (byte count grew)", `${seen.length} updates, e.g. ${seen.slice(0, 3).join(" → ")}`);
65 check(/Downloading big\.bin/.test(sawStatus), "the status line said what was happening", sawStatus);
66 check(statSync(big.path).size === 3 * 1024 * 1024, "the saved file is the full size on disk");
67
68 // ---- a PAID download: linked to the payment ----
69 await T("x402.approval", { mode: "auto", maxUsd: 1 });
70 T("page.goto", { url: base + "/download/paid", wait: false }).catch(() => {});
71 d = await finished("dataset.csv");
72 await T("x402.approval", { mode: "ask", maxUsd: 0 });
73 check(d?.state === "completed" && readFileSync(d.path, "utf8").startsWith("id,value"), "a paid download completes after the payment", d?.name);
74 check(d?.paid === "$0.001", "…and the record carries the amount that unlocked it", d?.paid);
75
76 // ---- the Downloads panel (status bar, File ▸ Downloads, ⌘⇧J) ----
77 const panel = () => c.ev(`(() => [...document.querySelectorAll("#dlPanel .dl")].map((r) => ({ name: r.querySelector(".nm").textContent, link: r.querySelector(".nm").tagName === "A", gone: r.classList.contains("gone"), info: r.querySelector(".t2").textContent, buttons: [...r.querySelectorAll("button")].map((b) => b.textContent) })))()`);
78 const press = (name, label) => c.ev(`(() => { const r = [...document.querySelectorAll("#dlPanel .dl")].find((r) => r.querySelector(".nm").textContent === ${JSON.stringify(name)}); const b = r && [...r.querySelectorAll("button")].find((b) => b.textContent === ${JSON.stringify(label)}); if (!b) return false; b.click(); return true; })()`);
79 const waitPanel = async (fn, what) => { for (let i = 0; i < 60; i++) { const p = await panel(); if (fn(p)) return p; await sleep(100); } return panel(); };
80 await c.ev(`(onTabCmd("downloads"), true)`);
81 let rows = await waitPanel((p) => p.length >= 5, "the panel");
82 check(await c.ev(`document.getElementById("dlPanel").classList.contains("open")`), "File ▸ Downloads opens the Downloads panel");
83 check(rows.length === 5 && rows[0].name === "dataset.csv" && rows.at(-1).name === "hello-report.txt", "it lists every download, newest first", rows.map((r) => r.name).join(", "));
84 const paidRow = rows.find((r) => r.name === "dataset.csv");
85 check(/127\.0\.0\.1/.test(paidRow.info) && /paid \$0\.001/.test(paidRow.info) && paidRow.link, "a row says the site, the size and what was paid, and its name opens the file", paidRow.info);
86 check(rows.find((r) => r.name === "big.bin").info.includes("3.0 MB"), "and the size", rows.find((r) => r.name === "big.bin").info);
87 let since = (await T("x402.events", { since: 0 })).next;
88 await c.ev(`(document.querySelector('#dlPanel .dl a.nm').click(), true)`);
89 let opened = null;
90 for (let i = 0; i < 40 && !opened; i++) { opened = (await T("x402.events", { since })).events.find((e) => e.kind === "download-opened"); await sleep(100); }
91 check(!!opened, "clicking a name opens the file (recorded here, not opened)");
92 check(await press("big.bin", "Show in Finder"), "each file has Show in Finder");
93
94 // a file moved or deleted outside the browser
95 const report = (await list()).find((x) => x.name === "hello-report.txt");
96 rmSync(report.path);
97 await c.ev(`(setDl(false), setDl(true), true)`);
98 rows = await waitPanel((p) => p.some((r) => r.name === "hello-report.txt" && r.gone), "the deleted file");
99 const goneRow = rows.find((r) => r.name === "hello-report.txt");
100 check(goneRow?.gone && !goneRow.link && /Moved or deleted/.test(goneRow.info) && !goneRow.buttons.includes("Show in Finder"), "a file deleted since is shown as moved or deleted, and can't be opened", goneRow?.info);
101
102 // take one off the list: the file stays
103 const one = (await list()).find((x) => x.name === "hello-report (1).txt");
104 await press("hello-report (1).txt", "✕");
105 rows = await waitPanel((p) => !p.some((r) => r.name === "hello-report (1).txt"), "the row to go");
106 check(!rows.some((r) => r.name === "hello-report (1).txt") && existsSync(one.path), "✕ takes a download off the list, and the file stays where it is");
107
108 // cancel a running one from the panel, then retry it
109 T("page.goto", { url: base + "/download/big", wait: false }).catch(() => {});
110 rows = await waitPanel((p) => p[0]?.name === "big (1).bin" && p[0].buttons.includes("Cancel"), "the running download");
111 const btn = await c.ev(`document.getElementById("dlBtn").textContent`);
112 check(rows[0]?.buttons.includes("Cancel") && /^⬇ \d+%$/.test(btn), "a running download has Cancel, and the status bar button shows its progress", btn);
113 await press("big (1).bin", "Cancel");
114 rows = await waitPanel((p) => /Cancelled/.test(p[0]?.info ?? ""), "the cancel");
115 check(/Cancelled/.test(rows[0]?.info ?? "") && rows[0].buttons.includes("Retry"), "Cancel stops it, and it can be retried", rows[0]?.info);
116 check(!paidRow.buttons.includes("Retry"), "a paid download has no Retry (fetching it again could pay twice)");
117 await press("big (1).bin", "Retry");
118 let again = null;
119 for (let i = 0; i < 200 && !again; i++) { again = (await list()).find((x) => x.id > rows.length && x.name.startsWith("big") && x.state === "completed" && x.received === 3 * 1024 * 1024 && x.startedAt > Date.now() - 30000); await sleep(100); }
120 check(!!again, "Retry downloads it again, in full", again?.name);
121 check((await c.ev(`document.getElementById("dlBtn").textContent`)) === "Downloads", "and the status bar button goes back to Downloads");
122
123 // kept for the next start
124 const saved = JSON.parse(readFileSync(join(ctx.tmp, "profile-downloads", "downloads.json"), "utf8"));
125 check(saved.v === 1 && saved.items.some((x) => x.name === "dataset.csv" && x.paid === "$0.001") && !saved.items.some((x) => x.name === "hello-report (1).txt"), "the list is saved in the profile for the next start", `${saved.items.length} items`);
126
127 // ⌘⇧J from the page closes it; Clear list keeps only what is running
128 await c.ev(`(() => { active.wv.focus(); const m = ${JSON.stringify(process.platform === "darwin" ? "meta" : "control")}; active.wv.sendInputEvent({ type: "keyDown", keyCode: "J", modifiers: [m, "shift"] }); active.wv.sendInputEvent({ type: "keyUp", keyCode: "J", modifiers: [m, "shift"] }); return true; })()`);
129 let closed = false;
130 for (let i = 0; i < 30 && !closed; i++) { closed = !(await c.ev(`document.getElementById("dlPanel").classList.contains("open")`)); await sleep(100); }
131 check(closed, "⌘⇧J while the page has the keyboard closes it again");
132 await c.ev(`(setDl(true), true)`);
133 await waitPanel((p) => p.length > 0, "the panel");
134 await c.ev(`(() => { [...document.querySelectorAll("#dlPanel h4 button")].find((b) => b.textContent === "Clear list").click(); return true; })()`);
135 await waitPanel((p) => p.length === 0, "an empty list");
136 check((await list()).length === 0 && /Nothing downloaded yet/.test(await c.ev(`document.getElementById("dlPanel").textContent`)), "Clear list takes the finished ones off, and the panel says there is nothing yet");
137 check(existsSync(join(dir, "big.bin")), "and no file was deleted");
138 await c.ev(`(setDl(false), true)`);
139
140 // ---- macOS quarantine: a downloaded file must be marked so Gatekeeper vets anything you run ----
141 if (process.platform === "darwin" && big) {
142 let q = "";
143 try { q = execFileSync("xattr", ["-p", "com.apple.quarantine", big.path], { encoding: "utf8" }).trim(); } catch { /* absent */ }
144 check(q.length > 0, "the file carries the com.apple.quarantine attribute (Gatekeeper will vet it)", q || "ABSENT");
145 }
146}