S15 TypeScript seals: seal, open and sealAnonymous beside go/seal

The forge module's minting processes are TypeScript and the vault's two steps need ADR 0206's
sealed box and the NaCl anonymous box its intake opens; both now live once in mesh-sdk, proven
byte for byte against the Go package's bytes (tweetnacl 1.0.3 and blakejs 1.2.1 pinned).

Builds: design 47 H2 §808, §822, H-A-407 and its addendum
This commit is contained in:
2026-11-22 00:59:54 +01:00
parent 3ad8ccbc06
commit d6cdf3b8f5
8 changed files with 376 additions and 2 deletions
+1
View File
@@ -16,3 +16,4 @@ export * as state from "./state/index.js";
export * as runtime from "./runtime/index.js";
export * as callers from "./callers/index.js";
export * as views from "./views/index.js";
export * as seal from "./seal/index.js";
+181
View File
@@ -0,0 +1,181 @@
// The mesh's sealed box in TypeScript (novox/hq ADR 0183, ADR 0206; design 47 H2, lead answer H-A-407), the same
// box as the Go package seal (go/seal) byte for byte: a value sealed to one recipient's public key, which only that
// recipient's private key opens. X25519 for the agreement, HKDF-SHA256 for the key, AES-256-GCM for the box.
//
// A box is `{ v: 1, eph, iv, tag, ct }`, every field standard base64; `eph` is the one-time public key as SPKI DER.
// The key is derived with the salt eph-DER ‖ the recipient's raw public key and the info "novox-mesh sealed box v1",
// so a box cannot be re-addressed to another key. Keys travel as PEM: the public key as SPKI ("PUBLIC KEY"), the
// private key as PKCS #8 ("PRIVATE KEY"). Node's crypto only.
//
// sealAnonymous is the other seal, the NaCl anonymous box (libsodium's crypto_box_seal) the vault's intake opens:
// X25519 and XSalsa20-Poly1305 under a one-time key, the nonce BLAKE2b-24 of the one-time public key ‖ the recipient's,
// the box the one-time public key ‖ the sealed bytes. From two pinned libraries, tweetnacl and blakejs (H-A-407).
import {
createCipheriv,
createDecipheriv,
createPrivateKey,
createPublicKey,
diffieHellman,
generateKeyPairSync,
hkdfSync,
randomBytes,
type KeyObject,
} from "node:crypto";
import nacl from "tweetnacl";
import blakejs from "blakejs";
/** A value sealed to one recipient, as it travels in JSON (go/seal's Box). */
export interface Box {
v: number;
eph: string;
iv: string;
tag: string;
ct: string;
}
/** A recipient's keypair as the two PEM strings it is kept and sent as (go/seal's KeyPair). */
export interface KeyPair {
publicKey: string;
privateKey: string;
}
/** The only box version open opens. */
export const VERSION = 1;
const INFO = "novox-mesh sealed box v1";
// PKCS #8 DER of an X25519 private key is this prefix and the key's 32 raw bytes (RFC 8410).
const X25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b656e04220420", "hex");
/** A fresh X25519 keypair, PEM-encoded. */
export function generateKeyPair(): KeyPair {
const { publicKey, privateKey } = generateKeyPairSync("x25519");
return {
publicKey: publicKey.export({ type: "spki", format: "pem" }).toString(),
privateKey: privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
};
}
/** Seals plaintext to the recipient's PEM public key, with a fresh one-time key and iv. */
export function seal(plaintext: string, recipientPEM: string): Box {
const eph = generateKeyPairSync("x25519").privateKey;
return sealWith(plaintext, recipientPEM, eph, randomBytes(12));
}
/**
* sealWith is seal with its two sources of randomness given: the one-time key (a KeyObject, or its 32 raw bytes) and
* the iv. Exported for the byte-for-byte tests against the Go package's vectors; a caller seals with seal.
*/
export function sealWith(plaintext: string, recipientPEM: string, eph: KeyObject | Uint8Array, iv: Uint8Array): Box {
const recipient = publicFromPEM(recipientPEM);
const ephKey = eph instanceof Uint8Array ? privateFromRaw(eph) : eph;
const secret = diffieHellman({ privateKey: ephKey, publicKey: recipient });
const ephDER = createPublicKey(ephKey).export({ type: "spki", format: "der" });
const cipher = createCipheriv("aes-256-gcm", boxKey(secret, ephDER, rawPublic(recipient)), iv);
const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
const b64 = (b: Uint8Array) => Buffer.from(b).toString("base64");
return { v: VERSION, eph: b64(ephDER), iv: b64(iv), tag: b64(cipher.getAuthTag()), ct: b64(ct) };
}
/**
* Opens a box with the recipient's PEM private key. It throws for a box sealed to another key, one changed in any
* field, or one of another version.
*/
export function open(box: Box, privatePEM: string): string {
if (box.v !== VERSION) {
throw new Error(`a sealed box of version ${box.v}, not ${VERSION}`);
}
const priv = privateFromPEM(privatePEM);
const ephDER = Buffer.from(box.eph, "base64");
let eph: KeyObject;
try {
eph = createPublicKey({ key: ephDER, format: "der", type: "spki" });
} catch (e) {
throw new Error(`the box's eph: ${(e as Error).message}`);
}
if (eph.asymmetricKeyType !== "x25519") {
throw new Error("the box's eph is not an X25519 key");
}
const secret = diffieHellman({ privateKey: priv, publicKey: eph });
const iv = Buffer.from(box.iv, "base64");
const tag = Buffer.from(box.tag, "base64");
if (iv.length !== 12 || tag.length !== 16) {
throw new Error("the box does not open with this key");
}
try {
const decipher = createDecipheriv("aes-256-gcm", boxKey(secret, ephDER, rawPublic(createPublicKey(priv))), iv);
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(Buffer.from(box.ct, "base64")), decipher.final()]).toString("utf8");
} catch {
throw new Error("the box does not open with this key");
}
}
function publicFromPEM(pem: string): KeyObject {
let k: KeyObject;
try {
k = createPublicKey(pem);
} catch {
throw new Error("not a PEM public key");
}
if (k.asymmetricKeyType !== "x25519") {
throw new Error("not an X25519 public key");
}
return k;
}
function privateFromPEM(pem: string): KeyObject {
let k: KeyObject;
try {
k = createPrivateKey(pem);
} catch {
throw new Error("not a PEM private key");
}
if (k.asymmetricKeyType !== "x25519") {
throw new Error("not an X25519 private key");
}
return k;
}
function privateFromRaw(raw: Uint8Array): KeyObject {
if (raw.length !== 32) {
throw new Error("an X25519 private key is 32 bytes");
}
return createPrivateKey({ key: Buffer.concat([X25519_PKCS8_PREFIX, raw]), format: "der", type: "pkcs8" });
}
// rawPublic is an X25519 public key's 32 raw bytes: the end of its SPKI DER.
function rawPublic(k: KeyObject): Buffer {
const der = k.export({ type: "spki", format: "der" });
return der.subarray(der.length - 32);
}
// boxKey is HKDF-SHA256 (RFC 5869) for one 32-byte block, salted with eph-DER ‖ the recipient's raw public key.
function boxKey(secret: Uint8Array, ephDER: Uint8Array, recipientRaw: Uint8Array): Buffer {
return Buffer.from(hkdfSync("sha256", secret, Buffer.concat([ephDER, recipientRaw]), INFO, 32));
}
/**
* Seals value to sealTo, a raw X25519 public key in standard base64 (the vault's `seal_to`), in the NaCl anonymous
* box, answered in standard base64: what golang.org/x/crypto/nacl/box's SealAnonymous makes and OpenAnonymous opens.
*/
export function sealAnonymous(value: string | Uint8Array, sealTo: string): string {
return sealAnonymousWith(value, sealTo, nacl.randomBytes(nacl.box.secretKeyLength));
}
/**
* sealAnonymousWith is sealAnonymous with its one-time private key given (32 bytes). Exported for the byte-for-byte
* tests against the Go package's bytes; a caller seals with sealAnonymous.
*/
export function sealAnonymousWith(value: string | Uint8Array, sealTo: string, ephSecret: Uint8Array): string {
const recipient = new Uint8Array(Buffer.from(sealTo.trim(), "base64"));
if (recipient.length !== nacl.box.publicKeyLength) {
throw new Error("the key to seal to is not a raw X25519 public key in base64");
}
const eph = nacl.box.keyPair.fromSecretKey(new Uint8Array(ephSecret));
const nonce = blakejs.blake2b(Buffer.concat([eph.publicKey, recipient]), undefined, nacl.box.nonceLength);
const message = typeof value === "string" ? new Uint8Array(Buffer.from(value, "utf8")) : new Uint8Array(value);
const sealed = nacl.box(message, nonce, recipient, eph.secretKey);
return Buffer.concat([eph.publicKey, sealed]).toString("base64");
}