@duct-sdk/sdk 0.3.11 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/adapters/next/receiver.d.ts +2 -6
  3. package/dist/adapters/next/receiver.js +20 -66
  4. package/dist/adapters/remix/receiver.d.ts +2 -6
  5. package/dist/adapters/remix/receiver.js +16 -33
  6. package/dist/adapters/sveltekit/receiver.d.ts +2 -6
  7. package/dist/adapters/sveltekit/receiver.js +13 -40
  8. package/dist/adapters/vite/receiver.d.ts +2 -4
  9. package/dist/adapters/vite/receiver.js +13 -30
  10. package/dist/cli/agents/api-agent.d.ts +3 -1
  11. package/dist/cli/agents/api-agent.js +22 -11
  12. package/dist/cli/agents/auth-agent.js +4 -4
  13. package/dist/cli/agents/pipeline.js +63 -7
  14. package/dist/cli/agents/route-agent.d.ts +3 -1
  15. package/dist/cli/agents/route-agent.js +17 -6
  16. package/dist/cli/detectors/topology.d.ts +1 -1
  17. package/dist/cli/detectors/topology.js +1 -1
  18. package/dist/cli/generators/config.js +71 -44
  19. package/dist/cli/generators/config.test.d.ts +1 -0
  20. package/dist/cli/generators/config.test.js +219 -0
  21. package/dist/cli/generators/normalize.d.ts +10 -0
  22. package/dist/cli/generators/normalize.js +49 -0
  23. package/dist/cli/generators/receiver.d.ts +2 -1
  24. package/dist/cli/generators/receiver.js +20 -201
  25. package/dist/cli/generators/token-route.d.ts +8 -0
  26. package/dist/cli/generators/token-route.js +235 -0
  27. package/dist/cli/generators/token-route.test.d.ts +1 -0
  28. package/dist/cli/generators/token-route.test.js +53 -0
  29. package/dist/cli/generators/wiring-snippets.d.ts +23 -0
  30. package/dist/cli/generators/wiring-snippets.js +233 -0
  31. package/dist/cli/generators/wiring-snippets.test.d.ts +1 -0
  32. package/dist/cli/generators/wiring-snippets.test.js +66 -0
  33. package/dist/cli/index.js +41 -1
  34. package/dist/cli/init.d.ts +1 -7
  35. package/dist/cli/init.js +100 -53
  36. package/dist/cli/output-paths.d.ts +10 -0
  37. package/dist/cli/output-paths.js +60 -0
  38. package/dist/cli/processors/curl-parser.test.d.ts +1 -0
  39. package/dist/cli/processors/curl-parser.test.js +24 -0
  40. package/dist/cli/processors/integration-audit.d.ts +23 -0
  41. package/dist/cli/processors/integration-audit.js +208 -0
  42. package/dist/cli/processors/integration-audit.test.d.ts +1 -0
  43. package/dist/cli/processors/integration-audit.test.js +154 -0
  44. package/dist/cli/processors/prisma-parser.js +1 -1
  45. package/dist/cli/processors/verify-discovery.d.ts +33 -0
  46. package/dist/cli/processors/verify-discovery.js +193 -0
  47. package/dist/cli/processors/verify-discovery.test.d.ts +1 -0
  48. package/dist/cli/processors/verify-discovery.test.js +153 -0
  49. package/dist/cli/processors/zod-extractor.js +1 -1
  50. package/dist/core/config.d.ts +59 -0
  51. package/dist/core/config.js +66 -28
  52. package/dist/core/endpoints.d.ts +2 -0
  53. package/dist/core/endpoints.js +10 -0
  54. package/dist/core/limits.d.ts +1 -1
  55. package/dist/core/limits.js +1 -1
  56. package/dist/core/page-resolve.d.ts +49 -0
  57. package/dist/core/page-resolve.js +87 -0
  58. package/dist/core/receiver.d.ts +33 -0
  59. package/dist/core/receiver.js +77 -0
  60. package/dist/core/types.d.ts +16 -0
  61. package/dist/server.d.ts +4 -0
  62. package/dist/server.js +4 -0
  63. package/package.json +2 -1
@@ -24,13 +24,7 @@ export interface InitOptions {
24
24
  /** Industry/category override (e.g., fintech, ecommerce, saas) */
25
25
  industry?: string;
26
26
  }
27
- export interface GeneratedFiles {
28
- configPath: string;
29
- receiverPath: string;
30
- tokenRoutePath: string;
31
- shellComponentPath: string;
32
- envTemplatePath: string;
33
- }
27
+ export type { GeneratedOutputPaths as GeneratedFiles } from "./output-paths.js";
34
28
  /**
35
29
  * Run the Duct init command.
36
30
  * This is the main entry point for `npx duct init`.
package/dist/cli/init.js CHANGED
@@ -9,6 +9,8 @@ import * as readline from "readline";
9
9
  import ora from "ora";
10
10
  import chalk from "chalk";
11
11
  import inquirer from "inquirer";
12
+ import { validateDuctConfigStrict, } from "../core/config.js";
13
+ import { normalizeDuctConfigForCodegen } from "./generators/normalize.js";
12
14
  import { SandboxFS } from "./fs/sandbox.js";
13
15
  import { detectFramework } from "./detectors/framework.js";
14
16
  import { detectAuth } from "./detectors/auth.js";
@@ -19,8 +21,11 @@ import { runAgentPipeline, DuctPipelineEmitter, } from "./agents/pipeline.js";
19
21
  import { runInteractiveReview } from "./prompts/review.js";
20
22
  import { generateConfigFile, generateManualTemplate } from "./generators/config.js";
21
23
  import { generateReceiver, generateTokenRoute, } from "./generators/receiver.js";
22
- import { generateShell, generateEnvTemplateForFramework, getEnvTemplateName, } from "./generators/shell.js";
23
- import { getActiveAuthBase, getConfiguredDashboard, getManifestApiBases, } from "../core/endpoints.js";
24
+ import { generateShell, generateEnvTemplateForFramework, } from "./generators/shell.js";
25
+ import { getGeneratedOutputPaths } from "./output-paths.js";
26
+ import { buildWiringPlan, sideEffectActionsApproved, } from "./generators/wiring-snippets.js";
27
+ import { integrationAuditFailed, printIntegrationAuditIssues, runIntegrationAudit, } from "./processors/integration-audit.js";
28
+ import { getActiveAuthBase, getConfiguredDashboard, getDocsUrl, getManifestApiBases, } from "../core/endpoints.js";
24
29
  import { fileURLToPath } from "node:url";
25
30
  import { exec } from "child_process";
26
31
  const pkgPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../package.json");
@@ -72,6 +77,21 @@ async function fetchAccountShells(apiKey, authBase) {
72
77
  // ----------------------------------------------------------------
73
78
  // Helpers
74
79
  // ----------------------------------------------------------------
80
+ function printWiringPlan(projectRoot, wiringPlan) {
81
+ console.log(chalk.bold("\n Wiring plan\n"));
82
+ for (const item of wiringPlan.items) {
83
+ const relPath = path.relative(projectRoot, item.path);
84
+ const tag = item.action === "create"
85
+ ? chalk.green("create")
86
+ : item.action === "modify"
87
+ ? chalk.yellow("modify")
88
+ : chalk.blue("verify");
89
+ console.log(` ${tag.padEnd(8)} ${chalk.gray(relPath.padEnd(36))} ${item.summary}`);
90
+ }
91
+ console.log(chalk.gray(`\n Middleware snippet: ${wiringPlan.middlewareSnippetPath}` +
92
+ (wiringPlan.uctSnippetPath ? ` · consent snippet: ${wiringPlan.uctSnippetPath}` : "")));
93
+ console.log("");
94
+ }
75
95
  function frameworkDisplay(framework) {
76
96
  const map = {
77
97
  "next-app": "Next.js (App Router)",
@@ -227,14 +247,13 @@ function detectIndustryFromDeps(deps) {
227
247
  return undefined;
228
248
  }
229
249
  function buildDuctConfigFromPipeline(result, shellId, productName, baseUrl, logoUrl, apiBaseUrl, industry, dataModel) {
230
- return {
250
+ return normalizeDuctConfigForCodegen({
231
251
  shellId,
232
252
  product: {
233
253
  name: productName,
234
254
  description: `${productName} — AI-powered interaction shell`,
235
255
  baseUrl,
236
256
  ...(apiBaseUrl ? { apiBaseUrl } : {}),
237
- ...(logoUrl ? { logoUrl } : {}),
238
257
  ...(industry ? { industry } : {}),
239
258
  },
240
259
  auth: result.auth,
@@ -247,9 +266,28 @@ function buildDuctConfigFromPipeline(result, shellId, productName, baseUrl, logo
247
266
  },
248
267
  widget: {
249
268
  position: "bottom-right",
269
+ ...(logoUrl ? { logoUrl } : {}),
250
270
  },
271
+ ...(result.intershell_enabled !== undefined ||
272
+ result.registry_visibility !== undefined
273
+ ? {
274
+ intershell_enabled: result.intershell_enabled ?? false,
275
+ registry_visibility: result.registry_visibility ?? "private",
276
+ }
277
+ : {}),
251
278
  ...(dataModel && dataModel.entities.length > 0 ? { dataModel } : {}),
252
- };
279
+ });
280
+ }
281
+ function displayConfigValidationIssues(issues) {
282
+ console.log(chalk.red("\n Manifest validation failed:\n"));
283
+ for (const issue of issues) {
284
+ const severityLabel = issue.severity === "error"
285
+ ? chalk.red(`[${issue.severity}]`)
286
+ : chalk.yellow(`[${issue.severity}]`);
287
+ console.log(` ${severityLabel} ${chalk.bold(issue.area)} — ${issue.issue}`);
288
+ console.log(chalk.gray(` Fix: ${issue.fix}`));
289
+ }
290
+ console.log("");
253
291
  }
254
292
  async function writeFile(filePath, content, dryRun) {
255
293
  if (dryRun) {
@@ -376,48 +414,6 @@ async function discoverFrameworkRoot(startDir, maxDepth = 3) {
376
414
  projectRoot: best.projectRoot,
377
415
  };
378
416
  }
379
- function getOutputPaths(cwd, framework) {
380
- const isNextApp = framework.hasAppRouter || framework.name === "next-app";
381
- const isNextPages = framework.hasPagesRouter || framework.name === "next-pages";
382
- const configPath = path.join(cwd, "duct.config.ts");
383
- let receiverPath;
384
- let tokenRoutePath;
385
- if (isNextApp) {
386
- receiverPath = path.join(cwd, "app", "api", "duct", "receive", "route.ts");
387
- tokenRoutePath = path.join(cwd, "app", "api", "duct", "token", "route.ts");
388
- }
389
- else if (isNextPages) {
390
- receiverPath = path.join(cwd, "pages", "api", "duct", "receive.ts");
391
- tokenRoutePath = path.join(cwd, "pages", "api", "duct", "token.ts");
392
- }
393
- else if (framework.name === "remix") {
394
- receiverPath = path.join(cwd, "app", "routes", "api.duct.receive.ts");
395
- tokenRoutePath = path.join(cwd, "app", "routes", "api.duct.token.ts");
396
- }
397
- else if (framework.name === "sveltekit") {
398
- receiverPath = path.join(cwd, "src", "routes", "api", "duct", "receive", "+server.ts");
399
- tokenRoutePath = path.join(cwd, "src", "routes", "api", "duct", "token", "+server.ts");
400
- }
401
- else {
402
- receiverPath = path.join(cwd, "server", "routes", "duct-receive.ts");
403
- tokenRoutePath = path.join(cwd, "server", "routes", "duct-token.ts");
404
- }
405
- const shellComponentPath = isNextApp || isNextPages
406
- ? path.join(cwd, "components", "DuctShell.tsx")
407
- : framework.name === "remix"
408
- ? path.join(cwd, "app", "components", "DuctShell.tsx")
409
- : framework.name === "sveltekit"
410
- ? path.join(cwd, "src", "lib", "components", "DuctShell.svelte")
411
- : path.join(cwd, "src", "components", "DuctShell.tsx");
412
- const envTemplatePath = path.join(cwd, getEnvTemplateName(framework));
413
- return {
414
- configPath,
415
- receiverPath,
416
- tokenRoutePath,
417
- shellComponentPath,
418
- envTemplatePath,
419
- };
420
- }
421
417
  // ----------------------------------------------------------------
422
418
  // pushManifest
423
419
  // ----------------------------------------------------------------
@@ -672,6 +668,23 @@ export async function runInit(opts = {}) {
672
668
  const authSpinner = ora("Detecting auth system...").start();
673
669
  const authDetection = await detectAuth(sandboxFs);
674
670
  authSpinner.succeed(`Auth detected: ${authDisplay(authDetection.system)}`);
671
+ let thirdPartyAgentMode = "none";
672
+ if (!yes && !opts.manual) {
673
+ const { partnerAgents } = await inquirer.prompt([
674
+ {
675
+ type: "list",
676
+ name: "partnerAgents",
677
+ message: "Will third-party AI agents act on behalf of your users?",
678
+ choices: [
679
+ { name: "No — human shell only (default)", value: "none" },
680
+ { name: "Yes — Duct consent tokens (uct_)", value: "duct-consent" },
681
+ { name: "Yes — we use company OAuth delegation", value: "oauth" },
682
+ ],
683
+ default: "none",
684
+ },
685
+ ]);
686
+ thirdPartyAgentMode = partnerAgents;
687
+ }
675
688
  // ---- Step 3: Gather basic info ----
676
689
  let shellId;
677
690
  let productName;
@@ -984,10 +997,14 @@ export async function runInit(opts = {}) {
984
997
  routes: reviewed.routes,
985
998
  deeplinks: reviewed.deeplinks,
986
999
  auth: reviewed.auth,
1000
+ intershell_enabled: reviewed.intershell_enabled,
1001
+ registry_visibility: reviewed.registry_visibility,
987
1002
  };
988
1003
  }
989
1004
  // Show what will be generated
990
- const outputPaths = getOutputPaths(projectRoot, framework);
1005
+ const outputPaths = getGeneratedOutputPaths(projectRoot, framework);
1006
+ const wiringPlan = buildWiringPlan(outputPaths, framework, authDetection, thirdPartyAgentMode);
1007
+ printWiringPlan(projectRoot, wiringPlan);
991
1008
  console.log(chalk.bold("\n Writing files to your project\n"));
992
1009
  console.log(chalk.gray(` ${path.relative(cwd, outputPaths.configPath).padEnd(22)} manifest`));
993
1010
  console.log(chalk.gray(` ${path.relative(cwd, outputPaths.receiverPath).padEnd(22)} receiver route`));
@@ -1074,6 +1091,13 @@ export async function runInit(opts = {}) {
1074
1091
  // ---- Step 7: Write files ----
1075
1092
  const logoUrl = await detectLogoUrl(projectRoot);
1076
1093
  const config = buildDuctConfigFromPipeline(reviewedPipelineResult, shellId, productName, baseUrl, logoUrl, apiBaseUrl, industry, prismaDataModel);
1094
+ const validation = validateDuctConfigStrict(config);
1095
+ if (!validation.ok) {
1096
+ displayConfigValidationIssues(validation.issues);
1097
+ console.log(chalk.red(" Aborted. The generated manifest failed validation — no files were written.\n" +
1098
+ " Re-run init after fixing the detected issues, or use --manual for a template.\n"));
1099
+ return;
1100
+ }
1077
1101
  const isManualMode = Boolean(opts.manual) || process.argv.includes("--manual");
1078
1102
  const configContent = (noAgents && isManualMode)
1079
1103
  ? generateManualTemplate({
@@ -1093,6 +1117,10 @@ export async function runInit(opts = {}) {
1093
1117
  await writeFile(outputPaths.receiverPath, receiverContent, dryRun);
1094
1118
  await writeFile(outputPaths.tokenRoutePath, tokenRouteContent, dryRun);
1095
1119
  await writeFile(outputPaths.shellComponentPath, shellContent, dryRun);
1120
+ await writeFile(path.join(projectRoot, wiringPlan.middlewareSnippetPath), wiringPlan.middlewareSnippet, dryRun);
1121
+ if (wiringPlan.uctSnippet && wiringPlan.uctSnippetPath) {
1122
+ await writeFile(path.join(projectRoot, wiringPlan.uctSnippetPath), wiringPlan.uctSnippet, dryRun);
1123
+ }
1096
1124
  // Safely append to the env template
1097
1125
  const envExists = await fileExists(outputPaths.envTemplatePath);
1098
1126
  if (envExists) {
@@ -1130,12 +1158,30 @@ export async function runInit(opts = {}) {
1130
1158
  }
1131
1159
  // ---- Post-write validation: token endpoint path ----
1132
1160
  const expectedTokenPath = "/api/duct/token";
1133
- const configuredTokenPath = reviewedPipelineResult.auth.tokenEndpoint;
1134
- if (configuredTokenPath && configuredTokenPath !== expectedTokenPath) {
1161
+ const configuredTokenPath = config.auth.tokenEndpoint;
1162
+ if (configuredTokenPath &&
1163
+ !configuredTokenPath.endsWith(expectedTokenPath) &&
1164
+ !configuredTokenPath.includes(`${expectedTokenPath}`)) {
1135
1165
  console.log(chalk.yellow(` ⚠ Token endpoint mismatch: config says '${configuredTokenPath}' but generated route is at '${expectedTokenPath}'`));
1136
1166
  console.log(chalk.gray(" Update auth.tokenEndpoint in duct.config.ts if this is intentional.\n"));
1137
1167
  }
1138
1168
  console.log(chalk.green("\n ✓ Files written successfully!\n"));
1169
+ const auditIssues = await runIntegrationAudit(sandboxFs, {
1170
+ projectRoot,
1171
+ config,
1172
+ framework,
1173
+ outputPaths,
1174
+ authDetection,
1175
+ thirdPartyAgentMode,
1176
+ });
1177
+ printIntegrationAuditIssues(auditIssues);
1178
+ if (integrationAuditFailed(auditIssues)) {
1179
+ console.log(chalk.yellow(" ⚠ Integration audit found blocking issues — fix the items above before `duct push`.\n"));
1180
+ }
1181
+ if (sideEffectActionsApproved(config)) {
1182
+ console.log(chalk.bold(" Webhooks (recommended):"));
1183
+ console.log(chalk.gray(" Side-effect actions detected — configure confirmation webhooks in Dashboard → Shell → Settings → Webhooks.\n"));
1184
+ }
1139
1185
  // ---- Post-write validation: receiver route health check ----
1140
1186
  if (baseUrl) {
1141
1187
  const receiverUrl = `${baseUrl.replace(/\/$/, "")}/api/duct/receive`;
@@ -1170,15 +1216,16 @@ export async function runInit(opts = {}) {
1170
1216
  console.log(chalk.yellow("\n ⚠ Set DUCT_API_KEY to auto-push, or run `npx duct push` manually."));
1171
1217
  }
1172
1218
  const dashboard = getConfiguredDashboard(auth);
1173
- const docsBase = dashboard.replace(/(app|dashboard)\./, "docs.");
1219
+ const docsBase = getDocsUrl();
1174
1220
  console.log(chalk.bold(`\n ◆ Shell is live\n`));
1175
1221
  console.log(` Shell ID ${chalk.cyan(shellId)}`);
1176
1222
  console.log(` Manifest synced · ${config.routes?.length ?? 0} routes · ${config.actions?.length ?? 0} actions · ${config.deeplinks?.length ?? 0} deeplinks`);
1177
1223
  console.log(` Status registered with Duct cloud\n`);
1178
1224
  console.log(` Next:`);
1179
1225
  console.log(` 1. Review duct.config.ts — set agentAccessible flags on your actions`);
1180
- console.log(` 2. Mount <DuctShell /> in your root layout (see duct/shell.tsx)`);
1181
- console.log(` 3. Confirm the receiver route is reachable at /duct/receive\n`);
1226
+ console.log(` 2. Mount <DuctShell /> in your root layout (see ${path.relative(projectRoot, outputPaths.shellComponentPath)})`);
1227
+ console.log(` 3. Wire verifyDuctToken from ${wiringPlan.middlewareSnippetPath} into ${authDetection.middlewarePath ?? "your API middleware"}`);
1228
+ console.log(` 4. Run \`npx duct checkup\` to re-run the integration audit\n`);
1182
1229
  console.log(` Docs ${docsBase}/quickstart`);
1183
1230
  console.log(` Support ${dashboard}/discord`);
1184
1231
  console.log(chalk.gray(` ─────────────────────────────────────────────────────────────\n`));
@@ -0,0 +1,10 @@
1
+ import type { FrameworkInfo } from "./detectors/framework.js";
2
+ export interface GeneratedOutputPaths {
3
+ configPath: string;
4
+ receiverPath: string;
5
+ tokenRoutePath: string;
6
+ shellComponentPath: string;
7
+ envTemplatePath: string;
8
+ }
9
+ export declare function getGeneratedOutputPaths(cwd: string, framework: FrameworkInfo): GeneratedOutputPaths;
10
+ export declare function relativeOutputPaths(cwd: string, paths: GeneratedOutputPaths): GeneratedOutputPaths;
@@ -0,0 +1,60 @@
1
+ // ============================================================
2
+ // @duct/sdk — Generated file path resolution
3
+ // ============================================================
4
+ import * as path from "path";
5
+ function getEnvTemplateName(framework) {
6
+ if (framework.name === "vite-react" || framework.name === "remix") {
7
+ return ".env.example";
8
+ }
9
+ return ".env.local.example";
10
+ }
11
+ export function getGeneratedOutputPaths(cwd, framework) {
12
+ const isNextApp = framework.hasAppRouter || framework.name === "next-app";
13
+ const isNextPages = framework.hasPagesRouter || framework.name === "next-pages";
14
+ const configPath = path.join(cwd, "duct.config.ts");
15
+ let receiverPath;
16
+ let tokenRoutePath;
17
+ if (isNextApp) {
18
+ receiverPath = path.join(cwd, "app", "api", "duct", "receive", "route.ts");
19
+ tokenRoutePath = path.join(cwd, "app", "api", "duct", "token", "route.ts");
20
+ }
21
+ else if (isNextPages) {
22
+ receiverPath = path.join(cwd, "pages", "api", "duct", "receive.ts");
23
+ tokenRoutePath = path.join(cwd, "pages", "api", "duct", "token.ts");
24
+ }
25
+ else if (framework.name === "remix") {
26
+ receiverPath = path.join(cwd, "app", "routes", "api.duct.receive.ts");
27
+ tokenRoutePath = path.join(cwd, "app", "routes", "api.duct.token.ts");
28
+ }
29
+ else if (framework.name === "sveltekit") {
30
+ receiverPath = path.join(cwd, "src", "routes", "api", "duct", "receive", "+server.ts");
31
+ tokenRoutePath = path.join(cwd, "src", "routes", "api", "duct", "token", "+server.ts");
32
+ }
33
+ else {
34
+ receiverPath = path.join(cwd, "server", "routes", "duct-receive.ts");
35
+ tokenRoutePath = path.join(cwd, "server", "routes", "duct-token.ts");
36
+ }
37
+ const shellComponentPath = isNextApp || isNextPages
38
+ ? path.join(cwd, "components", "DuctShell.tsx")
39
+ : framework.name === "remix"
40
+ ? path.join(cwd, "app", "components", "DuctShell.tsx")
41
+ : framework.name === "sveltekit"
42
+ ? path.join(cwd, "src", "lib", "components", "DuctShell.svelte")
43
+ : path.join(cwd, "src", "components", "DuctShell.tsx");
44
+ return {
45
+ configPath,
46
+ receiverPath,
47
+ tokenRoutePath,
48
+ shellComponentPath,
49
+ envTemplatePath: path.join(cwd, getEnvTemplateName(framework)),
50
+ };
51
+ }
52
+ export function relativeOutputPaths(cwd, paths) {
53
+ return {
54
+ configPath: path.relative(cwd, paths.configPath),
55
+ receiverPath: path.relative(cwd, paths.receiverPath),
56
+ tokenRoutePath: path.relative(cwd, paths.tokenRoutePath),
57
+ shellComponentPath: path.relative(cwd, paths.shellComponentPath),
58
+ envTemplatePath: path.relative(cwd, paths.envTemplatePath),
59
+ };
60
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,24 @@
1
+ import { describe, it } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { parseCurlCommand, parseCurlCollection } from './curl-parser.js';
4
+ describe('curl-parser', () => {
5
+ it('parses a simple GET curl command', () => {
6
+ const req = parseCurlCommand("curl -X GET 'https://api.example.com/v1/orders'");
7
+ assert.ok(req);
8
+ assert.equal(req.method, 'GET');
9
+ assert.equal(req.path, '/v1/orders');
10
+ });
11
+ it('parses POST with JSON body', () => {
12
+ const req = parseCurlCommand('curl -X POST https://api.example.com/v1/orders -d \'{"sku":"ABC"}\'');
13
+ assert.ok(req);
14
+ assert.equal(req.method, 'POST');
15
+ assert.deepEqual(req.body, { sku: 'ABC' });
16
+ });
17
+ it('parses a shell script with multiple curls', async () => {
18
+ const content = `curl -X GET 'https://api.example.com/users'
19
+ curl -X DELETE 'https://api.example.com/users/1'`;
20
+ const result = await parseCurlCollection(content, 'api.sh');
21
+ assert.equal(result.requestCount, 2);
22
+ assert.equal(result.actions.length, 2);
23
+ });
24
+ });
@@ -0,0 +1,23 @@
1
+ import type { SandboxFS } from "../fs/sandbox.js";
2
+ import type { AuthDetectionResult } from "../detectors/auth.js";
3
+ import type { FrameworkInfo } from "../detectors/framework.js";
4
+ import type { DuctConfig } from "../../core/types.js";
5
+ import type { GeneratedOutputPaths } from "../output-paths.js";
6
+ import { type ThirdPartyAgentMode } from "../generators/wiring-snippets.js";
7
+ export interface IntegrationAuditIssue {
8
+ severity: "error" | "warning" | "info";
9
+ area: string;
10
+ issue: string;
11
+ fix: string;
12
+ }
13
+ export interface IntegrationAuditContext {
14
+ projectRoot: string;
15
+ config: DuctConfig;
16
+ framework: FrameworkInfo;
17
+ outputPaths: GeneratedOutputPaths;
18
+ authDetection: AuthDetectionResult;
19
+ thirdPartyAgentMode?: ThirdPartyAgentMode;
20
+ }
21
+ export declare function runIntegrationAudit(sandboxFs: SandboxFS, ctx: IntegrationAuditContext): Promise<IntegrationAuditIssue[]>;
22
+ export declare function printIntegrationAuditIssues(issues: IntegrationAuditIssue[]): void;
23
+ export declare function integrationAuditFailed(issues: IntegrationAuditIssue[]): boolean;
@@ -0,0 +1,208 @@
1
+ // ============================================================
2
+ // @duct/sdk — Post-init / checkup integration self-audit
3
+ // ============================================================
4
+ import * as path from "path";
5
+ import { projectUsesVerifyDuctToken, } from "../generators/wiring-snippets.js";
6
+ const LAYOUT_CANDIDATES = [
7
+ "app/layout.tsx",
8
+ "app/layout.jsx",
9
+ "src/app/layout.tsx",
10
+ "pages/_app.tsx",
11
+ "pages/_app.jsx",
12
+ "app/root.tsx",
13
+ "src/routes/+layout.svelte",
14
+ "src/App.tsx",
15
+ ];
16
+ export async function runIntegrationAudit(sandboxFs, ctx) {
17
+ const issues = [];
18
+ const rel = (absolutePath) => path.relative(ctx.projectRoot, absolutePath);
19
+ if (!(await sandboxFs.exists(rel(ctx.outputPaths.configPath)))) {
20
+ issues.push({
21
+ severity: "error",
22
+ area: "manifest",
23
+ issue: "duct.config.ts is missing",
24
+ fix: "Run `npx duct init` or restore duct.config.ts",
25
+ });
26
+ }
27
+ const tokenExists = await sandboxFs.exists(rel(ctx.outputPaths.tokenRoutePath));
28
+ if (!tokenExists) {
29
+ issues.push({
30
+ severity: "error",
31
+ area: "token route",
32
+ issue: `Token route not found at ${rel(ctx.outputPaths.tokenRoutePath)}`,
33
+ fix: "Re-run init or create POST /api/duct/token calling generateDuctToken",
34
+ });
35
+ }
36
+ else {
37
+ const tokenContent = await sandboxFs.readFile(rel(ctx.outputPaths.tokenRoutePath));
38
+ if (tokenContent && !tokenContent.includes("generateDuctToken")) {
39
+ issues.push({
40
+ severity: "error",
41
+ area: "token route",
42
+ issue: "Token route does not call generateDuctToken",
43
+ fix: `Update ${rel(ctx.outputPaths.tokenRoutePath)} to import from @duct-sdk/sdk/server`,
44
+ });
45
+ }
46
+ if (tokenContent && !tokenContent.includes("@duct-sdk/sdk/server")) {
47
+ issues.push({
48
+ severity: "warning",
49
+ area: "token route",
50
+ issue: "Token route may import from @duct-sdk/sdk root (crashes in Node)",
51
+ fix: "Use `import { generateDuctToken } from \"@duct-sdk/sdk/server\"`",
52
+ });
53
+ }
54
+ }
55
+ const receiverExists = await sandboxFs.exists(rel(ctx.outputPaths.receiverPath));
56
+ if (!receiverExists) {
57
+ issues.push({
58
+ severity: "error",
59
+ area: "deeplink receiver",
60
+ issue: `Receiver route missing at ${rel(ctx.outputPaths.receiverPath)}`,
61
+ fix: "Create POST /api/duct/receive API route with verifyDeeplinkToken",
62
+ });
63
+ }
64
+ else {
65
+ const receiverContent = await sandboxFs.readFile(rel(ctx.outputPaths.receiverPath));
66
+ if (receiverContent && !receiverContent.includes("verifyDeeplinkToken")) {
67
+ issues.push({
68
+ severity: "warning",
69
+ area: "deeplink receiver",
70
+ issue: "Receiver does not call verifyDeeplinkToken",
71
+ fix: "Verify deeplink JWT server-side before applying state",
72
+ });
73
+ }
74
+ }
75
+ const badReceiverPage = await sandboxFs.exists("app/duct/receive/page.tsx");
76
+ if (badReceiverPage) {
77
+ issues.push({
78
+ severity: "error",
79
+ area: "deeplink receiver",
80
+ issue: "Deeplink receiver exists as a client page (app/duct/receive/page.tsx)",
81
+ fix: "Use POST /api/duct/receive API route instead of a page component",
82
+ });
83
+ }
84
+ const hasMiddleware = await projectUsesVerifyDuctToken(sandboxFs);
85
+ if (!hasMiddleware) {
86
+ issues.push({
87
+ severity: "warning",
88
+ area: "middleware",
89
+ issue: "No verifyDuctToken fallback found in API auth middleware",
90
+ fix: `Add the snippet from .duct/snippets/verify-duct-token.ts to ${ctx.authDetection.middlewarePath ?? "your auth middleware"}`,
91
+ });
92
+ }
93
+ let shellMounted = false;
94
+ for (const layout of LAYOUT_CANDIDATES) {
95
+ const content = await sandboxFs.readFile(layout);
96
+ if (content && /DuctShell|DuctShellEmbed/.test(content)) {
97
+ shellMounted = true;
98
+ break;
99
+ }
100
+ }
101
+ if (!shellMounted) {
102
+ issues.push({
103
+ severity: "warning",
104
+ area: "embed",
105
+ issue: "DuctShell / DuctShellEmbed not found in root layout",
106
+ fix: `Mount the generated shell component once in ${LAYOUT_CANDIDATES[0]}`,
107
+ });
108
+ }
109
+ const envContent = (await sandboxFs.readFile(".env.local.example")) ??
110
+ (await sandboxFs.readFile(".env.example"));
111
+ if (!envContent?.includes("DUCT_SECRET_KEY")) {
112
+ issues.push({
113
+ severity: "warning",
114
+ area: "env",
115
+ issue: "DUCT_SECRET_KEY missing from env template",
116
+ fix: `Add DUCT_SECRET_KEY and DUCT_SHELL_ID to ${rel(ctx.outputPaths.envTemplatePath)}`,
117
+ });
118
+ }
119
+ if (envContent && /NEXT_PUBLIC_DUCT_SECRET|VITE_DUCT_SECRET|PUBLIC_DUCT_SECRET/.test(envContent)) {
120
+ issues.push({
121
+ severity: "error",
122
+ area: "env",
123
+ issue: "DUCT_SECRET_KEY appears in a client-exposed env var prefix",
124
+ fix: "Keep DUCT_SECRET_KEY server-only; use NEXT_PUBLIC_DUCT_SHELL_ID for the shell ID",
125
+ });
126
+ }
127
+ const routePaths = new Set((ctx.config.routes ?? []).map((route) => route.path));
128
+ for (const deeplink of ctx.config.deeplinks ?? []) {
129
+ const normalizedTarget = deeplink.targetRoute.replace(/\[([^\]]+)\]/g, ":$1");
130
+ const normalizedRoutes = [...routePaths].map((routePath) => routePath.replace(/\[([^\]]+)\]/g, ":$1"));
131
+ if (!routePaths.has(deeplink.targetRoute) &&
132
+ !normalizedRoutes.includes(normalizedTarget)) {
133
+ issues.push({
134
+ severity: "error",
135
+ area: "deeplinks",
136
+ issue: `Deeplink "${deeplink.id}" targets unknown route ${deeplink.targetRoute}`,
137
+ fix: "Add the route to routes[] or fix deeplink.targetRoute",
138
+ });
139
+ }
140
+ }
141
+ if (ctx.config.auth.tokenEndpoint) {
142
+ const expectedSuffix = "/api/duct/token";
143
+ if (!ctx.config.auth.tokenEndpoint.endsWith(expectedSuffix) &&
144
+ !ctx.config.auth.tokenEndpoint.includes(expectedSuffix)) {
145
+ issues.push({
146
+ severity: "warning",
147
+ area: "auth",
148
+ issue: `auth.tokenEndpoint (${ctx.config.auth.tokenEndpoint}) may not match generated route`,
149
+ fix: `Align token route path with auth.tokenEndpoint (${rel(ctx.outputPaths.tokenRoutePath)})`,
150
+ });
151
+ }
152
+ }
153
+ if (ctx.thirdPartyAgentMode === "duct-consent") {
154
+ const uctSnippet = await sandboxFs.readFile(".duct/snippets/uct-consent-auth.ts");
155
+ const hasUct = uctSnippet !== null ||
156
+ (await projectUsesVerifyDuctToken(sandboxFs)) ||
157
+ (await fileContains(sandboxFs, "uct_")) ||
158
+ (await fileContains(sandboxFs, "verify/consent-token"));
159
+ if (!hasUct) {
160
+ issues.push({
161
+ severity: "warning",
162
+ area: "agents",
163
+ issue: "Third-party agents enabled but no uct_ verification middleware detected",
164
+ fix: "Wire .duct/snippets/uct-consent-auth.ts into your API auth chain",
165
+ });
166
+ }
167
+ }
168
+ const requiresAuthActions = (ctx.config.actions ?? []).filter((action) => action.requiresAuth);
169
+ if (ctx.thirdPartyAgentMode === "none" &&
170
+ requiresAuthActions.length > 0 &&
171
+ !(await fileContains(sandboxFs, "verify/consent-token"))) {
172
+ issues.push({
173
+ severity: "info",
174
+ area: "agents",
175
+ issue: "Human shell works with duct_delegated only; partner agents need uct_ or OAuth",
176
+ fix: "Re-run init and choose third-party agent support, or see DUCT_CONFIG_PROMPT.md Phase 4b",
177
+ });
178
+ }
179
+ return issues;
180
+ }
181
+ async function fileContains(sandboxFs, needle) {
182
+ const files = await sandboxFs.findFiles("**/*.{ts,tsx,js,jsx}", { maxFiles: 150 });
183
+ for (const file of files) {
184
+ const content = await sandboxFs.readFile(file);
185
+ if (content?.includes(needle))
186
+ return true;
187
+ }
188
+ return false;
189
+ }
190
+ export function printIntegrationAuditIssues(issues) {
191
+ if (issues.length === 0) {
192
+ return;
193
+ }
194
+ console.log("\n Integration audit:\n");
195
+ console.log(" | Severity | Area | Issue");
196
+ console.log(" |----------|-----------------|------");
197
+ for (const issue of issues) {
198
+ console.log(` | ${issue.severity.padEnd(8)} | ${issue.area.slice(0, 15).padEnd(15)} | ${issue.issue.slice(0, 60)}`);
199
+ }
200
+ console.log("\n Fixes:");
201
+ for (const issue of issues) {
202
+ console.log(` • [${issue.area}] ${issue.fix}`);
203
+ }
204
+ console.log("");
205
+ }
206
+ export function integrationAuditFailed(issues) {
207
+ return issues.some((issue) => issue.severity === "error");
208
+ }
@@ -0,0 +1 @@
1
+ export {};