@duct-sdk/sdk 0.4.5 → 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.
Files changed (58) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +36 -1
  3. package/TOKEN_SPEC.md +237 -0
  4. package/dist/adapters/react/page-context-guard.d.ts +7 -0
  5. package/dist/adapters/react/page-context-guard.js +26 -0
  6. package/dist/adapters/react/page-context-guard.test.d.ts +1 -0
  7. package/dist/adapters/react/page-context-guard.test.js +15 -0
  8. package/dist/adapters/react/shell.js +1 -23
  9. package/dist/adapters/react/use-page-context.d.ts +1 -1
  10. package/dist/adapters/react/use-page-context.js +6 -16
  11. package/dist/cli/agents/reviewer-agent.d.ts +3 -1
  12. package/dist/cli/agents/reviewer-agent.js +29 -21
  13. package/dist/cli/config-loader.d.ts +15 -0
  14. package/dist/cli/config-loader.js +187 -0
  15. package/dist/cli/config-loader.test.d.ts +1 -0
  16. package/dist/cli/config-loader.test.js +63 -0
  17. package/dist/cli/detectors/framework.d.ts +1 -1
  18. package/dist/cli/detectors/framework.js +40 -0
  19. package/dist/cli/generators/receiver.js +206 -76
  20. package/dist/cli/generators/shell.js +50 -4
  21. package/dist/cli/generators/shell.test.d.ts +1 -0
  22. package/dist/cli/generators/shell.test.js +73 -0
  23. package/dist/cli/generators/token-route.d.ts +1 -0
  24. package/dist/cli/generators/token-route.js +108 -5
  25. package/dist/cli/generators/wiring-snippets.js +59 -19
  26. package/dist/cli/generators/wiring-snippets.test.js +15 -1
  27. package/dist/cli/index.js +108 -151
  28. package/dist/cli/init.js +110 -17
  29. package/dist/cli/manifest-diff.d.ts +21 -0
  30. package/dist/cli/manifest-diff.js +158 -0
  31. package/dist/cli/manifest-diff.test.d.ts +1 -0
  32. package/dist/cli/manifest-diff.test.js +104 -0
  33. package/dist/cli/output-paths.d.ts +2 -0
  34. package/dist/cli/output-paths.js +22 -4
  35. package/dist/core/config-policy.test.d.ts +1 -0
  36. package/dist/core/config-policy.test.js +101 -0
  37. package/dist/core/config.d.ts +86 -1
  38. package/dist/core/config.js +120 -2
  39. package/dist/core/invariants.test.d.ts +1 -0
  40. package/dist/core/invariants.test.js +217 -0
  41. package/dist/core/jcs.d.ts +5 -0
  42. package/dist/core/jcs.js +21 -0
  43. package/dist/core/receipt.d.ts +70 -0
  44. package/dist/core/receipt.js +86 -0
  45. package/dist/core/receipt.test.d.ts +1 -0
  46. package/dist/core/receipt.test.js +75 -0
  47. package/dist/core/replay-store.d.ts +51 -0
  48. package/dist/core/replay-store.js +65 -0
  49. package/dist/core/token.d.ts +14 -0
  50. package/dist/core/token.js +50 -18
  51. package/dist/core/token.test.d.ts +1 -0
  52. package/dist/core/token.test.js +66 -0
  53. package/dist/core/types.d.ts +72 -0
  54. package/dist/index.d.ts +6 -4
  55. package/dist/index.js +4 -2
  56. package/dist/server.d.ts +6 -4
  57. package/dist/server.js +4 -2
  58. 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, 'return json({ error: "Unauthorized" }, { status: 401 })')}
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, 'return json({ error: "Unauthorized" }, { status: 401 })')}
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, 'return res.status(401).json({ error: "Unauthorized" })')}
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, 'return res.status(401).json({ error: "Unauthorized" })')}
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() });
@@ -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.session;
63
+ (req as Request & { user?: Record<string, unknown> }).user = result.payload!.session;
64
64
  return next();
65
65
  }
66
66
  `;
@@ -101,6 +101,10 @@ export function generateUctVerificationSnippet(framework) {
101
101
  * Third-party agent user identity — verify Duct consent tokens (uct_).
102
102
  * POST \${DUCT_AUTH_URL}/v1/verify/consent-token
103
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
+ *
104
108
  * On success, req.ductUserRef contains the opaque company user identifier you
105
109
  * supplied at consent-request time. Resolve mutable data (email, roles) from
106
110
  * YOUR own DB using that id — never trust the JWT payload for live attributes.
@@ -115,16 +119,24 @@ interface UctVerifyResult {
115
119
  allowedActions?: string[];
116
120
  }
117
121
 
118
- async function verifyUct(token: string): Promise<UctVerifyResult | null> {
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
+ }
119
131
  const res = await fetch(\`\${DUCT_AUTH_URL}/v1/verify/consent-token\`, {
120
132
  method: "POST",
121
133
  headers: { "Content-Type": "application/json" },
122
- body: JSON.stringify({ token }),
134
+ body: JSON.stringify(body),
123
135
  });
124
136
  if (!res.ok) return 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 };
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 };
128
140
  }
129
141
 
130
142
  export async function ductOrConsentAuth(req: Request, res: Response, next: NextFunction) {
@@ -133,13 +145,26 @@ export async function ductOrConsentAuth(req: Request, res: Response, next: NextF
133
145
 
134
146
  const token = authHeader.slice(7);
135
147
  if (token.startsWith("uct_")) {
136
- const result = await verifyUct(token);
137
- if (!result) return res.status(401).json({ error: "Invalid consent token" });
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" });
138
152
  (req as Request & { ductUserRef?: string }).ductUserRef = result.userRef;
139
153
  return next();
140
154
  }
141
155
 
142
- // Fall through to ductDelegatedAuth (verifyDuctToken) for human shell tokens
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;
143
168
  return next();
144
169
  }
145
170
  `;
@@ -148,9 +173,13 @@ export async function ductOrConsentAuth(req: Request, res: Response, next: NextF
148
173
  * Third-party agent user identity — accept uct_ consent tokens OR duct_delegated JWTs.
149
174
  * Configure DUCT_AUTH_URL in server env (never NEXT_PUBLIC_* / VITE_*).
150
175
  *
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.
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.
154
183
  */
155
184
  import { verifyDuctToken } from "@duct-sdk/sdk/server";
156
185
 
@@ -161,16 +190,24 @@ interface ConsentVerifyResult {
161
190
  allowed_actions?: string[];
162
191
  }
163
192
 
164
- async function verifyConsentToken(token: string): Promise<ConsentVerifyResult | null> {
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
+ }
165
202
  const res = await fetch(\`\${DUCT_AUTH_URL}/v1/verify/consent-token\`, {
166
203
  method: "POST",
167
204
  headers: { "Content-Type": "application/json" },
168
- body: JSON.stringify({ token }),
205
+ body: JSON.stringify(body),
169
206
  });
170
207
  if (!res.ok) return 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 };
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 };
174
211
  }
175
212
 
176
213
  export async function resolveAgentAwareUser(
@@ -181,9 +218,12 @@ export async function resolveAgentAwareUser(
181
218
 
182
219
  const token = authHeader.slice(7);
183
220
  if (token.startsWith("uct_")) {
184
- const result = await verifyConsentToken(token);
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
+ });
185
225
  if (!result) return null;
186
- // Resolve the live user from your DB using result.user_ref
226
+ // Map user_ref to the live user with your server-side lookup.
187
227
  return { userRef: result.user_ref };
188
228
  }
189
229
 
@@ -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);