feat: harden bridge origin/CSP, cache decryption, and overhaul the web client UI
This commit is contained in:
parent
f637d5be57
commit
80133da100
10 changed files with 975 additions and 352 deletions
694
web/js/app.js
694
web/js/app.js
|
|
@ -12,12 +12,41 @@ import { connectStream } from "./transport.js";
|
|||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// The status line is a toast: click to dismiss, empty means hidden.
|
||||
// Everything is built as nodes rather than markup, so no message content can
|
||||
// ever reach innerHTML. Null children are dropped, which keeps conditional
|
||||
// pieces inline at the call site.
|
||||
function el(tag, props = {}, ...children) {
|
||||
const node = Object.assign(document.createElement(tag), props);
|
||||
node.append(...children.filter(child => child != null));
|
||||
return node;
|
||||
}
|
||||
|
||||
// SVG lives in its own namespace, so el()'s createElement cannot build these;
|
||||
// each is a reference into the sprite in index.html.
|
||||
function icon(name) {
|
||||
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
svg.setAttribute("class", "icon");
|
||||
svg.setAttribute("aria-hidden", "true");
|
||||
const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
|
||||
use.setAttribute("href", `#i-${name}`);
|
||||
svg.append(use);
|
||||
return svg;
|
||||
}
|
||||
|
||||
const placeholder = (text, warn = false) =>
|
||||
el("p", { className: warn ? "placeholder warn" : "placeholder", textContent: text });
|
||||
|
||||
// The status line is a toast: click to dismiss, empty means hidden. Plain
|
||||
// notices fade; warnings stay until dismissed, since those carry the §4/§8
|
||||
// trust messages the user must actually read.
|
||||
let toastTimer = null;
|
||||
function status(text, warn = false) {
|
||||
const toast = $("status");
|
||||
toast.textContent = text;
|
||||
toast.hidden = !text;
|
||||
toast.className = "toast" + (warn ? " warn" : "");
|
||||
toast.className = warn ? "toast warn" : "toast";
|
||||
clearTimeout(toastTimer);
|
||||
if (text && !warn) toastTimer = setTimeout(() => status(""), 6000);
|
||||
}
|
||||
$("status").onclick = () => status("");
|
||||
|
||||
|
|
@ -34,6 +63,18 @@ const fmtRowTime = (seconds) => {
|
|||
return date.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
|
||||
};
|
||||
|
||||
// A copy button beats asking the user to select 64 hex characters by hand.
|
||||
function copyButton(text, what) {
|
||||
return el("button", { type: "button", className: "copy", textContent: "copy", onclick: async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
status(`${what} copied to the clipboard`);
|
||||
} catch {
|
||||
status(`the clipboard is unavailable; select and copy ${what} by hand`, true);
|
||||
}
|
||||
} });
|
||||
}
|
||||
|
||||
// The stored account as an address object, default port included when custom.
|
||||
function accountAddress() {
|
||||
const account = store.account();
|
||||
|
|
@ -42,6 +83,34 @@ function accountAddress() {
|
|||
return parseAddress(`${account.user}@${account.host}${suffix}`);
|
||||
}
|
||||
|
||||
// --- appearance ----------------------------------------------------------------
|
||||
|
||||
// Three states, because "follow the system" is a real preference and not the
|
||||
// absence of one. The CSS does the rest: color-scheme decides which half of
|
||||
// every light-dark() token applies, so nothing here touches a colour.
|
||||
const THEMES = [
|
||||
{ value: null, icon: "auto", label: "theme: following the system" },
|
||||
{ value: "light", icon: "sun", label: "theme: light" },
|
||||
{ value: "dark", icon: "moon", label: "theme: dark" },
|
||||
];
|
||||
|
||||
function applyTheme() {
|
||||
const mode = THEMES.find(t => t.value === store.theme()) ?? THEMES[0];
|
||||
if (mode.value) document.documentElement.dataset.theme = mode.value;
|
||||
else delete document.documentElement.dataset.theme;
|
||||
const button = $("theme");
|
||||
button.querySelector("use").setAttribute("href", `#i-${mode.icon}`);
|
||||
button.title = mode.label;
|
||||
button.setAttribute("aria-label", mode.label);
|
||||
}
|
||||
|
||||
$("theme").onclick = () => {
|
||||
const current = THEMES.findIndex(t => t.value === store.theme());
|
||||
store.setTheme(THEMES[(current + 1) % THEMES.length].value);
|
||||
applyTheme();
|
||||
status(THEMES.find(t => t.value === store.theme()).label);
|
||||
};
|
||||
|
||||
// --- connection --------------------------------------------------------------
|
||||
|
||||
// §4: registration and fetching demand a pinned key; sending to a recipient
|
||||
|
|
@ -61,15 +130,21 @@ async function connect(addr, { requirePin }) {
|
|||
|
||||
// --- identity setup ------------------------------------------------------------
|
||||
|
||||
// Nothing in the top bar works before an identity exists, so it stays hidden
|
||||
// rather than offering buttons that can only answer "no identity yet".
|
||||
function showSetup() {
|
||||
$("setup").hidden = false;
|
||||
$("app").hidden = true;
|
||||
$("search").hidden = true;
|
||||
$("top-actions").hidden = true;
|
||||
$("account").textContent = "";
|
||||
}
|
||||
|
||||
function showApp() {
|
||||
$("setup").hidden = true;
|
||||
$("app").hidden = false;
|
||||
$("search").hidden = false;
|
||||
$("top-actions").hidden = false;
|
||||
renderAccount();
|
||||
renderFolder();
|
||||
}
|
||||
|
|
@ -109,11 +184,22 @@ function renderAccount() {
|
|||
|
||||
let folder = "inbox";
|
||||
let selectedId = null;
|
||||
let query = "";
|
||||
// Bumped per render, so a superseded pass stops appending rows mid-flight.
|
||||
let renderToken = 0;
|
||||
// Rows opened per turn: a cold folder yields between batches rather than
|
||||
// blocking the tab for an X25519 and an Ed25519 verification per message.
|
||||
const BATCH = 20;
|
||||
|
||||
for (const button of $("folders").querySelectorAll("button"))
|
||||
button.onclick = () => {
|
||||
folder = button.dataset.folder;
|
||||
for (const b of $("folders").querySelectorAll("button")) b.classList.toggle("active", b === button);
|
||||
for (const b of $("folders").querySelectorAll("button")) {
|
||||
const active = b === button;
|
||||
b.classList.toggle("active", active);
|
||||
if (active) b.setAttribute("aria-current", "true");
|
||||
else b.removeAttribute("aria-current");
|
||||
}
|
||||
selectedId = null;
|
||||
resetView();
|
||||
renderFolder();
|
||||
|
|
@ -122,90 +208,159 @@ for (const button of $("folders").querySelectorAll("button"))
|
|||
// The reader empties when a folder changes, so a stale message cannot linger
|
||||
// under a different list.
|
||||
function resetView() {
|
||||
$("view").replaceChildren(Object.assign(document.createElement("p"),
|
||||
{ className: "placeholder", textContent: "select a message" }));
|
||||
$("app").classList.remove("reading");
|
||||
$("view").replaceChildren(placeholder(folder === "contacts"
|
||||
? "contacts and their keys are listed alongside"
|
||||
: "select a message"));
|
||||
}
|
||||
|
||||
// Counted from ids and read markers alone, independent of the visible folder —
|
||||
// leaving the inbox used to blank the badge.
|
||||
async function updateUnreadBadge() {
|
||||
$("count-inbox").textContent = (await store.unreadCount()) || "";
|
||||
}
|
||||
|
||||
async function renderFolder() {
|
||||
const list = $("list");
|
||||
if (folder === "contacts") return renderContacts(list);
|
||||
const rows = [...await store.listMessages(folder)].reverse(); // newest first
|
||||
updateUnreadBadge();
|
||||
// The toolbar carries the current folder's action, not a fixed one.
|
||||
const contacts = folder === "contacts";
|
||||
$("mail-tools").hidden = contacts;
|
||||
$("import-form").hidden = !contacts;
|
||||
// The filter never reaches past the open folder, so the field says which one.
|
||||
$("search").placeholder = `search ${folder}`;
|
||||
$("search").setAttribute("aria-label", `search ${folder}`);
|
||||
if (contacts) return renderContacts(list);
|
||||
const token = ++renderToken;
|
||||
const rows = await store.listMessages(folder); // newest first
|
||||
if (token !== renderToken) return;
|
||||
list.replaceChildren();
|
||||
let unread = 0;
|
||||
for (const row of rows) {
|
||||
const opened = describe(row);
|
||||
const isUnread = !store.isRead(row.id);
|
||||
if (folder === "inbox" && isUnread) unread++;
|
||||
const item = document.createElement("div");
|
||||
item.className = `item${row.id === selectedId ? " selected" : ""}${isUnread ? " unread" : ""}`;
|
||||
const who = document.createElement("div");
|
||||
who.className = "who";
|
||||
who.textContent = folder === "sent" ? row.recipient : (opened.fromShort ?? "?");
|
||||
const mid = document.createElement("div");
|
||||
mid.className = "mid";
|
||||
const subject = document.createElement("span");
|
||||
subject.className = "subject";
|
||||
subject.textContent = opened.error ? `<unreadable: ${opened.error}>`
|
||||
: (opened.subject || "(no subject)");
|
||||
const snippet = document.createElement("span");
|
||||
snippet.className = "snippet";
|
||||
snippet.textContent = opened.error ? "" : ` — ${opened.snippet}`;
|
||||
mid.append(subject, snippet);
|
||||
const when = document.createElement("div");
|
||||
when.className = "when";
|
||||
when.textContent = fmtRowTime(folder === "sent" ? row.sentAt : (opened.time ?? row.receivedAt));
|
||||
item.append(who, mid, when);
|
||||
item.onclick = () => openMessage(row.id);
|
||||
list.append(item);
|
||||
if (!rows.length) {
|
||||
list.append(placeholder(folder === "inbox" ? "no mail — fetch" : "nothing sent"));
|
||||
return void updateListStatus();
|
||||
}
|
||||
for (let offset = 0; offset < rows.length; offset += BATCH) {
|
||||
if (offset) await new Promise(resolve => setTimeout(resolve));
|
||||
if (token !== renderToken) return;
|
||||
list.append(...rows.slice(offset, offset + BATCH).map(messageRow));
|
||||
applyQuery();
|
||||
}
|
||||
$("count-inbox").textContent = folder === "inbox" && unread ? String(unread) : "";
|
||||
if (!rows.length) list.append(Object.assign(document.createElement("p"),
|
||||
{ className: "placeholder", textContent: folder === "inbox" ? "no mail — fetch" : "nothing sent" }));
|
||||
}
|
||||
|
||||
// The header search filters the rendered list client-side; nothing leaves the page.
|
||||
$("search").oninput = () => {
|
||||
const query = $("search").value.trim().toLowerCase();
|
||||
// A real button, so every row is reachable and openable from the keyboard.
|
||||
function messageRow(row) {
|
||||
const opened = describe(row);
|
||||
// Only the inbox has a read state; sent copies were never "unread".
|
||||
const unread = folder === "inbox" && !store.isRead(row.id);
|
||||
const item = el("button", {
|
||||
type: "button",
|
||||
className: `item${row.id === selectedId ? " selected" : ""}${unread ? " unread" : ""}`,
|
||||
onclick: () => openMessage(row.id),
|
||||
});
|
||||
if (row.id === selectedId) item.setAttribute("aria-current", "true");
|
||||
const who = el("div", { className: "who",
|
||||
textContent: folder === "sent" ? row.recipient : (opened.fromShort ?? "?") });
|
||||
if (folder === "inbox" && !opened.error && !opened.knownSender)
|
||||
who.append(el("span", { className: "dot", title: "sender key not bound to an address" }));
|
||||
item.append(who,
|
||||
el("div", { className: "mid" },
|
||||
el("span", { className: "subject", textContent: opened.error
|
||||
? `<unreadable: ${opened.error}>` : (opened.subject || "(no subject)") }),
|
||||
el("span", { className: "snippet", textContent: opened.error ? "" : ` — ${opened.snippet}` })),
|
||||
el("div", { className: "when",
|
||||
textContent: fmtRowTime(folder === "sent" ? row.sentAt : (opened.time ?? row.receivedAt)) }));
|
||||
// Sender or recipient, their key, the subject and the whole body — not the
|
||||
// snippet, and not the timestamp.
|
||||
item.dataset.search = (opened.error
|
||||
? `${row.recipient ?? ""} ${opened.error}`
|
||||
: [row.recipient ?? "", opened.from, b32encode(opened.sender), opened.subject, opened.body].join(" ")
|
||||
).toLowerCase();
|
||||
return item;
|
||||
}
|
||||
|
||||
// Filters the current folder client-side; nothing leaves the page. Each row
|
||||
// carries its own haystack, built from the fields worth matching rather than
|
||||
// from whatever the row happens to render. Re-applied after every render, so a
|
||||
// redraw cannot silently drop it.
|
||||
function applyQuery() {
|
||||
for (const item of $("list").querySelectorAll(".item"))
|
||||
item.hidden = Boolean(query) && !item.textContent.toLowerCase().includes(query);
|
||||
item.hidden = Boolean(query) && !(item.dataset.search ?? "").includes(query);
|
||||
updateListStatus();
|
||||
}
|
||||
|
||||
// The toolbar's right side, which also makes a narrowed search visible.
|
||||
function updateListStatus() {
|
||||
const items = [...$("list").querySelectorAll(".item")];
|
||||
const shown = items.filter(item => !item.hidden).length;
|
||||
$("list-status").textContent = !items.length ? ""
|
||||
: shown === items.length ? `${items.length} message${items.length === 1 ? "" : "s"}`
|
||||
: `${shown} of ${items.length}`;
|
||||
}
|
||||
|
||||
$("search").oninput = () => {
|
||||
query = $("search").value.trim().toLowerCase();
|
||||
applyQuery();
|
||||
};
|
||||
|
||||
// Open an envelope and split its body; anything unreadable shows as such
|
||||
// rather than throwing, so one bad message cannot blank the list. The wire
|
||||
// carries no sender name, so an unknown key can only be shown as its
|
||||
// fingerprint until the user binds it to an address — which a signed Reply-To
|
||||
// Opening an envelope costs an X25519 agreement and an Ed25519 verification, and
|
||||
// an envelope's plaintext never changes — so the result is kept. Failures are
|
||||
// cached too, so one bad message is not retried on every render.
|
||||
const openedCache = new Map();
|
||||
|
||||
function openEnvelope(row) {
|
||||
let entry = openedCache.get(row.id);
|
||||
if (!entry) {
|
||||
try {
|
||||
const opened = unseal(store.identities(), row.envelope);
|
||||
const { fields, body } = parseFrontmatter(new TextDecoder().decode(opened.body));
|
||||
entry = { ...opened, fields, body,
|
||||
subject: fields.Subject || "",
|
||||
snippet: body.replace(/\s+/g, " ").trim().slice(0, 140) };
|
||||
} catch (err) {
|
||||
entry = { error: err.message };
|
||||
}
|
||||
openedCache.set(row.id, entry);
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
// What is known about a sender changes as the user binds addresses to keys, so
|
||||
// this layer sits over the cached envelope and is recomputed per render — it is
|
||||
// a map lookup, not crypto. The wire carries no sender name, so an unknown key
|
||||
// can only be shown as its fingerprint until bound, which a signed Reply-To
|
||||
// field lets the sender do in-band.
|
||||
function describe(row) {
|
||||
try {
|
||||
const opened = unseal(store.identities(), row.envelope);
|
||||
const { fields, body } = parseFrontmatter(new TextDecoder().decode(opened.body));
|
||||
const known = store.addressForKey(opened.sender);
|
||||
let replyAddress = null;
|
||||
if (fields["Reply-To"]) {
|
||||
try {
|
||||
const claimed = parseAddress(fields["Reply-To"]);
|
||||
// Only a full smol:// address whose key matches the signer counts;
|
||||
// anything else is ordinary text.
|
||||
if (claimed.identity && timingSafeEqual(claimed.identity, opened.sender))
|
||||
replyAddress = claimed;
|
||||
} catch { /* malformed claim: display, never bind */ }
|
||||
}
|
||||
return {
|
||||
...opened,
|
||||
fields, body,
|
||||
subject: fields.Subject || "",
|
||||
snippet: body.replace(/\s+/g, " ").trim().slice(0, 140),
|
||||
from: known ?? `unknown · ${fingerprint(opened.sender)}`,
|
||||
// rows stay narrow: the full fingerprint belongs to the reader
|
||||
fromShort: known ?? `unknown · ${b32encode(opened.sender).slice(0, 4)}`,
|
||||
knownSender: Boolean(known),
|
||||
replyAddress,
|
||||
};
|
||||
} catch (err) {
|
||||
return { error: err.message };
|
||||
const opened = openEnvelope(row);
|
||||
if (opened.error) return opened;
|
||||
const known = store.addressForKey(opened.sender);
|
||||
let replyAddress = null;
|
||||
if (opened.fields["Reply-To"]) {
|
||||
try {
|
||||
const claimed = parseAddress(opened.fields["Reply-To"]);
|
||||
// Only a full smol:// address whose key matches the signer counts;
|
||||
// anything else is ordinary text.
|
||||
if (claimed.identity && timingSafeEqual(claimed.identity, opened.sender))
|
||||
replyAddress = claimed;
|
||||
} catch { /* malformed claim: display, never bind */ }
|
||||
}
|
||||
return {
|
||||
...opened,
|
||||
from: known ?? "unknown sender",
|
||||
// rows stay narrow: the full fingerprint belongs to the reader
|
||||
fromShort: known ?? `unknown · ${b32encode(opened.sender).slice(0, 4)}`,
|
||||
knownSender: Boolean(known),
|
||||
verifiedSender: Boolean(known && store.contact(known)?.verified),
|
||||
replyAddress,
|
||||
};
|
||||
}
|
||||
|
||||
// A label/value row; `empty` marks a value that is guidance rather than data.
|
||||
const field = (label, value, empty = false, extra = null) =>
|
||||
el("div", { className: "field" },
|
||||
el("span", { className: "field-label", textContent: label }),
|
||||
el("span", { className: empty ? "field-value empty" : "field-value", textContent: value }),
|
||||
extra);
|
||||
|
||||
// --- reading ------------------------------------------------------------------
|
||||
|
||||
async function openMessage(id) {
|
||||
|
|
@ -216,97 +371,98 @@ async function openMessage(id) {
|
|||
renderFolder();
|
||||
const opened = describe(row);
|
||||
const view = $("view");
|
||||
if (opened.error) {
|
||||
view.replaceChildren();
|
||||
const note = document.createElement("p");
|
||||
note.className = "placeholder warn";
|
||||
note.textContent = opened.error;
|
||||
view.append(note);
|
||||
return;
|
||||
}
|
||||
// Under the narrow breakpoint the reader covers the list, so it needs a way back.
|
||||
$("app").classList.add("reading");
|
||||
const back = el("button", { type: "button", className: "back",
|
||||
onclick: () => { $("app").classList.remove("reading"); } }, icon("back"), "messages");
|
||||
if (opened.error) return void view.replaceChildren(back, placeholder(opened.error, true));
|
||||
|
||||
const fields = Object.entries(opened.fields).filter(([k]) => k !== "Subject");
|
||||
view.innerHTML = `<h2></h2><div class="meta"></div><div class="fields"></div>` +
|
||||
`<div class="verified">signature verified</div><pre></pre><div class="actions"></div>`;
|
||||
view.querySelector("h2").textContent = opened.subject || "(no subject)";
|
||||
view.querySelector(".meta").textContent = folder === "sent"
|
||||
? `to: ${row.recipient}\nid: ${row.id}\nsent: ${fmtTime(row.sentAt)}`
|
||||
: `from: ${opened.from}\nkey: ${b32encode(opened.sender)}\nid: ${row.id}\ndate: ${fmtTime(opened.time)}`;
|
||||
view.querySelector(".fields").textContent = fields.map(([k, v]) => `${k}: ${v}`).join("\n");
|
||||
view.querySelector("pre").textContent = opened.body;
|
||||
const actions = view.querySelector(".actions");
|
||||
if (folder === "inbox") {
|
||||
if (opened.knownSender) {
|
||||
actions.append(replyButton(opened, row));
|
||||
} else if (opened.replyAddress) {
|
||||
// The sender signed their own smol:// address into the payload, so
|
||||
// binding it is one click. A pinned conflicting key is refused (§8).
|
||||
const note = document.createElement("p");
|
||||
note.className = "placeholder";
|
||||
note.textContent =
|
||||
`this message carries the sender's signed address: ${opened.replyAddress.short}`;
|
||||
actions.before(note);
|
||||
const save = document.createElement("button");
|
||||
save.textContent = "save sender & reply";
|
||||
save.onclick = () => {
|
||||
try {
|
||||
saveReplyAddress(opened.replyAddress, opened.sender);
|
||||
openMessage(row.id);
|
||||
openCompose({
|
||||
to: opened.replyAddress.short,
|
||||
subject: opened.subject ? (opened.subject.startsWith("Re:") ? opened.subject : `Re: ${opened.subject}`) : "",
|
||||
replyTo: row.id,
|
||||
});
|
||||
} catch (err) {
|
||||
status(err.message, true);
|
||||
}
|
||||
};
|
||||
actions.append(save);
|
||||
} else {
|
||||
// The wire gives only a signed key; a reply needs the sender's address,
|
||||
// which the user supplies once and we bind to that exact key.
|
||||
const note = document.createElement("p");
|
||||
note.className = "placeholder";
|
||||
note.textContent = "The wire carries no sender name, only this signed key. " +
|
||||
"To reply, give the sender's address — it is checked against this key:";
|
||||
const form = document.createElement("form");
|
||||
form.className = "name-sender";
|
||||
const input = document.createElement("input");
|
||||
input.placeholder = "alice@example.org or smol://…";
|
||||
input.spellcheck = false;
|
||||
const name = document.createElement("button");
|
||||
name.textContent = "name sender & reply";
|
||||
form.append(input, name);
|
||||
form.onsubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
name.disabled = true;
|
||||
try {
|
||||
await nameSender(input.value, opened.sender);
|
||||
openMessage(row.id); // the sender is named now; the reply button appears
|
||||
openCompose({
|
||||
to: store.addressForKey(opened.sender),
|
||||
subject: opened.subject ? (opened.subject.startsWith("Re:") ? opened.subject : `Re: ${opened.subject}`) : "",
|
||||
replyTo: row.id,
|
||||
});
|
||||
} catch (err) {
|
||||
status(err.message, true);
|
||||
} finally {
|
||||
name.disabled = false;
|
||||
}
|
||||
};
|
||||
actions.append(note, form);
|
||||
}
|
||||
const actions = el("div", { className: "actions" });
|
||||
view.replaceChildren(...[
|
||||
back,
|
||||
el("h2", { textContent: opened.subject || "(no subject)" }),
|
||||
el("div", { className: "meta", textContent: folder === "sent"
|
||||
? `to: ${row.recipient}\nid: ${row.id}\nsent: ${fmtTime(row.sentAt)}`
|
||||
: `from: ${opened.from}\nid: ${row.id}\ndate: ${fmtTime(opened.time)}` }),
|
||||
trustRow(opened),
|
||||
fields.length ? el("div", { className: "fields",
|
||||
textContent: fields.map(([k, v]) => `${k}: ${v}`).join("\n") }) : null,
|
||||
el("pre", { textContent: opened.body }),
|
||||
actions,
|
||||
].filter(node => node != null));
|
||||
if (folder !== "inbox") return;
|
||||
|
||||
if (opened.knownSender) {
|
||||
actions.append(el("button", { type: "button", onclick: () => startReply(row) },
|
||||
icon("reply"), "reply"));
|
||||
} else if (opened.replyAddress) {
|
||||
// The sender signed their own smol:// address into the payload, so binding
|
||||
// it is one click. A pinned conflicting key is refused (§8).
|
||||
actions.before(placeholder(
|
||||
`this message carries the sender's signed address: ${opened.replyAddress.short}`));
|
||||
actions.append(el("button", { type: "button", textContent: "save sender & reply", onclick: () => {
|
||||
try {
|
||||
saveReplyAddress(opened.replyAddress, opened.sender);
|
||||
openMessage(row.id);
|
||||
startReply(row);
|
||||
} catch (err) {
|
||||
status(err.message, true);
|
||||
}
|
||||
} }));
|
||||
} else {
|
||||
// The wire gives only a signed key; a reply needs the sender's address,
|
||||
// which the user supplies once and we bind to that exact key.
|
||||
const input = el("input", { placeholder: "alice@example.org or smol://…", spellcheck: false });
|
||||
const submit = el("button", { textContent: "name sender & reply" });
|
||||
const form = el("form", { className: "name-sender" }, input, submit);
|
||||
form.onsubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
submit.disabled = true;
|
||||
try {
|
||||
await nameSender(input.value, opened.sender);
|
||||
openMessage(row.id); // the sender is named now; the reply button appears
|
||||
startReply(row);
|
||||
} catch (err) {
|
||||
status(err.message, true);
|
||||
} finally {
|
||||
submit.disabled = false;
|
||||
}
|
||||
};
|
||||
actions.before(placeholder("The wire carries no sender name, only this signed key. " +
|
||||
"To reply, give the sender's address — it is checked against this key:"));
|
||||
actions.append(form);
|
||||
}
|
||||
}
|
||||
|
||||
function replyButton(opened, row) {
|
||||
const reply = document.createElement("button");
|
||||
reply.textContent = "reply";
|
||||
reply.onclick = () => openCompose({
|
||||
// §4/§8: a signature always verifies here, because unseal() throws otherwise.
|
||||
// What can be weak is the binding between that key and an address, so that is
|
||||
// what the chip reports.
|
||||
function trustRow(opened) {
|
||||
if (folder === "sent")
|
||||
return el("div", { className: "trust" },
|
||||
el("span", { className: "badge", textContent: "your own sealed copy" }));
|
||||
const chip = opened.verifiedSender ? ["badge ok", "verified sender key"]
|
||||
: opened.knownSender ? ["badge", "key pinned on first use"]
|
||||
: ["badge alert", "key bound to no address"];
|
||||
return el("div", { className: "trust" },
|
||||
el("span", { className: chip[0], textContent: chip[1] }),
|
||||
el("div", { className: "keyblock" },
|
||||
el("div", { textContent: fingerprint(opened.sender) }),
|
||||
el("div", { className: "full", textContent: b32encode(opened.sender) })));
|
||||
}
|
||||
|
||||
const replySubject = (subject) =>
|
||||
!subject ? "" : subject.startsWith("Re:") ? subject : `Re: ${subject}`;
|
||||
|
||||
// One path for all three ways a reply can start, so the Re: rule lives once.
|
||||
function startReply(row) {
|
||||
const opened = describe(row);
|
||||
openCompose({
|
||||
to: store.addressForKey(opened.sender) ?? "",
|
||||
subject: opened.subject ? (opened.subject.startsWith("Re:") ? opened.subject : `Re: ${opened.subject}`) : "",
|
||||
subject: replySubject(opened.subject),
|
||||
replyTo: row.id,
|
||||
});
|
||||
return reply;
|
||||
}
|
||||
|
||||
// Bind a user-supplied address to the key that signed a message. A smol://
|
||||
|
|
@ -360,20 +516,25 @@ function openCompose({ to = "", subject = "", body = "", replyTo = null } = {})
|
|||
|
||||
$("write").onclick = () => openCompose();
|
||||
|
||||
$("compose-cancel").onclick = () => compose.close();
|
||||
|
||||
// Every submission is a send: cancel is a plain button, and Enter in a field
|
||||
// submits with no submitter — which the old check read as cancel, discarding
|
||||
// the draft.
|
||||
compose.querySelector("form").onsubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
if (event.submitter?.value !== "send") {
|
||||
compose.close();
|
||||
return;
|
||||
}
|
||||
const form = event.target;
|
||||
const send = $("send");
|
||||
$("compose-error").textContent = "";
|
||||
send.disabled = true; // one click, one envelope: a second seals a second message
|
||||
try {
|
||||
await sendMail(form.to.value, form.subject.value, form.body.value, form.dataset.replyTo,
|
||||
form.elements.anonymous.checked);
|
||||
compose.close();
|
||||
} catch (err) {
|
||||
$("compose-error").textContent = err.message;
|
||||
} finally {
|
||||
send.disabled = false;
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -434,8 +595,13 @@ $("fetch").onclick = async () => {
|
|||
const addr = accountAddress();
|
||||
if (!me) return status("no identity yet", true);
|
||||
if (!addr) return status("not registered; register in settings first", true);
|
||||
const button = $("fetch"), label = button.querySelector(".label");
|
||||
const resting = label.textContent;
|
||||
button.disabled = true; // one session at a time; the icon spins while it is
|
||||
label.textContent = "fetching…";
|
||||
status("fetching…");
|
||||
let stored = 0, rejected = 0;
|
||||
let stored = 0;
|
||||
const rejected = [];
|
||||
try {
|
||||
const opened = await connect(addr, { requirePin: true });
|
||||
try {
|
||||
|
|
@ -451,9 +617,9 @@ $("fetch").onclick = async () => {
|
|||
unseal(store.identities(), record.envelope);
|
||||
} catch (err) {
|
||||
// Left on the server rather than destroyed, so a client-side bug
|
||||
// cannot lose mail.
|
||||
rejected++;
|
||||
status(`${hex(record.id)}: ${err.message}; left on server`, true);
|
||||
// cannot lose mail. Collected rather than announced, because the
|
||||
// closing summary would overwrite each one in turn.
|
||||
rejected.push(`${hex(record.id)}: ${err.message}`);
|
||||
continue;
|
||||
}
|
||||
if (await store.storeIfNew("inbox", {
|
||||
|
|
@ -467,9 +633,14 @@ $("fetch").onclick = async () => {
|
|||
} finally {
|
||||
opened.session.stream.close();
|
||||
}
|
||||
status(`${stored} new, ${rejected} rejected` + (rejected ? " (left on the server)" : ""));
|
||||
status([`${stored} new, ${rejected.length} rejected`, ...rejected.map(line => ` ${line}`),
|
||||
rejected.length ? "left on the server" : null].filter(Boolean).join("\n"),
|
||||
rejected.length > 0);
|
||||
} catch (err) {
|
||||
status(err.message, true);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
label.textContent = resting;
|
||||
}
|
||||
renderFolder();
|
||||
};
|
||||
|
|
@ -477,30 +648,73 @@ $("fetch").onclick = async () => {
|
|||
// --- contacts -------------------------------------------------------------------
|
||||
|
||||
function renderContacts(list) {
|
||||
list.replaceChildren();
|
||||
const contacts = store.allContacts();
|
||||
for (const { address, key, verified } of contacts) {
|
||||
const item = document.createElement("div");
|
||||
item.className = "item contact";
|
||||
const who = document.createElement("div");
|
||||
who.className = "who";
|
||||
who.textContent = address;
|
||||
const mid = document.createElement("div");
|
||||
mid.className = "mid";
|
||||
const fp = document.createElement("div");
|
||||
fp.textContent = fingerprint(b32decode(key));
|
||||
const badge = document.createElement("span");
|
||||
badge.className = verified ? "badge ok" : "badge";
|
||||
badge.textContent = verified ? "verified key" : "tofu";
|
||||
mid.append(fp, badge);
|
||||
const refresh = document.createElement("button");
|
||||
refresh.textContent = "refresh";
|
||||
refresh.onclick = () => refreshContact(address);
|
||||
item.append(who, mid, refresh);
|
||||
list.append(item);
|
||||
}
|
||||
if (!contacts.length) list.append(Object.assign(document.createElement("p"),
|
||||
{ className: "placeholder", textContent: "no contacts; import a smol:// address or write to someone" }));
|
||||
list.replaceChildren(...contacts.map(({ address, key, verified, history }) => {
|
||||
const item = el("button", {
|
||||
type: "button",
|
||||
className: `item contact${address === selectedId ? " selected" : ""}`,
|
||||
onclick: () => openContact(address),
|
||||
});
|
||||
if (address === selectedId) item.setAttribute("aria-current", "true");
|
||||
item.append(
|
||||
el("div", { className: "who", textContent: address }),
|
||||
el("div", { className: "mid" },
|
||||
el("div", { textContent: fingerprint(b32decode(key)) }),
|
||||
el("span", { className: verified ? "badge ok" : "badge",
|
||||
textContent: verified ? "verified key" : "tofu" }),
|
||||
history.length ? el("span", { className: "badge",
|
||||
textContent: `${history.length} previous` }) : null));
|
||||
item.dataset.search =
|
||||
`${address} ${key} ${fingerprint(b32decode(key))} ${history.map(h => h.key).join(" ")}`.toLowerCase();
|
||||
return item;
|
||||
}));
|
||||
if (!contacts.length)
|
||||
list.append(placeholder("no contacts yet — import a smol:// address above, or write to someone"));
|
||||
}
|
||||
|
||||
// The full key, the address to hand out, and any key this one replaced — the
|
||||
// row can only afford a fingerprint, and §8 turns on the user being able to
|
||||
// inspect exactly what changed.
|
||||
function openContact(address) {
|
||||
const known = store.contact(address);
|
||||
if (!known) return;
|
||||
selectedId = address;
|
||||
renderFolder();
|
||||
const addr = parseAddress(address);
|
||||
const view = $("view");
|
||||
$("app").classList.add("reading");
|
||||
|
||||
const refresh = el("button", { type: "button", onclick: async (event) => {
|
||||
event.target.disabled = true;
|
||||
try {
|
||||
await refreshContact(address);
|
||||
} finally {
|
||||
event.target.disabled = false;
|
||||
}
|
||||
} }, icon("refresh"), "re-resolve");
|
||||
|
||||
view.replaceChildren(...[
|
||||
el("button", { type: "button", className: "back",
|
||||
onclick: () => { $("app").classList.remove("reading"); } }, icon("back"), "contacts"),
|
||||
el("h2", { textContent: address }),
|
||||
el("div", { className: "trust" },
|
||||
el("span", { className: known.verified ? "badge ok" : "badge",
|
||||
textContent: known.verified ? "verified key" : "key pinned on first use" })),
|
||||
field("fingerprint", fingerprint(known.key)),
|
||||
field("public key", b32encode(known.key)),
|
||||
field("address", addr.uri(known.key), false, copyButton(addr.uri(known.key), "the address")),
|
||||
known.history.length ? el("section", { className: "history" },
|
||||
el("h3", { textContent: `previous keys (${known.history.length})` }),
|
||||
el("p", { className: "hint", textContent:
|
||||
"Replaced by a signed rotation chain (SPEC.md §7). Mail signed with these was sent " +
|
||||
"before the change; rotation is not revocation, so a stolen key can still rotate onward." }),
|
||||
...known.history.map(({ key, until }) => el("div", { className: "keyblock" },
|
||||
el("div", { textContent: fingerprint(b32decode(key)) }),
|
||||
el("div", { className: "full", textContent: key }),
|
||||
el("div", { className: "replaced", textContent: `replaced ${fmtTime(Math.floor(until / 1000))}` }))))
|
||||
: null,
|
||||
el("div", { className: "actions" }, refresh),
|
||||
].filter(node => node != null));
|
||||
}
|
||||
|
||||
// Re-resolve a contact and apply §8: a valid rotation chain is accepted and
|
||||
|
|
@ -532,7 +746,8 @@ async function refreshContact(address) {
|
|||
} catch (err) {
|
||||
status(err.message, true);
|
||||
}
|
||||
renderFolder();
|
||||
if (folder === "contacts" && selectedId === address) openContact(address);
|
||||
else renderFolder();
|
||||
}
|
||||
|
||||
// --- settings ---------------------------------------------------------------------
|
||||
|
|
@ -547,50 +762,69 @@ function openSettings() {
|
|||
$("settings-open").onclick = openSettings;
|
||||
$("settings-close").onclick = () => settings.close();
|
||||
|
||||
// Registering against an unpinned server is refused, so the dialog is ordered
|
||||
// by what depends on what; the chips say how far along that order you are.
|
||||
function step(id, done) {
|
||||
const chip = $(id);
|
||||
chip.classList.toggle("done", done);
|
||||
chip.textContent = done ? "\u2713" : chip.dataset.n;
|
||||
}
|
||||
|
||||
function renderSettings() {
|
||||
const me = store.identity();
|
||||
const account = store.account();
|
||||
const pins = store.allPins();
|
||||
|
||||
step("step-server", pins.length > 0);
|
||||
step("step-address", Boolean(account));
|
||||
|
||||
$("pins").replaceChildren(...pins.map(({ host, key }) =>
|
||||
el("li", {},
|
||||
el("span", { textContent: host }),
|
||||
el("span", { className: "key", textContent: key }),
|
||||
el("button", { type: "button", textContent: "remove",
|
||||
onclick: () => { store.unpinServer(host); renderSettings(); } }))));
|
||||
if (!pins.length)
|
||||
$("pins").append(el("li", { className: "placeholder", textContent: "no server pinned yet" }));
|
||||
|
||||
const card = $("identity-card");
|
||||
card.replaceChildren();
|
||||
if (!me) return;
|
||||
const lines = [
|
||||
`fingerprint: ${fingerprint(me.publicKey)}`,
|
||||
`address: ${account ? account.user + "@" + account.host : "(not registered)"}`,
|
||||
`share: ${account ? accountAddress().uri(me.publicKey) : "(register to get a shareable address)"}`,
|
||||
"",
|
||||
];
|
||||
for (const text of lines) {
|
||||
const div = document.createElement("div");
|
||||
div.textContent = text;
|
||||
card.append(div);
|
||||
}
|
||||
const seed = document.createElement("div");
|
||||
seed.className = "seed";
|
||||
seed.textContent = hex(me.seed);
|
||||
const warning = document.createElement("div");
|
||||
warning.className = "warn";
|
||||
warning.textContent = "back this seed up; it is the only secret";
|
||||
const retired = document.createElement("div");
|
||||
retired.textContent = `retired keys: ${store.identities().length - 1} (kept to read old mail)`;
|
||||
card.append(seed, warning, retired);
|
||||
const share = account ? accountAddress().uri(me.publicKey) : null;
|
||||
const retired = store.identities().length - 1;
|
||||
|
||||
const pins = $("pins");
|
||||
pins.replaceChildren();
|
||||
for (const { host, key } of store.allPins()) {
|
||||
const li = document.createElement("li");
|
||||
const name = document.createElement("span");
|
||||
name.textContent = host;
|
||||
const value = document.createElement("span");
|
||||
value.className = "key";
|
||||
value.textContent = key;
|
||||
const remove = document.createElement("button");
|
||||
remove.textContent = "remove";
|
||||
remove.onclick = () => { store.unpinServer(host); renderSettings(); };
|
||||
li.append(name, value, remove);
|
||||
pins.append(li);
|
||||
}
|
||||
if (!store.allPins().length) pins.append(Object.assign(document.createElement("li"),
|
||||
{ className: "placeholder", textContent: "no pinned servers" }));
|
||||
// Settings opens by itself right after an identity is created, which is a poor
|
||||
// moment to paint the only secret across the screen — so it is asked for.
|
||||
const masked = "\u2022".repeat(64);
|
||||
const seed = el("div", { className: "seed", textContent: masked });
|
||||
const reveal = el("button", { type: "button", textContent: "reveal", onclick: () => {
|
||||
const showing = seed.textContent !== masked;
|
||||
seed.textContent = showing ? masked : hex(me.seed);
|
||||
reveal.textContent = showing ? "reveal" : "hide";
|
||||
} });
|
||||
|
||||
card.append(...[
|
||||
field("fingerprint", fingerprint(me.publicKey)),
|
||||
field("address", account ? `${account.user}@${account.host}` : "not registered yet", !account),
|
||||
field("shareable", share ?? "register above to get one", !share,
|
||||
share ? copyButton(share, "your address") : null),
|
||||
el("div", { className: "seed-card" },
|
||||
el("h4", { textContent: "recovery seed" }),
|
||||
el("div", { className: "row" }, seed, reveal, copyButton(hex(me.seed), "the seed")),
|
||||
el("p", { textContent: "The only secret there is. Anyone who holds it can read your mail and " +
|
||||
"write as you, and losing it loses the address with it — there is no reset. Copy it " +
|
||||
"somewhere safe now." })),
|
||||
field("retired keys", String(retired)),
|
||||
retired ? el("p", { className: "hint",
|
||||
textContent: "Kept so mail sealed to a superseded key stays readable." }) : null,
|
||||
el("details", {},
|
||||
el("summary", { textContent: "advanced" }),
|
||||
el("p", { className: "hint", textContent:
|
||||
"Rotating issues a fresh key with a signed certificate proving it replaces this one. " +
|
||||
"Contacts accept the change from that chain, and the old seed is kept, since mail sealed " +
|
||||
"to it is readable with nothing else. Rotation is not revocation (SPEC.md \u00a77)." }),
|
||||
el("button", { type: "button", textContent: "rotate identity", onclick: rotateIdentity })),
|
||||
].filter(node => node != null));
|
||||
}
|
||||
|
||||
$("pin-form").onsubmit = (event) => {
|
||||
|
|
@ -618,7 +852,6 @@ $("import-form").onsubmit = (event) => {
|
|||
store.saveContact(addr.short, addr.identity, true);
|
||||
status(`imported ${addr.short} ${b32encode(addr.identity)} (verified)\n` +
|
||||
`fingerprint: ${fingerprint(addr.identity)}`);
|
||||
renderSettings();
|
||||
renderFolder();
|
||||
form.reset();
|
||||
} catch (err) {
|
||||
|
|
@ -642,13 +875,14 @@ $("register-form").onsubmit = async (event) => {
|
|||
store.setAccount(addr);
|
||||
status(`registered ${addr.short}\nshare: ${addr.uri(me.publicKey)}`);
|
||||
renderAccount();
|
||||
renderSettings();
|
||||
form.reset();
|
||||
} catch (err) {
|
||||
status(err.message, true);
|
||||
}
|
||||
};
|
||||
|
||||
$("rotate").onclick = async () => {
|
||||
async function rotateIdentity() {
|
||||
const me = store.identity();
|
||||
const addr = accountAddress();
|
||||
if (!me || !addr) return status("rotate needs a registered account", true);
|
||||
|
|
@ -665,15 +899,19 @@ $("rotate").onclick = async () => {
|
|||
opened.session.stream.close();
|
||||
}
|
||||
store.rotateIdentity(fresh.seed);
|
||||
// The key set grew, so a cached "not one of our keys" failure may be stale.
|
||||
openedCache.clear();
|
||||
status(`rotated ${addr.short}\nnew key: ${b32encode(fresh.publicKey)}`);
|
||||
renderAccount();
|
||||
renderSettings();
|
||||
renderFolder();
|
||||
} catch (err) {
|
||||
status(err.message, true);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// --- boot --------------------------------------------------------------------------
|
||||
|
||||
applyTheme();
|
||||
store.identity() ? showApp() : showSetup();
|
||||
status(store.identity() ? "" : "create an identity to begin");
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue