@duct-sdk/sdk 0.5.2 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog — @duct-sdk/sdk
2
2
 
3
+ ## [0.5.3] — 2026-07-17
4
+
5
+ ### Security
6
+ - **Consent callback scaffold (v2)** — `duct init` consent-callback routes receive `duct_consent_code` in the redirect (90s TTL) and exchange it server-to-server via `POST /v1/consent/redeem` with shell credentials. Long-lived consent tokens are never placed in browser URLs or query strings.
7
+
8
+ ### Changed
9
+ - Generated consent callback snippets (Next.js App Router + Express) updated for the authorization-code delivery flow; store redeemed tokens server-side for agent retrieval.
10
+
3
11
  ## [0.5.2] — 2026-07-12
4
12
 
5
13
  ### Added
package/README.md CHANGED
@@ -1,55 +1,91 @@
1
+ <p align="center">
2
+ <img src="./assets/duct-wordmark.svg" alt="DUCT" width="420" />
3
+ </p>
4
+
1
5
  # @duct-sdk/sdk
2
6
 
3
7
  **Let agents use your product safely.**
4
8
 
5
- The Duct SDK scans your codebase, generates a manifest, and provides embed components so humans and agents can call your existing APIs through one permissioned surface.
9
+ [npm version](https://www.npmjs.com/package/@duct-sdk/sdk)
10
+ [Node](https://www.npmjs.com/package/@duct-sdk/sdk)
11
+
12
+ The official Duct SDK and CLI. Scan your codebase, declare a manifest, push it to Duct, and embed a permissioned chat shell — so humans and AI agents call your **existing APIs** through one audited surface.
13
+
6
14
 
7
- - **Humans** — chat or use an embedded shell; Duct runs actions or hands off via signed deeplinks
8
- - **Agents** — structured, permissioned API access from the same manifest — no scraping, no screen automation
15
+ | Audience | What you get |
16
+ | ------------- | ----------------------------------------------------------------------------------------------- |
17
+ | **Humans** | Embedded chat shell, structured results, signed deeplink handoff into your app |
18
+ | **Agents** | Permissioned API access from the same manifest — no scraping or screen automation |
19
+ | **Operators** | Shell credentials, action tiers, and usage from the [Duct dashboard](https://ductai.vercel.app) |
9
20
 
10
- Credentials and shell provisioning are managed by the Duct dashboard.
11
21
 
12
22
  ---
13
23
 
14
- ## What integration looks like
15
24
 
16
- Duct does not replace your API or rewrite your product. You wire four things in your codebase, and Duct does the rest:
17
25
 
18
- | What you add | Where |
19
- |---|---|
20
- | Token minting endpoint | `POST /api/duct/token` — one server route |
21
- | Auth middleware fallback | `verifyDuctToken` added to your existing Bearer-token check |
22
- | Deeplink receiver | `POST /api/duct/receive` — verifies signed nav tokens |
23
- | Widget embed | `<DuctShell>` once in your root layout |
26
+ ## Documentation
27
+
28
+
29
+ | Resource | Description |
30
+ | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
31
+ | [Developer docs](https://ductai.vercel.app/docs) | Quickstart, CLI, frameworks, agents, threat model |
32
+ | [AI integration prompt](https://ductai.vercel.app/docs/integration-prompt) | Full `DUCT_CONFIG_PROMPT.md` — copy into Cursor, Claude Code, Codex, or any agentic IDE |
33
+ | [TOKEN_SPEC.md](./TOKEN_SPEC.md) | Token prefixes, claims, TTLs, and cross-language verify snippets |
34
+ | [CHANGELOG.md](./CHANGELOG.md) | Release notes |
24
35
 
25
- The manifest (`duct.config.ts`) declares which routes, actions, and deeplinks exist. `duct push` uploads it to Duct. Your API stays unchanged.
26
36
 
27
37
  ---
28
38
 
29
- ## Quickstart
30
39
 
31
- **1. Create your shell** in the Duct dashboard and copy your API key.
32
40
 
33
- **2. Authenticate the CLI:**
41
+ ## AI-assisted integration
42
+
43
+ Duct ships a single integration prompt (`DUCT_CONFIG_PROMPT.md`) for greenfield setup or auditing an existing `duct.config.ts`. Paste it into your coding assistant with the product repo open; the agent generates or reviews manifest fields, the four wiring points, env vars, and a ship checklist.
44
+
45
+ **Get the prompt:** [ductai.vercel.app/docs/integration-prompt](https://ductai.vercel.app/docs/integration-prompt) — expandable, copy-ready, with URLs resolved for your environment.
46
+
47
+ Typical flow:
48
+
49
+ 1. Run `duct init` or `duct init --manual` for a first draft.
50
+ 2. Paste `DUCT_CONFIG_PROMPT.md` from the docs page to audit wiring and permissions.
51
+ 3. `duct push`, embed `<DuctShell>`, smoke-test in the dashboard playground.
52
+
53
+ ---
54
+
55
+
56
+
57
+ ## Install
34
58
 
35
59
  ```bash
36
- npx @duct-sdk/sdk login
60
+ npm install @duct-sdk/sdk
61
+ # or run without installing:
62
+ npx @duct-sdk/sdk <command>
37
63
  ```
38
64
 
39
- > **Node 22+ note:** if the CLI exits with an ERR_REQUIRE_ESM error, run with
40
- > `node --experimental-require-module $(npx --no which duct) <command>` or install the
41
- > package globally with `npm i -g @duct-sdk/sdk` and use `duct <command>`.
65
+ Global CLI (optional): `npm i -g @duct-sdk/sdk` → `duct <command>`.
66
+
67
+ > **Node 22+:** if the CLI exits with `ERR_REQUIRE_ESM`, use
68
+ > `node --experimental-require-module $(npx --no which duct) <command>` or install globally.
69
+
70
+ ---
71
+
42
72
 
43
- **3. Generate a manifest:**
73
+
74
+ ## Quickstart
75
+
76
+ **1. Create a shell** in the Duct dashboard and copy your API key.
77
+
78
+ **2. Log in:**
44
79
 
45
80
  ```bash
46
- # Recommended first run — instant editable template, no LLM required
47
- npx @duct-sdk/sdk init --manual
81
+ npx @duct-sdk/sdk login
82
+ ```
48
83
 
49
- # AI-assisted scan of your codebase once your API surface is stable
50
- npx @duct-sdk/sdk init
84
+ **3. Generate a manifest:**
51
85
 
52
- # From an existing OpenAPI / Swagger spec
86
+ ```bash
87
+ npx @duct-sdk/sdk init --manual # instant template (recommended first run)
88
+ npx @duct-sdk/sdk init # AI-assisted scan when your API is stable
53
89
  npx @duct-sdk/sdk init --api-spec openapi.yaml
54
90
  ```
55
91
 
@@ -59,10 +95,9 @@ npx @duct-sdk/sdk init --api-spec openapi.yaml
59
95
  npx @duct-sdk/sdk push
60
96
  ```
61
97
 
62
- **5. Embed the shell:**
98
+ **5. Embed** (Next.js App Router example):
63
99
 
64
100
  ```tsx
65
- // Next.js App Router (root layout)
66
101
  import { DuctShell } from '@duct-sdk/sdk/next';
67
102
 
68
103
  export default function RootLayout({ children }) {
@@ -74,12 +109,15 @@ export default function RootLayout({ children }) {
74
109
  shellId={process.env.NEXT_PUBLIC_DUCT_SHELL_ID!}
75
110
  shellHost={process.env.NEXT_PUBLIC_DUCT_SHELL_HOST}
76
111
  onTokenRequest={async () => {
77
- const res = await fetch('/api/duct/token', { method: 'POST', credentials: 'include' });
112
+ const res = await fetch('/api/duct/token', {
113
+ method: 'POST',
114
+ credentials: 'include',
115
+ });
78
116
  return (await res.json()).token ?? '';
79
117
  }}
80
- preset="tall" // "tall" | "square" | "large"
81
- position="bottom-right" // starting corner; bubble + panel are draggable
82
- theme="system" // "system" | "light" | "dark"
118
+ preset="tall"
119
+ position="bottom-right"
120
+ theme="system"
83
121
  />
84
122
  </body>
85
123
  </html>
@@ -87,78 +125,94 @@ export default function RootLayout({ children }) {
87
125
  }
88
126
  ```
89
127
 
128
+
129
+
130
+ ### Four wiring points
131
+
132
+ Duct does not replace your API. You add four integration points in **your** codebase:
133
+
134
+
135
+ | # | What | Where |
136
+ | --- | ----------------- | ----------------------------------------------------------------- |
137
+ | 1 | Token minting | `POST /api/duct/token` → `generateDuctToken` |
138
+ | 2 | API auth | Existing middleware also accepts `verifyDuctToken` delegated JWTs |
139
+ | 3 | Deeplink receiver | `POST /api/duct/receive` → `verifyDeeplinkToken` |
140
+ | 4 | Widget embed | `<DuctShell>` in root layout with `onTokenRequest` |
141
+
142
+
143
+ `duct.config.ts` declares routes, actions, deeplinks, and agent permissions. `duct push` uploads it; your business logic stays unchanged.
144
+
90
145
  ---
91
146
 
92
- ## Import guide — use the right subpath
93
147
 
94
- | Import | Use when |
95
- |---|---|
96
- | `@duct-sdk/sdk/server` | **Any Node.js / Edge backend** — token helpers, config, introspect. No React. Safe in Express, Fastify, Next.js API routes, Remix loaders, SvelteKit hooks. |
97
- | `@duct-sdk/sdk/next` | Next.js App Router frontend (requires React) |
98
- | `@duct-sdk/sdk/react` | Plain React or non-Next frameworks (requires React) |
99
- | `@duct-sdk/sdk/vite` | Vite + Express (requires React) |
100
- | `@duct-sdk/sdk/remix` | Remix (requires React) |
101
- | `@duct-sdk/sdk/sveltekit` | SvelteKit |
102
- | `@duct-sdk/sdk` (root) | Full bundle — only in React SSR frontends where React is already installed. **Crashes plain Express/Fastify backends.** |
148
+
149
+ ## Import guide
150
+
151
+ Use the **subpath** that matches your runtime. The root export pulls React adapters and will crash plain Node servers.
152
+
153
+
154
+ | Import | Use when |
155
+ | ------------------------- | ------------------------------------------------------------------- |
156
+ | `@duct-sdk/sdk/server` | **Any Node / Edge backend** — tokens, config, introspect. No React. |
157
+ | `@duct-sdk/sdk/next` | Next.js App Router (React) |
158
+ | `@duct-sdk/sdk/react` | React without Next |
159
+ | `@duct-sdk/sdk/vite` | Vite + Express (React) |
160
+ | `@duct-sdk/sdk/remix` | Remix (React) |
161
+ | `@duct-sdk/sdk/sveltekit` | SvelteKit |
162
+ | `@duct-sdk/sdk` | React SSR frontends only — **not** Express/Fastify APIs |
163
+
103
164
 
104
165
  ```ts
105
- // ✅ Correct — server route (Express, Next.js API, Remix loader, etc.)
166
+ // Server route (Express, Next.js route handler, Remix loader, …)
106
167
  import { generateDuctToken, verifyDuctToken } from '@duct-sdk/sdk/server';
107
-
108
- // ❌ Wrong — pulls in React adapters, crashes if React is not installed
109
- import { generateDuctToken } from '@duct-sdk/sdk';
110
168
  ```
111
169
 
112
170
  ---
113
171
 
114
- ## CLI reference
115
172
 
116
- | Command | Description |
117
- |---|---|
118
- | `duct login` | Authenticate with your Duct API key |
119
- | `duct init` | AI-assisted scan — generates config + shell files |
120
- | `duct init --manual` | Instant template without LLM (recommended first run) |
121
- | `duct init --update` | Re-scan only files changed since last push |
122
- | `duct init --api-spec <path>` | Generate manifest from OpenAPI / Swagger spec |
123
- | `duct init --no-agents` | Skip AI scan; blank template |
124
- | `duct push` | Push `duct.config.ts` to Duct |
125
- | `duct pull <hash>` | Restore a manifest version from push history |
126
- | `duct promote --from <id> --to <id>` | Copy manifest to another environment shell |
127
- | `duct scan` | Detect drift between live API and manifest |
128
- | `duct checkup` | Check env config and service connectivity |
129
173
 
130
- Install globally to drop the `npx`: `npm i -g @duct-sdk/sdk`.
174
+ ## CLI
175
+
176
+
177
+ | Command | Description |
178
+ | ------------------------------------ | ---------------------------------------- |
179
+ | `duct login` | Authenticate with your Duct API key |
180
+ | `duct init` | AI-assisted scan → config + shell files |
181
+ | `duct init --manual` | Template without LLM |
182
+ | `duct init --update` | Re-scan files changed since last push |
183
+ | `duct init --api-spec <path>` | Manifest from OpenAPI / Swagger |
184
+ | `duct push` | Upload `duct.config.ts` to Duct |
185
+ | `duct pull <hash>` | Restore a manifest version from history |
186
+ | `duct promote --from <id> --to <id>` | Copy manifest between environment shells |
187
+ | `duct scan` | Drift between live API and manifest |
188
+ | `duct checkup` | Env config and service connectivity |
189
+
131
190
 
132
191
  ---
133
192
 
134
- ## Framework support
135
193
 
136
- | Framework | Import | Client env vars |
137
- |---|---|---|
138
- | Next.js (App Router) | `@duct-sdk/sdk/next` | `NEXT_PUBLIC_DUCT_SHELL_ID`, `NEXT_PUBLIC_DUCT_SHELL_HOST` |
139
- | Vite | `@duct-sdk/sdk/vite` | `VITE_DUCT_SHELL_ID`, `VITE_DUCT_SHELL_HOST` |
140
- | Remix | `@duct-sdk/sdk/remix` | `VITE_DUCT_SHELL_ID`, `VITE_DUCT_SHELL_HOST` |
141
- | SvelteKit | `@duct-sdk/sdk/sveltekit` | `PUBLIC_DUCT_SHELL_ID`, `PUBLIC_DUCT_SHELL_HOST` |
142
- | React (generic) | `@duct-sdk/sdk/react` | any |
143
- | Express / Fastify / other Node | `@duct-sdk/sdk/server` | — (server only) |
144
194
 
145
- ### Vite + Express
195
+ ## Frameworks
196
+
197
+
198
+ | Framework | Import | Client env vars |
199
+ | ------------------------ | ------------------------- | ---------------------------------------------------------- |
200
+ | Next.js (App Router) | `@duct-sdk/sdk/next` | `NEXT_PUBLIC_DUCT_SHELL_ID`, `NEXT_PUBLIC_DUCT_SHELL_HOST` |
201
+ | Vite | `@duct-sdk/sdk/vite` | `VITE_DUCT_SHELL_ID`, `VITE_DUCT_SHELL_HOST` |
202
+ | Remix | `@duct-sdk/sdk/remix` | `VITE_DUCT_SHELL_ID`, `VITE_DUCT_SHELL_HOST` |
203
+ | SvelteKit | `@duct-sdk/sdk/sveltekit` | `PUBLIC_DUCT_SHELL_ID`, `PUBLIC_DUCT_SHELL_HOST` |
204
+ | React (generic) | `@duct-sdk/sdk/react` | framework-specific |
205
+ | Express / Fastify / Node | `@duct-sdk/sdk/server` | — (server only) |
146
206
 
147
- Keep environment variables in three files:
148
207
 
149
- ```
150
- /.env → DUCT_SECRET_KEY, DUCT_SHELL_ID (server, never commit)
151
- /backend/.env → same values for the Express process if run separately
152
- /frontend/.env → VITE_DUCT_SHELL_ID, VITE_DUCT_SHELL_HOST (public)
153
- ```
154
208
 
155
- Express token route:
209
+
210
+ ### Vite + Express
156
211
 
157
212
  ```ts
158
213
  import express from 'express';
159
- import { generateDuctToken } from '@duct-sdk/sdk/server'; // ← /server, not root
214
+ import { generateDuctToken, verifyDuctToken } from '@duct-sdk/sdk/server';
160
215
 
161
- const router = express.Router();
162
216
  router.post('/api/duct/token', express.json(), async (req, res) => {
163
217
  if (!req.user) return res.status(401).json({ error: 'unauthenticated' });
164
218
  const { token } = await generateDuctToken({
@@ -171,85 +225,62 @@ router.post('/api/duct/token', express.json(), async (req, res) => {
171
225
  });
172
226
  ```
173
227
 
174
- API auth middleware:
175
-
176
- ```ts
177
- import { verifyDuctToken } from '@duct-sdk/sdk/server';
178
-
179
- app.use(async (req, res, next) => {
180
- const header = req.headers.authorization ?? '';
181
- if (!header.startsWith('Bearer ')) return res.status(401).end();
182
- const raw = header.slice(7);
183
- // Try your own JWT first
184
- const mine = await verifyMyJwt(raw).catch(() => null);
185
- if (mine) { req.user = mine; return next(); }
186
- // Fall back to Duct delegated token
187
- const duct = await verifyDuctToken(raw, {
188
- secretKey: process.env.DUCT_SECRET_KEY!,
189
- expectedShellId: process.env.DUCT_SHELL_ID!,
190
- });
191
- if (duct.valid) { req.user = duct.payload!.session; return next(); }
192
- res.status(401).end();
193
- });
194
- ```
228
+ Keep secrets in server `.env` only (`DUCT_SECRET_KEY`, `DUCT_SHELL_ID`). Client bundles use public `VITE_*` shell ID / host vars.
195
229
 
196
230
  ---
197
231
 
198
- ## Webhook configuration
199
-
200
- Webhook URLs (deeplink callback, event stream) and the signing secret are **not** part of `duct.config.ts` and are **not** pushed via `duct push`. Configure them in the **Duct dashboard → Shell → Settings → Webhooks**.
201
232
 
202
- Your endpoint receives a POST with an `X-Duct-Signature` HMAC-SHA256 header for verification. Webhooks are optional — the shell, widget, and action flow work without them.
203
-
204
- ---
205
233
 
206
- ## Deeplinks — route inventory first
234
+ ## Deeplinks & replay protection
207
235
 
208
- Before declaring deeplinks, inventory every navigable page in your app:
236
+ Declare deeplinks only for routes you have inventoried in `routes[]`. The receiver must verify signed tokens server-side — never trust raw query params.
209
237
 
210
- 1. List all routes where a user lands with identity-specific state (order ID, document ID, profile slug).
211
- 2. Mark which of those a conversation could meaningfully route to.
212
- 3. Declare only those in `deeplinks[]` with matching `stateFields`.
213
-
214
- A `targetRoute` must match an entry in `routes[]`. The deeplink receiver must verify the signed token server-side before using any state value — never trust raw query params.
215
-
216
- ### JTI replay protection
217
-
218
- Deeplink JWTs include a unique `jti` (JWT ID) claim. Each token is **single-use**: after your receiver verifies it successfully, pass a `replayStore` to `verifyDeeplinkToken` so the same `jti` cannot be accepted again within the TTL window.
238
+ Deeplink JWTs include a `jti` claim. Pass a `replayStore` to `verifyDeeplinkToken` so each token is single-use:
219
239
 
220
240
  ```ts
221
241
  import {
222
242
  verifyDeeplinkToken,
223
243
  createDevReplayStore,
224
244
  RedisReplayStore,
225
- } from "@duct-sdk/sdk/server";
245
+ } from '@duct-sdk/sdk/server';
226
246
 
227
- // Dev / single-instance only:
228
- const replayStore = createDevReplayStore();
229
-
230
- // Production (multi-replica): shared Redis
231
- // const replayStore = new RedisReplayStore(redisClient, "duct:jti:");
247
+ const replayStore = createDevReplayStore(); // dev / single instance
248
+ // const replayStore = new RedisReplayStore(redisClient, 'duct:jti:'); // production
232
249
 
233
250
  const result = await verifyDeeplinkToken(token, {
234
251
  secretKey: process.env.DUCT_SECRET_KEY!,
235
252
  expectedShellId: ductConfig.shellId,
236
253
  replayStore,
237
254
  });
238
-
239
- if (!result.valid && result.error === "Token already used") {
240
- return res.status(409).json({ error: "Token already used" });
241
- }
242
255
  ```
243
256
 
244
- Generated receivers (`duct init`) wire `createDevReplayStore()` by default. Swap in `RedisReplayStore` before production deploy. Tokens minted without `jti` are rejected when a replay store is configured.
257
+ Details: [TOKEN_SPEC.md](./TOKEN_SPEC.md).
258
+
259
+ ---
260
+
261
+
245
262
 
246
- See [TOKEN_SPEC.md](./TOKEN_SPEC.md) for the full token contract and cross-language verify snippets.
263
+ ## Webhooks
264
+
265
+ Webhook URLs and signing secrets are configured in the **dashboard → Shell → Settings → Webhooks**, not in `duct.config.ts`. Your endpoint verifies `X-Duct-Signature` (HMAC-SHA256). Webhooks are optional for chat and actions.
247
266
 
248
267
  ---
249
268
 
269
+
270
+
250
271
  ## Security
251
272
 
252
- - Keep `DUCT_SECRET_KEY` server-side only — never in client bundles or `NEXT_PUBLIC_*` / `VITE_*` vars
253
- - Use least privilege when marking actions `agentAccessible: true`
254
- - `sideEffects: true` on any action that creates, updates, deletes, or charges
273
+ - Keep `DUCT_SECRET_KEY` server-side — never in `NEXT_PUBLIC_*`, `VITE_*`, or client bundles
274
+ - Default mutations to `agentAccessible: false` and `sideEffects: true` where appropriate
255
275
  - Rotate keys in the dashboard if credentials are exposed
276
+ - Review agent-accessible actions before production — use the [integration prompt](https://ductai.vercel.app/docs/integration-prompt) audit checklist
277
+
278
+ ---
279
+
280
+
281
+
282
+ ## Support
283
+
284
+ - Docs: [ductai.vercel.app/docs](https://ductai.vercel.app/docs)
285
+ - npm: [@duct-sdk/sdk](https://www.npmjs.com/package/@duct-sdk/sdk)
286
+
Binary file
@@ -0,0 +1,16 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" role="img" aria-label="DUCT" viewBox="0 0 380 98">
2
+ <text
3
+ fill="#B84A22"
4
+ font-family="ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"
5
+ font-size="13"
6
+ font-weight="700"
7
+ xml:space="preserve"
8
+ >
9
+ <tspan x="0" y="14">██████╗ ██╗ ██╗ ╔██████ ████████╗</tspan>
10
+ <tspan x="0" dy="14">██╔══██╗ ██║ ██║ ╚════╗██ ╚══██╔══╝</tspan>
11
+ <tspan x="0" dy="14">██║ ██║ ██║ ██║ ║██ ██║</tspan>
12
+ <tspan x="0" dy="14">██║ ██║ ██║ ██║ ║██ ██║</tspan>
13
+ <tspan x="0" dy="14">██████╔╝ ╚██████╔╝ ╔██████╝ ██║</tspan>
14
+ <tspan x="0" dy="14">╚═════╝ ╚═════╝ ╚═════╝ ╚═╝</tspan>
15
+ </text>
16
+ </svg>
Binary file
@@ -325,34 +325,43 @@ export const dynamic = "force-dynamic";
325
325
  export async function GET(request: NextRequest) {
326
326
  const { searchParams } = new URL(request.url);
327
327
 
328
- const userConsentToken = searchParams.get("user_consent_token");
329
- const userRef = searchParams.get("user_ref"); // opaque id you supplied at /consent/request
328
+ const consentCode = searchParams.get("duct_consent_code");
330
329
  const error = searchParams.get("error");
331
330
 
332
331
  if (error) {
333
- // User denied — redirect to a graceful error page
334
332
  return NextResponse.redirect(new URL("/agent-access-denied", request.url));
335
333
  }
336
334
 
337
- if (!userConsentToken) {
338
- return NextResponse.json({ error: "missing_token" }, { status: 400 });
335
+ if (!consentCode) {
336
+ return NextResponse.json({ error: "missing_code" }, { status: 400 });
339
337
  }
340
338
 
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));
339
+ const authUrl = process.env.DUCT_AUTH_URL ?? "http://localhost:3001";
340
+ const redeemResp = await fetch(\`\${authUrl}/v1/consent/redeem\`, {
341
+ method: "POST",
342
+ headers: { "Content-Type": "application/json" },
343
+ body: JSON.stringify({
344
+ shellId: process.env.DUCT_SHELL_ID,
345
+ clientSecret: process.env.DUCT_SECRET_KEY,
346
+ code: consentCode,
347
+ }),
348
+ cache: "no-store",
349
+ });
350
+ const redeemData = (await redeemResp.json()) as {
351
+ user_consent_token?: string;
352
+ user_ref?: string;
353
+ error?: string;
354
+ };
355
+
356
+ if (!redeemResp.ok || !redeemData.user_consent_token) {
357
+ return NextResponse.json({ error: redeemData.error ?? "redeem_failed" }, { status: 400 });
358
+ }
359
+
360
+ // TODO: store { userConsentToken: redeemData.user_consent_token, userRef: redeemData.user_ref }
361
+ // server-side so the agent can retrieve it — never keep uct_ in the browser URL.
362
+
363
+ const clean = new URL("/agent-connected", request.url);
364
+ return NextResponse.redirect(clean);
356
365
  }
357
366
  `;
358
367
  }
@@ -363,28 +372,37 @@ import { Router, Request, Response } from "express";
363
372
  const router = Router();
364
373
 
365
374
  router.get("/", async (req: Request, res: Response) => {
366
- const { user_consent_token: userConsentToken, user_ref: userRef, error } = req.query as Record<string, string>;
375
+ const { duct_consent_code: consentCode, error } = req.query as Record<string, string>;
367
376
 
368
377
  if (error) {
369
- // User denied — redirect to a graceful error page
370
378
  return res.redirect("/agent-access-denied");
371
379
  }
372
380
 
373
- if (!userConsentToken) {
374
- return res.status(400).json({ error: "missing_token" });
381
+ if (!consentCode) {
382
+ return res.status(400).json({ error: "missing_code" });
383
+ }
384
+
385
+ const authUrl = process.env.DUCT_AUTH_URL ?? "http://localhost:3001";
386
+ const redeemResp = await fetch(\`\${authUrl}/v1/consent/redeem\`, {
387
+ method: "POST",
388
+ headers: { "Content-Type": "application/json" },
389
+ body: JSON.stringify({
390
+ shellId: process.env.DUCT_SHELL_ID,
391
+ clientSecret: process.env.DUCT_SECRET_KEY,
392
+ code: consentCode,
393
+ }),
394
+ });
395
+ const redeemData = (await redeemResp.json()) as {
396
+ user_consent_token?: string;
397
+ user_ref?: string;
398
+ error?: string;
399
+ };
400
+
401
+ if (!redeemResp.ok || !redeemData.user_consent_token) {
402
+ return res.status(400).json({ error: redeemData.error ?? "redeem_failed" });
375
403
  }
376
404
 
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
- // );
405
+ // TODO: store redeemData.user_consent_token + redeemData.user_ref server-side for the agent.
388
406
 
389
407
  return res.redirect("/agent-connected");
390
408
  });
@@ -3,8 +3,12 @@ export interface ActionDefinitionGrant {
3
3
  actionId: string;
4
4
  definitionHash: string;
5
5
  }
6
- export declare function computeActionDefinitionFingerprint(action: Pick<ActionManifest, "method" | "path" | "sideEffects" | "sensitivityLevel">): string;
7
- export declare function buildActionDefinitionGrants(actionIds: string[], actionsById: Record<string, Pick<ActionManifest, "method" | "path" | "sideEffects" | "sensitivityLevel">>): ActionDefinitionGrant[];
6
+ export declare function computeActionDefinitionFingerprint(action: Pick<ActionManifest, "method" | "path" | "sideEffects" | "sensitivityLevel"> & {
7
+ endpoint?: string;
8
+ }): string;
9
+ export declare function buildActionDefinitionGrants(actionIds: string[], actionsById: Record<string, Pick<ActionManifest, "method" | "path" | "sideEffects" | "sensitivityLevel"> & {
10
+ endpoint?: string;
11
+ }>): ActionDefinitionGrant[];
8
12
  export type ActionRiskTier = "read" | "write" | "delete";
9
13
  export declare function classifyActionRiskTier(action: Pick<ActionManifest, "method" | "sideEffects">): ActionRiskTier;
10
14
  export declare function checkAgentScope(scopes: string[], action: Pick<ActionManifest, "id" | "method" | "path" | "sideEffects" | "sensitivityLevel">, params?: Record<string, unknown>): {
@@ -1,8 +1,11 @@
1
1
  import { createHash } from "node:crypto";
2
2
  export function computeActionDefinitionFingerprint(action) {
3
+ const effectiveTarget = action.endpoint ?? action.path ?? "";
4
+ // Keep canonical key set aligned with server-side action definition fingerprints.
3
5
  const canonical = JSON.stringify({
4
6
  method: (action.method ?? "GET").toUpperCase(),
5
7
  path: action.path ?? "",
8
+ endpoint: effectiveTarget,
6
9
  sideEffects: Boolean(action.sideEffects),
7
10
  sensitivityLevel: action.sensitivityLevel ?? "low",
8
11
  });
@@ -289,8 +289,8 @@ export interface AgentPermissions {
289
289
  validUntil?: string;
290
290
  /**
291
291
  * Explicit action IDs third-party consent (`uct_`) may authorize per request.
292
- * When set, wildcard `['*']` consent is rejected — each grant must list actions from this set.
293
- * Enforced at consent issuance and the Duct gateway. Absent = legacy wildcard allowed.
292
+ * When set, each grant must list actions from this set. Enforced at consent
293
+ * issuance (auth service) and the Duct gateway on invoke.
294
294
  */
295
295
  consentActionScope?: string[];
296
296
  }
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@duct-sdk/sdk",
3
- "version": "0.5.2",
3
+ "version": "0.5.3",
4
4
  "type": "module",
5
- "description": "Duct SDK — A shell (like terminal) that knows when to talk, when to show, and when to hand off.",
5
+ "description": "Duct SDK — manifest, CLI, and embed components for permissioned human and agent access to your product APIs.",
6
+ "homepage": "https://ductai.vercel.app/docs",
6
7
  "main": "dist/index.js",
7
8
  "types": "dist/index.d.ts",
8
9
  "bin": {
@@ -20,7 +21,7 @@
20
21
  "scripts": {
21
22
  "build": "tsc",
22
23
  "dev": "tsc --watch",
23
- "test": "npm run build && node --test dist/core/token.test.js dist/core/invariants.test.js dist/core/receipt.test.js dist/core/config-policy.test.js dist/adapters/react/page-context-guard.test.js dist/cli/config-loader.test.js dist/cli/manifest-diff.test.js dist/cli/generators/shell.test.js 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",
24
+ "test": "npm run build && node --test dist/core/*.test.js dist/adapters/react/*.test.js dist/cli/*.test.js dist/cli/generators/*.test.js dist/cli/processors/*.test.js",
24
25
  "verify:publish": "node scripts/verify-publish.mjs",
25
26
  "prepublishOnly": "npm run build && npm run verify:publish"
26
27
  },
@@ -64,6 +65,7 @@
64
65
  },
65
66
  "files": [
66
67
  "dist",
68
+ "assets",
67
69
  "README.md",
68
70
  "CHANGELOG.md",
69
71
  "TOKEN_SPEC.md"