-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathissue.ts
More file actions
595 lines (520 loc) · 18.7 KB
/
Copy pathissue.ts
File metadata and controls
595 lines (520 loc) · 18.7 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
/**
* Receipt issuance
* Validates input, generates UUIDv7 rid, and signs with Ed25519
*/
import { uuidv7 } from 'uuidv7';
import { sign } from '@peac/crypto';
import { defaultCodec } from './_internal/record-core/codec/jws-jwt.js';
import { runBoundedValidatorShadow } from './_internal/record-core/bounded-validator.js';
import { runBoundedValidationGate } from './_internal/record-core/validation-gate.js';
import { isShadowEnabled, scheduleShadow, type ShadowEnableOptions } from './_internal/shadow.js';
import { readLegacyPathFlag, type LegacyPathOptions } from './_internal/legacy-path.js';
import {
realObservationForIssue,
shadowObservationFromBoundedAcceptedOnly,
type ShadowObservation,
} from './_internal/shadow-observe.js';
import type { JsonValue, EvidencePillar, PolicyBlock } from '@peac/kernel';
import { ZodError } from 'zod';
import {
PEACReceiptClaims,
ReceiptClaims,
SubjectProfileSnapshot,
validateSubjectSnapshot,
createEvidenceNotJsonError,
createConstraintViolationError,
createWorkflowContextInvalidError,
createWorkflowDagInvalidError,
validateKernelConstraints,
type PEACError,
type PurposeToken,
type CanonicalPurpose,
type PurposeReason,
isValidPurposeToken,
isCanonicalPurpose,
isValidPurposeReason,
// Workflow correlation (v0.10.2+)
type WorkflowContext,
isValidWorkflowContext,
hasValidDagSemantics,
WORKFLOW_EXTENSION_KEY,
// Wire 0.2 (v0.12.0-preview.1)
isCanonicalIss,
Wire02ClaimsSchema,
type Wire02Claims,
} from '@peac/schema';
import { hashReceipt, fireTelemetryHook, type TelemetryHook } from './telemetry.js';
/**
* Wire 0.1 record options (frozen legacy).
*
* @deprecated Use {@link IssueWire02Options} (or the {@link IssueOptions} alias)
* for current stable issuance.
*/
export interface IssueWire01Options {
/** Issuer URL (https://) */
iss: string;
/** Audience / resource URL (https://) */
aud: string;
/** Amount in smallest currency unit */
amt: number;
/** ISO 4217 currency code (uppercase) */
cur: string;
/** Payment rail identifier */
rail: string;
/** Rail-specific payment reference */
reference: string;
/** Asset transferred (e.g., "USD", "USDC", "BTC") - defaults to currency if not provided */
asset?: string;
/** Environment ("live" or "test") - defaults to "test" */
env?: 'live' | 'test';
/** Network/rail identifier (optional, SHOULD for crypto) */
network?: string;
/** Facilitator reference (optional) */
facilitator_ref?: string;
/** Rail-specific evidence (JSON-safe) - defaults to empty object if not provided */
evidence?: JsonValue;
/** Idempotency key (optional) */
idempotency_key?: string;
/** Rail-specific metadata (optional) */
metadata?: Record<string, unknown>;
/** Subject URI (optional) */
subject?: string;
/** Extensions (optional) */
ext?: PEACReceiptClaims['ext'];
/** Expiry timestamp (Unix seconds, optional) */
exp?: number;
/** Subject profile snapshot for envelope (v0.9.17+, optional) */
subject_snapshot?: SubjectProfileSnapshot;
/**
* Purposes declared by the requesting agent (v0.9.24+, optional)
*
* From PEAC-Purpose request header. Accepts single token or array.
* Unknown tokens are preserved for forward compatibility.
*/
purpose?: PurposeToken | PurposeToken[];
/**
* Single purpose enforced by policy (v0.9.24+, optional)
*
* MUST be one of declared purposes OR a more restrictive downgrade.
* Only canonical purposes have enforcement semantics.
*/
purpose_enforced?: CanonicalPurpose;
/**
* Reason for enforcement decision (v0.9.24+, optional)
*
* The audit spine - explains WHY purpose was enforced as it was.
*/
purpose_reason?: PurposeReason;
/**
* Workflow correlation context (v0.10.2+, optional)
*
* Links this receipt into a multi-step workflow DAG.
* Added to ext['org.peacprotocol/workflow'].
*/
workflow_context?: WorkflowContext;
/** Ed25519 private key (32 bytes) */
privateKey: Uint8Array;
/** Key ID (ISO 8601 timestamp) */
kid: string;
/** Telemetry hook (optional, fire-and-forget) */
telemetry?: TelemetryHook;
}
/**
* Result of issuing a receipt
*/
export interface IssueResult {
/** JWS compact serialization */
jws: string;
/** Validated subject snapshot (if provided) */
subject_snapshot?: SubjectProfileSnapshot;
}
/**
* Error thrown during receipt issuance
*
* Wraps a structured PEACError for programmatic handling.
*/
export class IssueError extends Error {
/** Structured error details */
readonly peacError: PEACError;
constructor(peacError: PEACError) {
const details = peacError.details as { message?: string } | undefined;
super(details?.message ?? peacError.code);
this.name = 'IssueError';
this.peacError = peacError;
}
}
/**
* Issues a legacy Wire 0.1 receipt.
*
* @deprecated Use {@link issue} for current stable issuance. Wire 0.1
* issuance is retained for backward compatibility but discouraged for new
* applications.
*
* @param options - Wire 0.1 record options
* @returns Issue result with JWS and optional subject_snapshot
* @throws IssueError if evidence contains non-JSON-safe values
*/
export async function issueWire01(options: IssueWire01Options): Promise<IssueResult> {
// Validate URLs
if (!options.iss.startsWith('https://')) {
throw new Error('Issuer URL must start with https://');
}
if (!options.aud.startsWith('https://')) {
throw new Error('Audience URL must start with https://');
}
if (options.subject && !options.subject.startsWith('https://')) {
throw new Error('Subject URI must start with https://');
}
// Validate currency code
if (!/^[A-Z]{3}$/.test(options.cur)) {
throw new Error('Currency must be ISO 4217 uppercase (e.g., USD)');
}
// Validate amount
if (!Number.isInteger(options.amt) || options.amt < 0) {
throw new Error('Amount must be a non-negative integer');
}
// Validate expiry (if provided)
if (options.exp !== undefined) {
if (!Number.isInteger(options.exp) || options.exp < 0) {
throw new Error('Expiry must be a non-negative integer');
}
}
// Normalize and validate purpose (v0.9.24+)
let purposeDeclared: PurposeToken[] | undefined;
if (options.purpose !== undefined) {
// Normalize to array
const rawPurposes = Array.isArray(options.purpose) ? options.purpose : [options.purpose];
// Validate each token
const invalidTokens: string[] = [];
for (const token of rawPurposes) {
if (!isValidPurposeToken(token)) {
invalidTokens.push(token);
}
}
if (invalidTokens.length > 0) {
throw new Error(`Invalid purpose tokens: ${invalidTokens.join(', ')}`);
}
// Check for explicit 'undeclared' which is invalid on wire
if (rawPurposes.includes('undeclared')) {
throw new Error("Explicit 'undeclared' is not a valid purpose token (internal-only)");
}
purposeDeclared = rawPurposes;
}
// Validate purpose_enforced (must be canonical)
if (options.purpose_enforced !== undefined) {
if (!isCanonicalPurpose(options.purpose_enforced)) {
throw new Error(
`purpose_enforced must be a canonical purpose, got: ${options.purpose_enforced}`
);
}
}
// Validate purpose_reason
if (options.purpose_reason !== undefined) {
if (!isValidPurposeReason(options.purpose_reason)) {
throw new Error(`Invalid purpose_reason: ${options.purpose_reason}`);
}
}
// Validate workflow_context (v0.10.2+)
if (options.workflow_context !== undefined) {
if (!isValidWorkflowContext(options.workflow_context)) {
throw new IssueError(
createWorkflowContextInvalidError('Does not conform to WorkflowContextSchema')
);
}
if (!hasValidDagSemantics(options.workflow_context)) {
// Determine specific reason
const ctx = options.workflow_context;
const isSelfParent = ctx.parent_step_ids.includes(ctx.step_id);
const hasDuplicates = new Set(ctx.parent_step_ids).size !== ctx.parent_step_ids.length;
const reason = isSelfParent ? 'self_parent' : hasDuplicates ? 'duplicate_parent' : 'cycle';
throw new IssueError(createWorkflowDagInvalidError(reason));
}
}
// Generate UUIDv7 for receipt ID
const rid = uuidv7();
// Get current timestamp
const iat = Math.floor(Date.now() / 1000);
// Build receipt claims
const claims: PEACReceiptClaims = {
iss: options.iss,
aud: options.aud,
iat,
rid,
amt: options.amt,
cur: options.cur,
payment: {
rail: options.rail,
reference: options.reference,
amount: options.amt,
currency: options.cur,
asset: options.asset ?? options.cur, // Default asset to currency for backward compatibility
env: options.env ?? 'test', // Default to test environment for backward compatibility
evidence: options.evidence ?? {}, // Default to empty object for backward compatibility
...(options.network && { network: options.network }),
...(options.facilitator_ref && { facilitator_ref: options.facilitator_ref }),
...(options.idempotency_key && { idempotency_key: options.idempotency_key }),
...(options.metadata && { metadata: options.metadata }),
},
...(options.exp && { exp: options.exp }),
...(options.subject && { subject: { uri: options.subject } }),
// Build extensions (merge user-provided ext with workflow_context)
...((options.ext || options.workflow_context) && {
ext: {
...options.ext,
...(options.workflow_context && {
[WORKFLOW_EXTENSION_KEY]: options.workflow_context,
}),
},
}),
// Purpose claims (v0.9.24+)
...(purposeDeclared && { purpose_declared: purposeDeclared }),
...(options.purpose_enforced && { purpose_enforced: options.purpose_enforced }),
...(options.purpose_reason && { purpose_reason: options.purpose_reason }),
};
// Validate structural kernel constraints before signing (fail-closed)
const constraintResult = validateKernelConstraints(claims);
if (!constraintResult.valid) {
throw new IssueError(createConstraintViolationError(constraintResult.violations));
}
// Validate claims with Zod - map evidence errors to typed error
try {
ReceiptClaims.parse(claims);
} catch (err: unknown) {
if (err instanceof ZodError) {
// Check if any error path touches evidence
const evidenceIssue = err.issues.find((issue) =>
issue.path.some((p) => p === 'evidence' || p === 'payment')
);
if (evidenceIssue && evidenceIssue.path.includes('evidence')) {
const peacError = createEvidenceNotJsonError(
evidenceIssue.message,
evidenceIssue.path as (string | number)[]
);
throw new IssueError(peacError);
}
}
throw err;
}
// Validate subject_snapshot if provided (v0.9.17+)
// This validates schema and logs advisory PII warning if applicable
const validatedSnapshot = validateSubjectSnapshot(options.subject_snapshot);
// Track start time for telemetry
const startTime = performance.now();
// Sign with Ed25519
const jws = await sign(claims, options.privateKey, options.kid);
// Emit telemetry (fire-and-forget, guarded)
fireTelemetryHook(options.telemetry?.onReceiptIssued, {
receiptHash: hashReceipt(jws),
issuer: options.iss,
kid: options.kid,
durationMs: performance.now() - startTime,
});
return {
jws,
...(validatedSnapshot && { subject_snapshot: validatedSnapshot }),
};
}
/**
* Issue a Wire 0.1 PEAC record and return just the JWS string
*
* @deprecated Wire 0.1 issuance is frozen legacy. Use {@link issue} for the current stable format.
*
* @param options - Wire 0.1 record options
* @returns JWS compact serialization
*/
export async function issueJws(options: IssueWire01Options): Promise<string> {
const result = await issueWire01(options);
return result.jws;
}
/**
* Issue a PEAC record in the current stable public format.
*
* This is the canonical public issuance API. It issues Wire 0.2 records
* (`typ: interaction-record+jwt`). For an explicit wire-pinned API, use
* {@link issueWire02} directly.
*
* @param options - Record options (same as {@link IssueWire02Options})
* @returns Issue result with JWS
* @throws IssueError if iss is not canonical or schema validation fails
*/
export async function issue(options: IssueWire02Options): Promise<IssueResult> {
return issueWire02(options);
}
// ---------------------------------------------------------------------------
// Wire 0.2 issuance (v0.12.0-preview.1)
// ---------------------------------------------------------------------------
/**
* Options for issuing a Wire 0.2 record
*/
export interface IssueWire02Options {
/**
* Canonical issuer.
* Accepted: https:// ASCII origin or did: identifier.
* Non-canonical values produce an IssueError.
*/
iss: string;
/** Structural kind: 'evidence' or 'challenge' */
kind: 'evidence' | 'challenge';
/**
* Open semantic type.
* Accepted: reverse-DNS notation (e.g., 'org.example/flow') or absolute URI.
*/
type: string;
/** Ed25519 private key (32 bytes) */
privateKey: Uint8Array;
/** Key ID (max 256 chars per JOSE hardening rules) */
kid: string;
/**
* Unique receipt identifier.
* Generated via uuidv7 if not provided.
*/
jti?: string;
/** Subject identifier (max 2048 chars, optional) */
sub?: string;
/**
* Evidence pillars (sorted ascending, closed 10-value taxonomy).
* Validated against Wire02ClaimsSchema before signing.
*/
pillars?: EvidencePillar[];
/**
* ISO 8601 / RFC 3339 timestamp when the interaction occurred.
* Evidence kind only; rejected on challenge kind with E_OCCURRED_AT_ON_CHALLENGE.
*/
occurred_at?: string;
/** Declared purpose string (max 256 chars, optional) */
purpose_declared?: string;
/**
* Policy binding block.
* digest must be 'sha256:<64 lowercase hex>' format (use computePolicyDigestJcs from @peac/protocol).
*/
policy?: PolicyBlock;
/** Extension groups (open; caller-provided, not validated here) */
extensions?: Record<string, unknown>;
}
/**
* Canonical issuance options type.
*
* Alias for {@link IssueWire02Options}: the current stable receipt format.
*/
export type IssueOptions = IssueWire02Options;
/**
* Issue a Wire 0.2 record (explicit wire-pinned API).
*
* Most callers should use {@link issue} instead, which delegates here.
* Use `issueWire02` directly for conformance tests, benchmarks, and
* callers that need explicit wire version pinning.
*
* Validates the iss canonical form and Wire02ClaimsSchema before signing.
* Always sets typ to 'interaction-record+jwt' (WIRE_02_JWS_TYP).
*
* @param options - Wire 0.2 record options
* @returns Issue result with JWS
* @throws IssueError if iss is not canonical or schema validation fails
*/
export async function issueWire02(options: IssueWire02Options): Promise<IssueResult> {
// Internal rollback-path flag. Selects the bounded-validation
// admission gate (default) or the inline canonical schema check
// (rollback). Both branches share the canonical materializer that
// builds the IssueResult and the JWS bytes.
const legacyPath = readLegacyPathFlag(options as unknown as LegacyPathOptions);
// Validate canonical iss before signing
if (!isCanonicalIss(options.iss)) {
throw new IssueError({
code: 'E_ISS_NOT_CANONICAL',
category: 'validation',
severity: 'error',
retryable: false,
http_status: 400,
details: {
message: `iss is not in canonical form: "${options.iss}". Use an https://<origin> or did:<method> identifier.`,
},
} as PEACError);
}
// Generate jti if not provided
const jti = options.jti ?? uuidv7();
// Get current timestamp
const iat = Math.floor(Date.now() / 1000);
// Build Wire 0.2 claims
const claims: Wire02Claims = {
peac_version: '0.2',
kind: options.kind,
type: options.type,
iss: options.iss,
iat,
jti,
...(options.sub !== undefined && { sub: options.sub }),
...(options.pillars !== undefined && { pillars: options.pillars }),
...(options.occurred_at !== undefined && { occurred_at: options.occurred_at }),
...(options.purpose_declared !== undefined && { purpose_declared: options.purpose_declared }),
...(options.policy !== undefined && { policy: options.policy }),
...(options.extensions !== undefined && { extensions: options.extensions }),
};
// Validate schema before signing (fail-closed). The default branch
// routes through the bounded validation gate; the rollback branch
// retains the inline canonical schema check. Both branches produce
// byte-identical JWS bytes for every input both branches accept.
if (legacyPath) {
const parseResult = Wire02ClaimsSchema.safeParse(claims);
if (!parseResult.success) {
const firstIssue = parseResult.error.issues[0];
throw new IssueError({
code: 'E_INVALID_FORMAT',
category: 'validation',
severity: 'error',
retryable: false,
http_status: 400,
details: {
message: `Wire 0.2 claims schema validation failed: ${firstIssue?.message ?? 'unknown'}`,
},
} as PEACError);
}
} else {
const gateResult = runBoundedValidationGate({
surface: 'issueWire02',
payload: claims as unknown,
});
if (!gateResult.ok) {
throw new IssueError({
code: gateResult.code,
category: 'validation',
severity: 'error',
retryable: false,
http_status: 400,
details: { message: gateResult.message },
} as PEACError);
}
}
// Sign with Wire 0.2 via the internal codec boundary (always sets
// typ: 'interaction-record+jwt'). Default codec is a pure pass-through
// to @peac/crypto.signWire02; serialized output is byte-identical to
// the prior release.
const jws = await defaultCodec.encode(claims, options.privateKey, options.kid);
// Shadow scheduling fires only on the rollback branch where the
// bounded validator is genuinely a comparison path; under the
// default branch the bounded validator runs as the production
// admission gate, so a duplicate shadow run would compare the same
// code path against itself.
if (legacyPath && isShadowEnabled(options as unknown as ShadowEnableOptions)) {
scheduleShadow<ShadowObservation>({
call: 'issue',
realResult: realObservationForIssue(),
realError: undefined,
shadowFn: async () =>
shadowObservationFromBoundedAcceptedOnly(
runBoundedValidatorShadow({
claims: {
kind: claims.kind,
type: claims.type,
iss: claims.iss,
iat: claims.iat,
occurred_at: claims.occurred_at,
extensions: claims.extensions,
},
now: iat,
})
),
recordRef: jws,
});
}
return { jws };
}