@orangecheck/agent-core 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,329 @@
1
+ // OC Agent v1.2 — Federation Principal (FEDERATION.md).
2
+ //
3
+ // ADDITIVE module. Implements the federation-principal extension WITHOUT
4
+ // touching the v1 single-address path (types.ts DelegationEnvelope, verify.ts
5
+ // verifyDelegation are unchanged + byte-identical against their vectors). A
6
+ // dispatcher routes by `principal.alg` / `signer.alg`:
7
+ //
8
+ // principal.alg === 'bip322' → verifyDelegation (v1, unchanged)
9
+ // principal.alg === 'federation' → verifyFederationDelegation (this module)
10
+ //
11
+ // A federation principal is a content-addressed M-of-N guardian set. A
12
+ // delegation / revocation under it is authentic iff M of N declared guardians
13
+ // have BIP-322-signed the canonical message. The canonical-message + id rules
14
+ // are unchanged — only the principal line (`federation:<descriptor_id>`) and the
15
+ // signature block (`federation-bip322` with M-of-N) generalize. FEDERATION.md
16
+ // §2 / §3 / §4.
17
+
18
+ import { sha256 } from '@noble/hashes/sha256';
19
+
20
+ import {
21
+ canonicalizeScopes,
22
+ computeDelegationId,
23
+ computeRevocationId,
24
+ delegationCanonicalMessage,
25
+ hexEncode,
26
+ revocationCanonicalMessage,
27
+ } from './canonical.js';
28
+ import type { ActorRef, AgentErrorCode, DelegationBond, DelegationRevocationRef } from './types.js';
29
+
30
+ // ─────────────────────────────────────────────────────────────────────────────
31
+ // Types (FEDERATION.md §2 / §3.2)
32
+ // ─────────────────────────────────────────────────────────────────────────────
33
+
34
+ export interface FederationGuardian {
35
+ /** mainnet Bitcoin address (P2WPKH, P2TR, or P2PKH). */
36
+ address: string;
37
+ alg: 'bip322';
38
+ /** Optional human label. NOT part of the cryptographic identity. */
39
+ name?: string;
40
+ }
41
+
42
+ export interface FederationDescriptor {
43
+ v: 1;
44
+ kind: 'agent-federation';
45
+ /** "M-of-N", 1 ≤ M ≤ N, N === guardians.length. */
46
+ threshold: string;
47
+ guardians: FederationGuardian[];
48
+ }
49
+
50
+ export interface FederationPrincipal {
51
+ alg: 'federation';
52
+ descriptor_id: string;
53
+ descriptor: FederationDescriptor;
54
+ }
55
+
56
+ export interface FederationSignature {
57
+ alg: 'federation-bip322';
58
+ threshold: string;
59
+ signatures: Array<{ guardian_address: string; value: string }>;
60
+ }
61
+
62
+ export interface FederationDelegationEnvelope {
63
+ v: 1;
64
+ kind: 'agent-delegation';
65
+ id: string;
66
+ principal: FederationPrincipal;
67
+ agent: ActorRef;
68
+ scopes: string[];
69
+ bond: DelegationBond | null;
70
+ issued_at: string;
71
+ expires_at: string;
72
+ nonce: string;
73
+ revocation: DelegationRevocationRef;
74
+ sig: FederationSignature;
75
+ }
76
+
77
+ export interface FederationRevocationEnvelope {
78
+ v: 1;
79
+ kind: 'agent-revocation';
80
+ id: string;
81
+ delegation_id: string;
82
+ /** Federation principal that authorizes the revocation (the guardian set). */
83
+ signer: FederationPrincipal;
84
+ reason: string;
85
+ signed_at: string;
86
+ ots?: unknown | null;
87
+ sig: FederationSignature;
88
+ }
89
+
90
+ export type FederationVerifyResult =
91
+ | { ok: true; id: string; canonicalMessage: string }
92
+ | { ok: false; code: AgentErrorCode; message: string };
93
+
94
+ export interface VerifyFederationBase {
95
+ /** Injected BIP-322 verifier. Required unless `skipSignatureVerification`. */
96
+ verifyBip322?: (msg: string, signatureB64: string, address: string) => Promise<boolean>;
97
+ skipSignatureVerification?: boolean;
98
+ }
99
+
100
+ // ─────────────────────────────────────────────────────────────────────────────
101
+ // Descriptor canonicalization (FEDERATION.md §2.1 / §2.2)
102
+ // ─────────────────────────────────────────────────────────────────────────────
103
+
104
+ /**
105
+ * The canonical, line-oriented descriptor message. Guardians are emitted in
106
+ * lexicographic byte order of their address (NOT the JSON array order); the
107
+ * `name` label is excluded — it is JSON-only metadata. No trailing LF.
108
+ */
109
+ export function federationDescriptorCanonicalMessage(descriptor: FederationDescriptor): string {
110
+ const addresses = descriptor.guardians
111
+ .map((g) => g.address)
112
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
113
+ return [
114
+ 'oc-agent:federation:v1',
115
+ `threshold: ${descriptor.threshold}`,
116
+ ...addresses.map((a) => `guardian: ${a}`),
117
+ ].join('\n');
118
+ }
119
+
120
+ /** descriptor_id := H(canonical_descriptor_bytes). 64 lowercase hex. */
121
+ export function computeFederationDescriptorId(descriptor: FederationDescriptor): string {
122
+ return hexEncode(sha256(new TextEncoder().encode(federationDescriptorCanonicalMessage(descriptor))));
123
+ }
124
+
125
+ function parseThreshold(t: unknown): { m: number; n: number } | null {
126
+ if (typeof t !== 'string') return null;
127
+ const m = /^(\d+)-of-(\d+)$/.exec(t);
128
+ if (!m) return null;
129
+ const mm = Number(m[1]);
130
+ const nn = Number(m[2]);
131
+ if (!Number.isInteger(mm) || !Number.isInteger(nn) || mm < 1 || mm > nn) return null;
132
+ return { m: mm, n: nn };
133
+ }
134
+
135
+ const HEX64 = /^[0-9a-f]{64}$/;
136
+ const ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/;
137
+
138
+ /**
139
+ * Shared descriptor + quorum validation (FEDERATION.md §3.3 checks 3–8 minus the
140
+ * id check, plus BIP-322). `reconstructedId` is the already-computed envelope id.
141
+ */
142
+ async function checkFederationQuorum(
143
+ principal: FederationPrincipal,
144
+ sig: FederationSignature,
145
+ reconstructedId: string,
146
+ input: VerifyFederationBase
147
+ ): Promise<{ ok: true } | { ok: false; code: AgentErrorCode; message: string }> {
148
+ // §3.3.2 — principal alg.
149
+ if (principal?.alg !== 'federation') {
150
+ return fail('E_MALFORMED', 'principal.alg must be "federation"');
151
+ }
152
+ const descriptor = principal.descriptor;
153
+ if (!descriptor || descriptor.kind !== 'agent-federation') {
154
+ return fail('E_MALFORMED', 'principal.descriptor missing or wrong kind');
155
+ }
156
+ const parsed = parseThreshold(descriptor.threshold);
157
+ if (!parsed) return fail('E_MALFORMED', `malformed threshold "${descriptor.threshold}"`);
158
+ if (!Array.isArray(descriptor.guardians) || descriptor.guardians.length !== parsed.n) {
159
+ return fail('E_MALFORMED', 'guardians length must equal N in M-of-N');
160
+ }
161
+
162
+ // §3.3.3 — descriptor_id matches the canonical hash of the inlined descriptor.
163
+ const computedDescId = computeFederationDescriptorId(descriptor);
164
+ if (principal.descriptor_id !== computedDescId) {
165
+ return fail(
166
+ 'E_BAD_FEDERATION_DESCRIPTOR',
167
+ `declared descriptor_id (${principal.descriptor_id}) != canonical hash (${computedDescId})`
168
+ );
169
+ }
170
+
171
+ // §3.3.4 — sig.threshold equals descriptor.threshold.
172
+ if (sig?.alg !== 'federation-bip322') {
173
+ return fail('E_MALFORMED', 'sig.alg must be "federation-bip322"');
174
+ }
175
+ if (sig.threshold !== descriptor.threshold) {
176
+ return fail(
177
+ 'E_THRESHOLD_MISMATCH',
178
+ `sig.threshold (${sig.threshold}) != descriptor.threshold (${descriptor.threshold})`
179
+ );
180
+ }
181
+
182
+ // §3.3.5 — at least M signatures.
183
+ const sigs = sig.signatures;
184
+ if (!Array.isArray(sigs)) return fail('E_MALFORMED', 'sig.signatures must be an array');
185
+ if (sigs.length < parsed.m) {
186
+ return fail(
187
+ 'E_THRESHOLD_NOT_MET',
188
+ `${sigs.length} signature(s) below threshold M=${parsed.m}`
189
+ );
190
+ }
191
+
192
+ // §3.3.6 / §3.3.7 — every signer is a declared guardian; no duplicates.
193
+ const guardianSet = new Set(descriptor.guardians.map((g) => g.address));
194
+ const seen = new Set<string>();
195
+ for (const s of sigs) {
196
+ if (!guardianSet.has(s.guardian_address)) {
197
+ return fail('E_UNKNOWN_GUARDIAN', `${s.guardian_address} is not a declared guardian`);
198
+ }
199
+ if (seen.has(s.guardian_address)) {
200
+ return fail('E_DUPLICATE_GUARDIAN', `${s.guardian_address} signed more than once`);
201
+ }
202
+ seen.add(s.guardian_address);
203
+ }
204
+
205
+ // §3.3.8 — each signature verifies under BIP-322 over the hex-encoded id.
206
+ if (!input.skipSignatureVerification) {
207
+ if (!input.verifyBip322) return fail('E_BAD_SIG', 'no BIP-322 verifier supplied');
208
+ for (const s of sigs) {
209
+ const ok = await input.verifyBip322(reconstructedId, s.value, s.guardian_address);
210
+ if (!ok) {
211
+ return fail('E_BAD_SIG', `guardian ${s.guardian_address} signature did not verify`);
212
+ }
213
+ }
214
+ }
215
+ return { ok: true };
216
+ }
217
+
218
+ // ─────────────────────────────────────────────────────────────────────────────
219
+ // Delegation under a federation principal (FEDERATION.md §3)
220
+ // ─────────────────────────────────────────────────────────────────────────────
221
+
222
+ export interface VerifyFederationDelegationInput extends VerifyFederationBase {
223
+ envelope: FederationDelegationEnvelope;
224
+ now?: Date;
225
+ skipTemporalCheck?: boolean;
226
+ }
227
+
228
+ export async function verifyFederationDelegation(
229
+ input: VerifyFederationDelegationInput
230
+ ): Promise<FederationVerifyResult> {
231
+ const env = input.envelope;
232
+ if (env?.kind !== 'agent-delegation') return fail('E_MALFORMED', 'kind must be "agent-delegation"');
233
+ if (!HEX64.test(env.id ?? '')) return fail('E_MALFORMED', 'id must be 64 lowercase hex chars');
234
+ if (!env.agent?.address || env.agent.alg !== 'bip322') return fail('E_MALFORMED', 'agent invalid');
235
+ if (!Array.isArray(env.scopes) || env.scopes.length === 0) {
236
+ return fail('E_MALFORMED', 'scopes must be a non-empty array');
237
+ }
238
+ if (!ISO_UTC.test(env.issued_at) || !ISO_UTC.test(env.expires_at)) {
239
+ return fail('E_MALFORMED', 'issued_at / expires_at must be ISO 8601 UTC');
240
+ }
241
+ if (!/^[0-9a-f]{32}$/.test(env.nonce)) return fail('E_MALFORMED', 'nonce must be 32 hex chars');
242
+
243
+ // Canonical scopes (identical rules to v1) must be sorted on the envelope.
244
+ let canonicalScopes: string[];
245
+ try {
246
+ canonicalScopes = canonicalizeScopes(env.scopes);
247
+ } catch (e) {
248
+ return fail('E_BAD_SCOPE_GRAMMAR', (e as Error).message);
249
+ }
250
+ for (let i = 0; i < canonicalScopes.length; i++) {
251
+ if (env.scopes[i] !== canonicalScopes[i]) {
252
+ return fail('E_BAD_SCOPE_GRAMMAR', `scope index ${i} not in canonical order`);
253
+ }
254
+ }
255
+
256
+ // §3.3.1 / §3.1 — reconstruct the id with the `federation:<descriptor_id>`
257
+ // principal substitution. Everything else is the v1 canonical message.
258
+ const canonInput = {
259
+ principal: `federation:${env.principal?.descriptor_id ?? ''}`,
260
+ agent: env.agent.address,
261
+ scopes: canonicalScopes,
262
+ bond_sats: env.bond?.sats ?? 0,
263
+ bond_attestation: env.bond?.attestation_id ?? 'none',
264
+ issued_at: env.issued_at,
265
+ expires_at: env.expires_at,
266
+ nonce: env.nonce,
267
+ };
268
+ const reconstructedId = computeDelegationId(canonInput);
269
+ if (reconstructedId !== env.id) {
270
+ return fail('E_BAD_ID', `reconstructed id (${reconstructedId}) != envelope.id (${env.id})`);
271
+ }
272
+
273
+ const quorum = await checkFederationQuorum(env.principal, env.sig, env.id, input);
274
+ if (!quorum.ok) return quorum;
275
+
276
+ if (!input.skipTemporalCheck) {
277
+ const now = input.now ?? new Date();
278
+ const issued = new Date(env.issued_at);
279
+ const expires = new Date(env.expires_at);
280
+ if (expires <= issued) return fail('E_MALFORMED', 'expires_at <= issued_at');
281
+ if (now < issued) return fail('E_NOT_YET_VALID', `delegation not valid until ${env.issued_at}`);
282
+ if (now >= expires) return fail('E_EXPIRED', `delegation expired at ${env.expires_at}`);
283
+ }
284
+
285
+ return { ok: true, id: env.id, canonicalMessage: delegationCanonicalMessage(canonInput) };
286
+ }
287
+
288
+ // ─────────────────────────────────────────────────────────────────────────────
289
+ // Revocation under a federation principal (FEDERATION.md §4)
290
+ // ─────────────────────────────────────────────────────────────────────────────
291
+
292
+ export interface VerifyFederationRevocationInput extends VerifyFederationBase {
293
+ envelope: FederationRevocationEnvelope;
294
+ }
295
+
296
+ export async function verifyFederationRevocation(
297
+ input: VerifyFederationRevocationInput
298
+ ): Promise<FederationVerifyResult> {
299
+ const env = input.envelope;
300
+ if (env?.kind !== 'agent-revocation') return fail('E_MALFORMED', 'kind must be "agent-revocation"');
301
+ if (!HEX64.test(env.id ?? '')) return fail('E_MALFORMED', 'id must be 64 lowercase hex chars');
302
+ if (!HEX64.test(env.delegation_id ?? '')) return fail('E_MALFORMED', 'delegation_id must be 64-hex');
303
+ if (typeof env.reason !== 'string' || env.reason.length > 128) {
304
+ return fail('E_MALFORMED', 'reason must be a string ≤128 bytes');
305
+ }
306
+ if (!ISO_UTC.test(env.signed_at)) return fail('E_MALFORMED', 'signed_at must be ISO 8601 UTC');
307
+
308
+ // §4 — the `address:` line carries the `federation:<descriptor_id>`
309
+ // substitution; everything else is the v1 revocation canonical message.
310
+ const canonInput = {
311
+ address: `federation:${env.signer?.descriptor_id ?? ''}`,
312
+ delegation_id: env.delegation_id,
313
+ reason: env.reason,
314
+ signed_at: env.signed_at,
315
+ };
316
+ const reconstructedId = computeRevocationId(canonInput);
317
+ if (reconstructedId !== env.id) {
318
+ return fail('E_BAD_ID', `reconstructed id (${reconstructedId}) != envelope.id (${env.id})`);
319
+ }
320
+
321
+ const quorum = await checkFederationQuorum(env.signer, env.sig, env.id, input);
322
+ if (!quorum.ok) return quorum;
323
+
324
+ return { ok: true, id: env.id, canonicalMessage: revocationCanonicalMessage(canonInput) };
325
+ }
326
+
327
+ function fail(code: AgentErrorCode, message: string): { ok: false; code: AgentErrorCode; message: string } {
328
+ return { ok: false, code, message };
329
+ }
package/src/index.ts CHANGED
@@ -49,6 +49,24 @@ export type {
49
49
  VerifyRevocationInput,
50
50
  VerifySubdelegationInput,
51
51
  } from './verify.js';
52
+ export {
53
+ federationDescriptorCanonicalMessage,
54
+ computeFederationDescriptorId,
55
+ verifyFederationDelegation,
56
+ verifyFederationRevocation,
57
+ } from './federation.js';
58
+ export type {
59
+ FederationGuardian,
60
+ FederationDescriptor,
61
+ FederationPrincipal,
62
+ FederationSignature,
63
+ FederationDelegationEnvelope,
64
+ FederationRevocationEnvelope,
65
+ FederationVerifyResult,
66
+ VerifyFederationBase,
67
+ VerifyFederationDelegationInput,
68
+ VerifyFederationRevocationInput,
69
+ } from './federation.js';
52
70
  export {
53
71
  sealScopes,
54
72
  unsealScopes,
@@ -61,3 +79,6 @@ export type {
61
79
  UnsealScopesInput,
62
80
  UnsealedScopes,
63
81
  } from './private-scope.js';
82
+
83
+ export { assertScopeGranted, ScopeNotGrantedError } from './assert-scope.js';
84
+ export type { ScopeBearingDelegation } from './assert-scope.js';
@@ -187,6 +187,21 @@ function isNegative(v: Vector): v is NegativeVector {
187
187
  return 'negative' in v && v.negative === true;
188
188
  }
189
189
 
190
+ // v1.2 federation-principal vectors (v18–v26) are exercised by federation.test.ts
191
+ // against verifyFederationDelegation / verifyFederationRevocation. They use a
192
+ // `federation:<descriptor_id>` principal that the v1 single-address path here
193
+ // intentionally rejects, so skip them in the generic v1 loops. (v26 — the
194
+ // single-address baseline — stays: its principal.alg is "bip322".)
195
+ function isFederation(v: Vector): boolean {
196
+ const d = v as unknown as {
197
+ kind?: string;
198
+ expected?: { envelope?: { principal?: { alg?: string }; signer?: { alg?: string } } };
199
+ };
200
+ if (d.kind === 'federation-descriptor') return true;
201
+ const env = d.expected?.envelope;
202
+ return env?.principal?.alg === 'federation' || env?.signer?.alg === 'federation';
203
+ }
204
+
190
205
  async function loadVectors(): Promise<{ name: string; data: Vector }[]> {
191
206
  try {
192
207
  const files = await readdir(VECTORS_DIR);
@@ -217,6 +232,7 @@ describe('oc-agent-protocol test vectors', () => {
217
232
  const subdelegationEnvelopes = new Map<string, SubdelegationEnvelope>();
218
233
  for (const { data } of vectors) {
219
234
  if (isNegative(data)) continue;
235
+ if (isFederation(data)) continue;
220
236
  if ((data as { private_scope?: unknown }).private_scope) continue;
221
237
  if (data.kind === 'delegation') {
222
238
  delegationEnvelopes.set(data.expected.id, data.expected.envelope);
@@ -227,6 +243,7 @@ describe('oc-agent-protocol test vectors', () => {
227
243
 
228
244
  for (const { name, data } of vectors) {
229
245
  if (isNegative(data)) continue;
246
+ if (isFederation(data)) continue;
230
247
  if ((data as { private_scope?: unknown }).private_scope) continue;
231
248
  it(`${name} — canonical message reconstructs byte-identical`, () => {
232
249
  const msg = reconstructCanonical(data);
package/src/types.ts CHANGED
@@ -254,7 +254,13 @@ export type AgentErrorCode =
254
254
  | 'E_SCOPES_BOTH_PROVIDED'
255
255
  | 'E_SCOPES_NEITHER_PROVIDED'
256
256
  | 'E_SCOPES_UNREADABLE'
257
- | 'E_BAD_LOCK_ENVELOPE';
257
+ | 'E_BAD_LOCK_ENVELOPE'
258
+ // v1.2 federation principal (FEDERATION.md §3.3)
259
+ | 'E_BAD_FEDERATION_DESCRIPTOR'
260
+ | 'E_THRESHOLD_MISMATCH'
261
+ | 'E_THRESHOLD_NOT_MET'
262
+ | 'E_UNKNOWN_GUARDIAN'
263
+ | 'E_DUPLICATE_GUARDIAN';
258
264
 
259
265
  export interface VerifyOk<T> {
260
266
  ok: true;