@duct-sdk/sdk 0.4.5 → 0.5.2

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 +50 -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 +18 -26
  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
package/CHANGELOG.md CHANGED
@@ -1,7 +1,57 @@
1
1
  # Changelog — @duct-sdk/sdk
2
2
 
3
+ ## [0.5.2] — 2026-07-12
4
+
5
+ ### Added
6
+ - **`DUCT_TOKEN_PUSH`** — `DuctShell` pushes a fresh `onTokenRequest` token when the iframe is ready and whenever the panel opens, so host login reconnects the chat without a hard refresh.
7
+
8
+ ## [0.5.1] — 2026-07-09
9
+
10
+ ### Changed
11
+ - **`DuctShell`** — removed the host-panel close control. The embedded shell host renders the panel close and posts `DUCT_CLOSE`; the SDK still listens and collapses the panel.
12
+
13
+ Public release notes for the Duct SDK. Versioning follows [semver](https://semver.org).
14
+
15
+ ## [0.5.0] — 2026-07-08
16
+
17
+ ### Added
18
+ - `duct init` framework support: Nuxt, Vue 3, Express, and FastAPI / Python generators; Express + FastAPI detection.
19
+
20
+ ### Fixed
21
+ - Token-route generator emitted `return return …` (uncompilable) when `guestAllowed:false`; fixed across all frameworks.
22
+ - Unknown / unsupported stacks now hard-stop with guidance instead of writing Next.js files.
23
+
24
+
3
25
  Public release notes for the Duct SDK. Versioning follows [semver](https://semver.org).
4
26
 
27
+ ## [0.4.7] — 2026-07-08
28
+
29
+ ### Added
30
+ - **`TOKEN_SPEC.md`** — language-agnostic token verification spec (prefixes, claims, TTLs, HS256 + Ed25519/JWKS paths) with Python, Go, and Ruby verify snippets.
31
+ - **`verifyReceipt()`** — pure crypto-layer outcome receipt verification in `@duct-sdk/sdk/server` (HMAC + optional Ed25519 JWKS/public keys).
32
+ - **Manifest privilege diff at push** — `duct push` fetches the live manifest, prints privilege-increasing deltas, and blocks unless `--yes`. `duct push --dry-run` prints the diff and exits without pushing.
33
+ - **Richer manifest policy schema** — `validFrom`/`validUntil`, `approveIf`, `actionLimit` (rate vs count), and `agentPermissions.consentActionScope` with Zod + cross-validation.
34
+
35
+ ### Fixed
36
+ - **`duct pull`** — restored `duct.config.ts` now imports `@duct-sdk/sdk` (was `@duct/sdk`).
37
+
38
+ ### Docs
39
+ - Deeplink receiver docs (README + generated receiver comments) document `jti` replay protection and `RedisReplayStore` for production.
40
+
41
+ ## [0.4.6] — 2026-07-08
42
+
43
+ ### Security
44
+ - **Deeplink replay protection** — `DeeplinkTokenPayload` now includes `jti`; `verifyDeeplinkToken` accepts an optional `replayStore` and ships `createDevReplayStore` / `RedisReplayStore`. Generated receivers wire the dev store; Remix/Express/SvelteKit templates now include replay logic.
45
+ - **`generateDuctToken` allowlist** — session fields are copied only from `auth.sessionFields` (denylist retained as secondary guard).
46
+ - **`duct push` safety gate** — runs `crossValidateDuctConfig` (hard-fail) and agent-safety checks; warnings require `--yes` to override in CI.
47
+ - **Config loading** — `duct.config.ts` is parsed as static data (no `process` in VM context); runtime references are rejected.
48
+ - **Embed hardening** — generated Vue/Nuxt shells validate `event.origin` and same-origin deeplink URLs; `useDuctPageContext` fails closed without `shellHost`.
49
+ - **Express consent middleware** — `ductOrConsentAuth` rejects unrecognized Bearer tokens instead of calling `next()`; verify snippets document `expectedShellId`.
50
+
51
+ ### Changed
52
+ - **`duct init`** — detects existing generated files and prompts to skip/overwrite instead of clobbering (`--yes` skips existing files).
53
+ - **`duct login`** — documents credential storage, warns that `--token` leaks to shell history, notes Windows NTFS ACL reliance.
54
+
5
55
  ## [0.4.5] — 2026-07-05
6
56
 
7
57
  ### Added
package/README.md CHANGED
@@ -184,7 +184,10 @@ app.use(async (req, res, next) => {
184
184
  const mine = await verifyMyJwt(raw).catch(() => null);
185
185
  if (mine) { req.user = mine; return next(); }
186
186
  // Fall back to Duct delegated token
187
- const duct = await verifyDuctToken(raw, { secretKey: process.env.DUCT_SECRET_KEY! });
187
+ const duct = await verifyDuctToken(raw, {
188
+ secretKey: process.env.DUCT_SECRET_KEY!,
189
+ expectedShellId: process.env.DUCT_SHELL_ID!,
190
+ });
188
191
  if (duct.valid) { req.user = duct.payload!.session; return next(); }
189
192
  res.status(401).end();
190
193
  });
@@ -210,6 +213,38 @@ Before declaring deeplinks, inventory every navigable page in your app:
210
213
 
211
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.
212
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.
219
+
220
+ ```ts
221
+ import {
222
+ verifyDeeplinkToken,
223
+ createDevReplayStore,
224
+ RedisReplayStore,
225
+ } from "@duct-sdk/sdk/server";
226
+
227
+ // Dev / single-instance only:
228
+ const replayStore = createDevReplayStore();
229
+
230
+ // Production (multi-replica): shared Redis
231
+ // const replayStore = new RedisReplayStore(redisClient, "duct:jti:");
232
+
233
+ const result = await verifyDeeplinkToken(token, {
234
+ secretKey: process.env.DUCT_SECRET_KEY!,
235
+ expectedShellId: ductConfig.shellId,
236
+ replayStore,
237
+ });
238
+
239
+ if (!result.valid && result.error === "Token already used") {
240
+ return res.status(409).json({ error: "Token already used" });
241
+ }
242
+ ```
243
+
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.
245
+
246
+ See [TOKEN_SPEC.md](./TOKEN_SPEC.md) for the full token contract and cross-language verify snippets.
247
+
213
248
  ---
214
249
 
215
250
  ## Security
package/TOKEN_SPEC.md ADDED
@@ -0,0 +1,237 @@
1
+ # Duct Token Specification
2
+
3
+ Language-agnostic contract for verifying Duct tokens in any backend. This document is the source of truth for integrators who do not use the TypeScript SDK.
4
+
5
+ > **Production recommendation:** use **Ed25519 / JWKS** for delegated tokens, deeplinks, and outcome receipts where offline verification matters. **HS256 with a shared `DUCT_SECRET_KEY`** remains supported for local development and migration — never ship the symmetric secret to third-party verifiers.
6
+
7
+ ---
8
+
9
+ ## Token prefixes
10
+
11
+ | Prefix | Transport | Purpose |
12
+ |--------|-----------|---------|
13
+ | `at_` | `Authorization: Bearer at_…` | Agent access token — identifies a registered third-party agent shell |
14
+ | `uct_` | `X-Duct-User-Consent: uct_…` | User consent token — scoped human approval for agent side-effects |
15
+ | `dt_` | `Authorization: Bearer dt_…` | Delegation token — short-lived cross-shell delegated identity (single-use `jti`) |
16
+ | `rcpt_` | Audit / API body | Outcome receipt ID — references a signed gateway receipt (not a JWT) |
17
+ | *(none)* | Query `?token=` or `Bearer` | Deeplink JWT — handoff from shell to your receiver |
18
+
19
+ Plain delegated user tokens (`duct_delegated` JWT type) have **no prefix** — they are standard HS256 JWTs minted by your app's token route.
20
+
21
+ ---
22
+
23
+ ## Algorithms
24
+
25
+ ### Symmetric (local dev / migration)
26
+
27
+ | Token kind | Algorithm | Secret | Header `alg` |
28
+ |------------|-----------|--------|--------------|
29
+ | Delegated user JWT | HS256 | `DUCT_SECRET_KEY` (≥32 chars recommended) | `HS256` |
30
+ | Deeplink JWT | HS256 | `DUCT_SECRET_KEY` | `HS256` |
31
+
32
+ Pin `algorithms: ['HS256']` (or library equivalent). Reject `none` and unexpected algs.
33
+
34
+ ### Asymmetric (production — recommended)
35
+
36
+ | Token kind | Algorithm | Public keys | `kid` header |
37
+ |------------|-----------|-------------|--------------|
38
+ | Delegated / deeplink JWT | EdDSA (Ed25519) | `GET /v1/keys` JWKS on the Duct gateway | per-key `kid` |
39
+ | Outcome receipt | Ed25519 over canonical JSON body | `GET /v1/keys/receipts` JWKS | `kid` on receipt |
40
+
41
+ Fetch JWKS periodically; cache keys by `kid`. Fall back to gateway verify endpoints when JWKS is empty (HMAC-only mode).
42
+
43
+ ---
44
+
45
+ ## Claims
46
+
47
+ ### Delegated user JWT (`duct_delegated`)
48
+
49
+ Minted by your token route via `generateDuctToken()`.
50
+
51
+ | Claim | Required | Description |
52
+ |-------|----------|-------------|
53
+ | `type` | yes | Must be `"duct_delegated"` |
54
+ | `sub` | yes | User ID |
55
+ | `iss` | yes | Shell ID (`shell_…`) |
56
+ | `iat` / `exp` | yes | Unix seconds |
57
+ | `session` | yes | Allowlisted scalar session fields |
58
+ | `allowedActions` | no | Explicit action ID grant list |
59
+
60
+ **Default TTL:** `auth.tokenExpirySeconds` in manifest (default **60s**). Examples often use 300s.
61
+
62
+ **Verify:** `iss === expectedShellId`, `exp` in future, `type === duct_delegated`, signature valid.
63
+
64
+ ### Deeplink JWT
65
+
66
+ | Claim | Required | Description |
67
+ |-------|----------|-------------|
68
+ | `deeplink_id` | yes | Target deeplink from manifest |
69
+ | `iss` / `aud` | yes | Both must equal shell ID |
70
+ | `sub` | no | User subject when authenticated |
71
+ | `iat` / `exp` | yes | Unix seconds |
72
+ | `jti` | yes (when replay store used) | Single-use replay protection |
73
+ | `state` | yes | Object — pre-fill fields for target route |
74
+
75
+ **Default TTL:** per-deeplink `expirySeconds` (default **300s**).
76
+
77
+ **Replay:** after signature verification, reject if `jti` was seen before (Redis recommended in production).
78
+
79
+ ### Agent access (`at_`)
80
+
81
+ Opaque platform-issued token. Verify via `POST /v1/verify/agent-access-token` (auth service) — not a local JWT.
82
+
83
+ ### User consent (`uct_`)
84
+
85
+ Opaque consent grant. Verify via `POST /v1/verify/consent-token`. Payload includes `allowed_actions` array; wildcard `['*']` is only valid when manifest does **not** set `agentPermissions.consentActionScope`.
86
+
87
+ ### Delegation (`dt_`)
88
+
89
+ Short-lived cross-shell JWT. **Default TTL: 60s.** Single-use per `jti`. Verify via auth service delegation endpoints.
90
+
91
+ ---
92
+
93
+ ## Outcome receipts (`rcpt_` / signed body)
94
+
95
+ Receipts are **not JWTs**. Structure:
96
+
97
+ ```json
98
+ {
99
+ "claim_type": "duct:action:v1",
100
+ "issued_at": "2026-07-01T00:00:00.000Z",
101
+ "shell_id": "shell_acme_prod",
102
+ "action_id": "refund_order",
103
+ "caller_type": "agent",
104
+ "decision": "permit",
105
+ "reason": "allowed",
106
+ "permission_source": "manifest",
107
+ "capture_mode": "gateway_observed",
108
+ "scope_of_claim": { "asserts": [], "does_not_assert": [] },
109
+ "receipt_id": "<sha256-prefix of canonical body>",
110
+ "signature": "<hex HMAC or base64 Ed25519>",
111
+ "kid": "duct-gateway-hs256-v1 | duct-ed25519-…"
112
+ }
113
+ ```
114
+
115
+ **Canonicalization:** JSON with sorted object keys at every level (see `canonicalizeJson` in SDK).
116
+
117
+ **Verification steps:**
118
+
119
+ 1. Strip `receipt_id`, `signature`, `kid`; canonicalize remaining body.
120
+ 2. `receipt_id` must equal first 32 hex chars of `sha256(canonical)`.
121
+ 3. If `kid === duct-gateway-hs256-v1`: HMAC-SHA256 hex verify with `RECEIPT_SIGNING_KEY` (gateway-only).
122
+ 4. Else: Ed25519 verify canonical bytes against JWKS key matching `kid`.
123
+
124
+ TypeScript helper: `verifyReceipt()` from `@duct-sdk/sdk/server`.
125
+
126
+ Context checks (replay, delegation revoked, manifest stale) require `POST /v1/receipts/verify`.
127
+
128
+ ---
129
+
130
+ ## Verify snippets
131
+
132
+ ### Python (PyJWT) — delegated HS256 JWT
133
+
134
+ ```python
135
+ import jwt
136
+
137
+ def verify_delegated(token: str, secret: str, shell_id: str) -> dict:
138
+ payload = jwt.decode(
139
+ token,
140
+ secret,
141
+ algorithms=["HS256"],
142
+ issuer=shell_id,
143
+ options={"require": ["exp", "iat", "sub", "iss"]},
144
+ )
145
+ if payload.get("type") != "duct_delegated":
146
+ raise jwt.InvalidTokenError("wrong type")
147
+ return payload
148
+ ```
149
+
150
+ ### Python — deeplink with jti (replay is app-side)
151
+
152
+ ```python
153
+ payload = jwt.decode(
154
+ token,
155
+ secret,
156
+ algorithms=["HS256"],
157
+ issuer=shell_id,
158
+ audience=shell_id,
159
+ )
160
+ assert payload.get("deeplink_id")
161
+ jti = payload.get("jti")
162
+ # reject if redis.exists(f"duct:jti:{jti}")
163
+ ```
164
+
165
+ ### Go (golang-jwt)
166
+
167
+ ```go
168
+ import "github.com/golang-jwt/jwt/v5"
169
+
170
+ func verifyDelegated(tokenString, secret, shellID string) (jwt.MapClaims, error) {
171
+ tok, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
172
+ if t.Method.Alg() != jwt.SigningMethodHS256.Alg() {
173
+ return nil, jwt.ErrTokenUnverifiable
174
+ }
175
+ return []byte(secret), nil
176
+ }, jwt.WithIssuer(shellID))
177
+ if err != nil || !tok.Valid {
178
+ return nil, err
179
+ }
180
+ claims := tok.Claims.(jwt.MapClaims)
181
+ if claims["type"] != "duct_delegated" {
182
+ return nil, jwt.ErrTokenInvalidClaims
183
+ }
184
+ return claims, nil
185
+ }
186
+ ```
187
+
188
+ ### Ruby (jwt gem)
189
+
190
+ ```ruby
191
+ require "jwt"
192
+
193
+ def verify_delegated(token, secret, shell_id)
194
+ payload, = JWT.decode(
195
+ token,
196
+ secret,
197
+ true,
198
+ { algorithm: "HS256", iss: shell_id, verify_iss: true }
199
+ )
200
+ raise JWT::DecodeError, "wrong type" unless payload["type"] == "duct_delegated"
201
+ payload
202
+ end
203
+ ```
204
+
205
+ ### Ed25519 deeplink (production)
206
+
207
+ Use your JWT library's JWKS loader against `GET https://<gateway-host>/v1/keys`, pin `EdDSA`, and verify `iss`/`aud`/`deeplink_id`/`jti` as above.
208
+
209
+ ---
210
+
211
+ ## SDK helpers
212
+
213
+ | Function | Package | Notes |
214
+ |----------|---------|-------|
215
+ | `verifyDuctToken` | `@duct-sdk/sdk/server` | HS256 delegated JWT |
216
+ | `verifyDeeplinkToken` | `@duct-sdk/sdk/server` | HS256 + optional `replayStore` |
217
+ | `verifyReceipt` | `@duct-sdk/sdk/server` | HMAC or Ed25519 via `hmacSecret` / `jwks` / `publicKeys` |
218
+
219
+ ---
220
+
221
+ ## TTL summary
222
+
223
+ | Token | Default TTL | Config key |
224
+ |-------|-------------|------------|
225
+ | Delegated user JWT | 60s | `auth.tokenExpirySeconds` |
226
+ | Deeplink JWT | 300s | `deeplinks[].expirySeconds` |
227
+ | Delegation `dt_` | 60s | Platform default |
228
+ | Consent `uct_` | Per grant | Set at consent approval |
229
+ | Agent `at_` | Per registration | Dashboard / auth service |
230
+
231
+ ---
232
+
233
+ ## Related docs
234
+
235
+ - Manifest policy fields: `src/core/types.ts` (`validFrom`, `validUntil`, `approveIf`, `actionLimit`, `consentActionScope`)
236
+ - Receiver codegen: `duct init` → `verifyDeeplinkToken` + `createDevReplayStore()`
237
+ - Gateway verify: `POST /v1/receipts/verify`, `POST /v1/verify/consent-token`
@@ -0,0 +1,7 @@
1
+ /** Resolve shell host URL to an origin for postMessage validation. */
2
+ export declare function resolveShellOrigin(shellHost: string): string | null;
3
+ /**
4
+ * Returns true when a DUCT_REQUEST_CONTEXT message may be answered.
5
+ * Fails closed when shellHost is missing or invalid.
6
+ */
7
+ export declare function shouldHandlePageContextRequest(shellHost: string | undefined, eventOrigin: string): boolean;
@@ -0,0 +1,26 @@
1
+ // ============================================================
2
+ // @duct-sdk/sdk — useDuctPageContext origin guard helpers
3
+ // ============================================================
4
+ /** Resolve shell host URL to an origin for postMessage validation. */
5
+ export function resolveShellOrigin(shellHost) {
6
+ try {
7
+ return new URL(shellHost).origin;
8
+ }
9
+ catch {
10
+ return null;
11
+ }
12
+ }
13
+ /**
14
+ * Returns true when a DUCT_REQUEST_CONTEXT message may be answered.
15
+ * Fails closed when shellHost is missing or invalid.
16
+ */
17
+ export function shouldHandlePageContextRequest(shellHost, eventOrigin) {
18
+ if (!shellHost) {
19
+ return false;
20
+ }
21
+ const expectedOrigin = resolveShellOrigin(shellHost);
22
+ if (!expectedOrigin) {
23
+ return false;
24
+ }
25
+ return eventOrigin === expectedOrigin;
26
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,15 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { shouldHandlePageContextRequest } from "./page-context-guard.js";
4
+ describe("shouldHandlePageContextRequest", () => {
5
+ it("refuses foreign origins when shellHost is configured", () => {
6
+ assert.equal(shouldHandlePageContextRequest("http://localhost:3000", "https://evil.example"), false);
7
+ });
8
+ it("allows the shell origin", () => {
9
+ assert.equal(shouldHandlePageContextRequest("http://localhost:3000", "http://localhost:3000"), true);
10
+ });
11
+ it("fails closed without shellHost", () => {
12
+ assert.equal(shouldHandlePageContextRequest(undefined, "http://localhost:3000"), false);
13
+ assert.equal(shouldHandlePageContextRequest(undefined, "https://evil.example"), false);
14
+ });
15
+ });
@@ -116,28 +116,6 @@ function ShellDragHandle({ onPointerDown, isDragging, isDark, label = "Drag to m
116
116
  : "0 8px 24px rgba(12,11,9,0.12)",
117
117
  }, children: label }))] }));
118
118
  }
119
- /** Always-visible close control — panel chrome is outside the iframe. */
120
- function ShellCloseButton({ onClose, isDark, }) {
121
- return (_jsx("button", { type: "button", "aria-label": "Close chat", onClick: onClose, style: {
122
- position: "absolute",
123
- top: 6,
124
- right: 8,
125
- zIndex: 3,
126
- width: 28,
127
- height: 28,
128
- display: "flex",
129
- alignItems: "center",
130
- justifyContent: "center",
131
- border: "none",
132
- borderRadius: 8,
133
- cursor: "pointer",
134
- padding: 0,
135
- fontSize: 18,
136
- lineHeight: 1,
137
- color: isDark ? "#9C9790" : "#635F59",
138
- backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(12,11,9,0.05)",
139
- }, children: "\u00D7" }));
140
- }
141
119
  function shellLayoutStorageKey(shellId) {
142
120
  return `duct-shell-pos:${shellId}`;
143
121
  }
@@ -333,18 +311,31 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
333
311
  const postToShell = useCallback((message) => {
334
312
  iframeRef.current?.contentWindow?.postMessage(message, shellOrigin);
335
313
  }, [shellOrigin]);
314
+ /** Push a fresh host session token into the iframe (no round-trip request). */
315
+ const pushTokenToShell = useCallback(async () => {
316
+ if (!onTokenRequest)
317
+ return;
318
+ try {
319
+ const token = await onTokenRequest(shellId);
320
+ postToShell({ type: "DUCT_TOKEN_PUSH", token: token ?? "" });
321
+ }
322
+ catch {
323
+ // Host mint failed — shell retries on the next user message.
324
+ }
325
+ }, [onTokenRequest, shellId, postToShell]);
336
326
  // Toggle open state
337
327
  const setOpen = useCallback((next) => {
338
328
  if (!controlled)
339
329
  setIsOpen(next);
340
330
  onOpenChange?.(next);
341
331
  }, [controlled, onOpenChange]);
342
- // Animate open
332
+ // Animate open — also reconnect session token so login does not need a hard refresh.
343
333
  const openPanel = useCallback(() => {
344
334
  setIsAnimating(true);
345
335
  setOpen(true);
346
336
  requestAnimationFrame(() => requestAnimationFrame(() => setIsAnimating(false)));
347
- }, [setOpen]);
337
+ void pushTokenToShell();
338
+ }, [setOpen, pushTokenToShell]);
348
339
  // Animate close
349
340
  const closePanel = useCallback(() => {
350
341
  setIsAnimating(true);
@@ -389,6 +380,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
389
380
  if (userContext && Object.keys(userContext).length > 0) {
390
381
  postToShell({ type: "DUCT_USER_CONTEXT", context: userContext });
391
382
  }
383
+ void pushTokenToShell();
392
384
  break;
393
385
  }
394
386
  case "DUCT_REQUEST_TOKEN": {
@@ -462,7 +454,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
462
454
  break;
463
455
  }
464
456
  }
465
- }, [shellOrigin, isAllowedDeeplinkUrl, userContext, onTokenRequest, onPageContext, postToShell, onNavigate, openPanel, closePanel]);
457
+ }, [shellOrigin, isAllowedDeeplinkUrl, userContext, onTokenRequest, onPageContext, postToShell, onNavigate, openPanel, closePanel, pushTokenToShell]);
466
458
  useEffect(() => {
467
459
  window.addEventListener("message", handleMessage);
468
460
  return () => window.removeEventListener("message", handleMessage);
@@ -786,7 +778,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
786
778
  e.currentTarget.style.transform = "scale(1.07)";
787
779
  }, onMouseLeave: (e) => {
788
780
  e.currentTarget.style.transform = "scale(1)";
789
- }, children: bubbleIcon })), _jsxs("div", { ref: panelRef, style: panelStyle, "data-duct-shell": shellId, children: [draggable && panelOpen && (_jsx(ShellDragHandle, { onPointerDown: onPanelPointerDown, isDragging: isPanelDragging, isDark: isDarkChrome, label: "Drag to move" })), panelOpen && (_jsx(ShellCloseButton, { onClose: closePanel, isDark: isDarkChrome })), _jsx("iframe", { ref: iframeRef, src: shellUrl, title: "Duct Shell", sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", allow: "clipboard-write", referrerPolicy: "no-referrer-when-downgrade", style: {
781
+ }, children: bubbleIcon })), _jsxs("div", { ref: panelRef, style: panelStyle, "data-duct-shell": shellId, children: [draggable && panelOpen && (_jsx(ShellDragHandle, { onPointerDown: onPanelPointerDown, isDragging: isPanelDragging, isDark: isDarkChrome, label: "Drag to move" })), _jsx("iframe", { ref: iframeRef, src: shellUrl, title: "Duct Shell", sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", allow: "clipboard-write", referrerPolicy: "no-referrer-when-downgrade", style: {
790
782
  width: "100%",
791
783
  height: "100%",
792
784
  border: "none",
@@ -4,7 +4,7 @@ export interface UseDuctPageContextOptions {
4
4
  * The Duct shell host URL (e.g. "http://localhost:3000" in local dev).
5
5
  * When provided, the hook validates event.origin against this value — only the
6
6
  * Duct iframe can request page context, blocking arbitrary cross-origin access.
7
- * When omitted, the hook accepts requests from any origin (useful in dev/test).
7
+ * Required in production; omitting shellHost refuses all context responses.
8
8
  */
9
9
  shellHost?: string;
10
10
  }
@@ -20,6 +20,7 @@
20
20
  // ============================================================
21
21
  "use client";
22
22
  import { useEffect, useRef } from "react";
23
+ import { shouldHandlePageContextRequest } from "./page-context-guard.js";
23
24
  /**
24
25
  * useDuctPageContext — company-side hook for the Page Context Protocol.
25
26
  *
@@ -46,31 +47,20 @@ export function useDuctPageContext(resolver, options = {}) {
46
47
  resolverRef.current = resolver;
47
48
  const shellHostRef = useRef(options.shellHost);
48
49
  shellHostRef.current = options.shellHost;
49
- // Warn once in non-production when shellHost is omitted — any cross-origin frame
50
- // could then request the company's page context.
50
+ // Fail closed in development when shellHost is omitted.
51
51
  useEffect(() => {
52
52
  if (!options.shellHost && process.env.NODE_ENV !== "production") {
53
- console.error("[duct] useDuctPageContext: shellHost is not configured. " +
54
- "Any cross-origin iframe can request your page context. " +
53
+ throw new Error("[duct] useDuctPageContext: shellHost is required. " +
55
54
  "Pass shellHost (e.g. process.env.NEXT_PUBLIC_DUCT_SHELL_HOST) to restrict " +
56
55
  "requests to the Duct shell only.");
57
56
  }
58
57
  // eslint-disable-next-line react-hooks/exhaustive-deps
59
- }, []); // warn once on mount
58
+ }, []);
60
59
  useEffect(() => {
61
60
  function handleMessage(event) {
62
- // Origin guard: only allow the configured shell host
63
61
  const shellHost = shellHostRef.current;
64
- if (shellHost) {
65
- let expectedOrigin;
66
- try {
67
- expectedOrigin = new URL(shellHost).origin;
68
- }
69
- catch {
70
- return; // invalid shellHost — fail closed
71
- }
72
- if (event.origin !== expectedOrigin)
73
- return;
62
+ if (!shouldHandlePageContextRequest(shellHost, event.origin)) {
63
+ return;
74
64
  }
75
65
  if (typeof event.data !== "object" ||
76
66
  event.data === null ||
@@ -1,10 +1,12 @@
1
- import type { RouteManifest, ActionManifest, AuthSchema, DeeplinkDefinition, ReviewResult } from "../../core/types.js";
1
+ import type { RouteManifest, ActionManifest, AuthSchema, DeeplinkDefinition, ReviewResult, ReviewIssue } from "../../core/types.js";
2
2
  export interface ReviewAgentInput {
3
3
  routes: RouteManifest[];
4
4
  actions: ActionManifest[];
5
5
  auth: AuthSchema;
6
6
  deeplinks: DeeplinkDefinition[];
7
7
  }
8
+ /** Agent-safety checks used by `duct push` (no LLM). */
9
+ export declare function runAgentSafetyChecks(input: ReviewAgentInput): ReviewIssue[];
8
10
  /**
9
11
  * Run the Reviewer Agent to validate and score the pipeline output.
10
12
  */
@@ -31,10 +31,39 @@ Single ReviewResult object:
31
31
  // ----------------------------------------------------------------
32
32
  // Rule-based pre-checks
33
33
  // ----------------------------------------------------------------
34
+ /** Agent-safety checks used by `duct push` (no LLM). */
35
+ export function runAgentSafetyChecks(input) {
36
+ const issues = [];
37
+ const { actions } = input;
38
+ for (let i = 0; i < actions.length; i++) {
39
+ const action = actions[i];
40
+ if (action.agentAccessible &&
41
+ (action.sensitivityLevel === "high" || action.sensitivityLevel === "critical")) {
42
+ issues.push({
43
+ code: "HIGH_SENSITIVITY_AGENT_ACCESSIBLE",
44
+ severity: "error",
45
+ message: `Action "${action.id}" is agent-accessible but has sensitivity level "${action.sensitivityLevel}"`,
46
+ path: `actions[${i}].agentAccessible`,
47
+ suggestion: "Only mark agent-accessible for low/medium sensitivity actions, or require explicit user consent",
48
+ });
49
+ }
50
+ if (action.agentAccessible && action.sideEffects && !action.rateLimit) {
51
+ issues.push({
52
+ code: "AGENT_SIDE_EFFECT_NO_RATE_LIMIT",
53
+ severity: "warning",
54
+ message: `Agent-accessible action "${action.id}" has side effects but no rate limit`,
55
+ path: `actions[${i}].rateLimit`,
56
+ suggestion: "Add a rateLimit (requests/minute) to prevent agent abuse of side-effect actions",
57
+ });
58
+ }
59
+ }
60
+ return issues;
61
+ }
34
62
  async function runStaticChecks(input) {
35
63
  const issues = [];
36
64
  const { routes, actions, auth, deeplinks } = input;
37
65
  const seenActionEndpoints = new Set();
66
+ issues.push(...runAgentSafetyChecks(input));
38
67
  // Routes checks
39
68
  for (let i = 0; i < routes.length; i++) {
40
69
  const route = routes[i];
@@ -95,27 +124,6 @@ async function runStaticChecks(input) {
95
124
  suggestion: "Add a clear description of what this action does",
96
125
  });
97
126
  }
98
- // Warn if high sensitivity actions are marked agent-accessible
99
- if (action.agentAccessible &&
100
- (action.sensitivityLevel === "high" || action.sensitivityLevel === "critical")) {
101
- issues.push({
102
- code: "HIGH_SENSITIVITY_AGENT_ACCESSIBLE",
103
- severity: "error",
104
- message: `Action "${action.id}" is agent-accessible but has sensitivity level "${action.sensitivityLevel}"`,
105
- path: `actions[${i}].agentAccessible`,
106
- suggestion: "Only mark agent-accessible for low/medium sensitivity actions, or require explicit user consent",
107
- });
108
- }
109
- // Warn if side-effect actions are agent-accessible without rate limits
110
- if (action.agentAccessible && action.sideEffects && !action.rateLimit) {
111
- issues.push({
112
- code: "AGENT_SIDE_EFFECT_NO_RATE_LIMIT",
113
- severity: "warning",
114
- message: `Agent-accessible action "${action.id}" has side effects but no rate limit`,
115
- path: `actions[${i}].rateLimit`,
116
- suggestion: "Add a rateLimit (requests/minute) to prevent agent abuse of side-effect actions",
117
- });
118
- }
119
127
  }
120
128
  // Auth checks
121
129
  if (auth.strategy === "unknown") {
@@ -0,0 +1,15 @@
1
+ export declare class ConfigRuntimeReferenceError extends Error {
2
+ constructor();
3
+ }
4
+ export declare function configSourceHasRuntimeReferences(source: string): boolean;
5
+ export declare function extractConfigObjectLiteral(source: string): string | null;
6
+ /**
7
+ * Parse `defineDuctConfig({...})` as a JSON-safe object literal.
8
+ * Rejects configs that reference runtime values; does not expose `process`.
9
+ */
10
+ export declare function loadConfigFromSource(configPath: string): Promise<Record<string, unknown> | null>;
11
+ /**
12
+ * Load duct.config.ts / .js without executing untrusted TypeScript source.
13
+ * Prefer AST extraction for `.ts`; fall back to compiled JS siblings only.
14
+ */
15
+ export declare function loadDuctConfig(configPath: string): Promise<Record<string, unknown>>;