@tenuo/core 0.2.4-beta.0 → 0.2.5-beta.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.
package/dist/client.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
- import { createMcp } from "./mcp.js";
2
+ import { randomBytes } from "node:crypto";
3
+ import { createMcp, presentCall, verifyPresented } from "./mcp.js";
3
4
  import { AuthorizationDeniedError, ApprovalRequiredError, TenuoConfigurationError, TenuoError } from "./errors.js";
4
5
  import { Session, isSession, nativeSession } from "./session.js";
5
- import { createDevContext, createVerifierContext, importSessionFromChain, importSessionFromWire, loadWasm, } from "./wasm.js";
6
+ import { createDevContext, createIssuerContext, createVerifierContext, importSessionFromChain, importSessionFromWire, loadWasm, protocolLimits, publicKeyHexFromHolderKey, } from "./wasm.js";
6
7
  const currentSession = new AsyncLocalStorage();
7
8
  const toolPolicies = new WeakMap();
8
9
  const wrappedInners = new WeakSet();
10
+ const CLEARANCE_NAMES = new Set(["untrusted", "external", "partner", "internal", "privileged", "system"]);
9
11
  function nodeEnv() {
10
12
  if (typeof process === "undefined") {
11
13
  return undefined;
@@ -45,18 +47,21 @@ function normalizeHex(value) {
45
47
  }
46
48
  return hex;
47
49
  }
48
- export function publicKeyFromEnv(name) {
50
+ function envValue(name, what) {
49
51
  if (name.length === 0) {
50
- throw new TenuoConfigurationError("publicKeyFromEnv() requires an environment variable name");
52
+ throw new TenuoConfigurationError(`${what} requires an environment variable name`);
51
53
  }
52
54
  if (typeof process === "undefined") {
53
- throw new TenuoConfigurationError(`Environment variable ${name} is not available. Tenuo fails closed without a trusted root.`);
55
+ throw new TenuoConfigurationError(`Environment variable ${name} is not available. Tenuo fails closed without a ${what}.`);
54
56
  }
55
57
  const value = process.env[name];
56
58
  if (value === undefined || value.length === 0) {
57
- throw new TenuoConfigurationError(`Environment variable ${name} is not set or empty. Tenuo fails closed without a trusted root.`);
59
+ throw new TenuoConfigurationError(`Environment variable ${name} is not set or empty. Tenuo fails closed without a ${what}.`);
58
60
  }
59
- return { kind: "public-key", source: "env", hex: normalizeHex(value) };
61
+ return value;
62
+ }
63
+ export function publicKeyFromEnv(name) {
64
+ return { kind: "public-key", source: "env", hex: normalizeHex(envValue(name, "trusted root")) };
60
65
  }
61
66
  export function publicKeyFromHex(hex) {
62
67
  return { kind: "public-key", source: "hex", hex: normalizeHex(hex) };
@@ -65,13 +70,12 @@ export function publicKeyFromBytes(bytes) {
65
70
  if (bytes.length !== 32) {
66
71
  throw new TenuoConfigurationError("publicKeyFromBytes() requires a 32-byte public key");
67
72
  }
68
- const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
69
- return { kind: "public-key", source: "bytes", hex };
73
+ return { kind: "public-key", source: "bytes", hex: bytesToHex(bytes) };
70
74
  }
71
- function normalizeSecretHex(value) {
75
+ function normalizeSecretHex(value, what) {
72
76
  const hex = value.trim().toLowerCase().replace(/^0x/, "");
73
77
  if (!/^[0-9a-f]{64}$/.test(hex)) {
74
- throw new TenuoConfigurationError("Holder key must be a 32-byte hex secret (64 hex characters)");
78
+ throw new TenuoConfigurationError(`${what} must be a 32-byte hex secret (64 hex characters)`);
75
79
  }
76
80
  return hex;
77
81
  }
@@ -82,21 +86,90 @@ function hexToBytes(hex) {
82
86
  }
83
87
  return bytes;
84
88
  }
89
+ function bytesToHex(bytes) {
90
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
91
+ }
85
92
  export function holderKeyFromEnv(name) {
86
- if (name.length === 0) {
87
- throw new TenuoConfigurationError("holderKeyFromEnv() requires an environment variable name");
93
+ return hexToBytes(normalizeSecretHex(envValue(name, "holder key"), "Holder key"));
94
+ }
95
+ export function holderKeyFromHex(hex) {
96
+ return hexToBytes(normalizeSecretHex(hex, "Holder key"));
97
+ }
98
+ /**
99
+ * A fresh 32-byte Ed25519 secret. One per agent, kept in that agent's
100
+ * process; only its public key (see `publicKeyFromHolderKey`) travels.
101
+ */
102
+ export function generateHolderKey() {
103
+ return new Uint8Array(randomBytes(32));
104
+ }
105
+ /** Same shape as a holder key. Named separately so a control plane's key reads as one. */
106
+ export function generateIssuerKey() {
107
+ return generateHolderKey();
108
+ }
109
+ /** The public half of a holder or issuer secret. */
110
+ export function publicKeyFromHolderKey(holderKey) {
111
+ if (!(holderKey instanceof Uint8Array) || holderKey.length !== 32) {
112
+ throw new TenuoConfigurationError("publicKeyFromHolderKey() requires a 32-byte holder key");
88
113
  }
89
- if (typeof process === "undefined") {
90
- throw new TenuoConfigurationError(`Environment variable ${name} is not available. Tenuo fails closed without a holder key.`);
114
+ loadWasm();
115
+ return { kind: "public-key", source: "bytes", hex: publicKeyHexFromHolderKey(holderKey) };
116
+ }
117
+ const MAX_WASM_U32 = 0xffff_ffff;
118
+ function requireUint32(value, name, minimum = 0) {
119
+ if (!Number.isInteger(value) || value < minimum || value > MAX_WASM_U32) {
120
+ throw new TenuoConfigurationError(`${name} must be an integer between ${minimum} and ${MAX_WASM_U32}`);
91
121
  }
92
- const value = process.env[name];
93
- if (value === undefined || value.length === 0) {
94
- throw new TenuoConfigurationError(`Environment variable ${name} is not set or empty. Tenuo fails closed without a holder key.`);
122
+ return value;
123
+ }
124
+ /** Stable control-plane key from the environment. This process becomes an issuer. */
125
+ export function issuerKeyFromEnv(name) {
126
+ return { kind: "issuer-key", secret: hexToBytes(normalizeSecretHex(envValue(name, "issuer key"), "Issuer key")) };
127
+ }
128
+ export function issuerKeyFromHex(hex) {
129
+ return { kind: "issuer-key", secret: hexToBytes(normalizeSecretHex(hex, "Issuer key")) };
130
+ }
131
+ export function issuerKeyFromBytes(secret) {
132
+ if (!(secret instanceof Uint8Array) || secret.length !== 32) {
133
+ throw new TenuoConfigurationError("issuerKeyFromBytes() requires a 32-byte secret");
95
134
  }
96
- return hexToBytes(normalizeSecretHex(value));
135
+ return { kind: "issuer-key", secret: new Uint8Array(secret) };
97
136
  }
98
- export function holderKeyFromHex(hex) {
99
- return hexToBytes(normalizeSecretHex(hex));
137
+ function requireDepth(value, name) {
138
+ requireUint32(value, name);
139
+ const maximum = protocolLimits().max_delegation_depth;
140
+ if (value > maximum) {
141
+ throw new TenuoConfigurationError(`${name} ${value} exceeds the protocol maximum of ${maximum}`);
142
+ }
143
+ return value;
144
+ }
145
+ function requireTtl(value, name, minimum = 0) {
146
+ requireUint32(value, name, minimum);
147
+ const maximum = protocolLimits().max_warrant_ttl_seconds;
148
+ if (value > maximum) {
149
+ throw new TenuoConfigurationError(`${name} ${value} exceeds the protocol maximum of ${maximum}`);
150
+ }
151
+ return value;
152
+ }
153
+ function requirePublicKey(value, name) {
154
+ if (value === null ||
155
+ typeof value !== "object" ||
156
+ value.kind !== "public-key" ||
157
+ typeof value.hex !== "string") {
158
+ throw new TenuoConfigurationError(`${name} must be a public key handle (createTenuo.publicKeyFromHolderKey / publicKeyFromHex / publicKeyFromEnv)`);
159
+ }
160
+ return value;
161
+ }
162
+ function clearanceJson(value, name) {
163
+ if (typeof value === "number") {
164
+ if (!Number.isInteger(value) || value < 0 || value > 255) {
165
+ throw new TenuoConfigurationError(`${name} must be an integer 0-255 or a level name`);
166
+ }
167
+ return value;
168
+ }
169
+ if (typeof value === "string" && CLEARANCE_NAMES.has(value)) {
170
+ return value;
171
+ }
172
+ throw new TenuoConfigurationError(`${name} must be one of ${[...CLEARANCE_NAMES].join(", ")} or an integer 0-255`);
100
173
  }
101
174
  function rootHexes(options) {
102
175
  const handles = [];
@@ -131,11 +204,19 @@ class TenuoClient {
131
204
  context;
132
205
  canMint;
133
206
  mcp;
207
+ decide;
134
208
  constructor(options) {
135
209
  if (options.root?.kind === "dev-root") {
136
210
  this.context = createDevContext();
137
211
  this.canMint = true;
138
212
  }
213
+ else if (options.root?.kind === "issuer-key") {
214
+ if (!(options.root.secret instanceof Uint8Array) || options.root.secret.length !== 32) {
215
+ throw new TenuoConfigurationError("root: issuer key must be a 32-byte secret");
216
+ }
217
+ this.context = createIssuerContext(options.root.secret, rootHexes(options));
218
+ this.canMint = true;
219
+ }
139
220
  else {
140
221
  this.context = createVerifierContext(rootHexes(options));
141
222
  this.canMint = false;
@@ -143,7 +224,28 @@ class TenuoClient {
143
224
  if (options.revocationList !== undefined) {
144
225
  this.context.loadRevocationList(normalizeWireBytes(options.revocationList));
145
226
  }
146
- this.mcp = createMcp(this.context, (decision, tool) => applyDecision(decision, tool));
227
+ this.decide = (decision, tool, native, args) => {
228
+ this.applyDecision(decision, tool, native, args);
229
+ };
230
+ this.mcp = createMcp(this.context, this.decide);
231
+ }
232
+ applyDecision(decision, tool, native, args) {
233
+ if (decision.outcome === "allow") {
234
+ return;
235
+ }
236
+ if (decision.outcome === "approval_required") {
237
+ let request;
238
+ if (native !== undefined && args !== undefined) {
239
+ try {
240
+ request = approvalRequestFromWasm(this.context.approvalRequest(native, tool, args));
241
+ }
242
+ catch {
243
+ request = undefined;
244
+ }
245
+ }
246
+ throw new ApprovalRequiredError(decision.tool ?? tool, decision.required ?? 1, decision.received ?? 0, decision.message, request);
247
+ }
248
+ throw new AuthorizationDeniedError(decision.code ?? "TENUO_TOOL_NOT_AUTHORIZED", explainDeny(decision.message ?? "Authorization denied", decision.field), decision.field);
147
249
  }
148
250
  tool(inner, policy) {
149
251
  if (toolPolicies.has(inner) || wrappedInners.has(inner)) {
@@ -153,15 +255,14 @@ class TenuoClient {
153
255
  const original = inner.execute;
154
256
  const execute = async (args, callOptions) => {
155
257
  const session = resolveSession(callOptions);
156
- const decision = this.context.authorize(nativeSession(session), capability, args, approvalsFrom(callOptions), policy.allow, requestIdFrom(callOptions));
258
+ const native = nativeSession(session);
259
+ const decision = this.context.authorize(native, capability, args, approvalsFrom(callOptions), policy.allow, requestIdFrom(callOptions));
157
260
  emitReceipt(callOptions, decision.receipt);
158
261
  if (decision.outcome === "allow") {
159
262
  return original(plainArgs(decision.args), forwardExecuteOptions(callOptions));
160
263
  }
161
- if (decision.outcome === "approval_required") {
162
- throw new ApprovalRequiredError(decision.tool ?? capability, decision.required ?? 1, decision.received ?? 0, decision.message);
163
- }
164
- throw new AuthorizationDeniedError(decision.code ?? "TENUO_TOOL_NOT_AUTHORIZED", explainDeny(decision.message ?? "Authorization denied", decision.field), decision.field);
264
+ this.applyDecision(decision, capability, native, plainArgs(args));
265
+ throw new TenuoConfigurationError("unreachable: decision was neither allow nor deny");
165
266
  };
166
267
  const wrapped = Object.assign(Object.create(Object.getPrototypeOf(inner)), inner, {
167
268
  execute,
@@ -172,23 +273,95 @@ class TenuoClient {
172
273
  }
173
274
  session(input) {
174
275
  const allow = collectSessionAllow(input);
175
- if (Object.keys(allow).length === 0) {
276
+ const kind = input.kind ?? "execution";
277
+ if (kind !== "execution" && kind !== "issuer") {
278
+ throw new TenuoConfigurationError('session().kind must be "execution" or "issuer"');
279
+ }
280
+ if (Object.keys(allow).length === 0 && kind === "execution") {
176
281
  throw new TenuoConfigurationError("tenuo.session() requires tools from tenuo.tool() or at least one capability in allow");
177
282
  }
178
283
  if (!this.canMint) {
179
- throw new TenuoConfigurationError("session() mints a warrant and needs a local issuer. Use createTenuo({ root: createTenuo.devRoot() }).");
284
+ throw new TenuoConfigurationError("session() mints a warrant and needs a local issuer. Use createTenuo({ root: createTenuo.devRoot() }) or an issuer key.");
285
+ }
286
+ const options = { kind, allow };
287
+ if (input.ttlSeconds !== undefined) {
288
+ options.ttlSeconds = requireTtl(input.ttlSeconds, "session().ttlSeconds");
289
+ }
290
+ if (input.holder !== undefined) {
291
+ options.holder = requirePublicKey(input.holder, "session().holder").hex;
292
+ }
293
+ if (input.maxDepth !== undefined) {
294
+ options.maxDepth = requireDepth(input.maxDepth, "session().maxDepth");
295
+ }
296
+ if (input.clearance !== undefined) {
297
+ options.clearance = clearanceJson(input.clearance, "session().clearance");
298
+ }
299
+ if (input.sessionId !== undefined) {
300
+ options.sessionId = requireLabel(input.sessionId, "session().sessionId");
301
+ }
302
+ if (input.agentId !== undefined) {
303
+ options.agentId = requireLabel(input.agentId, "session().agentId");
180
304
  }
181
- const ttl = input.ttlSeconds ?? 0;
182
305
  if (input.requireApproval !== undefined) {
183
- if (input.requireApproval.approvers.length === 0) {
184
- throw new TenuoConfigurationError("requireApproval.approvers must not be empty");
185
- }
186
- if (input.requireApproval.min < 1) {
187
- throw new TenuoConfigurationError("requireApproval.min must be at least 1");
188
- }
306
+ options.requireApproval = requireApprovalJson(input.requireApproval);
307
+ }
308
+ if (input.issuableTools !== undefined) {
309
+ options.issuableTools = [...input.issuableTools];
310
+ }
311
+ if (input.constraintBounds !== undefined) {
312
+ options.constraintBounds = input.constraintBounds;
313
+ }
314
+ if (input.maxIssueDepth !== undefined) {
315
+ options.maxIssueDepth = requireDepth(input.maxIssueDepth, "session().maxIssueDepth");
316
+ }
317
+ try {
318
+ return new Session(this.context.mintExtended(options));
319
+ }
320
+ catch (error) {
321
+ throw new TenuoConfigurationError(errorMessage(error));
322
+ }
323
+ }
324
+ issue(issuer, input) {
325
+ if (!isSession(issuer)) {
326
+ throw new TenuoConfigurationError("issue() requires a Tenuo Session, not a plain object");
327
+ }
328
+ if (input === null || typeof input !== "object" || input.allow === undefined || Object.keys(input.allow).length === 0) {
329
+ throw new TenuoConfigurationError("issue() requires at least one capability in allow");
330
+ }
331
+ const options = {
332
+ allow: input.allow,
333
+ holder: requirePublicKey(input.holder, "issue().holder").hex,
334
+ };
335
+ if (input.ttlSeconds !== undefined) {
336
+ options.ttlSeconds = requireTtl(input.ttlSeconds, "issue().ttlSeconds", 1);
337
+ }
338
+ if (input.maxDepth !== undefined) {
339
+ options.maxDepth = requireDepth(input.maxDepth, "issue().maxDepth");
340
+ }
341
+ if (input.clearance !== undefined) {
342
+ options.clearance = clearanceJson(input.clearance, "issue().clearance");
343
+ }
344
+ if (input.sessionId !== undefined) {
345
+ options.sessionId = requireLabel(input.sessionId, "issue().sessionId");
346
+ }
347
+ if (input.agentId !== undefined) {
348
+ options.agentId = requireLabel(input.agentId, "issue().agentId");
349
+ }
350
+ if (input.requireApproval !== undefined) {
351
+ options.requireApproval = requireApprovalJson(input.requireApproval);
352
+ }
353
+ try {
354
+ return new Session(this.context.issue(nativeSession(issuer), options));
355
+ }
356
+ catch (error) {
357
+ throw chainError(error);
189
358
  }
190
- const native = this.context.mint(allow, ttl, requireApprovalJson(input.requireApproval));
191
- return new Session(native);
359
+ }
360
+ issuerPublicKey() {
361
+ if (!this.canMint) {
362
+ throw new TenuoConfigurationError("issuerPublicKey() needs a local issuer. This context verifies against trustedRoots and does not mint.");
363
+ }
364
+ return { kind: "public-key", source: "bytes", hex: this.context.issuerPublicKey() };
192
365
  }
193
366
  sessionFromWire(input) {
194
367
  if (!(input.holderKey instanceof Uint8Array) || input.holderKey.length !== 32) {
@@ -216,22 +389,125 @@ class TenuoClient {
216
389
  }
217
390
  return currentSession.run(session, fn);
218
391
  }
219
- narrow(session, allow) {
392
+ narrow(session, allow, options) {
220
393
  if (Object.keys(allow).length === 0) {
221
394
  throw new TenuoConfigurationError("tenuo.narrow() requires a non-empty allow policy");
222
395
  }
223
396
  if (!isSession(session)) {
224
397
  throw new TenuoConfigurationError("narrow() requires a Tenuo Session, not a plain object");
225
398
  }
399
+ const native = options === undefined ? undefined : narrowOptionsJson(options);
226
400
  try {
227
- return new Session(this.context.narrow(nativeSession(session), allow));
401
+ return new Session(this.context.narrow(nativeSession(session), allow, native));
228
402
  }
229
403
  catch (error) {
230
- const message = error instanceof Error ? error.message : String(error);
231
- if (message.startsWith("TENUO_CHAIN_INVALID")) {
232
- throw new AuthorizationDeniedError("TENUO_CHAIN_INVALID", message);
233
- }
234
- throw new TenuoConfigurationError(message);
404
+ throw chainError(error);
405
+ }
406
+ }
407
+ explain(session, tool, args) {
408
+ if (!isSession(session)) {
409
+ throw new TenuoConfigurationError("explain() requires a Tenuo Session, not a plain object");
410
+ }
411
+ let raw;
412
+ try {
413
+ raw = this.context.explain(nativeSession(session), tool, args);
414
+ }
415
+ catch (error) {
416
+ throw new TenuoConfigurationError(errorMessage(error));
417
+ }
418
+ const out = {
419
+ tool: raw.tool,
420
+ kind: raw.kind,
421
+ outcome: raw.outcome,
422
+ toolGranted: raw.tool_granted,
423
+ fields: raw.fields.map((f) => {
424
+ const field = {
425
+ field: f.field,
426
+ kind: f.kind,
427
+ constraint: f.constraint,
428
+ satisfied: f.satisfied,
429
+ };
430
+ if (f.value !== undefined) {
431
+ field.value = f.value;
432
+ }
433
+ if (f.reason !== undefined) {
434
+ field.reason = f.reason;
435
+ }
436
+ return field;
437
+ }),
438
+ unknownFields: [...raw.unknown_fields],
439
+ missingFields: [...raw.missing_fields],
440
+ expired: raw.expired,
441
+ expiresAt: raw.expires_at,
442
+ chainValid: raw.chain_valid,
443
+ };
444
+ if (raw.code !== undefined) {
445
+ out.code = raw.code;
446
+ }
447
+ if (raw.field !== undefined) {
448
+ out.field = raw.field;
449
+ }
450
+ if (raw.message !== undefined) {
451
+ out.message = raw.message;
452
+ }
453
+ if (raw.chain_error !== undefined) {
454
+ out.chainError = raw.chain_error;
455
+ }
456
+ return out;
457
+ }
458
+ approvalRequest(session, tool, args) {
459
+ if (!isSession(session)) {
460
+ throw new TenuoConfigurationError("approvalRequest() requires a Tenuo Session, not a plain object");
461
+ }
462
+ try {
463
+ return approvalRequestFromWasm(this.context.approvalRequest(nativeSession(session), tool, args));
464
+ }
465
+ catch (error) {
466
+ throw new TenuoConfigurationError(errorMessage(error));
467
+ }
468
+ }
469
+ attestApprovalRequest(session, tool, args) {
470
+ if (!isSession(session)) {
471
+ throw new TenuoConfigurationError("attestApprovalRequest() requires a Tenuo Session, not a plain object");
472
+ }
473
+ let raw;
474
+ try {
475
+ raw = this.context.approvalContextAttestation(nativeSession(session), tool, args);
476
+ }
477
+ catch (error) {
478
+ throw new TenuoConfigurationError(errorMessage(error));
479
+ }
480
+ return {
481
+ version: raw.version,
482
+ canonicalization: raw.canonicalization,
483
+ warrantId: raw.warrant_id,
484
+ tool: raw.tool,
485
+ requestHash: raw.request_hash,
486
+ holderKeyHex: raw.holder_key_hex,
487
+ argsCanonicalCborB64: raw.args_canonical_cbor_b64,
488
+ signerKeyHex: raw.signer_key_hex,
489
+ signatureB64: raw.signature_b64,
490
+ };
491
+ }
492
+ present(session, tool, args, options) {
493
+ if (!isSession(session)) {
494
+ throw new TenuoConfigurationError("present() requires a Tenuo Session, not a plain object");
495
+ }
496
+ return presentCall(this.context, this.decide, session, tool, args, options, "present()").presented;
497
+ }
498
+ verify(presented, tool, args, options) {
499
+ return verifyPresented(this.context, this.decide, presented, tool, args, options, "verify()");
500
+ }
501
+ revocationList(input) {
502
+ if (!this.canMint) {
503
+ throw new TenuoConfigurationError("revocationList() needs a local issuer key. Use createTenuo.signRevocationList() with an explicit secret, or an issuer-key root.");
504
+ }
505
+ const { ids, version } = revocationInput(input);
506
+ try {
507
+ return this.context.signRevocationListVersioned(ids, version);
508
+ }
509
+ catch (error) {
510
+ throw new TenuoConfigurationError(errorMessage(error));
235
511
  }
236
512
  }
237
513
  revoke(list) {
@@ -241,6 +517,54 @@ class TenuoClient {
241
517
  loadWasm();
242
518
  }
243
519
  }
520
+ function requireLabel(value, name) {
521
+ if (typeof value !== "string" || value.trim().length === 0) {
522
+ throw new TenuoConfigurationError(`${name} must be a non-empty string`);
523
+ }
524
+ return value;
525
+ }
526
+ function errorMessage(error) {
527
+ return error instanceof Error ? error.message : String(error);
528
+ }
529
+ /** Map a prefixed core message from narrow()/issue() to the matching error class. */
530
+ function chainError(error) {
531
+ if (error instanceof TenuoError) {
532
+ return error;
533
+ }
534
+ const message = explainChainFailure(errorMessage(error));
535
+ for (const code of ["TENUO_CHAIN_INVALID", "TENUO_DEPTH_EXCEEDED", "TENUO_WARRANT_EXPIRED"]) {
536
+ if (message.startsWith(code)) {
537
+ return new AuthorizationDeniedError(code, message);
538
+ }
539
+ }
540
+ return new TenuoConfigurationError(message);
541
+ }
542
+ function explainChainFailure(message) {
543
+ const tool = /tool '([^']+)' not in parent's tools/.exec(message)?.[1];
544
+ if (tool !== undefined) {
545
+ return `${message}. narrow() cannot add '${tool}': remove it or delegate from a parent that grants it.`;
546
+ }
547
+ if (message.includes("parent's allowed set") ||
548
+ message.includes("range expanded") ||
549
+ message.includes("would expand permissions") ||
550
+ message.includes("clearance cannot increase")) {
551
+ return `${message}. narrow() only accepts a child policy that is equal to or stricter than its parent.`;
552
+ }
553
+ return message;
554
+ }
555
+ function revocationInput(input) {
556
+ if (input === null || typeof input !== "object" || !Array.isArray(input.revoke)) {
557
+ throw new TenuoConfigurationError("revocation list input must be { revoke: string[], version? }");
558
+ }
559
+ const ids = input.revoke.filter((id) => typeof id === "string" && id.length > 0);
560
+ if (ids.length === 0 || ids.length !== input.revoke.length) {
561
+ throw new TenuoConfigurationError("revoke must be a non-empty array of warrant ids");
562
+ }
563
+ if (input.version !== undefined && (!Number.isInteger(input.version) || input.version < 1)) {
564
+ throw new TenuoConfigurationError("revocation list version must be a positive integer");
565
+ }
566
+ return { ids, version: input.version };
567
+ }
244
568
  function plainArgs(value) {
245
569
  if (value instanceof Map) {
246
570
  return Object.fromEntries(value);
@@ -251,33 +575,105 @@ function plainArgs(value) {
251
575
  return {};
252
576
  }
253
577
  function requireApprovalJson(require) {
254
- if (require === undefined) {
255
- return undefined;
578
+ if (require === null || typeof require !== "object") {
579
+ throw new TenuoConfigurationError("requireApproval must be an object");
580
+ }
581
+ if (!Array.isArray(require.approvers) || require.approvers.length === 0) {
582
+ throw new TenuoConfigurationError("requireApproval.approvers must not be empty");
583
+ }
584
+ if (!Number.isInteger(require.min) || require.min < 1) {
585
+ throw new TenuoConfigurationError("requireApproval.min must be at least 1");
256
586
  }
257
587
  const payload = {
258
- approvers: require.approvers.map((approver) => approver.hex),
588
+ approvers: require.approvers.map((approver, i) => requirePublicKey(approver, `requireApproval.approvers[${i}]`).hex),
259
589
  min: require.min,
260
590
  };
261
591
  if (require.tools !== undefined) {
262
592
  payload.tools = [...require.tools];
263
593
  }
594
+ if (require.gates !== undefined) {
595
+ const gates = {};
596
+ for (const [tool, gate] of Object.entries(require.gates)) {
597
+ const out = {};
598
+ if (gate.message !== undefined) {
599
+ out.message = gate.message;
600
+ }
601
+ if (gate.args !== undefined) {
602
+ out.args = { ...gate.args };
603
+ }
604
+ gates[tool] = out;
605
+ }
606
+ payload.gates = gates;
607
+ }
264
608
  return payload;
265
609
  }
266
- function applyDecision(decision, tool) {
267
- if (decision.outcome === "allow") {
268
- return;
610
+ function narrowOptionsJson(options) {
611
+ if (options === null || typeof options !== "object") {
612
+ throw new TenuoConfigurationError("narrow() options must be an object");
613
+ }
614
+ const known = ["holder", "ttlSeconds", "terminal", "maxDepth", "clearance", "agentId", "addApprovers", "minApprovals"];
615
+ for (const key of Object.keys(options)) {
616
+ if (!known.includes(key)) {
617
+ throw new TenuoConfigurationError(`narrow() options: unknown key '${key}' (expected ${known.join(", ")})`);
618
+ }
619
+ }
620
+ const out = {};
621
+ if (options.holder !== undefined) {
622
+ out.holder = requirePublicKey(options.holder, "narrow().holder").hex;
623
+ }
624
+ if (options.ttlSeconds !== undefined) {
625
+ out.ttlSeconds = requireTtl(options.ttlSeconds, "narrow().ttlSeconds", 1);
626
+ }
627
+ if (options.terminal !== undefined) {
628
+ if (typeof options.terminal !== "boolean") {
629
+ throw new TenuoConfigurationError("narrow().terminal must be a boolean");
630
+ }
631
+ out.terminal = options.terminal;
632
+ }
633
+ if (options.maxDepth !== undefined) {
634
+ out.maxDepth = requireDepth(options.maxDepth, "narrow().maxDepth");
635
+ }
636
+ if (out.terminal === true && out.maxDepth !== undefined) {
637
+ throw new TenuoConfigurationError("narrow() options: pass terminal or maxDepth, not both");
638
+ }
639
+ if (options.clearance !== undefined) {
640
+ out.clearance = clearanceJson(options.clearance, "narrow().clearance");
269
641
  }
270
- if (decision.outcome === "approval_required") {
271
- throw new ApprovalRequiredError(decision.tool ?? tool, decision.required ?? 1, decision.received ?? 0, decision.message);
642
+ if (options.agentId !== undefined) {
643
+ out.agentId = requireLabel(options.agentId, "narrow().agentId");
644
+ }
645
+ if (options.addApprovers !== undefined) {
646
+ out.addApprovers = options.addApprovers.map((a, i) => requirePublicKey(a, `narrow().addApprovers[${i}]`).hex);
647
+ }
648
+ if (options.minApprovals !== undefined) {
649
+ if (!Number.isInteger(options.minApprovals) || options.minApprovals < 1) {
650
+ throw new TenuoConfigurationError("narrow().minApprovals must be at least 1");
651
+ }
652
+ out.minApprovals = options.minApprovals;
272
653
  }
273
- throw new AuthorizationDeniedError(decision.code ?? "TENUO_TOOL_NOT_AUTHORIZED", explainDeny(decision.message ?? "Authorization denied", decision.field), decision.field);
654
+ return out;
655
+ }
656
+ function approvalRequestFromWasm(raw) {
657
+ return {
658
+ requestId: raw.request_id,
659
+ warrantId: raw.warrant_id,
660
+ tool: raw.tool,
661
+ args: { ...raw.args },
662
+ requestHash: raw.request_hash,
663
+ holderPublicKey: raw.holder_public_key,
664
+ requiredApprovers: [...raw.required_approvers],
665
+ minApprovals: raw.min_approvals,
666
+ warrantExpiresAt: raw.warrant_expires_at,
667
+ createdAt: raw.created_at,
668
+ message: raw.message,
669
+ };
274
670
  }
275
671
  function explainDeny(message, field) {
276
672
  if (!message.includes("unknown field not allowed")) {
277
673
  return message;
278
674
  }
279
675
  const named = field !== undefined && field.length > 0 ? `'${field}'` : "this argument";
280
- return `${message}. Zero-trust: name ${named} in allow (e.g. ${named}: pattern("*")), or drop it from the call. Empty allow: {} adds no extra ceiling.`;
676
+ return `${message}. Zero-trust: name ${named} in allow (for example ${named}: pattern("*")), or remove it from the call; constrained policies reject omitted fields.`;
281
677
  }
282
678
  function forwardExecuteOptions(callOptions) {
283
679
  if (callOptions === null || typeof callOptions !== "object") {
@@ -296,7 +692,7 @@ function forwardExecuteOptions(callOptions) {
296
692
  return Object.keys(rest).length === 0 ? undefined : rest;
297
693
  }
298
694
  function importWireError(error) {
299
- const message = error instanceof Error ? error.message : String(error);
695
+ const message = errorMessage(error);
300
696
  if (message.startsWith("TENUO_CHAIN_INVALID") || message.includes("invalid warrant")) {
301
697
  return new TenuoError("TENUO_CHAIN_INVALID", message);
302
698
  }
@@ -306,13 +702,18 @@ function importWireError(error) {
306
702
  if (message.startsWith("TENUO_UNTRUSTED_ROOT")) {
307
703
  return new TenuoError("TENUO_UNTRUSTED_ROOT", message);
308
704
  }
705
+ if (message.startsWith("TENUO_INVALID_POP")) {
706
+ // The warrant is fine; the key is not the one it was issued to.
707
+ const separator = /[.!?]$/.test(message.trim()) ? "" : ".";
708
+ return new AuthorizationDeniedError("TENUO_INVALID_POP", `${message}${separator} If this followed narrow(), set { holder: receiverPublicKey } for the agent that imports the child.`);
709
+ }
309
710
  return new TenuoConfigurationError(message);
310
711
  }
311
712
  function normalizeWireBytes(value) {
312
713
  if (typeof value === "string") {
313
714
  return value;
314
715
  }
315
- return Array.from(value, (byte) => byte.toString(16).padStart(2, "0")).join("");
716
+ return bytesToHex(value);
316
717
  }
317
718
  function emitReceipt(callOptions, receipt) {
318
719
  if (receipt === undefined || callOptions === null || typeof callOptions !== "object") {
@@ -396,6 +797,217 @@ function sortedAllow(allow) {
396
797
  }
397
798
  return out;
398
799
  }
800
+ // ---------------------------------------------------------------------------
801
+ // Static helpers: approvals, revocation, receipts, control-plane wire shapes
802
+ // ---------------------------------------------------------------------------
803
+ function requestHashOf(request) {
804
+ const hash = typeof request === "string" ? request : request.requestHash;
805
+ const hex = hash.trim().toLowerCase();
806
+ if (!/^[0-9a-f]{64}$/.test(hex)) {
807
+ throw new TenuoConfigurationError("signApproval() needs an ApprovalRequest or a 64-hex request hash");
808
+ }
809
+ return hex;
810
+ }
811
+ /** Sign an approval as an approver. The approver never needs the warrant or the holder key. */
812
+ export function signApproval(request, approverSecret, options) {
813
+ if (!(approverSecret instanceof Uint8Array) || approverSecret.length !== 32) {
814
+ throw new TenuoConfigurationError("signApproval() requires a 32-byte approver secret");
815
+ }
816
+ if (options === null || typeof options !== "object" || typeof options.externalId !== "string" || options.externalId.trim().length === 0) {
817
+ throw new TenuoConfigurationError("signApproval() requires options.externalId: who approved");
818
+ }
819
+ if (options.ttlSeconds !== undefined && (!Number.isInteger(options.ttlSeconds) || options.ttlSeconds < 1)) {
820
+ throw new TenuoConfigurationError("signApproval().ttlSeconds must be a positive integer");
821
+ }
822
+ const warrantExpiresAt = options.warrantExpiresAt ?? (typeof request === "object" ? request.warrantExpiresAt : undefined);
823
+ try {
824
+ return loadWasm().sdkSignApprovalForRequest(requestHashOf(request), approverSecret, options.externalId, options.ttlSeconds, warrantExpiresAt);
825
+ }
826
+ catch (error) {
827
+ throw new TenuoConfigurationError(errorMessage(error));
828
+ }
829
+ }
830
+ /** Decode an approval envelope. Not authorization: the call path still decides. */
831
+ export function inspectApproval(envelope) {
832
+ const text = typeof envelope === "string" ? envelope : Buffer.from(envelope).toString("base64");
833
+ let raw;
834
+ try {
835
+ raw = loadWasm().sdkInspectApproval(text);
836
+ }
837
+ catch (error) {
838
+ throw new TenuoConfigurationError(errorMessage(error));
839
+ }
840
+ const out = {
841
+ approverPublicKey: raw.approver_public_key,
842
+ requestHash: raw.request_hash,
843
+ externalId: raw.external_id,
844
+ approvedAt: raw.approved_at,
845
+ expiresAt: raw.expires_at,
846
+ expired: raw.expired,
847
+ signatureValid: raw.signature_valid,
848
+ };
849
+ if (raw.error !== undefined) {
850
+ out.error = raw.error;
851
+ }
852
+ return out;
853
+ }
854
+ /** Sign a revocation list with an explicit issuer secret. */
855
+ export function signRevocationList(input, issuerSecret) {
856
+ if (!(issuerSecret instanceof Uint8Array) || issuerSecret.length !== 32) {
857
+ throw new TenuoConfigurationError("signRevocationList() requires a 32-byte issuer secret");
858
+ }
859
+ const { ids, version } = revocationInput(input);
860
+ try {
861
+ return loadWasm().sdkSignRevocationListVersioned(ids, version, issuerSecret);
862
+ }
863
+ catch (error) {
864
+ throw new TenuoConfigurationError(errorMessage(error));
865
+ }
866
+ }
867
+ export function inspectRevocationList(wire) {
868
+ let raw;
869
+ try {
870
+ raw = loadWasm().sdkInspectRevocationList(normalizeWireBytes(wire));
871
+ }
872
+ catch (error) {
873
+ throw new TenuoConfigurationError(errorMessage(error));
874
+ }
875
+ return {
876
+ version: raw.version,
877
+ issuedAt: raw.issued_at,
878
+ issuerPublicKey: raw.issuer_public_key,
879
+ revokedIds: [...raw.revoked_ids],
880
+ signatureValid: raw.signature_valid,
881
+ };
882
+ }
883
+ /** Signature authenticity of a receipt. Not authorization. */
884
+ export function verifyReceipt(wire) {
885
+ let raw;
886
+ try {
887
+ raw = loadWasm().sdkVerifyReceipt(normalizeWireBytes(wire));
888
+ }
889
+ catch (error) {
890
+ throw new TenuoConfigurationError(errorMessage(error));
891
+ }
892
+ const out = {
893
+ authentic: true,
894
+ signerKey: raw.signer_key,
895
+ outcome: raw.outcome,
896
+ action: raw.action,
897
+ requestId: raw.request_id,
898
+ };
899
+ if (raw.decision_code !== undefined)
900
+ out.decisionCode = raw.decision_code;
901
+ if (raw.srl_version !== undefined)
902
+ out.srlVersion = raw.srl_version;
903
+ if (raw.srl_hash !== undefined)
904
+ out.srlHash = raw.srl_hash;
905
+ if (raw.request_hash !== undefined)
906
+ out.requestHash = raw.request_hash;
907
+ if (raw.policy_definition_hash !== undefined)
908
+ out.policyDefinitionHash = raw.policy_definition_hash;
909
+ if (raw.prev_receipt_hash !== undefined)
910
+ out.prevReceiptHash = raw.prev_receipt_hash;
911
+ if (raw.trusted_roots_hash !== undefined)
912
+ out.trustedRootsHash = raw.trusted_roots_hash;
913
+ return out;
914
+ }
915
+ /**
916
+ * Root-anchored receipt check: the embedded warrant chain against `roots`
917
+ * at the receipt's own decision instant. Needs no trust in the signer.
918
+ */
919
+ export function verifyReceiptChain(wire, roots) {
920
+ if (!Array.isArray(roots) || roots.length === 0) {
921
+ throw new TenuoConfigurationError("verifyReceiptChain() requires at least one trusted root");
922
+ }
923
+ let raw;
924
+ try {
925
+ raw = loadWasm().sdkVerifyReceiptChain(normalizeWireBytes(wire), roots.map((r, i) => requirePublicKey(r, `roots[${i}]`).hex));
926
+ }
927
+ catch (error) {
928
+ throw new TenuoConfigurationError(errorMessage(error));
929
+ }
930
+ const out = {
931
+ signerKey: raw.signer_key,
932
+ outcome: raw.outcome,
933
+ timestamp: raw.timestamp,
934
+ chainValid: raw.chain_valid,
935
+ };
936
+ if (raw.decision_code !== undefined)
937
+ out.decisionCode = raw.decision_code;
938
+ if (raw.chain_error !== undefined)
939
+ out.chainError = raw.chain_error;
940
+ if (raw.corroborates_denial !== undefined)
941
+ out.corroboratesDenial = raw.corroborates_denial;
942
+ if (raw.root_issuer !== undefined)
943
+ out.rootIssuer = raw.root_issuer;
944
+ if (raw.leaf_holder !== undefined)
945
+ out.leafHolder = raw.leaf_holder;
946
+ return out;
947
+ }
948
+ /**
949
+ * The v1 JSON body a control plane's approval API accepts. Same shape the
950
+ * Python SDK produces, so one approval service serves both.
951
+ */
952
+ export function controlPlaneApprovalRequestV1(request, options) {
953
+ if (request === null || typeof request !== "object" || typeof request.requestHash !== "string") {
954
+ throw new TenuoConfigurationError("controlPlaneApprovalRequestV1() needs an ApprovalRequest from tenuo.approvalRequest()");
955
+ }
956
+ const body = {
957
+ schema_version: 1,
958
+ request_id_hex: request.requestId,
959
+ warrant_id: request.warrantId,
960
+ tool: request.tool,
961
+ arguments: { ...request.args },
962
+ request_hash_hex: request.requestHash,
963
+ holder_public_key_hex: request.holderPublicKey,
964
+ required_approver_keys_hex: [...request.requiredApprovers],
965
+ min_approvals: Math.max(1, request.minApprovals),
966
+ warrant_expires_at_unix: request.warrantExpiresAt,
967
+ created_at_unix: request.createdAt,
968
+ };
969
+ if (options?.attestation !== undefined) {
970
+ const a = options.attestation;
971
+ body.attestation = {
972
+ version: a.version,
973
+ canonicalization: a.canonicalization,
974
+ warrant_id: a.warrantId,
975
+ tool: a.tool,
976
+ request_hash: a.requestHash,
977
+ holder_key_hex: a.holderKeyHex,
978
+ args_canonical_cbor_b64: a.argsCanonicalCborB64,
979
+ signer_key_hex: a.signerKeyHex,
980
+ signature_b64: a.signatureB64,
981
+ // Python readers look for these two names.
982
+ signer_key: a.signerKeyHex,
983
+ signature: a.signatureB64,
984
+ };
985
+ }
986
+ if (options?.temporal !== undefined && Object.keys(options.temporal).length > 0) {
987
+ body.temporal = { ...options.temporal };
988
+ }
989
+ if (request.message.length > 0) {
990
+ body.message = request.message;
991
+ }
992
+ return body;
993
+ }
994
+ /** Approval envelopes from a v1 response, ready for `{ approvals }` on the call. Empty unless status is a success. */
995
+ export function signedApprovalsFromResponseV1(response) {
996
+ if (response === null || typeof response !== "object" || typeof response.status !== "string") {
997
+ throw new TenuoConfigurationError("approval response must be an object with a status");
998
+ }
999
+ if (response.status !== "approved") {
1000
+ return [];
1001
+ }
1002
+ const list = response.signed_approvals_b64;
1003
+ if (list === undefined || list === null) {
1004
+ return [];
1005
+ }
1006
+ if (!Array.isArray(list) || list.some((item) => typeof item !== "string" || item.length === 0)) {
1007
+ throw new TenuoConfigurationError("signed_approvals_b64 must be an array of base64 strings");
1008
+ }
1009
+ return [...list];
1010
+ }
399
1011
  function createTenuoImpl(options = {}) {
400
1012
  if (!hasTrustAnchor(options)) {
401
1013
  throw new TenuoConfigurationError("createTenuo() requires trustedRoots or root: createTenuo.devRoot(). An empty trust set is not a configuration.");
@@ -413,5 +1025,19 @@ export const createTenuo = Object.assign(createTenuoImpl, {
413
1025
  publicKeyFromBytes,
414
1026
  holderKeyFromEnv,
415
1027
  holderKeyFromHex,
1028
+ generateHolderKey,
1029
+ generateIssuerKey,
1030
+ publicKeyFromHolderKey,
1031
+ issuerKeyFromEnv,
1032
+ issuerKeyFromHex,
1033
+ issuerKeyFromBytes,
1034
+ signApproval,
1035
+ inspectApproval,
1036
+ signRevocationList,
1037
+ inspectRevocationList,
1038
+ verifyReceipt,
1039
+ verifyReceiptChain,
1040
+ controlPlaneApprovalRequestV1,
1041
+ signedApprovalsFromResponseV1,
416
1042
  });
417
1043
  //# sourceMappingURL=client.js.map