@greenlandai/sdk 0.5.17 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +12 -0
- package/dist/index.cjs +76 -15
- package/index.js +1 -1
- package/package.json +10 -1
- package/src/core/crypto.js +7 -1
- package/src/core/messaging_client.js +304 -0
- package/src/core/messaging_store_node.js +94 -0
- package/src/core/messaging_v4.js +532 -0
- package/src/enyal.js +30 -5
- package/src/gldai.js +15 -4
- package/src/joulepai.js +14 -1
- package/src/rareeai.js +9 -4
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Where an ENYAL messaging client keeps its keys on a Node machine (SPEC §19) — the store messaging_client.js takes.
|
|
2
|
+
// Secrets: the OS keychain through the system's own tool — macOS `security -i` (the command, secret included, goes on STDIN, never in
|
|
3
|
+
// argv where `ps` would show it) or Linux `secret-tool` (secret on stdin) — else a 0600 JSON file, and the caller is told which.
|
|
4
|
+
// Windows has no stdin-only store here, so it uses the file. Pins and own-event hashes are not secret. Nothing here is sent to ENYAL.
|
|
5
|
+
// (Moved from enyal-mcp-local's store.js, P-DAY.132; the service name and home directory are parameters so each tool keeps its own.)
|
|
6
|
+
import { spawnSync } from "node:child_process";
|
|
7
|
+
import { mkdirSync, openSync, writeSync, closeSync, readFileSync, statSync, chmodSync, existsSync } from "node:fs";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
|
|
11
|
+
export const SERVICE = "enyal-messaging";
|
|
12
|
+
export const defaultHome = () => process.env.ENYAL_MESSAGING_HOME || join(homedir(), ".enyal-messaging");
|
|
13
|
+
const has = (cmd) => spawnSync("sh", ["-c", `command -v ${cmd}`], { encoding: "utf8" }).status === 0;
|
|
14
|
+
|
|
15
|
+
/** The OS keychain adapter in use, or null. */
|
|
16
|
+
export function keychain({ service = SERVICE, platform = process.platform, run = spawnSync, available = has,
|
|
17
|
+
disableEnv = "ENYAL_MESSAGING_NO_KEYCHAIN" } = {}) {
|
|
18
|
+
if (process.env[disableEnv] === "1") return null;
|
|
19
|
+
if (platform === "darwin" && available("security")) {
|
|
20
|
+
return {
|
|
21
|
+
name: "macOS Keychain",
|
|
22
|
+
set: (account, secret) => {
|
|
23
|
+
const hex = Buffer.from(secret, "utf8").toString("hex");
|
|
24
|
+
const r = run("security", ["-i"], { input: `add-generic-password -U -s ${service} -a ${account} -X ${hex}\n`, encoding: "utf8" });
|
|
25
|
+
if (r.status !== 0) throw new Error("the macOS Keychain refused the key");
|
|
26
|
+
},
|
|
27
|
+
get: (account) => {
|
|
28
|
+
const r = run("security", ["find-generic-password", "-s", service, "-a", account, "-w"], { encoding: "utf8" });
|
|
29
|
+
return r.status === 0 ? r.stdout.replace(/\n$/, "") : null;
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
if (platform === "linux" && process.env.DBUS_SESSION_BUS_ADDRESS && available("secret-tool")) {
|
|
34
|
+
return {
|
|
35
|
+
name: "Linux Secret Service",
|
|
36
|
+
set: (account, secret) => {
|
|
37
|
+
const r = run("secret-tool", ["store", "--label", service, "service", service, "account", account], { input: secret, encoding: "utf8" });
|
|
38
|
+
if (r.status !== 0) throw new Error("the Secret Service refused the key");
|
|
39
|
+
},
|
|
40
|
+
get: (account) => {
|
|
41
|
+
const r = run("secret-tool", ["lookup", "service", service, "account", account], { encoding: "utf8" });
|
|
42
|
+
return r.status === 0 && r.stdout ? r.stdout.replace(/\n$/, "") : null;
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function write0600(path, data, exclusive) {
|
|
50
|
+
mkdirSync(join(path, ".."), { recursive: true, mode: 0o700 });
|
|
51
|
+
const fd = openSync(path, exclusive ? "wx" : "w", 0o600);
|
|
52
|
+
try { writeSync(fd, JSON.stringify(data)); } finally { closeSync(fd); }
|
|
53
|
+
chmodSync(path, 0o600);
|
|
54
|
+
}
|
|
55
|
+
const readJson = (path) => (existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : null);
|
|
56
|
+
|
|
57
|
+
export class JsonState {
|
|
58
|
+
constructor(name, base = defaultHome()) { this.path = join(base, name); }
|
|
59
|
+
load(dflt) { const v = readJson(this.path); return v === null ? dflt : v; }
|
|
60
|
+
save(v) { write0600(this.path, v, false); }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export class KeyStore {
|
|
64
|
+
constructor(base = defaultHome(), kc = keychain(), { setupHint = "run the setup first (it makes your keys on this machine)" } = {}) {
|
|
65
|
+
this.base = base; this.kc = kc; this.setupHint = setupHint;
|
|
66
|
+
this.metaPath = join(base, "identity.json");
|
|
67
|
+
this.secretPath = join(base, "secret-keys.json");
|
|
68
|
+
}
|
|
69
|
+
where() { return this.kc ? `the ${this.kc.name}` : `the 0600 file ${this.secretPath}`; }
|
|
70
|
+
exists() { return existsSync(this.metaPath); }
|
|
71
|
+
state(name) { return new JsonState(name, this.base); }
|
|
72
|
+
save(principal, kid, secrets) {
|
|
73
|
+
if (this.exists()) throw new Error(`an identity already exists in ${this.base} — never overwritten`);
|
|
74
|
+
let location;
|
|
75
|
+
if (this.kc) { this.kc.set(principal, JSON.stringify(secrets)); location = "keychain"; }
|
|
76
|
+
else { write0600(this.secretPath, secrets, true); location = "file"; }
|
|
77
|
+
write0600(this.metaPath, { principal, kid, secrets_in: location }, true);
|
|
78
|
+
return location;
|
|
79
|
+
}
|
|
80
|
+
load() {
|
|
81
|
+
const meta = readJson(this.metaPath);
|
|
82
|
+
if (!meta) throw new Error(`no messaging identity here yet — ${this.setupHint}`);
|
|
83
|
+
let secrets;
|
|
84
|
+
if (meta.secrets_in === "keychain") {
|
|
85
|
+
const raw = this.kc && this.kc.get(meta.principal);
|
|
86
|
+
if (!raw) throw new Error("the identity's secrets are not in this machine's keychain");
|
|
87
|
+
secrets = JSON.parse(raw);
|
|
88
|
+
} else {
|
|
89
|
+
if (statSync(this.secretPath).mode & 0o077) throw new Error(`${this.secretPath} is readable by others — refusing to use it (chmod 600 it)`);
|
|
90
|
+
secrets = readJson(this.secretPath);
|
|
91
|
+
}
|
|
92
|
+
return { ...meta, ...secrets };
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
// ENYAL messaging v4 — end-to-end encrypted agent messages: client-side crypto (P-DAY.127 Phase B).
|
|
2
|
+
// Spec: docs specs/enyal-messaging-v4/SPEC.md. Test vectors: kat/messaging-v4-vectors.json (sha256 9e26a446…).
|
|
3
|
+
// ENYAL's servers never see a v4 message's plaintext: everything here runs on the sender's or reader's own device.
|
|
4
|
+
//
|
|
5
|
+
// Libraries: @noble/curves (P-256 ECDH + ECDSA) and @noble/post-quantum (ML-KEM-768) — already dependencies of this
|
|
6
|
+
// package — and the platform's WebCrypto (AES-256-GCM, HKDF-SHA256, SHA-256). No new dependency.
|
|
7
|
+
// Additive: nothing in the existing client calls this module until the Phase E cut-over.
|
|
8
|
+
//
|
|
9
|
+
// The same file ships in @enyalai/sdk (messaging_v4.js) and @greenlandai/sdk (src/core/messaging_v4.js); keep them identical.
|
|
10
|
+
import { ml_kem768 } from "@noble/post-quantum/ml-kem.js";
|
|
11
|
+
import { p256 } from "@noble/curves/nist.js";
|
|
12
|
+
import { entropyToMnemonic, mnemonicToEntropy } from "@scure/bip39";
|
|
13
|
+
import { wordlist as _bip39English } from "@scure/bip39/wordlists/english";
|
|
14
|
+
|
|
15
|
+
// Resolved at call time, never at import: importing the SDK must keep working on runtimes without WebCrypto.
|
|
16
|
+
function webcrypto() {
|
|
17
|
+
const c = globalThis.crypto;
|
|
18
|
+
if (!c || !c.subtle) throw new Error("messaging v4 needs WebCrypto (Node >= 19 or a modern browser)");
|
|
19
|
+
return c;
|
|
20
|
+
}
|
|
21
|
+
const subtle = new Proxy({}, { get: (_, k) => { const s = webcrypto().subtle; return s[k].bind(s); } });
|
|
22
|
+
const te = new TextEncoder();
|
|
23
|
+
const u8 = (s) => te.encode(s);
|
|
24
|
+
|
|
25
|
+
// ── encodings ────────────────────────────────────────────────────────────────────────────────────────────
|
|
26
|
+
export function concat(...parts) {
|
|
27
|
+
const n = parts.reduce((x, p) => x + p.length, 0), out = new Uint8Array(n);
|
|
28
|
+
let i = 0; for (const p of parts) { out.set(p, i); i += p.length; } return out;
|
|
29
|
+
}
|
|
30
|
+
export function toB64u(bytes) {
|
|
31
|
+
let s = ""; for (const b of bytes) s += String.fromCharCode(b);
|
|
32
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
33
|
+
}
|
|
34
|
+
export function fromB64u(str) {
|
|
35
|
+
const s = str.replace(/-/g, "+").replace(/_/g, "/"), pad = s.length % 4 ? "=".repeat(4 - (s.length % 4)) : "";
|
|
36
|
+
const bin = atob(s + pad), out = new Uint8Array(bin.length);
|
|
37
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out;
|
|
38
|
+
}
|
|
39
|
+
export function toHex(bytes) { return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); }
|
|
40
|
+
export function fromHex(h) { const o = new Uint8Array(h.length / 2); for (let i = 0; i < o.length; i++) o[i] = parseInt(h.substr(i * 2, 2), 16); return o; }
|
|
41
|
+
const bytesEqual = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
|
|
42
|
+
|
|
43
|
+
/** Canonical JSON (SPEC §2): sorted keys, no whitespace, integers only, UTF-8 strings (non-ASCII NOT \u-escaped). */
|
|
44
|
+
export function jcs(v) {
|
|
45
|
+
if (v === null || typeof v === "boolean") return JSON.stringify(v);
|
|
46
|
+
if (typeof v === "number") { if (!Number.isInteger(v)) throw new Error("canonical JSON: integers only"); return String(v); }
|
|
47
|
+
if (typeof v === "string") return JSON.stringify(v);
|
|
48
|
+
if (Array.isArray(v)) return "[" + v.map(jcs).join(",") + "]";
|
|
49
|
+
if (typeof v === "object") return "{" + Object.keys(v).sort().map((k) => JSON.stringify(k) + ":" + jcs(v[k])).join(",") + "}";
|
|
50
|
+
throw new Error("canonical JSON: unsupported value");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ── constants (SPEC §3) ──────────────────────────────────────────────────────────────────────────────────
|
|
54
|
+
export const DST = Object.freeze({
|
|
55
|
+
kid: u8("enyal-msg-v4-kid"),
|
|
56
|
+
wrapInfo: u8("enyal-msg-v4-wrap"),
|
|
57
|
+
ckAad: u8("enyal-msg-v4-ck"),
|
|
58
|
+
msgSig: concat(u8("ENYAL-MSG-v4-SIG"), new Uint8Array([0])),
|
|
59
|
+
keySig: concat(u8("ENYAL-MSGKEY-v1-SIG"), new Uint8Array([0])),
|
|
60
|
+
backup: u8("enyal-msg-v4-backup"),
|
|
61
|
+
});
|
|
62
|
+
const ZERO32 = new Uint8Array(32);
|
|
63
|
+
const ROLE_ORDER = ["sender", "recipient", "sender_owner", "recipient_owner"];
|
|
64
|
+
|
|
65
|
+
// ── primitives ───────────────────────────────────────────────────────────────────────────────────────────
|
|
66
|
+
export async function sha256(bytes) { return new Uint8Array(await subtle.digest("SHA-256", bytes)); }
|
|
67
|
+
// HKDF-SHA256 (RFC 5869), salt = 32 zero bytes, L = 32 — written out with HMAC because Node's WebCrypto HKDF refuses an
|
|
68
|
+
// `info` longer than 1024 bytes, and the wrap info (SPEC §6) is 1186 bytes (it binds the 1088-byte ML-KEM ciphertext).
|
|
69
|
+
async function hmac(key, data) {
|
|
70
|
+
const k = await subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
71
|
+
return new Uint8Array(await subtle.sign("HMAC", k, data));
|
|
72
|
+
}
|
|
73
|
+
async function hkdf32(ikm, info) {
|
|
74
|
+
const prk = await hmac(ZERO32, ikm); // extract
|
|
75
|
+
return hmac(prk, concat(info, new Uint8Array([1]))); // expand, one block = 32 bytes
|
|
76
|
+
}
|
|
77
|
+
async function gcmEncrypt(key, iv, pt, aad) {
|
|
78
|
+
const k = await subtle.importKey("raw", key, "AES-GCM", false, ["encrypt"]);
|
|
79
|
+
return new Uint8Array(await subtle.encrypt({ name: "AES-GCM", iv, additionalData: aad, tagLength: 128 }, k, pt));
|
|
80
|
+
}
|
|
81
|
+
async function gcmDecrypt(key, iv, ct, aad) {
|
|
82
|
+
const k = await subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]);
|
|
83
|
+
return new Uint8Array(await subtle.decrypt({ name: "AES-GCM", iv, additionalData: aad, tagLength: 128 }, k, ct));
|
|
84
|
+
}
|
|
85
|
+
const randomBytes = (n) => webcrypto().getRandomValues(new Uint8Array(n));
|
|
86
|
+
/** ECDSA P-256 / SHA-256, RFC 6979 deterministic, low-S, 64-byte r‖s (SPEC §1). */
|
|
87
|
+
export function sign(sigSk, message) { return p256.sign(message, sigSk, { lowS: true }); }
|
|
88
|
+
export function verify(sig, message, sigPk) { try { return p256.verify(sig, message, sigPk, { lowS: true }); } catch { return false; } }
|
|
89
|
+
|
|
90
|
+
// ── keys (SPEC §4) ───────────────────────────────────────────────────────────────────────────────────────
|
|
91
|
+
export async function kidOf(kemPk, ek, sigPk) { return (await sha256(concat(DST.kid, kemPk, ek, sigPk))).slice(0, 16); }
|
|
92
|
+
|
|
93
|
+
/** Rebuild a party from its three secrets (32-byte P-256 scalars + 64-byte ML-KEM seed). */
|
|
94
|
+
export async function partyFromSecrets({ kemSk, sigSk, mlkemSeed }) {
|
|
95
|
+
const kemPk = p256.getPublicKey(kemSk, true), sigPk = p256.getPublicKey(sigSk, true);
|
|
96
|
+
const { publicKey: ek, secretKey: dk } = ml_kem768.keygen(mlkemSeed);
|
|
97
|
+
return { kemSk, sigSk, mlkemSeed, kemPk, sigPk, ek, dk, kid: await kidOf(kemPk, ek, sigPk) };
|
|
98
|
+
}
|
|
99
|
+
/** Generate a fresh party ON THIS DEVICE. The secrets never leave it except inside a backup blob. */
|
|
100
|
+
export async function generateParty() {
|
|
101
|
+
return partyFromSecrets({ kemSk: p256.utils.randomSecretKey(), sigSk: p256.utils.randomSecretKey(), mlkemSeed: randomBytes(64) });
|
|
102
|
+
}
|
|
103
|
+
/** The public half a key event publishes. */
|
|
104
|
+
export function publicKeyFields(party) {
|
|
105
|
+
return { kid: toB64u(party.kid), kem_p256: toB64u(party.kemPk), kem_mlkem768: toB64u(party.ek), sig_p256: toB64u(party.sigPk) };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// ── key events (SPEC §5) ─────────────────────────────────────────────────────────────────────────────────
|
|
109
|
+
const REQUIRED_SIGS = { register: ["self"], rotate: ["self", "prev"], reset: ["self"] };
|
|
110
|
+
/** Sign a key-event body. signers: { self?, prev?, owner? } → sig secret keys. Returns { body, sigs }. */
|
|
111
|
+
export function signKeyEvent(body, signers) {
|
|
112
|
+
const msg = concat(DST.keySig, u8(jcs(body))), sigs = {};
|
|
113
|
+
for (const label of ["self", "prev", "owner"]) if (signers[label]) sigs[label] = toB64u(sign(signers[label], msg));
|
|
114
|
+
return { body, sigs };
|
|
115
|
+
}
|
|
116
|
+
/** chunk_hash = SHA-256(jcs(event)). */
|
|
117
|
+
export async function keyEventHash(event) { return toHex(await sha256(u8(jcs(event)))); }
|
|
118
|
+
/**
|
|
119
|
+
* Check a key event's signatures and shape. keys: { prev?, owner? } — the sig public keys the CALLER resolved from the log
|
|
120
|
+
* (prev = the principal's head before this event; owner = the owner's head in log order when this event was accepted).
|
|
121
|
+
* Returns { ok, reason }. The kid must recompute from the body's own public keys.
|
|
122
|
+
*/
|
|
123
|
+
export async function verifyKeyEvent(event, keys = {}) {
|
|
124
|
+
const b = event.body, s = event.sigs || {};
|
|
125
|
+
const msg = concat(DST.keySig, u8(jcs(b)));
|
|
126
|
+
const kemPk = fromB64u(b.kem_p256), ek = fromB64u(b.kem_mlkem768), sigPk = fromB64u(b.sig_p256);
|
|
127
|
+
if (ek.length !== 1184) return { ok: false, reason: "kem_mlkem768 must be 1184 bytes" };
|
|
128
|
+
if (toB64u(await kidOf(kemPk, ek, sigPk)) !== b.kid) return { ok: false, reason: "kid does not match the public keys" };
|
|
129
|
+
if (b.principal_kind === "account" && b.owner !== null) return { ok: false, reason: "accounts have owner null" };
|
|
130
|
+
const need = b.type === "revoke" ? [] : [...(REQUIRED_SIGS[b.type] || [])];
|
|
131
|
+
if (!REQUIRED_SIGS[b.type] && b.type !== "revoke") return { ok: false, reason: `unknown type ${b.type}` };
|
|
132
|
+
if (b.principal_kind === "agent") need.push("owner");
|
|
133
|
+
if (b.type === "revoke" && b.principal_kind === "account") need.push("prev"); // operator ruling 2026-10-04: required
|
|
134
|
+
if (b.type === "revoke" && !s.prev && !s.owner) return { ok: false, reason: "revoke needs prev or owner" };
|
|
135
|
+
if (b.principal_kind === "account" && s.owner) return { ok: false, reason: "an account event carries no owner signature" };
|
|
136
|
+
for (const label of need) if (!s[label]) return { ok: false, reason: `missing ${label} signature` };
|
|
137
|
+
const check = { self: sigPk, prev: keys.prev, owner: keys.owner };
|
|
138
|
+
for (const label of Object.keys(s)) {
|
|
139
|
+
if (!check[label]) return { ok: false, reason: `no ${label} key supplied to check the ${label} signature` };
|
|
140
|
+
if (!verify(fromB64u(s[label]), msg, check[label])) return { ok: false, reason: `${label} signature invalid` };
|
|
141
|
+
}
|
|
142
|
+
return { ok: true, reason: null };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ── the key log, in LOG ORDER (SPEC §5 "Time and order", "Client trust rule") ────────────────────────────
|
|
146
|
+
const tms = (iso) => { const t = Date.parse(iso); if (Number.isNaN(t)) throw new Error(`bad timestamp ${iso}`); return t; };
|
|
147
|
+
/** The public half of a key event as a reader / verifier: { principal, kid, kemPk, ek, sigPk, hosted, owner }. */
|
|
148
|
+
export function keyFromEvent(body) {
|
|
149
|
+
return { principal: body.principal, kid: fromB64u(body.kid), kemPk: fromB64u(body.kem_p256), ek: fromB64u(body.kem_mlkem768),
|
|
150
|
+
sigPk: fromB64u(body.sig_p256), hosted: body.hosted === true, owner: body.owner };
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* A client's view of the key log. Events are appended in the order the server ACCEPTED them (log order, fixed by anchoring),
|
|
154
|
+
* each with the server's accepted_at — never ordered by the client's created_at. Each append is verified against the heads the
|
|
155
|
+
* log itself holds at that point: `prev` against the principal's head, `owner` against the owner's head IN LOG ORDER at this
|
|
156
|
+
* event's acceptance. A revoke ends the chain until a reset. An append that fails throws and leaves the log unchanged.
|
|
157
|
+
* (Inclusion proofs against a BSV root — trust rule (a) — are checked by the caller before append; not in this class.)
|
|
158
|
+
*/
|
|
159
|
+
export class KeyLog {
|
|
160
|
+
constructor() { this.entries = []; this.byPrincipal = new Map(); }
|
|
161
|
+
_chain(p) { return this.byPrincipal.get(p) || []; }
|
|
162
|
+
_head(p) { const c = this._chain(p); return c.length ? c[c.length - 1] : null; }
|
|
163
|
+
async append(event, acceptedAt) {
|
|
164
|
+
const b = event.body, at = tms(acceptedAt);
|
|
165
|
+
if (b.v !== 1) throw new Error("key event v must be 1");
|
|
166
|
+
const last = this.entries[this.entries.length - 1];
|
|
167
|
+
if (last && at < last.at) throw new Error("accepted_at goes backwards — not log order");
|
|
168
|
+
const head = this._head(b.principal), chash = await keyEventHash(event);
|
|
169
|
+
if (!head) {
|
|
170
|
+
if (b.type !== "register" || b.seq !== 1 || b.prev !== null) throw new Error("a principal's first event must be register, seq 1, prev null");
|
|
171
|
+
} else {
|
|
172
|
+
if (b.type === "register") throw new Error("principal already registered");
|
|
173
|
+
if (b.seq !== head.body.seq + 1 || b.prev !== head.chash) throw new Error("seq/prev do not follow the principal's head");
|
|
174
|
+
if (head.body.type === "revoke" && b.type !== "reset") throw new Error("chain revoked: only a reset may follow");
|
|
175
|
+
if (b.principal_kind !== head.body.principal_kind) throw new Error("principal_kind changed");
|
|
176
|
+
if (b.owner !== head.body.owner) throw new Error("an agent's owner cannot change");
|
|
177
|
+
if (b.type === "revoke" && b.kid !== head.body.kid) throw new Error("a revoke must name the current head key");
|
|
178
|
+
}
|
|
179
|
+
const keys = {};
|
|
180
|
+
if (event.sigs && event.sigs.prev) {
|
|
181
|
+
if (!head || b.type === "reset" || head.body.type === "revoke") throw new Error("prev signature where no live head exists");
|
|
182
|
+
keys.prev = fromB64u(head.body.sig_p256);
|
|
183
|
+
}
|
|
184
|
+
if (b.principal_kind === "agent") {
|
|
185
|
+
const oh = this._head(b.owner);
|
|
186
|
+
if (!oh) throw new Error("owner has no key in the log");
|
|
187
|
+
if (oh.body.type === "revoke") throw new Error("owner's key is revoked");
|
|
188
|
+
if (oh.body.principal_kind !== "account") throw new Error("owner must be an account");
|
|
189
|
+
keys.owner = fromB64u(oh.body.sig_p256);
|
|
190
|
+
}
|
|
191
|
+
const r = await verifyKeyEvent(event, keys);
|
|
192
|
+
if (!r.ok) throw new Error(`key event refused: ${r.reason}`);
|
|
193
|
+
const entry = { index: this.entries.length, at, acceptedAt, body: b, chash, event };
|
|
194
|
+
this.entries.push(entry);
|
|
195
|
+
this.byPrincipal.set(b.principal, [...this._chain(b.principal), entry]);
|
|
196
|
+
return entry;
|
|
197
|
+
}
|
|
198
|
+
/** (b-encrypt) the key to ENCRYPT to: the principal's current head. Throws if absent or revoked; flags hosted / reset. */
|
|
199
|
+
encryptKey(principal) {
|
|
200
|
+
const h = this._head(principal);
|
|
201
|
+
if (!h) throw new Error(`no key for ${principal}`);
|
|
202
|
+
if (h.body.type === "revoke") throw new Error(`${principal}'s key is revoked — do not encrypt to it`);
|
|
203
|
+
return { ...keyFromEvent(h.body), reset: h.body.type === "reset", logIndex: h.index, chash: h.chash };
|
|
204
|
+
}
|
|
205
|
+
/** (b-verify) the key that was the principal's head in log order at the server's received_at; null if none or revoked then. */
|
|
206
|
+
verifyKeyAt(principal, receivedAt) {
|
|
207
|
+
const t = tms(receivedAt); let h = null;
|
|
208
|
+
for (const e of this._chain(principal)) { if (e.at <= t) h = e; else break; }
|
|
209
|
+
if (!h || h.body.type === "revoke") return null;
|
|
210
|
+
return { ...keyFromEvent(h.body), logIndex: h.index, chash: h.chash };
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ── envelope (SPEC §6) ───────────────────────────────────────────────────────────────────────────────────
|
|
215
|
+
/**
|
|
216
|
+
* Build the reader list: sender, recipient, sender_owner, recipient_owner; de-duplicated by kid, first role kept.
|
|
217
|
+
* A reader other than the sender whose key is HOSTED (SPEC §20: ENYAL holds it and can read that copy) is refused unless the
|
|
218
|
+
* caller passes allowHosted: true after warning the person — "<name>'s copy is readable by ENYAL (hosted messaging)".
|
|
219
|
+
*/
|
|
220
|
+
export function readerSet({ sender, recipient, senderOwner = null, recipientOwner = null, allowHosted = false }) {
|
|
221
|
+
const seen = new Set(), out = [];
|
|
222
|
+
for (const [p, role] of [[sender, "sender"], [recipient, "recipient"], [senderOwner, "sender_owner"], [recipientOwner, "recipient_owner"]]) {
|
|
223
|
+
if (!p) continue; const k = toHex(p.kid);
|
|
224
|
+
if (!seen.has(k)) { seen.add(k); out.push({ ...p, role }); }
|
|
225
|
+
}
|
|
226
|
+
const hosted = out.filter((r) => r.role !== "sender" && r.hosted === true);
|
|
227
|
+
if (hosted.length && !allowHosted) {
|
|
228
|
+
throw Object.assign(new Error(`hosted_reader: ENYAL can read the ${hosted.map((r) => r.role).join(", ")} copy (hosted messaging) — warn the person, then pass allowHosted: true`),
|
|
229
|
+
{ code: "hosted_reader", hosted: hosted.map((r) => ({ role: r.role, kid: toB64u(r.kid) })) });
|
|
230
|
+
}
|
|
231
|
+
return out;
|
|
232
|
+
}
|
|
233
|
+
async function wrapFor(reader, ck, hdrHash, det) {
|
|
234
|
+
const eSk = det ? det.ephSk : p256.utils.randomSecretKey();
|
|
235
|
+
const epk = p256.getPublicKey(eSk, true);
|
|
236
|
+
const ssEc = p256.getSharedSecret(eSk, reader.kemPk, true).slice(1);
|
|
237
|
+
const { cipherText: kc, sharedSecret: ssPq } = det ? ml_kem768.encapsulate(reader.ek, det.mlkemM) : ml_kem768.encapsulate(reader.ek);
|
|
238
|
+
const kek = await hkdf32(concat(ssEc, ssPq), concat(DST.wrapInfo, reader.kid, epk, kc, hdrHash));
|
|
239
|
+
const wn = det ? det.wn : randomBytes(12);
|
|
240
|
+
const wk = await gcmEncrypt(kek, wn, ck, concat(DST.ckAad, reader.kid));
|
|
241
|
+
return { kid: toB64u(reader.kid), role: reader.role, epk: toB64u(epk), kc: toB64u(kc), wn: toB64u(wn), wk: toB64u(wk) };
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Encrypt one message on this device. header: { v:4, msg_id, thread_id, sender, recipient, type, sent_at }.
|
|
245
|
+
* readers: from readerSet() — each { kid, kemPk, ek, role } (public keys only). senderSigSk signs inside the ciphertext.
|
|
246
|
+
* `_deterministic` exists for the test vectors only; never pass it in production.
|
|
247
|
+
*/
|
|
248
|
+
export async function buildEnvelope({ header, body, senderSigSk, readers, _deterministic = null }) {
|
|
249
|
+
if (header.v !== 4) throw new Error("header.v must be 4");
|
|
250
|
+
const hdr = u8(jcs(header)), hdrHash = await sha256(hdr);
|
|
251
|
+
const sig = sign(senderSigSk, concat(DST.msgSig, hdr, await sha256(u8(jcs(body)))));
|
|
252
|
+
const plaintext = u8(jcs({ body, sig: toB64u(sig) }));
|
|
253
|
+
const ck = _deterministic ? _deterministic.ck : randomBytes(32), n = _deterministic ? _deterministic.n : randomBytes(12);
|
|
254
|
+
const ct = await gcmEncrypt(ck, n, plaintext, hdr);
|
|
255
|
+
const wraps = [];
|
|
256
|
+
for (const r of readers) wraps.push(await wrapFor(r, ck, hdrHash, _deterministic ? _deterministic.wraps[r.role] : null));
|
|
257
|
+
return { v: 4, hdr: toB64u(hdr), n: toB64u(n), ct: toB64u(ct), wraps };
|
|
258
|
+
}
|
|
259
|
+
export async function envelopeHash(envelope) { return toHex(await sha256(u8(jcs(envelope)))); }
|
|
260
|
+
/** Idempotency hash (SPEC §7) = SHA-256(jcs(envelope)). */
|
|
261
|
+
export const idempotencyHash = envelopeHash;
|
|
262
|
+
|
|
263
|
+
async function openWith(envelope, ck) {
|
|
264
|
+
const hdr = fromB64u(envelope.hdr);
|
|
265
|
+
const plaintext = await gcmDecrypt(ck, fromB64u(envelope.n), fromB64u(envelope.ct), hdr);
|
|
266
|
+
const inner = JSON.parse(new TextDecoder().decode(plaintext));
|
|
267
|
+
return { header: JSON.parse(new TextDecoder().decode(hdr)), body: inner.body, sig: inner.sig };
|
|
268
|
+
}
|
|
269
|
+
/** Open a message with MY keys ({ kid, kemSk, dk }). Returns { header, body, sig, ck } or throws if I am not a reader. */
|
|
270
|
+
export async function openEnvelope(envelope, me) {
|
|
271
|
+
const myKid = toB64u(me.kid), w = envelope.wraps.find((x) => x.kid === myKid);
|
|
272
|
+
if (!w) throw new Error("not a reader of this message");
|
|
273
|
+
const hdr = fromB64u(envelope.hdr), hdrHash = await sha256(hdr), epk = fromB64u(w.epk), kc = fromB64u(w.kc);
|
|
274
|
+
const ssEc = p256.getSharedSecret(me.kemSk, epk, true).slice(1);
|
|
275
|
+
const ssPq = ml_kem768.decapsulate(kc, me.dk);
|
|
276
|
+
const kek = await hkdf32(concat(ssEc, ssPq), concat(DST.wrapInfo, me.kid, epk, kc, hdrHash));
|
|
277
|
+
const ck = await gcmDecrypt(kek, fromB64u(w.wn), fromB64u(w.wk), concat(DST.ckAad, me.kid));
|
|
278
|
+
return { ...(await openWith(envelope, ck)), ck };
|
|
279
|
+
}
|
|
280
|
+
/** Verify the sender signature inside an opened message against the sender's sig key (head in log order at received_at). */
|
|
281
|
+
export async function verifySender({ header, body, sig }, senderSigPk) {
|
|
282
|
+
const hdr = u8(jcs(header));
|
|
283
|
+
return verify(fromB64u(sig), concat(DST.msgSig, hdr, await sha256(u8(jcs(body)))), senderSigPk);
|
|
284
|
+
}
|
|
285
|
+
/** Franking (SPEC §8): verify ONE message from its content key alone — a reader discloses ck, never a private key. */
|
|
286
|
+
export async function frankingVerify(envelope, ck, senderSigPk, anchoredEnvelopeHash = null) {
|
|
287
|
+
if (anchoredEnvelopeHash && (await envelopeHash(envelope)) !== anchoredEnvelopeHash) return { ok: false, reason: "envelope hash does not match the anchor" };
|
|
288
|
+
let opened; try { opened = await openWith(envelope, ck); } catch { return { ok: false, reason: "content key does not open this envelope" }; }
|
|
289
|
+
if (!(await verifySender(opened, senderSigPk))) return { ok: false, reason: "sender signature invalid" };
|
|
290
|
+
return { ok: true, header: opened.header, body: opened.body };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// ── backup (SPEC §4) ─────────────────────────────────────────────────────────────────────────────────────
|
|
294
|
+
async function backupKey(entropy32, kid) { return hkdf32(entropy32, concat(DST.backup, kid)); }
|
|
295
|
+
/** Seal a party's three secrets under the 32-byte entropy of a GENERATED 24-word phrase (or a passkey PRF output). */
|
|
296
|
+
export async function sealBackup(party, entropy32, _nonce = null) {
|
|
297
|
+
const n = _nonce || randomBytes(12);
|
|
298
|
+
const secret = u8(jcs({ kem_p256_sk: toHex(party.kemSk), mlkem_seed: toHex(party.mlkemSeed), sig_p256_sk: toHex(party.sigSk) }));
|
|
299
|
+
const blob = await gcmEncrypt(await backupKey(entropy32, party.kid), n, secret, concat(DST.backup, party.kid));
|
|
300
|
+
return { kid: toB64u(party.kid), nonce: toB64u(n), blob: toB64u(blob) };
|
|
301
|
+
}
|
|
302
|
+
/** Open a backup with the phrase entropy; returns the rebuilt party, or throws on a wrong phrase. */
|
|
303
|
+
export async function openBackup({ kid, nonce, blob }, entropy32) {
|
|
304
|
+
const kidRaw = fromB64u(kid);
|
|
305
|
+
const secret = await gcmDecrypt(await backupKey(entropy32, kidRaw), fromB64u(nonce), fromB64u(blob), concat(DST.backup, kidRaw));
|
|
306
|
+
const s = JSON.parse(new TextDecoder().decode(secret));
|
|
307
|
+
const party = await partyFromSecrets({ kemSk: fromHex(s.kem_p256_sk), sigSk: fromHex(s.sig_p256_sk), mlkemSeed: fromHex(s.mlkem_seed) });
|
|
308
|
+
if (!bytesEqual(party.kid, kidRaw)) throw new Error("backup does not rebuild the expected key id");
|
|
309
|
+
return party;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// ── key-event batches and the client's inclusion check (SPEC §15) ───────────────────────────────────────
|
|
313
|
+
/** BSV-Merkle-A1 (docs merkle-canonical-spec-v1.md): single SHA-256 over 64 raw bytes, duplicate-last. → { root, proofs } */
|
|
314
|
+
export async function merkleA1(leaves) {
|
|
315
|
+
if (leaves.length === 0) return { root: "", proofs: [] };
|
|
316
|
+
if (leaves.length === 1) return { root: leaves[0], proofs: [[]] };
|
|
317
|
+
let level = [...leaves];
|
|
318
|
+
if (level.length % 2) level.push(level[level.length - 1]);
|
|
319
|
+
const levels = [level];
|
|
320
|
+
while (level.length > 1) {
|
|
321
|
+
const nxt = [];
|
|
322
|
+
for (let i = 0; i < level.length; i += 2) nxt.push(toHex(await sha256(concat(fromHex(level[i]), fromHex(level[i + 1])))));
|
|
323
|
+
if (nxt.length > 1 && nxt.length % 2) nxt.push(nxt[nxt.length - 1]);
|
|
324
|
+
levels.push(nxt);
|
|
325
|
+
level = nxt;
|
|
326
|
+
}
|
|
327
|
+
const proofs = leaves.map((_, i) => {
|
|
328
|
+
const p = []; let idx = i;
|
|
329
|
+
for (let l = 0; l < levels.length - 1; l++) { p.push({ hash: levels[l][idx ^ 1], position: idx % 2 === 0 ? "right" : "left" }); idx = Math.floor(idx / 2); }
|
|
330
|
+
return p;
|
|
331
|
+
});
|
|
332
|
+
return { root: level[0], proofs };
|
|
333
|
+
}
|
|
334
|
+
export async function verifyMerkleA1(leaf, proof, root) {
|
|
335
|
+
let cur = leaf;
|
|
336
|
+
for (const s of proof) {
|
|
337
|
+
if (s.position === "right") cur = toHex(await sha256(concat(fromHex(cur), fromHex(s.hash))));
|
|
338
|
+
else if (s.position === "left") cur = toHex(await sha256(concat(fromHex(s.hash), fromHex(cur))));
|
|
339
|
+
else return false;
|
|
340
|
+
}
|
|
341
|
+
return cur === root;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Parse a raw BSV transaction output by output (never a byte scan). → { txid, outputs: [{ value (BigInt), script }] } */
|
|
345
|
+
export async function parseRawTx(raw) {
|
|
346
|
+
let o = 0;
|
|
347
|
+
const need = (n) => { if (o + n > raw.length) throw new Error("transaction truncated"); };
|
|
348
|
+
const take = (n) => { need(n); const b = raw.subarray(o, o + n); o += n; return b; };
|
|
349
|
+
const varint = () => {
|
|
350
|
+
need(1); const f = raw[o++];
|
|
351
|
+
if (f < 0xfd) return f;
|
|
352
|
+
const w = f === 0xfd ? 2 : f === 0xfe ? 4 : 8; let v = 0n;
|
|
353
|
+
take(w).forEach((b, i) => { v |= BigInt(b) << BigInt(8 * i); });
|
|
354
|
+
if (v > BigInt(raw.length)) throw new Error("transaction length field out of range");
|
|
355
|
+
return Number(v);
|
|
356
|
+
};
|
|
357
|
+
take(4); // version
|
|
358
|
+
const nIn = varint();
|
|
359
|
+
for (let i = 0; i < nIn; i++) { take(36); take(varint()); take(4); }
|
|
360
|
+
const nOut = varint(), outputs = [];
|
|
361
|
+
for (let i = 0; i < nOut; i++) {
|
|
362
|
+
let value = 0n; take(8).forEach((b, j) => { value |= BigInt(b) << BigInt(8 * j); });
|
|
363
|
+
outputs.push({ value, script: take(varint()) });
|
|
364
|
+
}
|
|
365
|
+
take(4); // locktime
|
|
366
|
+
if (o !== raw.length) throw new Error("trailing bytes after the transaction");
|
|
367
|
+
const txid = toHex((await sha256(await sha256(raw))).reverse());
|
|
368
|
+
return { txid, outputs };
|
|
369
|
+
}
|
|
370
|
+
/** The data pushes of an OP_RETURN (0x6a) or OP_FALSE OP_RETURN (0x00 0x6a) script, or null for any other script. */
|
|
371
|
+
export function opReturnPushes(script) {
|
|
372
|
+
let o = script[0] === 0x6a ? 1 : script[0] === 0x00 && script[1] === 0x6a ? 2 : -1;
|
|
373
|
+
if (o < 0) return null;
|
|
374
|
+
const out = [];
|
|
375
|
+
while (o < script.length) {
|
|
376
|
+
const op = script[o++]; let n;
|
|
377
|
+
if (op >= 1 && op <= 75) n = op;
|
|
378
|
+
else if (op === 0x4c) n = script[o++];
|
|
379
|
+
else if (op === 0x4d) { n = script[o] | (script[o + 1] << 8); o += 2; }
|
|
380
|
+
else if (op === 0x4e) { n = script[o] | (script[o + 1] << 8) | (script[o + 2] << 16) | (script[o + 3] << 24); o += 4; }
|
|
381
|
+
else return null; // not a pure data-push script
|
|
382
|
+
if (o + n > script.length) return null;
|
|
383
|
+
out.push(script.subarray(o, o + n)); o += n;
|
|
384
|
+
}
|
|
385
|
+
return out;
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* SPEC §15 check of one key event against its published batch and the anchor transaction's raw bytes.
|
|
389
|
+
* batch: { algorithm_version: "A1", merkle_root, txid, leaves }. Returns { ok, reason, leafIndex }.
|
|
390
|
+
*/
|
|
391
|
+
export async function verifyBatchInclusion({ chunkHash, batch, rawTx }) {
|
|
392
|
+
if (batch.algorithm_version !== "A1") return { ok: false, reason: `unknown batch algorithm ${batch.algorithm_version}` };
|
|
393
|
+
const leafIndex = batch.leaves.indexOf(chunkHash);
|
|
394
|
+
if (leafIndex < 0) return { ok: false, reason: "the key event is not in the published batch" };
|
|
395
|
+
const { root, proofs } = await merkleA1(batch.leaves);
|
|
396
|
+
if (root !== batch.merkle_root) return { ok: false, reason: "the published leaf list does not rebuild the published root" };
|
|
397
|
+
if (!(await verifyMerkleA1(chunkHash, proofs[leafIndex], root))) return { ok: false, reason: "inclusion proof failed" };
|
|
398
|
+
const tx = await parseRawTx(rawTx);
|
|
399
|
+
if (tx.txid !== batch.txid) return { ok: false, reason: "the transaction bytes do not hash to the batch txid" };
|
|
400
|
+
const anchored = tx.outputs.some((out) => { const p = opReturnPushes(out.script); return p && p.length === 1 && toHex(p[0]) === root; });
|
|
401
|
+
if (!anchored) return { ok: false, reason: "no OP_RETURN in the transaction carries the batch root" };
|
|
402
|
+
return { ok: true, reason: null, leafIndex };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** Default public BSV sources (two independent operators). A user may replace them, e.g. with their own node. */
|
|
406
|
+
export const BSV_SOURCES = Object.freeze([
|
|
407
|
+
{ name: "bitails", raw: (t) => `https://api.bitails.io/download/tx/${t}`, status: (t) => `https://api.bitails.io/tx/${t}`,
|
|
408
|
+
block: (j) => ({ height: j.blockheight, hash: j.blockhash }) },
|
|
409
|
+
{ name: "gorillapool", raw: (t) => `https://ordinals.gorillapool.io/api/tx/${t}/raw`, status: (t) => `https://junglebus.gorillapool.io/v1/transaction/get/${t}`,
|
|
410
|
+
block: (j) => ({ height: j.block_height, hash: j.block_hash }) },
|
|
411
|
+
]);
|
|
412
|
+
/**
|
|
413
|
+
* Fetch an anchor transaction from at least 2 sources. Each source's bytes must hash to the txid (checked here, so a source cannot
|
|
414
|
+
* change the content), each must report it in a block, and the block hashes must agree. → { raw, block }
|
|
415
|
+
* Limit (SPEC §15): the sources' word that the block is in the chain is trusted; block headers are not verified here.
|
|
416
|
+
*/
|
|
417
|
+
export async function fetchAnchoredTransaction(txid, { sources = BSV_SOURCES, fetchImpl = globalThis.fetch, minSources = 2 } = {}) {
|
|
418
|
+
if (sources.length < minSources) throw new Error(`at least ${minSources} sources are required`);
|
|
419
|
+
let raw = null; const blocks = [];
|
|
420
|
+
for (const s of sources) {
|
|
421
|
+
const r = await fetchImpl(s.raw(txid));
|
|
422
|
+
if (!r.ok) throw new Error(`${s.name}: HTTP ${r.status} for the transaction`);
|
|
423
|
+
const bytes = new Uint8Array(await r.arrayBuffer());
|
|
424
|
+
const { txid: got } = await parseRawTx(bytes);
|
|
425
|
+
if (got !== txid) throw new Error(`${s.name}: the returned bytes hash to ${got}, not ${txid}`);
|
|
426
|
+
raw = raw || bytes;
|
|
427
|
+
const st = await fetchImpl(s.status(txid));
|
|
428
|
+
if (!st.ok) throw new Error(`${s.name}: HTTP ${st.status} for the transaction status`);
|
|
429
|
+
const b = s.block(await st.json());
|
|
430
|
+
if (!b.height || !b.hash) throw new Error(`${s.name}: the transaction is not in a block yet`);
|
|
431
|
+
blocks.push({ source: s.name, ...b });
|
|
432
|
+
}
|
|
433
|
+
if (new Set(blocks.map((b) => `${b.height}:${b.hash}`)).size !== 1) throw new Error("the sources disagree on the block");
|
|
434
|
+
return { raw, block: blocks[0], sources: blocks };
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// ── pins and key-change warnings (SPEC §16) ──────────────────────────────────────────────────────────────
|
|
438
|
+
const SEVERITY = { rotate: "info", reset: "warning", revoke: "warning" };
|
|
439
|
+
/**
|
|
440
|
+
* Pins each contact's key on first use; reports every change in the log since the pin. Persist `toJSON()` on the device.
|
|
441
|
+
* A pin names the pinned key EVENT by its chunk hash — never by a position in a KeyLog, because a KeyLog's positions depend on which
|
|
442
|
+
* principals that replay loaded (pinning by position reported a change that never happened; rev22 F-sdk-keypins-client-index-2026-10-05).
|
|
443
|
+
* A pin saved by an older version ({kid, logIndex}) is located by its key id instead.
|
|
444
|
+
*/
|
|
445
|
+
export class KeyPins {
|
|
446
|
+
constructor(saved = {}) { this.pins = new Map(Object.entries(saved)); }
|
|
447
|
+
toJSON() { return Object.fromEntries(this.pins); }
|
|
448
|
+
/** Pin a contact's current key (from KeyLog.encryptKey, which names the head event's chunk hash). Keeps an existing pin. */
|
|
449
|
+
pin(principal, key) {
|
|
450
|
+
if (this.pins.has(principal)) return;
|
|
451
|
+
if (!key.chash) throw new Error("pin needs the key's event (use KeyLog.encryptKey)");
|
|
452
|
+
this.pins.set(principal, { kid: toB64u(key.kid), chash: key.chash });
|
|
453
|
+
}
|
|
454
|
+
/** Every event for a pinned contact after its pinned event → [{ principal, type, severity, fromKid, toKid, logIndex }].
|
|
455
|
+
* A pinned event missing from the principal's chain (the log no longer holds what was pinned) → type "pin_not_in_log". */
|
|
456
|
+
changes(log) {
|
|
457
|
+
const out = [];
|
|
458
|
+
for (const [principal, pin] of this.pins) {
|
|
459
|
+
const chain = log._chain(principal);
|
|
460
|
+
if (!chain.length) continue; // this replay did not load the principal
|
|
461
|
+
let at = pin.chash ? chain.findIndex((e) => e.chash === pin.chash) : -1;
|
|
462
|
+
if (at < 0 && !pin.chash) at = chain.findIndex((e) => e.body.kid === pin.kid);
|
|
463
|
+
if (at < 0) {
|
|
464
|
+
const h = chain[chain.length - 1];
|
|
465
|
+
out.push({ principal, type: "pin_not_in_log", severity: "warning", fromKid: pin.kid, toKid: h.body.kid, logIndex: h.index });
|
|
466
|
+
continue;
|
|
467
|
+
}
|
|
468
|
+
let from = pin.kid;
|
|
469
|
+
for (const e of chain.slice(at + 1)) {
|
|
470
|
+
out.push({ principal, type: e.body.type, severity: SEVERITY[e.body.type] || "warning", fromKid: from, toKid: e.body.kid, logIndex: e.index });
|
|
471
|
+
from = e.body.kid;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return out;
|
|
475
|
+
}
|
|
476
|
+
/** Accept the changes seen (after the user confirms): move every pin to its principal's current head event. */
|
|
477
|
+
accept(log) { for (const principal of this.pins.keys()) { const h = log._head(principal); if (h) this.pins.set(principal, { kid: h.body.kid, chash: h.chash }); } }
|
|
478
|
+
}
|
|
479
|
+
/** SHA-256 of jcs(body) — what a device records for an event it made (an owner's countersignature changes the chunk_hash,
|
|
480
|
+
* never the body). */
|
|
481
|
+
export async function keyEventBodyHash(body) { return toHex(await sha256(u8(jcs(body)))); }
|
|
482
|
+
/** Alerts for events in MY OWN chain that this device did not make; `mine` = the body hashes of the events it made (SPEC §16). */
|
|
483
|
+
export async function ownChainAlerts(log, principal, mine) {
|
|
484
|
+
const known = new Set(mine), out = [];
|
|
485
|
+
for (const e of log._chain(principal)) {
|
|
486
|
+
if (!known.has(await keyEventBodyHash(e.body))) out.push({ principal, type: e.body.type, chunkHash: e.chash, logIndex: e.index });
|
|
487
|
+
}
|
|
488
|
+
return out;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
// ── backup phrase and passkey (SPEC §17) ─────────────────────────────────────────────────────────────────
|
|
492
|
+
/** A new 24-word BIP-39 phrase from 32 random bytes made on this device. */
|
|
493
|
+
export function generateBackupPhrase() { return entropyToMnemonic(randomBytes(32), _bip39English); }
|
|
494
|
+
/** The 32-byte entropy of a 24-word phrase (throws on a bad word or checksum). */
|
|
495
|
+
export function phraseToEntropy(phrase) {
|
|
496
|
+
const words = String(phrase).trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
497
|
+
if (words.length !== 24) throw new Error(`a backup phrase has 24 words, got ${words.length}`);
|
|
498
|
+
return mnemonicToEntropy(words.join(" "), _bip39English);
|
|
499
|
+
}
|
|
500
|
+
/** Seal a party under a NEW phrase. Show the phrase to the user once; store only `sealed`. */
|
|
501
|
+
export async function sealBackupWithPhrase(party) {
|
|
502
|
+
const phrase = generateBackupPhrase();
|
|
503
|
+
return { phrase, sealed: await sealBackup(party, phraseToEntropy(phrase)) };
|
|
504
|
+
}
|
|
505
|
+
export async function openBackupWithPhrase(sealed, phrase) { return openBackup(sealed, phraseToEntropy(phrase)); }
|
|
506
|
+
|
|
507
|
+
export const PASSKEY_PRF_LABEL = "enyal-msg-v4-passkey-prf";
|
|
508
|
+
export async function passkeyPrfSalt() { return sha256(u8(PASSKEY_PRF_LABEL)); }
|
|
509
|
+
/** Create a passkey that can back up messaging keys (WebAuthn PRF). Browser/app only. → { credentialId, prfEnabled } */
|
|
510
|
+
export async function createBackupPasskey({ rpId, rpName, userId, userName, credentials = globalThis.navigator && globalThis.navigator.credentials }) {
|
|
511
|
+
if (!credentials) throw new Error("passkeys need a browser (navigator.credentials)");
|
|
512
|
+
const cred = await credentials.create({ publicKey: {
|
|
513
|
+
rp: { id: rpId, name: rpName }, user: { id: u8(userId), name: userName, displayName: userName },
|
|
514
|
+
challenge: randomBytes(32), pubKeyCredParams: [{ type: "public-key", alg: -7 }, { type: "public-key", alg: -257 }],
|
|
515
|
+
authenticatorSelection: { residentKey: "required", userVerification: "required" }, extensions: { prf: {} } } });
|
|
516
|
+
const ext = cred.getClientExtensionResults ? cred.getClientExtensionResults() : {};
|
|
517
|
+
return { credentialId: new Uint8Array(cred.rawId), prfEnabled: !!(ext.prf && ext.prf.enabled) };
|
|
518
|
+
}
|
|
519
|
+
/** The 32-byte backup ikm from a PRF passkey (SPEC §17). Throws when the authenticator gives no PRF result — use the phrase. */
|
|
520
|
+
export async function passkeyBackupEntropy({ rpId, credentialId, credentials = globalThis.navigator && globalThis.navigator.credentials }) {
|
|
521
|
+
if (!credentials) throw new Error("passkeys need a browser (navigator.credentials)");
|
|
522
|
+
const assertion = await credentials.get({ publicKey: {
|
|
523
|
+
rpId, challenge: randomBytes(32), userVerification: "required",
|
|
524
|
+
allowCredentials: credentialId ? [{ type: "public-key", id: credentialId }] : [],
|
|
525
|
+
extensions: { prf: { eval: { first: await passkeyPrfSalt() } } } } });
|
|
526
|
+
const ext = assertion.getClientExtensionResults ? assertion.getClientExtensionResults() : {};
|
|
527
|
+
const first = ext.prf && ext.prf.results && ext.prf.results.first;
|
|
528
|
+
if (!first) throw new Error("this authenticator gives no PRF result — back up with the 24-word phrase instead");
|
|
529
|
+
const out = new Uint8Array(first);
|
|
530
|
+
if (out.length !== 32) throw new Error(`PRF result is ${out.length} bytes, expected 32`);
|
|
531
|
+
return out;
|
|
532
|
+
}
|