@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
@@ -0,0 +1,235 @@
1
+ // ============================================================
2
+ // @duct/sdk — Token route generator (auth-strategy aware)
3
+ // ============================================================
4
+ function guestGuard(guestAllowed) {
5
+ if (guestAllowed) {
6
+ return ` // Guest users allowed — empty session mints a limited delegated token.
7
+ // Set auth.guestAllowed: false in duct.config.ts to require login before minting.`;
8
+ }
9
+ return ` if (!userSession || Object.keys(userSession).length === 0) {
10
+ return unauthorized("Unauthorized");
11
+ }`;
12
+ }
13
+ function nextAuthSessionLookup(strategy, framework) {
14
+ if (strategy === "clerk") {
15
+ return {
16
+ imports: `import { currentUser } from "@clerk/nextjs/server";`,
17
+ lookup: ` const user = await currentUser();`,
18
+ userSessionExpr: `user
19
+ ? {
20
+ userId: user.id,
21
+ email: user.emailAddresses[0]?.emailAddress,
22
+ name: user.fullName ?? undefined,
23
+ }
24
+ : {}`,
25
+ };
26
+ }
27
+ if (strategy === "auth0") {
28
+ return {
29
+ imports: `import { getSession } from "@auth0/nextjs-auth0";`,
30
+ lookup: ` const session = await getSession();`,
31
+ userSessionExpr: `(session?.user as Record<string, unknown> | undefined) ?? {}`,
32
+ };
33
+ }
34
+ if (strategy === "nextauth") {
35
+ if (framework.hasAppRouter || framework.name === "next-app") {
36
+ return {
37
+ imports: `import { auth } from "@/auth";
38
+ // Fallback for NextAuth v4: import { getServerSession } from "next-auth";`,
39
+ lookup: ` const session = await auth().catch(async () => {
40
+ const { getServerSession } = await import("next-auth");
41
+ return getServerSession();
42
+ });`,
43
+ userSessionExpr: `(session?.user as Record<string, unknown> | undefined) ?? {}`,
44
+ };
45
+ }
46
+ return {
47
+ imports: `import { getServerSession } from "next-auth";`,
48
+ lookup: ` const session = await getServerSession(req, res, {});`,
49
+ userSessionExpr: `(session?.user as Record<string, unknown> | undefined) ?? {}`,
50
+ };
51
+ }
52
+ if (strategy === "session-cookie") {
53
+ return {
54
+ imports: `// import { getIronSession } from "iron-session";`,
55
+ lookup: ` // const session = await getIronSession(req, res, sessionOptions);`,
56
+ userSessionExpr: `{} // TODO: map your session object here`,
57
+ };
58
+ }
59
+ if (strategy === "custom-jwt") {
60
+ return {
61
+ imports: ``,
62
+ lookup: ` // Decode your app JWT from cookies/Authorization if present`,
63
+ userSessionExpr: `{} // TODO: map decoded JWT claims`,
64
+ };
65
+ }
66
+ return {
67
+ imports: `// No auth library detected — wire your session lookup below`,
68
+ lookup: ` // Example: const session = await getSession(request);`,
69
+ userSessionExpr: `{}`,
70
+ };
71
+ }
72
+ export function generateStrategyTokenRoute(framework, options) {
73
+ const expiry = options.tokenExpirySeconds ?? 300;
74
+ const guestBlock = guestGuard(options.guestAllowed);
75
+ if (framework.name === "sveltekit") {
76
+ return `// src/routes/api/duct/token/+server.ts
77
+ import type { RequestHandler } from "@sveltejs/kit";
78
+ import { json } from "@sveltejs/kit";
79
+ import { generateDuctToken } from "@duct-sdk/sdk/server";
80
+
81
+ export const POST: RequestHandler = async ({ locals }) => {
82
+ const secretKey = process.env.DUCT_SECRET_KEY;
83
+ const shellId = process.env.PUBLIC_DUCT_SHELL_ID || process.env.DUCT_SHELL_ID;
84
+
85
+ if (!secretKey || !shellId) {
86
+ return json({ error: "Duct not configured" }, { status: 500 });
87
+ }
88
+
89
+ const userSession = ((locals as Record<string, unknown>).user ?? {}) as Record<string, unknown>;
90
+ ${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'return json({ error: "Unauthorized" }, { status: 401 })')}
91
+
92
+ const { token, expiresAt } = await generateDuctToken({
93
+ secretKey,
94
+ shellId,
95
+ userSession,
96
+ expirySeconds: ${expiry},
97
+ });
98
+
99
+ return json({ token, expiresAt: expiresAt.toISOString() });
100
+ };
101
+ `;
102
+ }
103
+ if (framework.name === "remix") {
104
+ return `// app/routes/api.duct.token.ts
105
+ import type { ActionFunctionArgs } from "@remix-run/node";
106
+ import { json } from "@remix-run/node";
107
+ import { generateDuctToken } from "@duct-sdk/sdk/server";
108
+
109
+ export async function action({ request }: ActionFunctionArgs) {
110
+ if (request.method !== "POST") {
111
+ return json({ error: "Method not allowed" }, { status: 405 });
112
+ }
113
+
114
+ const secretKey = process.env.DUCT_SECRET_KEY;
115
+ const shellId = process.env.VITE_DUCT_SHELL_ID ?? process.env.DUCT_SHELL_ID;
116
+
117
+ if (!secretKey || !shellId) {
118
+ return json({ error: "Duct not configured" }, { status: 500 });
119
+ }
120
+
121
+ // Wire your Remix session (e.g. getSession from remix-auth)
122
+ const userSession: Record<string, unknown> = {};
123
+ ${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'return json({ error: "Unauthorized" }, { status: 401 })')}
124
+
125
+ const { token, expiresAt } = await generateDuctToken({
126
+ secretKey,
127
+ shellId,
128
+ userSession,
129
+ expirySeconds: ${expiry},
130
+ });
131
+
132
+ return json({ token, expiresAt: expiresAt.toISOString() });
133
+ }
134
+ `;
135
+ }
136
+ if (framework.name === "vite-react") {
137
+ return `// server/routes/duct-token.ts
138
+ import { Router } from "express";
139
+ import { generateDuctToken } from "@duct-sdk/sdk/server";
140
+
141
+ const router = Router();
142
+
143
+ router.post("/api/duct/token", async (req, res) => {
144
+ const secretKey = process.env.DUCT_SECRET_KEY;
145
+ const shellId = process.env.DUCT_SHELL_ID;
146
+
147
+ if (!secretKey || !shellId) {
148
+ return res.status(500).json({ error: "Duct not configured" });
149
+ }
150
+
151
+ const userSession = (req as typeof req & { user?: Record<string, unknown> }).user ?? {};
152
+ ${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'return res.status(401).json({ error: "Unauthorized" })')}
153
+
154
+ const { token, expiresAt } = await generateDuctToken({
155
+ secretKey,
156
+ shellId,
157
+ userSession,
158
+ expirySeconds: ${expiry},
159
+ });
160
+
161
+ return res.status(200).json({ token, expiresAt: expiresAt.toISOString() });
162
+ });
163
+
164
+ export default router;
165
+ `;
166
+ }
167
+ const auth = nextAuthSessionLookup(options.authStrategy, framework);
168
+ if (framework.hasAppRouter || framework.name === "next-app") {
169
+ return `// app/api/duct/token/route.ts
170
+ import { NextRequest, NextResponse } from "next/server";
171
+ import { generateDuctToken } from "@duct-sdk/sdk/server";
172
+ ${auth.imports}
173
+
174
+ function unauthorized(message: string) {
175
+ return NextResponse.json({ error: message }, { status: 401 });
176
+ }
177
+
178
+ export async function POST(_request: NextRequest) {
179
+ const secretKey = process.env.DUCT_SECRET_KEY;
180
+ const shellId = process.env.NEXT_PUBLIC_DUCT_SHELL_ID ?? process.env.DUCT_SHELL_ID;
181
+
182
+ if (!secretKey || !shellId) {
183
+ return NextResponse.json({ error: "Duct not configured" }, { status: 500 });
184
+ }
185
+
186
+ ${auth.lookup}
187
+ const userSession = ${auth.userSessionExpr};
188
+ ${guestBlock}
189
+
190
+ const { token, expiresAt } = await generateDuctToken({
191
+ secretKey,
192
+ shellId,
193
+ userSession,
194
+ expirySeconds: ${expiry},
195
+ });
196
+
197
+ return NextResponse.json({ token, expiresAt: expiresAt.toISOString() });
198
+ }
199
+ `;
200
+ }
201
+ return `// pages/api/duct/token.ts
202
+ import type { NextApiRequest, NextApiResponse } from "next";
203
+ import { generateDuctToken } from "@duct-sdk/sdk/server";
204
+ ${auth.imports}
205
+
206
+ type TokenResponse = { token?: string; expiresAt?: string; error?: string };
207
+
208
+ export default async function handler(req: NextApiRequest, res: NextApiResponse<TokenResponse>) {
209
+ if (req.method !== "POST") {
210
+ res.setHeader("Allow", "POST");
211
+ return res.status(405).json({ error: "Method not allowed" });
212
+ }
213
+
214
+ const secretKey = process.env.DUCT_SECRET_KEY;
215
+ const shellId = process.env.NEXT_PUBLIC_DUCT_SHELL_ID ?? process.env.DUCT_SHELL_ID;
216
+
217
+ if (!secretKey || !shellId) {
218
+ return res.status(500).json({ error: "Duct not configured" });
219
+ }
220
+
221
+ ${auth.lookup}
222
+ const userSession = ${auth.userSessionExpr};
223
+ ${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'return res.status(401).json({ error: "Unauthorized" })')}
224
+
225
+ const { token, expiresAt } = await generateDuctToken({
226
+ secretKey,
227
+ shellId,
228
+ userSession,
229
+ expirySeconds: ${expiry},
230
+ });
231
+
232
+ return res.status(200).json({ token, expiresAt: expiresAt.toISOString() });
233
+ }
234
+ `;
235
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,53 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { generateStrategyTokenRoute } from "./token-route.js";
4
+ function nextAppFramework() {
5
+ return {
6
+ name: "next-app",
7
+ version: "14.0.0",
8
+ hasAppRouter: true,
9
+ hasPagesRouter: false,
10
+ packageManager: "npm",
11
+ srcDir: ".",
12
+ };
13
+ }
14
+ describe("generateStrategyTokenRoute", () => {
15
+ it("includes clerk session lookup for clerk strategy", () => {
16
+ const code = generateStrategyTokenRoute(nextAppFramework(), {
17
+ authStrategy: "clerk",
18
+ guestAllowed: true,
19
+ });
20
+ assert.match(code, /@clerk\/nextjs\/server/);
21
+ assert.match(code, /currentUser/);
22
+ assert.match(code, /generateDuctToken/);
23
+ assert.match(code, /@duct-sdk\/sdk\/server/);
24
+ });
25
+ it("returns 401 when guestAllowed is false and session is empty", () => {
26
+ const code = generateStrategyTokenRoute(nextAppFramework(), {
27
+ authStrategy: "nextauth",
28
+ guestAllowed: false,
29
+ });
30
+ assert.match(code, /Object\.keys\(userSession\)\.length === 0/);
31
+ assert.match(code, /status: 401/);
32
+ });
33
+ it("allows guest minting when guestAllowed is true", () => {
34
+ const code = generateStrategyTokenRoute(nextAppFramework(), {
35
+ authStrategy: "nextauth",
36
+ guestAllowed: true,
37
+ });
38
+ assert.match(code, /Guest users allowed/);
39
+ assert.doesNotMatch(code, /Object\.keys\(userSession\)\.length === 0/);
40
+ });
41
+ it("generates express route for vite-react", () => {
42
+ const code = generateStrategyTokenRoute({
43
+ name: "vite-react",
44
+ version: "5.0.0",
45
+ hasAppRouter: false,
46
+ hasPagesRouter: false,
47
+ packageManager: "npm",
48
+ srcDir: "src",
49
+ }, { authStrategy: "custom-jwt", guestAllowed: false });
50
+ assert.match(code, /express/);
51
+ assert.match(code, /\/api\/duct\/token/);
52
+ });
53
+ });
@@ -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
+ export type ThirdPartyAgentMode = "none" | "duct-consent" | "oauth";
7
+ export interface WiringPlanItem {
8
+ path: string;
9
+ action: "create" | "modify" | "verify";
10
+ summary: string;
11
+ }
12
+ export interface WiringPlan {
13
+ items: WiringPlanItem[];
14
+ middlewareSnippetPath: string;
15
+ middlewareSnippet: string;
16
+ uctSnippetPath?: string;
17
+ uctSnippet?: string;
18
+ }
19
+ export declare function projectUsesVerifyDuctToken(sandboxFs: SandboxFS): Promise<boolean>;
20
+ export declare function generateVerifyDuctTokenMiddlewareSnippet(framework: FrameworkInfo, middlewarePath?: string): string;
21
+ export declare function generateUctVerificationSnippet(framework: FrameworkInfo): string;
22
+ export declare function buildWiringPlan(outputPaths: GeneratedOutputPaths, framework: FrameworkInfo, authDetection: AuthDetectionResult, thirdPartyAgentMode: ThirdPartyAgentMode): WiringPlan;
23
+ export declare function sideEffectActionsApproved(config: DuctConfig): boolean;
@@ -0,0 +1,233 @@
1
+ // ============================================================
2
+ // @duct/sdk — Middleware wiring snippets + wiring plan
3
+ // ============================================================
4
+ const MIDDLEWARE_CANDIDATES = [
5
+ "middleware.ts",
6
+ "middleware.js",
7
+ "src/middleware.ts",
8
+ "src/middleware.js",
9
+ "server/middleware/auth.ts",
10
+ "server/middleware/auth.js",
11
+ "lib/auth/middleware.ts",
12
+ "lib/auth.ts",
13
+ "src/lib/auth.ts",
14
+ "app/middleware.ts",
15
+ ];
16
+ export async function projectUsesVerifyDuctToken(sandboxFs) {
17
+ for (const candidate of MIDDLEWARE_CANDIDATES) {
18
+ const content = await sandboxFs.readFile(candidate);
19
+ if (content?.includes("verifyDuctToken")) {
20
+ return true;
21
+ }
22
+ }
23
+ const files = await sandboxFs.findFiles("**/*.{ts,tsx,js,jsx}", { maxFiles: 120 });
24
+ for (const file of files) {
25
+ if (!/middleware|auth|guard|protect/i.test(file))
26
+ continue;
27
+ const content = await sandboxFs.readFile(file);
28
+ if (content?.includes("verifyDuctToken")) {
29
+ return true;
30
+ }
31
+ }
32
+ return false;
33
+ }
34
+ export function generateVerifyDuctTokenMiddlewareSnippet(framework, middlewarePath) {
35
+ const target = middlewarePath ?? "your API auth middleware";
36
+ const isExpress = framework.name === "vite-react";
37
+ if (isExpress) {
38
+ return `/**
39
+ * Add to ${target} — verify Duct delegated tokens on proxied action calls.
40
+ * Import from @duct-sdk/sdk/server (not the root @duct-sdk/sdk export).
41
+ */
42
+ import type { Request, Response, NextFunction } from "express";
43
+ import { verifyDuctToken } from "@duct-sdk/sdk/server";
44
+
45
+ export async function ductDelegatedAuth(req: Request, res: Response, next: NextFunction) {
46
+ const authHeader = req.headers.authorization;
47
+ if (!authHeader?.startsWith("Bearer ")) {
48
+ return next();
49
+ }
50
+
51
+ const token = authHeader.slice(7);
52
+ const secretKey = process.env.DUCT_SECRET_KEY;
53
+ const shellId = process.env.DUCT_SHELL_ID;
54
+ if (!secretKey || !shellId) {
55
+ return res.status(500).json({ error: "Duct not configured" });
56
+ }
57
+
58
+ const result = await verifyDuctToken(token, { secretKey, expectedShellId: shellId });
59
+ if (!result.valid) {
60
+ return res.status(401).json({ error: result.error ?? "Invalid delegated token" });
61
+ }
62
+
63
+ (req as Request & { user?: Record<string, unknown> }).user = result.payload.session;
64
+ return next();
65
+ }
66
+ `;
67
+ }
68
+ return `/**
69
+ * Add to ${target} — fall back to verifyDuctToken when native session auth is absent.
70
+ * The agent proxy sends: Authorization: Bearer <duct_delegated>, X-Duct-Proxy: 1
71
+ */
72
+ import { verifyDuctToken } from "@duct-sdk/sdk/server";
73
+
74
+ export async function resolveUserFromRequest(request: Request): Promise<Record<string, unknown> | null> {
75
+ // 1) Try your native session/JWT first (NextAuth, Clerk, etc.)
76
+ // const session = await auth();
77
+ // if (session?.user) return session.user as Record<string, unknown>;
78
+
79
+ const authHeader = request.headers.get("authorization");
80
+ if (!authHeader?.startsWith("Bearer ")) {
81
+ return null;
82
+ }
83
+
84
+ const token = authHeader.slice(7);
85
+ const secretKey = process.env.DUCT_SECRET_KEY!;
86
+ const shellId = process.env.DUCT_SHELL_ID ?? process.env.NEXT_PUBLIC_DUCT_SHELL_ID!;
87
+
88
+ const result = await verifyDuctToken(token, { secretKey, expectedShellId: shellId });
89
+ if (!result.valid) {
90
+ throw new Error(result.error ?? "Invalid delegated token");
91
+ }
92
+
93
+ return result.payload.session;
94
+ }
95
+ `;
96
+ }
97
+ export function generateUctVerificationSnippet(framework) {
98
+ const isExpress = framework.name === "vite-react";
99
+ if (isExpress) {
100
+ return `/**
101
+ * Third-party agent user identity — verify Duct consent tokens (uct_).
102
+ * POST \${DUCT_AUTH_URL}/v1/verify/consent-token
103
+ */
104
+ import type { Request, Response, NextFunction } from "express";
105
+ import { verifyDuctToken } from "@duct-sdk/sdk/server";
106
+
107
+ const DUCT_AUTH_URL = process.env.DUCT_AUTH_URL ?? "http://localhost:3001";
108
+
109
+ async function verifyUct(token: string): Promise<Record<string, unknown> | null> {
110
+ const res = await fetch(\`\${DUCT_AUTH_URL}/v1/verify/consent-token\`, {
111
+ method: "POST",
112
+ headers: { "Content-Type": "application/json" },
113
+ body: JSON.stringify({ token }),
114
+ });
115
+ if (!res.ok) return null;
116
+ const body = (await res.json()) as { valid?: boolean; user?: Record<string, unknown> };
117
+ return body.valid ? body.user ?? {} : null;
118
+ }
119
+
120
+ export async function ductOrConsentAuth(req: Request, res: Response, next: NextFunction) {
121
+ const authHeader = req.headers.authorization;
122
+ if (!authHeader?.startsWith("Bearer ")) return next();
123
+
124
+ const token = authHeader.slice(7);
125
+ if (token.startsWith("uct_")) {
126
+ const user = await verifyUct(token);
127
+ if (!user) return res.status(401).json({ error: "Invalid consent token" });
128
+ (req as Request & { user?: Record<string, unknown> }).user = user;
129
+ return next();
130
+ }
131
+
132
+ // Fall through to ductDelegatedAuth (verifyDuctToken) for human shell tokens
133
+ return next();
134
+ }
135
+ `;
136
+ }
137
+ return `/**
138
+ * Third-party agent user identity — accept uct_ consent tokens OR duct_delegated JWTs.
139
+ * Configure DUCT_AUTH_URL in server env (never NEXT_PUBLIC_* / VITE_*).
140
+ */
141
+ import { verifyDuctToken } from "@duct-sdk/sdk/server";
142
+
143
+ const DUCT_AUTH_URL = process.env.DUCT_AUTH_URL ?? "http://localhost:3001";
144
+
145
+ async function verifyConsentToken(token: string): Promise<Record<string, unknown> | null> {
146
+ const res = await fetch(\`\${DUCT_AUTH_URL}/v1/verify/consent-token\`, {
147
+ method: "POST",
148
+ headers: { "Content-Type": "application/json" },
149
+ body: JSON.stringify({ token }),
150
+ });
151
+ if (!res.ok) return null;
152
+ const body = (await res.json()) as { valid?: boolean; user?: Record<string, unknown> };
153
+ return body.valid ? body.user ?? {} : null;
154
+ }
155
+
156
+ export async function resolveAgentAwareUser(request: Request): Promise<Record<string, unknown> | null> {
157
+ const authHeader = request.headers.get("authorization");
158
+ if (!authHeader?.startsWith("Bearer ")) return null;
159
+
160
+ const token = authHeader.slice(7);
161
+ if (token.startsWith("uct_")) {
162
+ return verifyConsentToken(token);
163
+ }
164
+
165
+ const secretKey = process.env.DUCT_SECRET_KEY!;
166
+ const shellId = process.env.DUCT_SHELL_ID ?? process.env.NEXT_PUBLIC_DUCT_SHELL_ID!;
167
+ const delegated = await verifyDuctToken(token, { secretKey, expectedShellId: shellId });
168
+ return delegated.valid ? delegated.payload.session : null;
169
+ }
170
+ `;
171
+ }
172
+ export function buildWiringPlan(outputPaths, framework, authDetection, thirdPartyAgentMode) {
173
+ const middlewareTarget = authDetection.middlewarePath ??
174
+ (framework.name === "vite-react" ? "server/middleware/auth.ts" : "middleware.ts");
175
+ const items = [
176
+ {
177
+ path: outputPaths.configPath,
178
+ action: "create",
179
+ summary: "Duct manifest — routes, actions, deeplinks, agent permissions",
180
+ },
181
+ {
182
+ path: outputPaths.tokenRoutePath,
183
+ action: "create",
184
+ summary: "Mint duct_delegated tokens for the embedded shell",
185
+ },
186
+ {
187
+ path: outputPaths.receiverPath,
188
+ action: "create",
189
+ summary: "Verify signed deeplink tokens server-side",
190
+ },
191
+ {
192
+ path: outputPaths.shellComponentPath,
193
+ action: "create",
194
+ summary: "Embed DuctShell with onTokenRequest → token route",
195
+ },
196
+ {
197
+ path: middlewareTarget,
198
+ action: "modify",
199
+ summary: "Add verifyDuctToken fallback so agent proxy action calls authenticate",
200
+ },
201
+ {
202
+ path: outputPaths.envTemplatePath,
203
+ action: "modify",
204
+ summary: "Set DUCT_SECRET_KEY + DUCT_SHELL_ID (server-only)",
205
+ },
206
+ ];
207
+ const middlewareSnippet = generateVerifyDuctTokenMiddlewareSnippet(framework, middlewareTarget);
208
+ const plan = {
209
+ items,
210
+ middlewareSnippetPath: ".duct/snippets/verify-duct-token.ts",
211
+ middlewareSnippet,
212
+ };
213
+ if (thirdPartyAgentMode === "duct-consent") {
214
+ plan.uctSnippetPath = ".duct/snippets/uct-consent-auth.ts";
215
+ plan.uctSnippet = generateUctVerificationSnippet(framework);
216
+ items.push({
217
+ path: middlewareTarget,
218
+ action: "modify",
219
+ summary: "Verify uct_ consent tokens for third-party agent /message calls",
220
+ });
221
+ }
222
+ if (thirdPartyAgentMode === "oauth") {
223
+ items.push({
224
+ path: "your OAuth token exchange handler",
225
+ action: "modify",
226
+ summary: "Mint scoped duct_delegated or exchange tokens for partner agents (company OAuth)",
227
+ });
228
+ }
229
+ return plan;
230
+ }
231
+ export function sideEffectActionsApproved(config) {
232
+ return (config.actions ?? []).some((action) => action.sideEffects);
233
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,66 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import * as path from "path";
4
+ import { buildWiringPlan, generateVerifyDuctTokenMiddlewareSnippet, sideEffectActionsApproved, } from "./wiring-snippets.js";
5
+ const framework = {
6
+ name: "next-app",
7
+ version: "14.0.0",
8
+ hasAppRouter: true,
9
+ hasPagesRouter: false,
10
+ packageManager: "npm",
11
+ srcDir: ".",
12
+ };
13
+ const authDetection = {
14
+ system: "nextauth",
15
+ confidence: 0.9,
16
+ sessionFields: ["id", "email"],
17
+ guestAllowed: false,
18
+ middlewarePath: "middleware.ts",
19
+ configFiles: [],
20
+ notes: [],
21
+ };
22
+ describe("wiring snippets", () => {
23
+ it("buildWiringPlan lists core generated files", () => {
24
+ const outputPaths = {
25
+ configPath: path.join("/proj", "duct.config.ts"),
26
+ tokenRoutePath: path.join("/proj", "app/api/duct/token/route.ts"),
27
+ receiverPath: path.join("/proj", "app/api/duct/receive/route.ts"),
28
+ shellComponentPath: path.join("/proj", "components", "DuctShell.tsx"),
29
+ envTemplatePath: path.join("/proj", ".env.local.example"),
30
+ };
31
+ const plan = buildWiringPlan(outputPaths, framework, authDetection, "none");
32
+ assert.ok(plan.items.some((item) => item.summary.includes("Mint duct_delegated")));
33
+ assert.ok(plan.items.some((item) => item.summary.includes("verifyDuctToken")));
34
+ assert.equal(plan.middlewareSnippetPath, ".duct/snippets/verify-duct-token.ts");
35
+ assert.match(plan.middlewareSnippet, /verifyDuctToken/);
36
+ });
37
+ it("adds uct snippet when third-party agents use duct-consent", () => {
38
+ const outputPaths = {
39
+ configPath: "/proj/duct.config.ts",
40
+ tokenRoutePath: "/proj/app/api/duct/token/route.ts",
41
+ receiverPath: "/proj/app/api/duct/receive/route.ts",
42
+ shellComponentPath: "/proj/components/DuctShell.tsx",
43
+ envTemplatePath: "/proj/.env.local.example",
44
+ };
45
+ const plan = buildWiringPlan(outputPaths, framework, authDetection, "duct-consent");
46
+ assert.equal(plan.uctSnippetPath, ".duct/snippets/uct-consent-auth.ts");
47
+ assert.match(plan.uctSnippet ?? "", /uct_/);
48
+ assert.ok(plan.items.some((item) => item.summary.includes("uct_")));
49
+ });
50
+ it("generateVerifyDuctTokenMiddlewareSnippet targets express for vite-react", () => {
51
+ const snippet = generateVerifyDuctTokenMiddlewareSnippet({
52
+ name: "vite-react",
53
+ version: "5.0.0",
54
+ hasAppRouter: false,
55
+ hasPagesRouter: false,
56
+ packageManager: "npm",
57
+ srcDir: "src",
58
+ }, "server/middleware/auth.ts");
59
+ assert.match(snippet, /express/);
60
+ assert.match(snippet, /ductDelegatedAuth/);
61
+ });
62
+ it("sideEffectActionsApproved detects side-effect actions", () => {
63
+ assert.equal(sideEffectActionsApproved({ actions: [{ sideEffects: true }] }), true);
64
+ assert.equal(sideEffectActionsApproved({ actions: [{ sideEffects: false }] }), false);
65
+ });
66
+ });
package/dist/cli/index.js CHANGED
@@ -8,6 +8,10 @@ import ora from "ora";
8
8
  import inquirer from "inquirer";
9
9
  import { runInit } from "./init.js";
10
10
  import { SandboxFS } from "./fs/sandbox.js";
11
+ import { detectFramework } from "./detectors/framework.js";
12
+ import { detectAuth } from "./detectors/auth.js";
13
+ import { getGeneratedOutputPaths } from "./output-paths.js";
14
+ import { integrationAuditFailed, printIntegrationAuditIssues, runIntegrationAudit, } from "./processors/integration-audit.js";
11
15
  import { getCandidateAuthBases, getConfiguredDashboard, getManifestApiBases, getActiveApiBase, getActiveAuthBase, getAuthUrl, getShellRuntimeUrl, } from "../core/endpoints.js";
12
16
  import * as fs from "fs/promises";
13
17
  import * as path from "path";
@@ -726,7 +730,43 @@ program
726
730
  console.log(chalk.yellow(" ⚠ Not logged in — run: npx duct login\n"));
727
731
  }
728
732
  else {
729
- console.log(chalk.green(" ✓ All checks complete\n"));
733
+ console.log(chalk.green(" ✓ Service connectivity checks complete\n"));
734
+ }
735
+ const cwd = process.cwd();
736
+ const configPath = path.resolve(cwd, "duct.config.ts");
737
+ const hasConfig = await fs.access(configPath).then(() => true).catch(() => false);
738
+ if (hasConfig) {
739
+ console.log(chalk.bold(" Project integration"));
740
+ try {
741
+ const sandboxFs = new SandboxFS(cwd);
742
+ const raw = await loadDuctConfig(configPath);
743
+ const config = raw;
744
+ const framework = await detectFramework(cwd);
745
+ const authDetection = await detectAuth(sandboxFs);
746
+ const outputPaths = getGeneratedOutputPaths(cwd, framework);
747
+ const auditIssues = await runIntegrationAudit(sandboxFs, {
748
+ projectRoot: cwd,
749
+ config,
750
+ framework,
751
+ outputPaths,
752
+ authDetection,
753
+ });
754
+ printIntegrationAuditIssues(auditIssues);
755
+ if (integrationAuditFailed(auditIssues)) {
756
+ console.log(chalk.red(" ✗ Integration audit found blocking issues\n"));
757
+ process.exit(1);
758
+ }
759
+ if (auditIssues.length === 0) {
760
+ console.log(chalk.green(" ✓ Integration audit passed\n"));
761
+ }
762
+ else {
763
+ console.log(chalk.yellow(" ⚠ Integration audit found warnings — review fixes above\n"));
764
+ }
765
+ }
766
+ catch (err) {
767
+ const message = err instanceof Error ? err.message : String(err);
768
+ console.log(chalk.yellow(` ⚠ Could not run integration audit: ${message}\n`));
769
+ }
730
770
  }
731
771
  });
732
772
  // ----------------------------------------------------------------