[browser] Firefox: one extension source for Firefox, Edge and Chrome; frames, public suffixes, the caller check, 2FA codes and saving logins; v0.20.0

- custos-browser: fill_allowed (a frame gets a login only when its page would too), public suffixes match
  exactly only (psl), ports digits only, caller (which extension started the host); spoof tests.
- custos-native: answers not_allowed to anything but the Custos extension, browser_totp and browser_save,
  the frame's and the page's origins, a random session per connection (its match code on Custos's cards).
- extension/: manifest.firefox.json (gecko id custos@marek-novak.cz) and manifest.chromium.json, one set of
  scripts; the popup shows 2FA codes, the save offer and the connection's code; tools/extension.mjs builds
  each browser and reproducible zips; tools/extension-test.mjs runs the background against a fake browser.
This commit is contained in:
2026-11-22 21:57:35 +01:00
parent a3b3a32745
commit 04a6031c5d
19 changed files with 1157 additions and 186 deletions
+141
View File
@@ -0,0 +1,141 @@
// Tests of the extension's background script against a fake browser (docs/BROWSER.md, "Tests"):
//
// node tools/extension-test.mjs
//
// The background is the extension's one gate to Custos: what it sends to the host must come from the browser's
// own view of the sender, never from the message; other extensions and odd frames get nothing; a login offered for
// saving never comes back out of it.
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
const root = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const code = fs.readFileSync(path.join(root, 'extension', 'background.js'), 'utf8');
const ID = 'custos-test-id';
/** A fresh background with a fake API. `host(req)` answers the native host's requests. */
function background(host) {
const sent = [];
let listener = null;
const port = {
onMessage: { addListener: (f) => (port.deliver = f) },
onDisconnect: { addListener: () => {} },
postMessage: (m) => {
sent.push(m);
queueMicrotask(() => port.deliver({ ...host(m), seq: m.seq }));
},
};
const tabs = [{ id: 1, url: 'https://github.com/login', active: true }];
const api = {
runtime: { id: ID, connectNative: () => port, onMessage: { addListener: (f) => (listener = f) } },
tabs: { query: async () => tabs, onRemoved: { addListener: () => {} } },
action: { setBadgeText: async () => {}, setBadgeBackgroundColor: async () => {} },
};
vm.runInNewContext(code, { chrome: api, URL, setTimeout, Promise, queueMicrotask, console });
const call = (msg, sender) =>
new Promise((resolve) => {
// Answers are made in the background's realm: compared as plain JSON.
const kept = listener(msg, { id: ID, ...sender }, (v) => resolve(JSON.parse(JSON.stringify(v))));
if (kept !== true) resolve('ignored');
});
return { call, sent, tabs };
}
const tab = (url) => ({ id: 1, url });
const top = (url) => ({ url, frameId: 0, tab: tab(url) });
const frame = (url, pageUrl) => ({ url, frameId: 7, tab: tab(pageUrl) });
const tests = [];
const test = (name, f) => tests.push([name, f]);
test('another extension, or a page, is not answered at all', async () => {
const b = background(() => ({ ok: true, logins: [{ id: 'a' }] }));
for (const id of ['someone-else', undefined, '']) {
assert.equal(await b.call({ kind: 'match' }, { ...top('https://github.com/'), id }), 'ignored');
assert.equal(await b.call({ kind: 'fill', id: 'a' }, { ...top('https://github.com/'), id }), 'ignored');
}
assert.equal(b.sent.length, 0);
});
test('the origins come from the browser, never from the message', async () => {
const b = background(() => ({ ok: true, logins: [] }));
await b.call({ kind: 'match', origin: 'https://bank.cz', top: 'https://bank.cz' }, top('https://github.com/login?x=1'));
assert.deepEqual(b.sent.map((m) => [m.op, m.origin, m.top]), [['browser_match', 'https://github.com', 'https://github.com']]);
});
test('a frame asks with its own origin and its page’s', async () => {
const b = background(() => ({ ok: true, logins: [] }));
await b.call({ kind: 'match' }, frame('https://evil.net/ad', 'https://github.com/'));
await b.call({ kind: 'fill', id: 'x' }, frame('https://github.com/login', 'https://evil.net/'));
assert.deepEqual(
b.sent.map((m) => [m.op, m.origin, m.top]),
[
['browser_match', 'https://evil.net', 'https://github.com'],
['browser_fill', 'https://github.com', 'https://evil.net'],
],
);
});
test('sandboxed, blank, script and file frames get nothing, and nothing is asked', async () => {
const b = background(() => ({ ok: true, logins: [{ id: 'a' }] }));
const odd = [
{ ...frame('https://github.com/login', 'https://evil.net/'), origin: 'null' },
{ ...top('https://github.com/'), origin: 'https://evil.net' },
frame('about:blank', 'https://github.com/'),
top('javascript:alert(1)'),
top('file:///C:/x.html'),
top('data:text/html,<input type=password>'),
{ url: 'https://github.com/', frameId: 3 },
];
for (const s of odd) {
assert.deepEqual(await b.call({ kind: 'match' }, s), { ok: false, error: 'no_match' }, JSON.stringify(s));
assert.deepEqual(await b.call({ kind: 'fill', id: 'a' }, s), { ok: false, error: 'no_match' });
}
assert.equal(b.sent.length, 0);
});
test('a locked Custos answers nothing but locked', async () => {
const b = background(() => ({ ok: false, error: 'locked' }));
const r = await b.call({ kind: 'fill', id: 'a' }, top('https://github.com/'));
assert.deepEqual(r, { ok: false, error: 'locked', seq: 1 });
});
test('a login offered for saving never comes back out, and goes only to Custos', async () => {
const b = background((m) => (m.op === 'browser_save' ? { ok: true, saved: 'new' } : { ok: true, code: '123456' }));
const at = top('https://github.com/login');
const offered = await b.call({ kind: 'offer-save', username: 'mark', password: 'hunter2-secret' }, at);
assert.deepEqual(offered, { ok: true, offer: { host: 'github.com', username: 'mark' } });
// Another page of the site in the same tab sees the offer, without the password; a frame or another site does not.
assert.deepEqual(await b.call({ kind: 'pending-save' }, top('https://github.com/home')), { ok: true, offer: { host: 'github.com', username: 'mark' } });
assert.deepEqual(await b.call({ kind: 'pending-save' }, frame('https://github.com/x', 'https://github.com/')), { ok: true, offer: null });
assert.deepEqual(await b.call({ kind: 'pending-save' }, top('https://evil.net/')), { ok: true, offer: null });
const popup = await b.call({ kind: 'match-tab' }, { url: `chrome-extension://${ID}/popup.html` });
assert.ok(!JSON.stringify(popup).includes('hunter2'), 'the popup never sees the password');
// A frame cannot save; the top page can, once.
assert.deepEqual(await b.call({ kind: 'save' }, frame('https://github.com/x', 'https://github.com/')), { ok: false, error: 'bad_request' });
const saved = await b.call({ kind: 'save' }, top('https://github.com/home'));
assert.equal(saved.saved, 'new');
const req = b.sent.find((m) => m.op === 'browser_save');
assert.deepEqual([req.origin, req.top, req.username, req.password], ['https://github.com', 'https://github.com', 'mark', 'hunter2-secret']);
assert.deepEqual(await b.call({ kind: 'save' }, top('https://github.com/home')), { ok: false, error: 'gone' });
});
test('an offer needs a password, from a web page', async () => {
const b = background(() => ({ ok: true }));
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: '' }, top('https://github.com/'))).ok, false);
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: 'p' }, top('about:blank'))).ok, false);
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: 'x'.repeat(4097) }, top('https://a.cz/'))).ok, false);
});
let failed = 0;
for (const [name, f] of tests) {
try {
await f();
console.log(`ok ${name}`);
} catch (e) {
failed++;
console.log(`FAIL ${name}\n${e.stack}`);
}
}
console.log(`${tests.length - failed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);
+87
View File
@@ -0,0 +1,87 @@
// Builds the browser extension for each browser from the one source in extension/ (docs/BROWSER.md):
//
// node tools/extension.mjs [--out <dir>] [--zip]
//
// writes <out>/firefox/ and <out>/chromium/ (default out: target/extension), each with its manifest.json (the
// browser's manifest.<browser>.json, with the workspace version) and the shared scripts and popup. With --zip
// also custos-<browser>-<version>.zip next to them, reproducible (fixed order and times): the Firefox one is what
// AMO signs, the Chromium one what the Edge and Chrome stores take.
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
const root = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const arg = (name) => {
const i = process.argv.indexOf(name);
return i > 0 ? process.argv[i + 1] : null;
};
const out = path.resolve(arg('--out') ?? path.join(root, 'target', 'extension'));
const zip = process.argv.includes('--zip');
const cargo = fs.readFileSync(path.join(root, 'Cargo.toml'), 'utf8');
const version = /\[workspace\.package\][^[]*?version = "([^"]+)"/s.exec(cargo)?.[1];
if (!version) throw new Error('no workspace version in Cargo.toml');
const SHARED = ['background.js', 'content.js', 'popup.html', 'popup.js', 'popup.css'];
const BROWSERS = ['firefox', 'chromium'];
/** A zip of `files` ([name, bytes]), deflated, with a fixed time: the same input gives the same bytes. */
function zipOf(files) {
const parts = [];
const central = [];
let offset = 0;
const time = 0, date = (2026 - 1980) << 9 | 1 << 5 | 1; // 2026-01-01 00:00
for (const [name, data] of files) {
const n = Buffer.from(name, 'utf8');
const packed = zlib.deflateRawSync(data, { level: 9 });
const crc = zlib.crc32(data);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt16LE(0x0800, 6); // UTF-8 names
local.writeUInt16LE(8, 8);
local.writeUInt16LE(time, 10);
local.writeUInt16LE(date, 12);
local.writeUInt32LE(crc, 14);
local.writeUInt32LE(packed.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(n.length, 26);
parts.push(local, n, packed);
const c = Buffer.alloc(46);
c.writeUInt32LE(0x02014b50, 0);
c.writeUInt16LE(20, 4);
c.writeUInt16LE(20, 6);
c.writeUInt16LE(0x0800, 8);
c.writeUInt16LE(8, 10);
c.writeUInt16LE(time, 12);
c.writeUInt16LE(date, 14);
c.writeUInt32LE(crc, 16);
c.writeUInt32LE(packed.length, 20);
c.writeUInt32LE(data.length, 24);
c.writeUInt16LE(n.length, 28);
c.writeUInt32LE(offset, 42);
central.push(c, n);
offset += 30 + n.length + packed.length;
}
const dir = Buffer.concat(central);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(files.length, 8);
end.writeUInt16LE(files.length, 10);
end.writeUInt32LE(dir.length, 12);
end.writeUInt32LE(offset, 16);
return Buffer.concat([...parts, dir, end]);
}
for (const browser of BROWSERS) {
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'extension', `manifest.${browser}.json`), 'utf8'));
const withVersion = { manifest_version: manifest.manifest_version, name: manifest.name, version, ...manifest };
const files = [['manifest.json', Buffer.from(JSON.stringify(withVersion, null, 2) + '\n')]];
for (const f of SHARED) files.push([f, fs.readFileSync(path.join(root, 'extension', f))]);
const dir = path.join(out, browser);
fs.rmSync(dir, { recursive: true, force: true });
fs.mkdirSync(dir, { recursive: true });
for (const [name, data] of files) fs.writeFileSync(path.join(dir, name), data);
if (zip) fs.writeFileSync(path.join(out, `custos-${browser}-${version}.zip`), zipOf(files));
console.log(`${browser}: ${dir}${zip ? ` (+ custos-${browser}-${version}.zip)` : ''}`);
}