@duct-sdk/sdk 0.4.5 → 0.5.1

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/CHANGELOG.md +45 -0
  2. package/README.md +36 -1
  3. package/TOKEN_SPEC.md +237 -0
  4. package/dist/adapters/react/page-context-guard.d.ts +7 -0
  5. package/dist/adapters/react/page-context-guard.js +26 -0
  6. package/dist/adapters/react/page-context-guard.test.d.ts +1 -0
  7. package/dist/adapters/react/page-context-guard.test.js +15 -0
  8. package/dist/adapters/react/shell.js +1 -23
  9. package/dist/adapters/react/use-page-context.d.ts +1 -1
  10. package/dist/adapters/react/use-page-context.js +6 -16
  11. package/dist/cli/agents/reviewer-agent.d.ts +3 -1
  12. package/dist/cli/agents/reviewer-agent.js +29 -21
  13. package/dist/cli/config-loader.d.ts +15 -0
  14. package/dist/cli/config-loader.js +187 -0
  15. package/dist/cli/config-loader.test.d.ts +1 -0
  16. package/dist/cli/config-loader.test.js +63 -0
  17. package/dist/cli/detectors/framework.d.ts +1 -1
  18. package/dist/cli/detectors/framework.js +40 -0
  19. package/dist/cli/generators/receiver.js +206 -76
  20. package/dist/cli/generators/shell.js +50 -4
  21. package/dist/cli/generators/shell.test.d.ts +1 -0
  22. package/dist/cli/generators/shell.test.js +73 -0
  23. package/dist/cli/generators/token-route.d.ts +1 -0
  24. package/dist/cli/generators/token-route.js +108 -5
  25. package/dist/cli/generators/wiring-snippets.js +59 -19
  26. package/dist/cli/generators/wiring-snippets.test.js +15 -1
  27. package/dist/cli/index.js +108 -151
  28. package/dist/cli/init.js +110 -17
  29. package/dist/cli/manifest-diff.d.ts +21 -0
  30. package/dist/cli/manifest-diff.js +158 -0
  31. package/dist/cli/manifest-diff.test.d.ts +1 -0
  32. package/dist/cli/manifest-diff.test.js +104 -0
  33. package/dist/cli/output-paths.d.ts +2 -0
  34. package/dist/cli/output-paths.js +22 -4
  35. package/dist/core/config-policy.test.d.ts +1 -0
  36. package/dist/core/config-policy.test.js +101 -0
  37. package/dist/core/config.d.ts +86 -1
  38. package/dist/core/config.js +120 -2
  39. package/dist/core/invariants.test.d.ts +1 -0
  40. package/dist/core/invariants.test.js +217 -0
  41. package/dist/core/jcs.d.ts +5 -0
  42. package/dist/core/jcs.js +21 -0
  43. package/dist/core/receipt.d.ts +70 -0
  44. package/dist/core/receipt.js +86 -0
  45. package/dist/core/receipt.test.d.ts +1 -0
  46. package/dist/core/receipt.test.js +75 -0
  47. package/dist/core/replay-store.d.ts +51 -0
  48. package/dist/core/replay-store.js +65 -0
  49. package/dist/core/token.d.ts +14 -0
  50. package/dist/core/token.js +50 -18
  51. package/dist/core/token.test.d.ts +1 -0
  52. package/dist/core/token.test.js +66 -0
  53. package/dist/core/types.d.ts +72 -0
  54. package/dist/index.d.ts +6 -4
  55. package/dist/index.js +4 -2
  56. package/dist/server.d.ts +6 -4
  57. package/dist/server.js +4 -2
  58. package/package.json +91 -90
@@ -4,6 +4,12 @@
4
4
  // ============================================================
5
5
  import { getDocsUrl } from "../../core/endpoints.js";
6
6
  import { generateStrategyTokenRoute, } from "./token-route.js";
7
+ const REPLAY_STORE_IMPORT = `import { verifyDeeplinkToken, createDevReplayStore } from "@duct-sdk/sdk/server";
8
+
9
+ /** In-process replay store — dev/single-instance only. Use RedisReplayStore in production. */
10
+ const replayStore = createDevReplayStore();`;
11
+ const REPLAY_STORE_VERIFY_OPTIONS = `,
12
+ replayStore,`;
7
13
  // ----------------------------------------------------------------
8
14
  // Next.js App Router receiver
9
15
  // ----------------------------------------------------------------
@@ -18,30 +24,18 @@ function generateNextAppRouterReceiver(_config) {
18
24
  * Do not remove the signature verification step.
19
25
  * Do not expose DUCT_SECRET_KEY client-side.
20
26
  *
27
+ * Replay protection: deeplink JWTs carry a single-use \`jti\` claim. The
28
+ * in-process replayStore below is dev/single-instance only — use
29
+ * RedisReplayStore from @duct-sdk/sdk/server in production so the same
30
+ * token cannot be verified twice across replicas.
31
+ *
21
32
  * Docs: ${docsBase}/deeplinks/receiver
22
33
  */
23
34
 
24
35
  import { NextRequest, NextResponse } from "next/server";
25
- import { verifyDeeplinkToken } from "@duct-sdk/sdk/server";
36
+ ${REPLAY_STORE_IMPORT}
26
37
  import ductConfig from "../../../../duct.config";
27
38
 
28
- // ── JTI replay protection ─────────────────────────────────────
29
- // Tracks consumed deeplink token IDs so a replayed token is rejected.
30
- // Each deeplink JWT has a \`jti\` claim; once consumed it is tracked for
31
- // 10 minutes (double the 5-min token TTL) then pruned.
32
- //
33
- // This in-process Map works for single-instance and development deployments.
34
- // For multi-replica or serverless production, replace with Redis SETNX:
35
- // await redis.set(\`duct:jti:\${jti}\`, "1", "EX", 600, "NX")
36
- // → returns null if already set (replay) or "OK" if new (proceed)
37
- const _usedJtis = new Map<string, number>();
38
- setInterval(() => {
39
- const now = Date.now();
40
- for (const [jti, at] of _usedJtis) {
41
- if (now - at > 10 * 60 * 1000) _usedJtis.delete(jti);
42
- }
43
- }, 60_000).unref?.();
44
-
45
39
  export async function POST(request: NextRequest) {
46
40
  const secretKey = process.env.DUCT_SECRET_KEY;
47
41
 
@@ -81,35 +75,18 @@ export async function POST(request: NextRequest) {
81
75
  // Verify the deeplink token (signature, expiry, audience)
82
76
  const verifyResult = await verifyDeeplinkToken(token, {
83
77
  secretKey,
84
- expectedShellId: ductConfig.shellId,
78
+ expectedShellId: ductConfig.shellId${REPLAY_STORE_VERIFY_OPTIONS}
85
79
  });
86
80
 
87
81
  if (!verifyResult.valid || !verifyResult.payload) {
88
82
  console.warn("[Duct] Invalid deeplink token:", verifyResult.error);
89
83
  return NextResponse.json(
90
- { error: "Invalid token", detail: verifyResult.error },
91
- { status: 401 }
84
+ { error: verifyResult.error === "Token already used" ? "Token already used" : "Invalid token", detail: verifyResult.error },
85
+ { status: verifyResult.error === "Token already used" ? 409 : 401 }
92
86
  );
93
87
  }
94
88
 
95
- // ── Replay check: reject already-consumed JTIs ────────────
96
- const jti = verifyResult.payload.jti as string | undefined;
97
- if (jti) {
98
- if (_usedJtis.has(jti)) {
99
- console.warn("[Duct] Replayed deeplink token rejected:", jti);
100
- return NextResponse.json(
101
- { error: "Token already used" },
102
- { status: 409 }
103
- );
104
- }
105
- _usedJtis.set(jti, Date.now());
106
- }
107
-
108
- const { deeplink_id, state, sub } = verifyResult.payload as {
109
- deeplink_id: string;
110
- state: Record<string, unknown>;
111
- sub?: string;
112
- };
89
+ const { deeplink_id, state, sub } = verifyResult.payload;
113
90
 
114
91
  // Validate deeplink_id is in our config
115
92
  const deeplinkDef = ductConfig.deeplinks.find((d) => d.id === deeplink_id);
@@ -192,11 +169,16 @@ function generateNextPagesRouterReceiver(_config) {
192
169
  * Do not remove the signature verification step.
193
170
  * Do not expose DUCT_SECRET_KEY client-side.
194
171
  *
172
+ * Replay protection: deeplink JWTs carry a single-use \`jti\` claim. The
173
+ * in-process replayStore below is dev/single-instance only — use
174
+ * RedisReplayStore from @duct-sdk/sdk/server in production so the same
175
+ * token cannot be verified twice across replicas.
176
+ *
195
177
  * Docs: ${docsBase}/deeplinks/receiver
196
178
  */
197
179
 
198
180
  import type { NextApiRequest, NextApiResponse } from "next";
199
- import { verifyDeeplinkToken } from "@duct-sdk/sdk/server";
181
+ ${REPLAY_STORE_IMPORT}
200
182
  import ductConfig from "../../../duct.config";
201
183
 
202
184
  type ReceiveResponse = {
@@ -208,15 +190,6 @@ type ReceiveResponse = {
208
190
  detail?: string;
209
191
  };
210
192
 
211
- // ── JTI replay protection (in-process; swap for Redis in multi-replica prod) ──
212
- const _usedJtis = new Map<string, number>();
213
- setInterval(() => {
214
- const now = Date.now();
215
- for (const [jti, at] of _usedJtis) {
216
- if (now - at > 10 * 60 * 1000) _usedJtis.delete(jti);
217
- }
218
- }, 60_000).unref?.();
219
-
220
193
  export default async function handler(
221
194
  req: NextApiRequest,
222
195
  res: NextApiResponse<ReceiveResponse>
@@ -249,32 +222,18 @@ export default async function handler(
249
222
 
250
223
  const verifyResult = await verifyDeeplinkToken(token, {
251
224
  secretKey,
252
- expectedShellId: ductConfig.shellId,
225
+ expectedShellId: ductConfig.shellId${REPLAY_STORE_VERIFY_OPTIONS}
253
226
  });
254
227
 
255
228
  if (!verifyResult.valid || !verifyResult.payload) {
256
229
  console.warn("[Duct] Invalid deeplink token:", verifyResult.error);
257
- return res.status(401).json({
258
- error: "Invalid token",
230
+ return res.status(verifyResult.error === "Token already used" ? 409 : 401).json({
231
+ error: verifyResult.error === "Token already used" ? "Token already used" : "Invalid token",
259
232
  detail: verifyResult.error,
260
233
  });
261
234
  }
262
235
 
263
- // Replay check
264
- const jti = verifyResult.payload.jti as string | undefined;
265
- if (jti) {
266
- if (_usedJtis.has(jti)) {
267
- console.warn("[Duct] Replayed deeplink token rejected:", jti);
268
- return res.status(409).json({ error: "Token already used" });
269
- }
270
- _usedJtis.set(jti, Date.now());
271
- }
272
-
273
- const { deeplink_id, state, sub } = verifyResult.payload as {
274
- deeplink_id: string;
275
- state: Record<string, unknown>;
276
- sub?: string;
277
- };
236
+ const { deeplink_id, state, sub } = verifyResult.payload;
278
237
 
279
238
  const deeplinkDef = ductConfig.deeplinks.find((d) => d.id === deeplink_id);
280
239
  if (!deeplinkDef) {
@@ -340,6 +299,7 @@ function generateTokenApiRoute(config, framework, tokenOptions) {
340
299
  authStrategy: tokenOptions?.authStrategy ?? config.auth.strategy,
341
300
  guestAllowed: tokenOptions?.guestAllowed ?? config.auth.guestAllowed,
342
301
  tokenExpirySeconds: tokenOptions?.tokenExpirySeconds ?? config.auth.tokenExpirySeconds,
302
+ sessionFields: tokenOptions?.sessionFields ?? config.auth.sessionFields,
343
303
  });
344
304
  }
345
305
  // ----------------------------------------------------------------
@@ -361,7 +321,13 @@ export function generateReceiver(config, framework) {
361
321
  case "sveltekit":
362
322
  return generateSvelteKitReceiver(config);
363
323
  case "vite-react":
324
+ case "express":
325
+ case "vue3":
364
326
  return generateExpressReceiver(config);
327
+ case "nuxt":
328
+ return generateNuxtReceiver(config);
329
+ case "fastapi":
330
+ return generateFastApiReceiver(config);
365
331
  default:
366
332
  // Fall back to App Router if unknown
367
333
  return generateNextAppRouterReceiver(config);
@@ -387,12 +353,17 @@ function generateRemixReceiver(_config) {
387
353
  * Do not remove the signature verification step.
388
354
  * Do not expose DUCT_SECRET_KEY client-side.
389
355
  *
356
+ * Replay protection: deeplink JWTs carry a single-use \`jti\` claim. The
357
+ * in-process replayStore below is dev/single-instance only — use
358
+ * RedisReplayStore from @duct-sdk/sdk/server in production so the same
359
+ * token cannot be verified twice across replicas.
360
+ *
390
361
  * Docs: ${docsBase}/deeplinks/receiver
391
362
  */
392
363
 
393
364
  import type { ActionFunctionArgs } from "@remix-run/node";
394
365
  import { json } from "@remix-run/node";
395
- import { verifyDeeplinkToken } from "@duct-sdk/sdk/server";
366
+ ${REPLAY_STORE_IMPORT}
396
367
  import ductConfig from "../../duct.config";
397
368
 
398
369
  export async function action({ request }: ActionFunctionArgs) {
@@ -421,11 +392,15 @@ export async function action({ request }: ActionFunctionArgs) {
421
392
 
422
393
  const verifyResult = await verifyDeeplinkToken(token, {
423
394
  secretKey,
424
- expectedShellId: ductConfig.shellId,
395
+ expectedShellId: ductConfig.shellId${REPLAY_STORE_VERIFY_OPTIONS}
425
396
  });
426
397
 
427
398
  if (!verifyResult.valid || !verifyResult.payload) {
428
- return json({ error: "Invalid token" }, { status: 401 });
399
+ const status = verifyResult.error === "Token already used" ? 409 : 401;
400
+ return json(
401
+ { error: verifyResult.error === "Token already used" ? "Token already used" : "Invalid token" },
402
+ { status }
403
+ );
429
404
  }
430
405
 
431
406
  const { deeplink_id, state, sub } = verifyResult.payload;
@@ -461,11 +436,16 @@ function generateExpressReceiver(_config) {
461
436
  * Do not remove the signature verification step.
462
437
  * Do not expose DUCT_SECRET_KEY client-side.
463
438
  *
439
+ * Replay protection: deeplink JWTs carry a single-use \`jti\` claim. The
440
+ * in-process replayStore below is dev/single-instance only — use
441
+ * RedisReplayStore from @duct-sdk/sdk/server in production so the same
442
+ * token cannot be verified twice across replicas.
443
+ *
464
444
  * Docs: ${docsBase}/deeplinks/receiver
465
445
  */
466
446
 
467
447
  import { Router, Request, Response } from "express";
468
- import { verifyDeeplinkToken } from "@duct-sdk/sdk/server";
448
+ ${REPLAY_STORE_IMPORT}
469
449
  import ductConfig from "../../duct.config";
470
450
 
471
451
  const router = Router();
@@ -491,11 +471,14 @@ router.post("/api/duct/receive", async (req: Request, res: Response) => {
491
471
 
492
472
  const verifyResult = await verifyDeeplinkToken(token, {
493
473
  secretKey,
494
- expectedShellId: ductConfig.shellId,
474
+ expectedShellId: ductConfig.shellId${REPLAY_STORE_VERIFY_OPTIONS}
495
475
  });
496
476
 
497
477
  if (!verifyResult.valid || !verifyResult.payload) {
498
- return res.status(401).json({ error: "Invalid token" });
478
+ const status = verifyResult.error === "Token already used" ? 409 : 401;
479
+ return res.status(status).json({
480
+ error: verifyResult.error === "Token already used" ? "Token already used" : "Invalid token",
481
+ });
499
482
  }
500
483
 
501
484
  const { deeplink_id, state, sub } = verifyResult.payload;
@@ -520,6 +503,149 @@ export default router;
520
503
  `;
521
504
  }
522
505
  // ----------------------------------------------------------------
506
+ // Nuxt (Nitro) receiver
507
+ // ----------------------------------------------------------------
508
+ function generateNuxtReceiver(_config) {
509
+ const docsBase = getDocsUrl();
510
+ return `/**
511
+ * Duct Deeplink Receiver — auto-generated by \`npx duct init\`
512
+ *
513
+ * Nitro server route. Do not remove the signature verification step.
514
+ * Do not expose DUCT_SECRET_KEY client-side.
515
+ *
516
+ * Replay protection: deeplink JWTs carry a single-use \`jti\`. The in-process
517
+ * replayStore below is dev/single-instance only — use RedisReplayStore from
518
+ * @duct-sdk/sdk/server in production.
519
+ *
520
+ * Docs: ${docsBase}/deeplinks/receiver
521
+ */
522
+
523
+ import { verifyDeeplinkToken, createDevReplayStore } from "@duct-sdk/sdk/server";
524
+ import ductConfig from "~/duct.config";
525
+
526
+ const replayStore = createDevReplayStore();
527
+
528
+ export default defineEventHandler(async (event) => {
529
+ const secretKey = process.env.DUCT_SECRET_KEY;
530
+ if (!secretKey) {
531
+ setResponseStatus(event, 500);
532
+ return { error: "Server configuration error" };
533
+ }
534
+
535
+ const authHeader = getHeader(event, "authorization");
536
+ let token: string | null = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : null;
537
+ if (!token) {
538
+ const body = await readBody(event).catch(() => null);
539
+ token = (body as { token?: string } | null)?.token ?? null;
540
+ }
541
+ if (!token) {
542
+ setResponseStatus(event, 401);
543
+ return { error: "No token provided" };
544
+ }
545
+
546
+ const verifyResult = await verifyDeeplinkToken(token, {
547
+ secretKey,
548
+ expectedShellId: ductConfig.shellId,
549
+ replayStore,
550
+ });
551
+
552
+ if (!verifyResult.valid || !verifyResult.payload) {
553
+ setResponseStatus(event, verifyResult.error === "Token already used" ? 409 : 401);
554
+ return { error: verifyResult.error === "Token already used" ? "Token already used" : "Invalid token" };
555
+ }
556
+
557
+ const { deeplink_id, state, sub } = verifyResult.payload;
558
+ const deeplinkDef = ductConfig.deeplinks.find((d) => d.id === deeplink_id);
559
+ if (!deeplinkDef) {
560
+ setResponseStatus(event, 400);
561
+ return { error: "Unknown deeplink" };
562
+ }
563
+
564
+ return {
565
+ success: true,
566
+ redirect: \`\${ductConfig.product.baseUrl}\${deeplinkDef.targetRoute}\`,
567
+ deeplinkId: deeplink_id,
568
+ userId: sub,
569
+ state,
570
+ };
571
+ });
572
+ `;
573
+ }
574
+ // ----------------------------------------------------------------
575
+ // FastAPI (Python) receiver
576
+ // ----------------------------------------------------------------
577
+ function generateFastApiReceiver(_config) {
578
+ const docsBase = getDocsUrl();
579
+ return `# duct_receive.py — auto-generated by \`npx duct init\`
580
+ # FastAPI route that verifies signed Duct deeplinks (HS256 JWT).
581
+ # Requires: pip install pyjwt
582
+ #
583
+ # Do not remove signature verification. Do not expose DUCT_SECRET_KEY client-side.
584
+ # Replay protection: deeplink tokens carry a single-use jti. Track consumed jtis
585
+ # in a shared store (e.g. Redis) in production; the in-memory set below is dev-only.
586
+ #
587
+ # Include this router in your app: app.include_router(router)
588
+ # Docs: ${docsBase}/deeplinks/receiver
589
+ import os
590
+
591
+ import jwt # PyJWT
592
+ from fastapi import APIRouter, Request
593
+ from fastapi.responses import JSONResponse
594
+
595
+ router = APIRouter()
596
+
597
+ DUCT_SHELL_ID = os.environ.get("DUCT_SHELL_ID", "")
598
+
599
+ # Dev-only in-memory replay guard. Replace with a shared store (Redis) in production.
600
+ _seen_jti: set = set()
601
+
602
+
603
+ @router.post("/api/duct/receive")
604
+ async def duct_receive(request: Request):
605
+ secret = os.environ.get("DUCT_SECRET_KEY")
606
+ if not secret:
607
+ return JSONResponse({"error": "Server configuration error"}, status_code=500)
608
+
609
+ auth = request.headers.get("authorization")
610
+ token = auth[7:] if auth and auth.startswith("Bearer ") else None
611
+ if not token:
612
+ body = await request.json()
613
+ token = body.get("token") if isinstance(body, dict) else None
614
+ if not token:
615
+ return JSONResponse({"error": "No token provided"}, status_code=401)
616
+
617
+ try:
618
+ payload = jwt.decode(
619
+ token,
620
+ secret,
621
+ algorithms=["HS256"],
622
+ issuer=DUCT_SHELL_ID or None,
623
+ audience=DUCT_SHELL_ID or None,
624
+ options={"verify_aud": bool(DUCT_SHELL_ID), "verify_iss": bool(DUCT_SHELL_ID)},
625
+ )
626
+ except jwt.PyJWTError as exc:
627
+ return JSONResponse({"error": "Invalid token", "detail": str(exc)}, status_code=401)
628
+
629
+ jti = payload.get("jti")
630
+ if jti:
631
+ if jti in _seen_jti:
632
+ return JSONResponse({"error": "Token already used"}, status_code=409)
633
+ _seen_jti.add(jti)
634
+
635
+ deeplink_id = payload.get("deeplink_id")
636
+ if not deeplink_id:
637
+ return JSONResponse({"error": "Token is missing deeplink_id"}, status_code=400)
638
+
639
+ # TODO: map deeplink_id + state to your app route and pre-load data.
640
+ return {
641
+ "success": True,
642
+ "deeplinkId": deeplink_id,
643
+ "userId": payload.get("sub"),
644
+ "state": payload.get("state") or {},
645
+ }
646
+ `;
647
+ }
648
+ // ----------------------------------------------------------------
523
649
  // SvelteKit receiver
524
650
  // ----------------------------------------------------------------
525
651
  function generateSvelteKitReceiver(_config) {
@@ -535,7 +661,7 @@ function generateSvelteKitReceiver(_config) {
535
661
 
536
662
  import type { RequestHandler } from "@sveltejs/kit";
537
663
  import { json } from "@sveltejs/kit";
538
- import { verifyDeeplinkToken } from "@duct-sdk/sdk/server";
664
+ ${REPLAY_STORE_IMPORT}
539
665
  import ductConfig from "../../../../../duct.config";
540
666
 
541
667
  export const POST: RequestHandler = async ({ request }) => {
@@ -565,11 +691,15 @@ export const POST: RequestHandler = async ({ request }) => {
565
691
 
566
692
  const verifyResult = await verifyDeeplinkToken(token, {
567
693
  secretKey,
568
- expectedShellId: ductConfig.shellId,
694
+ expectedShellId: ductConfig.shellId${REPLAY_STORE_VERIFY_OPTIONS}
569
695
  });
570
696
 
571
697
  if (!verifyResult.valid || !verifyResult.payload) {
572
- return json({ error: "Invalid token", detail: verifyResult.error }, { status: 401 });
698
+ const status = verifyResult.error === "Token already used" ? 409 : 401;
699
+ return json(
700
+ { error: verifyResult.error === "Token already used" ? "Token already used" : "Invalid token", detail: verifyResult.error },
701
+ { status }
702
+ );
573
703
  }
574
704
 
575
705
  const { deeplink_id, state, sub } = verifyResult.payload;
@@ -308,6 +308,14 @@ function getPublicShellHostEnvKey(framework) {
308
308
  }
309
309
  }
310
310
  export function generateEnvTemplateForFramework(config, framework) {
311
+ // Backend-only stacks (Express API, FastAPI) have no embeddable widget, so
312
+ // no public shell/host env keys — just the server-side credentials.
313
+ if (framework.name === "express" || framework.name === "fastapi") {
314
+ return `# Duct credentials (backend)
315
+ DUCT_SHELL_ID=${config.shellId}
316
+ DUCT_SECRET_KEY=<from-dashboard>
317
+ `;
318
+ }
311
319
  const shellKey = getPublicShellEnvKey(framework);
312
320
  const hostKey = getPublicShellHostEnvKey(framework);
313
321
  return `# Duct credentials
@@ -496,8 +504,23 @@ const iframeRef = ref<HTMLIFrameElement | null>(null);
496
504
 
497
505
  const shellId = import.meta.env.VITE_DUCT_SHELL_ID as string ?? '';
498
506
  const shellHost = import.meta.env.VITE_DUCT_SHELL_HOST as string ?? 'http://localhost:3000';
507
+ const shellOrigin = (() => {
508
+ try { return new URL(shellHost).origin; } catch { return shellHost; }
509
+ })();
499
510
  const shellUrl = computed(() => \`\${shellHost}/\${shellId}${themeQuery}\`);
500
511
 
512
+ function isAllowedDeeplinkUrl(url: string): boolean {
513
+ if (!url || url.startsWith('//')) return false;
514
+ if (url.startsWith('/')) return true;
515
+ try {
516
+ const parsed = new URL(url);
517
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
518
+ return parsed.origin === window.location.origin;
519
+ } catch {
520
+ return false;
521
+ }
522
+ }
523
+
501
524
  async function getToken(): Promise<string> {
502
525
  try {
503
526
  const res = await fetch('/api/duct/token', {
@@ -514,16 +537,20 @@ async function getToken(): Promise<string> {
514
537
  }
515
538
 
516
539
  async function handleMessage(event: MessageEvent) {
540
+ if (event.origin !== shellOrigin) return;
517
541
  if (event.data?.type === 'DUCT_REQUEST_TOKEN') {
518
542
  const token = await getToken();
519
543
  iframeRef.value?.contentWindow?.postMessage(
520
544
  { type: 'DUCT_TOKEN_RESPONSE', token, requestId: event.data.requestId },
521
- shellHost
545
+ shellOrigin
522
546
  );
523
547
  } else if (event.data?.type === 'DUCT_CLOSE') {
524
548
  open.value = false;
525
549
  } else if (event.data?.type === 'DUCT_DEEPLINK_NAVIGATE') {
526
- window.location.href = event.data.url as string;
550
+ const url = event.data.url as string;
551
+ if (isAllowedDeeplinkUrl(url)) {
552
+ window.location.href = url;
553
+ }
527
554
  }
528
555
  }
529
556
 
@@ -616,8 +643,23 @@ const iframeRef = ref<HTMLIFrameElement | null>(null);
616
643
  const config = useRuntimeConfig();
617
644
  const shellId = (config.public.ductShellId as string) ?? '';
618
645
  const shellHost = (config.public.ductShellHost as string) ?? 'http://localhost:3000';
646
+ const shellOrigin = (() => {
647
+ try { return new URL(shellHost).origin; } catch { return shellHost; }
648
+ })();
619
649
  const shellUrl = computed(() => \`\${shellHost}/\${shellId}${themeQuery}\`);
620
650
 
651
+ function isAllowedDeeplinkUrl(url: string): boolean {
652
+ if (!url || url.startsWith('//')) return false;
653
+ if (url.startsWith('/')) return true;
654
+ try {
655
+ const parsed = new URL(url);
656
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
657
+ return parsed.origin === window.location.origin;
658
+ } catch {
659
+ return false;
660
+ }
661
+ }
662
+
621
663
  async function getToken(): Promise<string> {
622
664
  try {
623
665
  const data = await $fetch<{ token?: string }>('/api/duct/token', {
@@ -631,16 +673,20 @@ async function getToken(): Promise<string> {
631
673
  }
632
674
 
633
675
  async function handleMessage(event: MessageEvent) {
676
+ if (event.origin !== shellOrigin) return;
634
677
  if (event.data?.type === 'DUCT_REQUEST_TOKEN') {
635
678
  const token = await getToken();
636
679
  iframeRef.value?.contentWindow?.postMessage(
637
680
  { type: 'DUCT_TOKEN_RESPONSE', token, requestId: event.data.requestId },
638
- shellHost
681
+ shellOrigin
639
682
  );
640
683
  } else if (event.data?.type === 'DUCT_CLOSE') {
641
684
  open.value = false;
642
685
  } else if (event.data?.type === 'DUCT_DEEPLINK_NAVIGATE') {
643
- await navigateTo(event.data.url as string, { external: true });
686
+ const url = event.data.url as string;
687
+ if (isAllowedDeeplinkUrl(url)) {
688
+ await navigateTo(url, { external: true });
689
+ }
644
690
  }
645
691
  }
646
692
 
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,73 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { generateShell } from "./shell.js";
4
+ import { generateReceiver } from "./receiver.js";
5
+ import { runAgentSafetyChecks } from "../agents/reviewer-agent.js";
6
+ const vueFramework = {
7
+ name: "vue3",
8
+ version: "3.4.0",
9
+ hasAppRouter: false,
10
+ hasPagesRouter: false,
11
+ packageManager: "npm",
12
+ srcDir: "src",
13
+ };
14
+ const minimalConfig = {
15
+ shellId: "shell_test",
16
+ product: {
17
+ name: "Test",
18
+ description: "Test product",
19
+ baseUrl: "https://app.example.com",
20
+ },
21
+ };
22
+ describe("generateShell vue3 origin guard", () => {
23
+ it("includes origin guard and isAllowedDeeplinkUrl", () => {
24
+ const code = generateShell(minimalConfig, vueFramework);
25
+ assert.match(code, /event\.origin !== shellOrigin/);
26
+ assert.match(code, /function isAllowedDeeplinkUrl/);
27
+ assert.match(code, /isAllowedDeeplinkUrl\(url\)/);
28
+ });
29
+ });
30
+ describe("generateReceiver replay store", () => {
31
+ it("wires createDevReplayStore into remix receiver", () => {
32
+ const remixFramework = {
33
+ name: "remix",
34
+ version: "2.0.0",
35
+ hasAppRouter: false,
36
+ hasPagesRouter: false,
37
+ packageManager: "npm",
38
+ srcDir: "app",
39
+ };
40
+ const code = generateReceiver(minimalConfig, remixFramework);
41
+ assert.match(code, /createDevReplayStore/);
42
+ assert.match(code, /replayStore/);
43
+ });
44
+ });
45
+ describe("runAgentSafetyChecks", () => {
46
+ it("errors on agentAccessible write with high sensitivity", () => {
47
+ const issues = runAgentSafetyChecks({
48
+ routes: [],
49
+ deeplinks: [],
50
+ auth: {
51
+ strategy: "none",
52
+ sessionFields: ["id"],
53
+ guestAllowed: false,
54
+ tokenExpirySeconds: 300,
55
+ },
56
+ actions: [
57
+ {
58
+ id: "delete_user",
59
+ name: "Delete",
60
+ description: "Deletes a user account permanently",
61
+ method: "DELETE",
62
+ path: "/api/users/:id",
63
+ agentAccessible: true,
64
+ sideEffects: true,
65
+ sensitivityLevel: "critical",
66
+ params: [],
67
+ requiresAuth: true,
68
+ },
69
+ ],
70
+ });
71
+ assert.ok(issues.some((i) => i.code === "HIGH_SENSITIVITY_AGENT_ACCESSIBLE" && i.severity === "error"));
72
+ });
73
+ });
@@ -4,5 +4,6 @@ export interface TokenRouteOptions {
4
4
  authStrategy: AuthStrategy;
5
5
  guestAllowed: boolean;
6
6
  tokenExpirySeconds?: number;
7
+ sessionFields?: string[];
7
8
  }
8
9
  export declare function generateStrategyTokenRoute(framework: FrameworkInfo, options: TokenRouteOptions): string;