node-tpm2 0.0.4-beta.2 → 0.0.4-beta.4

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.
@@ -114,6 +114,15 @@ try {
114
114
  }
115
115
  ```
116
116
 
117
+ ## Validate after install
118
+
119
+ ```bash
120
+ npm ls node-tpm2
121
+ node node_modules/node-tpm2/examples/smoke-test.mjs runtime
122
+ ```
123
+
124
+ Smoke-test is under `node_modules/node-tpm2/examples/` after `npm install`, not `./examples/` at your project root.
125
+
117
126
  ## What ships in npm
118
127
 
119
128
  The published package contains the JavaScript API, type definitions, user docs, and the smoke-test example — **not** Rust sources, `tbs-probe`, or spike binaries. Those stay in the git repo for developers.
@@ -0,0 +1,220 @@
1
+ # API roadmap
2
+
3
+ Plan to complete the public `node-tpm2` API: subsystem namespaces, exportable key
4
+ handles, and parity between Linux (TBS) and Windows (TBS for general ops, PCP for
5
+ attestation persistence where required).
6
+
7
+ This library is standalone. Consumers integrate via npm; nothing in this repo references
8
+ or depends on downstream products.
9
+
10
+ ---
11
+
12
+ ## Current state (0.0.4-beta)
13
+
14
+ **Shipped**
15
+
16
+ | Namespace | Methods |
17
+ |-----------|---------|
18
+ | Root | `Tpm.isAvailable()`, `Tpm.open()`, `Tpm.info()` |
19
+ | `tpm.pcr` | `read`, `extend` |
20
+ | `tpm.attest` | `provisionAk`, `quote`, `ekCertificate` |
21
+ | `AkHandle` | `export`, `quote`, `activateCredential`, `publicKeyDer` |
22
+ | Flat | `Tpm.pcrRead`, `Tpm.pcrExtend`, `readPublic`, `readEkCertificate`, `quote`, `provisionAk`, `activateCredential` |
23
+
24
+ **Rust foundation already present (not exposed on `TpmHandle` yet):**
25
+
26
+ - Command codec: `CreatePrimary`, `Create`, `Load`, `FlushContext`, `Quote`, `GetRandom`, sessions, policy digest
27
+ - Linux key path: `keys.rs` (storage primary, AK create/load)
28
+ - Windows PCP path: `pcp.rs` (identity AK, machine DACL, quote, activation)
29
+ - NV: EK certificate read via fixed index
30
+ - Credential: full activate-credential flow (Linux TBS; Windows PCP)
31
+
32
+ ---
33
+
34
+ ## Target API
35
+
36
+ ```typescript
37
+ import { Tpm, TpmError } from 'node-tpm2';
38
+
39
+ await using tpm = await Tpm.open();
40
+
41
+ // ── Root ──────────────────────────────────────────────────────────
42
+ await Tpm.isAvailable();
43
+ await tpm.info();
44
+
45
+ // ── random ────────────────────────────────────────────────────────
46
+ await tpm.random.bytes(32);
47
+
48
+ // ── pcr ───────────────────────────────────────────────────────────
49
+ await tpm.pcr.read([0, 1, 7], 'sha256');
50
+ await tpm.pcr.extend(7, digest); // digest: Buffer, 32 bytes for sha256 bank
51
+
52
+ // ── nv ────────────────────────────────────────────────────────────
53
+ await tpm.nv.read('0x01c00002'); // handle or well-known name
54
+ await tpm.nv.write('0x01800001', data, opts); // opts: auth, offset — policy-dependent
55
+
56
+ // ── keys ──────────────────────────────────────────────────────────
57
+ const key = await tpm.keys.create({
58
+ type: 'ecc', // 'ecc' | 'rsa'
59
+ sign: true,
60
+ decrypt: false,
61
+ });
62
+ const blob = key.export();
63
+ const loaded = await tpm.keys.load(blob);
64
+ await loaded.sign(digest); // Buffer in → signature Buffer out
65
+ await loaded.decrypt(cipher); // when key was created with decrypt: true
66
+
67
+ // ── seal ──────────────────────────────────────────────────────────
68
+ const sealed = await tpm.seal({
69
+ data: secret,
70
+ pcrSelection: [7],
71
+ pcrPolicy: 'current' | digest, // bind to current PCR state or explicit digest
72
+ });
73
+ const plain = await tpm.unseal(sealed);
74
+
75
+ // ── attest (opinionated attestation — unchanged intent) ───────────
76
+ const ak = await tpm.attest.provisionAk({ scope, keyName, overwrite });
77
+ await ak.quote({ pcrSelection, qualifyingData });
78
+ await tpm.attest.ekCertificate();
79
+ await ak.activateCredential({ credentialBlob, secret });
80
+
81
+ // ── plumbing ──────────────────────────────────────────────────────
82
+ await tpm.readPublic('0x81010001');
83
+ ```
84
+
85
+ Flat equivalents remain on `Tpm.*` for every operation (thin wrappers over the same native calls).
86
+
87
+ ---
88
+
89
+ ## Platform strategy
90
+
91
+ | Concern | Linux | Windows |
92
+ |---------|-------|---------|
93
+ | Transport | `/dev/tpmrm0` | TBS (`Tbsip_Submit_Command`) |
94
+ | General keys (`keys.*`) | TBS wrapped TPM2B blobs | TBS wrapped blobs (same codec as Linux) |
95
+ | Attestation AK (`attest.provisionAk`) | TBS wrapped ECDSA AK | NCrypt PCP persisted key (`PCP1` / `PCP2` blob) |
96
+ | Quote / activate | Load blob transiently → operate → flush | PCP open by key name + TBS for quote crypto |
97
+ | Seal / unseal | TBS policy-bound object | TBS (same commands; no PCP required) |
98
+ | NV | TBS NV_Read / NV_Write | TBS NV commands |
99
+
100
+ **Rule:** PCP is for **attestation key persistence and fleet cross-user quote**, not for every key operation. General `keys.*` and `seal` use the shared TBS command path on both OSes so behavior and blobs stay aligned.
101
+
102
+ ---
103
+
104
+ ## Implementation phases
105
+
106
+ ### Phase 0 — API hygiene ✅ (this branch)
107
+
108
+ **Goal:** Published types match runtime; namespace skeleton on `TpmHandle`.
109
+
110
+ - [x] Remove bogus top-level exports from `index.d.ts`
111
+ - [x] Add namespace objects on `TpmHandle`: `random`, `nv`, `keys`, `seal`, `pcr.extend`
112
+ - [x] Add `KeyHandle` / `KeyBlob` types; unimplemented methods throw `NOT_SUPPORTED`
113
+ - [ ] Acceptance: `npm run verify:package`
114
+
115
+ ### Phase 1 — `tpm.random.bytes` ✅ (this branch)
116
+
117
+ **Goal:** Public `GetRandom`.
118
+
119
+ - [x] Rust: `random.rs` — marshal `TPM2_GetRandom`, ≤64 bytes per call, loop for larger
120
+ - [x] NAPI: `randomBytes`
121
+ - [x] JS: `tpm.random.bytes(n)`, `Tpm.randomBytes(n)`
122
+ - [ ] Tests: integration on Linux + Windows VM
123
+
124
+ ### Phase 2 — `tpm.keys` ✅ (this branch; decrypt deferred)
125
+
126
+ **Goal:** General exportable signing keys via TBS wrapped blobs (both OSes).
127
+
128
+ - [x] `keys.create` / `keys.load` / `key.sign` — ECC + RSA sign keys
129
+ - [x] Unit tests: templates, Sign command golden, option validation, HW roundtrip
130
+ - [ ] `key.decrypt` — RSA OAEP (deferred)
131
+ - [ ] Windows VM sign smoke
132
+
133
+ ### Phase 3 — `tpm.pcr.extend` ✅ (this branch)
134
+
135
+ **Goal:** Software measurement hook.
136
+
137
+ - [x] Rust: `TPM2_PCR_Extend` with SHA-256 bank selection matching `pcr.read`.
138
+ - [x] JS: `tpm.pcr.extend(index, digest)`.
139
+ - [x] Tests: extend → read → digest changed.
140
+ - [x] Caveats: some firmware policies lock PCRs; surface `TPM_RC` / `COMMAND_BLOCKED` cleanly.
141
+ - [ ] Acceptance: works unprivileged on swtpm and dev VM where PCRs are extendable.
142
+
143
+ ### Phase 4 — `tpm.nv` (1 week)
144
+
145
+ **Goal:** General NV index access beyond EK cert helper.
146
+
147
+ - Rust:
148
+ - `nv.read_public(handle)` — already partially in `nv.rs`; expose metadata (size, attributes).
149
+ - `nv.read(handle, offset, size)`.
150
+ - `nv.write(handle, offset, data, auth?)` — auth optional buffer for password/session auth.
151
+ - `nv.define` / `nv.undefine` — **defer** unless needed (owner-auth, high privilege).
152
+ - Migrate `readEkCertificate` to call `nv.read` on well-known EK cert index internally.
153
+ - JS: `tpm.nv.read`, `tpm.nv.write`; document which indices are safe on consumer hardware.
154
+ - Acceptance: EK cert read unchanged; optional integration test against swtpm-defined NV index.
155
+
156
+ ### Phase 5 — `tpm.seal` / `tpm.unseal` (1–2 weeks)
157
+
158
+ **Goal:** TPM-bound secrets with optional PCR policy.
159
+
160
+ - Rust:
161
+ - `seal({ data, pcrSelection?, name? })` — create storage primary or use fixed template, `Create` sealed object, export blob.
162
+ - `unseal(blob)` — load + `Unseal`.
163
+ - PCR policy: `PolicyPCR` session when `pcrSelection` provided.
164
+ - JS: `tpm.seal`, `tpm.unseal`; flat aliases.
165
+ - Tests: roundtrip without PCR; roundtrip with PCR extend before unseal; negative test wrong PCR.
166
+ - Acceptance: Linux + Windows TBS; document that PCR-bound seal requires extend permission on chosen indices.
167
+
168
+ ### Phase 6 — Hardening & 1.0 (ongoing)
169
+
170
+ - Real hardware matrix (firmware TPM, Hyper-V, physical laptop).
171
+ - Fuzz/malformed response handling on codec.
172
+ - Stable semver on error codes (`latest` tag).
173
+ - Performance: reuse TBS context per `TpmHandle` where safe (today: per-call context on Windows TBS path).
174
+
175
+ ---
176
+
177
+ ## Dependency order
178
+
179
+ ```
180
+ Phase 0 (hygiene)
181
+
182
+ Phase 1 (random) ─────────────────────────────┐
183
+ ↓ │
184
+ Phase 2 (keys) ──→ Phase 5 (seal uses keys) │
185
+ ↓ │
186
+ Phase 3 (pcr.extend) ──→ Phase 5 (PCR policy) │
187
+ ↓ │
188
+ Phase 4 (nv) ─────────────────────────────────┘
189
+
190
+ Phase 6 (1.0)
191
+ ```
192
+
193
+ Phases 1 and 3 can run in parallel after Phase 0. Phase 2 blocks Phase 5. Phase 4 is independent.
194
+
195
+ ---
196
+
197
+ ## Testing strategy
198
+
199
+ | Layer | Tool |
200
+ |-------|------|
201
+ | Command golden bytes | Rust unit tests |
202
+ | Privilege / elevation | `tbs-probe` (repo only) + `examples/smoke-test.mjs` (published) |
203
+ | Cross-platform | Linux CI + Windows VM manual gate before each beta |
204
+ | NV / seal edge cases | swtpm with scripted NV define in CI (Linux) |
205
+
206
+ ---
207
+
208
+ ## Out of scope (remain non-goals)
209
+
210
+ - macOS TPM (no hardware).
211
+ - Persistent handle / `EvictControl` in the public API.
212
+ - Full TPM2 policy language exposed to JS (only fixed recipes: activate-credential, seal-with-PCR).
213
+ - PKCS#11, OpenSSL engine, or platform keystore integration.
214
+
215
+ ---
216
+
217
+ ## Versioning
218
+
219
+ - Implement phases on `dev`; beta publish after each phase or logical group (e.g. beta.4 = random + keys).
220
+ - `1.0.0` when Phases 0–5 acceptance criteria pass on real hardware and API surface in README matches implementation.
@@ -23,6 +23,24 @@ On Windows, node-tpm2 uses the **Microsoft Platform Crypto Provider** for attest
23
23
 
24
24
  Blob layout: magic + key name + PCP creation attestation fields (`public` holds metadata; `private` is empty).
25
25
 
26
+ ## Threat model: device vs application
27
+
28
+ **A quote proves an enrolled device, not a specific app or user.**
29
+
30
+ On Windows, a machine-scoped attestation key (`PCP2`) is a **host-local capability**, not a secret. The exported blob is mainly a **locator**: magic, `keyName`, and scope. At quote time the library opens the persisted PCP key by that name. Any standard-user process that knows the fleet `keyName` can obtain a valid quote from the same AK — that is how cross-user runtime quoting works after one-time elevated provisioning.
31
+
32
+ This is inherent to device attestation on Windows (and similar on Linux: anyone with read/write on `/dev/tpmrm0` can use a copied AK blob on the same TPM). It is **not** a library bug and should not be “fixed” by treating the blob as a password.
33
+
34
+ | What a quote establishes | What it does **not** establish |
35
+ |--------------------------|--------------------------------|
36
+ | The TPM that was enrolled still holds the AK | Which Windows process produced the quote |
37
+ | PCR values at quote time match the attestation | Which human user clicked “sign in” |
38
+ | `qualifyingData` matches what the verifier sent (if you set it) | That only your product binary ran |
39
+
40
+ **Your enrollment service** should bind identity at enroll time: verify `akPublicDer`, optionally verify PCP creation attestation fields in the blob, register the device once, then issue runtime challenges via `qualifyingData`. **App and user binding** are separate layers (session auth, mTLS, OS login, etc.).
41
+
42
+ Use a **vendor-prefixed, stable `keyName`** for machine scope (for example `my-app-device-ak`). Do not rely on secrecy of the blob or key name; rely on TPM possession + server-side enrollment records + challenge nonces.
43
+
26
44
  ## Machine key provisioning
27
45
 
28
46
  ```javascript
@@ -127,8 +127,8 @@ async function runProvisionMachine(args) {
127
127
  saveBlob(out, akBlob);
128
128
  console.log(`PASS Tpm.provisionAk(machine) keyName=${keyName} SPKI=${akPublicDer.length}B`);
129
129
  console.log(` wrote ${out}`);
130
- console.log('\nNEXT (standard user):');
131
- console.log(` node examples/smoke-test.mjs quote --in ${out}`);
130
+ console.log('\nNEXT (standard user, from your project directory):');
131
+ console.log(` node node_modules/node-tpm2/examples/smoke-test.mjs quote --in ${out}`);
132
132
  }
133
133
 
134
134
  async function runQuote(args) {
@@ -172,7 +172,9 @@ async function main() {
172
172
 
173
173
  main().catch((err) => {
174
174
  console.error('FAIL:', err.message ?? err);
175
+ if (err.code) console.error(' code:', err.code);
175
176
  if (err.suggestion) console.error(' suggestion:', err.suggestion);
176
177
  if (err.tpmRc != null) console.error(' tpmRc:', err.tpmRc);
178
+ if (err.hresult != null) console.error(' hresult:', err.hresult);
177
179
  process.exit(1);
178
180
  });
package/index.d.ts CHANGED
@@ -32,6 +32,9 @@ export declare type AkBlob = {
32
32
  private: Buffer;
33
33
  };
34
34
 
35
+ /** General key blob (same wire shape as AkBlob; distinct type for clarity). */
36
+ export declare type KeyBlob = AkBlob;
37
+
35
38
  export declare type QuoteOptions = {
36
39
  akBlob: AkBlob;
37
40
  pcrSelection: number[];
@@ -74,6 +77,19 @@ export declare type ActivateCredentialFlatOptions = ActivateCredentialOptions &
74
77
  akBlob: AkBlob;
75
78
  };
76
79
 
80
+ /** General device key creation options. */
81
+ export declare type KeyCreateOptions = {
82
+ type: 'ecc' | 'rsa';
83
+ sign?: boolean;
84
+ decrypt?: boolean;
85
+ };
86
+
87
+ /** @throws {TpmError} NOT_SUPPORTED until Phase 5 */
88
+ export declare type SealOptions = {
89
+ data: Buffer;
90
+ pcrSelection?: number[];
91
+ };
92
+
77
93
  export declare interface AkHandle {
78
94
  export(): AkBlob;
79
95
  readonly publicKeyDer: Buffer;
@@ -81,6 +97,13 @@ export declare interface AkHandle {
81
97
  activateCredential(opts: ActivateCredentialOptions): Promise<Buffer>;
82
98
  }
83
99
 
100
+ /** @throws {TpmError} NOT_SUPPORTED until RSA decrypt is implemented */
101
+ export declare interface KeyHandle {
102
+ export(): KeyBlob;
103
+ sign(digest: Buffer): Promise<Buffer>;
104
+ decrypt(cipher: Buffer): Promise<Buffer>;
105
+ }
106
+
84
107
  export declare type TpmInfo = {
85
108
  manufacturer: string;
86
109
  firmwareVersion: string;
@@ -92,6 +115,26 @@ export declare interface TpmHandle {
92
115
  info(): Promise<TpmInfo>;
93
116
  pcr: {
94
117
  read(selection: number[], bank?: 'sha256'): Promise<Record<number, string>>;
118
+ extend(index: number, digest: Buffer): Promise<void>;
119
+ };
120
+ random: {
121
+ bytes(count: number): Promise<Buffer>;
122
+ };
123
+ nv: {
124
+ /** @throws {TpmError} NOT_SUPPORTED until Phase 4 */
125
+ read(handle: string, offset?: number, size?: number): Promise<Buffer>;
126
+ /** @throws {TpmError} NOT_SUPPORTED until Phase 4 */
127
+ write(handle: string, data: Buffer, offset?: number): Promise<void>;
128
+ };
129
+ keys: {
130
+ create(opts: KeyCreateOptions): Promise<KeyHandle>;
131
+ load(blob: KeyBlob): Promise<KeyHandle>;
132
+ };
133
+ seal: {
134
+ /** @throws {TpmError} NOT_SUPPORTED until Phase 5 */
135
+ seal(opts: SealOptions): Promise<Buffer>;
136
+ /** @throws {TpmError} NOT_SUPPORTED until Phase 5 */
137
+ unseal(blob: Buffer): Promise<Buffer>;
95
138
  };
96
139
  attest: {
97
140
  ekCertificate(): Promise<Buffer | null>;
@@ -107,33 +150,14 @@ export declare const Tpm: {
107
150
  open(): Promise<TpmHandle>;
108
151
  getFixedProperties(): Promise<TpmInfo>;
109
152
  info(): Promise<TpmInfo>;
153
+ randomBytes(count: number): Promise<Buffer>;
110
154
  pcrRead(selection: number[], bank?: 'sha256'): Promise<Record<number, string>>;
155
+ pcrExtend(index: number, digest: Buffer): Promise<void>;
111
156
  readPublic(handle: string): Promise<ReadPublicResult>;
112
157
  readEkCertificate(): Promise<Buffer | null>;
113
158
  quote(opts: QuoteOptions): Promise<QuoteResult>;
114
159
  provisionAk(opts?: ProvisionAkOptions): Promise<ProvisionAkResult>;
115
160
  activateCredential(opts: ActivateCredentialFlatOptions): Promise<Buffer>;
161
+ createKey(opts?: KeyCreateOptions): Promise<{ publicKeyDer: Buffer; keyBlob: KeyBlob }>;
162
+ signKeyBlob(opts: { keyBlob: KeyBlob; digest: Buffer }): Promise<Buffer>;
116
163
  };
117
-
118
- export declare function pcrRead(
119
- selection: number[],
120
- bank?: 'sha256',
121
- ): Promise<Record<number, string>>;
122
-
123
- export declare function readPublic(handle: string): Promise<ReadPublicResult>;
124
-
125
- export declare function readEkCertificate(): Promise<Buffer | null>;
126
-
127
- export declare function quote(opts: QuoteOptions): Promise<QuoteResult>;
128
-
129
- export declare function provisionAk(
130
- opts?: ProvisionAkOptions,
131
- ): Promise<ProvisionAkResult>;
132
-
133
- export declare function activateCredential(
134
- opts: ActivateCredentialFlatOptions,
135
- ): Promise<Buffer>;
136
-
137
- export declare function getFixedProperties(): Promise<TpmInfo>;
138
-
139
- export declare function isAvailable(): Promise<boolean>;