@duct-sdk/sdk 0.3.12 → 0.4.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 (63) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/adapters/next/receiver.d.ts +2 -6
  3. package/dist/adapters/next/receiver.js +20 -66
  4. package/dist/adapters/remix/receiver.d.ts +2 -6
  5. package/dist/adapters/remix/receiver.js +16 -33
  6. package/dist/adapters/sveltekit/receiver.d.ts +2 -6
  7. package/dist/adapters/sveltekit/receiver.js +13 -40
  8. package/dist/adapters/vite/receiver.d.ts +2 -4
  9. package/dist/adapters/vite/receiver.js +13 -30
  10. package/dist/cli/agents/api-agent.d.ts +3 -1
  11. package/dist/cli/agents/api-agent.js +22 -11
  12. package/dist/cli/agents/auth-agent.js +4 -4
  13. package/dist/cli/agents/pipeline.js +65 -7
  14. package/dist/cli/agents/route-agent.d.ts +3 -1
  15. package/dist/cli/agents/route-agent.js +17 -6
  16. package/dist/cli/detectors/topology.d.ts +1 -1
  17. package/dist/cli/detectors/topology.js +1 -1
  18. package/dist/cli/generators/config.js +77 -44
  19. package/dist/cli/generators/config.test.d.ts +1 -0
  20. package/dist/cli/generators/config.test.js +219 -0
  21. package/dist/cli/generators/normalize.d.ts +10 -0
  22. package/dist/cli/generators/normalize.js +49 -0
  23. package/dist/cli/generators/receiver.d.ts +2 -1
  24. package/dist/cli/generators/receiver.js +20 -201
  25. package/dist/cli/generators/token-route.d.ts +8 -0
  26. package/dist/cli/generators/token-route.js +235 -0
  27. package/dist/cli/generators/token-route.test.d.ts +1 -0
  28. package/dist/cli/generators/token-route.test.js +53 -0
  29. package/dist/cli/generators/wiring-snippets.d.ts +23 -0
  30. package/dist/cli/generators/wiring-snippets.js +233 -0
  31. package/dist/cli/generators/wiring-snippets.test.d.ts +1 -0
  32. package/dist/cli/generators/wiring-snippets.test.js +66 -0
  33. package/dist/cli/index.js +41 -1
  34. package/dist/cli/init.d.ts +1 -7
  35. package/dist/cli/init.js +100 -53
  36. package/dist/cli/output-paths.d.ts +10 -0
  37. package/dist/cli/output-paths.js +60 -0
  38. package/dist/cli/processors/curl-parser.test.d.ts +1 -0
  39. package/dist/cli/processors/curl-parser.test.js +24 -0
  40. package/dist/cli/processors/integration-audit.d.ts +23 -0
  41. package/dist/cli/processors/integration-audit.js +208 -0
  42. package/dist/cli/processors/integration-audit.test.d.ts +1 -0
  43. package/dist/cli/processors/integration-audit.test.js +154 -0
  44. package/dist/cli/processors/prisma-parser.js +1 -1
  45. package/dist/cli/processors/verify-discovery.d.ts +33 -0
  46. package/dist/cli/processors/verify-discovery.js +193 -0
  47. package/dist/cli/processors/verify-discovery.test.d.ts +1 -0
  48. package/dist/cli/processors/verify-discovery.test.js +153 -0
  49. package/dist/cli/processors/zod-extractor.js +1 -1
  50. package/dist/core/config.d.ts +26 -0
  51. package/dist/core/config.js +65 -28
  52. package/dist/core/endpoints.d.ts +2 -0
  53. package/dist/core/endpoints.js +10 -0
  54. package/dist/core/login-handoff.d.ts +41 -0
  55. package/dist/core/login-handoff.js +133 -0
  56. package/dist/core/login-handoff.test.d.ts +1 -0
  57. package/dist/core/login-handoff.test.js +31 -0
  58. package/dist/core/receiver.d.ts +33 -0
  59. package/dist/core/receiver.js +77 -0
  60. package/dist/core/types.d.ts +10 -0
  61. package/dist/server.d.ts +2 -0
  62. package/dist/server.js +2 -0
  63. package/package.json +2 -1
@@ -91,6 +91,12 @@ const AuthSchemaSchema = z.object({
91
91
  tokenExpirySeconds: z.number().positive().default(60),
92
92
  tokenEndpoint: z.string().url().optional(),
93
93
  customClaims: z.record(z.string()).optional(),
94
+ loginDeeplinkId: z
95
+ .string()
96
+ .min(1)
97
+ .regex(/^[a-z_][a-z0-9_]*$/, "loginDeeplinkId must be snake_case")
98
+ .optional(),
99
+ loginRoutePath: z.string().min(1).startsWith("/").optional(),
94
100
  });
95
101
  const StateFieldSchema = z.object({
96
102
  key: z.string().min(1),
@@ -172,6 +178,60 @@ export const DuctConfigSchema = z.object({
172
178
  registry_visibility: z.enum(['public', 'private']).optional().default('private'),
173
179
  intershell_enabled: z.boolean().optional().default(false),
174
180
  });
181
+ function zodIssuesToValidationIssues(errors) {
182
+ return errors.map((e) => ({
183
+ severity: "error",
184
+ area: e.path.length > 0 ? e.path.join(".") : "config",
185
+ issue: e.message,
186
+ fix: e.path.join(".") === "auth.tokenEndpoint"
187
+ ? "Set auth.tokenEndpoint to a full URL (e.g. https://app.example.com/api/duct/token) or omit the field"
188
+ : "Correct the field per the Duct config reference",
189
+ }));
190
+ }
191
+ function crossValidateDuctConfig(data) {
192
+ const issues = [];
193
+ const routePaths = new Set(data.routes.map((r) => r.path));
194
+ for (const deeplink of data.deeplinks) {
195
+ const normalizedTarget = deeplink.targetRoute.replace(/\[([^\]]+)\]/g, ":$1");
196
+ const normalizedRoutes = Array.from(routePaths).map((p) => p.replace(/\[([^\]]+)\]/g, ":$1"));
197
+ if (!normalizedRoutes.some((r) => r === normalizedTarget || routePaths.has(deeplink.targetRoute))) {
198
+ issues.push({
199
+ severity: "error",
200
+ area: "deeplinks",
201
+ issue: `Deeplink "${deeplink.id}" targets route "${deeplink.targetRoute}" which is not defined in routes[]`,
202
+ fix: `Add a matching route to routes[] or update deeplink "${deeplink.id}".targetRoute`,
203
+ });
204
+ }
205
+ }
206
+ const actionIds = new Set(data.actions.map((a) => a.id));
207
+ if (data.agentPermissions.actionOverrides) {
208
+ for (const actionId of Object.keys(data.agentPermissions.actionOverrides)) {
209
+ if (!actionIds.has(actionId)) {
210
+ issues.push({
211
+ severity: "error",
212
+ area: "agentPermissions",
213
+ issue: `actionOverrides references unknown action ID "${actionId}"`,
214
+ fix: `Remove the override or add action "${actionId}" to actions[]`,
215
+ });
216
+ }
217
+ }
218
+ }
219
+ return issues;
220
+ }
221
+ /**
222
+ * Validate a Duct config without throwing — used by `duct init` before writing files.
223
+ */
224
+ export function validateDuctConfigStrict(config) {
225
+ const result = DuctConfigSchema.safeParse(config);
226
+ if (!result.success) {
227
+ return { ok: false, issues: zodIssuesToValidationIssues(result.error.errors) };
228
+ }
229
+ const crossIssues = crossValidateDuctConfig(result.data);
230
+ if (crossIssues.length > 0) {
231
+ return { ok: false, issues: crossIssues };
232
+ }
233
+ return { ok: true, data: result.data };
234
+ }
175
235
  /**
176
236
  * Define and validate a Duct configuration.
177
237
  * This is the primary entrypoint for companies configuring their Duct shell.
@@ -204,35 +264,12 @@ export const DuctConfigSchema = z.object({
204
264
  * ```
205
265
  */
206
266
  export function defineDuctConfig(config) {
207
- const result = DuctConfigSchema.safeParse(config);
208
- if (!result.success) {
209
- const formatted = result.error.errors
210
- .map((e) => ` • [${e.path.join(".")}] ${e.message}`)
267
+ const validation = validateDuctConfigStrict(config);
268
+ if (!validation.ok) {
269
+ const formatted = validation.issues
270
+ .map((i) => ` • [${i.area}] ${i.issue}`)
211
271
  .join("\n");
212
272
  throw new Error(`Invalid Duct configuration:\n${formatted}\n\nSee your Duct docs /config reference for details.`);
213
273
  }
214
- // Cross-validate: deeplink target routes must exist in routes list
215
- const routePaths = new Set(result.data.routes.map((r) => r.path));
216
- const deeplinkErrors = [];
217
- for (const deeplink of result.data.deeplinks) {
218
- // Normalize dynamic segments for comparison
219
- const normalizedTarget = deeplink.targetRoute.replace(/\[([^\]]+)\]/g, ":$1");
220
- const normalizedRoutes = Array.from(routePaths).map((p) => p.replace(/\[([^\]]+)\]/g, ":$1"));
221
- if (!normalizedRoutes.some((r) => r === normalizedTarget || routePaths.has(deeplink.targetRoute))) {
222
- deeplinkErrors.push(`Deeplink "${deeplink.id}" targets route "${deeplink.targetRoute}" which is not defined in routes[]`);
223
- }
224
- }
225
- if (deeplinkErrors.length > 0) {
226
- throw new Error(`Duct configuration validation errors:\n${deeplinkErrors.map((e) => ` • ${e}`).join("\n")}`);
227
- }
228
- // Cross-validate: agent permission actionOverrides must reference valid action IDs
229
- const actionIds = new Set(result.data.actions.map((a) => a.id));
230
- if (result.data.agentPermissions.actionOverrides) {
231
- for (const actionId of Object.keys(result.data.agentPermissions.actionOverrides)) {
232
- if (!actionIds.has(actionId)) {
233
- throw new Error(`agentPermissions.actionOverrides references unknown action ID: "${actionId}"`);
234
- }
235
- }
236
- }
237
- return result.data;
274
+ return validation.data;
238
275
  }
@@ -9,6 +9,8 @@ export declare function getManifestApiBase(profile?: EndpointProfile | null): st
9
9
  export declare function getShellRuntimeUrl(): string;
10
10
  export declare function getRegistryUrl(): string;
11
11
  export declare function getConfiguredDashboard(profile?: EndpointProfile | null): string;
12
+ /** Public docs base URL for generated file headers and CLI hints. */
13
+ export declare function getDocsUrl(): string;
12
14
  export declare function getManifestApiBases(profile?: EndpointProfile | null): string[];
13
15
  export declare function getCandidateApiBases(profile?: EndpointProfile | null): string[];
14
16
  export declare function getCandidateAuthBases(profile?: EndpointProfile | null): string[];
@@ -100,6 +100,16 @@ export function getConfiguredDashboard(profile) {
100
100
  stripTrailingSlash(profile?.dashboardUrl ?? "") ||
101
101
  deriveSubdomain(getDuctBaseUrl(), "dash", 3004));
102
102
  }
103
+ /** Public docs base URL for generated file headers and CLI hints. */
104
+ export function getDocsUrl() {
105
+ const explicit = env("DUCT_DOCS_URL");
106
+ if (explicit)
107
+ return explicit;
108
+ const website = env("DUCT_WEBSITE_URL");
109
+ if (website)
110
+ return `${website}/docs`;
111
+ return "http://localhost:3005/docs";
112
+ }
103
113
  // ── Backward-compat helpers (used internally) ────────────────────
104
114
  export function getManifestApiBases(profile) {
105
115
  const configured = [
@@ -0,0 +1,41 @@
1
+ export interface LoginRouteLike {
2
+ path: string;
3
+ }
4
+ export interface LoginDeeplinkLike {
5
+ id: string;
6
+ pathTemplate?: string;
7
+ targetRoute?: string;
8
+ }
9
+ export interface LoginAuthConfig {
10
+ guestAllowed?: boolean;
11
+ loginDeeplinkId?: string;
12
+ loginRoutePath?: string;
13
+ }
14
+ export interface LoginHandoffManifest {
15
+ baseUrl?: string;
16
+ auth?: LoginAuthConfig;
17
+ deeplinks?: LoginDeeplinkLike[];
18
+ routes?: LoginRouteLike[];
19
+ }
20
+ export interface LoginHandoffTarget {
21
+ deeplinkId: string;
22
+ url: string;
23
+ message: string;
24
+ }
25
+ export declare const DEFAULT_LOGIN_HANDOFF_MESSAGE = "You'll need to sign in first \u2014 I'll take you there now.";
26
+ /** Normalize dynamic route patterns to a static path prefix for navigation. */
27
+ export declare function normalizeRoutePathForLogin(path: string): string;
28
+ /**
29
+ * Pick the best login route path from a manifest route inventory.
30
+ * Used by `duct init` to populate `auth.loginRoutePath`.
31
+ */
32
+ export declare function detectLoginRoutePath(routes: LoginRouteLike[]): string | undefined;
33
+ /**
34
+ * Resolve where the shell should send an unauthenticated user to sign in.
35
+ * Priority: explicit deeplink id → explicit route path → deeplink heuristic → route heuristic.
36
+ */
37
+ export declare function resolveLoginHandoff(manifest: LoginHandoffManifest | null | undefined): LoginHandoffTarget | null;
38
+ /** True when the shell should treat the caller as unauthenticated. */
39
+ export declare function shellNeedsUserToken(manifest: LoginHandoffManifest | null | undefined, userToken?: string | null): boolean;
40
+ /** Attach login handoff fields discovered from routes/deeplinks during init. */
41
+ export declare function enrichAuthLoginHandoff<T extends LoginAuthConfig>(auth: T, routes: LoginRouteLike[], deeplinks?: LoginDeeplinkLike[]): T;
@@ -0,0 +1,133 @@
1
+ // ============================================================
2
+ // Login handoff — resolve where unauthenticated shell users sign in
3
+ // ============================================================
4
+ /** Route path segments that commonly represent a sign-in page. */
5
+ const LOGIN_ROUTE_RE = /^\/(login|signin|sign-in|auth\/signin|auth\/login|account\/login)(\/|$)/i;
6
+ const LOGIN_ID_RE = /login|sign[_-]?in/i;
7
+ export const DEFAULT_LOGIN_HANDOFF_MESSAGE = "You'll need to sign in first — I'll take you there now.";
8
+ /** Normalize dynamic route patterns to a static path prefix for navigation. */
9
+ export function normalizeRoutePathForLogin(path) {
10
+ const withoutQuery = path.split("?")[0] ?? path;
11
+ const staticPrefix = withoutQuery.split("[")[0].split(":")[0];
12
+ const trimmed = staticPrefix.replace(/\/+$/, "");
13
+ if (!trimmed)
14
+ return "/";
15
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
16
+ }
17
+ function isLoginPath(path) {
18
+ return LOGIN_ROUTE_RE.test(normalizeRoutePathForLogin(path));
19
+ }
20
+ function buildHandoffUrl(baseUrl, path) {
21
+ const trimmed = path.trim();
22
+ if (!trimmed)
23
+ return null;
24
+ if (/^https?:\/\//i.test(trimmed))
25
+ return trimmed;
26
+ if (trimmed.startsWith("/"))
27
+ return trimmed;
28
+ if (baseUrl) {
29
+ try {
30
+ return new URL(trimmed, baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`).pathname;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ return null;
37
+ }
38
+ /**
39
+ * Pick the best login route path from a manifest route inventory.
40
+ * Used by `duct init` to populate `auth.loginRoutePath`.
41
+ */
42
+ export function detectLoginRoutePath(routes) {
43
+ for (const route of routes) {
44
+ if (!route.path)
45
+ continue;
46
+ const normalized = normalizeRoutePathForLogin(route.path);
47
+ if (isLoginPath(normalized))
48
+ return normalized;
49
+ }
50
+ return undefined;
51
+ }
52
+ /**
53
+ * Resolve where the shell should send an unauthenticated user to sign in.
54
+ * Priority: explicit deeplink id → explicit route path → deeplink heuristic → route heuristic.
55
+ */
56
+ export function resolveLoginHandoff(manifest) {
57
+ if (!manifest)
58
+ return null;
59
+ const baseUrl = manifest.baseUrl;
60
+ const auth = manifest.auth;
61
+ const explicitDlId = auth?.loginDeeplinkId?.trim();
62
+ if (explicitDlId) {
63
+ const dl = manifest.deeplinks?.find((d) => d.id === explicitDlId);
64
+ const path = dl?.pathTemplate ?? dl?.targetRoute;
65
+ const url = path ? buildHandoffUrl(baseUrl, path) : null;
66
+ if (url) {
67
+ return {
68
+ deeplinkId: explicitDlId,
69
+ url,
70
+ message: DEFAULT_LOGIN_HANDOFF_MESSAGE,
71
+ };
72
+ }
73
+ }
74
+ const explicitRoute = auth?.loginRoutePath?.trim();
75
+ if (explicitRoute) {
76
+ const url = buildHandoffUrl(baseUrl, normalizeRoutePathForLogin(explicitRoute));
77
+ if (url) {
78
+ return {
79
+ deeplinkId: explicitDlId ?? "login_page",
80
+ url,
81
+ message: DEFAULT_LOGIN_HANDOFF_MESSAGE,
82
+ };
83
+ }
84
+ }
85
+ for (const dl of manifest.deeplinks ?? []) {
86
+ const path = dl.pathTemplate ?? dl.targetRoute ?? "";
87
+ if (LOGIN_ID_RE.test(dl.id) || isLoginPath(path)) {
88
+ const url = buildHandoffUrl(baseUrl, path);
89
+ if (url) {
90
+ return {
91
+ deeplinkId: dl.id,
92
+ url,
93
+ message: DEFAULT_LOGIN_HANDOFF_MESSAGE,
94
+ };
95
+ }
96
+ }
97
+ }
98
+ for (const route of manifest.routes ?? []) {
99
+ if (!route.path || !isLoginPath(route.path))
100
+ continue;
101
+ const url = buildHandoffUrl(baseUrl, normalizeRoutePathForLogin(route.path));
102
+ if (url) {
103
+ return {
104
+ deeplinkId: "login_page",
105
+ url,
106
+ message: DEFAULT_LOGIN_HANDOFF_MESSAGE,
107
+ };
108
+ }
109
+ }
110
+ return null;
111
+ }
112
+ /** True when the shell should treat the caller as unauthenticated. */
113
+ export function shellNeedsUserToken(manifest, userToken) {
114
+ if (manifest?.auth?.guestAllowed === true)
115
+ return false;
116
+ return !userToken?.trim();
117
+ }
118
+ /** Attach login handoff fields discovered from routes/deeplinks during init. */
119
+ export function enrichAuthLoginHandoff(auth, routes, deeplinks = []) {
120
+ const enriched = { ...auth };
121
+ if (!enriched.loginRoutePath) {
122
+ const detected = detectLoginRoutePath(routes);
123
+ if (detected)
124
+ enriched.loginRoutePath = detected;
125
+ }
126
+ if (!enriched.loginDeeplinkId) {
127
+ const dl = deeplinks.find((d) => LOGIN_ID_RE.test(d.id) ||
128
+ isLoginPath(d.pathTemplate ?? d.targetRoute ?? ""));
129
+ if (dl)
130
+ enriched.loginDeeplinkId = dl.id;
131
+ }
132
+ return enriched;
133
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,31 @@
1
+ import { describe, it } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { detectLoginRoutePath, enrichAuthLoginHandoff, resolveLoginHandoff, } from './login-handoff.js';
4
+ describe('detectLoginRoutePath', () => {
5
+ it('finds common login paths', () => {
6
+ assert.equal(detectLoginRoutePath([
7
+ { path: '/dashboard' },
8
+ { path: '/auth/signin' },
9
+ ]), '/auth/signin');
10
+ });
11
+ });
12
+ describe('enrichAuthLoginHandoff', () => {
13
+ it('adds loginRoutePath from routes', () => {
14
+ const auth = enrichAuthLoginHandoff({
15
+ strategy: 'nextauth',
16
+ sessionFields: ['userId'],
17
+ guestAllowed: false,
18
+ tokenExpirySeconds: 300,
19
+ }, [{ path: '/login' }]);
20
+ assert.equal(auth.loginRoutePath, '/login');
21
+ });
22
+ });
23
+ describe('resolveLoginHandoff', () => {
24
+ it('prefers explicit loginRoutePath', () => {
25
+ const target = resolveLoginHandoff({
26
+ baseUrl: 'https://app.example.com',
27
+ auth: { guestAllowed: false, loginRoutePath: '/sign-in' },
28
+ });
29
+ assert.equal(target?.url, '/sign-in');
30
+ });
31
+ });
@@ -0,0 +1,33 @@
1
+ import type { DeeplinkTokenPayload, SessionContext } from "./types.js";
2
+ /** Unified onReceive result shape across all framework adapters. */
3
+ export interface DeeplinkReceiverResult {
4
+ /** Override the redirect URL (default: derived from config) */
5
+ redirectUrl?: string;
6
+ /** Additional data to include in JSON responses (Next adapter) */
7
+ data?: Record<string, unknown>;
8
+ /** Additional headers to set on the response */
9
+ headers?: Record<string, string>;
10
+ }
11
+ /**
12
+ * Build a redirect URL from a deeplink target route and token state.
13
+ * Replaces `[param]` segments and appends remaining state as query params.
14
+ */
15
+ export declare function buildDeeplinkRedirectUrl(targetRoute: string, state: Record<string, unknown>, baseUrl: string): string;
16
+ /** Build a minimal session context for a deeplink handoff. */
17
+ export declare function buildDeeplinkSession(sub: string, shellId: string): SessionContext;
18
+ /**
19
+ * Validate required JWT claims after verifyDeeplinkToken succeeds.
20
+ * Returns an error message when a required claim is missing, else null.
21
+ */
22
+ export declare function validateDeeplinkClaims(payload: DeeplinkTokenPayload): string | null;
23
+ /**
24
+ * Fire-and-forget callback to Duct confirming deeplink receipt.
25
+ * No-op when DUCT_API_KEY is unset.
26
+ */
27
+ export declare function confirmDeeplinkReceipt(options: {
28
+ deeplinkId: string;
29
+ shellId: string;
30
+ userId: string;
31
+ redirectUrl: string;
32
+ apiKey?: string;
33
+ }): void;
@@ -0,0 +1,77 @@
1
+ // ============================================================
2
+ // @duct/sdk — Shared deeplink receiver helpers
3
+ // Used by Next, Remix, Vite, and SvelteKit adapters.
4
+ // ============================================================
5
+ import { getActiveApiBase } from "./endpoints.js";
6
+ /**
7
+ * Build a redirect URL from a deeplink target route and token state.
8
+ * Replaces `[param]` segments and appends remaining state as query params.
9
+ */
10
+ export function buildDeeplinkRedirectUrl(targetRoute, state, baseUrl) {
11
+ let path = targetRoute;
12
+ const usedKeys = new Set();
13
+ for (const match of [...targetRoute.matchAll(/\[([^\]]+)\]/g)]) {
14
+ const paramName = match[1];
15
+ const value = state[paramName] ??
16
+ state[`${paramName}Id`] ??
17
+ state[`${paramName}_id`];
18
+ if (value !== undefined) {
19
+ path = path.replace(match[0], String(value));
20
+ usedKeys.add(paramName);
21
+ }
22
+ }
23
+ const queryEntries = Object.entries(state).filter(([key]) => !usedKeys.has(key) && state[key] !== undefined && state[key] !== null);
24
+ if (queryEntries.length > 0) {
25
+ const qs = new URLSearchParams(queryEntries.map(([k, v]) => [k, String(v)])).toString();
26
+ path += `?${qs}`;
27
+ }
28
+ const base = baseUrl.replace(/\/$/, "");
29
+ return `${base}${path}`;
30
+ }
31
+ /** Build a minimal session context for a deeplink handoff. */
32
+ export function buildDeeplinkSession(sub, shellId) {
33
+ return {
34
+ sessionId: `dl_${Date.now()}_${Math.random().toString(36).slice(2)}`,
35
+ shellId,
36
+ user: { id: sub },
37
+ isAgent: false,
38
+ messages: [],
39
+ createdAt: new Date().toISOString(),
40
+ updatedAt: new Date().toISOString(),
41
+ };
42
+ }
43
+ /**
44
+ * Validate required JWT claims after verifyDeeplinkToken succeeds.
45
+ * Returns an error message when a required claim is missing, else null.
46
+ */
47
+ export function validateDeeplinkClaims(payload) {
48
+ if (!payload.iss)
49
+ return "Token missing iss claim";
50
+ if (!payload.sub)
51
+ return "Token missing sub claim";
52
+ return null;
53
+ }
54
+ /**
55
+ * Fire-and-forget callback to Duct confirming deeplink receipt.
56
+ * No-op when DUCT_API_KEY is unset.
57
+ */
58
+ export function confirmDeeplinkReceipt(options) {
59
+ const ductApiKey = options.apiKey ?? process.env["DUCT_API_KEY"];
60
+ if (!ductApiKey)
61
+ return;
62
+ const ductApiBase = getActiveApiBase();
63
+ fetch(`${ductApiBase}/v1/deeplinks/${options.deeplinkId}/confirm`, {
64
+ method: "POST",
65
+ headers: {
66
+ "Content-Type": "application/json",
67
+ Authorization: `Bearer ${ductApiKey}`,
68
+ },
69
+ body: JSON.stringify({
70
+ shellId: options.shellId,
71
+ userId: options.userId,
72
+ redirectUrl: options.redirectUrl,
73
+ }),
74
+ }).catch((err) => {
75
+ console.warn("[Duct] Could not confirm receipt:", err.message);
76
+ });
77
+ }
@@ -124,6 +124,16 @@ export interface AuthSchema {
124
124
  tokenEndpoint?: string;
125
125
  /** Custom claims added to tokens */
126
126
  customClaims?: Record<string, string>;
127
+ /**
128
+ * Deeplink id for the sign-in page. When an unauthenticated user hits a
129
+ * requiresAuth action, the shell navigates here instead of showing an error.
130
+ */
131
+ loginDeeplinkId?: string;
132
+ /**
133
+ * App route path for sign-in (e.g. `/login`). Used when no login deeplink is
134
+ * declared — auto-detected from routes during `duct init` when possible.
135
+ */
136
+ loginRoutePath?: string;
127
137
  /** Agent detection confidence (0.0–1.0). */
128
138
  confidence?: number;
129
139
  /** Files and signals that led to this auth strategy being detected. */
package/dist/server.d.ts CHANGED
@@ -12,6 +12,8 @@ export { sendIntershellAction, sendIntershellQuery } from "./core/intershell.js"
12
12
  export type { IntershellClientOptions, IntershellMessage, IntershellActionResult, } from "./core/intershell.js";
13
13
  export { checkShellStatus } from "./core/status.js";
14
14
  export type { ShellStatus, ShellStatusWidget, CheckShellStatusOptions } from "./core/status.js";
15
+ export { buildDeeplinkRedirectUrl, buildDeeplinkSession, validateDeeplinkClaims, confirmDeeplinkReceipt, } from "./core/receiver.js";
16
+ export type { DeeplinkReceiverResult } from "./core/receiver.js";
15
17
  export { SHELL_PRESET_DIMENSIONS, DEFAULT_SHELL_PRESET, SHELL_PANEL_VIEWPORT_INSETS, resolveShellDimensions, fitShellPanelDimensions, } from "./core/types.js";
16
18
  export type { ShellPreset, ShellPanelViewportInsets } from "./core/types.js";
17
19
  export type { DuctConfig, DuctTokenPayload, DeeplinkTokenPayload, ActionManifest, ActionParam, RouteManifest, RouteParam, QueryParam, AuthSchema, AuthStrategy, DeeplinkDefinition, StateField, ShellManifest, ProductConfig, AgentPermissions, AgentPermissionLevel, WidgetConfig, SensitivityLevel, SessionContext, DuctAdapter, ReceiverOptions, } from "./core/types.js";
package/dist/server.js CHANGED
@@ -23,5 +23,7 @@ export { buildAction, checkActionPermission, buildActionSearchIndex, shouldDefer
23
23
  export { sendIntershellAction, sendIntershellQuery } from "./core/intershell.js";
24
24
  // Shell status check (server-side polling)
25
25
  export { checkShellStatus } from "./core/status.js";
26
+ // Shared deeplink receiver helpers (used by framework adapters)
27
+ export { buildDeeplinkRedirectUrl, buildDeeplinkSession, validateDeeplinkClaims, confirmDeeplinkReceipt, } from "./core/receiver.js";
26
28
  // Shell embed layout (presets + viewport fitting)
27
29
  export { SHELL_PRESET_DIMENSIONS, DEFAULT_SHELL_PRESET, SHELL_PANEL_VIEWPORT_INSETS, resolveShellDimensions, fitShellPanelDimensions, } from "./core/types.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duct-sdk/sdk",
3
- "version": "0.3.12",
3
+ "version": "0.4.1",
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",
@@ -20,6 +20,7 @@
20
20
  "scripts": {
21
21
  "build": "tsc",
22
22
  "dev": "tsc --watch",
23
+ "test": "npm run build && node --test dist/cli/generators/config.test.js dist/cli/generators/token-route.test.js dist/cli/generators/wiring-snippets.test.js dist/cli/processors/curl-parser.test.js dist/cli/processors/integration-audit.test.js dist/cli/processors/verify-discovery.test.js",
23
24
  "verify:publish": "node scripts/verify-publish.mjs",
24
25
  "prepublishOnly": "npm run build && npm run verify:publish"
25
26
  },