@duct-sdk/sdk 0.4.4 → 0.5.1

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 (60) hide show
  1. package/CHANGELOG.md +55 -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 +110 -37
  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.d.ts +14 -0
  26. package/dist/cli/generators/wiring-snippets.js +180 -16
  27. package/dist/cli/generators/wiring-snippets.test.js +15 -1
  28. package/dist/cli/index.js +108 -151
  29. package/dist/cli/init.js +110 -17
  30. package/dist/cli/manifest-diff.d.ts +21 -0
  31. package/dist/cli/manifest-diff.js +158 -0
  32. package/dist/cli/manifest-diff.test.d.ts +1 -0
  33. package/dist/cli/manifest-diff.test.js +104 -0
  34. package/dist/cli/output-paths.d.ts +2 -0
  35. package/dist/cli/output-paths.js +22 -4
  36. package/dist/cli/processors/integration-audit.js +1 -1
  37. package/dist/core/config-policy.test.d.ts +1 -0
  38. package/dist/core/config-policy.test.js +101 -0
  39. package/dist/core/config.d.ts +86 -1
  40. package/dist/core/config.js +120 -2
  41. package/dist/core/invariants.test.d.ts +1 -0
  42. package/dist/core/invariants.test.js +217 -0
  43. package/dist/core/jcs.d.ts +5 -0
  44. package/dist/core/jcs.js +21 -0
  45. package/dist/core/receipt.d.ts +70 -0
  46. package/dist/core/receipt.js +86 -0
  47. package/dist/core/receipt.test.d.ts +1 -0
  48. package/dist/core/receipt.test.js +75 -0
  49. package/dist/core/replay-store.d.ts +51 -0
  50. package/dist/core/replay-store.js +65 -0
  51. package/dist/core/token.d.ts +14 -0
  52. package/dist/core/token.js +50 -18
  53. package/dist/core/token.test.d.ts +1 -0
  54. package/dist/core/token.test.js +66 -0
  55. package/dist/core/types.d.ts +72 -0
  56. package/dist/index.d.ts +6 -4
  57. package/dist/index.js +4 -2
  58. package/dist/server.d.ts +6 -4
  59. package/dist/server.js +4 -2
  60. package/package.json +91 -90
@@ -20,6 +20,7 @@
20
20
  // ============================================================
21
21
  "use client";
22
22
  import { useEffect, useRef } from "react";
23
+ import { shouldHandlePageContextRequest } from "./page-context-guard.js";
23
24
  /**
24
25
  * useDuctPageContext — company-side hook for the Page Context Protocol.
25
26
  *
@@ -46,31 +47,20 @@ export function useDuctPageContext(resolver, options = {}) {
46
47
  resolverRef.current = resolver;
47
48
  const shellHostRef = useRef(options.shellHost);
48
49
  shellHostRef.current = options.shellHost;
49
- // Warn once in non-production when shellHost is omitted — any cross-origin frame
50
- // could then request the company's page context.
50
+ // Fail closed in development when shellHost is omitted.
51
51
  useEffect(() => {
52
52
  if (!options.shellHost && process.env.NODE_ENV !== "production") {
53
- console.error("[duct] useDuctPageContext: shellHost is not configured. " +
54
- "Any cross-origin iframe can request your page context. " +
53
+ throw new Error("[duct] useDuctPageContext: shellHost is required. " +
55
54
  "Pass shellHost (e.g. process.env.NEXT_PUBLIC_DUCT_SHELL_HOST) to restrict " +
56
55
  "requests to the Duct shell only.");
57
56
  }
58
57
  // eslint-disable-next-line react-hooks/exhaustive-deps
59
- }, []); // warn once on mount
58
+ }, []);
60
59
  useEffect(() => {
61
60
  function handleMessage(event) {
62
- // Origin guard: only allow the configured shell host
63
61
  const shellHost = shellHostRef.current;
64
- if (shellHost) {
65
- let expectedOrigin;
66
- try {
67
- expectedOrigin = new URL(shellHost).origin;
68
- }
69
- catch {
70
- return; // invalid shellHost — fail closed
71
- }
72
- if (event.origin !== expectedOrigin)
73
- return;
62
+ if (!shouldHandlePageContextRequest(shellHost, event.origin)) {
63
+ return;
74
64
  }
75
65
  if (typeof event.data !== "object" ||
76
66
  event.data === null ||
@@ -1,10 +1,12 @@
1
- import type { RouteManifest, ActionManifest, AuthSchema, DeeplinkDefinition, ReviewResult } from "../../core/types.js";
1
+ import type { RouteManifest, ActionManifest, AuthSchema, DeeplinkDefinition, ReviewResult, ReviewIssue } from "../../core/types.js";
2
2
  export interface ReviewAgentInput {
3
3
  routes: RouteManifest[];
4
4
  actions: ActionManifest[];
5
5
  auth: AuthSchema;
6
6
  deeplinks: DeeplinkDefinition[];
7
7
  }
8
+ /** Agent-safety checks used by `duct push` (no LLM). */
9
+ export declare function runAgentSafetyChecks(input: ReviewAgentInput): ReviewIssue[];
8
10
  /**
9
11
  * Run the Reviewer Agent to validate and score the pipeline output.
10
12
  */
@@ -31,10 +31,39 @@ Single ReviewResult object:
31
31
  // ----------------------------------------------------------------
32
32
  // Rule-based pre-checks
33
33
  // ----------------------------------------------------------------
34
+ /** Agent-safety checks used by `duct push` (no LLM). */
35
+ export function runAgentSafetyChecks(input) {
36
+ const issues = [];
37
+ const { actions } = input;
38
+ for (let i = 0; i < actions.length; i++) {
39
+ const action = actions[i];
40
+ if (action.agentAccessible &&
41
+ (action.sensitivityLevel === "high" || action.sensitivityLevel === "critical")) {
42
+ issues.push({
43
+ code: "HIGH_SENSITIVITY_AGENT_ACCESSIBLE",
44
+ severity: "error",
45
+ message: `Action "${action.id}" is agent-accessible but has sensitivity level "${action.sensitivityLevel}"`,
46
+ path: `actions[${i}].agentAccessible`,
47
+ suggestion: "Only mark agent-accessible for low/medium sensitivity actions, or require explicit user consent",
48
+ });
49
+ }
50
+ if (action.agentAccessible && action.sideEffects && !action.rateLimit) {
51
+ issues.push({
52
+ code: "AGENT_SIDE_EFFECT_NO_RATE_LIMIT",
53
+ severity: "warning",
54
+ message: `Agent-accessible action "${action.id}" has side effects but no rate limit`,
55
+ path: `actions[${i}].rateLimit`,
56
+ suggestion: "Add a rateLimit (requests/minute) to prevent agent abuse of side-effect actions",
57
+ });
58
+ }
59
+ }
60
+ return issues;
61
+ }
34
62
  async function runStaticChecks(input) {
35
63
  const issues = [];
36
64
  const { routes, actions, auth, deeplinks } = input;
37
65
  const seenActionEndpoints = new Set();
66
+ issues.push(...runAgentSafetyChecks(input));
38
67
  // Routes checks
39
68
  for (let i = 0; i < routes.length; i++) {
40
69
  const route = routes[i];
@@ -95,27 +124,6 @@ async function runStaticChecks(input) {
95
124
  suggestion: "Add a clear description of what this action does",
96
125
  });
97
126
  }
98
- // Warn if high sensitivity actions are marked agent-accessible
99
- if (action.agentAccessible &&
100
- (action.sensitivityLevel === "high" || action.sensitivityLevel === "critical")) {
101
- issues.push({
102
- code: "HIGH_SENSITIVITY_AGENT_ACCESSIBLE",
103
- severity: "error",
104
- message: `Action "${action.id}" is agent-accessible but has sensitivity level "${action.sensitivityLevel}"`,
105
- path: `actions[${i}].agentAccessible`,
106
- suggestion: "Only mark agent-accessible for low/medium sensitivity actions, or require explicit user consent",
107
- });
108
- }
109
- // Warn if side-effect actions are agent-accessible without rate limits
110
- if (action.agentAccessible && action.sideEffects && !action.rateLimit) {
111
- issues.push({
112
- code: "AGENT_SIDE_EFFECT_NO_RATE_LIMIT",
113
- severity: "warning",
114
- message: `Agent-accessible action "${action.id}" has side effects but no rate limit`,
115
- path: `actions[${i}].rateLimit`,
116
- suggestion: "Add a rateLimit (requests/minute) to prevent agent abuse of side-effect actions",
117
- });
118
- }
119
127
  }
120
128
  // Auth checks
121
129
  if (auth.strategy === "unknown") {
@@ -0,0 +1,15 @@
1
+ export declare class ConfigRuntimeReferenceError extends Error {
2
+ constructor();
3
+ }
4
+ export declare function configSourceHasRuntimeReferences(source: string): boolean;
5
+ export declare function extractConfigObjectLiteral(source: string): string | null;
6
+ /**
7
+ * Parse `defineDuctConfig({...})` as a JSON-safe object literal.
8
+ * Rejects configs that reference runtime values; does not expose `process`.
9
+ */
10
+ export declare function loadConfigFromSource(configPath: string): Promise<Record<string, unknown> | null>;
11
+ /**
12
+ * Load duct.config.ts / .js without executing untrusted TypeScript source.
13
+ * Prefer AST extraction for `.ts`; fall back to compiled JS siblings only.
14
+ */
15
+ export declare function loadDuctConfig(configPath: string): Promise<Record<string, unknown>>;
@@ -0,0 +1,187 @@
1
+ // ============================================================
2
+ // @duct/sdk — duct.config.ts static loader (no arbitrary code exec)
3
+ // ============================================================
4
+ import * as fs from "fs/promises";
5
+ import * as path from "path";
6
+ import * as vm from "node:vm";
7
+ import { pathToFileURL } from "node:url";
8
+ export class ConfigRuntimeReferenceError extends Error {
9
+ constructor() {
10
+ super("duct.config.ts references runtime values (process, require, fetch, import). " +
11
+ "Use static literals only — push/scan must not execute project code.");
12
+ this.name = "ConfigRuntimeReferenceError";
13
+ }
14
+ }
15
+ export function configSourceHasRuntimeReferences(source) {
16
+ const stripped = source
17
+ .replace(/\/\*[\s\S]*?\*\//g, "")
18
+ .replace(/\/\/.*$/gm, "");
19
+ return (/\bprocess\b/.test(stripped) ||
20
+ /\brequire\s*\(/.test(stripped) ||
21
+ /\bfetch\s*\(/.test(stripped) ||
22
+ /\bimport\s*\(/.test(stripped));
23
+ }
24
+ export function extractConfigObjectLiteral(source) {
25
+ const marker = "defineDuctConfig(";
26
+ const markerIndex = source.indexOf(marker);
27
+ if (markerIndex === -1)
28
+ return null;
29
+ const startSearch = markerIndex + marker.length;
30
+ let objectStart = -1;
31
+ for (let i = startSearch; i < source.length; i++) {
32
+ const ch = source[i];
33
+ if (!/\s/.test(ch)) {
34
+ if (ch !== "{")
35
+ return null;
36
+ objectStart = i;
37
+ break;
38
+ }
39
+ }
40
+ if (objectStart === -1)
41
+ return null;
42
+ let depth = 0;
43
+ let inSingle = false;
44
+ let inDouble = false;
45
+ let inTemplate = false;
46
+ let inLineComment = false;
47
+ let inBlockComment = false;
48
+ for (let i = objectStart; i < source.length; i++) {
49
+ const ch = source[i];
50
+ const next = source[i + 1] ?? "";
51
+ const prev = source[i - 1] ?? "";
52
+ if (inLineComment) {
53
+ if (ch === "\n")
54
+ inLineComment = false;
55
+ continue;
56
+ }
57
+ if (inBlockComment) {
58
+ if (prev === "*" && ch === "/")
59
+ inBlockComment = false;
60
+ continue;
61
+ }
62
+ if (!inSingle && !inDouble && !inTemplate) {
63
+ if (ch === "/" && next === "/") {
64
+ inLineComment = true;
65
+ i++;
66
+ continue;
67
+ }
68
+ if (ch === "/" && next === "*") {
69
+ inBlockComment = true;
70
+ i++;
71
+ continue;
72
+ }
73
+ }
74
+ if (!inDouble && !inTemplate && ch === "'" && prev !== "\\") {
75
+ inSingle = !inSingle;
76
+ continue;
77
+ }
78
+ if (!inSingle && !inTemplate && ch === '"' && prev !== "\\") {
79
+ inDouble = !inDouble;
80
+ continue;
81
+ }
82
+ if (!inSingle && !inDouble && ch === "`" && prev !== "\\") {
83
+ inTemplate = !inTemplate;
84
+ continue;
85
+ }
86
+ if (inSingle || inDouble || inTemplate) {
87
+ continue;
88
+ }
89
+ if (ch === "{")
90
+ depth++;
91
+ if (ch === "}") {
92
+ depth--;
93
+ if (depth === 0) {
94
+ return source.slice(objectStart, i + 1);
95
+ }
96
+ }
97
+ }
98
+ return null;
99
+ }
100
+ function toCompiledCandidates(configPath) {
101
+ const ext = path.extname(configPath).toLowerCase();
102
+ if (ext !== ".ts" && ext !== ".tsx") {
103
+ return [configPath];
104
+ }
105
+ const jsSibling = configPath.replace(/\.(ts|tsx)$/i, ".js");
106
+ const mjsSibling = configPath.replace(/\.(ts|tsx)$/i, ".mjs");
107
+ const cjsSibling = configPath.replace(/\.(ts|tsx)$/i, ".cjs");
108
+ const distStyle = configPath
109
+ .replace(/([\\/])src([\\/])/g, "$1dist$2")
110
+ .replace(/\.(ts|tsx)$/i, ".js");
111
+ return [...new Set([jsSibling, mjsSibling, cjsSibling, distStyle])];
112
+ }
113
+ /**
114
+ * Parse `defineDuctConfig({...})` as a JSON-safe object literal.
115
+ * Rejects configs that reference runtime values; does not expose `process`.
116
+ */
117
+ export async function loadConfigFromSource(configPath) {
118
+ const source = await fs.readFile(configPath, "utf-8");
119
+ if (configSourceHasRuntimeReferences(source)) {
120
+ throw new ConfigRuntimeReferenceError();
121
+ }
122
+ const objectLiteral = extractConfigObjectLiteral(source);
123
+ if (!objectLiteral) {
124
+ return null;
125
+ }
126
+ if (configSourceHasRuntimeReferences(objectLiteral)) {
127
+ throw new ConfigRuntimeReferenceError();
128
+ }
129
+ const script = new vm.Script(`(${objectLiteral})`, { filename: configPath });
130
+ const evaluated = script.runInNewContext(Object.freeze({ Math, Date, JSON }), {
131
+ timeout: 1000,
132
+ codeGeneration: { strings: false },
133
+ });
134
+ if (!evaluated || typeof evaluated !== "object") {
135
+ return null;
136
+ }
137
+ return evaluated;
138
+ }
139
+ /**
140
+ * Load duct.config.ts / .js without executing untrusted TypeScript source.
141
+ * Prefer AST extraction for `.ts`; fall back to compiled JS siblings only.
142
+ */
143
+ export async function loadDuctConfig(configPath) {
144
+ const ext = path.extname(configPath).toLowerCase();
145
+ if (ext === ".ts" || ext === ".tsx") {
146
+ try {
147
+ const sourceLoaded = await loadConfigFromSource(configPath);
148
+ if (sourceLoaded) {
149
+ return sourceLoaded;
150
+ }
151
+ }
152
+ catch (err) {
153
+ if (err instanceof ConfigRuntimeReferenceError) {
154
+ throw err;
155
+ }
156
+ }
157
+ }
158
+ const candidates = toCompiledCandidates(configPath);
159
+ for (const candidate of candidates) {
160
+ if (/\.tsx?$/i.test(candidate)) {
161
+ continue;
162
+ }
163
+ try {
164
+ await fs.access(candidate);
165
+ }
166
+ catch {
167
+ continue;
168
+ }
169
+ try {
170
+ const module = (await import(pathToFileURL(candidate).href));
171
+ const loaded = module.default ?? module;
172
+ if (loaded && typeof loaded === "object") {
173
+ return loaded;
174
+ }
175
+ }
176
+ catch {
177
+ // Try next candidate.
178
+ }
179
+ }
180
+ if (ext !== ".ts" && ext !== ".tsx") {
181
+ const sourceLoaded = await loadConfigFromSource(configPath);
182
+ if (sourceLoaded) {
183
+ return sourceLoaded;
184
+ }
185
+ }
186
+ throw new Error("CONFIG_LOAD_FAILED");
187
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,63 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import * as fs from "fs/promises";
4
+ import * as os from "os";
5
+ import * as path from "path";
6
+ import { ConfigRuntimeReferenceError, configSourceHasRuntimeReferences, loadConfigFromSource, } from "./config-loader.js";
7
+ describe("configSourceHasRuntimeReferences", () => {
8
+ it("detects process.exit at top level", () => {
9
+ const source = `process.exit(1);\nexport default defineDuctConfig({ shellId: "x" });`;
10
+ assert.equal(configSourceHasRuntimeReferences(source), true);
11
+ });
12
+ it("allows static defineDuctConfig literals", () => {
13
+ const source = `
14
+ import { defineDuctConfig } from "@duct-sdk/sdk";
15
+ export default defineDuctConfig({
16
+ shellId: "shell_acme",
17
+ product: { name: "Acme", description: "Test app", baseUrl: "https://app.acme.com" },
18
+ });
19
+ `;
20
+ assert.equal(configSourceHasRuntimeReferences(source), false);
21
+ });
22
+ });
23
+ describe("loadConfigFromSource", () => {
24
+ it("does not execute process.exit during load", async () => {
25
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "duct-config-"));
26
+ const configPath = path.join(dir, "duct.config.ts");
27
+ const source = `
28
+ process.exit(42);
29
+ import { defineDuctConfig } from "@duct-sdk/sdk";
30
+ export default defineDuctConfig({
31
+ shellId: "shell_bad",
32
+ product: { name: "Bad", description: "Should not run", baseUrl: "https://bad.example" },
33
+ auth: { strategy: "none", sessionFields: ["id"], guestAllowed: true, tokenExpirySeconds: 60 },
34
+ routes: [],
35
+ actions: [],
36
+ deeplinks: [],
37
+ agentPermissions: { defaultLevel: "none", requireUserConsent: true },
38
+ });
39
+ `;
40
+ await fs.writeFile(configPath, source, "utf-8");
41
+ await assert.rejects(() => loadConfigFromSource(configPath), (err) => err instanceof ConfigRuntimeReferenceError);
42
+ });
43
+ it("parses static defineDuctConfig object literal", async () => {
44
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "duct-config-"));
45
+ const configPath = path.join(dir, "duct.config.ts");
46
+ const source = `
47
+ import { defineDuctConfig } from "@duct-sdk/sdk";
48
+ export default defineDuctConfig({
49
+ shellId: "shell_ok",
50
+ product: { name: "Ok", description: "Static config", baseUrl: "https://ok.example" },
51
+ auth: { strategy: "none", sessionFields: ["id"], guestAllowed: true, tokenExpirySeconds: 60 },
52
+ routes: [],
53
+ actions: [],
54
+ deeplinks: [],
55
+ agentPermissions: { defaultLevel: "none", requireUserConsent: true },
56
+ });
57
+ `;
58
+ await fs.writeFile(configPath, source, "utf-8");
59
+ const loaded = await loadConfigFromSource(configPath);
60
+ assert.ok(loaded);
61
+ assert.equal(loaded.shellId, "shell_ok");
62
+ });
63
+ });
@@ -1,4 +1,4 @@
1
- export type FrameworkName = "next-app" | "next-pages" | "remix" | "vite-react" | "sveltekit" | "vue3" | "nuxt" | "unknown";
1
+ export type FrameworkName = "next-app" | "next-pages" | "remix" | "vite-react" | "sveltekit" | "vue3" | "nuxt" | "express" | "fastapi" | "unknown";
2
2
  export interface FrameworkInfo {
3
3
  name: FrameworkName;
4
4
  version: string;
@@ -58,6 +58,27 @@ async function detectPackageManager(projectRoot) {
58
58
  return "npm";
59
59
  return "unknown";
60
60
  }
61
+ /** Detect a Python FastAPI backend via requirements.txt / pyproject.toml. */
62
+ async function detectFastApiVersion(projectRoot) {
63
+ try {
64
+ const req = await fs.readFile(path.join(projectRoot, "requirements.txt"), "utf-8");
65
+ const m = req.match(/^\s*fastapi\b\s*([=<>!~]=?\s*[\d.]+)?/im);
66
+ if (m)
67
+ return cleanVersion(m[1] ?? null);
68
+ }
69
+ catch {
70
+ /* no requirements.txt */
71
+ }
72
+ try {
73
+ const toml = await fs.readFile(path.join(projectRoot, "pyproject.toml"), "utf-8");
74
+ if (/(^|\n)\s*fastapi\b/i.test(toml) || /["']fastapi["']/i.test(toml))
75
+ return "unknown";
76
+ }
77
+ catch {
78
+ /* no pyproject.toml */
79
+ }
80
+ return null;
81
+ }
61
82
  // ----------------------------------------------------------------
62
83
  // detectFramework
63
84
  // ----------------------------------------------------------------
@@ -80,6 +101,11 @@ export async function detectFramework(projectRoot) {
80
101
  srcDir: projectRoot,
81
102
  };
82
103
  if (!pkg) {
104
+ // Pure Python project (no package.json) — check for FastAPI.
105
+ const fastapiVersion = await detectFastApiVersion(projectRoot);
106
+ if (fastapiVersion) {
107
+ return { ...defaultResult, name: "fastapi", version: fastapiVersion };
108
+ }
83
109
  return defaultResult;
84
110
  }
85
111
  // ---- Next.js ----
@@ -238,5 +264,19 @@ export async function detectFramework(projectRoot) {
238
264
  configFile,
239
265
  };
240
266
  }
267
+ // ---- Standalone Express backend (no frontend framework matched above) ----
268
+ const expressVersion = getDependencyVersion(pkg, "express");
269
+ if (expressVersion) {
270
+ return {
271
+ ...defaultResult,
272
+ name: "express",
273
+ version: cleanVersion(expressVersion),
274
+ };
275
+ }
276
+ // ---- FastAPI backend alongside a package.json (e.g. tooling/monorepo root) ----
277
+ const fastapiVersion = await detectFastApiVersion(projectRoot);
278
+ if (fastapiVersion) {
279
+ return { ...defaultResult, name: "fastapi", version: fastapiVersion };
280
+ }
241
281
  return defaultResult;
242
282
  }