@duct-sdk/sdk 0.5.12 → 0.6.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 (159) hide show
  1. package/CHANGELOG.md +385 -336
  2. package/README.md +418 -264
  3. package/TOKEN_SPEC.md +243 -237
  4. package/dist/cli/add.d.ts +7 -0
  5. package/dist/cli/add.js +152 -0
  6. package/dist/cli/agent-prompt.d.ts +3 -0
  7. package/dist/cli/agent-prompt.js +39 -0
  8. package/dist/cli/api-sources.d.ts +26 -0
  9. package/dist/cli/api-sources.js +222 -0
  10. package/dist/cli/cloud.d.ts +133 -0
  11. package/dist/cli/cloud.js +298 -0
  12. package/dist/cli/config-loader.d.ts +14 -0
  13. package/dist/cli/config-loader.js +56 -7
  14. package/dist/cli/device-login.d.ts +17 -0
  15. package/dist/cli/device-login.js +75 -0
  16. package/dist/cli/drift.js +6 -6
  17. package/dist/cli/generators/any-stack.d.ts +3 -0
  18. package/dist/cli/generators/any-stack.js +97 -0
  19. package/dist/cli/generators/config.js +3 -2
  20. package/dist/cli/generators/receiver.js +7 -7
  21. package/dist/cli/generators/shell.js +12 -12
  22. package/dist/cli/generators/token-route.js +245 -245
  23. package/dist/cli/index.js +402 -611
  24. package/dist/cli/mcp-core.d.ts +42 -0
  25. package/dist/cli/mcp-core.js +161 -0
  26. package/dist/cli/mcp-setup.d.ts +4 -0
  27. package/dist/cli/mcp-setup.js +360 -0
  28. package/dist/cli/mcp.d.ts +2 -0
  29. package/dist/cli/mcp.js +457 -0
  30. package/dist/cli/migrate-intershell.js +5 -5
  31. package/dist/cli/policy-defaults.d.ts +37 -0
  32. package/dist/cli/policy-defaults.js +127 -0
  33. package/dist/cli/processors/integration-audit.js +2 -2
  34. package/dist/cli/processors/openapi-parser.d.ts +5 -0
  35. package/dist/cli/processors/openapi-parser.js +8 -3
  36. package/dist/cli/project-loader.d.ts +58 -0
  37. package/dist/cli/project-loader.js +198 -0
  38. package/dist/cli/project-writer.d.ts +23 -0
  39. package/dist/cli/project-writer.js +171 -0
  40. package/dist/cli/push.d.ts +43 -0
  41. package/dist/cli/push.js +276 -0
  42. package/dist/cli/safety-checks.d.ts +9 -0
  43. package/dist/cli/safety-checks.js +29 -0
  44. package/dist/cli/setup.d.ts +20 -0
  45. package/dist/cli/setup.js +349 -0
  46. package/dist/cli/shell-name.d.ts +8 -0
  47. package/dist/cli/shell-name.js +29 -0
  48. package/dist/cli/shells.d.ts +22 -0
  49. package/dist/cli/shells.js +122 -0
  50. package/dist/cli/split.d.ts +7 -0
  51. package/dist/cli/split.js +71 -0
  52. package/dist/cli/sync.d.ts +25 -0
  53. package/dist/cli/sync.js +120 -0
  54. package/dist/cli/test-runner.d.ts +21 -0
  55. package/dist/cli/test-runner.js +281 -0
  56. package/dist/core/compile.d.ts +43 -0
  57. package/dist/core/compile.js +510 -0
  58. package/dist/core/config.d.ts +533 -1
  59. package/dist/core/config.js +32 -12
  60. package/dist/core/hosted-upstream-check.d.ts +3 -0
  61. package/dist/core/hosted-upstream-check.js +35 -0
  62. package/dist/core/login-handoff.d.ts +1 -1
  63. package/dist/core/login-handoff.js +1 -1
  64. package/dist/core/project.d.ts +1798 -0
  65. package/dist/core/project.js +278 -0
  66. package/dist/core/readiness-checks.js +2 -2
  67. package/dist/core/types.d.ts +26 -1
  68. package/dist/index.d.ts +6 -0
  69. package/dist/index.js +16 -0
  70. package/dist/project.d.ts +4 -0
  71. package/dist/project.js +8 -0
  72. package/dist/server.d.ts +2 -0
  73. package/dist/server.js +1 -0
  74. package/fixtures/token-conformance-vectors.json +26 -0
  75. package/package.json +94 -94
  76. package/dist/adapters/react/page-context-guard.test.d.ts +0 -1
  77. package/dist/adapters/react/page-context-guard.test.js +0 -15
  78. package/dist/cli/agents/api-agent.d.ts +0 -22
  79. package/dist/cli/agents/api-agent.js +0 -761
  80. package/dist/cli/agents/auth-agent.d.ts +0 -7
  81. package/dist/cli/agents/auth-agent.js +0 -212
  82. package/dist/cli/agents/deeplink-agent.d.ts +0 -6
  83. package/dist/cli/agents/deeplink-agent.js +0 -285
  84. package/dist/cli/agents/llm.d.ts +0 -33
  85. package/dist/cli/agents/llm.js +0 -309
  86. package/dist/cli/agents/pipeline.d.ts +0 -72
  87. package/dist/cli/agents/pipeline.js +0 -421
  88. package/dist/cli/agents/reviewer-agent.d.ts +0 -13
  89. package/dist/cli/agents/reviewer-agent.js +0 -450
  90. package/dist/cli/agents/route-agent.d.ts +0 -17
  91. package/dist/cli/agents/route-agent.js +0 -383
  92. package/dist/cli/config-loader.test.d.ts +0 -1
  93. package/dist/cli/config-loader.test.js +0 -63
  94. package/dist/cli/detectors/topology.d.ts +0 -46
  95. package/dist/cli/detectors/topology.js +0 -417
  96. package/dist/cli/generators/config.test.d.ts +0 -1
  97. package/dist/cli/generators/config.test.js +0 -222
  98. package/dist/cli/generators/shell.test.d.ts +0 -1
  99. package/dist/cli/generators/shell.test.js +0 -73
  100. package/dist/cli/generators/token-route.test.d.ts +0 -1
  101. package/dist/cli/generators/token-route.test.js +0 -53
  102. package/dist/cli/generators/wiring-snippets.test.d.ts +0 -1
  103. package/dist/cli/generators/wiring-snippets.test.js +0 -80
  104. package/dist/cli/init.d.ts +0 -32
  105. package/dist/cli/init.js +0 -1336
  106. package/dist/cli/manifest-diff.test.d.ts +0 -1
  107. package/dist/cli/manifest-diff.test.js +0 -144
  108. package/dist/cli/processors/curl-parser.test.d.ts +0 -1
  109. package/dist/cli/processors/curl-parser.test.js +0 -24
  110. package/dist/cli/processors/integration-audit.test.d.ts +0 -1
  111. package/dist/cli/processors/integration-audit.test.js +0 -154
  112. package/dist/cli/processors/postprocess.d.ts +0 -22
  113. package/dist/cli/processors/postprocess.js +0 -107
  114. package/dist/cli/processors/prisma-parser.d.ts +0 -35
  115. package/dist/cli/processors/prisma-parser.js +0 -117
  116. package/dist/cli/processors/verify-discovery.d.ts +0 -33
  117. package/dist/cli/processors/verify-discovery.js +0 -193
  118. package/dist/cli/processors/verify-discovery.test.d.ts +0 -1
  119. package/dist/cli/processors/verify-discovery.test.js +0 -153
  120. package/dist/cli/processors/zod-extractor.d.ts +0 -27
  121. package/dist/cli/processors/zod-extractor.js +0 -153
  122. package/dist/cli/prompts/review.d.ts +0 -61
  123. package/dist/cli/prompts/review.js +0 -410
  124. package/dist/cli/selectors/express.d.ts +0 -12
  125. package/dist/cli/selectors/express.js +0 -117
  126. package/dist/cli/selectors/fastapi.d.ts +0 -12
  127. package/dist/cli/selectors/fastapi.js +0 -122
  128. package/dist/cli/selectors/generic.d.ts +0 -10
  129. package/dist/cli/selectors/generic.js +0 -74
  130. package/dist/cli/selectors/index.d.ts +0 -37
  131. package/dist/cli/selectors/index.js +0 -315
  132. package/dist/cli/selectors/next.d.ts +0 -12
  133. package/dist/cli/selectors/next.js +0 -130
  134. package/dist/core/config-policy.test.d.ts +0 -1
  135. package/dist/core/config-policy.test.js +0 -101
  136. package/dist/core/config-roundtrip.test.d.ts +0 -1
  137. package/dist/core/config-roundtrip.test.js +0 -180
  138. package/dist/core/endpoint-guard.test.d.ts +0 -1
  139. package/dist/core/endpoint-guard.test.js +0 -57
  140. package/dist/core/env-diagnostics.test.d.ts +0 -1
  141. package/dist/core/env-diagnostics.test.js +0 -31
  142. package/dist/core/evidence-bundle.conformance.test.d.ts +0 -1
  143. package/dist/core/evidence-bundle.conformance.test.js +0 -110
  144. package/dist/core/evidence-bundle.test.d.ts +0 -1
  145. package/dist/core/evidence-bundle.test.js +0 -58
  146. package/dist/core/invariants.test.d.ts +0 -1
  147. package/dist/core/invariants.test.js +0 -217
  148. package/dist/core/login-handoff.test.d.ts +0 -1
  149. package/dist/core/login-handoff.test.js +0 -31
  150. package/dist/core/profile.test.d.ts +0 -1
  151. package/dist/core/profile.test.js +0 -95
  152. package/dist/core/readiness-checks.test.d.ts +0 -1
  153. package/dist/core/readiness-checks.test.js +0 -106
  154. package/dist/core/receipt.test.d.ts +0 -1
  155. package/dist/core/receipt.test.js +0 -75
  156. package/dist/core/side-effects-review.test.d.ts +0 -1
  157. package/dist/core/side-effects-review.test.js +0 -28
  158. package/dist/core/token.test.d.ts +0 -1
  159. package/dist/core/token.test.js +0 -66
@@ -7,11 +7,11 @@ function sessionFieldsLiteral(fields) {
7
7
  }
8
8
  function guestGuard(guestAllowed) {
9
9
  if (guestAllowed) {
10
- return ` // Guest users allowed — empty session mints a limited delegated token.
10
+ return ` // Guest users allowed — empty session mints a limited delegated token.
11
11
  // Set auth.guestAllowed: false in duct.config.ts to require login before minting.`;
12
12
  }
13
- return ` if (!userSession || Object.keys(userSession).length === 0) {
14
- return unauthorized("Unauthorized");
13
+ return ` if (!userSession || Object.keys(userSession).length === 0) {
14
+ return unauthorized("Unauthorized");
15
15
  }`;
16
16
  }
17
17
  function nextAuthSessionLookup(strategy, framework) {
@@ -19,12 +19,12 @@ function nextAuthSessionLookup(strategy, framework) {
19
19
  return {
20
20
  imports: `import { currentUser } from "@clerk/nextjs/server";`,
21
21
  lookup: ` const user = await currentUser();`,
22
- userSessionExpr: `user
23
- ? {
24
- userId: user.id,
25
- email: user.emailAddresses[0]?.emailAddress,
26
- name: user.fullName ?? undefined,
27
- }
22
+ userSessionExpr: `user
23
+ ? {
24
+ userId: user.id,
25
+ email: user.emailAddresses[0]?.emailAddress,
26
+ name: user.fullName ?? undefined,
27
+ }
28
28
  : {}`,
29
29
  };
30
30
  }
@@ -38,11 +38,11 @@ function nextAuthSessionLookup(strategy, framework) {
38
38
  if (strategy === "nextauth") {
39
39
  if (framework.hasAppRouter || framework.name === "next-app") {
40
40
  return {
41
- imports: `import { auth } from "@/auth";
41
+ imports: `import { auth } from "@/auth";
42
42
  // Fallback for NextAuth v4: import { getServerSession } from "next-auth";`,
43
- lookup: ` const session = await auth().catch(async () => {
44
- const { getServerSession } = await import("next-auth");
45
- return getServerSession();
43
+ lookup: ` const session = await auth().catch(async () => {
44
+ const { getServerSession } = await import("next-auth");
45
+ return getServerSession();
46
46
  });`,
47
47
  userSessionExpr: `(session?.user as Record<string, unknown> | undefined) ?? {}`,
48
48
  };
@@ -78,129 +78,129 @@ export function generateStrategyTokenRoute(framework, options) {
78
78
  const guestBlock = guestGuard(options.guestAllowed);
79
79
  const sessionFieldsLine = ` sessionFields: ${sessionFieldsLiteral(options.sessionFields)},`;
80
80
  if (framework.name === "sveltekit") {
81
- return `// src/routes/api/duct/token/+server.ts
82
- import type { RequestHandler } from "@sveltejs/kit";
83
- import { json } from "@sveltejs/kit";
84
- import { generateDuctToken } from "@duct-sdk/sdk/server";
85
-
86
- export const POST: RequestHandler = async ({ locals }) => {
87
- const secretKey = process.env.DUCT_SECRET_KEY;
88
- const shellId = process.env.PUBLIC_DUCT_SHELL_ID || process.env.DUCT_SHELL_ID;
89
-
90
- if (!secretKey || !shellId) {
91
- return json({ error: "Duct not configured" }, { status: 500 });
92
- }
93
-
94
- const userSession = ((locals as Record<string, unknown>).user ?? {}) as Record<string, unknown>;
95
- ${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'json({ error: "Unauthorized" }, { status: 401 })')}
96
-
97
- const { token, expiresAt } = await generateDuctToken({
98
- secretKey,
99
- shellId,
100
- userSession,
101
- expirySeconds: ${expiry},
102
- ${sessionFieldsLine}
103
- });
104
-
105
- return json({ token, expiresAt: expiresAt.toISOString() });
106
- };
81
+ return `// src/routes/api/duct/token/+server.ts
82
+ import type { RequestHandler } from "@sveltejs/kit";
83
+ import { json } from "@sveltejs/kit";
84
+ import { generateDuctToken } from "@duct-sdk/sdk/server";
85
+
86
+ export const POST: RequestHandler = async ({ locals }) => {
87
+ const secretKey = process.env.DUCT_SECRET_KEY;
88
+ const shellId = process.env.PUBLIC_DUCT_SHELL_ID || process.env.DUCT_SHELL_ID;
89
+
90
+ if (!secretKey || !shellId) {
91
+ return json({ error: "Duct not configured" }, { status: 500 });
92
+ }
93
+
94
+ const userSession = ((locals as Record<string, unknown>).user ?? {}) as Record<string, unknown>;
95
+ ${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'json({ error: "Unauthorized" }, { status: 401 })')}
96
+
97
+ const { token, expiresAt } = await generateDuctToken({
98
+ secretKey,
99
+ shellId,
100
+ userSession,
101
+ expirySeconds: ${expiry},
102
+ ${sessionFieldsLine}
103
+ });
104
+
105
+ return json({ token, expiresAt: expiresAt.toISOString() });
106
+ };
107
107
  `;
108
108
  }
109
109
  if (framework.name === "remix") {
110
- return `// app/routes/api.duct.token.ts
111
- import type { ActionFunctionArgs } from "@remix-run/node";
112
- import { json } from "@remix-run/node";
113
- import { generateDuctToken } from "@duct-sdk/sdk/server";
114
-
115
- export async function action({ request }: ActionFunctionArgs) {
116
- if (request.method !== "POST") {
117
- return json({ error: "Method not allowed" }, { status: 405 });
118
- }
119
-
120
- const secretKey = process.env.DUCT_SECRET_KEY;
121
- const shellId = process.env.VITE_DUCT_SHELL_ID ?? process.env.DUCT_SHELL_ID;
122
-
123
- if (!secretKey || !shellId) {
124
- return json({ error: "Duct not configured" }, { status: 500 });
125
- }
126
-
127
- // Wire your Remix session (e.g. getSession from remix-auth)
128
- const userSession: Record<string, unknown> = {};
129
- ${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'json({ error: "Unauthorized" }, { status: 401 })')}
130
-
131
- const { token, expiresAt } = await generateDuctToken({
132
- secretKey,
133
- shellId,
134
- userSession,
135
- expirySeconds: ${expiry},
136
- ${sessionFieldsLine}
137
- });
138
-
139
- return json({ token, expiresAt: expiresAt.toISOString() });
140
- }
110
+ return `// app/routes/api.duct.token.ts
111
+ import type { ActionFunctionArgs } from "@remix-run/node";
112
+ import { json } from "@remix-run/node";
113
+ import { generateDuctToken } from "@duct-sdk/sdk/server";
114
+
115
+ export async function action({ request }: ActionFunctionArgs) {
116
+ if (request.method !== "POST") {
117
+ return json({ error: "Method not allowed" }, { status: 405 });
118
+ }
119
+
120
+ const secretKey = process.env.DUCT_SECRET_KEY;
121
+ const shellId = process.env.VITE_DUCT_SHELL_ID ?? process.env.DUCT_SHELL_ID;
122
+
123
+ if (!secretKey || !shellId) {
124
+ return json({ error: "Duct not configured" }, { status: 500 });
125
+ }
126
+
127
+ // Wire your Remix session (e.g. getSession from remix-auth)
128
+ const userSession: Record<string, unknown> = {};
129
+ ${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'json({ error: "Unauthorized" }, { status: 401 })')}
130
+
131
+ const { token, expiresAt } = await generateDuctToken({
132
+ secretKey,
133
+ shellId,
134
+ userSession,
135
+ expirySeconds: ${expiry},
136
+ ${sessionFieldsLine}
137
+ });
138
+
139
+ return json({ token, expiresAt: expiresAt.toISOString() });
140
+ }
141
141
  `;
142
142
  }
143
143
  if (framework.name === "vite-react" ||
144
144
  framework.name === "express" ||
145
145
  framework.name === "vue3") {
146
- return `// server/routes/duct-token.ts
147
- import { Router } from "express";
148
- import { generateDuctToken } from "@duct-sdk/sdk/server";
149
-
150
- const router = Router();
151
-
152
- router.post("/api/duct/token", async (req, res) => {
153
- const secretKey = process.env.DUCT_SECRET_KEY;
154
- const shellId = process.env.DUCT_SHELL_ID;
155
-
156
- if (!secretKey || !shellId) {
157
- return res.status(500).json({ error: "Duct not configured" });
158
- }
159
-
160
- const userSession = (req as typeof req & { user?: Record<string, unknown> }).user ?? {};
161
- ${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'res.status(401).json({ error: "Unauthorized" })')}
162
-
163
- const { token, expiresAt } = await generateDuctToken({
164
- secretKey,
165
- shellId,
166
- userSession,
167
- expirySeconds: ${expiry},
168
- ${sessionFieldsLine}
169
- });
170
-
171
- return res.status(200).json({ token, expiresAt: expiresAt.toISOString() });
172
- });
173
-
174
- export default router;
146
+ return `// server/routes/duct-token.ts
147
+ import { Router } from "express";
148
+ import { generateDuctToken } from "@duct-sdk/sdk/server";
149
+
150
+ const router = Router();
151
+
152
+ router.post("/api/duct/token", async (req, res) => {
153
+ const secretKey = process.env.DUCT_SECRET_KEY;
154
+ const shellId = process.env.DUCT_SHELL_ID;
155
+
156
+ if (!secretKey || !shellId) {
157
+ return res.status(500).json({ error: "Duct not configured" });
158
+ }
159
+
160
+ const userSession = (req as typeof req & { user?: Record<string, unknown> }).user ?? {};
161
+ ${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'res.status(401).json({ error: "Unauthorized" })')}
162
+
163
+ const { token, expiresAt } = await generateDuctToken({
164
+ secretKey,
165
+ shellId,
166
+ userSession,
167
+ expirySeconds: ${expiry},
168
+ ${sessionFieldsLine}
169
+ });
170
+
171
+ return res.status(200).json({ token, expiresAt: expiresAt.toISOString() });
172
+ });
173
+
174
+ export default router;
175
175
  `;
176
176
  }
177
177
  if (framework.name === "nuxt") {
178
- return `// server/api/duct/token.post.ts
179
- import { generateDuctToken } from "@duct-sdk/sdk/server";
180
-
181
- export default defineEventHandler(async (event) => {
182
- const secretKey = process.env.DUCT_SECRET_KEY;
183
- const shellId = process.env.NUXT_PUBLIC_DUCT_SHELL_ID ?? process.env.DUCT_SHELL_ID;
184
-
185
- if (!secretKey || !shellId) {
186
- setResponseStatus(event, 500);
187
- return { error: "Duct not configured" };
188
- }
189
-
190
- // Wire your Nuxt server session (e.g. from nuxt-auth-utils / event.context).
191
- const userSession = ((event.context as Record<string, unknown>).user ?? {}) as Record<string, unknown>;
192
- ${guestBlock.replace(/return unauthorized\("Unauthorized"\);/g, 'setResponseStatus(event, 401); return { error: "Unauthorized" };')}
193
-
194
- const { token, expiresAt } = await generateDuctToken({
195
- secretKey,
196
- shellId,
197
- userSession,
198
- expirySeconds: ${expiry},
199
- ${sessionFieldsLine}
200
- });
201
-
202
- return { token, expiresAt: expiresAt.toISOString() };
203
- });
178
+ return `// server/api/duct/token.post.ts
179
+ import { generateDuctToken } from "@duct-sdk/sdk/server";
180
+
181
+ export default defineEventHandler(async (event) => {
182
+ const secretKey = process.env.DUCT_SECRET_KEY;
183
+ const shellId = process.env.NUXT_PUBLIC_DUCT_SHELL_ID ?? process.env.DUCT_SHELL_ID;
184
+
185
+ if (!secretKey || !shellId) {
186
+ setResponseStatus(event, 500);
187
+ return { error: "Duct not configured" };
188
+ }
189
+
190
+ // Wire your Nuxt server session (e.g. from nuxt-auth-utils / event.context).
191
+ const userSession = ((event.context as Record<string, unknown>).user ?? {}) as Record<string, unknown>;
192
+ ${guestBlock.replace(/return unauthorized\("Unauthorized"\);/g, 'setResponseStatus(event, 401); return { error: "Unauthorized" };')}
193
+
194
+ const { token, expiresAt } = await generateDuctToken({
195
+ secretKey,
196
+ shellId,
197
+ userSession,
198
+ expirySeconds: ${expiry},
199
+ ${sessionFieldsLine}
200
+ });
201
+
202
+ return { token, expiresAt: expiresAt.toISOString() };
203
+ });
204
204
  `;
205
205
  }
206
206
  if (framework.name === "fastapi") {
@@ -208,131 +208,131 @@ ${sessionFieldsLine}
208
208
  const guestPy = options.guestAllowed
209
209
  ? " # Guest users allowed — an empty session mints a limited delegated token.\n # Set auth.guestAllowed: false in duct.config.ts to require login first."
210
210
  : ' if not user_session:\n return JSONResponse({"error": "Unauthorized"}, status_code=401)';
211
- return `# duct_token.py — auto-generated by \`npx duct init\`
212
- # FastAPI route that mints a Duct delegated token (HS256 JWT, matches @duct-sdk/sdk).
213
- # Requires: pip install pyjwt
214
- import os
215
- import time
216
- from datetime import datetime, timezone
217
-
218
- import jwt # PyJWT
219
- from fastapi import APIRouter, Request
220
- from fastapi.responses import JSONResponse
221
-
222
- router = APIRouter()
223
-
224
- # Allowlisted session fields copied into the delegated token (from auth.sessionFields).
225
- _ALLOWED_FIELDS = ${JSON.stringify(scalarFields)}
226
- _DENY_FRAGMENTS = ("token", "secret", "password", "key", "hash", "salt",
227
- "credential", "jwt", "cookie", "bearer", "ssn", "otp")
228
-
229
-
230
- def _filter_scalars(session: dict) -> dict:
231
- out = {}
232
- items = ((k, session.get(k)) for k in _ALLOWED_FIELDS) if _ALLOWED_FIELDS else session.items()
233
- for key, value in items:
234
- if any(frag in key.lower() for frag in _DENY_FRAGMENTS):
235
- continue
236
- if value is None or isinstance(value, (str, int, float, bool)):
237
- out[key] = value
238
- return out
239
-
240
-
241
- @router.post("/api/duct/token")
242
- async def duct_token(request: Request):
243
- secret = os.environ.get("DUCT_SECRET_KEY")
244
- shell_id = os.environ.get("DUCT_SHELL_ID")
245
- if not secret or not shell_id:
246
- return JSONResponse({"error": "Duct not configured"}, status_code=500)
247
-
248
- # TODO: replace with your real authenticated session lookup.
249
- user_session: dict = getattr(request.state, "user", {}) or {}
250
- ${guestPy}
251
-
252
- now = int(time.time())
253
- exp = now + ${expiry}
254
- sub = str(user_session.get("id") or user_session.get("sub") or "anonymous")
255
- payload = {
256
- "type": "duct_delegated",
257
- "session": _filter_scalars(user_session),
258
- "sub": sub,
259
- "iss": shell_id,
260
- "iat": now,
261
- "exp": exp,
262
- }
263
- token = jwt.encode(payload, secret, algorithm="HS256")
264
- expires_at = datetime.fromtimestamp(exp, tz=timezone.utc).isoformat().replace("+00:00", "Z")
265
- return {"token": token, "expiresAt": expires_at}
211
+ return `# duct_token.py — generated by \`npx @duct-sdk/sdk add identity\`
212
+ # FastAPI route that mints a Duct delegated token (HS256 JWT, matches @duct-sdk/sdk).
213
+ # Requires: pip install pyjwt
214
+ import os
215
+ import time
216
+ from datetime import datetime, timezone
217
+
218
+ import jwt # PyJWT
219
+ from fastapi import APIRouter, Request
220
+ from fastapi.responses import JSONResponse
221
+
222
+ router = APIRouter()
223
+
224
+ # Allowlisted session fields copied into the delegated token (from auth.sessionFields).
225
+ _ALLOWED_FIELDS = ${JSON.stringify(scalarFields)}
226
+ _DENY_FRAGMENTS = ("token", "secret", "password", "key", "hash", "salt",
227
+ "credential", "jwt", "cookie", "bearer", "ssn", "otp")
228
+
229
+
230
+ def _filter_scalars(session: dict) -> dict:
231
+ out = {}
232
+ items = ((k, session.get(k)) for k in _ALLOWED_FIELDS) if _ALLOWED_FIELDS else session.items()
233
+ for key, value in items:
234
+ if any(frag in key.lower() for frag in _DENY_FRAGMENTS):
235
+ continue
236
+ if value is None or isinstance(value, (str, int, float, bool)):
237
+ out[key] = value
238
+ return out
239
+
240
+
241
+ @router.post("/api/duct/token")
242
+ async def duct_token(request: Request):
243
+ secret = os.environ.get("DUCT_SECRET_KEY")
244
+ shell_id = os.environ.get("DUCT_SHELL_ID")
245
+ if not secret or not shell_id:
246
+ return JSONResponse({"error": "Duct not configured"}, status_code=500)
247
+
248
+ # TODO: replace with your real authenticated session lookup.
249
+ user_session: dict = getattr(request.state, "user", {}) or {}
250
+ ${guestPy}
251
+
252
+ now = int(time.time())
253
+ exp = now + ${expiry}
254
+ sub = str(user_session.get("id") or user_session.get("sub") or "anonymous")
255
+ payload = {
256
+ "type": "duct_delegated",
257
+ "session": _filter_scalars(user_session),
258
+ "sub": sub,
259
+ "iss": shell_id,
260
+ "iat": now,
261
+ "exp": exp,
262
+ }
263
+ token = jwt.encode(payload, secret, algorithm="HS256")
264
+ expires_at = datetime.fromtimestamp(exp, tz=timezone.utc).isoformat().replace("+00:00", "Z")
265
+ return {"token": token, "expiresAt": expires_at}
266
266
  `;
267
267
  }
268
268
  const auth = nextAuthSessionLookup(options.authStrategy, framework);
269
269
  if (framework.hasAppRouter || framework.name === "next-app") {
270
- return `// app/api/duct/token/route.ts
271
- import { NextRequest, NextResponse } from "next/server";
272
- import { generateDuctToken } from "@duct-sdk/sdk/server";
273
- ${auth.imports}
274
-
275
- function unauthorized(message: string) {
276
- return NextResponse.json({ error: message }, { status: 401 });
277
- }
278
-
279
- export async function POST(_request: NextRequest) {
280
- const secretKey = process.env.DUCT_SECRET_KEY;
281
- const shellId = process.env.NEXT_PUBLIC_DUCT_SHELL_ID ?? process.env.DUCT_SHELL_ID;
282
-
283
- if (!secretKey || !shellId) {
284
- return NextResponse.json({ error: "Duct not configured" }, { status: 500 });
285
- }
286
-
287
- ${auth.lookup}
288
- const userSession = ${auth.userSessionExpr};
289
- ${guestBlock}
290
-
291
- const { token, expiresAt } = await generateDuctToken({
292
- secretKey,
293
- shellId,
294
- userSession,
295
- expirySeconds: ${expiry},
296
- ${sessionFieldsLine}
297
- });
298
-
299
- return NextResponse.json({ token, expiresAt: expiresAt.toISOString() });
300
- }
270
+ return `// app/api/duct/token/route.ts
271
+ import { NextRequest, NextResponse } from "next/server";
272
+ import { generateDuctToken } from "@duct-sdk/sdk/server";
273
+ ${auth.imports}
274
+
275
+ function unauthorized(message: string) {
276
+ return NextResponse.json({ error: message }, { status: 401 });
277
+ }
278
+
279
+ export async function POST(_request: NextRequest) {
280
+ const secretKey = process.env.DUCT_SECRET_KEY;
281
+ const shellId = process.env.NEXT_PUBLIC_DUCT_SHELL_ID ?? process.env.DUCT_SHELL_ID;
282
+
283
+ if (!secretKey || !shellId) {
284
+ return NextResponse.json({ error: "Duct not configured" }, { status: 500 });
285
+ }
286
+
287
+ ${auth.lookup}
288
+ const userSession = ${auth.userSessionExpr};
289
+ ${guestBlock}
290
+
291
+ const { token, expiresAt } = await generateDuctToken({
292
+ secretKey,
293
+ shellId,
294
+ userSession,
295
+ expirySeconds: ${expiry},
296
+ ${sessionFieldsLine}
297
+ });
298
+
299
+ return NextResponse.json({ token, expiresAt: expiresAt.toISOString() });
300
+ }
301
301
  `;
302
302
  }
303
- return `// pages/api/duct/token.ts
304
- import type { NextApiRequest, NextApiResponse } from "next";
305
- import { generateDuctToken } from "@duct-sdk/sdk/server";
306
- ${auth.imports}
307
-
308
- type TokenResponse = { token?: string; expiresAt?: string; error?: string };
309
-
310
- export default async function handler(req: NextApiRequest, res: NextApiResponse<TokenResponse>) {
311
- if (req.method !== "POST") {
312
- res.setHeader("Allow", "POST");
313
- return res.status(405).json({ error: "Method not allowed" });
314
- }
315
-
316
- const secretKey = process.env.DUCT_SECRET_KEY;
317
- const shellId = process.env.NEXT_PUBLIC_DUCT_SHELL_ID ?? process.env.DUCT_SHELL_ID;
318
-
319
- if (!secretKey || !shellId) {
320
- return res.status(500).json({ error: "Duct not configured" });
321
- }
322
-
323
- ${auth.lookup}
324
- const userSession = ${auth.userSessionExpr};
325
- ${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'res.status(401).json({ error: "Unauthorized" })')}
326
-
327
- const { token, expiresAt } = await generateDuctToken({
328
- secretKey,
329
- shellId,
330
- userSession,
331
- expirySeconds: ${expiry},
332
- ${sessionFieldsLine}
333
- });
334
-
335
- return res.status(200).json({ token, expiresAt: expiresAt.toISOString() });
336
- }
303
+ return `// pages/api/duct/token.ts
304
+ import type { NextApiRequest, NextApiResponse } from "next";
305
+ import { generateDuctToken } from "@duct-sdk/sdk/server";
306
+ ${auth.imports}
307
+
308
+ type TokenResponse = { token?: string; expiresAt?: string; error?: string };
309
+
310
+ export default async function handler(req: NextApiRequest, res: NextApiResponse<TokenResponse>) {
311
+ if (req.method !== "POST") {
312
+ res.setHeader("Allow", "POST");
313
+ return res.status(405).json({ error: "Method not allowed" });
314
+ }
315
+
316
+ const secretKey = process.env.DUCT_SECRET_KEY;
317
+ const shellId = process.env.NEXT_PUBLIC_DUCT_SHELL_ID ?? process.env.DUCT_SHELL_ID;
318
+
319
+ if (!secretKey || !shellId) {
320
+ return res.status(500).json({ error: "Duct not configured" });
321
+ }
322
+
323
+ ${auth.lookup}
324
+ const userSession = ${auth.userSessionExpr};
325
+ ${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'res.status(401).json({ error: "Unauthorized" })')}
326
+
327
+ const { token, expiresAt } = await generateDuctToken({
328
+ secretKey,
329
+ shellId,
330
+ userSession,
331
+ expirySeconds: ${expiry},
332
+ ${sessionFieldsLine}
333
+ });
334
+
335
+ return res.status(200).json({ token, expiresAt: expiresAt.toISOString() });
336
+ }
337
337
  `;
338
338
  }