Withdraw the key manager, and keep what probing it established

A Settings section for public keys is furniture, not a feature. Nothing
in ihasmail signs, encrypts, decrypts or verifies with a key, so the
page could only ever tell the reader in its own footnote that adding one
does nothing. It is withdrawn on that reasoning -- the same reasoning
that closed PR #67, reached again with the code in front of us.

So this reverts every user-visible part of it: the section, the lib, the
mock handlers, the component and the 261 catalogue strings. Nothing in
web/ or server/ differs from main now.

What stays is the part that was expensive and is true regardless. The
x:PublicKey registry was probed against a live 0.16.20 on 2026-09-05,
and the findings are now in KNOWN-ISSUES rather than in a closed pull
request -- which is where they sat for the nine days between #67 and
this branch, and why the work was done twice. Consolidated into one
entry, framed as what Stalwart does rather than what ihasmail offers:

  - an ordinary user may read and write their own keys, whatever the
    permissions table says
  - the registry takes S/MIME certificates as well as OpenPGP keys, and
    parses both -- confirmed with a real self-signed X.509 certificate,
    and a malformed one gets its own BER decoding error
  - a key can parse and still be refused, with different words. A
    sign-and-certify key -- what `gpg --quick-generate-key` makes --
    gets "Could not find any suitable keys", which is not a paste error
    and must not be shown as one
  - emailAddresses comes back as {} when empty, an object where a list
    property should be an array. It type-checks, then throws in join()
  - a create answers with the id alone; patching `key` is allowed
  - expiresAt is the registry's field and is not derived from the key

ROADMAP now says plainly that key management has been built and
withdrawn twice, that the registry is not the obstacle, and that
verifying a signature -- which needs only public keys -- is the shortest
route to a key being worth having. Encryption at rest moves from "not
offered yet" to refused: it is a one-way door, since turning it off does
not decrypt what is already there, and that is not a switch to hand an
ordinary user however easy it would be to add.
This commit is contained in:
2026-09-05 01:11:25 -07:00
parent 6a467d9bc4
commit 45c8929697
19 changed files with 14 additions and 1101 deletions
-103
View File
@@ -1,103 +0,0 @@
import { describe, expect, it, vi } from "vitest";
const call = vi.fn();
vi.mock("@/jmap/client", async (orig) => {
const real = await orig<typeof import("@/jmap/client")>();
return { ...real, client: { ...real.client, call: (...a: unknown[]) => call(...a), hasCapabilityAnywhere: () => true } };
});
vi.mock("@/store/session", () => ({
useSession: { getState: () => ({ session: { primaryAccounts: { "urn:stalwart:jmap": "v" } }, accountFor: () => "v" }) },
}));
const { isExpired, keyExcerpt, keyKind, keyKindLabel, listPublicKeys } = await import("@/lib/publicKeys");
/**
* These read a key without parsing one. Stalwart parses it — with a real
* OpenPGP implementation that says precisely what is wrong — so anything
* checked here could only be a second opinion, and the one that counts would
* still be the server's. What is left is labelling: which sort of key this is,
* whether its stated expiry has passed, and enough of the body to tell two
* keys apart in a list.
*/
const PGP = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nmQINBGAbCdEFGh\nijKLmnOPqrSt\n=aBc1\n-----END PGP PUBLIC KEY BLOCK-----";
const X509 = "-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgIE\n-----END CERTIFICATE-----";
describe("which sort of key this is", () => {
it("reads the armour header, and only the header", () => {
expect(keyKind(PGP)).toBe("openpgp");
expect(keyKind(X509)).toBe("smime");
});
it("tolerates leading whitespace from a paste", () => {
expect(keyKind("\n\n " + PGP)).toBe("openpgp");
});
it("says so rather than guessing when the header is not one it knows", () => {
// Not "invalid" — that is the server's call to make, not this function's.
expect(keyKind("ssh-ed25519 AAAAC3Nz")).toBe("unknown");
expect(keyKind("")).toBe("unknown");
expect(keyKindLabel(keyKind("nonsense"))).toBe("Unrecognised");
});
});
describe("expiry", () => {
const now = new Date("2026-08-26T12:00:00Z");
it("is not expired when no expiry was set", () => {
expect(isExpired({ expiresAt: null }, now)).toBe(false);
});
it("compares against the given moment, not the machine clock", () => {
expect(isExpired({ expiresAt: "2026-08-25T12:00:00Z" }, now)).toBe(true);
expect(isExpired({ expiresAt: "2026-08-27T12:00:00Z" }, now)).toBe(false);
});
it("treats an unreadable date as no expiry rather than as expired", () => {
// Marking a usable key "Expired" over a date we could not read would be
// worse than saying nothing about it.
expect(isExpired({ expiresAt: "whenever" }, now)).toBe(false);
});
});
describe("telling two keys apart", () => {
it("excerpts the body, skipping armour, headers and the checksum", () => {
const x = keyExcerpt(PGP, 12);
expect(x).toBe("mQINBGAbCdEF");
expect(x).not.toContain("-----");
expect(x).not.toContain("=aBc1");
});
it("gives something rather than nothing for a key with no body", () => {
expect(keyExcerpt("-----BEGIN PGP PUBLIC KEY BLOCK-----\n-----END PGP PUBLIC KEY BLOCK-----")).toBe("—");
});
});
describe("reading the registry back", () => {
/*
* Stalwart answers an empty `emailAddresses` with `{}` -- an object, where a
* JMAP list property should be an array. Confirmed against a live 0.16.20 on
* 2026-09-05. Trusting the type would put an object through `.join(", ")`
* and throw in the middle of rendering the list, so the shape is checked
* rather than believed, and this is the test that says why.
*/
it("survives emailAddresses arriving as an object instead of an array", async () => {
call.mockResolvedValueOnce({ list: [{ id: "k1", key: PGP, description: "Work", createdAt: "2026-09-05T07:48:03Z", expiresAt: null, emailAddresses: {} }] });
const [k] = await listPublicKeys();
expect(Array.isArray(k!.emailAddresses)).toBe(true);
expect(k!.emailAddresses).toEqual([]);
});
it("keeps the addresses when the server does send a list", async () => {
call.mockResolvedValueOnce({ list: [{ id: "k1", key: PGP, emailAddresses: ["[email protected]", 7, "[email protected]"] }] });
const [k] = await listPublicKeys();
// The stray number is dropped rather than rendered as "7".
expect(k!.emailAddresses).toEqual(["[email protected]", "[email protected]"]);
});
it("fills in what a sparse object leaves out, so the card never renders undefined", async () => {
call.mockResolvedValueOnce({ list: [{ id: "k1" }] });
const [k] = await listPublicKeys();
expect(k).toEqual({ id: "k1", key: "", description: "", createdAt: null, expiresAt: null, emailAddresses: [] });
});
});
-172
View File
@@ -1,172 +0,0 @@
/**
* Public keys, over Stalwart's `x:PublicKey` registry.
*
* These are the keys other people use to encrypt mail *to* this account, and
* the ones a signature is checked against. Nothing secret is involved: no
* private key is held, asked for, or sent anywhere by any of this.
*
* Established against a live 0.16.20 on 2026-09-05 rather than assumed. The
* first two because the documentation says otherwise; the rest because they
* decide how this file has to be written:
*
* - An ordinary user may read *and* write their own keys. Stalwart's
* permissions table lists the `sysPublicKey*` permissions as
* administrative; the server granted them to a normal account. A create
* with a malformed key came back `invalidProperties`, not `forbidden`,
* which is a rejection of the key rather than of the person.
*
* - Stalwart parses the key itself, with a real OpenPGP implementation, and
* says precisely what is wrong: "Failed to decode OpenPGP public key:
* Malformed packet: Malformed CTB…". So ihasmail does not validate key
* material. Anything it checked would only be a second opinion, and the
* one that mattered would still be the server's. It refuses a *readable*
* key that cannot encrypt just as firmly, and differently — "Could not
* find any suitable keys in OpenPGP public key" — which is the rejection
* an exported sign-only key gets.
*
* - `emailAddresses` comes back as `{}` when it is empty: an object where a
* JMAP list property should be an array. `normalize` therefore checks the
* shape instead of trusting it, and every reader of this type gets a real
* array. Deleting that check reintroduces a crash in `.join()`.
*
* - A create answers with the id alone — no `createdAt` — so adding a key
* reloads the list rather than believing what it got back.
*
* - `destroy` works, and leaves the registry empty. That path had never been
* run against a real server before this probe.
*/
import { CAP, client, setErrorMessage } from "@/jmap/client";
import type { GetResponse, Id, SetResponse } from "@/jmap/types";
import { useSession } from "@/store/session";
import { t } from "@/lib/i18n";
const STALWART = "urn:stalwart:jmap";
const USING = [CAP.core, STALWART];
export interface PublicKey {
id: Id;
key: string;
description: string;
createdAt: string | null;
expiresAt: string | null;
emailAddresses: string[];
}
/** What a key can be edited to; `key` itself is replaced by adding a new one. */
export type PublicKeyPatch = Partial<Pick<PublicKey, "description" | "expiresAt" | "emailAddresses">>;
const PROPS = ["id", "key", "description", "createdAt", "expiresAt", "emailAddresses"];
/** Whether this server offers the registry at all. */
export function publicKeysAvailable(): boolean {
return client.hasCapabilityAnywhere(STALWART) && Boolean(accountId());
}
function accountId(): Id | null {
const s = useSession.getState();
return s.session?.primaryAccounts?.[STALWART] ?? s.accountFor(CAP.mail);
}
function normalize(raw: Partial<PublicKey> & { id: Id }): PublicKey {
return {
id: raw.id,
key: typeof raw.key === "string" ? raw.key : "",
description: typeof raw.description === "string" ? raw.description : "",
createdAt: typeof raw.createdAt === "string" ? raw.createdAt : null,
expiresAt: typeof raw.expiresAt === "string" ? raw.expiresAt : null,
emailAddresses: Array.isArray(raw.emailAddresses) ? raw.emailAddresses.filter((a): a is string => typeof a === "string") : [],
};
}
export async function listPublicKeys(): Promise<PublicKey[]> {
const id = accountId();
if (!id) return [];
const res = await client.call<GetResponse<PublicKey>>("x:PublicKey/get", { accountId: id, ids: null, properties: PROPS }, USING);
return res.list.map((k) => normalize(k as Partial<PublicKey> & { id: Id }));
}
export async function addPublicKey(key: string, description: string, extra: PublicKeyPatch = {}): Promise<PublicKey> {
const id = accountId();
if (!id) throw new Error(t("No account to add a key to."));
const res = await client.call<SetResponse<PublicKey>>(
"x:PublicKey/set",
{ accountId: id, create: { k: { key: key.trim(), description: description.trim(), ...clean(extra) } } },
USING,
);
const err = res.notCreated?.k;
// The server's own words: it parsed the key and knows what is wrong with it.
if (err) throw new Error(setErrorMessage(err));
return normalize((res.created?.k ?? { id: "" }) as Partial<PublicKey> & { id: Id });
}
export async function updatePublicKey(keyId: Id, patch: PublicKeyPatch): Promise<void> {
const id = accountId();
if (!id) return;
const res = await client.call<SetResponse<PublicKey>>("x:PublicKey/set", { accountId: id, update: { [keyId]: clean(patch) } }, USING);
const err = res.notUpdated?.[keyId];
if (err) throw new Error(setErrorMessage(err));
}
export async function removePublicKey(keyId: Id): Promise<void> {
const id = accountId();
if (!id) return;
const res = await client.call<SetResponse<PublicKey>>("x:PublicKey/set", { accountId: id, destroy: [keyId] }, USING);
const err = res.notDestroyed?.[keyId];
if (err) throw new Error(setErrorMessage(err));
}
/** Drop keys the caller left undefined, so a patch never blanks a field by accident. */
function clean(patch: PublicKeyPatch): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(patch)) if (v !== undefined) out[k] = v;
return out;
}
/* ------------------------------------------------------------------ */
/* Reading a key without parsing one */
/* ------------------------------------------------------------------ */
export type KeyKind = "openpgp" | "smime" | "unknown";
/**
* Which kind of key this is, from its armour header alone.
*
* Deliberately not a parse. The header is a label, and reading a label is not
* the same as validating the thing it is stuck to — the server does that, and
* a second opinion here could only ever disagree with the one that counts.
*/
export function keyKind(key: string): KeyKind {
const head = key.trimStart().slice(0, 120).toUpperCase();
if (head.includes("BEGIN PGP PUBLIC KEY BLOCK")) return "openpgp";
if (head.includes("BEGIN CERTIFICATE") || head.includes("BEGIN PKCS7")) return "smime";
return "unknown";
}
/**
* "OpenPGP" and "S/MIME" are the formats' own names and stay as they are in
* every language; only the fallback is a word rather than a name, so only the
* fallback is translated.
*/
export function keyKindLabel(kind: KeyKind): string {
return kind === "openpgp" ? "OpenPGP" : kind === "smime" ? "S/MIME" : t("Unrecognised");
}
/** Whether a key has an expiry that has already passed. */
export function isExpired(k: Pick<PublicKey, "expiresAt">, now = new Date()): boolean {
if (!k.expiresAt) return false;
const at = Date.parse(k.expiresAt);
return Number.isFinite(at) && at < now.getTime();
}
/**
* A short, stable excerpt of the key body, for telling two keys apart in a
* list. Not a fingerprint: computing a real one means parsing the key, and
* calling this a fingerprint would invite someone to verify against it.
*/
export function keyExcerpt(key: string, length = 24): string {
const body = key
.split(/\r?\n/)
.filter((l) => l && !l.startsWith("-----") && !l.includes(":") && !l.startsWith("="))
.join("");
return body.slice(0, length) || "—";
}