@calimero-network/mero-js 33.0.0 → 33.2.0

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.
@@ -0,0 +1,124 @@
1
+ /**
2
+ * The recovery disk's files, as their holder's device handles them.
3
+ *
4
+ * A Calimero node (`merod --recovery-dir`) writes each app's backup sealed to
5
+ * the X25519 public key of whoever upgrades the app: the operator, or the
6
+ * app's organization or owner account. Only that key's private half opens a
7
+ * file, and it never reaches a node. The device:
8
+ *
9
+ * 1. makes the key pair ({@link newBackupKeyPair}) and registers the public
10
+ * half (`POST /orgs/{org}/backup-key` or `/auth/backup-key`, with a passkey);
11
+ * 2. after a loss, gets the files' headers (`GET /ops/recovery-files`, through
12
+ * the operator), checks each with {@link verifyRecoveryHeader} and opens
13
+ * each one's data key with {@link openDataKey};
14
+ * 3. sends those keys straight to the node, over the attested sealed channel
15
+ * (`POST /recover/holder`, {@link holderRecoveryBody}).
16
+ *
17
+ * The format is core's `calimero_client::recovery`: HPKE (RFC 9180) base mode,
18
+ * DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-256-GCM, `info`
19
+ * {@link HPKE_INFO}, `aad` {@link HPKE_AAD}; the header is JSON signed by the
20
+ * node's Ed25519 receipt key over {@link SIGNING_LABEL} and its bytes. The
21
+ * tests open what core sealed. {@link verifyRecoveryAttestation} checks, as
22
+ * core's `verify_attestation` does, that the signing key is an attested node's
23
+ * receipt key: give it the quote verifier the client trusts nodes with.
24
+ */
25
+ import type { VerifyTransportQuote } from '../sealed/sealed.js';
26
+ export declare const RECOVERY_FORMAT = 1;
27
+ export declare const SIGNING_LABEL: Uint8Array;
28
+ export declare const HPKE_INFO: Uint8Array;
29
+ export declare const HPKE_AAD: Uint8Array;
30
+ /** Who holds a backup key: `{ kind: 'operator' }`, `{ kind: 'org', id }`, `{ kind: 'account', id }`. */
31
+ export type BackupHolder = {
32
+ kind: 'operator';
33
+ } | {
34
+ kind: 'org';
35
+ id: string;
36
+ } | {
37
+ kind: 'account';
38
+ id: string;
39
+ };
40
+ /** What a recovery file's header says (core's `recovery::Header`). */
41
+ export interface RecoveryHeader {
42
+ format: number;
43
+ kind: 'app' | 'holder' | 'system' | 'code';
44
+ holder: BackupHolder;
45
+ cluster: string;
46
+ app?: string;
47
+ org?: string;
48
+ hash?: string;
49
+ group: number;
50
+ index: number;
51
+ writtenAt: number;
52
+ merod: string;
53
+ release: string;
54
+ node: number;
55
+ recipient: string;
56
+ enc: string;
57
+ wrappedKey: string;
58
+ size: number;
59
+ sha256: string;
60
+ bodyBytes: number;
61
+ bodySha256: string;
62
+ signingKey: string;
63
+ attestation: unknown;
64
+ }
65
+ /** A listed file as `GET /ops/recovery-files` answers it. */
66
+ export interface ListedRecoveryFile {
67
+ name: string;
68
+ /** The header as signed (JSON text). */
69
+ header: string;
70
+ /** The node's Ed25519 signature, hex. */
71
+ signature: string;
72
+ }
73
+ /** `operator`, `org:<id>` or `account:<id>`: how routes name a holder. */
74
+ export declare function holderKey(holder: BackupHolder): string;
75
+ /**
76
+ * A new backup key pair: keep `secret` (32 raw bytes) off every node, offline;
77
+ * register `publicKey` (64 hex).
78
+ */
79
+ export declare function newBackupKeyPair(): Promise<{
80
+ secret: Uint8Array;
81
+ publicKey: string;
82
+ }>;
83
+ /** The public key (64 hex) of a backup key's secret. */
84
+ export declare function backupPublicKey(secret: Uint8Array): Promise<string>;
85
+ /**
86
+ * Check a header against the node's signature and read it. Refuses a format
87
+ * newer than this release reads and a signature that does not hold.
88
+ */
89
+ export declare function verifyRecoveryHeader(file: Pick<ListedRecoveryFile, 'header' | 'signature'>): Promise<RecoveryHeader>;
90
+ /** Open a file's data key (32 bytes) with the holder's secret: HPKE base mode. */
91
+ export declare function openDataKey(header: RecoveryHeader, secret: Uint8Array): Promise<Uint8Array>;
92
+ /** `{ file, key }`: a file and its opened data key, as the recovery routes take them. */
93
+ export interface OpenedRecoveryFile {
94
+ file: string;
95
+ key: string;
96
+ }
97
+ /**
98
+ * The body of `POST /recover/holder` from a holder's listed files: the newest
99
+ * `holder` file, the newest file of each app in `apps` (all of them when
100
+ * absent) and every code file, each checked and opened with `secret`; with
101
+ * `verifyQuote`, each one's attestation too ({@link verifyRecoveryAttestation}).
102
+ */
103
+ export declare function holderRecoveryBody(holder: BackupHolder, files: ListedRecoveryFile[], secret: Uint8Array, options?: {
104
+ apps?: string[];
105
+ verifyQuote?: VerifyTransportQuote;
106
+ }): Promise<{
107
+ holder: string;
108
+ slice: OpenedRecoveryFile;
109
+ apps: OpenedRecoveryFile[];
110
+ code: OpenedRecoveryFile[];
111
+ }>;
112
+ /** The nonce a node's recovery attestation binds (core's `recovery::attestation_nonce`), hex. */
113
+ export declare function recoveryAttestationNonce(cluster: string, node: number): Promise<string>;
114
+ /**
115
+ * What a receipt-key quote binds after its nonce (core's `receipt_key_binding`),
116
+ * hex: the key and the cluster's governance, as the node serialized it.
117
+ */
118
+ export declare function receiptKeyBinding(receiptKey: Uint8Array, governance: unknown): Promise<string>;
119
+ /**
120
+ * Check that the key that signed `header` is a node's receipt key, attested
121
+ * (`purpose=receipts`) by a quote `verifyQuote` accepts: attested hardware
122
+ * wrote the file. Rejects with the reason.
123
+ */
124
+ export declare function verifyRecoveryAttestation(header: RecoveryHeader, verifyQuote: VerifyTransportQuote): Promise<void>;
@@ -0,0 +1,196 @@
1
+ /**
2
+ * The recovery disk's files, as their holder's device handles them.
3
+ *
4
+ * A Calimero node (`merod --recovery-dir`) writes each app's backup sealed to
5
+ * the X25519 public key of whoever upgrades the app: the operator, or the
6
+ * app's organization or owner account. Only that key's private half opens a
7
+ * file, and it never reaches a node. The device:
8
+ *
9
+ * 1. makes the key pair ({@link newBackupKeyPair}) and registers the public
10
+ * half (`POST /orgs/{org}/backup-key` or `/auth/backup-key`, with a passkey);
11
+ * 2. after a loss, gets the files' headers (`GET /ops/recovery-files`, through
12
+ * the operator), checks each with {@link verifyRecoveryHeader} and opens
13
+ * each one's data key with {@link openDataKey};
14
+ * 3. sends those keys straight to the node, over the attested sealed channel
15
+ * (`POST /recover/holder`, {@link holderRecoveryBody}).
16
+ *
17
+ * The format is core's `calimero_client::recovery`: HPKE (RFC 9180) base mode,
18
+ * DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-256-GCM, `info`
19
+ * {@link HPKE_INFO}, `aad` {@link HPKE_AAD}; the header is JSON signed by the
20
+ * node's Ed25519 receipt key over {@link SIGNING_LABEL} and its bytes. The
21
+ * tests open what core sealed. {@link verifyRecoveryAttestation} checks, as
22
+ * core's `verify_attestation` does, that the signing key is an attested node's
23
+ * receipt key: give it the quote verifier the client trusts nodes with.
24
+ */
25
+ import { concat, fromHex, hex } from '../crypto/internal.js';
26
+ import { dh, x25519KeyPair } from '../sealed/noise.js';
27
+ export const RECOVERY_FORMAT = 1;
28
+ export const SIGNING_LABEL = new TextEncoder().encode('calimero.recovery-backup.v1\0');
29
+ export const HPKE_INFO = new TextEncoder().encode('calimero.recovery-backup.v1');
30
+ export const HPKE_AAD = new TextEncoder().encode('calimero.recovery-backup.key.v1');
31
+ const KEM_ID = 0x0020; // DHKEM(X25519, HKDF-SHA256)
32
+ const KDF_ID = 0x0001; // HKDF-SHA256
33
+ const AEAD_ID = 0x0002; // AES-256-GCM
34
+ const MODE_BASE = 0x00;
35
+ const utf8 = (s) => new TextEncoder().encode(s);
36
+ const i2osp2 = (n) => new Uint8Array([(n >> 8) & 0xff, n & 0xff]);
37
+ const KEM_SUITE = concat(utf8('KEM'), i2osp2(KEM_ID));
38
+ const HPKE_SUITE = concat(utf8('HPKE'), i2osp2(KEM_ID), i2osp2(KDF_ID), i2osp2(AEAD_ID));
39
+ /** `operator`, `org:<id>` or `account:<id>`: how routes name a holder. */
40
+ export function holderKey(holder) {
41
+ return holder.kind === 'operator' ? 'operator' : `${holder.kind}:${holder.id}`;
42
+ }
43
+ /**
44
+ * A new backup key pair: keep `secret` (32 raw bytes) off every node, offline;
45
+ * register `publicKey` (64 hex).
46
+ */
47
+ export async function newBackupKeyPair() {
48
+ const secret = crypto.getRandomValues(new Uint8Array(32));
49
+ return { secret, publicKey: await backupPublicKey(secret) };
50
+ }
51
+ /** The public key (64 hex) of a backup key's secret. */
52
+ export async function backupPublicKey(secret) {
53
+ return hex((await x25519KeyPair(secret)).publicKey);
54
+ }
55
+ /**
56
+ * Check a header against the node's signature and read it. Refuses a format
57
+ * newer than this release reads and a signature that does not hold.
58
+ */
59
+ export async function verifyRecoveryHeader(file) {
60
+ const bytes = utf8(file.header);
61
+ const header = JSON.parse(file.header);
62
+ if (typeof header.format !== 'number' || header.format > RECOVERY_FORMAT) {
63
+ throw new Error(`recovery file format ${header.format} is not one this release reads (${RECOVERY_FORMAT})`);
64
+ }
65
+ const key = await crypto.subtle.importKey('raw', fromHex(header.signingKey, 'signing key', 32), { name: 'Ed25519' }, false, ['verify']);
66
+ const ok = await crypto.subtle.verify('Ed25519', key, fromHex(file.signature, 'signature', 64), concat(SIGNING_LABEL, bytes));
67
+ if (!ok)
68
+ throw new Error("the node's signature over the header does not hold");
69
+ return header;
70
+ }
71
+ async function hmac(key, data) {
72
+ const raw = key.length === 0 ? new Uint8Array(32) : key;
73
+ const k = await crypto.subtle.importKey('raw', raw, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
74
+ return new Uint8Array(await crypto.subtle.sign('HMAC', k, data));
75
+ }
76
+ async function expand(prk, info, length) {
77
+ const out = new Uint8Array(length);
78
+ let previous = new Uint8Array(0);
79
+ for (let i = 1, offset = 0; offset < length; i += 1) {
80
+ previous = await hmac(prk, concat(previous, info, new Uint8Array([i])));
81
+ out.set(previous.subarray(0, Math.min(previous.length, length - offset)), offset);
82
+ offset += previous.length;
83
+ }
84
+ return out;
85
+ }
86
+ const labeledExtract = (suite, salt, label, ikm) => hmac(salt, concat(utf8('HPKE-v1'), suite, utf8(label), ikm));
87
+ const labeledExpand = (suite, prk, label, info, length) => expand(prk, concat(i2osp2(length), utf8('HPKE-v1'), suite, utf8(label), info), length);
88
+ /** Open a file's data key (32 bytes) with the holder's secret: HPKE base mode. */
89
+ export async function openDataKey(header, secret) {
90
+ const recipient = await x25519KeyPair(secret);
91
+ if (hex(recipient.publicKey) !== header.recipient) {
92
+ throw new Error('this key is not the one the file was sealed to');
93
+ }
94
+ const enc = fromHex(header.enc, 'encapsulated key', 32);
95
+ const dhValue = await dh(recipient.privateKey, enc);
96
+ const empty = new Uint8Array(0);
97
+ const prk = await labeledExtract(KEM_SUITE, empty, 'eae_prk', dhValue);
98
+ const shared = await labeledExpand(KEM_SUITE, prk, 'shared_secret', concat(enc, recipient.publicKey), 32);
99
+ const pskIdHash = await labeledExtract(HPKE_SUITE, empty, 'psk_id_hash', empty);
100
+ const infoHash = await labeledExtract(HPKE_SUITE, empty, 'info_hash', HPKE_INFO);
101
+ const context = concat(new Uint8Array([MODE_BASE]), pskIdHash, infoHash);
102
+ const schedule = await labeledExtract(HPKE_SUITE, shared, 'secret', empty);
103
+ const key = await labeledExpand(HPKE_SUITE, schedule, 'key', context, 32);
104
+ const nonce = await labeledExpand(HPKE_SUITE, schedule, 'base_nonce', context, 12);
105
+ const aes = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['decrypt']);
106
+ let plain;
107
+ try {
108
+ plain = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce, additionalData: HPKE_AAD }, aes, fromHex(header.wrappedKey, 'wrapped key', 48)));
109
+ }
110
+ catch {
111
+ throw new Error('this key does not open the file');
112
+ }
113
+ if (plain.length !== 32)
114
+ throw new Error('the data key is not 32 bytes');
115
+ return plain;
116
+ }
117
+ /**
118
+ * The body of `POST /recover/holder` from a holder's listed files: the newest
119
+ * `holder` file, the newest file of each app in `apps` (all of them when
120
+ * absent) and every code file, each checked and opened with `secret`; with
121
+ * `verifyQuote`, each one's attestation too ({@link verifyRecoveryAttestation}).
122
+ */
123
+ export async function holderRecoveryBody(holder, files, secret, options = {}) {
124
+ const checked = [];
125
+ for (const f of [...files].sort((a, b) => a.name.localeCompare(b.name))) {
126
+ const header = await verifyRecoveryHeader(f);
127
+ if (options.verifyQuote)
128
+ await verifyRecoveryAttestation(header, options.verifyQuote);
129
+ if (holderKey(header.holder) !== holderKey(holder)) {
130
+ throw new Error(`${f.name} is ${holderKey(header.holder)}'s, not ${holderKey(holder)}'s`);
131
+ }
132
+ checked.push({ name: f.name, header });
133
+ }
134
+ const open = async (c) => ({
135
+ file: c.name,
136
+ key: hex(await openDataKey(c.header, secret)),
137
+ });
138
+ const slice = checked.filter((c) => c.header.kind === 'holder').pop();
139
+ if (!slice)
140
+ throw new Error(`no holder file of ${holderKey(holder)}`);
141
+ const newestByApp = new Map();
142
+ for (const c of checked) {
143
+ if (c.header.kind === 'app' && c.header.app && (!options.apps || options.apps.includes(c.header.app))) {
144
+ newestByApp.set(c.header.app, c);
145
+ }
146
+ }
147
+ return {
148
+ holder: holderKey(holder),
149
+ slice: await open(slice),
150
+ apps: await Promise.all([...newestByApp.values()].map(open)),
151
+ code: await Promise.all(checked.filter((c) => c.header.kind === 'code').map(open)),
152
+ };
153
+ }
154
+ async function sha256(data) {
155
+ return new Uint8Array(await crypto.subtle.digest('SHA-256', data));
156
+ }
157
+ /** The nonce a node's recovery attestation binds (core's `recovery::attestation_nonce`), hex. */
158
+ export async function recoveryAttestationNonce(cluster, node) {
159
+ const name = utf8(cluster);
160
+ const len = new Uint8Array(4);
161
+ new DataView(len.buffer).setUint32(0, name.length, false);
162
+ const id = new Uint8Array(8);
163
+ new DataView(id.buffer).setBigUint64(0, BigInt(node), false);
164
+ return hex(await sha256(concat(utf8('calimero.recovery-backup.attest.v1\0'), len, name, id)));
165
+ }
166
+ /**
167
+ * What a receipt-key quote binds after its nonce (core's `receipt_key_binding`),
168
+ * hex: the key and the cluster's governance, as the node serialized it.
169
+ */
170
+ export async function receiptKeyBinding(receiptKey, governance) {
171
+ const g = await sha256(utf8(JSON.stringify(governance)));
172
+ return hex(await sha256(concat(utf8('calimero.tee-attest.receipt-key.v2'), receiptKey, g)));
173
+ }
174
+ /**
175
+ * Check that the key that signed `header` is a node's receipt key, attested
176
+ * (`purpose=receipts`) by a quote `verifyQuote` accepts: attested hardware
177
+ * wrote the file. Rejects with the reason.
178
+ */
179
+ export async function verifyRecoveryAttestation(header, verifyQuote) {
180
+ const doc = header.attestation;
181
+ if (!doc || typeof doc.quote !== 'string')
182
+ throw new Error('the file carries no attestation');
183
+ if (doc.cluster !== header.cluster || doc.node !== header.node) {
184
+ throw new Error("the attestation is another node's");
185
+ }
186
+ if (doc.receiptKey !== header.signingKey) {
187
+ throw new Error('the attested key is not the one that signed the file');
188
+ }
189
+ const nonce = await recoveryAttestationNonce(header.cluster, header.node);
190
+ if (doc.nonce !== nonce)
191
+ throw new Error('the attestation is not over the recovery nonce');
192
+ const reportDataSuffix = await receiptKeyBinding(fromHex(header.signingKey, 'signing key', 32), doc.governance);
193
+ const ok = await verifyQuote({ quoteB64: doc.quote, nonce, reportDataSuffix });
194
+ if (!ok)
195
+ throw new Error('the quote was not accepted');
196
+ }
@@ -172,12 +172,15 @@ export declare class NodeTransport implements Transport {
172
172
  private current;
173
173
  /** The refresh under way, which every request that needs one shares. */
174
174
  private refreshing;
175
- private readonly retry;
175
+ /** The backoff between retries, for a caller that retries a request the routes do not. */
176
+ readonly retry: Required<RetryOptions>;
176
177
  /** Rejections of the underlying `fetch` itself: the node could not be reached or dropped the connection. */
177
178
  private readonly networkFailures;
178
179
  /** The directory the node list came from, if it came from one. */
179
180
  private source;
180
181
  constructor(options: NodeTransportOptions);
182
+ /** Whether `error` is a `fetch` that got no answer: the node could not be reached or dropped the connection. */
183
+ isNetworkFailure(error: unknown): boolean;
181
184
  /** Re-read the node list from `source` when it is due, and after a failover. */
182
185
  useDirectory(source: DirectorySource): void;
183
186
  /** The node requests go to now: `baseUrl`, until a `421 WRONG_NODE` or a failover moved on. */
@@ -185,6 +185,10 @@ export class NodeTransport {
185
185
  };
186
186
  this.raw = raw;
187
187
  }
188
+ /** Whether `error` is a `fetch` that got no answer: the node could not be reached or dropped the connection. */
189
+ isNetworkFailure(error) {
190
+ return error instanceof TypeError && this.networkFailures.has(error);
191
+ }
188
192
  /** Re-read the node list from `source` when it is due, and after a failover. */
189
193
  useDirectory(source) {
190
194
  this.source = source;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@calimero-network/mero-js",
3
- "version": "33.0.0",
3
+ "version": "33.2.0",
4
4
  "description": "JavaScript client for Calimero 1.0: attested TEE nodes, a sealed channel, passkeys and API keys",
5
5
  "type": "module",
6
6
  "exports": {