@duct-sdk/sdk 0.1.6

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 (70) hide show
  1. package/README.md +92 -0
  2. package/dist/adapters/next/index.d.ts +4 -0
  3. package/dist/adapters/next/index.js +5 -0
  4. package/dist/adapters/next/receiver.d.ts +44 -0
  5. package/dist/adapters/next/receiver.js +162 -0
  6. package/dist/adapters/next/shell.d.ts +88 -0
  7. package/dist/adapters/next/shell.js +255 -0
  8. package/dist/adapters/react/index.d.ts +2 -0
  9. package/dist/adapters/react/index.js +4 -0
  10. package/dist/adapters/react/shell.d.ts +88 -0
  11. package/dist/adapters/react/shell.js +255 -0
  12. package/dist/adapters/remix/index.d.ts +2 -0
  13. package/dist/adapters/remix/index.js +4 -0
  14. package/dist/adapters/remix/receiver.d.ts +44 -0
  15. package/dist/adapters/remix/receiver.js +153 -0
  16. package/dist/adapters/sveltekit/index.d.ts +2 -0
  17. package/dist/adapters/sveltekit/index.js +4 -0
  18. package/dist/adapters/sveltekit/receiver.d.ts +56 -0
  19. package/dist/adapters/sveltekit/receiver.js +154 -0
  20. package/dist/adapters/vite/index.d.ts +2 -0
  21. package/dist/adapters/vite/index.js +4 -0
  22. package/dist/adapters/vite/receiver.d.ts +82 -0
  23. package/dist/adapters/vite/receiver.js +164 -0
  24. package/dist/assets/logo.d.ts +1 -0
  25. package/dist/assets/logo.js +1 -0
  26. package/dist/cli/agents/api-agent.d.ts +14 -0
  27. package/dist/cli/agents/api-agent.js +656 -0
  28. package/dist/cli/agents/auth-agent.d.ts +6 -0
  29. package/dist/cli/agents/auth-agent.js +198 -0
  30. package/dist/cli/agents/deeplink-agent.d.ts +6 -0
  31. package/dist/cli/agents/deeplink-agent.js +263 -0
  32. package/dist/cli/agents/llm.d.ts +33 -0
  33. package/dist/cli/agents/llm.js +276 -0
  34. package/dist/cli/agents/pipeline.d.ts +51 -0
  35. package/dist/cli/agents/pipeline.js +236 -0
  36. package/dist/cli/agents/reviewer-agent.d.ts +11 -0
  37. package/dist/cli/agents/reviewer-agent.js +442 -0
  38. package/dist/cli/agents/route-agent.d.ts +13 -0
  39. package/dist/cli/agents/route-agent.js +346 -0
  40. package/dist/cli/detectors/auth.d.ts +18 -0
  41. package/dist/cli/detectors/auth.js +273 -0
  42. package/dist/cli/detectors/framework.d.ts +22 -0
  43. package/dist/cli/detectors/framework.js +242 -0
  44. package/dist/cli/drift.d.ts +39 -0
  45. package/dist/cli/drift.js +247 -0
  46. package/dist/cli/fs/sandbox.d.ts +77 -0
  47. package/dist/cli/fs/sandbox.js +295 -0
  48. package/dist/cli/generators/config.d.ts +7 -0
  49. package/dist/cli/generators/config.js +255 -0
  50. package/dist/cli/generators/receiver.d.ts +12 -0
  51. package/dist/cli/generators/receiver.js +683 -0
  52. package/dist/cli/generators/shell.d.ts +18 -0
  53. package/dist/cli/generators/shell.js +672 -0
  54. package/dist/cli/index.d.ts +2 -0
  55. package/dist/cli/index.js +603 -0
  56. package/dist/cli/init.d.ts +26 -0
  57. package/dist/cli/init.js +835 -0
  58. package/dist/core/action.d.ts +37 -0
  59. package/dist/core/action.js +140 -0
  60. package/dist/core/config.d.ts +514 -0
  61. package/dist/core/config.js +221 -0
  62. package/dist/core/endpoints.d.ts +17 -0
  63. package/dist/core/endpoints.js +128 -0
  64. package/dist/core/token.d.ts +70 -0
  65. package/dist/core/token.js +174 -0
  66. package/dist/core/types.d.ts +450 -0
  67. package/dist/core/types.js +11 -0
  68. package/dist/index.d.ts +7 -0
  69. package/dist/index.js +9 -0
  70. package/package.json +84 -0
@@ -0,0 +1,683 @@
1
+ // ============================================================
2
+ // @duct/sdk — Receiver File Generator
3
+ // Generates framework-specific deeplink receiver routes
4
+ // ============================================================
5
+ // ----------------------------------------------------------------
6
+ // Next.js App Router receiver
7
+ // ----------------------------------------------------------------
8
+ function generateNextAppRouterReceiver(_config) {
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
+ }
146
+ `;
147
+ }
148
+ // ----------------------------------------------------------------
149
+ // Next.js Pages Router receiver
150
+ // ----------------------------------------------------------------
151
+ function generateNextPagesRouterReceiver(_config) {
152
+ 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
+ }
277
+ `;
278
+ }
279
+ // ----------------------------------------------------------------
280
+ // Token API route generator
281
+ // ----------------------------------------------------------------
282
+ function generateTokenApiRoute(_config, framework) {
283
+ 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
+ };
312
+ `;
313
+ }
314
+ 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
+ }
354
+ `;
355
+ }
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
+ }
397
+ `;
398
+ }
399
+ // ----------------------------------------------------------------
400
+ // generateReceiver
401
+ // ----------------------------------------------------------------
402
+ /**
403
+ * Generate a framework-specific receiver file.
404
+ *
405
+ * @returns Object with file paths and their contents
406
+ */
407
+ export function generateReceiver(config, framework) {
408
+ switch (framework.name) {
409
+ case "next-app":
410
+ return generateNextAppRouterReceiver(config);
411
+ case "next-pages":
412
+ return generateNextPagesRouterReceiver(config);
413
+ case "remix":
414
+ return generateRemixReceiver(config);
415
+ case "sveltekit":
416
+ return generateSvelteKitReceiver(config);
417
+ case "vite-react":
418
+ return generateExpressReceiver(config);
419
+ default:
420
+ // Fall back to App Router if unknown
421
+ return generateNextAppRouterReceiver(config);
422
+ }
423
+ }
424
+ /**
425
+ * Generate the token API route file (separate from the receiver).
426
+ */
427
+ export function generateTokenRoute(config, framework) {
428
+ return generateTokenApiRoute(config, framework);
429
+ }
430
+ // ----------------------------------------------------------------
431
+ // Remix receiver
432
+ // ----------------------------------------------------------------
433
+ function generateRemixReceiver(_config) {
434
+ 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
+ }
502
+ `;
503
+ }
504
+ // ----------------------------------------------------------------
505
+ // Express/Vite-React receiver
506
+ // ----------------------------------------------------------------
507
+ function generateExpressReceiver(_config) {
508
+ 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;
574
+ `;
575
+ }
576
+ // ----------------------------------------------------------------
577
+ // SvelteKit receiver
578
+ // ----------------------------------------------------------------
579
+ function generateSvelteKitReceiver(_config) {
580
+ 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
+ }
682
+ `;
683
+ }
@@ -0,0 +1,18 @@
1
+ import type { DuctConfig } from "../../core/types.js";
2
+ import type { FrameworkInfo } from "../detectors/framework.js";
3
+ export declare function generateEnvTemplate(config: DuctConfig, framework: FrameworkInfo): string;
4
+ export declare function generateEnvTemplateForFramework(config: DuctConfig, framework: FrameworkInfo): string;
5
+ /** Returns the filename init.ts should write the env template to. */
6
+ export declare function getEnvTemplateName(framework: FrameworkInfo): string;
7
+ /**
8
+ * Generate a framework-specific shell component file.
9
+ * Returns the file contents as a string.
10
+ *
11
+ * File extension is baked into the content header comment so the caller
12
+ * (init.ts getOutputPaths) knows what path to write to.
13
+ */
14
+ export declare function generateShell(config: DuctConfig, framework: FrameworkInfo): string;
15
+ /**
16
+ * Generate the layout integration snippet for a given framework.
17
+ */
18
+ export declare function generateLayoutSnippet(config: DuctConfig, framework: FrameworkInfo): string;