Initial import of BugPass
This commit is contained in:
commit
df3554542c
20 files changed
+1588
No files matched your search
@@ -0,0 +1,60 @@
|
||||
# Build-time parts of the bugpass extension (kept out of extension/ so
|
||||
# they are not zipped into the xpi). Returns { lib, host }.
|
||||
{ pkgs, ext ? ../extension }: let
|
||||
lesspass = pkgs.fetchFromGitHub {
|
||||
owner = "lesspass";
|
||||
repo = "lesspass";
|
||||
rev = "d8f29da390d4492a5ea7c106779c93f71aa976ff";
|
||||
hash = "sha256-4BqNYIQFozNEf+XEMdb3uTqjU9JyadadF9DQUIyMtxk=";
|
||||
};
|
||||
core = "${lesspass}/packages/lesspass/src";
|
||||
in {
|
||||
# lesspass.js (bundled LessPass core) + psl.js (Public Suffix List rules), checked against official vectors.
|
||||
lib = pkgs.runCommand "bugpass-lib" { nativeBuildInputs = [ pkgs.esbuild pkgs.nodejs pkgs.python3 ]; } ''
|
||||
mkdir -p $out
|
||||
echo 'export * from "${core}/index.ts"; export { FingerprintIcons } from "${core}/fingerprint/fingerprint.ts";' > entry.ts
|
||||
esbuild entry.ts --bundle --format=esm --target=es2022 --outfile=$out/lesspass.js
|
||||
|
||||
python3 - ${pkgs.publicsuffix-list}/share/publicsuffix/public_suffix_list.dat > $out/psl.js <<'EOF'
|
||||
import json, sys
|
||||
def idna(rule):
|
||||
return ".".join(l if l in ("*", "!") else l.encode("idna").decode() for l in rule.split("."))
|
||||
rules = []
|
||||
for line in open(sys.argv[1], encoding="utf-8"):
|
||||
r = line.split()[0] if line.strip() else ""
|
||||
if r and not r.startswith("//"):
|
||||
bang = r.startswith("!")
|
||||
rules.append(("!" if bang else "") + idna(r.lstrip("!")))
|
||||
print("export default new Set(" + json.dumps(rules, separators=(",", ":")) + ");")
|
||||
EOF
|
||||
|
||||
cp $out/*.js ${ext}/domain.js ${ext}/icons.js ${ext}/background.js . && cp ${./test.mjs} test.mjs && cp ${./test-bg.mjs} test-bg.mjs
|
||||
node test.mjs && node test-bg.mjs
|
||||
'';
|
||||
|
||||
# Native messaging host: stores profiles (never passwords) in $XDG_DATA_HOME/bugpass/profiles.json.
|
||||
host = pkgs.runCommand "bugpass-host" { nativeBuildInputs = [ pkgs.python3 ]; } ''
|
||||
install -Dm755 ${pkgs.writeScript "bugpass-host" "#!${pkgs.python3}/bin/python3\n${builtins.readFile ./host.py}"} $out/bin/bugpass-host
|
||||
mkdir -p $out/lib/mozilla/native-messaging-hosts
|
||||
cat > $out/lib/mozilla/native-messaging-hosts/bugpass.json <<EOF
|
||||
{"name":"bugpass","description":"BugPass profile storage","path":"$out/bin/bugpass-host","type":"stdio","allowed_extensions":["bugpass@local"]}
|
||||
EOF
|
||||
|
||||
# self-test: framed round trip
|
||||
XDG_DATA_HOME=$TMPDIR python3 - $out/bin/bugpass-host <<'EOF'
|
||||
import json, struct, subprocess, sys
|
||||
msgs = [{"cmd": "save", "profile": {"site": "a.org", "login": "me", "lowercase": True, "uppercase": True,
|
||||
"digits": True, "symbols": False, "length": 20, "counter": 2, "password": "nope"}},
|
||||
{"cmd": "save", "profile": {"site": "a.org", "login": "me", "length": 12}},
|
||||
{"cmd": "list"}, {"cmd": "delete", "site": "a.org", "login": "me"}, {"cmd": "list"}]
|
||||
data = b"".join(struct.pack("=I", len(b)) + b for b in (json.dumps(m).encode() for m in msgs))
|
||||
out = subprocess.run([sys.argv[1]], input=data, capture_output=True, check=True).stdout
|
||||
res = []
|
||||
while out:
|
||||
n, = struct.unpack("=I", out[:4]); res.append(json.loads(out[4:4 + n])); out = out[4 + n:]
|
||||
p = res[2]["profiles"]
|
||||
assert len(p) == 1 and p[0]["length"] == 12 and "password" not in p[0], res
|
||||
assert res[4] == {"profiles": []}, res
|
||||
EOF
|
||||
'';
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
PATH = os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share"), "bugpass", "profiles.json")
|
||||
DEFAULTS = {"lowercase": True, "uppercase": True, "digits": True, "symbols": True, "length": 16, "counter": 1}
|
||||
|
||||
|
||||
def load():
|
||||
try:
|
||||
with open(PATH) as f:
|
||||
return json.load(f)
|
||||
except FileNotFoundError:
|
||||
return []
|
||||
|
||||
|
||||
def store(profiles):
|
||||
os.makedirs(os.path.dirname(PATH), exist_ok=True)
|
||||
tmp = PATH + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump(profiles, f, indent=1)
|
||||
os.replace(tmp, PATH)
|
||||
|
||||
|
||||
def clean(p):
|
||||
# whitelist fields: a master/generated password can never end up on disk
|
||||
out = {"site": str(p["site"]), "login": str(p.get("login", ""))}
|
||||
for k, d in DEFAULTS.items():
|
||||
out[k] = bool(p.get(k, d)) if isinstance(d, bool) else int(p.get(k, d))
|
||||
out["length"] = min(35, max(5, out["length"]))
|
||||
out["counter"] = max(1, out["counter"])
|
||||
return out
|
||||
|
||||
|
||||
def handle(m):
|
||||
profiles = load()
|
||||
if m.get("cmd") == "list":
|
||||
return {"profiles": profiles}
|
||||
if m.get("cmd") == "save":
|
||||
p = clean(m["profile"])
|
||||
key = (p["site"], p["login"])
|
||||
elif m.get("cmd") == "delete":
|
||||
p, key = None, (m["site"], m["login"])
|
||||
else:
|
||||
return {"error": "unknown cmd"}
|
||||
profiles = [q for q in profiles if (q["site"], q["login"]) != key] + ([p] if p else [])
|
||||
store(profiles)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
while (head := sys.stdin.buffer.read(4)) and len(head) == 4:
|
||||
try:
|
||||
reply = handle(json.loads(sys.stdin.buffer.read(struct.unpack("=I", head)[0])))
|
||||
except Exception as e:
|
||||
reply = {"error": str(e)}
|
||||
data = json.dumps(reply).encode()
|
||||
sys.stdout.buffer.write(struct.pack("=I", len(data)) + data)
|
||||
sys.stdout.buffer.flush()
|
||||
@@ -0,0 +1,32 @@
|
||||
// background.js message guard + lock/fill flow, with a mocked `browser`.
|
||||
import assert from "node:assert/strict";
|
||||
globalThis.window = globalThis;
|
||||
const sent = [];
|
||||
const ROOT = "moz-extension://uuid/";
|
||||
globalThis.browser = {
|
||||
runtime: { id: "bugpass@local", getURL: (p) => ROOT + p, onMessage: { addListener() {} }, sendNativeMessage: async () => ({ profiles: [] }) },
|
||||
tabs: { get: async (id) => ({ id, url: id === 1 ? "https://login.example.org/x" : "https://evil.test/" }), sendMessage: async (...a) => { sent.push(a); } },
|
||||
};
|
||||
const { onMessage } = await import("./background.js");
|
||||
const ext = { id: "bugpass@local", url: ROOT + "popup.html" };
|
||||
const page = { id: "bugpass@local", url: "https://example.org/", tab: { id: 1 } };
|
||||
const profile = { site: "example.org", login: "[email protected]", lowercase: true, uppercase: true, digits: true, symbols: true, length: 16, counter: 1 };
|
||||
|
||||
for (const type of ["status", "unlock", "reveal", "fill", "copy", "list", "relay"])
|
||||
await assert.rejects(onMessage({ type, master: "x", profile, tabId: 1 }, page), /forbidden/);
|
||||
assert.deepEqual(await onMessage({ type: "status" }, ext), { unlocked: false });
|
||||
assert.deepEqual(await onMessage({ type: "reveal", profile }, ext), { locked: true });
|
||||
assert.deepEqual(await onMessage({ type: "fill", tabId: 1, profile }, ext), { locked: true });
|
||||
await assert.rejects(onMessage({ type: "unlock", master: "" }, ext));
|
||||
assert.equal((await onMessage({ type: "unlock", master: "password" }, ext)).fingerprint.length, 3);
|
||||
assert.deepEqual(await onMessage({ type: "reveal", profile }, ext), { password: "WHLpUL)e00[iHR+w" });
|
||||
await assert.rejects(onMessage({ type: "fill", tabId: 2, profile }, ext), /not on/);
|
||||
assert.equal(sent.length, 0);
|
||||
await onMessage({ type: "fill", tabId: 1, profile }, ext);
|
||||
assert.deepEqual(sent[0], [1, { type: "fill", username: profile.login, password: "WHLpUL)e00[iHR+w", toast: false }, { frameId: 0 }]);
|
||||
await onMessage({ type: "relay", msg: { type: "fill", password: "x" } }, { ...ext, tab: { id: 1 } });
|
||||
assert.equal(sent.length, 1, "relay must not forward fill");
|
||||
await onMessage({ type: "lock" }, ext);
|
||||
assert.deepEqual(await onMessage({ type: "reveal", profile }, ext), { locked: true });
|
||||
console.log("bugpass: background guard ok");
|
||||
process.exit(0); // idle auto-lock timer
|
||||
@@ -0,0 +1,29 @@
|
||||
import assert from "node:assert/strict";
|
||||
globalThis.window = globalThis; // lesspass' pbkdf2 uses window.crypto
|
||||
const { generatePassword, buildFingerprint, FingerprintIcons } = await import("./lesspass.js");
|
||||
const { getDomain } = await import("./domain.js");
|
||||
const { ICONS } = await import("./icons.js");
|
||||
|
||||
const base = { site: "example.org", login: "[email protected]", lowercase: true, uppercase: true, digits: true, symbols: true, length: 16, counter: 1 };
|
||||
const vectors = [
|
||||
[{}, "WHLpUL)e00[iHR+w"],
|
||||
[{ symbols: false, length: 14, counter: 2 }, "MBAsB7b1Prt8Sl"],
|
||||
[{ lowercase: false, uppercase: false, symbols: false }, "8742368585200667"],
|
||||
[{ digits: false }, "s>{F}RwkN/-fmM.X"],
|
||||
];
|
||||
for (const [opts, want] of vectors) assert.equal(await generatePassword({ ...base, ...opts }, "password"), want);
|
||||
|
||||
assert.deepEqual(await buildFingerprint("password"), [
|
||||
{ color: "#FFB5DA", icon: "fa-flask" },
|
||||
{ color: "#009191", icon: "fa-archive" },
|
||||
{ color: "#B5DAFE", icon: "fa-beer" },
|
||||
]);
|
||||
for (const i of FingerprintIcons) assert.ok(ICONS[i], `no glyph for ${i}`);
|
||||
|
||||
for (const [h, d] of [
|
||||
["git.bug.tools", "bug.tools"], ["x.bbc.co.uk", "bbc.co.uk"], ["example.org", "example.org"],
|
||||
["a.b.example.com", "example.com"], ["www.ck", "www.ck"], ["a.b.foo.ck", "b.foo.ck"],
|
||||
["foo.github.io", "foo.github.io"], ["localhost", "localhost"], ["192.168.1.1", "192.168.1.1"],
|
||||
["[::1]", "[::1]"], ["WWW.Example.COM.", "example.com"],
|
||||
]) assert.equal(getDomain(h), d, h);
|
||||
console.log("bugpass: all vectors ok");
|
||||
Reference in new issue
Block a user