@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.
- package/CHANGELOG.md +42 -0
- package/dist/adapters/next/receiver.d.ts +2 -6
- package/dist/adapters/next/receiver.js +20 -66
- package/dist/adapters/remix/receiver.d.ts +2 -6
- package/dist/adapters/remix/receiver.js +16 -33
- package/dist/adapters/sveltekit/receiver.d.ts +2 -6
- package/dist/adapters/sveltekit/receiver.js +13 -40
- package/dist/adapters/vite/receiver.d.ts +2 -4
- package/dist/adapters/vite/receiver.js +13 -30
- package/dist/cli/agents/api-agent.d.ts +3 -1
- package/dist/cli/agents/api-agent.js +22 -11
- package/dist/cli/agents/auth-agent.js +4 -4
- package/dist/cli/agents/pipeline.js +65 -7
- package/dist/cli/agents/route-agent.d.ts +3 -1
- package/dist/cli/agents/route-agent.js +17 -6
- package/dist/cli/detectors/topology.d.ts +1 -1
- package/dist/cli/detectors/topology.js +1 -1
- package/dist/cli/generators/config.js +77 -44
- package/dist/cli/generators/config.test.d.ts +1 -0
- package/dist/cli/generators/config.test.js +219 -0
- package/dist/cli/generators/normalize.d.ts +10 -0
- package/dist/cli/generators/normalize.js +49 -0
- package/dist/cli/generators/receiver.d.ts +2 -1
- package/dist/cli/generators/receiver.js +20 -201
- package/dist/cli/generators/token-route.d.ts +8 -0
- package/dist/cli/generators/token-route.js +235 -0
- package/dist/cli/generators/token-route.test.d.ts +1 -0
- package/dist/cli/generators/token-route.test.js +53 -0
- package/dist/cli/generators/wiring-snippets.d.ts +23 -0
- package/dist/cli/generators/wiring-snippets.js +233 -0
- package/dist/cli/generators/wiring-snippets.test.d.ts +1 -0
- package/dist/cli/generators/wiring-snippets.test.js +66 -0
- package/dist/cli/index.js +41 -1
- package/dist/cli/init.d.ts +1 -7
- package/dist/cli/init.js +100 -53
- package/dist/cli/output-paths.d.ts +10 -0
- package/dist/cli/output-paths.js +60 -0
- package/dist/cli/processors/curl-parser.test.d.ts +1 -0
- package/dist/cli/processors/curl-parser.test.js +24 -0
- package/dist/cli/processors/integration-audit.d.ts +23 -0
- package/dist/cli/processors/integration-audit.js +208 -0
- package/dist/cli/processors/integration-audit.test.d.ts +1 -0
- package/dist/cli/processors/integration-audit.test.js +154 -0
- package/dist/cli/processors/prisma-parser.js +1 -1
- package/dist/cli/processors/verify-discovery.d.ts +33 -0
- package/dist/cli/processors/verify-discovery.js +193 -0
- package/dist/cli/processors/verify-discovery.test.d.ts +1 -0
- package/dist/cli/processors/verify-discovery.test.js +153 -0
- package/dist/cli/processors/zod-extractor.js +1 -1
- package/dist/core/config.d.ts +26 -0
- package/dist/core/config.js +65 -28
- package/dist/core/endpoints.d.ts +2 -0
- package/dist/core/endpoints.js +10 -0
- package/dist/core/login-handoff.d.ts +41 -0
- package/dist/core/login-handoff.js +133 -0
- package/dist/core/login-handoff.test.d.ts +1 -0
- package/dist/core/login-handoff.test.js +31 -0
- package/dist/core/receiver.d.ts +33 -0
- package/dist/core/receiver.js +77 -0
- package/dist/core/types.d.ts +10 -0
- package/dist/server.d.ts +2 -0
- package/dist/server.js +2 -0
- package/package.json +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,48 @@
|
|
|
2
2
|
|
|
3
3
|
Public release notes for the Duct SDK. Versioning follows [semver](https://semver.org).
|
|
4
4
|
|
|
5
|
+
## [0.4.1] — 2026-07-03
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
- **`auth.loginRoutePath` and `auth.loginDeeplinkId`** — optional manifest fields that tell the shell where to send unauthenticated users before invoking `requiresAuth` actions.
|
|
9
|
+
- **`core/login-handoff.ts`** — `detectLoginRoutePath()`, `enrichAuthLoginHandoff()`, and `resolveLoginHandoff()` helpers shared with codegen.
|
|
10
|
+
- **`duct init` auto-wiring** — pipeline sets `loginRoutePath` (and `loginDeeplinkId` when a matching deeplink exists) from discovered routes.
|
|
11
|
+
|
|
12
|
+
## [0.4.0] — 2026-07-02
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
- **`duct init` wiring plan** — prints create/modify/verify steps before writing files; writes `.duct/snippets/verify-duct-token.ts` (and optional consent-auth snippet when third-party agents are enabled).
|
|
16
|
+
- **Post-init integration audit** — deterministic issues table after file write (token route, receiver, embed, env, deeplinks, middleware). Same audit runs in `duct checkup` when `duct.config.ts` exists.
|
|
17
|
+
- **Third-party agent prompt** — init asks whether partner agents need user-scoped access (`none` / Duct consent / company OAuth) and generates the matching middleware guidance.
|
|
18
|
+
- **Ground-truth verification** — routes and actions matched against the filesystem; hallucinated endpoints downgraded or dropped; evidence persisted as inline comments and schemas in generated config.
|
|
19
|
+
- **29 automated tests** — config normalization, token routes, wiring snippets, integration audit, verify-discovery, curl-parser.
|
|
20
|
+
|
|
21
|
+
### Improved
|
|
22
|
+
- **Auth-aware token routes** — per-strategy session lookup (NextAuth, Clerk, Auth0, session-cookie, custom-jwt, Express, Remix, SvelteKit); returns 401 when `guestAllowed: false` and session is empty.
|
|
23
|
+
- **`duct init --api-spec`** — RouteAgent still runs in parallel so UI routes and deeplinks are discovered alongside OpenAPI actions.
|
|
24
|
+
- **Pre-write validation** — `validateDuctConfigStrict()` aborts init with an issues table on invalid config.
|
|
25
|
+
- **Relaxed `/api/` filter** — non-`/api/` action paths kept with a warning and confidence cap instead of dropped silently.
|
|
26
|
+
- **Webhook next-steps** — printed when side-effect actions are approved during review.
|
|
27
|
+
- **Ship checklist** — post-init next steps include middleware wiring path and `duct checkup`.
|
|
28
|
+
|
|
29
|
+
### Fixed
|
|
30
|
+
- **`tokenEndpoint` Zod validation** — relative paths normalized to full URLs before codegen; invalid values omitted.
|
|
31
|
+
- **Intershell review answers** — `intershell_enabled` / `registry_visibility` from interactive review now reach the generated config.
|
|
32
|
+
- **`apiBaseUrl` + `logoUrl`** — emitted in generated `duct.config.ts` product/widget blocks.
|
|
33
|
+
- **Server imports** — all generated token/receiver routes import from `@duct-sdk/sdk/server`.
|
|
34
|
+
- **Docs URL in config header** — points at Duct docs instead of a fabricated `docs.<company-domain>` link.
|
|
35
|
+
- **Docs URL in every receiver file** — `generators/receiver.ts` (Next App/Pages, Remix, Express, SvelteKit) still hardcoded `docs.your-domain.com` after the config-file fix; all five now resolve via `getDocsUrl()` too.
|
|
36
|
+
|
|
37
|
+
## [0.3.13] — 2026-07-02
|
|
38
|
+
|
|
39
|
+
### Fixed
|
|
40
|
+
- **Deeplink receipt confirmation** — Remix, Vite, and SvelteKit receivers now call `/v1/deeplinks/:id/confirm` (fire-and-forget) when `DUCT_API_KEY` is set, matching the Next.js adapter. Extracted into shared `core/receiver.ts` so adapters cannot drift.
|
|
41
|
+
- **Claim validation** — all four receivers reject tokens missing `iss` or `sub` claims after verification.
|
|
42
|
+
|
|
43
|
+
### Changed
|
|
44
|
+
- **Unified `onReceive` result** — `ReceiverResult` / `RemixReceiverResult` / `ViteReceiverResult` / `SvelteKitReceiverResult` now share the same shape (`redirectUrl`, `data`, `headers`). Next adapter applies `headers` on JSON responses.
|
|
45
|
+
- **`@duct-sdk/sdk/server`** — exports `buildDeeplinkRedirectUrl`, `buildDeeplinkSession`, `validateDeeplinkClaims`, `confirmDeeplinkReceipt`, and `DeeplinkReceiverResult`.
|
|
46
|
+
|
|
5
47
|
## [0.3.11] — 2026-06-16
|
|
6
48
|
|
|
7
49
|
### Fixed
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type NextRequest, NextResponse } from "next/server";
|
|
2
2
|
import type { DuctConfig, SessionContext } from "../../core/types.js";
|
|
3
|
+
import { type DeeplinkReceiverResult } from "../../core/receiver.js";
|
|
3
4
|
export interface DuctReceiverOptions {
|
|
4
5
|
/** Your Duct config (import from duct.config.ts) */
|
|
5
6
|
config: DuctConfig;
|
|
@@ -16,12 +17,7 @@ export interface DuctReceiverOptions {
|
|
|
16
17
|
*/
|
|
17
18
|
onError?: (error: Error, req: NextRequest) => NextResponse | Promise<NextResponse>;
|
|
18
19
|
}
|
|
19
|
-
export
|
|
20
|
-
/** Override the redirect URL (default: derived from config) */
|
|
21
|
-
redirectUrl?: string;
|
|
22
|
-
/** Additional data to include in the response */
|
|
23
|
-
data?: Record<string, unknown>;
|
|
24
|
-
}
|
|
20
|
+
export type ReceiverResult = DeeplinkReceiverResult;
|
|
25
21
|
/**
|
|
26
22
|
* Create a Next.js App Router POST handler for the Duct deeplink receiver.
|
|
27
23
|
*
|
|
@@ -4,46 +4,7 @@
|
|
|
4
4
|
// ============================================================
|
|
5
5
|
import { NextResponse } from "next/server";
|
|
6
6
|
import { verifyDeeplinkToken } from "../../core/token.js";
|
|
7
|
-
import {
|
|
8
|
-
// ----------------------------------------------------------------
|
|
9
|
-
// Helpers
|
|
10
|
-
// ----------------------------------------------------------------
|
|
11
|
-
function buildDefaultRedirectUrl(targetRoute, state, baseUrl) {
|
|
12
|
-
let path = targetRoute;
|
|
13
|
-
// Replace path params [id] with state values
|
|
14
|
-
const paramMatches = [...targetRoute.matchAll(/\[([^\]]+)\]/g)];
|
|
15
|
-
const usedKeys = new Set();
|
|
16
|
-
for (const match of paramMatches) {
|
|
17
|
-
const paramName = match[1];
|
|
18
|
-
const value = state[paramName] ??
|
|
19
|
-
state[`${paramName}Id`] ??
|
|
20
|
-
state[`${paramName}_id`];
|
|
21
|
-
if (value !== undefined) {
|
|
22
|
-
path = path.replace(match[0], String(value));
|
|
23
|
-
usedKeys.add(paramName);
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
// Append remaining state as query params
|
|
27
|
-
const queryEntries = Object.entries(state).filter(([key]) => !usedKeys.has(key) && state[key] !== undefined && state[key] !== null);
|
|
28
|
-
if (queryEntries.length > 0) {
|
|
29
|
-
const qs = new URLSearchParams(queryEntries.map(([k, v]) => [k, String(v)])).toString();
|
|
30
|
-
path += `?${qs}`;
|
|
31
|
-
}
|
|
32
|
-
// Normalize base URL
|
|
33
|
-
const base = baseUrl.replace(/\/$/, "");
|
|
34
|
-
return `${base}${path}`;
|
|
35
|
-
}
|
|
36
|
-
function buildSessionContext(sub, shellId) {
|
|
37
|
-
return {
|
|
38
|
-
sessionId: `dl_${Date.now()}_${Math.random().toString(36).slice(2)}`,
|
|
39
|
-
shellId,
|
|
40
|
-
user: { id: sub },
|
|
41
|
-
isAgent: false,
|
|
42
|
-
messages: [],
|
|
43
|
-
createdAt: new Date().toISOString(),
|
|
44
|
-
updatedAt: new Date().toISOString(),
|
|
45
|
-
};
|
|
46
|
-
}
|
|
7
|
+
import { buildDeeplinkRedirectUrl, buildDeeplinkSession, confirmDeeplinkReceipt, validateDeeplinkClaims, } from "../../core/receiver.js";
|
|
47
8
|
// ----------------------------------------------------------------
|
|
48
9
|
// DuctReceiver
|
|
49
10
|
// ----------------------------------------------------------------
|
|
@@ -105,6 +66,10 @@ export function DuctReceiver(options) {
|
|
|
105
66
|
}
|
|
106
67
|
return NextResponse.json({ error: "Invalid or expired token", detail: verifyResult.error }, { status: 401 });
|
|
107
68
|
}
|
|
69
|
+
const claimError = validateDeeplinkClaims(verifyResult.payload);
|
|
70
|
+
if (claimError) {
|
|
71
|
+
return NextResponse.json({ error: claimError }, { status: 401 });
|
|
72
|
+
}
|
|
108
73
|
const { deeplink_id, state, sub } = verifyResult.payload;
|
|
109
74
|
// Validate deeplink ID against our config
|
|
110
75
|
const deeplinkDef = config.deeplinks.find((d) => d.id === deeplink_id);
|
|
@@ -112,9 +77,7 @@ export function DuctReceiver(options) {
|
|
|
112
77
|
console.warn("[Duct] Unknown deeplink ID:", deeplink_id);
|
|
113
78
|
return NextResponse.json({ error: `Unknown deeplink: "${deeplink_id}"` }, { status: 400 });
|
|
114
79
|
}
|
|
115
|
-
|
|
116
|
-
const session = buildSessionContext(sub, config.shellId);
|
|
117
|
-
session.user = { id: sub };
|
|
80
|
+
const session = buildDeeplinkSession(sub, config.shellId);
|
|
118
81
|
// Call user's onReceive handler
|
|
119
82
|
let customResult;
|
|
120
83
|
try {
|
|
@@ -128,35 +91,26 @@ export function DuctReceiver(options) {
|
|
|
128
91
|
}
|
|
129
92
|
return NextResponse.json({ error: "Internal server error in onReceive handler" }, { status: 500 });
|
|
130
93
|
}
|
|
131
|
-
// Determine redirect URL
|
|
132
94
|
const redirectUrl = customResult?.redirectUrl ??
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
headers: {
|
|
142
|
-
"Content-Type": "application/json",
|
|
143
|
-
Authorization: `Bearer ${ductApiKey}`,
|
|
144
|
-
},
|
|
145
|
-
body: JSON.stringify({
|
|
146
|
-
shellId: config.shellId,
|
|
147
|
-
userId: sub,
|
|
148
|
-
redirectUrl,
|
|
149
|
-
}),
|
|
150
|
-
}).catch((err) => {
|
|
151
|
-
console.warn("[Duct] Could not confirm receipt:", err.message);
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
return NextResponse.json({
|
|
95
|
+
buildDeeplinkRedirectUrl(deeplinkDef.targetRoute, state, config.product.baseUrl);
|
|
96
|
+
confirmDeeplinkReceipt({
|
|
97
|
+
deeplinkId: deeplink_id,
|
|
98
|
+
shellId: config.shellId,
|
|
99
|
+
userId: sub,
|
|
100
|
+
redirectUrl,
|
|
101
|
+
});
|
|
102
|
+
const response = NextResponse.json({
|
|
155
103
|
success: true,
|
|
156
104
|
redirect: redirectUrl,
|
|
157
105
|
deeplinkId: deeplink_id,
|
|
158
106
|
userId: sub,
|
|
159
107
|
...(customResult?.data ?? {}),
|
|
160
108
|
});
|
|
109
|
+
if (customResult?.headers) {
|
|
110
|
+
for (const [k, v] of Object.entries(customResult.headers)) {
|
|
111
|
+
response.headers.set(k, v);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return response;
|
|
161
115
|
};
|
|
162
116
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { DuctConfig, SessionContext } from "../../core/types.js";
|
|
2
|
+
import { type DeeplinkReceiverResult } from "../../core/receiver.js";
|
|
2
3
|
export interface DuctRemixReceiverOptions {
|
|
3
4
|
/** Your Duct config (import from duct.config.ts) */
|
|
4
5
|
config: DuctConfig;
|
|
@@ -15,12 +16,7 @@ export interface DuctRemixReceiverOptions {
|
|
|
15
16
|
*/
|
|
16
17
|
onError?: (error: Error, request: Request) => Response | Promise<Response>;
|
|
17
18
|
}
|
|
18
|
-
export
|
|
19
|
-
/** Override the redirect URL (default: derived from config) */
|
|
20
|
-
redirectUrl?: string;
|
|
21
|
-
/** Additional headers to set on the redirect response */
|
|
22
|
-
headers?: Record<string, string>;
|
|
23
|
-
}
|
|
19
|
+
export type RemixReceiverResult = DeeplinkReceiverResult;
|
|
24
20
|
/**
|
|
25
21
|
* Create a Remix action function for the Duct deeplink receiver.
|
|
26
22
|
*
|
|
@@ -3,37 +3,7 @@
|
|
|
3
3
|
// Verifies Duct deeplink tokens for Remix (v2/v3 loader/action)
|
|
4
4
|
// ============================================================
|
|
5
5
|
import { verifyDeeplinkToken } from "../../core/token.js";
|
|
6
|
-
|
|
7
|
-
// Helpers
|
|
8
|
-
// ----------------------------------------------------------------
|
|
9
|
-
function buildRedirectUrl(targetRoute, state, baseUrl) {
|
|
10
|
-
let path = targetRoute;
|
|
11
|
-
const usedKeys = new Set();
|
|
12
|
-
for (const match of [...targetRoute.matchAll(/\[([^\]]+)\]/g)]) {
|
|
13
|
-
const key = match[1];
|
|
14
|
-
const value = state[key] ?? state[`${key}Id`] ?? state[`${key}_id`];
|
|
15
|
-
if (value !== undefined) {
|
|
16
|
-
path = path.replace(match[0], String(value));
|
|
17
|
-
usedKeys.add(key);
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
const qs = Object.entries(state)
|
|
21
|
-
.filter(([k, v]) => !usedKeys.has(k) && v !== undefined && v !== null)
|
|
22
|
-
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)
|
|
23
|
-
.join("&");
|
|
24
|
-
return `${baseUrl.replace(/\/$/, "")}${path}${qs ? `?${qs}` : ""}`;
|
|
25
|
-
}
|
|
26
|
-
function buildSession(sub, shellId) {
|
|
27
|
-
return {
|
|
28
|
-
sessionId: `dl_${Date.now()}_${Math.random().toString(36).slice(2)}`,
|
|
29
|
-
shellId,
|
|
30
|
-
user: { id: sub },
|
|
31
|
-
isAgent: false,
|
|
32
|
-
messages: [],
|
|
33
|
-
createdAt: new Date().toISOString(),
|
|
34
|
-
updatedAt: new Date().toISOString(),
|
|
35
|
-
};
|
|
36
|
-
}
|
|
6
|
+
import { buildDeeplinkRedirectUrl, buildDeeplinkSession, confirmDeeplinkReceipt, validateDeeplinkClaims, } from "../../core/receiver.js";
|
|
37
7
|
// ----------------------------------------------------------------
|
|
38
8
|
// DuctRemixReceiver — returns a Remix action function
|
|
39
9
|
// ----------------------------------------------------------------
|
|
@@ -116,6 +86,13 @@ export function DuctRemixReceiver(options) {
|
|
|
116
86
|
headers: { "Content-Type": "application/json" },
|
|
117
87
|
});
|
|
118
88
|
}
|
|
89
|
+
const claimError = validateDeeplinkClaims(result.payload);
|
|
90
|
+
if (claimError) {
|
|
91
|
+
return new Response(JSON.stringify({ error: claimError }), {
|
|
92
|
+
status: 401,
|
|
93
|
+
headers: { "Content-Type": "application/json" },
|
|
94
|
+
});
|
|
95
|
+
}
|
|
119
96
|
const { deeplink_id, state, sub } = result.payload;
|
|
120
97
|
const deeplinkDef = config.deeplinks.find((d) => d.id === deeplink_id);
|
|
121
98
|
if (!deeplinkDef) {
|
|
@@ -124,12 +101,18 @@ export function DuctRemixReceiver(options) {
|
|
|
124
101
|
headers: { "Content-Type": "application/json" },
|
|
125
102
|
});
|
|
126
103
|
}
|
|
127
|
-
const session =
|
|
128
|
-
let redirectUrl =
|
|
104
|
+
const session = buildDeeplinkSession(sub, config.shellId);
|
|
105
|
+
let redirectUrl = buildDeeplinkRedirectUrl(deeplinkDef.targetRoute, state, config.product.baseUrl);
|
|
129
106
|
try {
|
|
130
107
|
const userResult = await onReceive(deeplink_id, state, session);
|
|
131
108
|
if (userResult?.redirectUrl)
|
|
132
109
|
redirectUrl = userResult.redirectUrl;
|
|
110
|
+
confirmDeeplinkReceipt({
|
|
111
|
+
deeplinkId: deeplink_id,
|
|
112
|
+
shellId: config.shellId,
|
|
113
|
+
userId: sub,
|
|
114
|
+
redirectUrl,
|
|
115
|
+
});
|
|
133
116
|
const headers = new Headers({ Location: redirectUrl });
|
|
134
117
|
headers.set("Content-Type", "application/json");
|
|
135
118
|
if (userResult?.headers) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { DuctConfig, SessionContext } from "../../core/types.js";
|
|
2
|
+
import { type DeeplinkReceiverResult } from "../../core/receiver.js";
|
|
2
3
|
/**
|
|
3
4
|
* A SvelteKit RequestEvent — subset of what SvelteKit provides.
|
|
4
5
|
* Typed loosely so the adapter does not require @sveltejs/kit as a
|
|
@@ -27,12 +28,7 @@ export interface DuctSvelteKitReceiverOptions {
|
|
|
27
28
|
*/
|
|
28
29
|
onError?: (error: Error, event: SvelteKitRequestEvent) => Response | Promise<Response>;
|
|
29
30
|
}
|
|
30
|
-
export
|
|
31
|
-
/** Override the redirect URL (default: derived from config) */
|
|
32
|
-
redirectUrl?: string;
|
|
33
|
-
/** Additional headers to set on the redirect response */
|
|
34
|
-
headers?: Record<string, string>;
|
|
35
|
-
}
|
|
31
|
+
export type SvelteKitReceiverResult = DeeplinkReceiverResult;
|
|
36
32
|
/**
|
|
37
33
|
* Create a SvelteKit POST handler for the Duct deeplink receiver.
|
|
38
34
|
*
|
|
@@ -3,39 +3,10 @@
|
|
|
3
3
|
// Verifies Duct deeplink tokens for SvelteKit (server hooks / +server.ts)
|
|
4
4
|
// ============================================================
|
|
5
5
|
import { verifyDeeplinkToken } from "../../core/token.js";
|
|
6
|
+
import { buildDeeplinkRedirectUrl, buildDeeplinkSession, confirmDeeplinkReceipt, validateDeeplinkClaims, } from "../../core/receiver.js";
|
|
6
7
|
// ----------------------------------------------------------------
|
|
7
8
|
// Helpers
|
|
8
9
|
// ----------------------------------------------------------------
|
|
9
|
-
function buildRedirectUrl(targetRoute, state, baseUrl) {
|
|
10
|
-
let path = targetRoute;
|
|
11
|
-
const usedKeys = new Set();
|
|
12
|
-
// Replace [param] style tokens with values from state
|
|
13
|
-
for (const match of [...targetRoute.matchAll(/\[([^\]]+)\]/g)]) {
|
|
14
|
-
const key = match[1];
|
|
15
|
-
const value = state[key] ?? state[`${key}Id`] ?? state[`${key}_id`];
|
|
16
|
-
if (value !== undefined) {
|
|
17
|
-
path = path.replace(match[0], String(value));
|
|
18
|
-
usedKeys.add(key);
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
// Append remaining state as query string
|
|
22
|
-
const qs = Object.entries(state)
|
|
23
|
-
.filter(([k, v]) => !usedKeys.has(k) && v !== undefined && v !== null)
|
|
24
|
-
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)
|
|
25
|
-
.join("&");
|
|
26
|
-
return `${baseUrl.replace(/\/$/, "")}${path}${qs ? `?${qs}` : ""}`;
|
|
27
|
-
}
|
|
28
|
-
function buildSession(sub, shellId) {
|
|
29
|
-
return {
|
|
30
|
-
sessionId: `dl_${Date.now()}_${Math.random().toString(36).slice(2)}`,
|
|
31
|
-
shellId,
|
|
32
|
-
user: { id: sub },
|
|
33
|
-
isAgent: false,
|
|
34
|
-
messages: [],
|
|
35
|
-
createdAt: new Date().toISOString(),
|
|
36
|
-
updatedAt: new Date().toISOString(),
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
10
|
function errorResponse(body, status) {
|
|
40
11
|
return new Response(JSON.stringify(body), {
|
|
41
12
|
status,
|
|
@@ -112,28 +83,30 @@ export function DuctSvelteKitReceiver(options) {
|
|
|
112
83
|
return onError(err, event);
|
|
113
84
|
return errorResponse({ error: "Invalid token", detail: result.error }, 401);
|
|
114
85
|
}
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
if (!result.payload.iss) {
|
|
119
|
-
return errorResponse({ error: "Token missing iss claim" }, 401);
|
|
120
|
-
}
|
|
121
|
-
if (!sub) {
|
|
122
|
-
return errorResponse({ error: "Token missing sub claim" }, 401);
|
|
86
|
+
const claimError = validateDeeplinkClaims(result.payload);
|
|
87
|
+
if (claimError) {
|
|
88
|
+
return errorResponse({ error: claimError }, 401);
|
|
123
89
|
}
|
|
90
|
+
const { deeplink_id, state, sub } = result.payload;
|
|
124
91
|
// ── Look up deeplink definition ────────────────────────────
|
|
125
92
|
const deeplinkDef = config.deeplinks.find((d) => d.id === deeplink_id);
|
|
126
93
|
if (!deeplinkDef) {
|
|
127
94
|
return errorResponse({ error: "Unknown deeplink" }, 400);
|
|
128
95
|
}
|
|
129
|
-
const session =
|
|
130
|
-
let redirectUrl =
|
|
96
|
+
const session = buildDeeplinkSession(sub, config.shellId);
|
|
97
|
+
let redirectUrl = buildDeeplinkRedirectUrl(deeplinkDef.targetRoute, state, config.product.baseUrl);
|
|
131
98
|
// ── Call user handler ──────────────────────────────────────
|
|
132
99
|
try {
|
|
133
100
|
const userResult = await onReceive(deeplink_id, state, session);
|
|
134
101
|
if (userResult?.redirectUrl) {
|
|
135
102
|
redirectUrl = userResult.redirectUrl;
|
|
136
103
|
}
|
|
104
|
+
confirmDeeplinkReceipt({
|
|
105
|
+
deeplinkId: deeplink_id,
|
|
106
|
+
shellId: config.shellId,
|
|
107
|
+
userId: sub,
|
|
108
|
+
redirectUrl,
|
|
109
|
+
});
|
|
137
110
|
const headers = new Headers({ Location: redirectUrl });
|
|
138
111
|
headers.set("Content-Type", "application/json");
|
|
139
112
|
if (userResult?.headers) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { DuctConfig, SessionContext } from "../../core/types.js";
|
|
2
|
+
import { type DeeplinkReceiverResult } from "../../core/receiver.js";
|
|
2
3
|
/** Minimal request interface — subset supported by Express / Hono / Fetch API */
|
|
3
4
|
export interface DuctRequest {
|
|
4
5
|
method: string;
|
|
@@ -27,10 +28,7 @@ export interface DuctViteReceiverOptions {
|
|
|
27
28
|
/** Called on any error during handling */
|
|
28
29
|
onError?: (error: Error) => DuctResponseInit | Promise<DuctResponseInit>;
|
|
29
30
|
}
|
|
30
|
-
export
|
|
31
|
-
redirectUrl?: string;
|
|
32
|
-
headers?: Record<string, string>;
|
|
33
|
-
}
|
|
31
|
+
export type ViteReceiverResult = DeeplinkReceiverResult;
|
|
34
32
|
/**
|
|
35
33
|
* Create a framework-agnostic handler for the Duct deeplink receiver.
|
|
36
34
|
* Returns a plain `DuctResponseInit` object you can adapt to your server.
|
|
@@ -4,37 +4,10 @@
|
|
|
4
4
|
// Works with Express, Hono, or any Node.js HTTP server.
|
|
5
5
|
// ============================================================
|
|
6
6
|
import { verifyDeeplinkToken } from "../../core/token.js";
|
|
7
|
+
import { buildDeeplinkRedirectUrl, buildDeeplinkSession, confirmDeeplinkReceipt, validateDeeplinkClaims, } from "../../core/receiver.js";
|
|
7
8
|
// ----------------------------------------------------------------
|
|
8
9
|
// Helpers
|
|
9
10
|
// ----------------------------------------------------------------
|
|
10
|
-
function buildRedirectUrl(targetRoute, state, baseUrl) {
|
|
11
|
-
let path = targetRoute;
|
|
12
|
-
const usedKeys = new Set();
|
|
13
|
-
for (const match of [...targetRoute.matchAll(/\[([^\]]+)\]/g)]) {
|
|
14
|
-
const key = match[1];
|
|
15
|
-
const value = state[key] ?? state[`${key}Id`] ?? state[`${key}_id`];
|
|
16
|
-
if (value !== undefined) {
|
|
17
|
-
path = path.replace(match[0], String(value));
|
|
18
|
-
usedKeys.add(key);
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
const qs = Object.entries(state)
|
|
22
|
-
.filter(([k, v]) => !usedKeys.has(k) && v !== undefined && v !== null)
|
|
23
|
-
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)
|
|
24
|
-
.join("&");
|
|
25
|
-
return `${baseUrl.replace(/\/$/, "")}${path}${qs ? `?${qs}` : ""}`;
|
|
26
|
-
}
|
|
27
|
-
function buildSession(sub, shellId) {
|
|
28
|
-
return {
|
|
29
|
-
sessionId: `dl_${Date.now()}_${Math.random().toString(36).slice(2)}`,
|
|
30
|
-
shellId,
|
|
31
|
-
user: { id: sub },
|
|
32
|
-
isAgent: false,
|
|
33
|
-
messages: [],
|
|
34
|
-
createdAt: new Date().toISOString(),
|
|
35
|
-
updatedAt: new Date().toISOString(),
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
11
|
function jsonResponse(body, status, extra) {
|
|
39
12
|
return {
|
|
40
13
|
status,
|
|
@@ -132,17 +105,27 @@ export function DuctViteReceiver(options) {
|
|
|
132
105
|
return onError(err);
|
|
133
106
|
return jsonResponse({ error: "Invalid token", detail: result.error }, 401);
|
|
134
107
|
}
|
|
108
|
+
const claimError = validateDeeplinkClaims(result.payload);
|
|
109
|
+
if (claimError) {
|
|
110
|
+
return jsonResponse({ error: claimError }, 401);
|
|
111
|
+
}
|
|
135
112
|
const { deeplink_id, state, sub } = result.payload;
|
|
136
113
|
const deeplinkDef = config.deeplinks.find((d) => d.id === deeplink_id);
|
|
137
114
|
if (!deeplinkDef) {
|
|
138
115
|
return jsonResponse({ error: "Unknown deeplink" }, 400);
|
|
139
116
|
}
|
|
140
|
-
const session =
|
|
141
|
-
let redirectUrl =
|
|
117
|
+
const session = buildDeeplinkSession(sub, config.shellId);
|
|
118
|
+
let redirectUrl = buildDeeplinkRedirectUrl(deeplinkDef.targetRoute, state, config.product.baseUrl);
|
|
142
119
|
try {
|
|
143
120
|
const userResult = await onReceive(deeplink_id, state, session);
|
|
144
121
|
if (userResult?.redirectUrl)
|
|
145
122
|
redirectUrl = userResult.redirectUrl;
|
|
123
|
+
confirmDeeplinkReceipt({
|
|
124
|
+
deeplinkId: deeplink_id,
|
|
125
|
+
shellId: config.shellId,
|
|
126
|
+
userId: sub,
|
|
127
|
+
redirectUrl,
|
|
128
|
+
});
|
|
146
129
|
return {
|
|
147
130
|
status: 302,
|
|
148
131
|
headers: {
|
|
@@ -17,4 +17,6 @@ export interface ApiScannerStrategy {
|
|
|
17
17
|
* @param inlineSpecContent - Raw spec content passed via --api-spec (bypasses sandbox lookup).
|
|
18
18
|
* @param inlineSpecPath - Display path for the inline spec (used in prompt context).
|
|
19
19
|
*/
|
|
20
|
-
export declare function runApiAgent(sandboxFs: SandboxFS, hintFiles?: string[], inlineSpecContent?: string, inlineSpecPath?: string
|
|
20
|
+
export declare function runApiAgent(sandboxFs: SandboxFS, hintFiles?: string[], inlineSpecContent?: string, inlineSpecPath?: string, options?: {
|
|
21
|
+
retry?: boolean;
|
|
22
|
+
}): Promise<ActionManifest[]>;
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { callDuctLLM } from "./llm.js";
|
|
6
6
|
import { extractZodHintsFromFiles } from "../processors/zod-extractor.js";
|
|
7
7
|
import { parsePrismaSchema } from "../processors/prisma-parser.js";
|
|
8
|
+
import { normalizeEvidenceArray } from "../processors/verify-discovery.js";
|
|
8
9
|
const MAX_LISTED_FILES = 60;
|
|
9
10
|
const MAX_SNIPPET_FILES = 20;
|
|
10
11
|
const SNIPPET_SIZE = 1800;
|
|
@@ -351,12 +352,12 @@ async function detectApiRoots(sandboxFs) {
|
|
|
351
352
|
// Deduplicate while preserving order
|
|
352
353
|
return [...new Set(roots)];
|
|
353
354
|
}
|
|
354
|
-
async function buildFileSystemPrompt(sandboxFs, hintFiles) {
|
|
355
|
+
async function buildFileSystemPrompt(sandboxFs, hintFiles, retryHint) {
|
|
355
356
|
const lines = [];
|
|
356
357
|
lines.push("Analyze these API route files and produce an ActionManifest array.\n");
|
|
357
358
|
lines.push("Only include endpoints that are explicitly backed by code evidence in the snippets below.");
|
|
358
359
|
lines.push("If evidence is missing or ambiguous, omit the action instead of guessing.\n");
|
|
359
|
-
//
|
|
360
|
+
// Inject Prisma model field names so the agent can map CRUD params accurately.
|
|
360
361
|
const prismaSchema = await sandboxFs.readFile("prisma/schema.prisma");
|
|
361
362
|
if (prismaSchema) {
|
|
362
363
|
const { annotation } = parsePrismaSchema(prismaSchema);
|
|
@@ -540,6 +541,10 @@ STRICTNESS RULES:
|
|
|
540
541
|
- If uncertain, omit the action.
|
|
541
542
|
|
|
542
543
|
DO NOT include Next.js internal routes or static assets.`);
|
|
544
|
+
if (retryHint) {
|
|
545
|
+
lines.push("");
|
|
546
|
+
lines.push(retryHint);
|
|
547
|
+
}
|
|
543
548
|
return lines.join("\n");
|
|
544
549
|
}
|
|
545
550
|
// ----------------------------------------------------------------
|
|
@@ -557,7 +562,7 @@ DO NOT include Next.js internal routes or static assets.`);
|
|
|
557
562
|
* @param inlineSpecContent - Raw spec content passed via --api-spec (bypasses sandbox lookup).
|
|
558
563
|
* @param inlineSpecPath - Display path for the inline spec (used in prompt context).
|
|
559
564
|
*/
|
|
560
|
-
export async function runApiAgent(sandboxFs, hintFiles, inlineSpecContent, inlineSpecPath) {
|
|
565
|
+
export async function runApiAgent(sandboxFs, hintFiles, inlineSpecContent, inlineSpecPath, options) {
|
|
561
566
|
// If spec was passed directly (--api-spec flag), use it without further discovery
|
|
562
567
|
if (inlineSpecContent) {
|
|
563
568
|
const prompt = await buildOpenAPIPrompt(inlineSpecContent, inlineSpecPath ?? "openapi.json");
|
|
@@ -603,7 +608,10 @@ export async function runApiAgent(sandboxFs, hintFiles, inlineSpecContent, inlin
|
|
|
603
608
|
}
|
|
604
609
|
}
|
|
605
610
|
// Fall back to filesystem scanning
|
|
606
|
-
const
|
|
611
|
+
const retryHint = options?.retry
|
|
612
|
+
? "RETRY: Your previous pass returned zero actions. Re-read every snippet and include each endpoint you can tie to an explicit HTTP method + path in the code."
|
|
613
|
+
: undefined;
|
|
614
|
+
const prompt = await buildFileSystemPrompt(sandboxFs, hintFiles, retryHint);
|
|
607
615
|
const result = await callDuctLLM({
|
|
608
616
|
agentName: "ApiAgent",
|
|
609
617
|
systemPrompt: "You are an expert at analyzing Next.js, Express, and tRPC API codebases. " +
|
|
@@ -635,14 +643,19 @@ function sanitizeActions(actions) {
|
|
|
635
643
|
const sensitivityLevel = validateSensitivityLevel(a.sensitivityLevel);
|
|
636
644
|
const sideEffects = a.sideEffects ?? ["POST", "PUT", "PATCH", "DELETE"].includes(method);
|
|
637
645
|
// agentAccessible inference: safe defaults
|
|
638
|
-
// true only when: GET method AND sensitivity is none/low AND no side effects
|
|
639
|
-
// The LLM may have set it based on code evidence — respect that if it's true
|
|
640
646
|
const inferredAgentAccessible = method === "GET" &&
|
|
641
647
|
!sideEffects &&
|
|
642
648
|
sensitivityLevel !== "high" &&
|
|
643
649
|
sensitivityLevel !== "critical";
|
|
644
|
-
// If the LLM set agentAccessible: true but our inference says false → keep false (fail-closed)
|
|
645
650
|
const agentAccessible = a.agentAccessible === true ? inferredAgentAccessible : false;
|
|
651
|
+
const evidence = normalizeEvidenceArray(a.evidence);
|
|
652
|
+
let confidence = typeof a.confidence === "number"
|
|
653
|
+
? Math.min(1, Math.max(0, a.confidence))
|
|
654
|
+
: undefined;
|
|
655
|
+
if (!isLikelyApiPath(path)) {
|
|
656
|
+
evidence.push("warning: path does not start with /api/ — verify action proxy target");
|
|
657
|
+
confidence = Math.min(confidence ?? 0.7, 0.65);
|
|
658
|
+
}
|
|
646
659
|
return {
|
|
647
660
|
id: toSnakeCase(a.id || path),
|
|
648
661
|
name: a.name || a.id,
|
|
@@ -658,12 +671,10 @@ function sanitizeActions(actions) {
|
|
|
658
671
|
requiresAuth: a.requiresAuth ?? true,
|
|
659
672
|
rateLimit: a.rateLimit,
|
|
660
673
|
searchHint: a.searchHint,
|
|
661
|
-
|
|
662
|
-
...(
|
|
663
|
-
...(typeof a.evidence === "string" && a.evidence ? { evidence: a.evidence } : {}),
|
|
674
|
+
...(confidence !== undefined ? { confidence } : {}),
|
|
675
|
+
...(evidence.length > 0 ? { evidence } : {}),
|
|
664
676
|
};
|
|
665
677
|
})
|
|
666
|
-
.filter((a) => isLikelyApiPath(a.path))
|
|
667
678
|
.filter((a) => !isInternalRoute(a.path))
|
|
668
679
|
.filter((a) => {
|
|
669
680
|
const key = `${a.method}:${a.path}`;
|
|
@@ -19,7 +19,7 @@ Single AuthSchema object:
|
|
|
19
19
|
],
|
|
20
20
|
"guestAllowed": false, // Whether unauthenticated users can use the shell
|
|
21
21
|
"tokenExpirySeconds": 300, // How long Duct delegated tokens should live
|
|
22
|
-
"tokenEndpoint": "/api/duct/token", // Optional:
|
|
22
|
+
"tokenEndpoint": "https://app.example.com/api/duct/token", // Optional: full URL for token generation
|
|
23
23
|
"customClaims": {} // Optional: extra claims to include in tokens
|
|
24
24
|
}
|
|
25
25
|
`.trim();
|
|
@@ -183,9 +183,9 @@ export async function runAuthAgent(sandboxFs, hintFiles) {
|
|
|
183
183
|
tokenExpirySeconds: typeof raw.tokenExpirySeconds === "number"
|
|
184
184
|
? raw.tokenExpirySeconds
|
|
185
185
|
: 300,
|
|
186
|
-
|
|
187
|
-
? raw.tokenEndpoint
|
|
188
|
-
:
|
|
186
|
+
...(typeof raw.tokenEndpoint === "string" && raw.tokenEndpoint.trim()
|
|
187
|
+
? { tokenEndpoint: raw.tokenEndpoint.trim() }
|
|
188
|
+
: {}),
|
|
189
189
|
customClaims: typeof raw.customClaims === "object" && raw.customClaims !== null
|
|
190
190
|
? raw.customClaims
|
|
191
191
|
: undefined,
|