@duct-sdk/sdk 0.4.5 → 0.5.2

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +36 -1
  3. package/TOKEN_SPEC.md +237 -0
  4. package/dist/adapters/react/page-context-guard.d.ts +7 -0
  5. package/dist/adapters/react/page-context-guard.js +26 -0
  6. package/dist/adapters/react/page-context-guard.test.d.ts +1 -0
  7. package/dist/adapters/react/page-context-guard.test.js +15 -0
  8. package/dist/adapters/react/shell.js +18 -26
  9. package/dist/adapters/react/use-page-context.d.ts +1 -1
  10. package/dist/adapters/react/use-page-context.js +6 -16
  11. package/dist/cli/agents/reviewer-agent.d.ts +3 -1
  12. package/dist/cli/agents/reviewer-agent.js +29 -21
  13. package/dist/cli/config-loader.d.ts +15 -0
  14. package/dist/cli/config-loader.js +187 -0
  15. package/dist/cli/config-loader.test.d.ts +1 -0
  16. package/dist/cli/config-loader.test.js +63 -0
  17. package/dist/cli/detectors/framework.d.ts +1 -1
  18. package/dist/cli/detectors/framework.js +40 -0
  19. package/dist/cli/generators/receiver.js +206 -76
  20. package/dist/cli/generators/shell.js +50 -4
  21. package/dist/cli/generators/shell.test.d.ts +1 -0
  22. package/dist/cli/generators/shell.test.js +73 -0
  23. package/dist/cli/generators/token-route.d.ts +1 -0
  24. package/dist/cli/generators/token-route.js +108 -5
  25. package/dist/cli/generators/wiring-snippets.js +59 -19
  26. package/dist/cli/generators/wiring-snippets.test.js +15 -1
  27. package/dist/cli/index.js +108 -151
  28. package/dist/cli/init.js +110 -17
  29. package/dist/cli/manifest-diff.d.ts +21 -0
  30. package/dist/cli/manifest-diff.js +158 -0
  31. package/dist/cli/manifest-diff.test.d.ts +1 -0
  32. package/dist/cli/manifest-diff.test.js +104 -0
  33. package/dist/cli/output-paths.d.ts +2 -0
  34. package/dist/cli/output-paths.js +22 -4
  35. package/dist/core/config-policy.test.d.ts +1 -0
  36. package/dist/core/config-policy.test.js +101 -0
  37. package/dist/core/config.d.ts +86 -1
  38. package/dist/core/config.js +120 -2
  39. package/dist/core/invariants.test.d.ts +1 -0
  40. package/dist/core/invariants.test.js +217 -0
  41. package/dist/core/jcs.d.ts +5 -0
  42. package/dist/core/jcs.js +21 -0
  43. package/dist/core/receipt.d.ts +70 -0
  44. package/dist/core/receipt.js +86 -0
  45. package/dist/core/receipt.test.d.ts +1 -0
  46. package/dist/core/receipt.test.js +75 -0
  47. package/dist/core/replay-store.d.ts +51 -0
  48. package/dist/core/replay-store.js +65 -0
  49. package/dist/core/token.d.ts +14 -0
  50. package/dist/core/token.js +50 -18
  51. package/dist/core/token.test.d.ts +1 -0
  52. package/dist/core/token.test.js +66 -0
  53. package/dist/core/types.d.ts +72 -0
  54. package/dist/index.d.ts +6 -4
  55. package/dist/index.js +4 -2
  56. package/dist/server.d.ts +6 -4
  57. package/dist/server.js +4 -2
  58. package/package.json +91 -90
@@ -51,6 +51,38 @@ const SensitivityLevelSchema = z.enum([
51
51
  "high",
52
52
  "critical",
53
53
  ]);
54
+ const ApprovalCompareOpSchema = z.enum(["gt", "gte", "lt", "lte", "eq", "neq"]);
55
+ const ApprovalLogicalOpSchema = z.enum(["and", "or"]);
56
+ const ApprovalPredicateSchema = z.lazy(() => z.union([
57
+ z.object({
58
+ op: ApprovalLogicalOpSchema,
59
+ rules: z.array(ApprovalPredicateSchema).min(1),
60
+ }),
61
+ z.object({
62
+ op: z.literal("in"),
63
+ param: z.string().min(1),
64
+ values: z.array(z.union([z.string(), z.number(), z.boolean()])).min(1),
65
+ }),
66
+ z.object({
67
+ op: ApprovalCompareOpSchema,
68
+ param: z.string().min(1),
69
+ value: z.union([z.string(), z.number(), z.boolean()]),
70
+ }),
71
+ ]));
72
+ const ActionLimitPolicySchema = z.discriminatedUnion("type", [
73
+ z.object({
74
+ type: z.literal("rate"),
75
+ maxPerWindow: z.number().int().positive(),
76
+ windowSeconds: z.number().int().positive(),
77
+ }),
78
+ z.object({
79
+ type: z.literal("count"),
80
+ maxCount: z.number().int().positive(),
81
+ }),
82
+ ]);
83
+ const iso8601Schema = z
84
+ .string()
85
+ .datetime({ offset: true, message: "Must be ISO 8601 with timezone offset" });
54
86
  const ActionParamSchema = z.object({
55
87
  name: z.string().min(1),
56
88
  type: z.enum(["string", "number", "boolean", "object", "array"]),
@@ -74,6 +106,10 @@ const ActionManifestSchema = z.object({
74
106
  responseSchema: z.record(z.unknown()).optional(),
75
107
  requiresAuth: z.boolean(),
76
108
  rateLimit: z.number().positive().optional(),
109
+ validFrom: iso8601Schema.optional(),
110
+ validUntil: iso8601Schema.optional(),
111
+ approveIf: ApprovalPredicateSchema.optional(),
112
+ actionLimit: ActionLimitPolicySchema.optional(),
77
113
  });
78
114
  const AuthStrategySchema = z.enum([
79
115
  "nextauth",
@@ -137,6 +173,9 @@ const AgentPermissionsSchema = z.object({
137
173
  allowedCallers: z.array(z.string()).optional(),
138
174
  requireUserConsent: z.boolean(),
139
175
  allowedActions: z.array(z.string()).optional(),
176
+ validFrom: iso8601Schema.optional(),
177
+ validUntil: iso8601Schema.optional(),
178
+ consentActionScope: z.array(z.string().min(1)).optional(),
140
179
  });
141
180
  const WidgetConfigSchema = z.object({
142
181
  primaryColor: z.string().optional(),
@@ -188,7 +227,25 @@ function zodIssuesToValidationIssues(errors) {
188
227
  : "Correct the field per the Duct config reference",
189
228
  }));
190
229
  }
191
- function crossValidateDuctConfig(data) {
230
+ function parseIsoInstant(value) {
231
+ const ms = Date.parse(value);
232
+ return Number.isNaN(ms) ? null : ms;
233
+ }
234
+ function collectApprovalParams(predicate, out) {
235
+ if (predicate.op === "and" || predicate.op === "or") {
236
+ for (const rule of predicate.rules)
237
+ collectApprovalParams(rule, out);
238
+ return;
239
+ }
240
+ if (predicate.op === "in") {
241
+ out.add(predicate.param);
242
+ return;
243
+ }
244
+ if ("param" in predicate) {
245
+ out.add(predicate.param);
246
+ }
247
+ }
248
+ export function crossValidateDuctConfig(data) {
192
249
  const issues = [];
193
250
  const routePaths = new Set(data.routes.map((r) => r.path));
194
251
  for (const deeplink of data.deeplinks) {
@@ -216,6 +273,67 @@ function crossValidateDuctConfig(data) {
216
273
  }
217
274
  }
218
275
  }
276
+ if (data.agentPermissions.validFrom && data.agentPermissions.validUntil) {
277
+ const from = parseIsoInstant(data.agentPermissions.validFrom);
278
+ const until = parseIsoInstant(data.agentPermissions.validUntil);
279
+ if (from !== null && until !== null && from >= until) {
280
+ issues.push({
281
+ severity: "error",
282
+ area: "agentPermissions",
283
+ issue: "validFrom must be before validUntil",
284
+ fix: "Set agentPermissions.validUntil later than validFrom",
285
+ });
286
+ }
287
+ }
288
+ if (data.agentPermissions.consentActionScope) {
289
+ for (const actionId of data.agentPermissions.consentActionScope) {
290
+ if (actionId === "*") {
291
+ issues.push({
292
+ severity: "error",
293
+ area: "agentPermissions.consentActionScope",
294
+ issue: 'Wildcard "*" is not allowed in consentActionScope',
295
+ fix: "List explicit action IDs instead of '*'",
296
+ });
297
+ }
298
+ else if (!actionIds.has(actionId)) {
299
+ issues.push({
300
+ severity: "error",
301
+ area: "agentPermissions.consentActionScope",
302
+ issue: `consentActionScope references unknown action ID "${actionId}"`,
303
+ fix: `Add action "${actionId}" to actions[] or remove it from consentActionScope`,
304
+ });
305
+ }
306
+ }
307
+ }
308
+ for (const action of data.actions) {
309
+ if (action.validFrom && action.validUntil) {
310
+ const from = parseIsoInstant(action.validFrom);
311
+ const until = parseIsoInstant(action.validUntil);
312
+ if (from !== null && until !== null && from >= until) {
313
+ issues.push({
314
+ severity: "error",
315
+ area: `actions.${action.id}`,
316
+ issue: `Action "${action.id}" validFrom must be before validUntil`,
317
+ fix: `Set actions.${action.id}.validUntil later than validFrom`,
318
+ });
319
+ }
320
+ }
321
+ if (action.approveIf) {
322
+ const paramNames = new Set(action.params.map((p) => p.name));
323
+ const referenced = new Set();
324
+ collectApprovalParams(action.approveIf, referenced);
325
+ for (const param of referenced) {
326
+ if (!paramNames.has(param)) {
327
+ issues.push({
328
+ severity: "error",
329
+ area: `actions.${action.id}.approveIf`,
330
+ issue: `approveIf references unknown param "${param}" on action "${action.id}"`,
331
+ fix: `Add param "${param}" to actions.${action.id}.params or fix the predicate`,
332
+ });
333
+ }
334
+ }
335
+ }
336
+ }
219
337
  return issues;
220
338
  }
221
339
  /**
@@ -238,7 +356,7 @@ export function validateDuctConfigStrict(config) {
238
356
  *
239
357
  * @example
240
358
  * ```ts
241
- * import { defineDuctConfig } from '@duct/sdk';
359
+ * import { defineDuctConfig } from '@duct-sdk/sdk';
242
360
  *
243
361
  * export default defineDuctConfig({
244
362
  * shellId: 'shell_acme_prod',
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,217 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createHmac } from "crypto";
4
+ import { SignJWT } from "jose";
5
+ import { generateShell } from "../cli/generators/shell.js";
6
+ import { canonicalizeJson } from "./jcs.js";
7
+ import { computeReceiptId, verifyReceipt, } from "./receipt.js";
8
+ import { generateDeeplinkToken, verifyDeeplinkToken, generateDuctToken, verifyDuctToken, createDevReplayStore, } from "./token.js";
9
+ const SECRET = "test-secret-key-at-least-32-chars-long";
10
+ const SHELL_ID = "shell_test_prod";
11
+ const HMAC_SECRET = "01234567890123456789012345678901";
12
+ function encodeSecret(secret) {
13
+ return new TextEncoder().encode(secret);
14
+ }
15
+ function unsignedJwt(payload) {
16
+ const header = Buffer.from(JSON.stringify({ alg: "none", typ: "JWT" })).toString("base64url");
17
+ const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
18
+ return `${header}.${body}.`;
19
+ }
20
+ function signTestReceipt(body) {
21
+ const receipt_id = computeReceiptId(body);
22
+ const canonical = canonicalizeJson(body);
23
+ const signature = createHmac("sha256", HMAC_SECRET).update(canonical).digest("hex");
24
+ return { ...body, receipt_id, signature, kid: "duct-gateway-hs256-v1" };
25
+ }
26
+ const minimalConfig = {
27
+ shellId: "shell_test",
28
+ product: {
29
+ name: "Test",
30
+ description: "Test product",
31
+ baseUrl: "https://app.example.com",
32
+ },
33
+ };
34
+ describe("P6-INV-4 token verifiers pin algorithms", () => {
35
+ it("verifyDuctToken rejects HS512 and alg:none tokens", async () => {
36
+ const hs512 = await new SignJWT({ type: "duct_delegated", session: {} })
37
+ .setProtectedHeader({ alg: "HS512" })
38
+ .setSubject("u_1")
39
+ .setIssuer(SHELL_ID)
40
+ .setIssuedAt()
41
+ .setExpirationTime("1h")
42
+ .sign(encodeSecret(SECRET));
43
+ const hs512Result = await verifyDuctToken(hs512, {
44
+ secretKey: SECRET,
45
+ expectedShellId: SHELL_ID,
46
+ });
47
+ assert.equal(hs512Result.valid, false);
48
+ const noneToken = unsignedJwt({
49
+ type: "duct_delegated",
50
+ sub: "u_1",
51
+ iss: SHELL_ID,
52
+ exp: Math.floor(Date.now() / 1000) + 3600,
53
+ });
54
+ const noneResult = await verifyDuctToken(noneToken, {
55
+ secretKey: SECRET,
56
+ expectedShellId: SHELL_ID,
57
+ });
58
+ assert.equal(noneResult.valid, false);
59
+ });
60
+ it("verifyDeeplinkToken rejects HS512 and alg:none tokens", async () => {
61
+ const hs512 = await new SignJWT({ deeplink_id: "view_order", state: {} })
62
+ .setProtectedHeader({ alg: "HS512" })
63
+ .setIssuer(SHELL_ID)
64
+ .setAudience(SHELL_ID)
65
+ .setJti(crypto.randomUUID())
66
+ .setIssuedAt()
67
+ .setExpirationTime("1h")
68
+ .sign(encodeSecret(SECRET));
69
+ const hs512Result = await verifyDeeplinkToken(hs512, {
70
+ secretKey: SECRET,
71
+ expectedShellId: SHELL_ID,
72
+ });
73
+ assert.equal(hs512Result.valid, false);
74
+ const noneToken = unsignedJwt({
75
+ deeplink_id: "view_order",
76
+ iss: SHELL_ID,
77
+ aud: SHELL_ID,
78
+ jti: crypto.randomUUID(),
79
+ exp: Math.floor(Date.now() / 1000) + 3600,
80
+ });
81
+ const noneResult = await verifyDeeplinkToken(noneToken, {
82
+ secretKey: SECRET,
83
+ expectedShellId: SHELL_ID,
84
+ });
85
+ assert.equal(noneResult.valid, false);
86
+ });
87
+ it("verifyReceipt rejects unknown kid / non-HS256 HMAC path", () => {
88
+ const body = {
89
+ claim_type: "duct:action:v1",
90
+ issued_at: "2026-07-01T00:00:00.000Z",
91
+ shell_id: "shell_test",
92
+ action_id: "search",
93
+ caller_type: "agent",
94
+ decision: "permit",
95
+ reason: "allowed",
96
+ permission_source: "manifest",
97
+ capture_mode: "gateway_observed",
98
+ scope_of_claim: { asserts: [], does_not_assert: [] },
99
+ };
100
+ const signed = signTestReceipt(body);
101
+ const wrongKid = {
102
+ ...signed,
103
+ kid: "attacker-hs512-v1",
104
+ signature: "00".repeat(32),
105
+ };
106
+ const result = verifyReceipt(wrongKid, { hmacSecret: HMAC_SECRET });
107
+ assert.equal(result.valid, false);
108
+ if (!result.valid)
109
+ assert.equal(result.reason, "INVALID_SIGNATURE");
110
+ });
111
+ });
112
+ describe("P6-INV-4 deeplink replay rejects reused jti", () => {
113
+ it("mint → verify ok → replay rejected; jti is non-empty", async () => {
114
+ const replayStore = createDevReplayStore();
115
+ const { token } = await generateDeeplinkToken({
116
+ secretKey: SECRET,
117
+ shellId: SHELL_ID,
118
+ deeplinkId: "view_order",
119
+ state: { orderId: "42" },
120
+ });
121
+ const first = await verifyDeeplinkToken(token, {
122
+ secretKey: SECRET,
123
+ expectedShellId: SHELL_ID,
124
+ replayStore,
125
+ });
126
+ assert.equal(first.valid, true);
127
+ assert.ok(first.payload);
128
+ assert.notEqual(first.payload.jti, "");
129
+ const second = await verifyDeeplinkToken(token, {
130
+ secretKey: SECRET,
131
+ expectedShellId: SHELL_ID,
132
+ replayStore,
133
+ });
134
+ assert.equal(second.valid, false);
135
+ assert.equal(second.error, "Token already used");
136
+ });
137
+ });
138
+ describe("P6-INV-4 generateDuctToken session allowlist", () => {
139
+ it("copies only auth.sessionFields scalars into delegated JWT", async () => {
140
+ const { token } = await generateDuctToken({
141
+ secretKey: SECRET,
142
+ shellId: SHELL_ID,
143
+ userSession: {
144
+ userId: "u_123",
145
+ jwt: "eyJhbGciOiJIUzI1NiJ9.secret",
146
+ ssn: "123-45-6789",
147
+ email: "user@example.com",
148
+ },
149
+ sessionFields: ["userId"],
150
+ });
151
+ const verified = await verifyDuctToken(token, {
152
+ secretKey: SECRET,
153
+ expectedShellId: SHELL_ID,
154
+ });
155
+ assert.equal(verified.valid, true);
156
+ assert.deepEqual(verified.payload?.session, { userId: "u_123" });
157
+ });
158
+ });
159
+ describe("P6-INV-4 generated embeds contain origin checks", () => {
160
+ const frameworks = [
161
+ {
162
+ name: "react (next-app)",
163
+ framework: {
164
+ name: "next-app",
165
+ version: "14.0.0",
166
+ hasAppRouter: true,
167
+ hasPagesRouter: false,
168
+ packageManager: "npm",
169
+ srcDir: "src",
170
+ },
171
+ // React embed delegates postMessage origin checks to DuctShell; shellHost must be wired.
172
+ pattern: /shellHost/,
173
+ },
174
+ {
175
+ name: "vue3",
176
+ framework: {
177
+ name: "vue3",
178
+ version: "3.4.0",
179
+ hasAppRouter: false,
180
+ hasPagesRouter: false,
181
+ packageManager: "npm",
182
+ srcDir: "src",
183
+ },
184
+ pattern: /event\.origin !== shellOrigin/,
185
+ },
186
+ {
187
+ name: "nuxt",
188
+ framework: {
189
+ name: "nuxt",
190
+ version: "3.0.0",
191
+ hasAppRouter: false,
192
+ hasPagesRouter: false,
193
+ packageManager: "npm",
194
+ srcDir: "src",
195
+ },
196
+ pattern: /event\.origin !== shellOrigin/,
197
+ },
198
+ {
199
+ name: "sveltekit",
200
+ framework: {
201
+ name: "sveltekit",
202
+ version: "2.0.0",
203
+ hasAppRouter: false,
204
+ hasPagesRouter: false,
205
+ packageManager: "npm",
206
+ srcDir: "src",
207
+ },
208
+ pattern: /event\.origin !== shellHost/,
209
+ },
210
+ ];
211
+ for (const { name, framework, pattern } of frameworks) {
212
+ it(`${name} generator output includes origin guard`, () => {
213
+ const code = generateShell(minimalConfig, framework);
214
+ assert.match(code, pattern);
215
+ });
216
+ }
217
+ });
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Simplified canonical JSON — sorted keys at every object level.
3
+ * Interim shortcut before full RFC 8785 JCS. Matches the Duct gateway canonical JSON implementation.
4
+ */
5
+ export declare function canonicalizeJson(value: unknown): string;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Simplified canonical JSON — sorted keys at every object level.
3
+ * Interim shortcut before full RFC 8785 JCS. Matches the Duct gateway canonical JSON implementation.
4
+ */
5
+ export function canonicalizeJson(value) {
6
+ return JSON.stringify(sortValue(value));
7
+ }
8
+ function sortValue(value) {
9
+ if (value === null || typeof value !== "object") {
10
+ return value;
11
+ }
12
+ if (Array.isArray(value)) {
13
+ return value.map(sortValue);
14
+ }
15
+ const obj = value;
16
+ const sorted = {};
17
+ for (const key of Object.keys(obj).sort()) {
18
+ sorted[key] = sortValue(obj[key]);
19
+ }
20
+ return sorted;
21
+ }
@@ -0,0 +1,70 @@
1
+ export type ReceiptClaimType = "duct:action:v1" | "duct:authority:v1" | "duct:intent:v1";
2
+ export type ReceiptDecision = "permit" | "deny" | "ask";
3
+ export type ReceiptCaptureMode = "gateway_observed" | "self_attested";
4
+ export type ReceiptRejectionReason = "WRONG_CLAIM" | "INVALID_SIGNATURE" | "RECEIPT_ID_MISMATCH" | "SIGNING_KEY_UNAVAILABLE";
5
+ export interface ScopeOfClaim {
6
+ asserts: string[];
7
+ does_not_assert: string[];
8
+ }
9
+ export interface DuctReceiptBody {
10
+ claim_type: ReceiptClaimType;
11
+ issued_at: string;
12
+ shell_id: string;
13
+ action_id: string;
14
+ caller_type: string;
15
+ decision: ReceiptDecision;
16
+ reason: string;
17
+ permission_source: string;
18
+ manifest_version?: number;
19
+ manifest_hash?: string;
20
+ params_hash?: string;
21
+ definition_hash?: string;
22
+ delegation_ref?: string;
23
+ capture_mode: ReceiptCaptureMode;
24
+ scope_of_claim: ScopeOfClaim;
25
+ intent_ref?: string;
26
+ }
27
+ export interface SignedDuctReceipt extends DuctReceiptBody {
28
+ receipt_id: string;
29
+ signature: string;
30
+ kid: string;
31
+ }
32
+ export declare function computeReceiptId(body: DuctReceiptBody): string;
33
+ /** JWKS-style public keys for Ed25519 receipt verification (`GET /v1/keys/receipts`). */
34
+ export interface ReceiptJwks {
35
+ keys: Array<{
36
+ kid: string;
37
+ kty: "OKP";
38
+ crv: "Ed25519";
39
+ x: string;
40
+ use?: "sig";
41
+ alg?: "EdDSA";
42
+ }>;
43
+ }
44
+ export interface VerifyReceiptOptions {
45
+ /**
46
+ * HMAC secret for receipts signed with kid `duct-gateway-hs256-v1`.
47
+ * Dev/migration path only — production verifiers should use Ed25519 + JWKS.
48
+ */
49
+ hmacSecret?: string;
50
+ /** Ed25519 public keys keyed by `kid` (SPKI DER base64). */
51
+ publicKeys?: Record<string, string>;
52
+ /** JWKS document from `GET /v1/keys/receipts`. Merged with `publicKeys`. */
53
+ jwks?: ReceiptJwks;
54
+ /** When set, reject receipts whose `claim_type` does not match. */
55
+ expectedClaimType?: ReceiptClaimType;
56
+ }
57
+ export type VerifyReceiptResult = {
58
+ valid: true;
59
+ receipt: SignedDuctReceipt;
60
+ } | {
61
+ valid: false;
62
+ layer_failed: "crypto" | "context";
63
+ reason: ReceiptRejectionReason;
64
+ };
65
+ /**
66
+ * Cryptographic + structural verification of a signed Duct outcome receipt.
67
+ * Context checks (replay, delegation status, manifest freshness) require gateway state
68
+ * and are performed by `POST /v1/receipts/verify` — not in this pure helper.
69
+ */
70
+ export declare function verifyReceipt(receipt: SignedDuctReceipt, options?: VerifyReceiptOptions): VerifyReceiptResult;
@@ -0,0 +1,86 @@
1
+ // ============================================================
2
+ // @duct-sdk/sdk — Outcome receipt verification (crypto layer)
3
+ // Mirrors the Duct gateway receipt verifier — no service imports.
4
+ // ============================================================
5
+ import { createHash, createHmac, createPublicKey, timingSafeEqual, verify as edVerify, } from "crypto";
6
+ import { canonicalizeJson } from "./jcs.js";
7
+ const HMAC_KID = "duct-gateway-hs256-v1";
8
+ export function computeReceiptId(body) {
9
+ const canonical = canonicalizeJson(body);
10
+ return createHash("sha256").update(canonical).digest("hex").slice(0, 32);
11
+ }
12
+ function timingSafeEqualString(a, b) {
13
+ const bufA = Buffer.from(a);
14
+ const bufB = Buffer.from(b);
15
+ if (bufA.length !== bufB.length)
16
+ return false;
17
+ try {
18
+ return timingSafeEqual(bufA, bufB);
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
24
+ function resolveEd25519PublicKey(kid, options) {
25
+ const derB64 = options.publicKeys?.[kid];
26
+ if (derB64) {
27
+ try {
28
+ return createPublicKey({ key: Buffer.from(derB64, "base64"), format: "der", type: "spki" });
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }
34
+ const jwk = options.jwks?.keys.find((k) => k.kid === kid && k.kty === "OKP" && k.crv === "Ed25519");
35
+ if (!jwk)
36
+ return null;
37
+ try {
38
+ return createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: jwk.x }, format: "jwk" });
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ }
44
+ function verifyEd25519Signature(canonical, signatureB64, kid, options) {
45
+ const publicKey = resolveEd25519PublicKey(kid, options);
46
+ if (!publicKey)
47
+ return false;
48
+ try {
49
+ const signature = Buffer.from(signatureB64, "base64");
50
+ return edVerify(null, Buffer.from(canonical, "utf-8"), publicKey, signature);
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }
56
+ /**
57
+ * Cryptographic + structural verification of a signed Duct outcome receipt.
58
+ * Context checks (replay, delegation status, manifest freshness) require gateway state
59
+ * and are performed by `POST /v1/receipts/verify` — not in this pure helper.
60
+ */
61
+ export function verifyReceipt(receipt, options = {}) {
62
+ if (options.expectedClaimType && receipt.claim_type !== options.expectedClaimType) {
63
+ return { valid: false, layer_failed: "context", reason: "WRONG_CLAIM" };
64
+ }
65
+ const { receipt_id, signature, kid, ...body } = receipt;
66
+ const expectedId = computeReceiptId(body);
67
+ if (receipt_id !== expectedId) {
68
+ return { valid: false, layer_failed: "crypto", reason: "RECEIPT_ID_MISMATCH" };
69
+ }
70
+ const canonical = canonicalizeJson(body);
71
+ if (kid !== HMAC_KID) {
72
+ const ok = verifyEd25519Signature(canonical, signature, kid, options);
73
+ if (!ok)
74
+ return { valid: false, layer_failed: "crypto", reason: "INVALID_SIGNATURE" };
75
+ return { valid: true, receipt };
76
+ }
77
+ const key = options.hmacSecret?.trim();
78
+ if (!key || key.length < 32) {
79
+ return { valid: false, layer_failed: "crypto", reason: "SIGNING_KEY_UNAVAILABLE" };
80
+ }
81
+ const expectedSig = createHmac("sha256", key).update(canonical).digest("hex");
82
+ if (!timingSafeEqualString(signature, expectedSig)) {
83
+ return { valid: false, layer_failed: "crypto", reason: "INVALID_SIGNATURE" };
84
+ }
85
+ return { valid: true, receipt };
86
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,75 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createHmac } from "crypto";
4
+ import { canonicalizeJson } from "./jcs.js";
5
+ import { computeReceiptId, verifyReceipt, } from "./receipt.js";
6
+ const HMAC_SECRET = "01234567890123456789012345678901";
7
+ function signTestReceipt(body) {
8
+ const receipt_id = computeReceiptId(body);
9
+ const canonical = canonicalizeJson(body);
10
+ const signature = createHmac("sha256", HMAC_SECRET).update(canonical).digest("hex");
11
+ return { ...body, receipt_id, signature, kid: "duct-gateway-hs256-v1" };
12
+ }
13
+ describe("verifyReceipt", () => {
14
+ it("verifies HMAC-signed action receipts", () => {
15
+ const body = {
16
+ claim_type: "duct:action:v1",
17
+ issued_at: "2026-07-01T00:00:00.000Z",
18
+ shell_id: "shell_test",
19
+ action_id: "search",
20
+ caller_type: "agent",
21
+ decision: "permit",
22
+ reason: "allowed",
23
+ permission_source: "manifest",
24
+ capture_mode: "gateway_observed",
25
+ scope_of_claim: {
26
+ asserts: ["gate admitted action"],
27
+ does_not_assert: ["upstream completed"],
28
+ },
29
+ };
30
+ const signed = signTestReceipt(body);
31
+ const result = verifyReceipt(signed, { hmacSecret: HMAC_SECRET });
32
+ assert.equal(result.valid, true);
33
+ });
34
+ it("rejects tampered receipt_id", () => {
35
+ const body = {
36
+ claim_type: "duct:action:v1",
37
+ issued_at: "2026-07-01T00:00:00.000Z",
38
+ shell_id: "shell_test",
39
+ action_id: "search",
40
+ caller_type: "agent",
41
+ decision: "permit",
42
+ reason: "allowed",
43
+ permission_source: "manifest",
44
+ capture_mode: "gateway_observed",
45
+ scope_of_claim: { asserts: [], does_not_assert: [] },
46
+ };
47
+ const signed = signTestReceipt(body);
48
+ const tampered = { ...signed, receipt_id: "deadbeef".repeat(4) };
49
+ const result = verifyReceipt(tampered, { hmacSecret: HMAC_SECRET });
50
+ assert.equal(result.valid, false);
51
+ if (!result.valid)
52
+ assert.equal(result.reason, "RECEIPT_ID_MISMATCH");
53
+ });
54
+ it("rejects wrong claim type when expectedClaimType set", () => {
55
+ const signed = signTestReceipt({
56
+ claim_type: "duct:action:v1",
57
+ issued_at: "2026-07-01T00:00:00.000Z",
58
+ shell_id: "shell_test",
59
+ action_id: "search",
60
+ caller_type: "agent",
61
+ decision: "permit",
62
+ reason: "allowed",
63
+ permission_source: "manifest",
64
+ capture_mode: "gateway_observed",
65
+ scope_of_claim: { asserts: [], does_not_assert: [] },
66
+ });
67
+ const result = verifyReceipt(signed, {
68
+ hmacSecret: HMAC_SECRET,
69
+ expectedClaimType: "duct:intent:v1",
70
+ });
71
+ assert.equal(result.valid, false);
72
+ if (!result.valid)
73
+ assert.equal(result.reason, "WRONG_CLAIM");
74
+ });
75
+ });