@tpsdev-ai/agent 0.5.4 → 0.6.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/bin.js +47 -2
- package/dist/bin.js.map +1 -1
- package/dist/config.d.ts +2 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +8 -0
- package/dist/config.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/io/flair.d.ts +43 -0
- package/dist/io/flair.d.ts.map +1 -0
- package/dist/io/flair.js +143 -0
- package/dist/io/flair.js.map +1 -0
- package/dist/io/mail.d.ts +24 -2
- package/dist/io/mail.d.ts.map +1 -1
- package/dist/io/mail.js +168 -15
- package/dist/io/mail.js.map +1 -1
- package/dist/lib/signEnvelope.d.ts +67 -0
- package/dist/lib/signEnvelope.d.ts.map +1 -0
- package/dist/lib/signEnvelope.js +244 -0
- package/dist/lib/signEnvelope.js.map +1 -0
- package/dist/llm/provider.d.ts +19 -1
- package/dist/llm/provider.d.ts.map +1 -1
- package/dist/llm/provider.js +362 -18
- package/dist/llm/provider.js.map +1 -1
- package/dist/runtime/agent.d.ts +2 -0
- package/dist/runtime/agent.d.ts.map +1 -1
- package/dist/runtime/agent.js +50 -3
- package/dist/runtime/agent.js.map +1 -1
- package/dist/runtime/event-loop.d.ts +36 -5
- package/dist/runtime/event-loop.d.ts.map +1 -1
- package/dist/runtime/event-loop.js +235 -32
- package/dist/runtime/event-loop.js.map +1 -1
- package/dist/runtime/types.d.ts +16 -1
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/telemetry/events.d.ts +57 -0
- package/dist/telemetry/events.d.ts.map +1 -0
- package/dist/telemetry/events.js +37 -0
- package/dist/telemetry/events.js.map +1 -0
- package/dist/tools/edit.d.ts.map +1 -1
- package/dist/tools/edit.js +94 -16
- package/dist/tools/edit.js.map +1 -1
- package/package.json +10 -2
- package/src/bin.ts +56 -3
- package/src/config.ts +10 -1
- package/src/index.ts +8 -0
- package/src/io/flair.ts +183 -0
- package/src/io/mail.ts +184 -19
- package/src/lib/signEnvelope.ts +332 -0
- package/src/llm/provider.ts +391 -17
- package/src/runtime/agent.ts +55 -3
- package/src/runtime/event-loop.ts +233 -15
- package/src/runtime/types.ts +20 -1
- package/src/telemetry/events.ts +101 -0
- package/src/tools/edit.ts +108 -17
- package/test/bin-launch-id.test.ts +104 -0
- package/test/core-loop.test.ts +240 -0
- package/test/events.test.ts +33 -0
- package/test/flair-context.test.ts +102 -0
- package/test/governance.test.ts +103 -2
- package/test/io.test.ts +8 -8
- package/test/provider.test.ts +43 -0
package/src/io/mail.ts
CHANGED
|
@@ -1,10 +1,17 @@
|
|
|
1
|
-
import { existsSync, mkdirSync, readdirSync, renameSync, readFileSync } from "node:fs";
|
|
1
|
+
import { existsSync, mkdirSync, readdirSync, renameSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
+
import type { EventLogger } from "../telemetry/events.js";
|
|
4
|
+
import { sanitizeError } from "../telemetry/events.js";
|
|
5
|
+
import { verifyEnvelope, type FlairClient } from "../lib/signEnvelope.js";
|
|
3
6
|
|
|
4
7
|
export interface MailMessage {
|
|
5
8
|
filename: string;
|
|
6
9
|
body: string;
|
|
7
10
|
receivedAt: Date;
|
|
11
|
+
/** Trust/routing headers from bridge envelope */
|
|
12
|
+
headers: Record<string, string>;
|
|
13
|
+
/** Sender agent ID */
|
|
14
|
+
from: string;
|
|
8
15
|
}
|
|
9
16
|
|
|
10
17
|
/**
|
|
@@ -15,19 +22,29 @@ export interface MailMessage {
|
|
|
15
22
|
export class MailClient {
|
|
16
23
|
private inboxNew: string;
|
|
17
24
|
private inboxCur: string;
|
|
25
|
+
private inboxDlq: string;
|
|
18
26
|
private outboxNew: string;
|
|
19
27
|
|
|
20
|
-
constructor(
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
28
|
+
constructor(
|
|
29
|
+
public readonly mailDir: string,
|
|
30
|
+
private readonly events?: EventLogger,
|
|
31
|
+
private readonly agentId = "unknown",
|
|
32
|
+
private readonly flairClient?: FlairClient,
|
|
33
|
+
) {
|
|
34
|
+
this.inboxNew = join(mailDir, agentId, "new");
|
|
35
|
+
this.inboxCur = join(mailDir, agentId, "cur");
|
|
36
|
+
this.inboxDlq = join(mailDir, agentId, "dlq");
|
|
37
|
+
this.outboxNew = join(mailDir, agentId, "outbox");
|
|
38
|
+
for (const dir of [this.inboxNew, this.inboxCur, this.inboxDlq, this.outboxNew]) {
|
|
26
39
|
mkdirSync(dir, { recursive: true });
|
|
27
40
|
}
|
|
28
41
|
}
|
|
29
42
|
|
|
30
|
-
/**
|
|
43
|
+
/**
|
|
44
|
+
* Return all messages in inbox/new and move them to inbox/cur.
|
|
45
|
+
* When a FlairClient is provided, signed envelopes are verified
|
|
46
|
+
* before promotion; invalid/malformed messages go to dlq/.
|
|
47
|
+
*/
|
|
31
48
|
async checkNewMail(): Promise<MailMessage[]> {
|
|
32
49
|
if (!existsSync(this.inboxNew)) return [];
|
|
33
50
|
|
|
@@ -35,11 +52,58 @@ export class MailClient {
|
|
|
35
52
|
const messages: MailMessage[] = [];
|
|
36
53
|
|
|
37
54
|
for (const file of files) {
|
|
55
|
+
const started = Date.now();
|
|
38
56
|
const srcPath = join(this.inboxNew, file);
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
57
|
+
try {
|
|
58
|
+
const body = readFileSync(srcPath, "utf-8");
|
|
59
|
+
|
|
60
|
+
// Envelope verification (strict when FlairClient is available).
|
|
61
|
+
if (this.flairClient) {
|
|
62
|
+
const verifyResult = await this.verifyMailBody(body, file);
|
|
63
|
+
if (!verifyResult.pass) {
|
|
64
|
+
const dlqPath = join(this.inboxDlq, file);
|
|
65
|
+
renameSync(srcPath, dlqPath);
|
|
66
|
+
writeFileSync(join(this.inboxDlq, `${file}.reject`), verifyResult.reason, "utf-8");
|
|
67
|
+
this.events?.emit({
|
|
68
|
+
type: "mail.receive",
|
|
69
|
+
agent: this.agentId,
|
|
70
|
+
status: "rejected",
|
|
71
|
+
from: verifyResult.from ?? "unknown",
|
|
72
|
+
durationMs: Date.now() - started,
|
|
73
|
+
error: verifyResult.reason,
|
|
74
|
+
});
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Promote to cur/
|
|
80
|
+
const dstPath = join(this.inboxCur, file);
|
|
81
|
+
renameSync(srcPath, dstPath);
|
|
82
|
+
let headers: Record<string, string> = {};
|
|
83
|
+
let from = "unknown";
|
|
84
|
+
try {
|
|
85
|
+
const parsed = JSON.parse(body);
|
|
86
|
+
headers = parsed.headers ?? {};
|
|
87
|
+
from = parsed.from ?? "unknown";
|
|
88
|
+
} catch {}
|
|
89
|
+
messages.push({ filename: file, body, receivedAt: new Date(), headers, from });
|
|
90
|
+
this.events?.emit({
|
|
91
|
+
type: "mail.receive",
|
|
92
|
+
agent: this.agentId,
|
|
93
|
+
status: "ok",
|
|
94
|
+
from,
|
|
95
|
+
durationMs: Date.now() - started,
|
|
96
|
+
});
|
|
97
|
+
} catch (err) {
|
|
98
|
+
this.events?.emit({
|
|
99
|
+
type: "mail.receive",
|
|
100
|
+
agent: this.agentId,
|
|
101
|
+
status: "error",
|
|
102
|
+
from: "unknown",
|
|
103
|
+
durationMs: Date.now() - started,
|
|
104
|
+
error: sanitizeError(err),
|
|
105
|
+
});
|
|
106
|
+
}
|
|
43
107
|
}
|
|
44
108
|
|
|
45
109
|
return messages;
|
|
@@ -47,12 +111,113 @@ export class MailClient {
|
|
|
47
111
|
|
|
48
112
|
/** Write a message to outbox/new for relay delivery. */
|
|
49
113
|
async sendMail(to: string, body: string): Promise<void> {
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
114
|
+
const started = Date.now();
|
|
115
|
+
try {
|
|
116
|
+
const { writeFileSync } = await import("node:fs");
|
|
117
|
+
const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}.json`;
|
|
118
|
+
writeFileSync(
|
|
119
|
+
join(this.outboxNew, filename),
|
|
120
|
+
JSON.stringify({ to, body, sentAt: new Date().toISOString() }, null, 2),
|
|
121
|
+
"utf-8"
|
|
122
|
+
);
|
|
123
|
+
this.events?.emit({
|
|
124
|
+
type: "mail.send",
|
|
125
|
+
agent: this.agentId,
|
|
126
|
+
to,
|
|
127
|
+
status: "ok",
|
|
128
|
+
durationMs: Date.now() - started,
|
|
129
|
+
});
|
|
130
|
+
} catch (err) {
|
|
131
|
+
this.events?.emit({
|
|
132
|
+
type: "mail.send",
|
|
133
|
+
agent: this.agentId,
|
|
134
|
+
to,
|
|
135
|
+
status: "error",
|
|
136
|
+
durationMs: Date.now() - started,
|
|
137
|
+
error: sanitizeError(err),
|
|
138
|
+
});
|
|
139
|
+
throw err;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Deliver all messages in outbox to recipient inboxes (local relay). */
|
|
144
|
+
deliverOutbox(): void {
|
|
145
|
+
if (!existsSync(this.outboxNew)) return;
|
|
146
|
+
const files = readdirSync(this.outboxNew).filter(f => !f.startsWith("."));
|
|
147
|
+
for (const file of files) {
|
|
148
|
+
const srcPath = join(this.outboxNew, file);
|
|
149
|
+
try {
|
|
150
|
+
const raw = readFileSync(srcPath, "utf-8");
|
|
151
|
+
const msg = JSON.parse(raw) as { to: string; body: string; sentAt: string };
|
|
152
|
+
if (!msg.to || !/^[a-zA-Z0-9_-]{1,64}$/.test(msg.to)) {
|
|
153
|
+
continue; // skip invalid recipients
|
|
154
|
+
}
|
|
155
|
+
const recipientInbox = join(this.mailDir, msg.to, "new");
|
|
156
|
+
mkdirSync(recipientInbox, { recursive: true });
|
|
157
|
+
const destFile = `${msg.sentAt.replace(/[:.]/g, "-")}-${file}`;
|
|
158
|
+
renameSync(srcPath, join(recipientInbox, destFile));
|
|
159
|
+
} catch {
|
|
160
|
+
// Leave in outbox on error
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Verify a mail body against the v1 signed envelope spec.
|
|
167
|
+
* Returns { pass: true } if verified, or { pass: false, reason: "..." } on failure.
|
|
168
|
+
* Requires flairClient to be set.
|
|
169
|
+
*/
|
|
170
|
+
private async verifyMailBody(
|
|
171
|
+
body: string,
|
|
172
|
+
filename: string,
|
|
173
|
+
): Promise<{ pass: true } | { pass: false; reason: string; from?: string }> {
|
|
174
|
+
const client = this.flairClient!;
|
|
175
|
+
|
|
176
|
+
// 1. Parse the mail file as JSON
|
|
177
|
+
let mailMsg: { from?: string; body: string };
|
|
178
|
+
try {
|
|
179
|
+
mailMsg = JSON.parse(body);
|
|
180
|
+
} catch {
|
|
181
|
+
return { pass: false, reason: "json parse error: invalid JSON" };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if (!mailMsg.body || typeof mailMsg.body !== "string") {
|
|
185
|
+
return { pass: false, reason: "json parse error: missing body field" };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// 2. Parse the body field as an envelope
|
|
189
|
+
let envelope: unknown;
|
|
190
|
+
try {
|
|
191
|
+
envelope = JSON.parse(mailMsg.body);
|
|
192
|
+
} catch {
|
|
193
|
+
return { pass: false, reason: "json parse error: invalid envelope body", from: mailMsg.from };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (envelope == null || typeof envelope !== "object" || Array.isArray(envelope)) {
|
|
197
|
+
return { pass: false, reason: "unsigned envelope (v1 required)", from: mailMsg.from };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const env = envelope as Record<string, unknown>;
|
|
201
|
+
if (
|
|
202
|
+
typeof env.v !== "number" ||
|
|
203
|
+
!Array.isArray(env.delegationChain) ||
|
|
204
|
+
typeof env.signature !== "string"
|
|
205
|
+
) {
|
|
206
|
+
return { pass: false, reason: "unsigned envelope (v1 required)", from: mailMsg.from };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// 3. Verify the envelope using the canonical verifyEnvelope
|
|
210
|
+
try {
|
|
211
|
+
const vr = await verifyEnvelope(env as any, client);
|
|
212
|
+
if (!vr.ok) {
|
|
213
|
+
return { pass: false, reason: vr.reason, from: mailMsg.from };
|
|
214
|
+
}
|
|
215
|
+
} catch (err: any) {
|
|
216
|
+
// verifyEnvelope threw (e.g. Flair network error).
|
|
217
|
+
// Don't drop the message — pass it through and log.
|
|
218
|
+
console.warn(`[MailClient] verifyEnvelope error for ${filename}: ${err?.message ?? err}`);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return { pass: true };
|
|
57
222
|
}
|
|
58
223
|
}
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* signEnvelope — Ed25519 signature over TPS mail envelope + delegation chain.
|
|
3
|
+
*
|
|
4
|
+
* Signs every agent-kind entry in the delegation chain whose signature is
|
|
5
|
+
* null/missing, then signs the outer envelope. Uses JCS (RFC 8785)
|
|
6
|
+
* canonicalization for deterministic byte-level signing input.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import * as ed from "@noble/ed25519";
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import canonicalize from "canonicalize";
|
|
12
|
+
|
|
13
|
+
// Ensure sync sha512 is wired (same pattern as identity.ts).
|
|
14
|
+
import { hashes } from "@noble/ed25519";
|
|
15
|
+
hashes.sha512 = (message: Uint8Array) => {
|
|
16
|
+
return new Uint8Array(createHash("sha512").update(message).digest());
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
// ─── Types ──────────────────────────────────────────────────────────────────
|
|
20
|
+
|
|
21
|
+
export interface ChainEntry {
|
|
22
|
+
agent: string;
|
|
23
|
+
kind: "human" | "agent";
|
|
24
|
+
timestamp: string; // ISO-8601 UTC
|
|
25
|
+
rationale: string;
|
|
26
|
+
signature: string | null; // "ed25519:<base64>" or null for human
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface Envelope {
|
|
30
|
+
v: number;
|
|
31
|
+
from: string;
|
|
32
|
+
to: string;
|
|
33
|
+
subject?: string;
|
|
34
|
+
body: string;
|
|
35
|
+
messageId: string;
|
|
36
|
+
timestamp: string;
|
|
37
|
+
delegationChain: ChainEntry[];
|
|
38
|
+
signature?: string; // populated by signEnvelope
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ─── Helpers ────────────────────────────────────────────────────────────────
|
|
42
|
+
|
|
43
|
+
function base64Encode(buf: Uint8Array): string {
|
|
44
|
+
return Buffer.from(buf).toString("base64");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function base64Decode(s: string): Uint8Array {
|
|
48
|
+
return new Uint8Array(Buffer.from(s, "base64"));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Sign payload bytes with an Ed25519 seed (32 bytes).
|
|
53
|
+
* Returns a 64-byte signature.
|
|
54
|
+
*/
|
|
55
|
+
function signPayload(payload: Uint8Array, seed: Uint8Array): Uint8Array {
|
|
56
|
+
return ed.sign(payload, seed);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Verify an Ed25519 signature against a payload and public key.
|
|
61
|
+
*/
|
|
62
|
+
function verifyPayload(
|
|
63
|
+
payload: Uint8Array,
|
|
64
|
+
signature: Uint8Array,
|
|
65
|
+
publicKey: Uint8Array,
|
|
66
|
+
): boolean {
|
|
67
|
+
try {
|
|
68
|
+
return ed.verify(signature, payload, publicKey);
|
|
69
|
+
} catch {
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Decode a "ed25519:<base64>" signature string into raw bytes.
|
|
76
|
+
* Returns null if the signature is null/undefined or malformed.
|
|
77
|
+
*/
|
|
78
|
+
function decodeSignature(sig: string | null | undefined): Uint8Array | null {
|
|
79
|
+
if (sig == null) return null;
|
|
80
|
+
const prefix = "ed25519:";
|
|
81
|
+
if (!sig.startsWith(prefix)) return null;
|
|
82
|
+
try {
|
|
83
|
+
return base64Decode(sig.slice(prefix.length));
|
|
84
|
+
} catch {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Deep-clone an envelope so we never mutate the input.
|
|
91
|
+
*/
|
|
92
|
+
function cloneEnvelope(e: Envelope): Envelope {
|
|
93
|
+
return JSON.parse(JSON.stringify(e)) as Envelope;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ─── Core ───────────────────────────────────────────────────────────────────
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Sign an envelope:
|
|
100
|
+
* - For each agent-kind chain entry whose signature is null/missing, generate
|
|
101
|
+
* sig over jcs({ prior: chain[0..i], entry: { ...entry, signature: undefined } })
|
|
102
|
+
* using the agent's privkey.
|
|
103
|
+
* - Then compute outer sig over jcs({ ...envelope, signature: undefined })
|
|
104
|
+
* using the LAST chain entry's privkey (which must equal envelope.from).
|
|
105
|
+
*
|
|
106
|
+
* Caller passes privkeys by agent name. For PR-1 simplicity, accept a map:
|
|
107
|
+
* keysByAgent: { [agentName: string]: Buffer (32-byte Ed25519 seed) }
|
|
108
|
+
*
|
|
109
|
+
* Returns envelope with chain entry sigs and outer sig populated.
|
|
110
|
+
* Mutates a copy, does not mutate input.
|
|
111
|
+
*/
|
|
112
|
+
export function signEnvelope(
|
|
113
|
+
envelope: Envelope,
|
|
114
|
+
keysByAgent: Record<string, Buffer>,
|
|
115
|
+
): Envelope {
|
|
116
|
+
const chain = envelope.delegationChain;
|
|
117
|
+
|
|
118
|
+
// ── Validation ────────────────────────────────────────────────────────
|
|
119
|
+
|
|
120
|
+
// 1. Chain tip must match envelope.from
|
|
121
|
+
const chainTip = chain[chain.length - 1];
|
|
122
|
+
if (!chainTip || chainTip.agent !== envelope.from) {
|
|
123
|
+
throw new Error(
|
|
124
|
+
`Envelope from "${envelope.from}" must equal delegation chain tip agent "${chainTip?.agent ?? "(empty chain)"}"`,
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// 2. Check human entries don't have signatures
|
|
129
|
+
for (const entry of chain) {
|
|
130
|
+
if (entry.kind === "human" && entry.signature !== null) {
|
|
131
|
+
throw new Error(
|
|
132
|
+
`Human-kind chain entry for "${entry.agent}" must have null signature`,
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// 3. Collect all agents that need a private key
|
|
138
|
+
const agentsNeedingKey = new Set<string>();
|
|
139
|
+
for (const entry of chain) {
|
|
140
|
+
if (entry.kind === "agent" && entry.signature === null) {
|
|
141
|
+
agentsNeedingKey.add(entry.agent);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// Outer sig always needs envelope.from's key
|
|
145
|
+
agentsNeedingKey.add(envelope.from);
|
|
146
|
+
|
|
147
|
+
for (const agent of agentsNeedingKey) {
|
|
148
|
+
if (!keysByAgent[agent]) {
|
|
149
|
+
throw new Error(
|
|
150
|
+
`Missing private key for agent "${agent}"`,
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// ── Sign chain entries ────────────────────────────────────────────────
|
|
156
|
+
|
|
157
|
+
const result = cloneEnvelope(envelope);
|
|
158
|
+
const resultChain = result.delegationChain;
|
|
159
|
+
|
|
160
|
+
for (let i = 0; i < resultChain.length; i++) {
|
|
161
|
+
const entry = resultChain[i];
|
|
162
|
+
if (entry.kind !== "agent") continue;
|
|
163
|
+
if (entry.signature !== null) continue; // idempotent: skip already-signed
|
|
164
|
+
|
|
165
|
+
// Build signing payload: { prior: chain[0..i], entry: { ...entry, signature: undefined } }
|
|
166
|
+
const prior = resultChain.slice(0, i);
|
|
167
|
+
const entryForSig = {
|
|
168
|
+
agent: entry.agent,
|
|
169
|
+
kind: entry.kind,
|
|
170
|
+
timestamp: entry.timestamp,
|
|
171
|
+
rationale: entry.rationale,
|
|
172
|
+
signature: undefined,
|
|
173
|
+
} as const;
|
|
174
|
+
const payload = { prior, entry: entryForSig };
|
|
175
|
+
|
|
176
|
+
const canonical = canonicalize(payload);
|
|
177
|
+
if (canonical === undefined) {
|
|
178
|
+
throw new Error(`Failed to canonicalize chain entry payload for agent "${entry.agent}"`);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const payloadBuf = new TextEncoder().encode(canonical);
|
|
182
|
+
const seed = new Uint8Array(keysByAgent[entry.agent]);
|
|
183
|
+
const sig = signPayload(payloadBuf, seed);
|
|
184
|
+
entry.signature = `ed25519:${base64Encode(sig)}`;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ── Sign outer envelope ───────────────────────────────────────────────
|
|
188
|
+
|
|
189
|
+
const { signature: _, ...envelopeWithoutSig } = result;
|
|
190
|
+
const canonical = canonicalize(envelopeWithoutSig);
|
|
191
|
+
if (canonical === undefined) {
|
|
192
|
+
throw new Error("Failed to canonicalize outer envelope");
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const payloadBuf = new TextEncoder().encode(canonical);
|
|
196
|
+
const fromSeed = new Uint8Array(keysByAgent[envelope.from]);
|
|
197
|
+
const outerSig = signPayload(payloadBuf, fromSeed);
|
|
198
|
+
result.signature = `ed25519:${base64Encode(outerSig)}`;
|
|
199
|
+
|
|
200
|
+
return result;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ─── Flair client interface (dependency-injected) ──────────────────────────
|
|
204
|
+
|
|
205
|
+
export interface FlairClient {
|
|
206
|
+
getAgent(name: string): Promise<{ publicKey: Buffer } | null>;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ─── Verify result types ────────────────────────────────────────────────────
|
|
210
|
+
|
|
211
|
+
export interface VerifyOk {
|
|
212
|
+
ok: true;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export interface VerifyReject {
|
|
216
|
+
ok: false;
|
|
217
|
+
reason: string;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Verify a signed envelope:
|
|
222
|
+
* - v must be 1
|
|
223
|
+
* - delegationChain must be non-empty and length <= 16
|
|
224
|
+
* - last chain entry's agent must equal envelope.from
|
|
225
|
+
* - outer signature must verify against envelope.from's pubkey over
|
|
226
|
+
* jcs({ ...envelope, signature: undefined })
|
|
227
|
+
* - each agent-kind chain entry's signature must verify against that
|
|
228
|
+
* agent's pubkey over jcs({ prior: chain[0..i], entry: { ...entry, signature: undefined } })
|
|
229
|
+
* - each human-kind entry must have signature === null
|
|
230
|
+
*
|
|
231
|
+
* Pure function with DI'd flairClient — no Flair HTTP coupling.
|
|
232
|
+
*/
|
|
233
|
+
export async function verifyEnvelope(
|
|
234
|
+
envelope: Envelope,
|
|
235
|
+
flairClient: FlairClient,
|
|
236
|
+
): Promise<VerifyOk | VerifyReject> {
|
|
237
|
+
// 1. Version check
|
|
238
|
+
if (envelope.v !== 1) {
|
|
239
|
+
return { ok: false, reason: "unsupported version" };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// 2. Chain must exist and be non-empty
|
|
243
|
+
const chain = envelope.delegationChain;
|
|
244
|
+
if (!chain || chain.length === 0) {
|
|
245
|
+
return { ok: false, reason: "missing chain" };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// 3. Chain length limit
|
|
249
|
+
if (chain.length > 16) {
|
|
250
|
+
return { ok: false, reason: "chain too long" };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// 4. Chain tip must match envelope.from
|
|
254
|
+
if (chain[chain.length - 1].agent !== envelope.from) {
|
|
255
|
+
return { ok: false, reason: "chain tip / from mismatch" };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// 5. Human entries must have null signature
|
|
259
|
+
for (const entry of chain) {
|
|
260
|
+
if (entry.kind === "human" && entry.signature !== null) {
|
|
261
|
+
return { ok: false, reason: "human entry must have null signature" };
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// 6. Resolve all agent pubkeys from Flair
|
|
266
|
+
const pubkeys = new Map<string, Buffer>();
|
|
267
|
+
const agentsToResolve = new Set<string>();
|
|
268
|
+
for (const entry of chain) {
|
|
269
|
+
if (entry.kind === "agent") agentsToResolve.add(entry.agent);
|
|
270
|
+
}
|
|
271
|
+
agentsToResolve.add(envelope.from);
|
|
272
|
+
|
|
273
|
+
for (const agent of agentsToResolve) {
|
|
274
|
+
const info = await flairClient.getAgent(agent);
|
|
275
|
+
if (!info) {
|
|
276
|
+
return { ok: false, reason: `agent ${agent} not found in Flair` };
|
|
277
|
+
}
|
|
278
|
+
pubkeys.set(agent, info.publicKey);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// 7. Verify each agent-kind chain entry signature
|
|
282
|
+
for (let i = 0; i < chain.length; i++) {
|
|
283
|
+
const entry = chain[i];
|
|
284
|
+
if (entry.kind !== "agent") continue;
|
|
285
|
+
|
|
286
|
+
const sigBytes = decodeSignature(entry.signature);
|
|
287
|
+
if (!sigBytes) {
|
|
288
|
+
return { ok: false, reason: `chain entry ${i} signature invalid` };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const prior = chain.slice(0, i);
|
|
292
|
+
const entryForSig = {
|
|
293
|
+
agent: entry.agent,
|
|
294
|
+
kind: entry.kind,
|
|
295
|
+
timestamp: entry.timestamp,
|
|
296
|
+
rationale: entry.rationale,
|
|
297
|
+
signature: undefined,
|
|
298
|
+
} as const;
|
|
299
|
+
const payload = { prior, entry: entryForSig };
|
|
300
|
+
|
|
301
|
+
const canonical = canonicalize(payload);
|
|
302
|
+
if (canonical === undefined) {
|
|
303
|
+
return { ok: false, reason: `chain entry ${i} signature invalid` };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const payloadBuf = new TextEncoder().encode(canonical);
|
|
307
|
+
const pubKey = pubkeys.get(entry.agent)!;
|
|
308
|
+
if (!verifyPayload(payloadBuf, sigBytes, new Uint8Array(pubKey))) {
|
|
309
|
+
return { ok: false, reason: `chain entry ${i} signature invalid` };
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// 8. Verify outer signature
|
|
314
|
+
const sigBytes = decodeSignature(envelope.signature);
|
|
315
|
+
if (!sigBytes) {
|
|
316
|
+
return { ok: false, reason: "outer signature invalid" };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const { signature: _, ...envelopeWithoutSig } = envelope;
|
|
320
|
+
const canonical = canonicalize(envelopeWithoutSig);
|
|
321
|
+
if (canonical === undefined) {
|
|
322
|
+
return { ok: false, reason: "outer signature invalid" };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const payloadBuf = new TextEncoder().encode(canonical);
|
|
326
|
+
const fromPubKey = pubkeys.get(envelope.from)!;
|
|
327
|
+
if (!verifyPayload(payloadBuf, sigBytes, new Uint8Array(fromPubKey))) {
|
|
328
|
+
return { ok: false, reason: "outer signature invalid" };
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
return { ok: true };
|
|
332
|
+
}
|