@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.
Files changed (60) hide show
  1. package/CHANGELOG.md +55 -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 +110 -37
  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.d.ts +14 -0
  26. package/dist/cli/generators/wiring-snippets.js +180 -16
  27. package/dist/cli/generators/wiring-snippets.test.js +15 -1
  28. package/dist/cli/index.js +108 -151
  29. package/dist/cli/init.js +110 -17
  30. package/dist/cli/manifest-diff.d.ts +21 -0
  31. package/dist/cli/manifest-diff.js +158 -0
  32. package/dist/cli/manifest-diff.test.d.ts +1 -0
  33. package/dist/cli/manifest-diff.test.js +104 -0
  34. package/dist/cli/output-paths.d.ts +2 -0
  35. package/dist/cli/output-paths.js +22 -4
  36. package/dist/cli/processors/integration-audit.js +1 -1
  37. package/dist/core/config-policy.test.d.ts +1 -0
  38. package/dist/core/config-policy.test.js +101 -0
  39. package/dist/core/config.d.ts +86 -1
  40. package/dist/core/config.js +120 -2
  41. package/dist/core/invariants.test.d.ts +1 -0
  42. package/dist/core/invariants.test.js +217 -0
  43. package/dist/core/jcs.d.ts +5 -0
  44. package/dist/core/jcs.js +21 -0
  45. package/dist/core/receipt.d.ts +70 -0
  46. package/dist/core/receipt.js +86 -0
  47. package/dist/core/receipt.test.d.ts +1 -0
  48. package/dist/core/receipt.test.js +75 -0
  49. package/dist/core/replay-store.d.ts +51 -0
  50. package/dist/core/replay-store.js +65 -0
  51. package/dist/core/token.d.ts +14 -0
  52. package/dist/core/token.js +50 -18
  53. package/dist/core/token.test.d.ts +1 -0
  54. package/dist/core/token.test.js +66 -0
  55. package/dist/core/types.d.ts +72 -0
  56. package/dist/index.d.ts +6 -4
  57. package/dist/index.js +4 -2
  58. package/dist/server.d.ts +6 -4
  59. package/dist/server.js +4 -2
  60. package/package.json +91 -90
package/CHANGELOG.md CHANGED
@@ -1,7 +1,62 @@
1
1
  # Changelog — @duct-sdk/sdk
2
2
 
3
+ ## [0.5.1] — 2026-07-09
4
+
5
+ ### Changed
6
+ - **`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.
7
+
3
8
  Public release notes for the Duct SDK. Versioning follows [semver](https://semver.org).
4
9
 
10
+ ## [0.5.0] — 2026-07-08
11
+
12
+ ### Added
13
+ - `duct init` framework support: Nuxt, Vue 3, Express, and FastAPI / Python generators; Express + FastAPI detection.
14
+
15
+ ### Fixed
16
+ - Token-route generator emitted `return return …` (uncompilable) when `guestAllowed:false`; fixed across all frameworks.
17
+ - Unknown / unsupported stacks now hard-stop with guidance instead of writing Next.js files.
18
+
19
+
20
+ Public release notes for the Duct SDK. Versioning follows [semver](https://semver.org).
21
+
22
+ ## [0.4.7] — 2026-07-08
23
+
24
+ ### Added
25
+ - **`TOKEN_SPEC.md`** — language-agnostic token verification spec (prefixes, claims, TTLs, HS256 + Ed25519/JWKS paths) with Python, Go, and Ruby verify snippets.
26
+ - **`verifyReceipt()`** — pure crypto-layer outcome receipt verification in `@duct-sdk/sdk/server` (HMAC + optional Ed25519 JWKS/public keys).
27
+ - **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.
28
+ - **Richer manifest policy schema** — `validFrom`/`validUntil`, `approveIf`, `actionLimit` (rate vs count), and `agentPermissions.consentActionScope` with Zod + cross-validation.
29
+
30
+ ### Fixed
31
+ - **`duct pull`** — restored `duct.config.ts` now imports `@duct-sdk/sdk` (was `@duct/sdk`).
32
+
33
+ ### Docs
34
+ - Deeplink receiver docs (README + generated receiver comments) document `jti` replay protection and `RedisReplayStore` for production.
35
+
36
+ ## [0.4.6] — 2026-07-08
37
+
38
+ ### Security
39
+ - **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.
40
+ - **`generateDuctToken` allowlist** — session fields are copied only from `auth.sessionFields` (denylist retained as secondary guard).
41
+ - **`duct push` safety gate** — runs `crossValidateDuctConfig` (hard-fail) and agent-safety checks; warnings require `--yes` to override in CI.
42
+ - **Config loading** — `duct.config.ts` is parsed as static data (no `process` in VM context); runtime references are rejected.
43
+ - **Embed hardening** — generated Vue/Nuxt shells validate `event.origin` and same-origin deeplink URLs; `useDuctPageContext` fails closed without `shellHost`.
44
+ - **Express consent middleware** — `ductOrConsentAuth` rejects unrecognized Bearer tokens instead of calling `next()`; verify snippets document `expectedShellId`.
45
+
46
+ ### Changed
47
+ - **`duct init`** — detects existing generated files and prompts to skip/overwrite instead of clobbering (`--yes` skips existing files).
48
+ - **`duct login`** — documents credential storage, warns that `--token` leaks to shell history, notes Windows NTFS ACL reliance.
49
+
50
+ ## [0.4.5] — 2026-07-05
51
+
52
+ ### Added
53
+ - **Consent callback route scaffold** — `duct init` with `duct-consent` mode now emits a consent callback route (`app/api/duct/callback/route.ts` for Next.js App Router, `routes/duct/callback.ts` for Express) that handles the `?user_consent_token=…&user_ref=…` redirect from Duct, with TODO markers for DB/queue storage.
54
+ - **`consentCallbackSnippet` / `consentCallbackSnippetPath`** on `WiringPlan`.
55
+ - `generateConsentCallbackSnippet(framework)` exported from `wiring-snippets.ts`.
56
+
57
+ ### Changed
58
+ - **`uct-consent-auth.ts` snippet updated** — `verifyUct` / `verifyConsentToken` now surface `user_ref` from `/v1/verify/consent-token`. Express version sets `req.ductUserRef`; Next.js/App Router version returns `{ userRef }` from `resolveAgentAwareUser`. Snippets no longer claim to return a generic `user` object.
59
+
5
60
  ## [0.4.4] — 2026-07-04
6
61
 
7
62
  ### Changed
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
+ });
@@ -5,7 +5,7 @@
5
5
  "use client";
6
6
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
7
7
  import React, { useEffect, useRef, useCallback, useMemo, useState, } from "react";
8
- import { resolveShellDimensions, SHELL_PANEL_VIEWPORT_INSETS, } from "../../core/types.js";
8
+ import { fitShellPanelDimensions, resolveShellDimensions, SHELL_PANEL_VIEWPORT_INSETS, } from "../../core/types.js";
9
9
  /**
10
10
  * Hook that polls the shell status endpoint once on mount.
11
11
  * Use when you need to conditionally render UI based on shell liveness.
@@ -156,18 +156,47 @@ function writeStoredShellLayout(shellId, layout) {
156
156
  }
157
157
  catch { /* ignore quota / private mode */ }
158
158
  }
159
- /** Keep a dragged panel visible inside the viewport. */
159
+ /** Keep a dragged panel fully inside the viewport (drag handle + close stay reachable). */
160
160
  function clampPanel(x, y, width, height) {
161
161
  if (typeof window === "undefined")
162
162
  return { x, y };
163
163
  const margin = 8;
164
- const maxX = window.innerWidth - width - margin;
165
- const maxY = window.innerHeight - height - margin;
164
+ const vw = window.innerWidth;
165
+ const vh = window.innerHeight;
166
+ const maxX = Math.max(margin, vw - width - margin);
167
+ const maxY = Math.max(margin, vh - height - margin);
166
168
  return {
167
- x: Math.min(Math.max(margin, x), Math.max(margin, maxX)),
168
- y: Math.min(Math.max(margin, y), Math.max(margin, maxY)),
169
+ x: Math.min(Math.max(margin, x), maxX),
170
+ y: Math.min(Math.max(margin, y), maxY),
169
171
  };
170
172
  }
173
+ /** Fit panel to the current viewport using the same caps as the panel CSS. */
174
+ function viewportPanelSize(presetDims, fallbackWidth, fallbackHeight) {
175
+ const rawW = typeof presetDims.width === "number" ? presetDims.width : fallbackWidth;
176
+ const rawH = typeof presetDims.height === "number" ? presetDims.height : fallbackHeight;
177
+ if (typeof window === "undefined")
178
+ return { width: rawW, height: rawH };
179
+ return fitShellPanelDimensions(rawW, rawH, window.innerWidth, window.innerHeight);
180
+ }
181
+ /** Bubble-relative anchor converted to clamped absolute top-left (panel always fits on screen). */
182
+ function anchoredPanelPosition(bubblePos, isRight, panelW, panelH) {
183
+ const vw = typeof window !== "undefined" ? window.innerWidth : 1280;
184
+ const vh = typeof window !== "undefined" ? window.innerHeight : 800;
185
+ if (!bubblePos) {
186
+ const x = isRight ? vw - panelW - 16 : 16;
187
+ const y = vh - panelH - 80;
188
+ return clampPanel(x, y, panelW, panelH);
189
+ }
190
+ const openLeft = bubblePos.x > vw / 2;
191
+ const openUp = bubblePos.y > vh / 2;
192
+ const x = openLeft
193
+ ? vw - Math.max(16, vw - (bubblePos.x + BUBBLE_SIZE)) - panelW
194
+ : Math.max(16, bubblePos.x);
195
+ const y = openUp
196
+ ? vh - Math.max(16, vh - bubblePos.y + 12) - panelH
197
+ : Math.max(16, bubblePos.y + BUBBLE_SIZE + 12);
198
+ return clampPanel(x, y, panelW, panelH);
199
+ }
171
200
  /** Coalesce high-frequency pointer moves to one React update per animation frame. */
172
201
  function scheduleRafUpdate(rafRef, pendingRef, pos, commit) {
173
202
  pendingRef.current = pos;
@@ -226,6 +255,8 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
226
255
  const [dynamicPreset, setDynamicPreset] = useState(undefined);
227
256
  // Free-drag bubble position (px from top-left of viewport). null = default corner.
228
257
  const [bubblePos, setBubblePos] = useState(null);
258
+ /** Launcher position — only updated when the bubble is dragged, never by panel drag/open. */
259
+ const bubbleAnchorRef = useRef(null);
229
260
  const [isDragging, setIsDragging] = useState(false);
230
261
  const dragState = useRef(null);
231
262
  // Open panel can also be dragged after launch. null = anchor near bubble/default corner.
@@ -295,6 +326,12 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
295
326
  // Animate close
296
327
  const closePanel = useCallback(() => {
297
328
  setIsAnimating(true);
329
+ // Panel drag must never move the launcher — restore the last bubble drop on close.
330
+ if (bubbleAnchorRef.current) {
331
+ const anchor = clampBubble(bubbleAnchorRef.current.x, bubbleAnchorRef.current.y);
332
+ bubbleAnchorRef.current = anchor;
333
+ setBubblePos(anchor);
334
+ }
298
335
  setTimeout(() => {
299
336
  setOpen(false);
300
337
  setIsAnimating(false);
@@ -451,13 +488,58 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
451
488
  mq.addEventListener("change", handler);
452
489
  return () => mq.removeEventListener("change", handler);
453
490
  }, [theme]);
491
+ // Escape closes the panel when drag handle / bubble are unreachable.
492
+ useEffect(() => {
493
+ if (!panelOpen)
494
+ return;
495
+ const onKey = (e) => {
496
+ if (e.key === "Escape")
497
+ closePanel();
498
+ };
499
+ window.addEventListener("keydown", onKey);
500
+ return () => window.removeEventListener("keydown", onKey);
501
+ }, [panelOpen, closePanel]);
502
+ // Re-clamp positions when the viewport changes so stored coords cannot strand the panel.
503
+ useEffect(() => {
504
+ if (!draggable || typeof window === "undefined")
505
+ return;
506
+ const onResize = () => {
507
+ const dims = resolveShellDimensions({
508
+ preset: dynamicPreset ?? preset,
509
+ width: dynamicWidth ?? panelWidth,
510
+ height: dynamicHeight ?? panelHeight,
511
+ });
512
+ const size = viewportPanelSize(dims, panelWidth, panelHeight);
513
+ setBubblePos((prev) => {
514
+ if (!prev)
515
+ return null;
516
+ const clamped = clampBubble(prev.x, prev.y);
517
+ bubbleAnchorRef.current = clamped;
518
+ return clamped;
519
+ });
520
+ setPanelPos((prev) => {
521
+ if (!prev)
522
+ return null;
523
+ const clamped = clampPanel(prev.x, prev.y, size.width, size.height);
524
+ const layout = { panel: clamped };
525
+ if (bubbleAnchorRef.current)
526
+ layout.bubble = bubbleAnchorRef.current;
527
+ writeStoredShellLayout(shellId, layout);
528
+ return clamped;
529
+ });
530
+ };
531
+ window.addEventListener("resize", onResize);
532
+ return () => window.removeEventListener("resize", onResize);
533
+ }, [shellId, draggable, dynamicPreset, preset, dynamicWidth, panelWidth, dynamicHeight, panelHeight]);
454
534
  // Restore bubble position saved from a prior visit (survives deeplink handoff navigations).
455
535
  useEffect(() => {
456
536
  if (!draggable || typeof window === "undefined")
457
537
  return;
458
538
  const layout = readStoredShellLayout(shellId);
459
539
  if (layout.bubble) {
460
- setBubblePos(clampBubble(layout.bubble.x, layout.bubble.y));
540
+ const pos = clampBubble(layout.bubble.x, layout.bubble.y);
541
+ bubbleAnchorRef.current = pos;
542
+ setBubblePos(pos);
461
543
  }
462
544
  }, [shellId, draggable]);
463
545
  // Restore or re-clamp panel position when dimensions change (e.g. manifest widget preset).
@@ -469,15 +551,14 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
469
551
  width: dynamicWidth ?? panelWidth,
470
552
  height: dynamicHeight ?? panelHeight,
471
553
  });
472
- const w = typeof dims.width === "number" ? dims.width : panelWidth;
473
- const h = typeof dims.height === "number" ? dims.height : panelHeight;
554
+ const size = viewportPanelSize(dims, panelWidth, panelHeight);
474
555
  setPanelPos((prev) => {
475
556
  if (prev)
476
- return clampPanel(prev.x, prev.y, w, h);
557
+ return clampPanel(prev.x, prev.y, size.width, size.height);
477
558
  const stored = readStoredShellLayout(shellId).panel;
478
559
  if (!stored)
479
560
  return null;
480
- return clampPanel(stored.x, stored.y, w, h);
561
+ return clampPanel(stored.x, stored.y, size.width, size.height);
481
562
  });
482
563
  }, [shellId, draggable, dynamicPreset, preset, dynamicWidth, panelWidth, dynamicHeight, panelHeight]);
483
564
  // Launcher bubble: pointer stays default until the user actually drags (4px threshold).
@@ -498,9 +579,8 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
498
579
  moved: false,
499
580
  };
500
581
  dragState.current = st;
501
- const initial = clampBubble(rect.left, rect.top);
502
- setBubblePos((prev) => prev ?? initial);
503
- bubbleDragPending.current = initial;
582
+ const startBubblePos = bubbleAnchorRef.current ?? bubblePos ?? clampBubble(rect.left, rect.top);
583
+ bubbleDragPending.current = startBubblePos;
504
584
  const commitBubblePos = (pos) => setBubblePos(pos);
505
585
  const onMove = (ev) => {
506
586
  if (!dragState.current)
@@ -526,10 +606,13 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
526
606
  setIsDragging(false);
527
607
  const finalPos = cancelRafUpdate(bubbleDragRaf, bubbleDragPending, commitBubblePos);
528
608
  if (st.moved) {
529
- const pos = finalPos ?? bubbleDragPending.current;
609
+ const pos = finalPos ?? bubbleDragPending.current ?? startBubblePos;
530
610
  if (pos) {
531
- setBubblePos(pos);
532
- writeStoredShellLayout(shellId, { bubble: pos });
611
+ const anchor = clampBubble(pos.x, pos.y);
612
+ bubbleAnchorRef.current = anchor;
613
+ setBubblePos(anchor);
614
+ // Bubble moved — drop saved panel so it re-anchors near the new launcher spot.
615
+ writeStoredShellLayout(shellId, { bubble: anchor });
533
616
  }
534
617
  setPanelPos(null);
535
618
  }
@@ -577,8 +660,10 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
577
660
  const finalPos = cancelRafUpdate(panelDragRaf, panelDragPending, commitPanelPos);
578
661
  if (finalPos) {
579
662
  setPanelPos(finalPos);
580
- const layout = readStoredShellLayout(shellId);
581
- writeStoredShellLayout(shellId, { ...layout, panel: finalPos });
663
+ const layout = { panel: finalPos };
664
+ if (bubbleAnchorRef.current)
665
+ layout.bubble = bubbleAnchorRef.current;
666
+ writeStoredShellLayout(shellId, layout);
582
667
  }
583
668
  };
584
669
  window.addEventListener("pointermove", onMove);
@@ -601,6 +686,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
601
686
  width: dynamicWidth ?? panelWidth,
602
687
  height: dynamicHeight ?? panelHeight,
603
688
  });
689
+ const panelSize = viewportPanelSize(presetDims, panelWidth, panelHeight);
604
690
  const widthVal = typeof presetDims.width === "number" ? `${presetDims.width}px` : presetDims.width;
605
691
  const heightVal = typeof presetDims.height === "number" ? `${presetDims.height}px` : presetDims.height;
606
692
  const panelWidthInset = SHELL_PANEL_VIEWPORT_INSETS.width;
@@ -611,26 +697,13 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
611
697
  const bubbleStyle = dragged
612
698
  ? { position: "fixed", left: `${bubblePos.x}px`, top: `${bubblePos.y}px` }
613
699
  : { position: "fixed", bottom: "16px", [isRight ? "right" : "left"]: "16px" };
614
- const panelAnchor = (() => {
615
- if (!dragged) {
616
- return { bottom: "80px", [isRight ? "right" : "left"]: "16px" };
617
- }
618
- // Open the panel toward whichever side has the most room.
619
- const vw = typeof window !== "undefined" ? window.innerWidth : 1280;
620
- const vh = typeof window !== "undefined" ? window.innerHeight : 800;
621
- const openLeft = bubblePos.x > vw / 2;
622
- const openUp = bubblePos.y > vh / 2;
623
- const horiz = openLeft
624
- ? { right: `${Math.max(16, vw - (bubblePos.x + BUBBLE_SIZE))}px` }
625
- : { left: `${Math.max(16, bubblePos.x)}px` };
626
- const vert = openUp
627
- ? { bottom: `${Math.max(16, vh - bubblePos.y + 12)}px` }
628
- : { top: `${Math.max(16, bubblePos.y + BUBBLE_SIZE + 12)}px` };
629
- return { ...horiz, ...vert };
630
- })();
700
+ const effectivePanelPos = panelPos
701
+ ? clampPanel(panelPos.x, panelPos.y, panelSize.width, panelSize.height)
702
+ : anchoredPanelPosition(bubblePos, isRight, panelSize.width, panelSize.height);
631
703
  const panelStyle = {
632
704
  position: "fixed",
633
- ...(panelPos ? { left: `${panelPos.x}px`, top: `${panelPos.y}px` } : panelAnchor),
705
+ left: `${effectivePanelPos.x}px`,
706
+ top: `${effectivePanelPos.y}px`,
634
707
  width: `min(${widthVal}, calc(100vw - ${panelWidthInset}px))`,
635
708
  height: `min(${heightVal}, calc(100dvh - ${panelHeightInset}px))`,
636
709
  zIndex: 9998,
@@ -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
  }