@duct-sdk/sdk 0.4.3 → 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,21 @@
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
+
15
+ ## [0.4.4] — 2026-07-04
16
+
17
+ ### Changed
18
+ - **`product.logoUrl`** — logo URL belongs under `product` in `duct.config.ts` (removed from `widget`). `duct init` auto-detects `public/logo.*` and resolves against `baseUrl`.
19
+
5
20
  ## [0.4.3] — 2026-07-03
6
21
 
7
22
  ### Fixed
@@ -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",
@@ -200,8 +200,6 @@ function generateWidget(widget, indentSpaces) {
200
200
  lines.push(`${pad} primaryColor: ${JSON.stringify(widget.primaryColor)},`);
201
201
  if (widget.position)
202
202
  lines.push(`${pad} position: ${JSON.stringify(widget.position)},`);
203
- if (widget.logoUrl)
204
- lines.push(`${pad} logoUrl: ${JSON.stringify(widget.logoUrl)},`);
205
203
  if (widget.defaultOpen !== undefined)
206
204
  lines.push(`${pad} defaultOpen: ${widget.defaultOpen},`);
207
205
  if (widget.launcherText)
@@ -254,7 +252,8 @@ export default defineDuctConfig({
254
252
  product: {
255
253
  name: ${JSON.stringify(productName)},
256
254
  description: ${JSON.stringify(`${productName} — AI-powered interaction shell`)},
257
- baseUrl: ${JSON.stringify(baseUrl)},
255
+ baseUrl: ${JSON.stringify(baseUrl)},${logoUrl ? `
256
+ logoUrl: ${JSON.stringify(logoUrl)},` : ''}
258
257
  // apiBaseUrl: optional separate origin for action HTTP proxy (defaults to baseUrl)
259
258
  },
260
259
 
@@ -359,8 +358,7 @@ export default defineDuctConfig({
359
358
 
360
359
  // Shell widget appearance
361
360
  widget: {
362
- position: "bottom-right",${logoUrl ? `
363
- logoUrl: ${JSON.stringify(logoUrl)},` : ""}
361
+ position: "bottom-right",
364
362
  },
365
363
  });
366
364
  `;
@@ -397,6 +395,9 @@ export function generateConfigFile(config) {
397
395
  ...(normalized.product.industry
398
396
  ? [`${i} industry: ${JSON.stringify(normalized.product.industry)},`]
399
397
  : []),
398
+ ...(normalized.product.logoUrl
399
+ ? [`${i} logoUrl: ${JSON.stringify(normalized.product.logoUrl)},`]
400
+ : []),
400
401
  `${i}},`,
401
402
  "",
402
403
  `${i}// Authentication configuration`,
@@ -13,6 +13,7 @@ function sampleConfig(overrides = {}) {
13
13
  description: "Acme test application",
14
14
  baseUrl: BASE_URL,
15
15
  apiBaseUrl: "https://api.acme.com",
16
+ logoUrl: "https://app.acme.com/logo.png",
16
17
  },
17
18
  auth: {
18
19
  strategy: "nextauth",
@@ -56,7 +57,6 @@ function sampleConfig(overrides = {}) {
56
57
  },
57
58
  widget: {
58
59
  position: "bottom-right",
59
- logoUrl: "https://app.acme.com/logo.png",
60
60
  },
61
61
  intershell_enabled: true,
62
62
  registry_visibility: "public",
@@ -97,7 +97,7 @@ describe("validateDuctConfigStrict", () => {
97
97
  });
98
98
  });
99
99
  describe("generateConfigFile", () => {
100
- it("emits apiBaseUrl, normalized tokenEndpoint, intershell flags, and widget logoUrl", () => {
100
+ it("emits apiBaseUrl, normalized tokenEndpoint, intershell flags, and product logoUrl", () => {
101
101
  const output = generateConfigFile(sampleConfig());
102
102
  assert.match(output, /apiBaseUrl: "https:\/\/api\.acme\.com"/);
103
103
  assert.match(output, /tokenEndpoint: "https:\/\/app\.acme\.com\/api\/duct\/token"/);
@@ -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
  }
package/dist/cli/init.js CHANGED
@@ -246,6 +246,16 @@ function detectIndustryFromDeps(deps) {
246
246
  return "analytics";
247
247
  return undefined;
248
248
  }
249
+ function resolveProductLogoUrl(baseUrl, logoUrl) {
250
+ if (!logoUrl?.trim())
251
+ return undefined;
252
+ const trimmed = logoUrl.trim();
253
+ if (/^https?:\/\//i.test(trimmed))
254
+ return trimmed;
255
+ const base = baseUrl.replace(/\/$/, '');
256
+ const path = trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
257
+ return `${base}${path}`;
258
+ }
249
259
  function buildDuctConfigFromPipeline(result, shellId, productName, baseUrl, logoUrl, apiBaseUrl, industry, dataModel) {
250
260
  return normalizeDuctConfigForCodegen({
251
261
  shellId,
@@ -255,6 +265,7 @@ function buildDuctConfigFromPipeline(result, shellId, productName, baseUrl, logo
255
265
  baseUrl,
256
266
  ...(apiBaseUrl ? { apiBaseUrl } : {}),
257
267
  ...(industry ? { industry } : {}),
268
+ ...(logoUrl ? { logoUrl: resolveProductLogoUrl(baseUrl, logoUrl) } : {}),
258
269
  },
259
270
  auth: result.auth,
260
271
  routes: result.routes,
@@ -266,7 +277,6 @@ function buildDuctConfigFromPipeline(result, shellId, productName, baseUrl, logo
266
277
  },
267
278
  widget: {
268
279
  position: "bottom-right",
269
- ...(logoUrl ? { logoUrl } : {}),
270
280
  },
271
281
  ...(result.intershell_enabled !== undefined ||
272
282
  result.registry_visibility !== undefined
@@ -1106,7 +1116,7 @@ export async function runInit(opts = {}) {
1106
1116
  baseUrl,
1107
1117
  authStrategy: authDetection.system,
1108
1118
  framework: topo.framework,
1109
- logoUrl,
1119
+ logoUrl: logoUrl ? resolveProductLogoUrl(baseUrl, logoUrl) : undefined,
1110
1120
  })
1111
1121
  : generateConfigFile(config);
1112
1122
  const receiverContent = generateReceiver(config, framework);
@@ -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;
@@ -9,6 +9,7 @@ export declare const DuctConfigSchema: z.ZodObject<{
9
9
  apiBaseUrl: z.ZodOptional<z.ZodString>;
10
10
  locale: z.ZodOptional<z.ZodString>;
11
11
  industry: z.ZodOptional<z.ZodString>;
12
+ logoUrl: z.ZodOptional<z.ZodString>;
12
13
  }, "strip", z.ZodTypeAny, {
13
14
  name: string;
14
15
  description: string;
@@ -16,6 +17,7 @@ export declare const DuctConfigSchema: z.ZodObject<{
16
17
  apiBaseUrl?: string | undefined;
17
18
  locale?: string | undefined;
18
19
  industry?: string | undefined;
20
+ logoUrl?: string | undefined;
19
21
  }, {
20
22
  name: string;
21
23
  description: string;
@@ -23,6 +25,7 @@ export declare const DuctConfigSchema: z.ZodObject<{
23
25
  apiBaseUrl?: string | undefined;
24
26
  locale?: string | undefined;
25
27
  industry?: string | undefined;
28
+ logoUrl?: string | undefined;
26
29
  }>;
27
30
  auth: z.ZodObject<{
28
31
  strategy: z.ZodEnum<["nextauth", "clerk", "auth0", "custom-jwt", "session-cookie", "none", "unknown"]>;
@@ -326,7 +329,6 @@ export declare const DuctConfigSchema: z.ZodObject<{
326
329
  theme: z.ZodOptional<z.ZodEnum<["light", "dark", "system"]>>;
327
330
  width: z.ZodOptional<z.ZodUnion<[z.ZodNumber, z.ZodString]>>;
328
331
  height: z.ZodOptional<z.ZodUnion<[z.ZodNumber, z.ZodString]>>;
329
- logoUrl: z.ZodOptional<z.ZodString>;
330
332
  customCSS: z.ZodOptional<z.ZodString>;
331
333
  }, "strip", z.ZodTypeAny, {
332
334
  primaryColor?: string | undefined;
@@ -340,7 +342,6 @@ export declare const DuctConfigSchema: z.ZodObject<{
340
342
  theme?: "light" | "dark" | "system" | undefined;
341
343
  width?: string | number | undefined;
342
344
  height?: string | number | undefined;
343
- logoUrl?: string | undefined;
344
345
  customCSS?: string | undefined;
345
346
  }, {
346
347
  primaryColor?: string | undefined;
@@ -354,7 +355,6 @@ export declare const DuctConfigSchema: z.ZodObject<{
354
355
  theme?: "light" | "dark" | "system" | undefined;
355
356
  width?: string | number | undefined;
356
357
  height?: string | number | undefined;
357
- logoUrl?: string | undefined;
358
358
  customCSS?: string | undefined;
359
359
  }>>;
360
360
  registry_visibility: z.ZodDefault<z.ZodOptional<z.ZodEnum<["public", "private"]>>>;
@@ -378,6 +378,7 @@ export declare const DuctConfigSchema: z.ZodObject<{
378
378
  apiBaseUrl?: string | undefined;
379
379
  locale?: string | undefined;
380
380
  industry?: string | undefined;
381
+ logoUrl?: string | undefined;
381
382
  };
382
383
  routes: {
383
384
  name: string;
@@ -465,7 +466,6 @@ export declare const DuctConfigSchema: z.ZodObject<{
465
466
  theme?: "light" | "dark" | "system" | undefined;
466
467
  width?: string | number | undefined;
467
468
  height?: string | number | undefined;
468
- logoUrl?: string | undefined;
469
469
  customCSS?: string | undefined;
470
470
  } | undefined;
471
471
  }, {
@@ -487,6 +487,7 @@ export declare const DuctConfigSchema: z.ZodObject<{
487
487
  apiBaseUrl?: string | undefined;
488
488
  locale?: string | undefined;
489
489
  industry?: string | undefined;
490
+ logoUrl?: string | undefined;
490
491
  };
491
492
  agentPermissions: {
492
493
  defaultLevel: "none" | "read" | "write" | "admin";
@@ -572,7 +573,6 @@ export declare const DuctConfigSchema: z.ZodObject<{
572
573
  theme?: "light" | "dark" | "system" | undefined;
573
574
  width?: string | number | undefined;
574
575
  height?: string | number | undefined;
575
- logoUrl?: string | undefined;
576
576
  customCSS?: string | undefined;
577
577
  } | undefined;
578
578
  registry_visibility?: "public" | "private" | undefined;
@@ -152,7 +152,6 @@ const WidgetConfigSchema = z.object({
152
152
  theme: z.enum(["light", "dark", "system"]).optional(),
153
153
  width: z.union([z.number(), z.string()]).optional(),
154
154
  height: z.union([z.number(), z.string()]).optional(),
155
- logoUrl: z.string().optional(),
156
155
  customCSS: z.string().optional(),
157
156
  });
158
157
  const ProductConfigSchema = z.object({
@@ -162,6 +161,7 @@ const ProductConfigSchema = z.object({
162
161
  apiBaseUrl: z.string().url().optional(),
163
162
  locale: z.string().optional(),
164
163
  industry: z.string().optional(),
164
+ logoUrl: z.string().url().optional(),
165
165
  });
166
166
  export const DuctConfigSchema = z.object({
167
167
  shellId: z
@@ -295,8 +295,6 @@ export interface WidgetConfig {
295
295
  width?: number | string;
296
296
  /** iframe height — default: 620. Ignored when `preset` is set. */
297
297
  height?: number | string;
298
- /** URL to your product logo (shown in empty state) */
299
- logoUrl?: string;
300
298
  /**
301
299
  * Number of conversation turns after which context is compacted into a summary.
302
300
  * Lower = cheaper (less history sent to LLM). Default: 8.
@@ -328,6 +326,8 @@ export interface ProductConfig {
328
326
  locale?: string;
329
327
  /** Industry/category for the product */
330
328
  industry?: string;
329
+ /** HTTPS URL to your product logo (shown in the open shell header) */
330
+ logoUrl?: string;
331
331
  }
332
332
  /**
333
333
  * Structured data describing what the user is currently viewing on the page.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duct-sdk/sdk",
3
- "version": "0.4.3",
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",