@duct-sdk/sdk 0.1.7 → 0.1.13

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 (58) hide show
  1. package/README.md +3 -3
  2. package/dist/adapters/next/index.d.ts +1 -1
  3. package/dist/adapters/next/shell.d.ts +55 -1
  4. package/dist/adapters/next/shell.js +100 -17
  5. package/dist/adapters/react/index.d.ts +5 -1
  6. package/dist/adapters/react/index.js +2 -0
  7. package/dist/adapters/react/shell.d.ts +61 -1
  8. package/dist/adapters/react/shell.js +110 -16
  9. package/dist/adapters/react/use-page-context.d.ts +32 -0
  10. package/dist/adapters/react/use-page-context.js +99 -0
  11. package/dist/cli/agents/api-agent.d.ts +9 -3
  12. package/dist/cli/agents/api-agent.js +163 -69
  13. package/dist/cli/agents/auth-agent.d.ts +2 -1
  14. package/dist/cli/agents/auth-agent.js +38 -24
  15. package/dist/cli/agents/deeplink-agent.js +71 -49
  16. package/dist/cli/agents/llm.d.ts +1 -1
  17. package/dist/cli/agents/llm.js +48 -15
  18. package/dist/cli/agents/pipeline.d.ts +16 -0
  19. package/dist/cli/agents/pipeline.js +18 -5
  20. package/dist/cli/agents/reviewer-agent.js +46 -46
  21. package/dist/cli/agents/route-agent.d.ts +3 -1
  22. package/dist/cli/agents/route-agent.js +70 -44
  23. package/dist/cli/detectors/topology.d.ts +26 -0
  24. package/dist/cli/detectors/topology.js +310 -0
  25. package/dist/cli/drift.d.ts +11 -0
  26. package/dist/cli/drift.js +147 -2
  27. package/dist/cli/fs/sandbox.d.ts +2 -0
  28. package/dist/cli/fs/sandbox.js +22 -8
  29. package/dist/cli/generators/config.d.ts +13 -0
  30. package/dist/cli/generators/config.js +200 -50
  31. package/dist/cli/generators/receiver.js +728 -601
  32. package/dist/cli/generators/shell.js +532 -490
  33. package/dist/cli/index.js +502 -19
  34. package/dist/cli/init.d.ts +11 -1
  35. package/dist/cli/init.js +367 -31
  36. package/dist/cli/processors/postprocess.d.ts +22 -0
  37. package/dist/cli/processors/postprocess.js +107 -0
  38. package/dist/cli/processors/prisma-parser.d.ts +35 -0
  39. package/dist/cli/processors/prisma-parser.js +117 -0
  40. package/dist/cli/processors/zod-extractor.d.ts +27 -0
  41. package/dist/cli/processors/zod-extractor.js +153 -0
  42. package/dist/cli/prompts/review.d.ts +32 -0
  43. package/dist/cli/prompts/review.js +240 -0
  44. package/dist/cli/selectors/index.d.ts +22 -0
  45. package/dist/cli/selectors/index.js +274 -0
  46. package/dist/core/config.d.ts +18 -18
  47. package/dist/core/endpoints.d.ts +1 -0
  48. package/dist/core/endpoints.js +4 -0
  49. package/dist/core/introspect.d.ts +47 -0
  50. package/dist/core/introspect.js +94 -0
  51. package/dist/core/status.d.ts +39 -0
  52. package/dist/core/status.js +40 -0
  53. package/dist/core/token.d.ts +36 -1
  54. package/dist/core/token.js +43 -2
  55. package/dist/core/types.d.ts +114 -0
  56. package/dist/index.d.ts +9 -2
  57. package/dist/index.js +6 -1
  58. package/package.json +84 -84
@@ -7,142 +7,173 @@
7
7
  // ----------------------------------------------------------------
8
8
  function generateNextAppRouterReceiver(_config) {
9
9
  const docsBase = "https://docs.your-domain.com"; // Consider injecting this dynamically if DUCT_URL is available
10
- return `/**
11
- * Duct Deeplink Receiver — auto-generated by \`npx duct init\`
12
- *
13
- * This route receives signed deeplinks from the Duct shell and navigates
14
- * the user to the correct page with pre-loaded state.
15
- *
16
- * Do not remove the signature verification step.
17
- * Do not expose DUCT_SECRET_KEY client-side.
18
- *
19
- * Docs: ${docsBase}/deeplinks/receiver
20
- */
21
-
22
- import { NextRequest, NextResponse } from "next/server";
23
- import { verifyDeeplinkToken } from "@shoryasethia/duct-sdk";
24
- import ductConfig from "../../../../duct.config";
25
-
26
- // Whitelist of allowed Duct cloud IPs (optional but recommended)
27
- // const DUCT_IPS = ["xxx.xxx.xxx.xxx"];
28
-
29
- export async function POST(request: NextRequest) {
30
- const secretKey = process.env.DUCT_SECRET_KEY;
31
-
32
- if (!secretKey) {
33
- console.error("[Duct] DUCT_SECRET_KEY environment variable is not set");
34
- return NextResponse.json(
35
- { error: "Server configuration error" },
36
- { status: 500 }
37
- );
38
- }
39
-
40
- // Get the token from the Authorization header or request body
41
- const authHeader = request.headers.get("authorization");
42
- let token: string | null = null;
43
-
44
- if (authHeader?.startsWith("Bearer ")) {
45
- token = authHeader.slice(7);
46
- } else {
47
- try {
48
- const body = await request.json() as { token?: string };
49
- token = body.token ?? null;
50
- } catch {
51
- return NextResponse.json(
52
- { error: "Invalid request body" },
53
- { status: 400 }
54
- );
55
- }
56
- }
57
-
58
- if (!token) {
59
- return NextResponse.json(
60
- { error: "No token provided" },
61
- { status: 401 }
62
- );
63
- }
64
-
65
- // Verify the deeplink token
66
- const verifyResult = await verifyDeeplinkToken(token, {
67
- secretKey,
68
- expectedShellId: ductConfig.shellId,
69
- });
70
-
71
- if (!verifyResult.valid || !verifyResult.payload) {
72
- console.warn("[Duct] Invalid deeplink token:", verifyResult.error);
73
- return NextResponse.json(
74
- { error: "Invalid token", detail: verifyResult.error },
75
- { status: 401 }
76
- );
77
- }
78
-
79
- const { deeplink_id, state, sub } = verifyResult.payload;
80
-
81
- // Validate deeplink_id is in our config
82
- const deeplinkDef = ductConfig.deeplinks.find((d) => d.id === deeplink_id);
83
- if (!deeplinkDef) {
84
- console.warn("[Duct] Unknown deeplink ID:", deeplink_id);
85
- return NextResponse.json(
86
- { error: "Unknown deeplink" },
87
- { status: 400 }
88
- );
89
- }
90
-
91
- // TODO: Add your application logic here
92
- // For example: pre-load data, create a session, set cookies, etc.
93
- console.log("[Duct] Received deeplink:", deeplink_id, "for user:", sub, "state:", state);
94
-
95
- // Return the redirect URL that the Duct shell should navigate to
96
- const redirectPath = buildRedirectPath(deeplinkDef.targetRoute, state);
97
- const redirectUrl = \`\${ductConfig.product.baseUrl}\${redirectPath}\`;
98
-
99
- // Confirm receipt to Duct cloud (Duct will then instruct the user's browser to navigate)
100
- return NextResponse.json({
101
- success: true,
102
- redirect: redirectUrl,
103
- deeplinkId: deeplink_id,
104
- userId: sub,
105
- });
106
- }
107
-
108
- function buildRedirectPath(
109
- targetRoute: string,
110
- state: Record<string, unknown>
111
- ): string {
112
- // Replace path params [id] with state values
113
- let path = targetRoute;
114
- const paramMatches = targetRoute.matchAll(/\\[([^\\]]+)\\]/g);
115
-
116
- for (const match of paramMatches) {
117
- const paramName = match[1];
118
- // Try common naming patterns
119
- const value =
120
- state[paramName] ??
121
- state[\`\${paramName}Id\`] ??
122
- state[\`\${paramName}_id\`];
123
-
124
- if (value !== undefined) {
125
- path = path.replace(match[0], String(value));
126
- }
127
- }
128
-
129
- // Append remaining state as query params
130
- const usedKeys = new Set(
131
- [...targetRoute.matchAll(/\\[([^\\]]+)\\]/g)].map((m) => m[1])
132
- );
133
- const queryEntries = Object.entries(state).filter(
134
- ([key]) => !usedKeys.has(key)
135
- );
136
-
137
- if (queryEntries.length > 0) {
138
- const qs = new URLSearchParams(
139
- queryEntries.map(([k, v]) => [k, String(v)])
140
- ).toString();
141
- path += \`?\${qs}\`;
142
- }
143
-
144
- return path;
145
- }
10
+ return `/**
11
+ * Duct Deeplink Receiver — auto-generated by \`npx duct init\`
12
+ *
13
+ * This route receives signed deeplinks from the Duct shell and navigates
14
+ * the user to the correct page with pre-loaded state.
15
+ *
16
+ * Do not remove the signature verification step.
17
+ * Do not expose DUCT_SECRET_KEY client-side.
18
+ *
19
+ * Docs: ${docsBase}/deeplinks/receiver
20
+ */
21
+
22
+ import { NextRequest, NextResponse } from "next/server";
23
+ import { verifyDeeplinkToken } from "@duct-sdk/sdk";
24
+ import ductConfig from "../../../../duct.config";
25
+
26
+ // ── JTI replay protection ─────────────────────────────────────
27
+ // Tracks consumed deeplink token IDs so a replayed token is rejected.
28
+ // Each deeplink JWT has a \`jti\` claim; once consumed it is tracked for
29
+ // 10 minutes (double the 5-min token TTL) then pruned.
30
+ //
31
+ // This in-process Map works for single-instance and development deployments.
32
+ // For multi-replica or serverless production, replace with Redis SETNX:
33
+ // await redis.set(\`duct:jti:\${jti}\`, "1", "EX", 600, "NX")
34
+ // → returns null if already set (replay) or "OK" if new (proceed)
35
+ const _usedJtis = new Map<string, number>();
36
+ setInterval(() => {
37
+ const now = Date.now();
38
+ for (const [jti, at] of _usedJtis) {
39
+ if (now - at > 10 * 60 * 1000) _usedJtis.delete(jti);
40
+ }
41
+ }, 60_000).unref?.();
42
+
43
+ export async function POST(request: NextRequest) {
44
+ const secretKey = process.env.DUCT_SECRET_KEY;
45
+
46
+ if (!secretKey) {
47
+ console.error("[Duct] DUCT_SECRET_KEY environment variable is not set");
48
+ return NextResponse.json(
49
+ { error: "Server configuration error" },
50
+ { status: 500 }
51
+ );
52
+ }
53
+
54
+ // Get the token from the Authorization header or request body
55
+ const authHeader = request.headers.get("authorization");
56
+ let token: string | null = null;
57
+
58
+ if (authHeader?.startsWith("Bearer ")) {
59
+ token = authHeader.slice(7);
60
+ } else {
61
+ try {
62
+ const body = await request.json() as { token?: string };
63
+ token = body.token ?? null;
64
+ } catch {
65
+ return NextResponse.json(
66
+ { error: "Invalid request body" },
67
+ { status: 400 }
68
+ );
69
+ }
70
+ }
71
+
72
+ if (!token) {
73
+ return NextResponse.json(
74
+ { error: "No token provided" },
75
+ { status: 401 }
76
+ );
77
+ }
78
+
79
+ // Verify the deeplink token (signature, expiry, audience)
80
+ const verifyResult = await verifyDeeplinkToken(token, {
81
+ secretKey,
82
+ expectedShellId: ductConfig.shellId,
83
+ });
84
+
85
+ if (!verifyResult.valid || !verifyResult.payload) {
86
+ console.warn("[Duct] Invalid deeplink token:", verifyResult.error);
87
+ return NextResponse.json(
88
+ { error: "Invalid token", detail: verifyResult.error },
89
+ { status: 401 }
90
+ );
91
+ }
92
+
93
+ // ── Replay check: reject already-consumed JTIs ────────────
94
+ const jti = verifyResult.payload.jti as string | undefined;
95
+ if (jti) {
96
+ if (_usedJtis.has(jti)) {
97
+ console.warn("[Duct] Replayed deeplink token rejected:", jti);
98
+ return NextResponse.json(
99
+ { error: "Token already used" },
100
+ { status: 409 }
101
+ );
102
+ }
103
+ _usedJtis.set(jti, Date.now());
104
+ }
105
+
106
+ const { deeplink_id, state, sub } = verifyResult.payload as {
107
+ deeplink_id: string;
108
+ state: Record<string, unknown>;
109
+ sub?: string;
110
+ };
111
+
112
+ // Validate deeplink_id is in our config
113
+ const deeplinkDef = ductConfig.deeplinks.find((d) => d.id === deeplink_id);
114
+ if (!deeplinkDef) {
115
+ console.warn("[Duct] Unknown deeplink ID:", deeplink_id);
116
+ return NextResponse.json(
117
+ { error: "Unknown deeplink" },
118
+ { status: 400 }
119
+ );
120
+ }
121
+
122
+ // TODO: Add your application logic here
123
+ // For example: pre-load data, create a session, set cookies, etc.
124
+ console.log("[Duct] Received deeplink:", deeplink_id, "for user:", sub, "state:", state);
125
+
126
+ // Return the redirect URL that the Duct shell should navigate to
127
+ const redirectPath = buildRedirectPath(deeplinkDef.targetRoute, state);
128
+ const redirectUrl = \`\${ductConfig.product.baseUrl}\${redirectPath}\`;
129
+
130
+ // Confirm receipt to Duct cloud (Duct will then instruct the user's browser to navigate)
131
+ return NextResponse.json({
132
+ success: true,
133
+ redirect: redirectUrl,
134
+ deeplinkId: deeplink_id,
135
+ userId: sub,
136
+ });
137
+ }
138
+
139
+ function buildRedirectPath(
140
+ targetRoute: string,
141
+ state: Record<string, unknown>
142
+ ): string {
143
+ // Replace path params [id] with state values
144
+ let path = targetRoute;
145
+ const paramMatches = targetRoute.matchAll(/\\[([^\\]]+)\\]/g);
146
+
147
+ for (const match of paramMatches) {
148
+ const paramName = match[1];
149
+ // Try common naming patterns
150
+ const value =
151
+ state[paramName] ??
152
+ state[\`\${paramName}Id\`] ??
153
+ state[\`\${paramName}_id\`];
154
+
155
+ if (value !== undefined) {
156
+ path = path.replace(match[0], String(value));
157
+ }
158
+ }
159
+
160
+ // Append remaining state as query params
161
+ const usedKeys = new Set(
162
+ [...targetRoute.matchAll(/\\[([^\\]]+)\\]/g)].map((m) => m[1])
163
+ );
164
+ const queryEntries = Object.entries(state).filter(
165
+ ([key]) => !usedKeys.has(key)
166
+ );
167
+
168
+ if (queryEntries.length > 0) {
169
+ const qs = new URLSearchParams(
170
+ queryEntries.map(([k, v]) => [k, String(v)])
171
+ ).toString();
172
+ path += \`?\${qs}\`;
173
+ }
174
+
175
+ return path;
176
+ }
146
177
  `;
147
178
  }
148
179
  // ----------------------------------------------------------------
@@ -150,130 +181,153 @@ function buildRedirectPath(
150
181
  // ----------------------------------------------------------------
151
182
  function generateNextPagesRouterReceiver(_config) {
152
183
  const docsBase = "https://docs.your-domain.com"; // Consider injecting this dynamically if DUCT_URL is available
153
- return `/**
154
- * Duct Deeplink Receiver — auto-generated by \`npx duct init\`
155
- *
156
- * This route receives signed deeplinks from the Duct shell and navigates
157
- * the user to the correct page with pre-loaded state.
158
- *
159
- * Do not remove the signature verification step.
160
- * Do not expose DUCT_SECRET_KEY client-side.
161
- *
162
- * Docs: ${docsBase}/deeplinks/receiver
163
- */
164
-
165
- import type { NextApiRequest, NextApiResponse } from "next";
166
- import { verifyDeeplinkToken } from "@shoryasethia/duct-sdk";
167
- import ductConfig from "../../../duct.config";
168
-
169
- type ReceiveResponse = {
170
- success?: boolean;
171
- redirect?: string;
172
- deeplinkId?: string;
173
- userId?: string;
174
- error?: string;
175
- detail?: string;
176
- };
177
-
178
- export default async function handler(
179
- req: NextApiRequest,
180
- res: NextApiResponse<ReceiveResponse>
181
- ) {
182
- if (req.method !== "POST") {
183
- res.setHeader("Allow", "POST");
184
- return res.status(405).json({ error: "Method not allowed" });
185
- }
186
-
187
- const secretKey = process.env.DUCT_SECRET_KEY;
188
-
189
- if (!secretKey) {
190
- console.error("[Duct] DUCT_SECRET_KEY environment variable is not set");
191
- return res.status(500).json({ error: "Server configuration error" });
192
- }
193
-
194
- // Get token from Authorization header or body
195
- const authHeader = req.headers.authorization;
196
- let token: string | null = null;
197
-
198
- if (authHeader?.startsWith("Bearer ")) {
199
- token = authHeader.slice(7);
200
- } else if (typeof req.body === "object" && req.body !== null) {
201
- token = (req.body as { token?: string }).token ?? null;
202
- }
203
-
204
- if (!token) {
205
- return res.status(401).json({ error: "No token provided" });
206
- }
207
-
208
- const verifyResult = await verifyDeeplinkToken(token, {
209
- secretKey,
210
- expectedShellId: ductConfig.shellId,
211
- });
212
-
213
- if (!verifyResult.valid || !verifyResult.payload) {
214
- console.warn("[Duct] Invalid deeplink token:", verifyResult.error);
215
- return res.status(401).json({
216
- error: "Invalid token",
217
- detail: verifyResult.error,
218
- });
219
- }
220
-
221
- const { deeplink_id, state, sub } = verifyResult.payload;
222
-
223
- const deeplinkDef = ductConfig.deeplinks.find((d) => d.id === deeplink_id);
224
- if (!deeplinkDef) {
225
- return res.status(400).json({ error: "Unknown deeplink" });
226
- }
227
-
228
- // TODO: Add your application logic here
229
- console.log("[Duct] Received deeplink:", deeplink_id, "for user:", sub);
230
-
231
- const redirectPath = buildRedirectPath(deeplinkDef.targetRoute, state);
232
- const redirectUrl = \`\${ductConfig.product.baseUrl}\${redirectPath}\`;
233
-
234
- return res.status(200).json({
235
- success: true,
236
- redirect: redirectUrl,
237
- deeplinkId: deeplink_id,
238
- userId: sub,
239
- });
240
- }
241
-
242
- function buildRedirectPath(
243
- targetRoute: string,
244
- state: Record<string, unknown>
245
- ): string {
246
- let path = targetRoute;
247
- const paramMatches = targetRoute.matchAll(/\\[([^\\]]+)\\]/g);
248
-
249
- for (const match of paramMatches) {
250
- const paramName = match[1];
251
- const value =
252
- state[paramName] ??
253
- state[\`\${paramName}Id\`] ??
254
- state[\`\${paramName}_id\`];
255
-
256
- if (value !== undefined) {
257
- path = path.replace(match[0], String(value));
258
- }
259
- }
260
-
261
- const usedKeys = new Set(
262
- [...targetRoute.matchAll(/\\[([^\\]]+)\\]/g)].map((m) => m[1])
263
- );
264
- const queryEntries = Object.entries(state).filter(
265
- ([key]) => !usedKeys.has(key)
266
- );
267
-
268
- if (queryEntries.length > 0) {
269
- const qs = new URLSearchParams(
270
- queryEntries.map(([k, v]) => [k, String(v)])
271
- ).toString();
272
- path += \`?\${qs}\`;
273
- }
274
-
275
- return path;
276
- }
184
+ return `/**
185
+ * Duct Deeplink Receiver — auto-generated by \`npx duct init\`
186
+ *
187
+ * This route receives signed deeplinks from the Duct shell and navigates
188
+ * the user to the correct page with pre-loaded state.
189
+ *
190
+ * Do not remove the signature verification step.
191
+ * Do not expose DUCT_SECRET_KEY client-side.
192
+ *
193
+ * Docs: ${docsBase}/deeplinks/receiver
194
+ */
195
+
196
+ import type { NextApiRequest, NextApiResponse } from "next";
197
+ import { verifyDeeplinkToken } from "@duct-sdk/sdk";
198
+ import ductConfig from "../../../duct.config";
199
+
200
+ type ReceiveResponse = {
201
+ success?: boolean;
202
+ redirect?: string;
203
+ deeplinkId?: string;
204
+ userId?: string;
205
+ error?: string;
206
+ detail?: string;
207
+ };
208
+
209
+ // ── JTI replay protection (in-process; swap for Redis in multi-replica prod) ──
210
+ const _usedJtis = new Map<string, number>();
211
+ setInterval(() => {
212
+ const now = Date.now();
213
+ for (const [jti, at] of _usedJtis) {
214
+ if (now - at > 10 * 60 * 1000) _usedJtis.delete(jti);
215
+ }
216
+ }, 60_000).unref?.();
217
+
218
+ export default async function handler(
219
+ req: NextApiRequest,
220
+ res: NextApiResponse<ReceiveResponse>
221
+ ) {
222
+ if (req.method !== "POST") {
223
+ res.setHeader("Allow", "POST");
224
+ return res.status(405).json({ error: "Method not allowed" });
225
+ }
226
+
227
+ const secretKey = process.env.DUCT_SECRET_KEY;
228
+
229
+ if (!secretKey) {
230
+ console.error("[Duct] DUCT_SECRET_KEY environment variable is not set");
231
+ return res.status(500).json({ error: "Server configuration error" });
232
+ }
233
+
234
+ // Get token from Authorization header or body
235
+ const authHeader = req.headers.authorization;
236
+ let token: string | null = null;
237
+
238
+ if (authHeader?.startsWith("Bearer ")) {
239
+ token = authHeader.slice(7);
240
+ } else if (typeof req.body === "object" && req.body !== null) {
241
+ token = (req.body as { token?: string }).token ?? null;
242
+ }
243
+
244
+ if (!token) {
245
+ return res.status(401).json({ error: "No token provided" });
246
+ }
247
+
248
+ const verifyResult = await verifyDeeplinkToken(token, {
249
+ secretKey,
250
+ expectedShellId: ductConfig.shellId,
251
+ });
252
+
253
+ if (!verifyResult.valid || !verifyResult.payload) {
254
+ console.warn("[Duct] Invalid deeplink token:", verifyResult.error);
255
+ return res.status(401).json({
256
+ error: "Invalid token",
257
+ detail: verifyResult.error,
258
+ });
259
+ }
260
+
261
+ // Replay check
262
+ const jti = verifyResult.payload.jti as string | undefined;
263
+ if (jti) {
264
+ if (_usedJtis.has(jti)) {
265
+ console.warn("[Duct] Replayed deeplink token rejected:", jti);
266
+ return res.status(409).json({ error: "Token already used" });
267
+ }
268
+ _usedJtis.set(jti, Date.now());
269
+ }
270
+
271
+ const { deeplink_id, state, sub } = verifyResult.payload as {
272
+ deeplink_id: string;
273
+ state: Record<string, unknown>;
274
+ sub?: string;
275
+ };
276
+
277
+ const deeplinkDef = ductConfig.deeplinks.find((d) => d.id === deeplink_id);
278
+ if (!deeplinkDef) {
279
+ return res.status(400).json({ error: "Unknown deeplink" });
280
+ }
281
+
282
+ // TODO: Add your application logic here
283
+ console.log("[Duct] Received deeplink:", deeplink_id, "for user:", sub);
284
+
285
+ const redirectPath = buildRedirectPath(deeplinkDef.targetRoute, state);
286
+ const redirectUrl = \`\${ductConfig.product.baseUrl}\${redirectPath}\`;
287
+
288
+ return res.status(200).json({
289
+ success: true,
290
+ redirect: redirectUrl,
291
+ deeplinkId: deeplink_id,
292
+ userId: sub,
293
+ });
294
+ }
295
+
296
+ function buildRedirectPath(
297
+ targetRoute: string,
298
+ state: Record<string, unknown>
299
+ ): string {
300
+ let path = targetRoute;
301
+ const paramMatches = targetRoute.matchAll(/\\[([^\\]]+)\\]/g);
302
+
303
+ for (const match of paramMatches) {
304
+ const paramName = match[1];
305
+ const value =
306
+ state[paramName] ??
307
+ state[\`\${paramName}Id\`] ??
308
+ state[\`\${paramName}_id\`];
309
+
310
+ if (value !== undefined) {
311
+ path = path.replace(match[0], String(value));
312
+ }
313
+ }
314
+
315
+ const usedKeys = new Set(
316
+ [...targetRoute.matchAll(/\\[([^\\]]+)\\]/g)].map((m) => m[1])
317
+ );
318
+ const queryEntries = Object.entries(state).filter(
319
+ ([key]) => !usedKeys.has(key)
320
+ );
321
+
322
+ if (queryEntries.length > 0) {
323
+ const qs = new URLSearchParams(
324
+ queryEntries.map(([k, v]) => [k, String(v)])
325
+ ).toString();
326
+ path += \`?\${qs}\`;
327
+ }
328
+
329
+ return path;
330
+ }
277
331
  `;
278
332
  }
279
333
  // ----------------------------------------------------------------
@@ -281,119 +335,192 @@ function buildRedirectPath(
281
335
  // ----------------------------------------------------------------
282
336
  function generateTokenApiRoute(_config, framework) {
283
337
  if (framework.name === "sveltekit") {
284
- return `// src/routes/api/duct/token/+server.ts
285
- // Generated by @duct/sdk
286
- // This endpoint generates short-lived Duct tokens for authenticated users.
287
-
288
- import type { RequestHandler } from "@sveltejs/kit";
289
- import { json } from "@sveltejs/kit";
290
- import { generateDuctToken } from "@shoryasethia/duct-sdk";
291
-
292
- export const POST: RequestHandler = async ({ locals }) => {
293
- const secretKey = process.env.DUCT_SECRET_KEY;
294
- const shellId = process.env.PUBLIC_DUCT_SHELL_ID || process.env.NEXT_PUBLIC_DUCT_SHELL_ID;
295
-
296
- if (!secretKey || !shellId) {
297
- return json({ error: "Duct not configured" }, { status: 500 });
298
- }
299
-
300
- // Replace with your auth integration (locals.user/session from your hooks).
301
- const userSession = ((locals as Record<string, unknown>).user ?? {}) as Record<string, unknown>;
302
-
303
- const { token, expiresAt } = await generateDuctToken({
304
- secretKey,
305
- shellId,
306
- userSession,
307
- expirySeconds: 300,
308
- });
309
-
310
- return json({ token, expiresAt: expiresAt.toISOString() });
311
- };
338
+ return `// src/routes/api/duct/token/+server.ts
339
+ // Generated by @duct/sdk
340
+ // This endpoint generates short-lived Duct tokens for authenticated users.
341
+
342
+ import type { RequestHandler } from "@sveltejs/kit";
343
+ import { json } from "@sveltejs/kit";
344
+ import { generateDuctToken } from "@duct-sdk/sdk";
345
+
346
+ export const POST: RequestHandler = async ({ locals }) => {
347
+ const secretKey = process.env.DUCT_SECRET_KEY;
348
+ const shellId = process.env.PUBLIC_DUCT_SHELL_ID || process.env.NEXT_PUBLIC_DUCT_SHELL_ID;
349
+
350
+ if (!secretKey || !shellId) {
351
+ return json({ error: "Duct not configured" }, { status: 500 });
352
+ }
353
+
354
+ // Replace with your auth integration (locals.user/session from your hooks).
355
+ const userSession = ((locals as Record<string, unknown>).user ?? {}) as Record<string, unknown>;
356
+
357
+ const { token, expiresAt } = await generateDuctToken({
358
+ secretKey,
359
+ shellId,
360
+ userSession,
361
+ expirySeconds: 300,
362
+ });
363
+
364
+ return json({ token, expiresAt: expiresAt.toISOString() });
365
+ };
366
+ `;
367
+ }
368
+ if (framework.name === "remix") {
369
+ return `// app/routes/api.duct.token.ts
370
+ // Generated by @duct/sdk
371
+ // This endpoint generates short-lived Duct tokens for authenticated users.
372
+
373
+ import type { ActionFunctionArgs } from "@remix-run/node";
374
+ import { json } from "@remix-run/node";
375
+ import { generateDuctToken } from "@duct-sdk/sdk";
376
+
377
+ export async function action({ request }: ActionFunctionArgs) {
378
+ if (request.method !== "POST") {
379
+ return json({ error: "Method not allowed" }, { status: 405 });
380
+ }
381
+
382
+ const secretKey = process.env.DUCT_SECRET_KEY;
383
+ const shellId = process.env.VITE_DUCT_SHELL_ID ?? process.env.DUCT_SHELL_ID;
384
+
385
+ if (!secretKey || !shellId) {
386
+ return json({ error: "Duct not configured" }, { status: 500 });
387
+ }
388
+
389
+ // Replace with your auth integration.
390
+ // Example: const session = await getSession(request.headers.get("Cookie"));
391
+ // If your app requires auth for shell actions, return 401 when no session.
392
+ const userSession: Record<string, unknown> = {};
393
+
394
+ const { token, expiresAt } = await generateDuctToken({
395
+ secretKey,
396
+ shellId,
397
+ userSession,
398
+ expirySeconds: 300,
399
+ });
400
+
401
+ return json({ token, expiresAt: expiresAt.toISOString() });
402
+ }
403
+ `;
404
+ }
405
+ if (framework.name === "vite-react") {
406
+ return `// server/routes/duct-token.ts
407
+ // Generated by @duct/sdk
408
+ // This endpoint generates short-lived Duct tokens for authenticated users.
409
+
410
+ import { Router, Request, Response } from "express";
411
+ import { generateDuctToken } from "@duct-sdk/sdk";
412
+
413
+ const router = Router();
414
+
415
+ router.post("/api/duct/token", async (req: Request, res: Response) => {
416
+ const secretKey = process.env.DUCT_SECRET_KEY;
417
+ const shellId = process.env.VITE_DUCT_SHELL_ID ?? process.env.DUCT_SHELL_ID;
418
+
419
+ if (!secretKey || !shellId) {
420
+ return res.status(500).json({ error: "Duct not configured" });
421
+ }
422
+
423
+ // Replace with your existing auth/session lookup.
424
+ // Example: const user = req.user; or decode req.cookies/Authorization.
425
+ // If your app requires auth for shell actions, return 401 when no user.
426
+ const userSession = (req as Request & { user?: Record<string, unknown> }).user ?? {};
427
+
428
+ const { token, expiresAt } = await generateDuctToken({
429
+ secretKey,
430
+ shellId,
431
+ userSession,
432
+ expirySeconds: 300,
433
+ });
434
+
435
+ return res.status(200).json({ token, expiresAt: expiresAt.toISOString() });
436
+ });
437
+
438
+ export default router;
312
439
  `;
313
440
  }
314
441
  if (framework.hasAppRouter || framework.name === "next-app") {
315
- return `// app/api/duct/token/route.ts
316
- // Generated by @duct/sdk
317
- // This endpoint generates short-lived Duct tokens for authenticated users.
318
- // The Duct shell calls this when it needs to identify the current user.
319
-
320
- import { NextRequest, NextResponse } from "next/server";
321
- import { generateDuctToken } from "@shoryasethia/duct-sdk";
322
- import { getServerSession } from "next-auth"; // or your auth library
323
- // import { auth } from "@/auth"; // NextAuth v5
324
- // import { currentUser } from "@clerk/nextjs/server"; // Clerk
325
-
326
- export async function POST(_request: NextRequest) {
327
- const secretKey = process.env.DUCT_SECRET_KEY;
328
- const shellId = process.env.NEXT_PUBLIC_DUCT_SHELL_ID;
329
-
330
- if (!secretKey || !shellId) {
331
- return NextResponse.json(
332
- { error: "Duct not configured" },
333
- { status: 500 }
334
- );
335
- }
336
-
337
- // Get the current user session — replace with your auth library
338
- const session = await getServerSession();
339
-
340
- // If your app requires auth for the shell, return 401 for unauthenticated users
341
- // if (!session) {
342
- // return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
343
- // }
344
-
345
- const { token, expiresAt } = await generateDuctToken({
346
- secretKey,
347
- shellId,
348
- userSession: session?.user ?? {},
349
- expirySeconds: 300,
350
- });
351
-
352
- return NextResponse.json({ token, expiresAt: expiresAt.toISOString() });
353
- }
442
+ return `// app/api/duct/token/route.ts
443
+ // Generated by @duct/sdk
444
+ // This endpoint generates short-lived Duct tokens for authenticated users.
445
+ // The Duct shell calls this when it needs to identify the current user.
446
+
447
+ import { NextRequest, NextResponse } from "next/server";
448
+ import { generateDuctToken } from "@duct-sdk/sdk";
449
+ import { getServerSession } from "next-auth"; // or your auth library
450
+ // import { auth } from "@/auth"; // NextAuth v5
451
+ // import { currentUser } from "@clerk/nextjs/server"; // Clerk
452
+
453
+ export async function POST(_request: NextRequest) {
454
+ const secretKey = process.env.DUCT_SECRET_KEY;
455
+ const shellId = process.env.NEXT_PUBLIC_DUCT_SHELL_ID;
456
+
457
+ if (!secretKey || !shellId) {
458
+ return NextResponse.json(
459
+ { error: "Duct not configured" },
460
+ { status: 500 }
461
+ );
462
+ }
463
+
464
+ // Get the current user session — replace with your auth library
465
+ const session = await getServerSession();
466
+
467
+ // If your app requires auth for the shell, return 401 for unauthenticated users
468
+ // if (!session) {
469
+ // return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
470
+ // }
471
+
472
+ const { token, expiresAt } = await generateDuctToken({
473
+ secretKey,
474
+ shellId,
475
+ userSession: session?.user ?? {},
476
+ expirySeconds: 300,
477
+ });
478
+
479
+ return NextResponse.json({ token, expiresAt: expiresAt.toISOString() });
480
+ }
354
481
  `;
355
482
  }
356
- return `// pages/api/duct/token.ts
357
- // Generated by @duct/sdk
358
- // This endpoint generates short-lived Duct tokens for authenticated users.
359
-
360
- import type { NextApiRequest, NextApiResponse } from "next";
361
- import { generateDuctToken } from "@shoryasethia/duct-sdk";
362
- import { getServerSession } from "next-auth"; // or your auth library
363
-
364
- type TokenResponse = {
365
- token?: string;
366
- expiresAt?: string;
367
- error?: string;
368
- };
369
-
370
- export default async function handler(
371
- req: NextApiRequest,
372
- res: NextApiResponse<TokenResponse>
373
- ) {
374
- if (req.method !== "POST") {
375
- res.setHeader("Allow", "POST");
376
- return res.status(405).json({ error: "Method not allowed" });
377
- }
378
-
379
- const secretKey = process.env.DUCT_SECRET_KEY;
380
- const shellId = process.env.NEXT_PUBLIC_DUCT_SHELL_ID;
381
-
382
- if (!secretKey || !shellId) {
383
- return res.status(500).json({ error: "Duct not configured" });
384
- }
385
-
386
- const session = await getServerSession(req, res, {});
387
-
388
- const { token, expiresAt } = await generateDuctToken({
389
- secretKey,
390
- shellId,
391
- userSession: (session as { user?: Record<string, unknown> })?.user ?? {},
392
- expirySeconds: 300,
393
- });
394
-
395
- return res.status(200).json({ token, expiresAt: expiresAt.toISOString() });
396
- }
483
+ return `// pages/api/duct/token.ts
484
+ // Generated by @duct/sdk
485
+ // This endpoint generates short-lived Duct tokens for authenticated users.
486
+
487
+ import type { NextApiRequest, NextApiResponse } from "next";
488
+ import { generateDuctToken } from "@duct-sdk/sdk";
489
+ import { getServerSession } from "next-auth"; // or your auth library
490
+
491
+ type TokenResponse = {
492
+ token?: string;
493
+ expiresAt?: string;
494
+ error?: string;
495
+ };
496
+
497
+ export default async function handler(
498
+ req: NextApiRequest,
499
+ res: NextApiResponse<TokenResponse>
500
+ ) {
501
+ if (req.method !== "POST") {
502
+ res.setHeader("Allow", "POST");
503
+ return res.status(405).json({ error: "Method not allowed" });
504
+ }
505
+
506
+ const secretKey = process.env.DUCT_SECRET_KEY;
507
+ const shellId = process.env.NEXT_PUBLIC_DUCT_SHELL_ID;
508
+
509
+ if (!secretKey || !shellId) {
510
+ return res.status(500).json({ error: "Duct not configured" });
511
+ }
512
+
513
+ const session = await getServerSession(req, res, {});
514
+
515
+ const { token, expiresAt } = await generateDuctToken({
516
+ secretKey,
517
+ shellId,
518
+ userSession: (session as { user?: Record<string, unknown> })?.user ?? {},
519
+ expirySeconds: 300,
520
+ });
521
+
522
+ return res.status(200).json({ token, expiresAt: expiresAt.toISOString() });
523
+ }
397
524
  `;
398
525
  }
399
526
  // ----------------------------------------------------------------
@@ -432,73 +559,73 @@ export function generateTokenRoute(config, framework) {
432
559
  // ----------------------------------------------------------------
433
560
  function generateRemixReceiver(_config) {
434
561
  const docsBase = "https://docs.your-domain.com"; // Consider injecting this dynamically if DUCT_URL is available
435
- return `/**
436
- * Duct Deeplink Receiver — auto-generated by \`npx duct init\`
437
- *
438
- * This route receives signed deeplinks from the Duct shell and navigates
439
- * the user to the correct page with pre-loaded state.
440
- *
441
- * Do not remove the signature verification step.
442
- * Do not expose DUCT_SECRET_KEY client-side.
443
- *
444
- * Docs: ${docsBase}/deeplinks/receiver
445
- */
446
-
447
- import type { ActionFunctionArgs } from "@remix-run/node";
448
- import { json } from "@remix-run/node";
449
- import { verifyDeeplinkToken } from "@shoryasethia/duct-sdk";
450
- import ductConfig from "../../duct.config";
451
-
452
- export async function action({ request }: ActionFunctionArgs) {
453
- if (request.method !== "POST") {
454
- return json({ error: "Method not allowed" }, { status: 405 });
455
- }
456
-
457
- const secretKey = process.env.DUCT_SECRET_KEY;
458
- if (!secretKey) {
459
- return json({ error: "Server configuration error" }, { status: 500 });
460
- }
461
-
462
- const authHeader = request.headers.get("authorization");
463
- let token: string | null = null;
464
-
465
- if (authHeader?.startsWith("Bearer ")) {
466
- token = authHeader.slice(7);
467
- } else {
468
- const body = await request.json() as { token?: string };
469
- token = body.token ?? null;
470
- }
471
-
472
- if (!token) {
473
- return json({ error: "No token provided" }, { status: 401 });
474
- }
475
-
476
- const verifyResult = await verifyDeeplinkToken(token, {
477
- secretKey,
478
- expectedShellId: ductConfig.shellId,
479
- });
480
-
481
- if (!verifyResult.valid || !verifyResult.payload) {
482
- return json({ error: "Invalid token" }, { status: 401 });
483
- }
484
-
485
- const { deeplink_id, state, sub } = verifyResult.payload;
486
- const deeplinkDef = ductConfig.deeplinks.find((d) => d.id === deeplink_id);
487
-
488
- if (!deeplinkDef) {
489
- return json({ error: "Unknown deeplink" }, { status: 400 });
490
- }
491
-
492
- const redirectUrl = \`\${ductConfig.product.baseUrl}\${deeplinkDef.targetRoute}\`;
493
-
494
- return json({
495
- success: true,
496
- redirect: redirectUrl,
497
- deeplinkId: deeplink_id,
498
- userId: sub,
499
- state,
500
- });
501
- }
562
+ return `/**
563
+ * Duct Deeplink Receiver — auto-generated by \`npx duct init\`
564
+ *
565
+ * This route receives signed deeplinks from the Duct shell and navigates
566
+ * the user to the correct page with pre-loaded state.
567
+ *
568
+ * Do not remove the signature verification step.
569
+ * Do not expose DUCT_SECRET_KEY client-side.
570
+ *
571
+ * Docs: ${docsBase}/deeplinks/receiver
572
+ */
573
+
574
+ import type { ActionFunctionArgs } from "@remix-run/node";
575
+ import { json } from "@remix-run/node";
576
+ import { verifyDeeplinkToken } from "@duct-sdk/sdk";
577
+ import ductConfig from "../../duct.config";
578
+
579
+ export async function action({ request }: ActionFunctionArgs) {
580
+ if (request.method !== "POST") {
581
+ return json({ error: "Method not allowed" }, { status: 405 });
582
+ }
583
+
584
+ const secretKey = process.env.DUCT_SECRET_KEY;
585
+ if (!secretKey) {
586
+ return json({ error: "Server configuration error" }, { status: 500 });
587
+ }
588
+
589
+ const authHeader = request.headers.get("authorization");
590
+ let token: string | null = null;
591
+
592
+ if (authHeader?.startsWith("Bearer ")) {
593
+ token = authHeader.slice(7);
594
+ } else {
595
+ const body = await request.json() as { token?: string };
596
+ token = body.token ?? null;
597
+ }
598
+
599
+ if (!token) {
600
+ return json({ error: "No token provided" }, { status: 401 });
601
+ }
602
+
603
+ const verifyResult = await verifyDeeplinkToken(token, {
604
+ secretKey,
605
+ expectedShellId: ductConfig.shellId,
606
+ });
607
+
608
+ if (!verifyResult.valid || !verifyResult.payload) {
609
+ return json({ error: "Invalid token" }, { status: 401 });
610
+ }
611
+
612
+ const { deeplink_id, state, sub } = verifyResult.payload;
613
+ const deeplinkDef = ductConfig.deeplinks.find((d) => d.id === deeplink_id);
614
+
615
+ if (!deeplinkDef) {
616
+ return json({ error: "Unknown deeplink" }, { status: 400 });
617
+ }
618
+
619
+ const redirectUrl = \`\${ductConfig.product.baseUrl}\${deeplinkDef.targetRoute}\`;
620
+
621
+ return json({
622
+ success: true,
623
+ redirect: redirectUrl,
624
+ deeplinkId: deeplink_id,
625
+ userId: sub,
626
+ state,
627
+ });
628
+ }
502
629
  `;
503
630
  }
504
631
  // ----------------------------------------------------------------
@@ -506,71 +633,71 @@ export async function action({ request }: ActionFunctionArgs) {
506
633
  // ----------------------------------------------------------------
507
634
  function generateExpressReceiver(_config) {
508
635
  const docsBase = "https://docs.your-domain.com"; // Consider injecting this dynamically if DUCT_URL is available
509
- return `/**
510
- * Duct Deeplink Receiver — auto-generated by \`npx duct init\`
511
- *
512
- * This route receives signed deeplinks from the Duct shell and navigates
513
- * the user to the correct page with pre-loaded state.
514
- *
515
- * Do not remove the signature verification step.
516
- * Do not expose DUCT_SECRET_KEY client-side.
517
- *
518
- * Docs: ${docsBase}/deeplinks/receiver
519
- */
520
-
521
- import { Router, Request, Response } from "express";
522
- import { verifyDeeplinkToken } from "@shoryasethia/duct-sdk";
523
- import ductConfig from "../../duct.config";
524
-
525
- const router = Router();
526
-
527
- router.post("/api/duct/receive", async (req: Request, res: Response) => {
528
- const secretKey = process.env.DUCT_SECRET_KEY;
529
- if (!secretKey) {
530
- return res.status(500).json({ error: "Server configuration error" });
531
- }
532
-
533
- const authHeader = req.headers.authorization;
534
- let token: string | null = null;
535
-
536
- if (authHeader?.startsWith("Bearer ")) {
537
- token = authHeader.slice(7);
538
- } else if (req.body?.token) {
539
- token = req.body.token as string;
540
- }
541
-
542
- if (!token) {
543
- return res.status(401).json({ error: "No token provided" });
544
- }
545
-
546
- const verifyResult = await verifyDeeplinkToken(token, {
547
- secretKey,
548
- expectedShellId: ductConfig.shellId,
549
- });
550
-
551
- if (!verifyResult.valid || !verifyResult.payload) {
552
- return res.status(401).json({ error: "Invalid token" });
553
- }
554
-
555
- const { deeplink_id, state, sub } = verifyResult.payload;
556
- const deeplinkDef = ductConfig.deeplinks.find((d) => d.id === deeplink_id);
557
-
558
- if (!deeplinkDef) {
559
- return res.status(400).json({ error: "Unknown deeplink" });
560
- }
561
-
562
- const redirectUrl = \`\${ductConfig.product.baseUrl}\${deeplinkDef.targetRoute}\`;
563
-
564
- return res.json({
565
- success: true,
566
- redirect: redirectUrl,
567
- deeplinkId: deeplink_id,
568
- userId: sub,
569
- state,
570
- });
571
- });
572
-
573
- export default router;
636
+ return `/**
637
+ * Duct Deeplink Receiver — auto-generated by \`npx duct init\`
638
+ *
639
+ * This route receives signed deeplinks from the Duct shell and navigates
640
+ * the user to the correct page with pre-loaded state.
641
+ *
642
+ * Do not remove the signature verification step.
643
+ * Do not expose DUCT_SECRET_KEY client-side.
644
+ *
645
+ * Docs: ${docsBase}/deeplinks/receiver
646
+ */
647
+
648
+ import { Router, Request, Response } from "express";
649
+ import { verifyDeeplinkToken } from "@duct-sdk/sdk";
650
+ import ductConfig from "../../duct.config";
651
+
652
+ const router = Router();
653
+
654
+ router.post("/api/duct/receive", async (req: Request, res: Response) => {
655
+ const secretKey = process.env.DUCT_SECRET_KEY;
656
+ if (!secretKey) {
657
+ return res.status(500).json({ error: "Server configuration error" });
658
+ }
659
+
660
+ const authHeader = req.headers.authorization;
661
+ let token: string | null = null;
662
+
663
+ if (authHeader?.startsWith("Bearer ")) {
664
+ token = authHeader.slice(7);
665
+ } else if (req.body?.token) {
666
+ token = req.body.token as string;
667
+ }
668
+
669
+ if (!token) {
670
+ return res.status(401).json({ error: "No token provided" });
671
+ }
672
+
673
+ const verifyResult = await verifyDeeplinkToken(token, {
674
+ secretKey,
675
+ expectedShellId: ductConfig.shellId,
676
+ });
677
+
678
+ if (!verifyResult.valid || !verifyResult.payload) {
679
+ return res.status(401).json({ error: "Invalid token" });
680
+ }
681
+
682
+ const { deeplink_id, state, sub } = verifyResult.payload;
683
+ const deeplinkDef = ductConfig.deeplinks.find((d) => d.id === deeplink_id);
684
+
685
+ if (!deeplinkDef) {
686
+ return res.status(400).json({ error: "Unknown deeplink" });
687
+ }
688
+
689
+ const redirectUrl = \`\${ductConfig.product.baseUrl}\${deeplinkDef.targetRoute}\`;
690
+
691
+ return res.json({
692
+ success: true,
693
+ redirect: redirectUrl,
694
+ deeplinkId: deeplink_id,
695
+ userId: sub,
696
+ state,
697
+ });
698
+ });
699
+
700
+ export default router;
574
701
  `;
575
702
  }
576
703
  // ----------------------------------------------------------------
@@ -578,106 +705,106 @@ export default router;
578
705
  // ----------------------------------------------------------------
579
706
  function generateSvelteKitReceiver(_config) {
580
707
  const docsBase = "https://docs.your-domain.com";
581
- return `/**
582
- * Duct Deeplink Receiver — auto-generated by \`npx duct init\`
583
- *
584
- * This route receives signed deeplinks from the Duct shell and navigates
585
- * the user to the correct page with pre-loaded state.
586
- *
587
- * Docs: ${docsBase}/deeplinks/receiver
588
- */
589
-
590
- import type { RequestHandler } from "@sveltejs/kit";
591
- import { json } from "@sveltejs/kit";
592
- import { verifyDeeplinkToken } from "@shoryasethia/duct-sdk";
593
- import ductConfig from "../../../../../duct.config";
594
-
595
- export const POST: RequestHandler = async ({ request }) => {
596
- const secretKey = process.env.DUCT_SECRET_KEY;
597
-
598
- if (!secretKey) {
599
- return json({ error: "Server configuration error" }, { status: 500 });
600
- }
601
-
602
- const authHeader = request.headers.get("authorization");
603
- let token: string | null = null;
604
-
605
- if (authHeader?.startsWith("Bearer ")) {
606
- token = authHeader.slice(7);
607
- } else {
608
- try {
609
- const body = (await request.json()) as { token?: string };
610
- token = body.token ?? null;
611
- } catch {
612
- return json({ error: "Invalid request body" }, { status: 400 });
613
- }
614
- }
615
-
616
- if (!token) {
617
- return json({ error: "No token provided" }, { status: 401 });
618
- }
619
-
620
- const verifyResult = await verifyDeeplinkToken(token, {
621
- secretKey,
622
- expectedShellId: ductConfig.shellId,
623
- });
624
-
625
- if (!verifyResult.valid || !verifyResult.payload) {
626
- return json({ error: "Invalid token", detail: verifyResult.error }, { status: 401 });
627
- }
628
-
629
- const { deeplink_id, state, sub } = verifyResult.payload;
630
- const deeplinkDef = ductConfig.deeplinks.find((d) => d.id === deeplink_id);
631
-
632
- if (!deeplinkDef) {
633
- return json({ error: "Unknown deeplink" }, { status: 400 });
634
- }
635
-
636
- const redirectPath = buildRedirectPath(deeplinkDef.targetRoute, state);
637
- const redirectUrl = \`\${ductConfig.product.baseUrl}\${redirectPath}\`;
638
-
639
- return json({
640
- success: true,
641
- redirect: redirectUrl,
642
- deeplinkId: deeplink_id,
643
- userId: sub,
644
- });
645
- };
646
-
647
- function buildRedirectPath(
648
- targetRoute: string,
649
- state: Record<string, unknown>
650
- ): string {
651
- let path = targetRoute;
652
- const paramMatches = targetRoute.matchAll(/\\[([^\\]]+)\\]/g);
653
-
654
- for (const match of paramMatches) {
655
- const paramName = match[1];
656
- const value =
657
- state[paramName] ??
658
- state[\`\${paramName}Id\`] ??
659
- state[\`\${paramName}_id\`];
660
-
661
- if (value !== undefined) {
662
- path = path.replace(match[0], String(value));
663
- }
664
- }
665
-
666
- const usedKeys = new Set(
667
- [...targetRoute.matchAll(/\\[([^\\]]+)\\]/g)].map((m) => m[1])
668
- );
669
- const queryEntries = Object.entries(state).filter(
670
- ([key]) => !usedKeys.has(key)
671
- );
672
-
673
- if (queryEntries.length > 0) {
674
- const qs = new URLSearchParams(
675
- queryEntries.map(([k, v]) => [k, String(v)])
676
- ).toString();
677
- path += \`?\${qs}\`;
678
- }
679
-
680
- return path;
681
- }
708
+ return `/**
709
+ * Duct Deeplink Receiver — auto-generated by \`npx duct init\`
710
+ *
711
+ * This route receives signed deeplinks from the Duct shell and navigates
712
+ * the user to the correct page with pre-loaded state.
713
+ *
714
+ * Docs: ${docsBase}/deeplinks/receiver
715
+ */
716
+
717
+ import type { RequestHandler } from "@sveltejs/kit";
718
+ import { json } from "@sveltejs/kit";
719
+ import { verifyDeeplinkToken } from "@duct-sdk/sdk";
720
+ import ductConfig from "../../../../../duct.config";
721
+
722
+ export const POST: RequestHandler = async ({ request }) => {
723
+ const secretKey = process.env.DUCT_SECRET_KEY;
724
+
725
+ if (!secretKey) {
726
+ return json({ error: "Server configuration error" }, { status: 500 });
727
+ }
728
+
729
+ const authHeader = request.headers.get("authorization");
730
+ let token: string | null = null;
731
+
732
+ if (authHeader?.startsWith("Bearer ")) {
733
+ token = authHeader.slice(7);
734
+ } else {
735
+ try {
736
+ const body = (await request.json()) as { token?: string };
737
+ token = body.token ?? null;
738
+ } catch {
739
+ return json({ error: "Invalid request body" }, { status: 400 });
740
+ }
741
+ }
742
+
743
+ if (!token) {
744
+ return json({ error: "No token provided" }, { status: 401 });
745
+ }
746
+
747
+ const verifyResult = await verifyDeeplinkToken(token, {
748
+ secretKey,
749
+ expectedShellId: ductConfig.shellId,
750
+ });
751
+
752
+ if (!verifyResult.valid || !verifyResult.payload) {
753
+ return json({ error: "Invalid token", detail: verifyResult.error }, { status: 401 });
754
+ }
755
+
756
+ const { deeplink_id, state, sub } = verifyResult.payload;
757
+ const deeplinkDef = ductConfig.deeplinks.find((d) => d.id === deeplink_id);
758
+
759
+ if (!deeplinkDef) {
760
+ return json({ error: "Unknown deeplink" }, { status: 400 });
761
+ }
762
+
763
+ const redirectPath = buildRedirectPath(deeplinkDef.targetRoute, state);
764
+ const redirectUrl = \`\${ductConfig.product.baseUrl}\${redirectPath}\`;
765
+
766
+ return json({
767
+ success: true,
768
+ redirect: redirectUrl,
769
+ deeplinkId: deeplink_id,
770
+ userId: sub,
771
+ });
772
+ };
773
+
774
+ function buildRedirectPath(
775
+ targetRoute: string,
776
+ state: Record<string, unknown>
777
+ ): string {
778
+ let path = targetRoute;
779
+ const paramMatches = targetRoute.matchAll(/\\[([^\\]]+)\\]/g);
780
+
781
+ for (const match of paramMatches) {
782
+ const paramName = match[1];
783
+ const value =
784
+ state[paramName] ??
785
+ state[\`\${paramName}Id\`] ??
786
+ state[\`\${paramName}_id\`];
787
+
788
+ if (value !== undefined) {
789
+ path = path.replace(match[0], String(value));
790
+ }
791
+ }
792
+
793
+ const usedKeys = new Set(
794
+ [...targetRoute.matchAll(/\\[([^\\]]+)\\]/g)].map((m) => m[1])
795
+ );
796
+ const queryEntries = Object.entries(state).filter(
797
+ ([key]) => !usedKeys.has(key)
798
+ );
799
+
800
+ if (queryEntries.length > 0) {
801
+ const qs = new URLSearchParams(
802
+ queryEntries.map(([k, v]) => [k, String(v)])
803
+ ).toString();
804
+ path += \`?\${qs}\`;
805
+ }
806
+
807
+ return path;
808
+ }
682
809
  `;
683
810
  }