-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
712 lines (621 loc) · 20.8 KB
/
index.ts
File metadata and controls
712 lines (621 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
// typescript-sdk/src/index.ts
import { createHash } from "node:crypto";
import { ethers } from "ethers";
import nacl from "tweetnacl";
/**
* CommandLayer TypeScript SDK — Commons v1.0.0
*
* Implements:
* - Canonicalization: cl-stable-json-v1 (deterministic JSON w/ sorted keys, no whitespace)
* - Hash recomputation: sha256 over canonicalized UNSIGNED receipt
* - Signature verification: Ed25519 over the HASH STRING (utf8)
* - ENS pubkey resolution: TXT lookup via ethers v6 resolver.getText()
*
* Node-only. (Uses node:crypto). For browser support, swap sha256 to noble + conditional exports.
*/
export const commonsVersion = "1.0.0";
/** @deprecated Use commonsVersion. */
export const version = commonsVersion;
// -----------------------
// Types
// -----------------------
export type Proof = {
alg?: string; // "ed25519-sha256"
canonical?: string; // "cl-stable-json-v1"
signer_id?: string; // e.g. runtime.commandlayer.eth
hash_sha256?: string; // hex
signature_b64?: string; // base64
[k: string]: any;
};
export type ReceiptMetadata = {
receipt_id?: string; // must equal proof.hash_sha256
proof?: Proof;
actor?: { id: string; role?: string; [k: string]: any };
[k: string]: any;
};
export type ReceiptTrace = {
trace_id?: string;
parent_trace_id?: string;
started_at?: string;
completed_at?: string;
duration_ms?: number;
provider?: string;
[k: string]: any;
};
export type X402 = {
verb?: string;
version?: string;
entry?: string;
tenant?: string;
extras?: Record<string, any>;
[k: string]: any;
};
export type Receipt<T = any> = {
status: "success" | "error" | string;
x402?: X402;
trace?: ReceiptTrace;
result?: T;
error?: any;
metadata?: ReceiptMetadata;
[k: string]: any;
};
export type VerifyChecks = {
schema_valid?: boolean; // not implemented here
hash_matches: boolean;
signature_valid: boolean;
receipt_id_matches: boolean;
alg_matches: boolean;
canonical_matches: boolean;
};
export type VerifyResult = {
ok: boolean;
checks: VerifyChecks;
values: {
verb: string | null;
signer_id: string | null;
alg: string | null;
canonical: string | null;
claimed_hash: string | null;
recomputed_hash: string | null;
receipt_id: string | null;
pubkey_source: "explicit" | "ens" | null;
ens_txt_key: string | null;
};
errors: {
signature_error?: string | null;
ens_error?: string | null;
verify_error?: string | null;
};
};
export class CommandLayerError extends Error {
statusCode?: number;
details?: any;
constructor(message: string, statusCode?: number, details?: any) {
super(message);
this.name = "CommandLayerError";
this.statusCode = statusCode;
this.details = details;
}
}
export type EnsVerifyOptions = {
/** Agent ENS name that holds TXT records (e.g. summarizeagent.eth) */
name: string;
/** Ethereum RPC URL (required for ENS resolution) */
rpcUrl: string;
};
export type SignerKeyResolution = {
algorithm: "ed25519";
kid: string;
rawPublicKeyBytes: Uint8Array;
};
export type VerifyOptions = {
/**
* Explicit Ed25519 public key (preferred).
* Accepts formats:
* - "ed25519:<base64>"
* - "<base64>" (32 bytes)
* - "0x<hex>" / "<hex>" (64 hex chars)
*/
publicKey?: string;
/** Resolve Ed25519 public key from ENS via TXT record. */
ens?: EnsVerifyOptions;
};
export type ClientOptions = {
runtime?: string; // default https://runtime.commandlayer.org
actor?: string; // used by classify + helpful elsewhere
timeoutMs?: number;
fetchImpl?: typeof fetch;
/**
* If true, every client call verifies the returned receipt.
* Requires either:
* - opts.verify.publicKey, OR
* - opts.verify.ens (with rpcUrl)
*/
verifyReceipts?: boolean;
/** Default verification config used when verifyReceipts is enabled */
verify?: VerifyOptions;
};
const VERBS = [
"summarize",
"analyze",
"classify",
"clean",
"convert",
"describe",
"explain",
"format",
"parse",
"fetch"
] as const;
type Verb = (typeof VERBS)[number];
// -----------------------
// Helpers
// -----------------------
function normalizeBase(url: string) {
return String(url || "").replace(/\/+$/, "");
}
// -----------------------
// Canonicalization: cl-stable-json-v1
// -----------------------
export function canonicalizeStableJsonV1(value: unknown): string {
return encode(value);
function encode(v: unknown): string {
if (v === null) return "null";
const t = typeof v;
if (t === "string") return JSON.stringify(v);
if (t === "boolean") return v ? "true" : "false";
if (t === "number") {
if (!Number.isFinite(v)) {
throw new Error("canonicalize: non-finite number not allowed");
}
if (Object.is(v, -0)) return "0";
return String(v);
}
if (t === "bigint") throw new Error("canonicalize: bigint not allowed");
if (t === "undefined" || t === "function" || t === "symbol") {
throw new Error(`canonicalize: unsupported type ${t}`);
}
if (Array.isArray(v)) {
return "[" + v.map(encode).join(",") + "]";
}
if (t === "object") {
const obj = v as Record<string, unknown>;
const keys = Object.keys(obj).sort();
let out = "{";
for (let i = 0; i < keys.length; i++) {
const k = keys[i]!;
const val = obj[k];
if (typeof val === "undefined") {
throw new Error(`canonicalize: undefined for key "${k}" not allowed`);
}
if (i) out += ",";
out += JSON.stringify(k) + ":" + encode(val);
}
out += "}";
return out;
}
throw new Error("canonicalize: unsupported value");
}
}
export function sha256HexUtf8(input: string): string {
return createHash("sha256").update(Buffer.from(input, "utf8")).digest("hex");
}
// -----------------------
// Ed25519 helpers (signs UTF-8 hash string)
// -----------------------
function b64ToBytes(b64: string): Uint8Array {
const buf = Buffer.from(b64, "base64");
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
}
function hexToBytes(hex: string): Uint8Array {
const h = hex.startsWith("0x") ? hex.slice(2) : hex;
if (!/^[0-9a-fA-F]{64}$/.test(h)) {
throw new Error("invalid hex (expected 64 hex chars for ed25519 pubkey)");
}
const buf = Buffer.from(h, "hex");
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
}
/**
* Accepts:
* - "ed25519:<base64>"
* - "ed25519=<base64>"
* - raw base64 (32 bytes)
* - 0xhex / hex (64 hex chars => 32 bytes)
*/
export function parseEd25519Pubkey(text: string): Uint8Array {
const s = String(text).trim();
const m = s.match(/^ed25519\s*[:=]\s*(.+)$/i);
const candidate = (m?.[1] ?? s).trim();
// hex path
if (/^(0x)?[0-9a-fA-F]{64}$/.test(candidate)) {
const pk = hexToBytes(candidate);
if (pk.length !== 32) throw new Error("invalid ed25519 pubkey length");
return pk;
}
// base64 path
const pk = b64ToBytes(candidate);
if (pk.length !== 32) throw new Error("invalid base64 ed25519 pubkey length (need 32 bytes)");
return pk;
}
export function verifyEd25519SignatureOverUtf8HashString(
hashHex: string,
signatureB64: string,
pubkey32: Uint8Array
): boolean {
if (pubkey32.length !== 32) throw new Error("ed25519: pubkey must be 32 bytes");
const msg = Buffer.from(hashHex, "utf8");
const sig = b64ToBytes(signatureB64);
if (sig.length !== 64) throw new Error("ed25519: signature must be 64 bytes");
return nacl.sign.detached.verify(new Uint8Array(msg), sig, pubkey32);
}
// -----------------------
// ENS TXT signer key resolution (ethers v6)
// -----------------------
export async function resolveSignerKey(name: string, rpcUrl: string): Promise<SignerKeyResolution> {
const provider = new ethers.JsonRpcProvider(rpcUrl);
const agentResolver = await provider.getResolver(name);
if (!agentResolver) {
throw new Error(`No resolver for agent ENS name: ${name}`);
}
const signerName = (await agentResolver.getText("cl.receipt.signer"))?.trim();
if (!signerName) {
throw new Error(`ENS TXT cl.receipt.signer missing for agent ENS name: ${name}`);
}
const signerResolver = await provider.getResolver(signerName);
if (!signerResolver) {
throw new Error(`No resolver for signer ENS name: ${signerName}`);
}
const pubKeyText = (await signerResolver.getText("cl.sig.pub"))?.trim();
if (!pubKeyText) {
throw new Error(`ENS TXT cl.sig.pub missing for signer ENS name: ${signerName}`);
}
const kid = (await signerResolver.getText("cl.sig.kid"))?.trim();
if (!kid) {
throw new Error(`ENS TXT cl.sig.kid missing for signer ENS name: ${signerName}`);
}
let rawPublicKeyBytes: Uint8Array;
try {
rawPublicKeyBytes = parseEd25519Pubkey(pubKeyText);
} catch (e: any) {
throw new Error(`ENS TXT cl.sig.pub malformed for signer ENS name: ${signerName}. ${e?.message || String(e)}`);
}
return {
algorithm: "ed25519",
kid,
rawPublicKeyBytes
};
}
// -----------------------
// Receipt verification (protocol-aligned)
// -----------------------
export function toUnsignedReceipt(receipt: Receipt): any {
if (!receipt || typeof receipt !== "object") throw new Error("receipt must be an object");
const r: any = structuredClone(receipt);
if (r.metadata && typeof r.metadata === "object") {
if ("receipt_id" in r.metadata) delete r.metadata.receipt_id;
if (r.metadata.proof && typeof r.metadata.proof === "object") {
const p = r.metadata.proof;
const unsignedProof: any = {};
if (typeof p.alg === "string") unsignedProof.alg = p.alg;
if (typeof p.canonical === "string") unsignedProof.canonical = p.canonical;
if (typeof p.signer_id === "string") unsignedProof.signer_id = p.signer_id;
r.metadata.proof = unsignedProof;
}
}
if ("receipt_id" in r) delete r.receipt_id;
return r;
}
export function recomputeReceiptHashSha256(receipt: Receipt): { canonical: string; hash_sha256: string } {
const unsigned = toUnsignedReceipt(receipt);
const canonical = canonicalizeStableJsonV1(unsigned);
const hash_sha256 = sha256HexUtf8(canonical);
return { canonical, hash_sha256 };
}
export async function verifyReceipt(receipt: Receipt, opts: VerifyOptions = {}): Promise<VerifyResult> {
try {
const proof: Proof = receipt?.metadata?.proof || {};
const claimedHash = typeof proof.hash_sha256 === "string" ? proof.hash_sha256 : null;
const sigB64 = typeof proof.signature_b64 === "string" ? proof.signature_b64 : null;
const alg = typeof proof.alg === "string" ? proof.alg : null;
const canonical = typeof proof.canonical === "string" ? proof.canonical : null;
const signer_id = typeof proof.signer_id === "string" ? proof.signer_id : null;
const algMatches = alg === "ed25519-sha256";
const canonicalMatches = canonical === "cl-stable-json-v1";
const { hash_sha256: recomputedHash } = recomputeReceiptHashSha256(receipt);
const hashMatches = claimedHash ? recomputedHash === claimedHash : false;
const receiptId = (receipt?.metadata?.receipt_id ?? (receipt as any)?.receipt_id ?? null) as string | null;
const receiptIdMatches = claimedHash ? receiptId === claimedHash : false;
let pubkey: Uint8Array | null = null;
let pubkey_source: "explicit" | "ens" | null = null;
let ens_error: string | null = null;
let ens_txt_key: string | null = null;
if (opts.publicKey) {
pubkey = parseEd25519Pubkey(opts.publicKey);
pubkey_source = "explicit";
} else if (opts.ens) {
ens_txt_key = "cl.receipt.signer -> cl.sig.pub, cl.sig.kid";
try {
const signerKey = await resolveSignerKey(opts.ens.name, opts.ens.rpcUrl);
pubkey = signerKey.rawPublicKeyBytes;
pubkey_source = "ens";
} catch (e: any) {
ens_error = e?.message || "ENS signer key resolution failed";
}
}
let signature_valid = false;
let signature_error: string | null = null;
if (!algMatches) signature_error = `proof.alg must be "ed25519-sha256" (got ${String(alg)})`;
else if (!canonicalMatches)
signature_error = `proof.canonical must be "cl-stable-json-v1" (got ${String(canonical)})`;
else if (!claimedHash || !sigB64) signature_error = "missing proof.hash_sha256 or proof.signature_b64";
else if (!pubkey) signature_error = ens_error || "no public key available (provide verify.publicKey or verify.ens)";
else {
try {
signature_valid = verifyEd25519SignatureOverUtf8HashString(claimedHash, sigB64, pubkey);
} catch (e: any) {
signature_valid = false;
signature_error = e?.message || "signature verify failed";
}
}
const ok = algMatches && canonicalMatches && hashMatches && receiptIdMatches && signature_valid;
return {
ok,
checks: {
hash_matches: hashMatches,
signature_valid,
receipt_id_matches: receiptIdMatches,
alg_matches: algMatches,
canonical_matches: canonicalMatches
},
values: {
verb: receipt?.x402?.verb ?? null,
signer_id,
alg,
canonical,
claimed_hash: claimedHash,
recomputed_hash: recomputedHash,
receipt_id: receiptId,
pubkey_source,
ens_txt_key
},
errors: {
signature_error,
ens_error,
verify_error: null
}
};
} catch (e: any) {
return {
ok: false,
checks: {
hash_matches: false,
signature_valid: false,
receipt_id_matches: false,
alg_matches: false,
canonical_matches: false
},
values: {
verb: receipt?.x402?.verb ?? null,
signer_id: receipt?.metadata?.proof?.signer_id ?? null,
alg: receipt?.metadata?.proof?.alg ?? null,
canonical: receipt?.metadata?.proof?.canonical ?? null,
claimed_hash: receipt?.metadata?.proof?.hash_sha256 ?? null,
recomputed_hash: null,
receipt_id: receipt?.metadata?.receipt_id ?? null,
pubkey_source: null,
ens_txt_key: null
},
errors: {
signature_error: null,
ens_error: null,
verify_error: e?.message || String(e)
}
};
}
}
// -----------------------
// Client
// -----------------------
export class CommandLayerClient {
runtime: string;
actor: string;
timeoutMs: number;
fetchImpl: typeof fetch;
// default OFF unless explicitly enabled
verifyReceipts: boolean;
verifyDefaults?: VerifyOptions;
constructor(opts: ClientOptions = {}) {
this.runtime = normalizeBase(opts.runtime || "https://runtime.commandlayer.org");
this.actor = opts.actor || "sdk-user";
this.timeoutMs = opts.timeoutMs ?? 30_000;
this.fetchImpl = opts.fetchImpl || fetch;
this.verifyReceipts = opts.verifyReceipts === true;
this.verifyDefaults = opts.verify;
}
private ensureVerifyConfigIfEnabled() {
if (!this.verifyReceipts) return;
const v = this.verifyDefaults;
const hasExplicit = !!(v?.publicKey && String(v.publicKey).trim().length);
const hasEns = !!(v?.ens?.name && v?.ens?.rpcUrl);
if (!hasExplicit && !hasEns) {
throw new CommandLayerError(
"verifyReceipts is enabled but no verification key config provided. Set: verify.publicKey OR verify.ens { name, rpcUrl }.",
400
);
}
}
async summarize(opts: { content: string; style?: string; format?: string; maxTokens?: number }) {
return this.call("summarize", {
input: {
content: opts.content,
summary_style: opts.style,
format_hint: opts.format
},
limits: { max_output_tokens: opts.maxTokens ?? 1000 }
});
}
async analyze(opts: { content: string; goal?: string; hints?: string[]; maxTokens?: number }) {
return this.call("analyze", {
input: opts.content,
...(opts.goal ? { goal: opts.goal } : {}),
...(opts.hints ? { hints: opts.hints } : {}),
limits: { max_output_tokens: opts.maxTokens ?? 1000 }
});
}
async classify(opts: { content: string; maxLabels?: number; maxTokens?: number }) {
return this.call("classify", {
actor: this.actor,
input: { content: opts.content },
limits: {
max_labels: opts.maxLabels ?? 5,
max_output_tokens: opts.maxTokens ?? 1000
}
});
}
async clean(opts: { content: string; operations?: string[]; maxTokens?: number }) {
return this.call("clean", {
input: {
content: opts.content,
operations: opts.operations ?? ["normalize_newlines", "collapse_whitespace", "trim"]
},
limits: { max_output_tokens: opts.maxTokens ?? 1000 }
});
}
async convert(opts: { content: string; from: string; to: string; maxTokens?: number }) {
return this.call("convert", {
input: { content: opts.content, source_format: opts.from, target_format: opts.to },
limits: { max_output_tokens: opts.maxTokens ?? 1000 }
});
}
async describe(opts: {
subject: string;
audience?: string;
detail?: "short" | "medium" | "detailed";
maxTokens?: number;
}) {
const subject = (opts.subject || "").slice(0, 140);
return this.call("describe", {
input: {
subject,
audience: opts.audience ?? "general",
detail_level: opts.detail ?? "medium"
},
limits: { max_output_tokens: opts.maxTokens ?? 1000 }
});
}
async explain(opts: {
subject: string;
audience?: string;
style?: string;
detail?: "short" | "medium" | "detailed";
maxTokens?: number;
}) {
const subject = (opts.subject || "").slice(0, 140);
return this.call("explain", {
input: {
subject,
audience: opts.audience ?? "general",
style: opts.style ?? "step-by-step",
detail_level: opts.detail ?? "medium"
},
limits: { max_output_tokens: opts.maxTokens ?? 1000 }
});
}
async format(opts: { content: string; to: string; maxTokens?: number }) {
return this.call("format", {
input: { content: opts.content, target_style: opts.to },
limits: { max_output_tokens: opts.maxTokens ?? 1000 }
});
}
async parse(opts: {
content: string;
contentType?: "json" | "yaml" | "text";
mode?: "best_effort" | "strict";
targetSchema?: string;
maxTokens?: number;
}) {
return this.call("parse", {
input: {
content: opts.content,
content_type: opts.contentType ?? "text",
mode: opts.mode ?? "best_effort",
...(opts.targetSchema ? { target_schema: opts.targetSchema } : {})
},
limits: { max_output_tokens: opts.maxTokens ?? 1000 }
});
}
async fetch(opts: { source: string; query?: string; include_metadata?: boolean; maxTokens?: number }) {
return this.call("fetch", {
input: {
source: opts.source,
...(opts.query !== undefined ? { query: opts.query } : {}),
...(opts.include_metadata !== undefined ? { include_metadata: opts.include_metadata } : {})
},
limits: { max_output_tokens: opts.maxTokens ?? 1000 }
});
}
async call(verb: Verb, body: Record<string, any>): Promise<Receipt> {
if (!VERBS.includes(verb as any)) {
throw new CommandLayerError(`Unsupported verb: ${verb}`, 400);
}
const url = `${this.runtime}/${verb}/v1.0.0`;
this.ensureVerifyConfigIfEnabled();
const payload = {
x402: {
verb,
version: "1.0.0",
entry: `x402://${verb}agent.eth/${verb}/v1.0.0`
},
...(body.actor ? { actor: body.actor } : { actor: this.actor }),
...body
};
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
try {
const resp = await this.fetchImpl(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": `commandlayer-js/${version}`
},
body: JSON.stringify(payload),
signal: controller.signal
});
let data: any;
try {
data = await resp.json();
} catch {
if (!resp.ok) {
throw new CommandLayerError(`HTTP ${resp.status} (non-JSON response)`, resp.status);
}
throw new CommandLayerError("Runtime returned non-JSON response", resp.status);
}
if (!resp.ok) {
throw new CommandLayerError(
data?.message || data?.error?.message || `HTTP ${resp.status}`,
resp.status,
data
);
}
if (this.verifyReceipts) {
const v = await verifyReceipt(data as Receipt, this.verifyDefaults || {});
if (!v.ok) {
throw new CommandLayerError("Receipt verification failed", 422, v);
}
}
return data as Receipt;
} catch (err: any) {
if (err?.name === "AbortError") throw new CommandLayerError("Request timed out", 408);
if (err instanceof CommandLayerError) throw err;
throw new CommandLayerError(err?.message || String(err));
} finally {
clearTimeout(timeoutId);
}
}
close() {
// no-op
}
}
export function createClient(opts: ClientOptions = {}) {
return new CommandLayerClient(opts);
}