@duct-sdk/sdk 0.4.4 → 0.4.5

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  Public release notes for the Duct SDK. Versioning follows [semver](https://semver.org).
4
4
 
5
+ ## [0.4.5] — 2026-07-05
6
+
7
+ ### Added
8
+ - **Consent callback route scaffold** — `duct init` with `duct-consent` mode now emits a consent callback route (`app/api/duct/callback/route.ts` for Next.js App Router, `routes/duct/callback.ts` for Express) that handles the `?user_consent_token=…&user_ref=…` redirect from Duct, with TODO markers for DB/queue storage.
9
+ - **`consentCallbackSnippet` / `consentCallbackSnippetPath`** on `WiringPlan`.
10
+ - `generateConsentCallbackSnippet(framework)` exported from `wiring-snippets.ts`.
11
+
12
+ ### Changed
13
+ - **`uct-consent-auth.ts` snippet updated** — `verifyUct` / `verifyConsentToken` now surface `user_ref` from `/v1/verify/consent-token`. Express version sets `req.ductUserRef`; Next.js/App Router version returns `{ userRef }` from `resolveAgentAwareUser`. Snippets no longer claim to return a generic `user` object.
14
+
5
15
  ## [0.4.4] — 2026-07-04
6
16
 
7
17
  ### Changed
@@ -5,7 +5,7 @@
5
5
  "use client";
6
6
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
7
7
  import React, { useEffect, useRef, useCallback, useMemo, useState, } from "react";
8
- import { resolveShellDimensions, SHELL_PANEL_VIEWPORT_INSETS, } from "../../core/types.js";
8
+ import { fitShellPanelDimensions, resolveShellDimensions, SHELL_PANEL_VIEWPORT_INSETS, } from "../../core/types.js";
9
9
  /**
10
10
  * Hook that polls the shell status endpoint once on mount.
11
11
  * Use when you need to conditionally render UI based on shell liveness.
@@ -116,6 +116,28 @@ function ShellDragHandle({ onPointerDown, isDragging, isDark, label = "Drag to m
116
116
  : "0 8px 24px rgba(12,11,9,0.12)",
117
117
  }, children: label }))] }));
118
118
  }
119
+ /** Always-visible close control — panel chrome is outside the iframe. */
120
+ function ShellCloseButton({ onClose, isDark, }) {
121
+ return (_jsx("button", { type: "button", "aria-label": "Close chat", onClick: onClose, style: {
122
+ position: "absolute",
123
+ top: 6,
124
+ right: 8,
125
+ zIndex: 3,
126
+ width: 28,
127
+ height: 28,
128
+ display: "flex",
129
+ alignItems: "center",
130
+ justifyContent: "center",
131
+ border: "none",
132
+ borderRadius: 8,
133
+ cursor: "pointer",
134
+ padding: 0,
135
+ fontSize: 18,
136
+ lineHeight: 1,
137
+ color: isDark ? "#9C9790" : "#635F59",
138
+ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(12,11,9,0.05)",
139
+ }, children: "\u00D7" }));
140
+ }
119
141
  function shellLayoutStorageKey(shellId) {
120
142
  return `duct-shell-pos:${shellId}`;
121
143
  }
@@ -156,18 +178,47 @@ function writeStoredShellLayout(shellId, layout) {
156
178
  }
157
179
  catch { /* ignore quota / private mode */ }
158
180
  }
159
- /** Keep a dragged panel visible inside the viewport. */
181
+ /** Keep a dragged panel fully inside the viewport (drag handle + close stay reachable). */
160
182
  function clampPanel(x, y, width, height) {
161
183
  if (typeof window === "undefined")
162
184
  return { x, y };
163
185
  const margin = 8;
164
- const maxX = window.innerWidth - width - margin;
165
- const maxY = window.innerHeight - height - margin;
186
+ const vw = window.innerWidth;
187
+ const vh = window.innerHeight;
188
+ const maxX = Math.max(margin, vw - width - margin);
189
+ const maxY = Math.max(margin, vh - height - margin);
166
190
  return {
167
- x: Math.min(Math.max(margin, x), Math.max(margin, maxX)),
168
- y: Math.min(Math.max(margin, y), Math.max(margin, maxY)),
191
+ x: Math.min(Math.max(margin, x), maxX),
192
+ y: Math.min(Math.max(margin, y), maxY),
169
193
  };
170
194
  }
195
+ /** Fit panel to the current viewport using the same caps as the panel CSS. */
196
+ function viewportPanelSize(presetDims, fallbackWidth, fallbackHeight) {
197
+ const rawW = typeof presetDims.width === "number" ? presetDims.width : fallbackWidth;
198
+ const rawH = typeof presetDims.height === "number" ? presetDims.height : fallbackHeight;
199
+ if (typeof window === "undefined")
200
+ return { width: rawW, height: rawH };
201
+ return fitShellPanelDimensions(rawW, rawH, window.innerWidth, window.innerHeight);
202
+ }
203
+ /** Bubble-relative anchor converted to clamped absolute top-left (panel always fits on screen). */
204
+ function anchoredPanelPosition(bubblePos, isRight, panelW, panelH) {
205
+ const vw = typeof window !== "undefined" ? window.innerWidth : 1280;
206
+ const vh = typeof window !== "undefined" ? window.innerHeight : 800;
207
+ if (!bubblePos) {
208
+ const x = isRight ? vw - panelW - 16 : 16;
209
+ const y = vh - panelH - 80;
210
+ return clampPanel(x, y, panelW, panelH);
211
+ }
212
+ const openLeft = bubblePos.x > vw / 2;
213
+ const openUp = bubblePos.y > vh / 2;
214
+ const x = openLeft
215
+ ? vw - Math.max(16, vw - (bubblePos.x + BUBBLE_SIZE)) - panelW
216
+ : Math.max(16, bubblePos.x);
217
+ const y = openUp
218
+ ? vh - Math.max(16, vh - bubblePos.y + 12) - panelH
219
+ : Math.max(16, bubblePos.y + BUBBLE_SIZE + 12);
220
+ return clampPanel(x, y, panelW, panelH);
221
+ }
171
222
  /** Coalesce high-frequency pointer moves to one React update per animation frame. */
172
223
  function scheduleRafUpdate(rafRef, pendingRef, pos, commit) {
173
224
  pendingRef.current = pos;
@@ -226,6 +277,8 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
226
277
  const [dynamicPreset, setDynamicPreset] = useState(undefined);
227
278
  // Free-drag bubble position (px from top-left of viewport). null = default corner.
228
279
  const [bubblePos, setBubblePos] = useState(null);
280
+ /** Launcher position — only updated when the bubble is dragged, never by panel drag/open. */
281
+ const bubbleAnchorRef = useRef(null);
229
282
  const [isDragging, setIsDragging] = useState(false);
230
283
  const dragState = useRef(null);
231
284
  // Open panel can also be dragged after launch. null = anchor near bubble/default corner.
@@ -295,6 +348,12 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
295
348
  // Animate close
296
349
  const closePanel = useCallback(() => {
297
350
  setIsAnimating(true);
351
+ // Panel drag must never move the launcher — restore the last bubble drop on close.
352
+ if (bubbleAnchorRef.current) {
353
+ const anchor = clampBubble(bubbleAnchorRef.current.x, bubbleAnchorRef.current.y);
354
+ bubbleAnchorRef.current = anchor;
355
+ setBubblePos(anchor);
356
+ }
298
357
  setTimeout(() => {
299
358
  setOpen(false);
300
359
  setIsAnimating(false);
@@ -451,13 +510,58 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
451
510
  mq.addEventListener("change", handler);
452
511
  return () => mq.removeEventListener("change", handler);
453
512
  }, [theme]);
513
+ // Escape closes the panel when drag handle / bubble are unreachable.
514
+ useEffect(() => {
515
+ if (!panelOpen)
516
+ return;
517
+ const onKey = (e) => {
518
+ if (e.key === "Escape")
519
+ closePanel();
520
+ };
521
+ window.addEventListener("keydown", onKey);
522
+ return () => window.removeEventListener("keydown", onKey);
523
+ }, [panelOpen, closePanel]);
524
+ // Re-clamp positions when the viewport changes so stored coords cannot strand the panel.
525
+ useEffect(() => {
526
+ if (!draggable || typeof window === "undefined")
527
+ return;
528
+ const onResize = () => {
529
+ const dims = resolveShellDimensions({
530
+ preset: dynamicPreset ?? preset,
531
+ width: dynamicWidth ?? panelWidth,
532
+ height: dynamicHeight ?? panelHeight,
533
+ });
534
+ const size = viewportPanelSize(dims, panelWidth, panelHeight);
535
+ setBubblePos((prev) => {
536
+ if (!prev)
537
+ return null;
538
+ const clamped = clampBubble(prev.x, prev.y);
539
+ bubbleAnchorRef.current = clamped;
540
+ return clamped;
541
+ });
542
+ setPanelPos((prev) => {
543
+ if (!prev)
544
+ return null;
545
+ const clamped = clampPanel(prev.x, prev.y, size.width, size.height);
546
+ const layout = { panel: clamped };
547
+ if (bubbleAnchorRef.current)
548
+ layout.bubble = bubbleAnchorRef.current;
549
+ writeStoredShellLayout(shellId, layout);
550
+ return clamped;
551
+ });
552
+ };
553
+ window.addEventListener("resize", onResize);
554
+ return () => window.removeEventListener("resize", onResize);
555
+ }, [shellId, draggable, dynamicPreset, preset, dynamicWidth, panelWidth, dynamicHeight, panelHeight]);
454
556
  // Restore bubble position saved from a prior visit (survives deeplink handoff navigations).
455
557
  useEffect(() => {
456
558
  if (!draggable || typeof window === "undefined")
457
559
  return;
458
560
  const layout = readStoredShellLayout(shellId);
459
561
  if (layout.bubble) {
460
- setBubblePos(clampBubble(layout.bubble.x, layout.bubble.y));
562
+ const pos = clampBubble(layout.bubble.x, layout.bubble.y);
563
+ bubbleAnchorRef.current = pos;
564
+ setBubblePos(pos);
461
565
  }
462
566
  }, [shellId, draggable]);
463
567
  // Restore or re-clamp panel position when dimensions change (e.g. manifest widget preset).
@@ -469,15 +573,14 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
469
573
  width: dynamicWidth ?? panelWidth,
470
574
  height: dynamicHeight ?? panelHeight,
471
575
  });
472
- const w = typeof dims.width === "number" ? dims.width : panelWidth;
473
- const h = typeof dims.height === "number" ? dims.height : panelHeight;
576
+ const size = viewportPanelSize(dims, panelWidth, panelHeight);
474
577
  setPanelPos((prev) => {
475
578
  if (prev)
476
- return clampPanel(prev.x, prev.y, w, h);
579
+ return clampPanel(prev.x, prev.y, size.width, size.height);
477
580
  const stored = readStoredShellLayout(shellId).panel;
478
581
  if (!stored)
479
582
  return null;
480
- return clampPanel(stored.x, stored.y, w, h);
583
+ return clampPanel(stored.x, stored.y, size.width, size.height);
481
584
  });
482
585
  }, [shellId, draggable, dynamicPreset, preset, dynamicWidth, panelWidth, dynamicHeight, panelHeight]);
483
586
  // Launcher bubble: pointer stays default until the user actually drags (4px threshold).
@@ -498,9 +601,8 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
498
601
  moved: false,
499
602
  };
500
603
  dragState.current = st;
501
- const initial = clampBubble(rect.left, rect.top);
502
- setBubblePos((prev) => prev ?? initial);
503
- bubbleDragPending.current = initial;
604
+ const startBubblePos = bubbleAnchorRef.current ?? bubblePos ?? clampBubble(rect.left, rect.top);
605
+ bubbleDragPending.current = startBubblePos;
504
606
  const commitBubblePos = (pos) => setBubblePos(pos);
505
607
  const onMove = (ev) => {
506
608
  if (!dragState.current)
@@ -526,10 +628,13 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
526
628
  setIsDragging(false);
527
629
  const finalPos = cancelRafUpdate(bubbleDragRaf, bubbleDragPending, commitBubblePos);
528
630
  if (st.moved) {
529
- const pos = finalPos ?? bubbleDragPending.current;
631
+ const pos = finalPos ?? bubbleDragPending.current ?? startBubblePos;
530
632
  if (pos) {
531
- setBubblePos(pos);
532
- writeStoredShellLayout(shellId, { bubble: pos });
633
+ const anchor = clampBubble(pos.x, pos.y);
634
+ bubbleAnchorRef.current = anchor;
635
+ setBubblePos(anchor);
636
+ // Bubble moved — drop saved panel so it re-anchors near the new launcher spot.
637
+ writeStoredShellLayout(shellId, { bubble: anchor });
533
638
  }
534
639
  setPanelPos(null);
535
640
  }
@@ -577,8 +682,10 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
577
682
  const finalPos = cancelRafUpdate(panelDragRaf, panelDragPending, commitPanelPos);
578
683
  if (finalPos) {
579
684
  setPanelPos(finalPos);
580
- const layout = readStoredShellLayout(shellId);
581
- writeStoredShellLayout(shellId, { ...layout, panel: finalPos });
685
+ const layout = { panel: finalPos };
686
+ if (bubbleAnchorRef.current)
687
+ layout.bubble = bubbleAnchorRef.current;
688
+ writeStoredShellLayout(shellId, layout);
582
689
  }
583
690
  };
584
691
  window.addEventListener("pointermove", onMove);
@@ -601,6 +708,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
601
708
  width: dynamicWidth ?? panelWidth,
602
709
  height: dynamicHeight ?? panelHeight,
603
710
  });
711
+ const panelSize = viewportPanelSize(presetDims, panelWidth, panelHeight);
604
712
  const widthVal = typeof presetDims.width === "number" ? `${presetDims.width}px` : presetDims.width;
605
713
  const heightVal = typeof presetDims.height === "number" ? `${presetDims.height}px` : presetDims.height;
606
714
  const panelWidthInset = SHELL_PANEL_VIEWPORT_INSETS.width;
@@ -611,26 +719,13 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
611
719
  const bubbleStyle = dragged
612
720
  ? { position: "fixed", left: `${bubblePos.x}px`, top: `${bubblePos.y}px` }
613
721
  : { position: "fixed", bottom: "16px", [isRight ? "right" : "left"]: "16px" };
614
- const panelAnchor = (() => {
615
- if (!dragged) {
616
- return { bottom: "80px", [isRight ? "right" : "left"]: "16px" };
617
- }
618
- // Open the panel toward whichever side has the most room.
619
- const vw = typeof window !== "undefined" ? window.innerWidth : 1280;
620
- const vh = typeof window !== "undefined" ? window.innerHeight : 800;
621
- const openLeft = bubblePos.x > vw / 2;
622
- const openUp = bubblePos.y > vh / 2;
623
- const horiz = openLeft
624
- ? { right: `${Math.max(16, vw - (bubblePos.x + BUBBLE_SIZE))}px` }
625
- : { left: `${Math.max(16, bubblePos.x)}px` };
626
- const vert = openUp
627
- ? { bottom: `${Math.max(16, vh - bubblePos.y + 12)}px` }
628
- : { top: `${Math.max(16, bubblePos.y + BUBBLE_SIZE + 12)}px` };
629
- return { ...horiz, ...vert };
630
- })();
722
+ const effectivePanelPos = panelPos
723
+ ? clampPanel(panelPos.x, panelPos.y, panelSize.width, panelSize.height)
724
+ : anchoredPanelPosition(bubblePos, isRight, panelSize.width, panelSize.height);
631
725
  const panelStyle = {
632
726
  position: "fixed",
633
- ...(panelPos ? { left: `${panelPos.x}px`, top: `${panelPos.y}px` } : panelAnchor),
727
+ left: `${effectivePanelPos.x}px`,
728
+ top: `${effectivePanelPos.y}px`,
634
729
  width: `min(${widthVal}, calc(100vw - ${panelWidthInset}px))`,
635
730
  height: `min(${heightVal}, calc(100dvh - ${panelHeightInset}px))`,
636
731
  zIndex: 9998,
@@ -691,7 +786,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
691
786
  e.currentTarget.style.transform = "scale(1.07)";
692
787
  }, onMouseLeave: (e) => {
693
788
  e.currentTarget.style.transform = "scale(1)";
694
- }, children: bubbleIcon })), _jsxs("div", { ref: panelRef, style: panelStyle, "data-duct-shell": shellId, children: [draggable && panelOpen && (_jsx(ShellDragHandle, { onPointerDown: onPanelPointerDown, isDragging: isPanelDragging, isDark: isDarkChrome, label: "Drag to move" })), _jsx("iframe", { ref: iframeRef, src: shellUrl, title: "Duct Shell", sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", allow: "clipboard-write", referrerPolicy: "no-referrer-when-downgrade", style: {
789
+ }, children: bubbleIcon })), _jsxs("div", { ref: panelRef, style: panelStyle, "data-duct-shell": shellId, children: [draggable && panelOpen && (_jsx(ShellDragHandle, { onPointerDown: onPanelPointerDown, isDragging: isPanelDragging, isDark: isDarkChrome, label: "Drag to move" })), panelOpen && (_jsx(ShellCloseButton, { onClose: closePanel, isDark: isDarkChrome })), _jsx("iframe", { ref: iframeRef, src: shellUrl, title: "Duct Shell", sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", allow: "clipboard-write", referrerPolicy: "no-referrer-when-downgrade", style: {
695
790
  width: "100%",
696
791
  height: "100%",
697
792
  border: "none",
@@ -15,9 +15,23 @@ export interface WiringPlan {
15
15
  middlewareSnippet: string;
16
16
  uctSnippetPath?: string;
17
17
  uctSnippet?: string;
18
+ /** Scaffold for the consent callback route (only when duct-consent mode). */
19
+ consentCallbackSnippetPath?: string;
20
+ consentCallbackSnippet?: string;
18
21
  }
19
22
  export declare function projectUsesVerifyDuctToken(sandboxFs: SandboxFS): Promise<boolean>;
20
23
  export declare function generateVerifyDuctTokenMiddlewareSnippet(framework: FrameworkInfo, middlewarePath?: string): string;
21
24
  export declare function generateUctVerificationSnippet(framework: FrameworkInfo): string;
22
25
  export declare function buildWiringPlan(outputPaths: GeneratedOutputPaths, framework: FrameworkInfo, authDetection: AuthDetectionResult, thirdPartyAgentMode: ThirdPartyAgentMode): WiringPlan;
26
+ /**
27
+ * Scaffold for the consent callback route your app must expose when using
28
+ * the duct-consent third-party agent mode.
29
+ *
30
+ * This route receives the redirect from Duct after a user approves an agent
31
+ * consent request. It stores the uct_ token and user_ref so the agent can
32
+ * retrieve them for subsequent calls.
33
+ *
34
+ * Replace the TODO sections with your own DB / queue / webhook logic.
35
+ */
36
+ export declare function generateConsentCallbackSnippet(framework: FrameworkInfo): string;
23
37
  export declare function sideEffectActionsApproved(config: DuctConfig): boolean;
@@ -100,21 +100,31 @@ export function generateUctVerificationSnippet(framework) {
100
100
  return `/**
101
101
  * Third-party agent user identity — verify Duct consent tokens (uct_).
102
102
  * POST \${DUCT_AUTH_URL}/v1/verify/consent-token
103
+ *
104
+ * On success, req.ductUserRef contains the opaque company user identifier you
105
+ * supplied at consent-request time. Resolve mutable data (email, roles) from
106
+ * YOUR own DB using that id — never trust the JWT payload for live attributes.
103
107
  */
104
108
  import type { Request, Response, NextFunction } from "express";
105
109
  import { verifyDuctToken } from "@duct-sdk/sdk/server";
106
110
 
107
111
  const DUCT_AUTH_URL = process.env.DUCT_AUTH_URL ?? "http://localhost:3001";
108
112
 
109
- async function verifyUct(token: string): Promise<Record<string, unknown> | null> {
113
+ interface UctVerifyResult {
114
+ userRef?: string;
115
+ allowedActions?: string[];
116
+ }
117
+
118
+ async function verifyUct(token: string): Promise<UctVerifyResult | null> {
110
119
  const res = await fetch(\`\${DUCT_AUTH_URL}/v1/verify/consent-token\`, {
111
120
  method: "POST",
112
121
  headers: { "Content-Type": "application/json" },
113
122
  body: JSON.stringify({ token }),
114
123
  });
115
124
  if (!res.ok) return null;
116
- const body = (await res.json()) as { valid?: boolean; user?: Record<string, unknown> };
117
- return body.valid ? body.user ?? {} : null;
125
+ const body = (await res.json()) as { valid?: boolean; user_ref?: string; allowed_actions?: string[] };
126
+ if (!body.valid) return null;
127
+ return { userRef: body.user_ref, allowedActions: body.allowed_actions };
118
128
  }
119
129
 
120
130
  export async function ductOrConsentAuth(req: Request, res: Response, next: NextFunction) {
@@ -123,9 +133,9 @@ export async function ductOrConsentAuth(req: Request, res: Response, next: NextF
123
133
 
124
134
  const token = authHeader.slice(7);
125
135
  if (token.startsWith("uct_")) {
126
- const user = await verifyUct(token);
127
- if (!user) return res.status(401).json({ error: "Invalid consent token" });
128
- (req as Request & { user?: Record<string, unknown> }).user = user;
136
+ const result = await verifyUct(token);
137
+ if (!result) return res.status(401).json({ error: "Invalid consent token" });
138
+ (req as Request & { ductUserRef?: string }).ductUserRef = result.userRef;
129
139
  return next();
130
140
  }
131
141
 
@@ -137,35 +147,50 @@ export async function ductOrConsentAuth(req: Request, res: Response, next: NextF
137
147
  return `/**
138
148
  * Third-party agent user identity — accept uct_ consent tokens OR duct_delegated JWTs.
139
149
  * Configure DUCT_AUTH_URL in server env (never NEXT_PUBLIC_* / VITE_*).
150
+ *
151
+ * When a uct_ token is present, the resolved object includes user_ref — the opaque
152
+ * company-supplied identifier you passed to /v1/consent/request. Use it to load the
153
+ * live user from YOUR database. Do NOT store PII in the token itself.
140
154
  */
141
155
  import { verifyDuctToken } from "@duct-sdk/sdk/server";
142
156
 
143
157
  const DUCT_AUTH_URL = process.env.DUCT_AUTH_URL ?? "http://localhost:3001";
144
158
 
145
- async function verifyConsentToken(token: string): Promise<Record<string, unknown> | null> {
159
+ interface ConsentVerifyResult {
160
+ user_ref?: string;
161
+ allowed_actions?: string[];
162
+ }
163
+
164
+ async function verifyConsentToken(token: string): Promise<ConsentVerifyResult | null> {
146
165
  const res = await fetch(\`\${DUCT_AUTH_URL}/v1/verify/consent-token\`, {
147
166
  method: "POST",
148
167
  headers: { "Content-Type": "application/json" },
149
168
  body: JSON.stringify({ token }),
150
169
  });
151
170
  if (!res.ok) return null;
152
- const body = (await res.json()) as { valid?: boolean; user?: Record<string, unknown> };
153
- return body.valid ? body.user ?? {} : null;
171
+ const body = (await res.json()) as { valid?: boolean; user_ref?: string; allowed_actions?: string[] };
172
+ if (!body.valid) return null;
173
+ return { user_ref: body.user_ref, allowed_actions: body.allowed_actions };
154
174
  }
155
175
 
156
- export async function resolveAgentAwareUser(request: Request): Promise<Record<string, unknown> | null> {
176
+ export async function resolveAgentAwareUser(
177
+ request: Request,
178
+ ): Promise<{ userRef?: string; session?: Record<string, unknown> } | null> {
157
179
  const authHeader = request.headers.get("authorization");
158
180
  if (!authHeader?.startsWith("Bearer ")) return null;
159
181
 
160
182
  const token = authHeader.slice(7);
161
183
  if (token.startsWith("uct_")) {
162
- return verifyConsentToken(token);
184
+ const result = await verifyConsentToken(token);
185
+ if (!result) return null;
186
+ // Resolve the live user from your DB using result.user_ref
187
+ return { userRef: result.user_ref };
163
188
  }
164
189
 
165
190
  const secretKey = process.env.DUCT_SECRET_KEY!;
166
191
  const shellId = process.env.DUCT_SHELL_ID ?? process.env.NEXT_PUBLIC_DUCT_SHELL_ID!;
167
192
  const delegated = await verifyDuctToken(token, { secretKey, expectedShellId: shellId });
168
- return delegated.valid ? delegated.payload.session : null;
193
+ return delegated.valid ? { session: delegated.payload.session as Record<string, unknown> } : null;
169
194
  }
170
195
  `;
171
196
  }
@@ -213,11 +238,20 @@ export function buildWiringPlan(outputPaths, framework, authDetection, thirdPart
213
238
  if (thirdPartyAgentMode === "duct-consent") {
214
239
  plan.uctSnippetPath = ".duct/snippets/uct-consent-auth.ts";
215
240
  plan.uctSnippet = generateUctVerificationSnippet(framework);
241
+ plan.consentCallbackSnippetPath = ".duct/snippets/duct-consent-callback.ts";
242
+ plan.consentCallbackSnippet = generateConsentCallbackSnippet(framework);
216
243
  items.push({
217
244
  path: middlewareTarget,
218
245
  action: "modify",
219
246
  summary: "Verify uct_ consent tokens for third-party agent /message calls",
220
247
  });
248
+ items.push({
249
+ path: framework.name === "next-app" || framework.name === "next-pages"
250
+ ? "app/api/duct/callback/route.ts"
251
+ : "routes/duct/callback.ts",
252
+ action: "create",
253
+ summary: "Consent callback — receives uct_ + user_ref after human approval, stores for agent",
254
+ });
221
255
  }
222
256
  if (thirdPartyAgentMode === "oauth") {
223
257
  items.push({
@@ -228,6 +262,96 @@ export function buildWiringPlan(outputPaths, framework, authDetection, thirdPart
228
262
  }
229
263
  return plan;
230
264
  }
265
+ /**
266
+ * Scaffold for the consent callback route your app must expose when using
267
+ * the duct-consent third-party agent mode.
268
+ *
269
+ * This route receives the redirect from Duct after a user approves an agent
270
+ * consent request. It stores the uct_ token and user_ref so the agent can
271
+ * retrieve them for subsequent calls.
272
+ *
273
+ * Replace the TODO sections with your own DB / queue / webhook logic.
274
+ */
275
+ export function generateConsentCallbackSnippet(framework) {
276
+ const isNextJs = framework.name === "next-app" ||
277
+ framework.name === "next-pages";
278
+ if (isNextJs) {
279
+ return `// app/api/duct/callback/route.ts
280
+ // Receives the redirect from Duct after a user approves an agent consent request.
281
+ import { NextRequest, NextResponse } from "next/server";
282
+
283
+ export const dynamic = "force-dynamic";
284
+
285
+ export async function GET(request: NextRequest) {
286
+ const { searchParams } = new URL(request.url);
287
+
288
+ const userConsentToken = searchParams.get("user_consent_token");
289
+ const userRef = searchParams.get("user_ref"); // opaque id you supplied at /consent/request
290
+ const error = searchParams.get("error");
291
+
292
+ if (error) {
293
+ // User denied — redirect to a graceful error page
294
+ return NextResponse.redirect(new URL("/agent-access-denied", request.url));
295
+ }
296
+
297
+ if (!userConsentToken) {
298
+ return NextResponse.json({ error: "missing_token" }, { status: 400 });
299
+ }
300
+
301
+ // TODO: store { userConsentToken, userRef } so the agent can retrieve it.
302
+ // Options:
303
+ // • Push to a webhook/queue your agent is listening on
304
+ // • Write to DB: INSERT INTO agent_grants (user_ref, uct, granted_at) VALUES (...)
305
+ // • Cache in Redis with a short TTL for the agent to poll
306
+ //
307
+ // Example DB upsert:
308
+ // await db.agentGrants.upsert({
309
+ // where: { userRef },
310
+ // update: { uct: userConsentToken, grantedAt: new Date() },
311
+ // create: { userRef, uct: userConsentToken, grantedAt: new Date() },
312
+ // });
313
+
314
+ // Redirect the user to a confirmation page
315
+ return NextResponse.redirect(new URL("/agent-connected", request.url));
316
+ }
317
+ `;
318
+ }
319
+ return `// routes/duct/callback.ts (Express)
320
+ // Receives the redirect from Duct after a user approves an agent consent request.
321
+ import { Router, Request, Response } from "express";
322
+
323
+ const router = Router();
324
+
325
+ router.get("/", async (req: Request, res: Response) => {
326
+ const { user_consent_token: userConsentToken, user_ref: userRef, error } = req.query as Record<string, string>;
327
+
328
+ if (error) {
329
+ // User denied — redirect to a graceful error page
330
+ return res.redirect("/agent-access-denied");
331
+ }
332
+
333
+ if (!userConsentToken) {
334
+ return res.status(400).json({ error: "missing_token" });
335
+ }
336
+
337
+ // TODO: store { userConsentToken, userRef } so the agent can retrieve it.
338
+ // Options:
339
+ // • Push to a webhook/queue your agent is listening on
340
+ // • Write to DB: INSERT INTO agent_grants (user_ref, uct, granted_at) VALUES (...)
341
+ // • Cache in Redis with a short TTL for the agent to poll
342
+ //
343
+ // Example DB insert:
344
+ // await db.query(
345
+ // "INSERT INTO agent_grants (user_ref, uct, granted_at) VALUES ($1, $2, NOW()) ON CONFLICT (user_ref) DO UPDATE SET uct = $2, granted_at = NOW()",
346
+ // [userRef, userConsentToken],
347
+ // );
348
+
349
+ return res.redirect("/agent-connected");
350
+ });
351
+
352
+ export default router;
353
+ `;
354
+ }
231
355
  export function sideEffectActionsApproved(config) {
232
356
  return (config.actions ?? []).some((action) => action.sideEffects);
233
357
  }
@@ -173,7 +173,7 @@ export async function runIntegrationAudit(sandboxFs, ctx) {
173
173
  severity: "info",
174
174
  area: "agents",
175
175
  issue: "Human shell works with duct_delegated only; partner agents need uct_ or OAuth",
176
- fix: "Re-run init and choose third-party agent support, or see DUCT_CONFIG_PROMPT.md Phase 4b",
176
+ fix: "Re-run init and choose third-party agent support, or see DUCT_CONFIG_PROMPT.md — Third-party agents and user identity",
177
177
  });
178
178
  }
179
179
  return issues;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duct-sdk/sdk",
3
- "version": "0.4.4",
3
+ "version": "0.4.5",
4
4
  "type": "module",
5
5
  "description": "Duct SDK — A shell (like terminal) that knows when to talk, when to show, and when to hand off.",
6
6
  "main": "dist/index.js",