theseus/lib/hermes.js

177 lines
7.2 KiB
JavaScript
Raw Normal View History

// Hermes: name-addressed NIP-17 messaging over Nostr.
//
// This module lives inside Theseus because it depends on `nostr-tools` (a
// non-trivial dep the shared library layer, Argus, shouldn't carry). Loaded
// from main.js via dynamic import — same pattern as password-vault.js.
//
// Layers, sender → wire (NIP-17 + NIP-59):
// 1. rumor = unsigned kind:14 chat event
// 2. seal = kind:13 signed by sender (rumor encrypted to recipient)
// 3. wrap = kind:1059 signed by ephemeral (seal encrypted to recipient)
//
// Only the wrap goes on the wire; the relay sees an ephemeral pubkey, an
// opaque ciphertext, and a #p tag — never the sender or the plaintext.
import { webcrypto as wc } from "node:crypto";
import {
finalizeEvent, generateSecretKey, getPublicKey, getEventHash,
verifyEvent, nip19, nip44,
} from "nostr-tools";
const enc = new TextEncoder();
// ---- key derivation --------------------------------------------------------
// Same shape password-vault uses: BIP-39 → 64-byte seed → 32-byte purpose root
// via HKDF-SHA256 with `info="silentmode/<purpose>"`. Different purpose string,
// so passwords/0 and messenger/0 are cryptographically disjoint — one leak
// never yields the other.
/** BIP-39 mnemonic → 64-byte seed (PBKDF2-SHA512, 2048 iters, standard). */
export async function bip39ToSeed(mnemonic, passphrase = "") {
const km = await wc.subtle.importKey("raw",
enc.encode(String(mnemonic).normalize("NFKD").trim()),
"PBKDF2", false, ["deriveBits"]);
const salt = enc.encode(("mnemonic" + String(passphrase || "")).normalize("NFKD"));
return new Uint8Array(await wc.subtle.deriveBits(
{ name: "PBKDF2", salt, iterations: 2048, hash: "SHA-512" }, km, 512));
}
/** Seed 32-byte purpose root via HKDF. Purpose string is public the
* security comes from the seed, not the info parameter. */
export async function seedToPurposeRoot(seedBytes, purpose) {
const key = await wc.subtle.importKey("raw", seedBytes, "HKDF", false, ["deriveBits"]);
const info = enc.encode(`silentmode/${purpose}`);
return new Uint8Array(await wc.subtle.deriveBits(
{ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info }, key, 256));
}
/** BIP-39 mnemonic { sk, pkHex, npub } the Nostr identity for messaging.
* Path is "messenger/0" reserved for Hermes in
* TheseusNavigator/ROADMAP-identity-wallet.md. */
export async function nostrKeyFromMnemonic(mnemonic, passphrase = "") {
const seed = await bip39ToSeed(mnemonic, passphrase);
const sk = await seedToPurposeRoot(seed, "messenger/0");
const pkHex = getPublicKey(sk);
return { sk, pkHex, npub: nip19.npubEncode(pkHex) };
}
/** Same identity but from an already-derived messenger/0 root (32 bytes)
* used when the password vault already carries the root and re-entering the
* mnemonic would be redundant. Input is Uint8Array(32) or 64-char hex. */
export function nostrKeyFromRoot(root) {
const sk = typeof root === "string"
? Uint8Array.from(Buffer.from(root, "hex"))
: root;
if (!(sk instanceof Uint8Array) || sk.length !== 32) {
throw new Error("nostrKeyFromRoot: expected 32-byte Uint8Array or 64-char hex");
}
const pkHex = getPublicKey(sk);
return { sk, pkHex, npub: nip19.npubEncode(pkHex) };
}
// ---- record parsers --------------------------------------------------------
// The BNS resolver is transparent: whatever the name owner published in `r`
// lands as entry.records.<key>. Here we validate and normalise the two Hermes
// record types.
//
// np — Nostr pubkey, hex (64) or npub1…
// nr — comma/space-separated list of ws(s):// relay URLs
const HEX_PUBKEY_RE = /^[0-9a-f]{64}$/i;
export function parseNpRecord(raw) {
if (typeof raw !== "string" || !raw.trim()) throw new Error("np: empty or missing");
const v = raw.trim();
if (HEX_PUBKEY_RE.test(v)) return v.toLowerCase();
if (v.startsWith("npub1")) {
const d = nip19.decode(v);
if (d.type !== "npub" || typeof d.data !== "string" || !HEX_PUBKEY_RE.test(d.data)) {
throw new Error("np: npub decoded to unexpected shape");
}
return d.data.toLowerCase();
}
throw new Error(`np: not hex(64) and not npub1…: ${v.slice(0, 24)}`);
}
export function parseNrRecord(raw, { defaults = [] } = {}) {
if (typeof raw !== "string" || !raw.trim()) return defaults.slice();
const seen = new Set(); const out = [];
for (const tok of raw.split(/[,\s]+/)) {
const url = tok.trim();
if (!/^wss?:\/\//i.test(url)) continue;
if (seen.has(url)) continue;
seen.add(url); out.push(url);
}
return out.length ? out : defaults.slice();
}
/** Extract Hermes recipient info from a resolver Entry. */
export function parseHermesRecords(entry, { defaultRelays = [] } = {}) {
if (!entry || !entry.records) throw new Error("no on-chain entry for name");
return {
npPk: parseNpRecord(entry.records.np),
relays: parseNrRecord(entry.records.nr, { defaults: defaultRelays }),
};
}
// ---- NIP-17 wrap / unwrap --------------------------------------------------
const KIND_CHAT = 14;
const KIND_SEAL = 13;
const KIND_GIFT_WRAP = 1059;
// NIP-59: randomise timestamps up to 2 days in the past so relays can't
// correlate wrap-arrival with real send-time.
const TWO_DAYS = 2 * 24 * 60 * 60;
const jitteredNow = () =>
Math.floor(Date.now() / 1000) - Math.floor(Math.random() * TWO_DAYS);
const convKey = (sk, pkHex) => nip44.v2.utils.getConversationKey(sk, pkHex);
const encrypt = (sk, pkHex, plain) => nip44.v2.encrypt(plain, convKey(sk, pkHex));
const decrypt = (sk, pkHex, cipher) => nip44.v2.decrypt(cipher, convKey(sk, pkHex));
/** Wrap a plaintext chat message from senderSk to recipientPkHex. */
export function wrapChat({ senderSk, recipientPkHex, text }) {
const senderPkHex = getPublicKey(senderSk);
const rumor = {
kind: KIND_CHAT,
pubkey: senderPkHex,
created_at: Math.floor(Date.now() / 1000),
tags: [["p", recipientPkHex]],
content: text,
};
rumor.id = getEventHash(rumor);
const seal = finalizeEvent({
kind: KIND_SEAL,
created_at: jitteredNow(),
tags: [],
content: encrypt(senderSk, recipientPkHex, JSON.stringify(rumor)),
}, senderSk);
const ephemeralSk = generateSecretKey();
return finalizeEvent({
kind: KIND_GIFT_WRAP,
created_at: jitteredNow(),
tags: [["p", recipientPkHex]],
content: encrypt(ephemeralSk, recipientPkHex, JSON.stringify(seal)),
}, ephemeralSk);
}
/** Unwrap a kind:1059 gift wrap for receiverSk.
* Returns { senderPkHex, text, createdAt } or throws on tamper. */
export function unwrapChat({ receiverSk, wrap }) {
if (wrap.kind !== KIND_GIFT_WRAP) throw new Error(`not a gift wrap (kind ${wrap.kind})`);
if (!verifyEvent(wrap)) throw new Error("gift wrap signature invalid");
const seal = JSON.parse(decrypt(receiverSk, wrap.pubkey, wrap.content));
if (seal.kind !== KIND_SEAL) throw new Error(`inner is not a seal (kind ${seal.kind})`);
if (!verifyEvent(seal)) throw new Error("seal signature invalid");
const rumor = JSON.parse(decrypt(receiverSk, seal.pubkey, seal.content));
if (rumor.kind !== KIND_CHAT) throw new Error(`inner is not chat (kind ${rumor.kind})`);
if (rumor.pubkey !== seal.pubkey) throw new Error("rumor.pubkey does not match seal.pubkey");
return { senderPkHex: rumor.pubkey, text: rumor.content, createdAt: rumor.created_at };
}