@duct-sdk/sdk 0.4.4 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +55 -0
- package/README.md +36 -1
- package/TOKEN_SPEC.md +237 -0
- package/dist/adapters/react/page-context-guard.d.ts +7 -0
- package/dist/adapters/react/page-context-guard.js +26 -0
- package/dist/adapters/react/page-context-guard.test.d.ts +1 -0
- package/dist/adapters/react/page-context-guard.test.js +15 -0
- package/dist/adapters/react/shell.js +110 -37
- package/dist/adapters/react/use-page-context.d.ts +1 -1
- package/dist/adapters/react/use-page-context.js +6 -16
- package/dist/cli/agents/reviewer-agent.d.ts +3 -1
- package/dist/cli/agents/reviewer-agent.js +29 -21
- package/dist/cli/config-loader.d.ts +15 -0
- package/dist/cli/config-loader.js +187 -0
- package/dist/cli/config-loader.test.d.ts +1 -0
- package/dist/cli/config-loader.test.js +63 -0
- package/dist/cli/detectors/framework.d.ts +1 -1
- package/dist/cli/detectors/framework.js +40 -0
- package/dist/cli/generators/receiver.js +206 -76
- package/dist/cli/generators/shell.js +50 -4
- package/dist/cli/generators/shell.test.d.ts +1 -0
- package/dist/cli/generators/shell.test.js +73 -0
- package/dist/cli/generators/token-route.d.ts +1 -0
- package/dist/cli/generators/token-route.js +108 -5
- package/dist/cli/generators/wiring-snippets.d.ts +14 -0
- package/dist/cli/generators/wiring-snippets.js +180 -16
- package/dist/cli/generators/wiring-snippets.test.js +15 -1
- package/dist/cli/index.js +108 -151
- package/dist/cli/init.js +110 -17
- package/dist/cli/manifest-diff.d.ts +21 -0
- package/dist/cli/manifest-diff.js +158 -0
- package/dist/cli/manifest-diff.test.d.ts +1 -0
- package/dist/cli/manifest-diff.test.js +104 -0
- package/dist/cli/output-paths.d.ts +2 -0
- package/dist/cli/output-paths.js +22 -4
- package/dist/cli/processors/integration-audit.js +1 -1
- package/dist/core/config-policy.test.d.ts +1 -0
- package/dist/core/config-policy.test.js +101 -0
- package/dist/core/config.d.ts +86 -1
- package/dist/core/config.js +120 -2
- package/dist/core/invariants.test.d.ts +1 -0
- package/dist/core/invariants.test.js +217 -0
- package/dist/core/jcs.d.ts +5 -0
- package/dist/core/jcs.js +21 -0
- package/dist/core/receipt.d.ts +70 -0
- package/dist/core/receipt.js +86 -0
- package/dist/core/receipt.test.d.ts +1 -0
- package/dist/core/receipt.test.js +75 -0
- package/dist/core/replay-store.d.ts +51 -0
- package/dist/core/replay-store.js +65 -0
- package/dist/core/token.d.ts +14 -0
- package/dist/core/token.js +50 -18
- package/dist/core/token.test.d.ts +1 -0
- package/dist/core/token.test.js +66 -0
- package/dist/core/types.d.ts +72 -0
- package/dist/index.d.ts +6 -4
- package/dist/index.js +4 -2
- package/dist/server.d.ts +6 -4
- package/dist/server.js +4 -2
- package/package.json +91 -90
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
// ============================================================
|
|
2
2
|
// @duct/sdk — Token route generator (auth-strategy aware)
|
|
3
3
|
// ============================================================
|
|
4
|
+
function sessionFieldsLiteral(fields) {
|
|
5
|
+
const list = fields && fields.length > 0 ? fields : [];
|
|
6
|
+
return JSON.stringify(list);
|
|
7
|
+
}
|
|
4
8
|
function guestGuard(guestAllowed) {
|
|
5
9
|
if (guestAllowed) {
|
|
6
10
|
return ` // Guest users allowed — empty session mints a limited delegated token.
|
|
@@ -72,6 +76,7 @@ function nextAuthSessionLookup(strategy, framework) {
|
|
|
72
76
|
export function generateStrategyTokenRoute(framework, options) {
|
|
73
77
|
const expiry = options.tokenExpirySeconds ?? 300;
|
|
74
78
|
const guestBlock = guestGuard(options.guestAllowed);
|
|
79
|
+
const sessionFieldsLine = ` sessionFields: ${sessionFieldsLiteral(options.sessionFields)},`;
|
|
75
80
|
if (framework.name === "sveltekit") {
|
|
76
81
|
return `// src/routes/api/duct/token/+server.ts
|
|
77
82
|
import type { RequestHandler } from "@sveltejs/kit";
|
|
@@ -87,13 +92,14 @@ export const POST: RequestHandler = async ({ locals }) => {
|
|
|
87
92
|
}
|
|
88
93
|
|
|
89
94
|
const userSession = ((locals as Record<string, unknown>).user ?? {}) as Record<string, unknown>;
|
|
90
|
-
${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, '
|
|
95
|
+
${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'json({ error: "Unauthorized" }, { status: 401 })')}
|
|
91
96
|
|
|
92
97
|
const { token, expiresAt } = await generateDuctToken({
|
|
93
98
|
secretKey,
|
|
94
99
|
shellId,
|
|
95
100
|
userSession,
|
|
96
101
|
expirySeconds: ${expiry},
|
|
102
|
+
${sessionFieldsLine}
|
|
97
103
|
});
|
|
98
104
|
|
|
99
105
|
return json({ token, expiresAt: expiresAt.toISOString() });
|
|
@@ -120,20 +126,23 @@ export async function action({ request }: ActionFunctionArgs) {
|
|
|
120
126
|
|
|
121
127
|
// Wire your Remix session (e.g. getSession from remix-auth)
|
|
122
128
|
const userSession: Record<string, unknown> = {};
|
|
123
|
-
${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, '
|
|
129
|
+
${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'json({ error: "Unauthorized" }, { status: 401 })')}
|
|
124
130
|
|
|
125
131
|
const { token, expiresAt } = await generateDuctToken({
|
|
126
132
|
secretKey,
|
|
127
133
|
shellId,
|
|
128
134
|
userSession,
|
|
129
135
|
expirySeconds: ${expiry},
|
|
136
|
+
${sessionFieldsLine}
|
|
130
137
|
});
|
|
131
138
|
|
|
132
139
|
return json({ token, expiresAt: expiresAt.toISOString() });
|
|
133
140
|
}
|
|
134
141
|
`;
|
|
135
142
|
}
|
|
136
|
-
if (framework.name === "vite-react"
|
|
143
|
+
if (framework.name === "vite-react" ||
|
|
144
|
+
framework.name === "express" ||
|
|
145
|
+
framework.name === "vue3") {
|
|
137
146
|
return `// server/routes/duct-token.ts
|
|
138
147
|
import { Router } from "express";
|
|
139
148
|
import { generateDuctToken } from "@duct-sdk/sdk/server";
|
|
@@ -149,19 +158,111 @@ router.post("/api/duct/token", async (req, res) => {
|
|
|
149
158
|
}
|
|
150
159
|
|
|
151
160
|
const userSession = (req as typeof req & { user?: Record<string, unknown> }).user ?? {};
|
|
152
|
-
${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, '
|
|
161
|
+
${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'res.status(401).json({ error: "Unauthorized" })')}
|
|
153
162
|
|
|
154
163
|
const { token, expiresAt } = await generateDuctToken({
|
|
155
164
|
secretKey,
|
|
156
165
|
shellId,
|
|
157
166
|
userSession,
|
|
158
167
|
expirySeconds: ${expiry},
|
|
168
|
+
${sessionFieldsLine}
|
|
159
169
|
});
|
|
160
170
|
|
|
161
171
|
return res.status(200).json({ token, expiresAt: expiresAt.toISOString() });
|
|
162
172
|
});
|
|
163
173
|
|
|
164
174
|
export default router;
|
|
175
|
+
`;
|
|
176
|
+
}
|
|
177
|
+
if (framework.name === "nuxt") {
|
|
178
|
+
return `// server/api/duct/token.post.ts
|
|
179
|
+
import { generateDuctToken } from "@duct-sdk/sdk/server";
|
|
180
|
+
|
|
181
|
+
export default defineEventHandler(async (event) => {
|
|
182
|
+
const secretKey = process.env.DUCT_SECRET_KEY;
|
|
183
|
+
const shellId = process.env.NUXT_PUBLIC_DUCT_SHELL_ID ?? process.env.DUCT_SHELL_ID;
|
|
184
|
+
|
|
185
|
+
if (!secretKey || !shellId) {
|
|
186
|
+
setResponseStatus(event, 500);
|
|
187
|
+
return { error: "Duct not configured" };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Wire your Nuxt server session (e.g. from nuxt-auth-utils / event.context).
|
|
191
|
+
const userSession = ((event.context as Record<string, unknown>).user ?? {}) as Record<string, unknown>;
|
|
192
|
+
${guestBlock.replace(/return unauthorized\("Unauthorized"\);/g, 'setResponseStatus(event, 401); return { error: "Unauthorized" };')}
|
|
193
|
+
|
|
194
|
+
const { token, expiresAt } = await generateDuctToken({
|
|
195
|
+
secretKey,
|
|
196
|
+
shellId,
|
|
197
|
+
userSession,
|
|
198
|
+
expirySeconds: ${expiry},
|
|
199
|
+
${sessionFieldsLine}
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
return { token, expiresAt: expiresAt.toISOString() };
|
|
203
|
+
});
|
|
204
|
+
`;
|
|
205
|
+
}
|
|
206
|
+
if (framework.name === "fastapi") {
|
|
207
|
+
const scalarFields = options.sessionFields && options.sessionFields.length > 0 ? options.sessionFields : [];
|
|
208
|
+
const guestPy = options.guestAllowed
|
|
209
|
+
? " # Guest users allowed — an empty session mints a limited delegated token.\n # Set auth.guestAllowed: false in duct.config.ts to require login first."
|
|
210
|
+
: ' if not user_session:\n return JSONResponse({"error": "Unauthorized"}, status_code=401)';
|
|
211
|
+
return `# duct_token.py — auto-generated by \`npx duct init\`
|
|
212
|
+
# FastAPI route that mints a Duct delegated token (HS256 JWT, matches @duct-sdk/sdk).
|
|
213
|
+
# Requires: pip install pyjwt
|
|
214
|
+
import os
|
|
215
|
+
import time
|
|
216
|
+
from datetime import datetime, timezone
|
|
217
|
+
|
|
218
|
+
import jwt # PyJWT
|
|
219
|
+
from fastapi import APIRouter, Request
|
|
220
|
+
from fastapi.responses import JSONResponse
|
|
221
|
+
|
|
222
|
+
router = APIRouter()
|
|
223
|
+
|
|
224
|
+
# Allowlisted session fields copied into the delegated token (from auth.sessionFields).
|
|
225
|
+
_ALLOWED_FIELDS = ${JSON.stringify(scalarFields)}
|
|
226
|
+
_DENY_FRAGMENTS = ("token", "secret", "password", "key", "hash", "salt",
|
|
227
|
+
"credential", "jwt", "cookie", "bearer", "ssn", "otp")
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _filter_scalars(session: dict) -> dict:
|
|
231
|
+
out = {}
|
|
232
|
+
items = ((k, session.get(k)) for k in _ALLOWED_FIELDS) if _ALLOWED_FIELDS else session.items()
|
|
233
|
+
for key, value in items:
|
|
234
|
+
if any(frag in key.lower() for frag in _DENY_FRAGMENTS):
|
|
235
|
+
continue
|
|
236
|
+
if value is None or isinstance(value, (str, int, float, bool)):
|
|
237
|
+
out[key] = value
|
|
238
|
+
return out
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
@router.post("/api/duct/token")
|
|
242
|
+
async def duct_token(request: Request):
|
|
243
|
+
secret = os.environ.get("DUCT_SECRET_KEY")
|
|
244
|
+
shell_id = os.environ.get("DUCT_SHELL_ID")
|
|
245
|
+
if not secret or not shell_id:
|
|
246
|
+
return JSONResponse({"error": "Duct not configured"}, status_code=500)
|
|
247
|
+
|
|
248
|
+
# TODO: replace with your real authenticated session lookup.
|
|
249
|
+
user_session: dict = getattr(request.state, "user", {}) or {}
|
|
250
|
+
${guestPy}
|
|
251
|
+
|
|
252
|
+
now = int(time.time())
|
|
253
|
+
exp = now + ${expiry}
|
|
254
|
+
sub = str(user_session.get("id") or user_session.get("sub") or "anonymous")
|
|
255
|
+
payload = {
|
|
256
|
+
"type": "duct_delegated",
|
|
257
|
+
"session": _filter_scalars(user_session),
|
|
258
|
+
"sub": sub,
|
|
259
|
+
"iss": shell_id,
|
|
260
|
+
"iat": now,
|
|
261
|
+
"exp": exp,
|
|
262
|
+
}
|
|
263
|
+
token = jwt.encode(payload, secret, algorithm="HS256")
|
|
264
|
+
expires_at = datetime.fromtimestamp(exp, tz=timezone.utc).isoformat().replace("+00:00", "Z")
|
|
265
|
+
return {"token": token, "expiresAt": expires_at}
|
|
165
266
|
`;
|
|
166
267
|
}
|
|
167
268
|
const auth = nextAuthSessionLookup(options.authStrategy, framework);
|
|
@@ -192,6 +293,7 @@ ${guestBlock}
|
|
|
192
293
|
shellId,
|
|
193
294
|
userSession,
|
|
194
295
|
expirySeconds: ${expiry},
|
|
296
|
+
${sessionFieldsLine}
|
|
195
297
|
});
|
|
196
298
|
|
|
197
299
|
return NextResponse.json({ token, expiresAt: expiresAt.toISOString() });
|
|
@@ -220,13 +322,14 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse<
|
|
|
220
322
|
|
|
221
323
|
${auth.lookup}
|
|
222
324
|
const userSession = ${auth.userSessionExpr};
|
|
223
|
-
${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, '
|
|
325
|
+
${guestBlock.replace(/unauthorized\("Unauthorized"\)/g, 'res.status(401).json({ error: "Unauthorized" })')}
|
|
224
326
|
|
|
225
327
|
const { token, expiresAt } = await generateDuctToken({
|
|
226
328
|
secretKey,
|
|
227
329
|
shellId,
|
|
228
330
|
userSession,
|
|
229
331
|
expirySeconds: ${expiry},
|
|
332
|
+
${sessionFieldsLine}
|
|
230
333
|
});
|
|
231
334
|
|
|
232
335
|
return res.status(200).json({ token, expiresAt: expiresAt.toISOString() });
|
|
@@ -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;
|
|
@@ -60,7 +60,7 @@ export async function ductDelegatedAuth(req: Request, res: Response, next: NextF
|
|
|
60
60
|
return res.status(401).json({ error: result.error ?? "Invalid delegated token" });
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
-
(req as Request & { user?: Record<string, unknown> }).user = result.payload
|
|
63
|
+
(req as Request & { user?: Record<string, unknown> }).user = result.payload!.session;
|
|
64
64
|
return next();
|
|
65
65
|
}
|
|
66
66
|
`;
|
|
@@ -100,21 +100,43 @@ 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
|
+
* Identity-only: { token } is enough to resolve user_ref.
|
|
105
|
+
* Policy mode (recommended when Duct proxies the call): also send
|
|
106
|
+
* target_shell + required_action from X-Duct-Shell-ID / X-Duct-Action-ID.
|
|
107
|
+
*
|
|
108
|
+
* On success, req.ductUserRef contains the opaque company user identifier you
|
|
109
|
+
* supplied at consent-request time. Resolve mutable data (email, roles) from
|
|
110
|
+
* YOUR own DB using that id — never trust the JWT payload for live attributes.
|
|
103
111
|
*/
|
|
104
112
|
import type { Request, Response, NextFunction } from "express";
|
|
105
113
|
import { verifyDuctToken } from "@duct-sdk/sdk/server";
|
|
106
114
|
|
|
107
115
|
const DUCT_AUTH_URL = process.env.DUCT_AUTH_URL ?? "http://localhost:3001";
|
|
108
116
|
|
|
109
|
-
|
|
117
|
+
interface UctVerifyResult {
|
|
118
|
+
userRef?: string;
|
|
119
|
+
allowedActions?: string[];
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function verifyUct(
|
|
123
|
+
token: string,
|
|
124
|
+
opts?: { targetShell?: string; requiredAction?: string },
|
|
125
|
+
): Promise<UctVerifyResult | null> {
|
|
126
|
+
const body: Record<string, string> = { token };
|
|
127
|
+
if (opts?.targetShell && opts?.requiredAction) {
|
|
128
|
+
body.target_shell = opts.targetShell;
|
|
129
|
+
body.required_action = opts.requiredAction;
|
|
130
|
+
}
|
|
110
131
|
const res = await fetch(\`\${DUCT_AUTH_URL}/v1/verify/consent-token\`, {
|
|
111
132
|
method: "POST",
|
|
112
133
|
headers: { "Content-Type": "application/json" },
|
|
113
|
-
body: JSON.stringify(
|
|
134
|
+
body: JSON.stringify(body),
|
|
114
135
|
});
|
|
115
136
|
if (!res.ok) return null;
|
|
116
|
-
const
|
|
117
|
-
|
|
137
|
+
const parsed = (await res.json()) as { valid?: boolean; user_ref?: string; allowed_actions?: string[] };
|
|
138
|
+
if (!parsed.valid) return null;
|
|
139
|
+
return { userRef: parsed.user_ref, allowedActions: parsed.allowed_actions };
|
|
118
140
|
}
|
|
119
141
|
|
|
120
142
|
export async function ductOrConsentAuth(req: Request, res: Response, next: NextFunction) {
|
|
@@ -123,13 +145,26 @@ export async function ductOrConsentAuth(req: Request, res: Response, next: NextF
|
|
|
123
145
|
|
|
124
146
|
const token = authHeader.slice(7);
|
|
125
147
|
if (token.startsWith("uct_")) {
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
148
|
+
const shellId = typeof req.headers["x-duct-shell-id"] === "string" ? req.headers["x-duct-shell-id"] : undefined;
|
|
149
|
+
const actionId = typeof req.headers["x-duct-action-id"] === "string" ? req.headers["x-duct-action-id"] : undefined;
|
|
150
|
+
const result = await verifyUct(token, { targetShell: shellId, requiredAction: actionId });
|
|
151
|
+
if (!result) return res.status(401).json({ success: false, message: "Invalid Duct user consent token" });
|
|
152
|
+
(req as Request & { ductUserRef?: string }).ductUserRef = result.userRef;
|
|
129
153
|
return next();
|
|
130
154
|
}
|
|
131
155
|
|
|
132
|
-
|
|
156
|
+
const secretKey = process.env.DUCT_SECRET_KEY;
|
|
157
|
+
const shellId = process.env.DUCT_SHELL_ID;
|
|
158
|
+
if (!secretKey || !shellId) {
|
|
159
|
+
return res.status(500).json({ error: "Duct not configured" });
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const delegated = await verifyDuctToken(token, { secretKey, expectedShellId: shellId });
|
|
163
|
+
if (!delegated.valid) {
|
|
164
|
+
return res.status(401).json({ error: delegated.error ?? "Invalid delegated token" });
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
(req as Request & { user?: Record<string, unknown> }).user = delegated.payload!.session;
|
|
133
168
|
return next();
|
|
134
169
|
}
|
|
135
170
|
`;
|
|
@@ -137,35 +172,65 @@ export async function ductOrConsentAuth(req: Request, res: Response, next: NextF
|
|
|
137
172
|
return `/**
|
|
138
173
|
* Third-party agent user identity — accept uct_ consent tokens OR duct_delegated JWTs.
|
|
139
174
|
* Configure DUCT_AUTH_URL in server env (never NEXT_PUBLIC_* / VITE_*).
|
|
175
|
+
*
|
|
176
|
+
* Identity-only: { token } is enough to resolve user_ref.
|
|
177
|
+
* When Duct proxies the call it also sends X-Duct-Shell-ID + X-Duct-Action-ID —
|
|
178
|
+
* pass those as target_shell / required_action for policy-bound verification.
|
|
179
|
+
*
|
|
180
|
+
* When a uct_ token is present, verify returns user_ref — an opaque handle YOU assigned
|
|
181
|
+
* at identity-resolution time (a Duct-facing alias; not necessarily a storage primary key).
|
|
182
|
+
* Map it to the live user on your server. Do NOT store PII in the token itself.
|
|
140
183
|
*/
|
|
141
184
|
import { verifyDuctToken } from "@duct-sdk/sdk/server";
|
|
142
185
|
|
|
143
186
|
const DUCT_AUTH_URL = process.env.DUCT_AUTH_URL ?? "http://localhost:3001";
|
|
144
187
|
|
|
145
|
-
|
|
188
|
+
interface ConsentVerifyResult {
|
|
189
|
+
user_ref?: string;
|
|
190
|
+
allowed_actions?: string[];
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function verifyConsentToken(
|
|
194
|
+
token: string,
|
|
195
|
+
opts?: { targetShell?: string; requiredAction?: string },
|
|
196
|
+
): Promise<ConsentVerifyResult | null> {
|
|
197
|
+
const body: Record<string, string> = { token };
|
|
198
|
+
if (opts?.targetShell && opts?.requiredAction) {
|
|
199
|
+
body.target_shell = opts.targetShell;
|
|
200
|
+
body.required_action = opts.requiredAction;
|
|
201
|
+
}
|
|
146
202
|
const res = await fetch(\`\${DUCT_AUTH_URL}/v1/verify/consent-token\`, {
|
|
147
203
|
method: "POST",
|
|
148
204
|
headers: { "Content-Type": "application/json" },
|
|
149
|
-
body: JSON.stringify(
|
|
205
|
+
body: JSON.stringify(body),
|
|
150
206
|
});
|
|
151
207
|
if (!res.ok) return null;
|
|
152
|
-
const
|
|
153
|
-
|
|
208
|
+
const parsed = (await res.json()) as { valid?: boolean; user_ref?: string; allowed_actions?: string[] };
|
|
209
|
+
if (!parsed.valid) return null;
|
|
210
|
+
return { user_ref: parsed.user_ref, allowed_actions: parsed.allowed_actions };
|
|
154
211
|
}
|
|
155
212
|
|
|
156
|
-
export async function resolveAgentAwareUser(
|
|
213
|
+
export async function resolveAgentAwareUser(
|
|
214
|
+
request: Request,
|
|
215
|
+
): Promise<{ userRef?: string; session?: Record<string, unknown> } | null> {
|
|
157
216
|
const authHeader = request.headers.get("authorization");
|
|
158
217
|
if (!authHeader?.startsWith("Bearer ")) return null;
|
|
159
218
|
|
|
160
219
|
const token = authHeader.slice(7);
|
|
161
220
|
if (token.startsWith("uct_")) {
|
|
162
|
-
|
|
221
|
+
const result = await verifyConsentToken(token, {
|
|
222
|
+
targetShell: request.headers.get("x-duct-shell-id") ?? undefined,
|
|
223
|
+
requiredAction: request.headers.get("x-duct-action-id") ?? undefined,
|
|
224
|
+
});
|
|
225
|
+
if (!result) return null;
|
|
226
|
+
// Map user_ref to the live user with your server-side lookup.
|
|
227
|
+
return { userRef: result.user_ref };
|
|
163
228
|
}
|
|
164
229
|
|
|
165
230
|
const secretKey = process.env.DUCT_SECRET_KEY!;
|
|
166
231
|
const shellId = process.env.DUCT_SHELL_ID ?? process.env.NEXT_PUBLIC_DUCT_SHELL_ID!;
|
|
167
232
|
const delegated = await verifyDuctToken(token, { secretKey, expectedShellId: shellId });
|
|
168
|
-
return delegated.valid ? delegated.payload.session : null;
|
|
233
|
+
return delegated.valid ? { session: delegated.payload.session as Record<string, unknown> } : null;
|
|
169
234
|
}
|
|
170
235
|
`;
|
|
171
236
|
}
|
|
@@ -213,11 +278,20 @@ export function buildWiringPlan(outputPaths, framework, authDetection, thirdPart
|
|
|
213
278
|
if (thirdPartyAgentMode === "duct-consent") {
|
|
214
279
|
plan.uctSnippetPath = ".duct/snippets/uct-consent-auth.ts";
|
|
215
280
|
plan.uctSnippet = generateUctVerificationSnippet(framework);
|
|
281
|
+
plan.consentCallbackSnippetPath = ".duct/snippets/duct-consent-callback.ts";
|
|
282
|
+
plan.consentCallbackSnippet = generateConsentCallbackSnippet(framework);
|
|
216
283
|
items.push({
|
|
217
284
|
path: middlewareTarget,
|
|
218
285
|
action: "modify",
|
|
219
286
|
summary: "Verify uct_ consent tokens for third-party agent /message calls",
|
|
220
287
|
});
|
|
288
|
+
items.push({
|
|
289
|
+
path: framework.name === "next-app" || framework.name === "next-pages"
|
|
290
|
+
? "app/api/duct/callback/route.ts"
|
|
291
|
+
: "routes/duct/callback.ts",
|
|
292
|
+
action: "create",
|
|
293
|
+
summary: "Consent callback — receives uct_ + user_ref after human approval, stores for agent",
|
|
294
|
+
});
|
|
221
295
|
}
|
|
222
296
|
if (thirdPartyAgentMode === "oauth") {
|
|
223
297
|
items.push({
|
|
@@ -228,6 +302,96 @@ export function buildWiringPlan(outputPaths, framework, authDetection, thirdPart
|
|
|
228
302
|
}
|
|
229
303
|
return plan;
|
|
230
304
|
}
|
|
305
|
+
/**
|
|
306
|
+
* Scaffold for the consent callback route your app must expose when using
|
|
307
|
+
* the duct-consent third-party agent mode.
|
|
308
|
+
*
|
|
309
|
+
* This route receives the redirect from Duct after a user approves an agent
|
|
310
|
+
* consent request. It stores the uct_ token and user_ref so the agent can
|
|
311
|
+
* retrieve them for subsequent calls.
|
|
312
|
+
*
|
|
313
|
+
* Replace the TODO sections with your own DB / queue / webhook logic.
|
|
314
|
+
*/
|
|
315
|
+
export function generateConsentCallbackSnippet(framework) {
|
|
316
|
+
const isNextJs = framework.name === "next-app" ||
|
|
317
|
+
framework.name === "next-pages";
|
|
318
|
+
if (isNextJs) {
|
|
319
|
+
return `// app/api/duct/callback/route.ts
|
|
320
|
+
// Receives the redirect from Duct after a user approves an agent consent request.
|
|
321
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
322
|
+
|
|
323
|
+
export const dynamic = "force-dynamic";
|
|
324
|
+
|
|
325
|
+
export async function GET(request: NextRequest) {
|
|
326
|
+
const { searchParams } = new URL(request.url);
|
|
327
|
+
|
|
328
|
+
const userConsentToken = searchParams.get("user_consent_token");
|
|
329
|
+
const userRef = searchParams.get("user_ref"); // opaque id you supplied at /consent/request
|
|
330
|
+
const error = searchParams.get("error");
|
|
331
|
+
|
|
332
|
+
if (error) {
|
|
333
|
+
// User denied — redirect to a graceful error page
|
|
334
|
+
return NextResponse.redirect(new URL("/agent-access-denied", request.url));
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
if (!userConsentToken) {
|
|
338
|
+
return NextResponse.json({ error: "missing_token" }, { status: 400 });
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// TODO: store { userConsentToken, userRef } so the agent can retrieve it.
|
|
342
|
+
// Options:
|
|
343
|
+
// • Push to a webhook/queue your agent is listening on
|
|
344
|
+
// • Write to DB: INSERT INTO agent_grants (user_ref, uct, granted_at) VALUES (...)
|
|
345
|
+
// • Cache in Redis with a short TTL for the agent to poll
|
|
346
|
+
//
|
|
347
|
+
// Example DB upsert:
|
|
348
|
+
// await db.agentGrants.upsert({
|
|
349
|
+
// where: { userRef },
|
|
350
|
+
// update: { uct: userConsentToken, grantedAt: new Date() },
|
|
351
|
+
// create: { userRef, uct: userConsentToken, grantedAt: new Date() },
|
|
352
|
+
// });
|
|
353
|
+
|
|
354
|
+
// Redirect the user to a confirmation page
|
|
355
|
+
return NextResponse.redirect(new URL("/agent-connected", request.url));
|
|
356
|
+
}
|
|
357
|
+
`;
|
|
358
|
+
}
|
|
359
|
+
return `// routes/duct/callback.ts (Express)
|
|
360
|
+
// Receives the redirect from Duct after a user approves an agent consent request.
|
|
361
|
+
import { Router, Request, Response } from "express";
|
|
362
|
+
|
|
363
|
+
const router = Router();
|
|
364
|
+
|
|
365
|
+
router.get("/", async (req: Request, res: Response) => {
|
|
366
|
+
const { user_consent_token: userConsentToken, user_ref: userRef, error } = req.query as Record<string, string>;
|
|
367
|
+
|
|
368
|
+
if (error) {
|
|
369
|
+
// User denied — redirect to a graceful error page
|
|
370
|
+
return res.redirect("/agent-access-denied");
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (!userConsentToken) {
|
|
374
|
+
return res.status(400).json({ error: "missing_token" });
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// TODO: store { userConsentToken, userRef } so the agent can retrieve it.
|
|
378
|
+
// Options:
|
|
379
|
+
// • Push to a webhook/queue your agent is listening on
|
|
380
|
+
// • Write to DB: INSERT INTO agent_grants (user_ref, uct, granted_at) VALUES (...)
|
|
381
|
+
// • Cache in Redis with a short TTL for the agent to poll
|
|
382
|
+
//
|
|
383
|
+
// Example DB insert:
|
|
384
|
+
// await db.query(
|
|
385
|
+
// "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()",
|
|
386
|
+
// [userRef, userConsentToken],
|
|
387
|
+
// );
|
|
388
|
+
|
|
389
|
+
return res.redirect("/agent-connected");
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
export default router;
|
|
393
|
+
`;
|
|
394
|
+
}
|
|
231
395
|
export function sideEffectActionsApproved(config) {
|
|
232
396
|
return (config.actions ?? []).some((action) => action.sideEffects);
|
|
233
397
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { describe, it } from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
3
|
import * as path from "path";
|
|
4
|
-
import { buildWiringPlan, generateVerifyDuctTokenMiddlewareSnippet, sideEffectActionsApproved, } from "./wiring-snippets.js";
|
|
4
|
+
import { buildWiringPlan, generateVerifyDuctTokenMiddlewareSnippet, generateUctVerificationSnippet, sideEffectActionsApproved, } from "./wiring-snippets.js";
|
|
5
5
|
const framework = {
|
|
6
6
|
name: "next-app",
|
|
7
7
|
version: "14.0.0",
|
|
@@ -58,6 +58,20 @@ describe("wiring snippets", () => {
|
|
|
58
58
|
}, "server/middleware/auth.ts");
|
|
59
59
|
assert.match(snippet, /express/);
|
|
60
60
|
assert.match(snippet, /ductDelegatedAuth/);
|
|
61
|
+
assert.match(snippet, /expectedShellId/);
|
|
62
|
+
});
|
|
63
|
+
it("ductOrConsentAuth rejects unrecognized delegated tokens", () => {
|
|
64
|
+
const snippet = generateUctVerificationSnippet({
|
|
65
|
+
name: "vite-react",
|
|
66
|
+
version: "5.0.0",
|
|
67
|
+
hasAppRouter: false,
|
|
68
|
+
hasPagesRouter: false,
|
|
69
|
+
packageManager: "npm",
|
|
70
|
+
srcDir: "src",
|
|
71
|
+
});
|
|
72
|
+
assert.match(snippet, /ductOrConsentAuth/);
|
|
73
|
+
assert.match(snippet, /expectedShellId/);
|
|
74
|
+
assert.doesNotMatch(snippet, /Fall through to ductDelegatedAuth[\s\S]*return next\(\)/);
|
|
61
75
|
});
|
|
62
76
|
it("sideEffectActionsApproved detects side-effect actions", () => {
|
|
63
77
|
assert.equal(sideEffectActionsApproved({ actions: [{ sideEffects: true }] }), true);
|