@duct-sdk/sdk 0.5.4 → 0.5.10

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 (41) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +10 -10
  3. package/dist/adapters/react/shell.d.ts +2 -2
  4. package/dist/adapters/react/shell.js +1 -2
  5. package/dist/cli/generators/config.test.js +3 -0
  6. package/dist/cli/index.js +216 -36
  7. package/dist/cli/prompts/review.js +14 -0
  8. package/dist/core/config-roundtrip.test.d.ts +1 -0
  9. package/dist/core/config-roundtrip.test.js +180 -0
  10. package/dist/core/config.d.ts +281 -25
  11. package/dist/core/config.js +51 -67
  12. package/dist/core/endpoint-guard.d.ts +27 -0
  13. package/dist/core/endpoint-guard.js +71 -0
  14. package/dist/core/endpoint-guard.test.d.ts +1 -0
  15. package/dist/core/endpoint-guard.test.js +57 -0
  16. package/dist/core/env-diagnostics.d.ts +13 -0
  17. package/dist/core/env-diagnostics.js +63 -0
  18. package/dist/core/env-diagnostics.test.d.ts +1 -0
  19. package/dist/core/env-diagnostics.test.js +31 -0
  20. package/dist/core/evidence-bundle.conformance.test.d.ts +1 -0
  21. package/dist/core/evidence-bundle.conformance.test.js +110 -0
  22. package/dist/core/evidence-bundle.d.ts +59 -0
  23. package/dist/core/evidence-bundle.js +68 -0
  24. package/dist/core/evidence-bundle.test.d.ts +1 -0
  25. package/dist/core/evidence-bundle.test.js +58 -0
  26. package/dist/core/profile.d.ts +44 -0
  27. package/dist/core/profile.js +128 -0
  28. package/dist/core/profile.test.d.ts +1 -0
  29. package/dist/core/profile.test.js +95 -0
  30. package/dist/core/readiness-checks.d.ts +131 -0
  31. package/dist/core/readiness-checks.js +162 -0
  32. package/dist/core/readiness-checks.test.d.ts +1 -0
  33. package/dist/core/readiness-checks.test.js +106 -0
  34. package/dist/core/receipt.d.ts +5 -1
  35. package/dist/core/types.d.ts +23 -0
  36. package/dist/core/types.js +3 -3
  37. package/dist/index.d.ts +4 -3
  38. package/dist/index.js +2 -1
  39. package/dist/server.d.ts +3 -2
  40. package/dist/server.js +2 -1
  41. package/package.json +94 -93
@@ -2,6 +2,8 @@
2
2
  // @duct/sdk — Config Definition and Validation
3
3
  // ============================================================
4
4
  import { z } from "zod";
5
+ import { ActionManifestSchema, iso8601Schema, } from "@duct-sdk/contracts";
6
+ export { ActionManifestSchema, ManifestActionSchema, SensitivityLevelSchema, ErrorEnvelopeSchema, ConfirmationStateSchema, } from "@duct-sdk/contracts";
5
7
  // ----------------------------------------------------------------
6
8
  // Zod Schemas
7
9
  // ----------------------------------------------------------------
@@ -43,73 +45,15 @@ const RouteManifestSchema = z.object({
43
45
  requiresAuth: z.boolean(),
44
46
  deeplinkable: z.boolean(),
45
47
  methods: z.array(z.string()).optional(),
46
- });
47
- const SensitivityLevelSchema = z.enum([
48
- "none",
49
- "low",
50
- "medium",
51
- "high",
52
- "critical",
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" });
86
- const ActionParamSchema = z.object({
87
- name: z.string().min(1),
88
- type: z.enum(["string", "number", "boolean", "object", "array"]),
89
- required: z.boolean(),
90
- description: z.string().optional(),
91
- schema: z.record(z.unknown()).optional(),
92
- });
93
- const ActionManifestSchema = z.object({
94
- id: z
95
- .string()
96
- .min(1)
97
- .regex(/^[a-z_][a-z0-9_]*$/, "Action IDs must be snake_case"),
98
- name: z.string().min(1),
99
- description: z.string().min(1),
100
- method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]),
101
- path: z.string().min(1).startsWith("/"),
102
- agentAccessible: z.boolean(),
103
- sideEffects: z.boolean(),
104
- sensitivityLevel: SensitivityLevelSchema,
105
- params: z.array(ActionParamSchema).default([]),
106
- responseSchema: z.record(z.unknown()).optional(),
107
- requiresAuth: z.boolean(),
108
- rateLimit: z.number().positive().optional(),
109
- validFrom: iso8601Schema.optional(),
110
- validUntil: iso8601Schema.optional(),
111
- approveIf: ApprovalPredicateSchema.optional(),
112
- actionLimit: ActionLimitPolicySchema.optional(),
48
+ updatedAt: z.string().optional(),
49
+ confidence: z.number().min(0).max(1).optional(),
50
+ evidence: z.array(z.string()).optional(),
51
+ searchAction: z
52
+ .object({
53
+ actionId: z.string().min(1),
54
+ paramMap: z.record(z.string()),
55
+ })
56
+ .optional(),
113
57
  });
114
58
  const AuthStrategySchema = z.enum([
115
59
  "nextauth",
@@ -133,6 +77,8 @@ const AuthSchemaSchema = z.object({
133
77
  .regex(/^[a-z_][a-z0-9_]*$/, "loginDeeplinkId must be snake_case")
134
78
  .optional(),
135
79
  loginRoutePath: z.string().min(1).startsWith("/").optional(),
80
+ confidence: z.number().min(0).max(1).optional(),
81
+ evidence: z.array(z.string()).optional(),
136
82
  });
137
83
  const StateFieldSchema = z.object({
138
84
  key: z.string().min(1),
@@ -156,10 +102,12 @@ const DeeplinkDefinitionSchema = z.object({
156
102
  stateFields: z.array(StateFieldSchema).default([]),
157
103
  expirySeconds: z.number().positive().default(300),
158
104
  requiresAuth: z.boolean(),
105
+ openInNewTab: z.boolean().optional(),
159
106
  intent: z.string().optional(),
160
107
  pageResolver: PageResolverSchema.optional(),
161
108
  allowFetch: z.boolean().optional(),
162
109
  contentSelector: z.string().optional(),
110
+ updatedAt: z.string().optional(),
163
111
  });
164
112
  const AgentPermissionLevelSchema = z.enum([
165
113
  "none",
@@ -171,12 +119,20 @@ const AgentPermissionsSchema = z.object({
171
119
  defaultLevel: AgentPermissionLevelSchema,
172
120
  actionOverrides: z.record(AgentPermissionLevelSchema).optional(),
173
121
  allowedCallers: z.array(z.string()).optional(),
122
+ allowedCallees: z
123
+ .array(z.string().regex(/^(shell_[a-z0-9_]+|\*)$/, "allowedCallees entries must be a shell_ id or '*'"))
124
+ .optional(),
174
125
  requireUserConsent: z.boolean(),
175
126
  allowedActions: z.array(z.string()).optional(),
176
127
  validFrom: iso8601Schema.optional(),
177
128
  validUntil: iso8601Schema.optional(),
178
129
  consentActionScope: z.array(z.string().min(1)).optional(),
179
130
  });
131
+ const WebhooksConfigSchema = z.object({
132
+ consentCallback: z.string().url().optional(),
133
+ identityUrl: z.string().url().optional(),
134
+ secret: z.string().optional(),
135
+ });
180
136
  const WidgetConfigSchema = z.object({
181
137
  primaryColor: z.string().optional(),
182
138
  position: z
@@ -192,6 +148,21 @@ const WidgetConfigSchema = z.object({
192
148
  width: z.union([z.number(), z.string()]).optional(),
193
149
  height: z.union([z.number(), z.string()]).optional(),
194
150
  customCSS: z.string().optional(),
151
+ compactionTurns: z.number().int().min(0).optional(),
152
+ maxToolIterations: z.number().int().positive().optional(),
153
+ maxPlanSteps: z.number().int().positive().optional(),
154
+ });
155
+ const DataModelEntitySchema = z.object({
156
+ id: z.string().min(1),
157
+ label: z.string().min(1),
158
+ discoveryAction: z.string().min(1),
159
+ fetchAction: z.string().min(1),
160
+ indexKey: z.string().min(1),
161
+ labelKey: z.string().min(1),
162
+ dimensions: z.array(z.string()).optional(),
163
+ });
164
+ const DataModelSchema = z.object({
165
+ entities: z.array(DataModelEntitySchema),
195
166
  });
196
167
  const ProductConfigSchema = z.object({
197
168
  name: z.string().min(1),
@@ -214,8 +185,10 @@ export const DuctConfigSchema = z.object({
214
185
  deeplinks: z.array(DeeplinkDefinitionSchema).default([]),
215
186
  agentPermissions: AgentPermissionsSchema,
216
187
  widget: WidgetConfigSchema.optional(),
188
+ dataModel: DataModelSchema.optional(),
217
189
  registry_visibility: z.enum(['public', 'private']).optional().default('private'),
218
190
  intershell_enabled: z.boolean().optional().default(false),
191
+ webhooks: WebhooksConfigSchema.optional(),
219
192
  });
220
193
  function zodIssuesToValidationIssues(errors) {
221
194
  return errors.map((e) => ({
@@ -334,6 +307,17 @@ export function crossValidateDuctConfig(data) {
334
307
  }
335
308
  }
336
309
  }
310
+ if (data.intershell_enabled) {
311
+ const hasProtectedAction = data.actions.some((action) => action.requiresAuth || action.sideEffects);
312
+ if (hasProtectedAction && !data.webhooks?.identityUrl) {
313
+ issues.push({
314
+ severity: "error",
315
+ area: "webhooks",
316
+ issue: "intershell_enabled shells with protected actions must configure webhooks.identityUrl",
317
+ fix: "Set webhooks.identityUrl to the company's identity resolver route, or disable intershell_enabled",
318
+ });
319
+ }
320
+ }
337
321
  return issues;
338
322
  }
339
323
  /**
@@ -0,0 +1,27 @@
1
+ import type { EndpointProfile } from "./endpoints.js";
2
+ export type DuctProfile = "local" | "hosted" | (string & {});
3
+ export declare function getDuctProfile(): DuctProfile;
4
+ export declare function isLocalDuctProfile(profile?: DuctProfile): boolean;
5
+ export declare function isLocalhostUrl(url: string): boolean;
6
+ export declare function allowsLocalhostEndpoints(): boolean;
7
+ export interface ResolvedServiceEndpoints {
8
+ ductUrl: string;
9
+ authUrl: string;
10
+ apiBase: string;
11
+ shellUrl: string;
12
+ registryUrl: string;
13
+ dashboardUrl: string;
14
+ docsUrl: string;
15
+ }
16
+ export declare function resolveServiceEndpoints(profile?: EndpointProfile | null): ResolvedServiceEndpoints;
17
+ export declare class HostedLocalhostEndpointError extends Error {
18
+ readonly localhostEndpoints: Array<{
19
+ key: string;
20
+ url: string;
21
+ }>;
22
+ constructor(localhostEndpoints: Array<{
23
+ key: string;
24
+ url: string;
25
+ }>);
26
+ }
27
+ export declare function assertHostedEndpointsNotLocalhost(profile?: EndpointProfile | null): void;
@@ -0,0 +1,71 @@
1
+ // ============================================================
2
+ // @duct/sdk — Hosted-mode endpoint guard
3
+ // ============================================================
4
+ import { getActiveApiBase, getAuthUrl, getConfiguredDashboard, getDocsUrl, getRegistryUrl, getShellRuntimeUrl, } from "./endpoints.js";
5
+ import { resolveActiveProfileName } from "./profile.js";
6
+ export function getDuctProfile() {
7
+ return resolveActiveProfileName();
8
+ }
9
+ export function isLocalDuctProfile(profile = getDuctProfile()) {
10
+ return profile.trim().toLowerCase() === "local";
11
+ }
12
+ export function isLocalhostUrl(url) {
13
+ if (!url.trim())
14
+ return false;
15
+ try {
16
+ const host = new URL(url).hostname.toLowerCase();
17
+ return (host === "localhost" ||
18
+ host === "127.0.0.1" ||
19
+ host === "::1" ||
20
+ host.endsWith(".localhost"));
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ }
26
+ export function allowsLocalhostEndpoints() {
27
+ if (isLocalDuctProfile())
28
+ return true;
29
+ const flag = (process.env["DUCT_ALLOW_LOCALHOST"] ?? "").trim().toLowerCase();
30
+ return flag === "true" || flag === "1" || flag === "yes";
31
+ }
32
+ export function resolveServiceEndpoints(profile) {
33
+ return {
34
+ ductUrl: (process.env["DUCT_URL"] ?? "").trim(),
35
+ authUrl: getAuthUrl(),
36
+ apiBase: getActiveApiBase(profile),
37
+ shellUrl: getShellRuntimeUrl(),
38
+ registryUrl: getRegistryUrl(),
39
+ dashboardUrl: getConfiguredDashboard(profile),
40
+ docsUrl: getDocsUrl(),
41
+ };
42
+ }
43
+ export class HostedLocalhostEndpointError extends Error {
44
+ localhostEndpoints;
45
+ constructor(localhostEndpoints) {
46
+ const detail = localhostEndpoints.map(({ key, url }) => `${key}=${url}`).join(", ");
47
+ super(`Hosted mode cannot use localhost service URLs (${detail}). ` +
48
+ "Set DUCT_URL to your platform origin, use DUCT_PROFILE=local for local dev, " +
49
+ "or set DUCT_ALLOW_LOCALHOST=true to override.");
50
+ this.name = "HostedLocalhostEndpointError";
51
+ this.localhostEndpoints = localhostEndpoints;
52
+ }
53
+ }
54
+ export function assertHostedEndpointsNotLocalhost(profile) {
55
+ if (allowsLocalhostEndpoints())
56
+ return;
57
+ const endpoints = resolveServiceEndpoints(profile);
58
+ const serviceKeys = [
59
+ "authUrl",
60
+ "apiBase",
61
+ "shellUrl",
62
+ "registryUrl",
63
+ "dashboardUrl",
64
+ ];
65
+ const localhostEndpoints = serviceKeys
66
+ .map((key) => ({ key, url: endpoints[key] }))
67
+ .filter(({ url }) => url && isLocalhostUrl(url));
68
+ if (localhostEndpoints.length > 0) {
69
+ throw new HostedLocalhostEndpointError(localhostEndpoints);
70
+ }
71
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,57 @@
1
+ import { describe, it, beforeEach, afterEach } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { allowsLocalhostEndpoints, assertHostedEndpointsNotLocalhost, getDuctProfile, HostedLocalhostEndpointError, isLocalhostUrl, } from "./endpoint-guard.js";
4
+ const ORIGINAL_ENV = { ...process.env };
5
+ function restoreEnv() {
6
+ for (const key of Object.keys(process.env)) {
7
+ if (!(key in ORIGINAL_ENV))
8
+ delete process.env[key];
9
+ }
10
+ for (const [key, value] of Object.entries(ORIGINAL_ENV)) {
11
+ if (value === undefined)
12
+ delete process.env[key];
13
+ else
14
+ process.env[key] = value;
15
+ }
16
+ }
17
+ describe("endpoint-guard", () => {
18
+ beforeEach(() => {
19
+ delete process.env.DUCT_PROFILE;
20
+ delete process.env.DUCT_ALLOW_LOCALHOST;
21
+ delete process.env.DUCT_URL;
22
+ delete process.env.DUCT_AUTH_URL;
23
+ delete process.env.DUCT_API_URL;
24
+ delete process.env.DUCT_SHELL_URL;
25
+ delete process.env.DUCT_DASHBOARD_URL;
26
+ delete process.env.DUCT_REGISTRY_URL;
27
+ });
28
+ afterEach(() => {
29
+ restoreEnv();
30
+ });
31
+ it("detects localhost URLs", () => {
32
+ assert.equal(isLocalhostUrl("http://localhost:3002"), true);
33
+ assert.equal(isLocalhostUrl("http://127.0.0.1:3001"), true);
34
+ assert.equal(isLocalhostUrl("https://api.example.com"), false);
35
+ });
36
+ it("treats DUCT_PROFILE=local as allowing localhost", () => {
37
+ process.env.DUCT_PROFILE = "local";
38
+ assert.equal(getDuctProfile(), "local");
39
+ assert.equal(allowsLocalhostEndpoints(), true);
40
+ assert.doesNotThrow(() => assertHostedEndpointsNotLocalhost());
41
+ });
42
+ it("fails hosted mode when endpoints resolve to localhost", () => {
43
+ assert.throws(() => assertHostedEndpointsNotLocalhost(), (err) => {
44
+ assert.ok(err instanceof HostedLocalhostEndpointError);
45
+ assert.ok(err.localhostEndpoints.length > 0);
46
+ return true;
47
+ });
48
+ });
49
+ it("allows localhost in hosted mode when DUCT_ALLOW_LOCALHOST=true", () => {
50
+ process.env.DUCT_ALLOW_LOCALHOST = "true";
51
+ assert.doesNotThrow(() => assertHostedEndpointsNotLocalhost());
52
+ });
53
+ it("passes hosted mode when DUCT_URL points to a remote origin", () => {
54
+ process.env.DUCT_URL = "https://acme.duct.dev";
55
+ assert.doesNotThrow(() => assertHostedEndpointsNotLocalhost());
56
+ });
57
+ });
@@ -0,0 +1,13 @@
1
+ import type { EndpointProfile } from "./endpoints.js";
2
+ export declare function shouldRedactEnvKey(key: string): boolean;
3
+ export declare function redactEnvValue(key: string, value: string): string;
4
+ export interface EnvDiagnosticLine {
5
+ key: string;
6
+ value: string;
7
+ }
8
+ export declare function collectEnvDiagnosticLines(profile?: EndpointProfile | null, options?: {
9
+ redact?: boolean;
10
+ }): EnvDiagnosticLine[];
11
+ export declare function formatEnvDiagnostics(profile?: EndpointProfile | null, options?: {
12
+ redact?: boolean;
13
+ }): string;
@@ -0,0 +1,63 @@
1
+ // ============================================================
2
+ // @duct/sdk — CLI env diagnostics (redacted output)
3
+ // ============================================================
4
+ import { resolveServiceEndpoints, getDuctProfile } from "./endpoint-guard.js";
5
+ const SECRET_ENV_KEYS = new Set([
6
+ "DUCT_API_KEY",
7
+ "DUCT_SECRET_KEY",
8
+ "ANTHROPIC_API_KEY",
9
+ "OPENAI_API_KEY",
10
+ "OPENROUTER_API_KEY",
11
+ "JWT_SECRET",
12
+ "INTERNAL_SERVICE_SECRET",
13
+ "SHELL_RUNTIME_SECRET",
14
+ "NPM_TOKEN",
15
+ "NODE_AUTH_TOKEN",
16
+ ]);
17
+ const SECRET_ENV_PATTERN = /(secret|token|password|api[_-]?key|auth)/i;
18
+ export function shouldRedactEnvKey(key) {
19
+ return SECRET_ENV_KEYS.has(key) || SECRET_ENV_PATTERN.test(key);
20
+ }
21
+ export function redactEnvValue(key, value) {
22
+ if (!value)
23
+ return value;
24
+ if (!shouldRedactEnvKey(key))
25
+ return value;
26
+ if (value.length <= 8)
27
+ return "***";
28
+ return `${value.slice(0, 4)}...${value.slice(-4)}`;
29
+ }
30
+ export function collectEnvDiagnosticLines(profile, options) {
31
+ const redact = options?.redact ?? false;
32
+ const lines = [];
33
+ const endpoints = resolveServiceEndpoints(profile);
34
+ lines.push({ key: "DUCT_PROFILE", value: getDuctProfile() || "(default: hosted)" });
35
+ lines.push({ key: "DUCT_URL", value: endpoints.ductUrl || "(not set)" });
36
+ lines.push({ key: "DUCT_AUTH_URL", value: endpoints.authUrl });
37
+ lines.push({ key: "DUCT_API_URL", value: endpoints.apiBase });
38
+ lines.push({ key: "DUCT_SHELL_URL", value: endpoints.shellUrl });
39
+ lines.push({ key: "DUCT_REGISTRY_URL", value: endpoints.registryUrl });
40
+ lines.push({ key: "DUCT_DASHBOARD_URL", value: endpoints.dashboardUrl });
41
+ lines.push({ key: "DUCT_DOCS_URL", value: endpoints.docsUrl });
42
+ const trackedKeys = [
43
+ "DUCT_SHELL_ID",
44
+ "DUCT_API_KEY",
45
+ "DUCT_SECRET_KEY",
46
+ "DUCT_ALLOW_LOCALHOST",
47
+ ];
48
+ for (const key of trackedKeys) {
49
+ const raw = process.env[key];
50
+ if (raw === undefined)
51
+ continue;
52
+ lines.push({
53
+ key,
54
+ value: redact ? redactEnvValue(key, raw) : raw,
55
+ });
56
+ }
57
+ return lines;
58
+ }
59
+ export function formatEnvDiagnostics(profile, options) {
60
+ return collectEnvDiagnosticLines(profile, options)
61
+ .map(({ key, value }) => `${key}=${value}`)
62
+ .join("\n");
63
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,31 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { collectEnvDiagnosticLines, redactEnvValue, shouldRedactEnvKey, } from "./env-diagnostics.js";
4
+ describe("env-diagnostics", () => {
5
+ it("flags secret-like env keys for redaction", () => {
6
+ assert.equal(shouldRedactEnvKey("DUCT_SECRET_KEY"), true);
7
+ assert.equal(shouldRedactEnvKey("DUCT_SHELL_ID"), false);
8
+ assert.equal(shouldRedactEnvKey("MY_AUTH_TOKEN"), true);
9
+ });
10
+ it("redacts secret values while preserving shape", () => {
11
+ assert.equal(redactEnvValue("DUCT_API_KEY", "dk_live_abcdefghijklmnop"), "dk_l...mnop");
12
+ assert.equal(redactEnvValue("DUCT_SHELL_ID", "shell_acme_prod"), "shell_acme_prod");
13
+ });
14
+ it("collectEnvDiagnosticLines redacts tracked secrets when requested", () => {
15
+ const previous = process.env.DUCT_API_KEY;
16
+ process.env.DUCT_API_KEY = "dk_live_secretvalue123456";
17
+ try {
18
+ const lines = collectEnvDiagnosticLines(null, { redact: true });
19
+ const apiKeyLine = lines.find((line) => line.key === "DUCT_API_KEY");
20
+ assert.ok(apiKeyLine);
21
+ assert.match(apiKeyLine.value, /\.\.\./);
22
+ assert.doesNotMatch(apiKeyLine.value, /secretvalue123456/);
23
+ }
24
+ finally {
25
+ if (previous === undefined)
26
+ delete process.env.DUCT_API_KEY;
27
+ else
28
+ process.env.DUCT_API_KEY = previous;
29
+ }
30
+ });
31
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,110 @@
1
+ import { describe, it } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createHmac } from 'crypto';
4
+ import { verifyEvidenceBundle } from './evidence-bundle.js';
5
+ import { computeReceiptId } from './receipt.js';
6
+ import { canonicalizeJson } from './jcs.js';
7
+ const HMAC_SECRET = 'conformance-fixture-secret-32bytes!!';
8
+ function signReceipt(body) {
9
+ const receipt_id = computeReceiptId(body);
10
+ const signature = createHmac('sha256', HMAC_SECRET).update(canonicalizeJson(body)).digest('hex');
11
+ return { ...body, receipt_id, signature, kid: 'duct-gateway-hs256-v1' };
12
+ }
13
+ function goldenReadActionBundle() {
14
+ const gate = signReceipt({
15
+ claim_type: 'duct:action:v1',
16
+ issued_at: '2026-01-01T00:00:01.000Z',
17
+ shell_id: 'shell_fixture',
18
+ action_id: 'get_items',
19
+ caller_type: 'human',
20
+ decision: 'permit',
21
+ reason: 'Passes all permission checks',
22
+ permission_source: 'default',
23
+ capture_mode: 'gateway_observed',
24
+ scope_of_claim: {
25
+ asserts: ['gate'],
26
+ does_not_assert: ['upstream'],
27
+ },
28
+ });
29
+ const execution = signReceipt({
30
+ claim_type: 'duct:execution:v1',
31
+ issued_at: '2026-01-01T00:00:05.000Z',
32
+ shell_id: 'shell_fixture',
33
+ action_id: 'get_items',
34
+ caller_type: 'human',
35
+ decision: 'permit',
36
+ reason: 'upstream_observed',
37
+ permission_source: 'gateway',
38
+ capture_mode: 'gateway_observed',
39
+ scope_of_claim: {
40
+ asserts: ['dispatch'],
41
+ does_not_assert: ['business correctness'],
42
+ },
43
+ gate_receipt_ref: gate.receipt_id,
44
+ execution_id: 'EX123',
45
+ upstream_status_class: 'success',
46
+ });
47
+ return {
48
+ manifest: {
49
+ schema: 'duct:audit-evidence:v1',
50
+ bundle_id: 'fixture-read-action',
51
+ exported_at: '2026-01-01T00:10:00.000Z',
52
+ shell_id: 'shell_fixture',
53
+ company_id: 'co_fixture',
54
+ profile: 'standard',
55
+ completeness: 'complete',
56
+ complete: true,
57
+ non_claims: [
58
+ 'does_not_assert_llm_reasoning_correctness',
59
+ 'does_not_assert_upstream_business_data_correctness',
60
+ ],
61
+ },
62
+ conversation: [
63
+ {
64
+ turn_id: 't_fixture',
65
+ message_preview: 'show my items',
66
+ reply_preview: 'Here are your items.',
67
+ occurred_at: '2026-01-01T00:00:00.000Z',
68
+ },
69
+ ],
70
+ evidence_events: [
71
+ { stage: 'request_observed' },
72
+ { stage: 'action_selected' },
73
+ { stage: 'policy_decided' },
74
+ { stage: 'upstream_dispatched' },
75
+ { stage: 'upstream_completed' },
76
+ { stage: 'response_delivered' },
77
+ ],
78
+ receipts: [gate, execution],
79
+ redaction_ledger: [],
80
+ integrity: { valid: true, window_size: 1 },
81
+ replay_descriptor: {
82
+ executions: [
83
+ {
84
+ execution_id: 'EX123',
85
+ action_id: 'get_items',
86
+ request_hash: 'abc123',
87
+ result_hash: 'def456',
88
+ },
89
+ ],
90
+ sandbox_only: true,
91
+ requires_fresh_approval: true,
92
+ },
93
+ };
94
+ }
95
+ describe('evidence bundle conformance fixtures', () => {
96
+ it('verifies the golden read-action scenario', () => {
97
+ const bundle = goldenReadActionBundle();
98
+ const result = verifyEvidenceBundle(bundle, { hmacSecret: HMAC_SECRET });
99
+ assert.equal(result.valid, true);
100
+ assert.equal(result.verified_receipts, 2);
101
+ assert.equal(result.completeness, 'complete');
102
+ assert.deepEqual(result.missing_stages, []);
103
+ });
104
+ it('flags partial bundles with warnings', () => {
105
+ const bundle = goldenReadActionBundle();
106
+ bundle.manifest.completeness = 'partial';
107
+ const result = verifyEvidenceBundle(bundle, { hmacSecret: HMAC_SECRET });
108
+ assert.ok(result.warnings.some((w) => w.includes('partial')));
109
+ });
110
+ });
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Offline verification for duct:audit-evidence:v1 bundles.
3
+ */
4
+ import { type ReceiptJwks, type SignedDuctReceipt, type VerifyReceiptOptions } from "./receipt.js";
5
+ export interface EvidenceBundleManifest {
6
+ schema: string;
7
+ bundle_id: string;
8
+ exported_at: string;
9
+ shell_id: string;
10
+ company_id: string;
11
+ profile: string;
12
+ completeness: "legacy" | "partial" | "complete";
13
+ complete: boolean;
14
+ verification_keys?: ReceiptJwks;
15
+ non_claims?: string[];
16
+ }
17
+ export interface EvidenceBundleIntegrity {
18
+ valid: boolean;
19
+ window_size: number;
20
+ head_hash?: string | null;
21
+ signed_checkpoint?: {
22
+ shell_id: string;
23
+ head_hash: string;
24
+ row_count_at_checkpoint: number;
25
+ issued_at: string;
26
+ signature: string;
27
+ kid: string;
28
+ };
29
+ redacted_count?: number;
30
+ }
31
+ export interface EvidenceBundle {
32
+ manifest: EvidenceBundleManifest;
33
+ conversation: unknown[];
34
+ evidence_events: unknown[];
35
+ receipts: SignedDuctReceipt[];
36
+ integrity?: EvidenceBundleIntegrity;
37
+ redaction_ledger: unknown[];
38
+ replay_descriptor?: {
39
+ executions: unknown[];
40
+ sandbox_only: boolean;
41
+ requires_fresh_approval: boolean;
42
+ };
43
+ }
44
+ export interface VerifyEvidenceBundleResult {
45
+ valid: boolean;
46
+ schema: string;
47
+ completeness: string;
48
+ verified_receipts: number;
49
+ failed_receipts: Array<{
50
+ receipt_id?: string;
51
+ reason: string;
52
+ }>;
53
+ integrity_valid: boolean;
54
+ missing_stages: string[];
55
+ redacted_fields: string[];
56
+ non_claims: string[];
57
+ warnings: string[];
58
+ }
59
+ export declare function verifyEvidenceBundle(bundle: EvidenceBundle, options?: VerifyReceiptOptions): VerifyEvidenceBundleResult;