@duct-sdk/sdk 0.5.13 → 0.6.0

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 (160) hide show
  1. package/CHANGELOG.md +385 -344
  2. package/README.md +418 -264
  3. package/TOKEN_SPEC.md +243 -243
  4. package/dist/cli/add.d.ts +7 -0
  5. package/dist/cli/add.js +152 -0
  6. package/dist/cli/agent-prompt.d.ts +3 -0
  7. package/dist/cli/agent-prompt.js +39 -0
  8. package/dist/cli/api-sources.d.ts +26 -0
  9. package/dist/cli/api-sources.js +222 -0
  10. package/dist/cli/cloud.d.ts +133 -0
  11. package/dist/cli/cloud.js +298 -0
  12. package/dist/cli/config-loader.d.ts +14 -0
  13. package/dist/cli/config-loader.js +56 -7
  14. package/dist/cli/device-login.d.ts +17 -0
  15. package/dist/cli/device-login.js +75 -0
  16. package/dist/cli/drift.js +6 -6
  17. package/dist/cli/generators/any-stack.d.ts +3 -0
  18. package/dist/cli/generators/any-stack.js +97 -0
  19. package/dist/cli/generators/config.js +3 -2
  20. package/dist/cli/generators/receiver.js +7 -7
  21. package/dist/cli/generators/shell.js +12 -12
  22. package/dist/cli/generators/token-route.js +245 -245
  23. package/dist/cli/index.js +396 -611
  24. package/dist/cli/mcp-core.d.ts +42 -0
  25. package/dist/cli/mcp-core.js +161 -0
  26. package/dist/cli/mcp-setup.d.ts +4 -0
  27. package/dist/cli/mcp-setup.js +360 -0
  28. package/dist/cli/mcp.d.ts +2 -0
  29. package/dist/cli/mcp.js +457 -0
  30. package/dist/cli/migrate-intershell.js +5 -5
  31. package/dist/cli/policy-defaults.d.ts +37 -0
  32. package/dist/cli/policy-defaults.js +127 -0
  33. package/dist/cli/processors/integration-audit.js +2 -2
  34. package/dist/cli/processors/openapi-parser.d.ts +5 -0
  35. package/dist/cli/processors/openapi-parser.js +8 -3
  36. package/dist/cli/project-loader.d.ts +58 -0
  37. package/dist/cli/project-loader.js +198 -0
  38. package/dist/cli/project-writer.d.ts +23 -0
  39. package/dist/cli/project-writer.js +171 -0
  40. package/dist/cli/push.d.ts +43 -0
  41. package/dist/cli/push.js +276 -0
  42. package/dist/cli/safety-checks.d.ts +9 -0
  43. package/dist/cli/safety-checks.js +29 -0
  44. package/dist/cli/setup.d.ts +20 -0
  45. package/dist/cli/setup.js +349 -0
  46. package/dist/cli/shell-name.d.ts +8 -0
  47. package/dist/cli/shell-name.js +29 -0
  48. package/dist/cli/shells.d.ts +22 -0
  49. package/dist/cli/shells.js +122 -0
  50. package/dist/cli/split.d.ts +7 -0
  51. package/dist/cli/split.js +71 -0
  52. package/dist/cli/sync.d.ts +25 -0
  53. package/dist/cli/sync.js +120 -0
  54. package/dist/cli/test-runner.d.ts +21 -0
  55. package/dist/cli/test-runner.js +281 -0
  56. package/dist/core/compile.d.ts +43 -0
  57. package/dist/core/compile.js +510 -0
  58. package/dist/core/config.d.ts +464 -1
  59. package/dist/core/config.js +14 -14
  60. package/dist/core/login-handoff.d.ts +1 -1
  61. package/dist/core/login-handoff.js +1 -1
  62. package/dist/core/project.d.ts +1798 -0
  63. package/dist/core/project.js +278 -0
  64. package/dist/core/readiness-checks.js +2 -2
  65. package/dist/core/types.d.ts +1 -1
  66. package/dist/index.d.ts +2 -0
  67. package/dist/index.js +1 -0
  68. package/dist/project.d.ts +4 -0
  69. package/dist/project.js +8 -0
  70. package/dist/server.d.ts +2 -0
  71. package/dist/server.js +1 -0
  72. package/package.json +94 -95
  73. package/dist/adapters/react/page-context-guard.test.d.ts +0 -1
  74. package/dist/adapters/react/page-context-guard.test.js +0 -15
  75. package/dist/cli/agents/api-agent.d.ts +0 -22
  76. package/dist/cli/agents/api-agent.js +0 -761
  77. package/dist/cli/agents/auth-agent.d.ts +0 -7
  78. package/dist/cli/agents/auth-agent.js +0 -212
  79. package/dist/cli/agents/deeplink-agent.d.ts +0 -6
  80. package/dist/cli/agents/deeplink-agent.js +0 -285
  81. package/dist/cli/agents/llm.d.ts +0 -33
  82. package/dist/cli/agents/llm.js +0 -309
  83. package/dist/cli/agents/pipeline.d.ts +0 -72
  84. package/dist/cli/agents/pipeline.js +0 -421
  85. package/dist/cli/agents/reviewer-agent.d.ts +0 -13
  86. package/dist/cli/agents/reviewer-agent.js +0 -450
  87. package/dist/cli/agents/route-agent.d.ts +0 -17
  88. package/dist/cli/agents/route-agent.js +0 -383
  89. package/dist/cli/config-loader.test.d.ts +0 -1
  90. package/dist/cli/config-loader.test.js +0 -63
  91. package/dist/cli/detectors/topology.d.ts +0 -46
  92. package/dist/cli/detectors/topology.js +0 -417
  93. package/dist/cli/generators/config.test.d.ts +0 -1
  94. package/dist/cli/generators/config.test.js +0 -222
  95. package/dist/cli/generators/shell.test.d.ts +0 -1
  96. package/dist/cli/generators/shell.test.js +0 -73
  97. package/dist/cli/generators/token-route.test.d.ts +0 -1
  98. package/dist/cli/generators/token-route.test.js +0 -53
  99. package/dist/cli/generators/wiring-snippets.test.d.ts +0 -1
  100. package/dist/cli/generators/wiring-snippets.test.js +0 -80
  101. package/dist/cli/init.d.ts +0 -32
  102. package/dist/cli/init.js +0 -1336
  103. package/dist/cli/manifest-diff.test.d.ts +0 -1
  104. package/dist/cli/manifest-diff.test.js +0 -144
  105. package/dist/cli/processors/curl-parser.test.d.ts +0 -1
  106. package/dist/cli/processors/curl-parser.test.js +0 -24
  107. package/dist/cli/processors/integration-audit.test.d.ts +0 -1
  108. package/dist/cli/processors/integration-audit.test.js +0 -154
  109. package/dist/cli/processors/postprocess.d.ts +0 -22
  110. package/dist/cli/processors/postprocess.js +0 -107
  111. package/dist/cli/processors/prisma-parser.d.ts +0 -35
  112. package/dist/cli/processors/prisma-parser.js +0 -117
  113. package/dist/cli/processors/verify-discovery.d.ts +0 -33
  114. package/dist/cli/processors/verify-discovery.js +0 -193
  115. package/dist/cli/processors/verify-discovery.test.d.ts +0 -1
  116. package/dist/cli/processors/verify-discovery.test.js +0 -153
  117. package/dist/cli/processors/zod-extractor.d.ts +0 -27
  118. package/dist/cli/processors/zod-extractor.js +0 -153
  119. package/dist/cli/prompts/review.d.ts +0 -61
  120. package/dist/cli/prompts/review.js +0 -410
  121. package/dist/cli/selectors/express.d.ts +0 -12
  122. package/dist/cli/selectors/express.js +0 -117
  123. package/dist/cli/selectors/fastapi.d.ts +0 -12
  124. package/dist/cli/selectors/fastapi.js +0 -122
  125. package/dist/cli/selectors/generic.d.ts +0 -10
  126. package/dist/cli/selectors/generic.js +0 -74
  127. package/dist/cli/selectors/index.d.ts +0 -37
  128. package/dist/cli/selectors/index.js +0 -315
  129. package/dist/cli/selectors/next.d.ts +0 -12
  130. package/dist/cli/selectors/next.js +0 -130
  131. package/dist/core/config-policy.test.d.ts +0 -1
  132. package/dist/core/config-policy.test.js +0 -101
  133. package/dist/core/config-roundtrip.test.d.ts +0 -1
  134. package/dist/core/config-roundtrip.test.js +0 -180
  135. package/dist/core/endpoint-guard.test.d.ts +0 -1
  136. package/dist/core/endpoint-guard.test.js +0 -57
  137. package/dist/core/env-diagnostics.test.d.ts +0 -1
  138. package/dist/core/env-diagnostics.test.js +0 -31
  139. package/dist/core/evidence-bundle.conformance.test.d.ts +0 -1
  140. package/dist/core/evidence-bundle.conformance.test.js +0 -110
  141. package/dist/core/evidence-bundle.test.d.ts +0 -1
  142. package/dist/core/evidence-bundle.test.js +0 -58
  143. package/dist/core/invariants.test.d.ts +0 -1
  144. package/dist/core/invariants.test.js +0 -217
  145. package/dist/core/login-handoff.test.d.ts +0 -1
  146. package/dist/core/login-handoff.test.js +0 -31
  147. package/dist/core/profile.test.d.ts +0 -1
  148. package/dist/core/profile.test.js +0 -95
  149. package/dist/core/readiness-checks.test.d.ts +0 -1
  150. package/dist/core/readiness-checks.test.js +0 -106
  151. package/dist/core/receipt.test.d.ts +0 -1
  152. package/dist/core/receipt.test.js +0 -75
  153. package/dist/core/sdk-entrypoint.test.d.ts +0 -1
  154. package/dist/core/sdk-entrypoint.test.js +0 -8
  155. package/dist/core/side-effects-review.test.d.ts +0 -1
  156. package/dist/core/side-effects-review.test.js +0 -28
  157. package/dist/core/token.conformance.test.d.ts +0 -1
  158. package/dist/core/token.conformance.test.js +0 -43
  159. package/dist/core/token.test.d.ts +0 -1
  160. package/dist/core/token.test.js +0 -66
package/TOKEN_SPEC.md CHANGED
@@ -1,243 +1,243 @@
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
- **Conformance:** [`fixtures/token-conformance-vectors.json`](./fixtures/token-conformance-vectors.json) plus `token.conformance.test.ts` in the SDK package.
6
-
7
- **Clock skew:** allow ±60s on `exp`/`iat` unless your deployment documents otherwise.
8
-
9
- **Rejection rules (HS256 delegated/deeplink):** reject `alg: none`, wrong `iss`/`aud`, expired `exp`, and missing required claims.
10
-
11
- > **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.
12
-
13
- ---
14
-
15
- ## Token prefixes
16
-
17
- | Prefix | Transport | Purpose |
18
- |--------|-----------|---------|
19
- | `at_` | `Authorization: Bearer at_…` | Agent access token — identifies a registered third-party agent shell |
20
- | `uct_` | `X-Duct-User-Consent: uct_…` | User consent token — scoped human approval for agent side-effects |
21
- | `dt_` | `Authorization: Bearer dt_…` | Delegation token — short-lived cross-shell delegated identity (single-use `jti`) |
22
- | `rcpt_` | Audit / API body | Outcome receipt ID — references a signed gateway receipt (not a JWT) |
23
- | *(none)* | Query `?token=` or `Bearer` | Deeplink JWT — handoff from shell to your receiver |
24
-
25
- Plain delegated user tokens (`duct_delegated` JWT type) have **no prefix** — they are standard HS256 JWTs minted by your app's token route.
26
-
27
- ---
28
-
29
- ## Algorithms
30
-
31
- ### Symmetric (local dev / migration)
32
-
33
- | Token kind | Algorithm | Secret | Header `alg` |
34
- |------------|-----------|--------|--------------|
35
- | Delegated user JWT | HS256 | `DUCT_SECRET_KEY` (≥32 chars recommended) | `HS256` |
36
- | Deeplink JWT | HS256 | `DUCT_SECRET_KEY` | `HS256` |
37
-
38
- Pin `algorithms: ['HS256']` (or library equivalent). Reject `none` and unexpected algs.
39
-
40
- ### Asymmetric (production — recommended)
41
-
42
- | Token kind | Algorithm | Public keys | `kid` header |
43
- |------------|-----------|-------------|--------------|
44
- | Delegated / deeplink JWT | EdDSA (Ed25519) | `GET /v1/keys` JWKS on the Duct gateway | per-key `kid` |
45
- | Outcome receipt | Ed25519 over canonical JSON body | `GET /v1/keys/receipts` JWKS | `kid` on receipt |
46
-
47
- Fetch JWKS periodically; cache keys by `kid`. Fall back to gateway verify endpoints when JWKS is empty (HMAC-only mode).
48
-
49
- ---
50
-
51
- ## Claims
52
-
53
- ### Delegated user JWT (`duct_delegated`)
54
-
55
- Minted by your token route via `generateDuctToken()`.
56
-
57
- | Claim | Required | Description |
58
- |-------|----------|-------------|
59
- | `type` | yes | Must be `"duct_delegated"` |
60
- | `sub` | yes | User ID |
61
- | `iss` | yes | Shell ID (`shell_…`) |
62
- | `iat` / `exp` | yes | Unix seconds |
63
- | `session` | yes | Allowlisted scalar session fields |
64
- | `allowedActions` | no | Explicit action ID grant list |
65
-
66
- **Default TTL:** `auth.tokenExpirySeconds` in manifest (default **60s**). Examples often use 300s.
67
-
68
- **Verify:** `iss === expectedShellId`, `exp` in future, `type === duct_delegated`, signature valid.
69
-
70
- ### Deeplink JWT
71
-
72
- | Claim | Required | Description |
73
- |-------|----------|-------------|
74
- | `deeplink_id` | yes | Target deeplink from manifest |
75
- | `iss` / `aud` | yes | Both must equal shell ID |
76
- | `sub` | no | User subject when authenticated |
77
- | `iat` / `exp` | yes | Unix seconds |
78
- | `jti` | yes (when replay store used) | Single-use replay protection |
79
- | `state` | yes | Object — pre-fill fields for target route |
80
-
81
- **Default TTL:** per-deeplink `expirySeconds` (default **300s**).
82
-
83
- **Replay:** after signature verification, reject if `jti` was seen before (Redis recommended in production).
84
-
85
- ### Agent access (`at_`)
86
-
87
- Opaque platform-issued token. Verify via `POST /v1/verify/agent-access-token` (auth service) — not a local JWT.
88
-
89
- ### User consent (`uct_`)
90
-
91
- 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`.
92
-
93
- ### Delegation (`dt_`)
94
-
95
- Short-lived cross-shell JWT. **Default TTL: 60s.** Single-use per `jti`. Verify via auth service delegation endpoints.
96
-
97
- ---
98
-
99
- ## Outcome receipts (`rcpt_` / signed body)
100
-
101
- Receipts are **not JWTs**. Structure:
102
-
103
- ```json
104
- {
105
- "claim_type": "duct:action:v1",
106
- "issued_at": "2026-07-01T00:00:00.000Z",
107
- "shell_id": "shell_acme_prod",
108
- "action_id": "refund_order",
109
- "caller_type": "agent",
110
- "decision": "permit",
111
- "reason": "allowed",
112
- "permission_source": "manifest",
113
- "capture_mode": "gateway_observed",
114
- "scope_of_claim": { "asserts": [], "does_not_assert": [] },
115
- "receipt_id": "<sha256-prefix of canonical body>",
116
- "signature": "<hex HMAC or base64 Ed25519>",
117
- "kid": "duct-gateway-hs256-v1 | duct-ed25519-…"
118
- }
119
- ```
120
-
121
- **Canonicalization:** JSON with sorted object keys at every level (see `canonicalizeJson` in SDK).
122
-
123
- **Verification steps:**
124
-
125
- 1. Strip `receipt_id`, `signature`, `kid`; canonicalize remaining body.
126
- 2. `receipt_id` must equal first 32 hex chars of `sha256(canonical)`.
127
- 3. If `kid === duct-gateway-hs256-v1`: HMAC-SHA256 hex verify with `RECEIPT_SIGNING_KEY` (gateway-only).
128
- 4. Else: Ed25519 verify canonical bytes against JWKS key matching `kid`.
129
-
130
- TypeScript helper: `verifyReceipt()` from `@duct-sdk/sdk/server`.
131
-
132
- Context checks (replay, delegation revoked, manifest stale) require `POST /v1/receipts/verify`.
133
-
134
- ---
135
-
136
- ## Verify snippets
137
-
138
- ### Python (PyJWT) — delegated HS256 JWT
139
-
140
- ```python
141
- import jwt
142
-
143
- def verify_delegated(token: str, secret: str, shell_id: str) -> dict:
144
- payload = jwt.decode(
145
- token,
146
- secret,
147
- algorithms=["HS256"],
148
- issuer=shell_id,
149
- options={"require": ["exp", "iat", "sub", "iss"]},
150
- )
151
- if payload.get("type") != "duct_delegated":
152
- raise jwt.InvalidTokenError("wrong type")
153
- return payload
154
- ```
155
-
156
- ### Python — deeplink with jti (replay is app-side)
157
-
158
- ```python
159
- payload = jwt.decode(
160
- token,
161
- secret,
162
- algorithms=["HS256"],
163
- issuer=shell_id,
164
- audience=shell_id,
165
- )
166
- assert payload.get("deeplink_id")
167
- jti = payload.get("jti")
168
- # reject if redis.exists(f"duct:jti:{jti}")
169
- ```
170
-
171
- ### Go (golang-jwt)
172
-
173
- ```go
174
- import "github.com/golang-jwt/jwt/v5"
175
-
176
- func verifyDelegated(tokenString, secret, shellID string) (jwt.MapClaims, error) {
177
- tok, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
178
- if t.Method.Alg() != jwt.SigningMethodHS256.Alg() {
179
- return nil, jwt.ErrTokenUnverifiable
180
- }
181
- return []byte(secret), nil
182
- }, jwt.WithIssuer(shellID))
183
- if err != nil || !tok.Valid {
184
- return nil, err
185
- }
186
- claims := tok.Claims.(jwt.MapClaims)
187
- if claims["type"] != "duct_delegated" {
188
- return nil, jwt.ErrTokenInvalidClaims
189
- }
190
- return claims, nil
191
- }
192
- ```
193
-
194
- ### Ruby (jwt gem)
195
-
196
- ```ruby
197
- require "jwt"
198
-
199
- def verify_delegated(token, secret, shell_id)
200
- payload, = JWT.decode(
201
- token,
202
- secret,
203
- true,
204
- { algorithm: "HS256", iss: shell_id, verify_iss: true }
205
- )
206
- raise JWT::DecodeError, "wrong type" unless payload["type"] == "duct_delegated"
207
- payload
208
- end
209
- ```
210
-
211
- ### Ed25519 deeplink (production)
212
-
213
- 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.
214
-
215
- ---
216
-
217
- ## SDK helpers
218
-
219
- | Function | Package | Notes |
220
- |----------|---------|-------|
221
- | `verifyDuctToken` | `@duct-sdk/sdk/server` | HS256 delegated JWT |
222
- | `verifyDeeplinkToken` | `@duct-sdk/sdk/server` | HS256 + optional `replayStore` |
223
- | `verifyReceipt` | `@duct-sdk/sdk/server` | HMAC or Ed25519 via `hmacSecret` / `jwks` / `publicKeys` |
224
-
225
- ---
226
-
227
- ## TTL summary
228
-
229
- | Token | Default TTL | Config key |
230
- |-------|-------------|------------|
231
- | Delegated user JWT | 60s | `auth.tokenExpirySeconds` |
232
- | Deeplink JWT | 300s | `deeplinks[].expirySeconds` |
233
- | Delegation `dt_` | 60s | Platform default |
234
- | Consent `uct_` | Per grant | Set at consent approval |
235
- | Agent `at_` | Per registration | Dashboard / auth service |
236
-
237
- ---
238
-
239
- ## Related docs
240
-
241
- - Manifest policy fields: `src/core/types.ts` (`validFrom`, `validUntil`, `approveIf`, `actionLimit`, `consentActionScope`)
242
- - Receiver codegen: `duct init` → `verifyDeeplinkToken` + `createDevReplayStore()`
243
- - Gateway verify: `POST /v1/receipts/verify`, `POST /v1/verify/consent-token`
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
+ **Conformance:** [`fixtures/token-conformance-vectors.json`](./fixtures/token-conformance-vectors.json) plus `token.conformance.test.ts` in the SDK package.
6
+
7
+ **Clock skew:** allow ±60s on `exp`/`iat` unless your deployment documents otherwise.
8
+
9
+ **Rejection rules (HS256 delegated/deeplink):** reject `alg: none`, wrong `iss`/`aud`, expired `exp`, and missing required claims.
10
+
11
+ > **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.
12
+
13
+ ---
14
+
15
+ ## Token prefixes
16
+
17
+ | Prefix | Transport | Purpose |
18
+ |--------|-----------|---------|
19
+ | `at_` | `Authorization: Bearer at_…` | Agent access token — identifies a registered third-party agent shell |
20
+ | `uct_` | `X-Duct-User-Consent: uct_…` | User consent token — scoped human approval for agent side-effects |
21
+ | `dt_` | `Authorization: Bearer dt_…` | Delegation token — short-lived cross-shell delegated identity (single-use `jti`) |
22
+ | `rcpt_` | Audit / API body | Outcome receipt ID — references a signed gateway receipt (not a JWT) |
23
+ | *(none)* | Query `?token=` or `Bearer` | Deeplink JWT — handoff from shell to your receiver |
24
+
25
+ Plain delegated user tokens (`duct_delegated` JWT type) have **no prefix** — they are standard HS256 JWTs minted by your app's token route.
26
+
27
+ ---
28
+
29
+ ## Algorithms
30
+
31
+ ### Symmetric (local dev / migration)
32
+
33
+ | Token kind | Algorithm | Secret | Header `alg` |
34
+ |------------|-----------|--------|--------------|
35
+ | Delegated user JWT | HS256 | `DUCT_SECRET_KEY` (≥32 chars recommended) | `HS256` |
36
+ | Deeplink JWT | HS256 | `DUCT_SECRET_KEY` | `HS256` |
37
+
38
+ Pin `algorithms: ['HS256']` (or library equivalent). Reject `none` and unexpected algs.
39
+
40
+ ### Asymmetric (production — recommended)
41
+
42
+ | Token kind | Algorithm | Public keys | `kid` header |
43
+ |------------|-----------|-------------|--------------|
44
+ | Delegated / deeplink JWT | EdDSA (Ed25519) | `GET /v1/keys` JWKS on the Duct gateway | per-key `kid` |
45
+ | Outcome receipt | Ed25519 over canonical JSON body | `GET /v1/keys/receipts` JWKS | `kid` on receipt |
46
+
47
+ Fetch JWKS periodically; cache keys by `kid`. Fall back to gateway verify endpoints when JWKS is empty (HMAC-only mode).
48
+
49
+ ---
50
+
51
+ ## Claims
52
+
53
+ ### Delegated user JWT (`duct_delegated`)
54
+
55
+ Minted by your token route via `generateDuctToken()`.
56
+
57
+ | Claim | Required | Description |
58
+ |-------|----------|-------------|
59
+ | `type` | yes | Must be `"duct_delegated"` |
60
+ | `sub` | yes | User ID |
61
+ | `iss` | yes | Shell ID (`shell_…`) |
62
+ | `iat` / `exp` | yes | Unix seconds |
63
+ | `session` | yes | Allowlisted scalar session fields |
64
+ | `allowedActions` | no | Explicit action ID grant list |
65
+
66
+ **Default TTL:** `auth.tokenExpirySeconds` in manifest (default **60s**). Examples often use 300s.
67
+
68
+ **Verify:** `iss === expectedShellId`, `exp` in future, `type === duct_delegated`, signature valid.
69
+
70
+ ### Deeplink JWT
71
+
72
+ | Claim | Required | Description |
73
+ |-------|----------|-------------|
74
+ | `deeplink_id` | yes | Target deeplink from manifest |
75
+ | `iss` / `aud` | yes | Both must equal shell ID |
76
+ | `sub` | no | User subject when authenticated |
77
+ | `iat` / `exp` | yes | Unix seconds |
78
+ | `jti` | yes (when replay store used) | Single-use replay protection |
79
+ | `state` | yes | Object — pre-fill fields for target route |
80
+
81
+ **Default TTL:** per-deeplink `expirySeconds` (default **300s**).
82
+
83
+ **Replay:** after signature verification, reject if `jti` was seen before (Redis recommended in production).
84
+
85
+ ### Agent access (`at_`)
86
+
87
+ Opaque platform-issued token. Verify via `POST /v1/verify/agent-access-token` (auth service) — not a local JWT.
88
+
89
+ ### User consent (`uct_`)
90
+
91
+ 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`.
92
+
93
+ ### Delegation (`dt_`)
94
+
95
+ Short-lived cross-shell JWT. **Default TTL: 60s.** Single-use per `jti`. Verify via auth service delegation endpoints.
96
+
97
+ ---
98
+
99
+ ## Outcome receipts (`rcpt_` / signed body)
100
+
101
+ Receipts are **not JWTs**. Structure:
102
+
103
+ ```json
104
+ {
105
+ "claim_type": "duct:action:v1",
106
+ "issued_at": "2026-07-01T00:00:00.000Z",
107
+ "shell_id": "shell_acme_prod",
108
+ "action_id": "refund_order",
109
+ "caller_type": "agent",
110
+ "decision": "permit",
111
+ "reason": "allowed",
112
+ "permission_source": "manifest",
113
+ "capture_mode": "gateway_observed",
114
+ "scope_of_claim": { "asserts": [], "does_not_assert": [] },
115
+ "receipt_id": "<sha256-prefix of canonical body>",
116
+ "signature": "<hex HMAC or base64 Ed25519>",
117
+ "kid": "duct-gateway-hs256-v1 | duct-ed25519-…"
118
+ }
119
+ ```
120
+
121
+ **Canonicalization:** JSON with sorted object keys at every level (see `canonicalizeJson` in SDK).
122
+
123
+ **Verification steps:**
124
+
125
+ 1. Strip `receipt_id`, `signature`, `kid`; canonicalize remaining body.
126
+ 2. `receipt_id` must equal first 32 hex chars of `sha256(canonical)`.
127
+ 3. If `kid === duct-gateway-hs256-v1`: HMAC-SHA256 hex verify with `RECEIPT_SIGNING_KEY` (gateway-only).
128
+ 4. Else: Ed25519 verify canonical bytes against JWKS key matching `kid`.
129
+
130
+ TypeScript helper: `verifyReceipt()` from `@duct-sdk/sdk/server`.
131
+
132
+ Context checks (replay, delegation revoked, manifest stale) require `POST /v1/receipts/verify`.
133
+
134
+ ---
135
+
136
+ ## Verify snippets
137
+
138
+ ### Python (PyJWT) — delegated HS256 JWT
139
+
140
+ ```python
141
+ import jwt
142
+
143
+ def verify_delegated(token: str, secret: str, shell_id: str) -> dict:
144
+ payload = jwt.decode(
145
+ token,
146
+ secret,
147
+ algorithms=["HS256"],
148
+ issuer=shell_id,
149
+ options={"require": ["exp", "iat", "sub", "iss"]},
150
+ )
151
+ if payload.get("type") != "duct_delegated":
152
+ raise jwt.InvalidTokenError("wrong type")
153
+ return payload
154
+ ```
155
+
156
+ ### Python — deeplink with jti (replay is app-side)
157
+
158
+ ```python
159
+ payload = jwt.decode(
160
+ token,
161
+ secret,
162
+ algorithms=["HS256"],
163
+ issuer=shell_id,
164
+ audience=shell_id,
165
+ )
166
+ assert payload.get("deeplink_id")
167
+ jti = payload.get("jti")
168
+ # reject if redis.exists(f"duct:jti:{jti}")
169
+ ```
170
+
171
+ ### Go (golang-jwt)
172
+
173
+ ```go
174
+ import "github.com/golang-jwt/jwt/v5"
175
+
176
+ func verifyDelegated(tokenString, secret, shellID string) (jwt.MapClaims, error) {
177
+ tok, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
178
+ if t.Method.Alg() != jwt.SigningMethodHS256.Alg() {
179
+ return nil, jwt.ErrTokenUnverifiable
180
+ }
181
+ return []byte(secret), nil
182
+ }, jwt.WithIssuer(shellID))
183
+ if err != nil || !tok.Valid {
184
+ return nil, err
185
+ }
186
+ claims := tok.Claims.(jwt.MapClaims)
187
+ if claims["type"] != "duct_delegated" {
188
+ return nil, jwt.ErrTokenInvalidClaims
189
+ }
190
+ return claims, nil
191
+ }
192
+ ```
193
+
194
+ ### Ruby (jwt gem)
195
+
196
+ ```ruby
197
+ require "jwt"
198
+
199
+ def verify_delegated(token, secret, shell_id)
200
+ payload, = JWT.decode(
201
+ token,
202
+ secret,
203
+ true,
204
+ { algorithm: "HS256", iss: shell_id, verify_iss: true }
205
+ )
206
+ raise JWT::DecodeError, "wrong type" unless payload["type"] == "duct_delegated"
207
+ payload
208
+ end
209
+ ```
210
+
211
+ ### Ed25519 deeplink (production)
212
+
213
+ 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.
214
+
215
+ ---
216
+
217
+ ## SDK helpers
218
+
219
+ | Function | Package | Notes |
220
+ |----------|---------|-------|
221
+ | `verifyDuctToken` | `@duct-sdk/sdk/server` | HS256 delegated JWT |
222
+ | `verifyDeeplinkToken` | `@duct-sdk/sdk/server` | HS256 + optional `replayStore` |
223
+ | `verifyReceipt` | `@duct-sdk/sdk/server` | HMAC or Ed25519 via `hmacSecret` / `jwks` / `publicKeys` |
224
+
225
+ ---
226
+
227
+ ## TTL summary
228
+
229
+ | Token | Default TTL | Config key |
230
+ |-------|-------------|------------|
231
+ | Delegated user JWT | 60s | `auth.tokenExpirySeconds` |
232
+ | Deeplink JWT | 300s | `deeplinks[].expirySeconds` |
233
+ | Delegation `dt_` | 60s | Platform default |
234
+ | Consent `uct_` | Per grant | Set at consent approval |
235
+ | Agent `at_` | Per registration | Dashboard / auth service |
236
+
237
+ ---
238
+
239
+ ## Related docs
240
+
241
+ - Manifest policy fields: `src/core/types.ts` (`validFrom`, `validUntil`, `approveIf`, `actionLimit`, `consentActionScope`)
242
+ - Receiver codegen: `duct add identity` → `verifyDeeplinkToken` + `createDevReplayStore()`
243
+ - Gateway verify: `POST /v1/receipts/verify`, `POST /v1/verify/consent-token`
@@ -0,0 +1,7 @@
1
+ export type AddLayer = "identity" | "shell";
2
+ export interface AddOptions {
3
+ cwd: string;
4
+ layer: AddLayer;
5
+ force?: boolean;
6
+ }
7
+ export declare function runAdd(opts: AddOptions): Promise<void>;
@@ -0,0 +1,152 @@
1
+ // ============================================================
2
+ // @duct-sdk/sdk — duct add identity | shell
3
+ //
4
+ // Optional layers on top of the agent gateway:
5
+ // identity agents act for a signed-in user (token route, deeplink receiver,
6
+ // middleware snippet). Detects your auth library and records it.
7
+ // shell embed the Duct chat shell in your app (component + duct/shell.ts).
8
+ // Existing files are never overwritten unless --force.
9
+ // ============================================================
10
+ import * as fs from "fs/promises";
11
+ import * as path from "path";
12
+ import { existsSync } from "fs";
13
+ import chalk from "chalk";
14
+ import { detectFramework } from "./detectors/framework.js";
15
+ import { detectAuth } from "./detectors/auth.js";
16
+ import { SandboxFS } from "./fs/sandbox.js";
17
+ import { frameworkHasShellComponent, getGeneratedOutputPaths } from "./output-paths.js";
18
+ import { generateReceiver, generateTokenRoute } from "./generators/receiver.js";
19
+ import { generateEnvTemplateForFramework, generateShell } from "./generators/shell.js";
20
+ import { normalizeDuctConfigForCodegen } from "./generators/normalize.js";
21
+ import { generateIdentityContract, generateShellEmbed } from "./generators/any-stack.js";
22
+ import { getShellRuntimeUrl } from "../core/endpoints.js";
23
+ import { buildWiringPlan } from "./generators/wiring-snippets.js";
24
+ import { resolveProjectConfig } from "./project-loader.js";
25
+ import { renderProjectFile, renderShellFile } from "./project-writer.js";
26
+ import { enrichAuthLoginHandoff } from "../core/login-handoff.js";
27
+ const LOGIN_PATHS = ["/login", "/signin", "/sign-in", "/auth/login", "/auth/signin", "/auth/sign-in"];
28
+ const PAGE_FILES = (route) => {
29
+ const trimmed = route.replace(/^\//, "");
30
+ const flat = trimmed.replace(/\//g, ".");
31
+ return [
32
+ ...["app", "src/app"].flatMap((dir) => ["tsx", "jsx", "ts", "js"].map((ext) => `${dir}/${trimmed}/page.${ext}`)),
33
+ ...["pages", "src/pages"].flatMap((dir) => ["tsx", "jsx", "ts", "js"].map((ext) => `${dir}/${trimmed}.${ext}`)),
34
+ ...["tsx", "jsx"].map((ext) => `app/routes/${flat}.${ext}`),
35
+ `src/routes/${trimmed}/+page.svelte`,
36
+ ];
37
+ };
38
+ /** Login pages that exist in the repo, as routes for login-handoff detection. */
39
+ function detectLoginRoutes(root) {
40
+ return LOGIN_PATHS.filter((route) => PAGE_FILES(route).some((file) => existsSync(path.join(root, file)))).map((route) => ({ path: route }));
41
+ }
42
+ async function writeIfAbsent(root, target, content, force) {
43
+ const relative = path.relative(root, target).split(path.sep).join("/");
44
+ if (existsSync(target) && !force) {
45
+ console.log(chalk.gray(` exists, kept ${relative}`));
46
+ return "skipped";
47
+ }
48
+ await fs.mkdir(path.dirname(target), { recursive: true });
49
+ await fs.writeFile(target, content, "utf-8");
50
+ console.log(chalk.green(` wrote ${relative}`));
51
+ return "written";
52
+ }
53
+ async function appendEnvTemplate(target, content) {
54
+ if (existsSync(target)) {
55
+ const existing = await fs.readFile(target, "utf-8");
56
+ if (existing.includes("DUCT_SHELL_ID"))
57
+ return;
58
+ await fs.appendFile(target, `\n${content}`, "utf-8");
59
+ }
60
+ else {
61
+ await fs.writeFile(target, content, "utf-8");
62
+ }
63
+ }
64
+ function frameworkLabel(framework) {
65
+ return framework.name === "unknown" ? "an unrecognised framework" : framework.name;
66
+ }
67
+ export async function runAdd(opts) {
68
+ let resolved = await resolveProjectConfig(opts.cwd);
69
+ const root = resolved.root;
70
+ const force = Boolean(opts.force);
71
+ const framework = await detectFramework(root);
72
+ const outputPaths = getGeneratedOutputPaths(root, framework);
73
+ console.log(chalk.bold(`\n duct add ${opts.layer}`) + chalk.gray(` (${frameworkLabel(framework)})\n`));
74
+ // No template for this stack: describe the HTTP contract instead of generating code for
75
+ // a framework the project does not use.
76
+ if (framework.name === "unknown") {
77
+ const config = normalizeDuctConfigForCodegen(resolved.config);
78
+ const dir = resolved.layout === "split" && resolved.paths ? path.dirname(resolved.paths.project) : root;
79
+ if (opts.layer === "identity") {
80
+ await writeIfAbsent(root, path.join(dir, "identity-contract.md"), generateIdentityContract(config), force);
81
+ console.log(chalk.bold("\n Next"));
82
+ console.log(" Your stack has no template, so duct/identity-contract.md describes the three HTTP");
83
+ console.log(" behaviours to add in your language: a token endpoint, a deeplink receiver, and");
84
+ console.log(" verifying Duct calls. Then: npx @duct-sdk/sdk push -> npx @duct-sdk/sdk test\n");
85
+ }
86
+ else {
87
+ await writeIfAbsent(root, path.join(dir, "shell-embed.html"), generateShellEmbed(config, getShellRuntimeUrl()), force);
88
+ console.log(chalk.bold("\n Next"));
89
+ console.log(" Paste duct/shell-embed.html into your pages (or load the shell URL in a mobile");
90
+ console.log(" WebView). Users acting on their own data also need: npx @duct-sdk/sdk add identity\n");
91
+ }
92
+ return;
93
+ }
94
+ if (opts.layer === "identity") {
95
+ const authDetection = await detectAuth(new SandboxFS(root));
96
+ // Record the detected auth library in duct/project.ts the first time.
97
+ if (resolved.layout === "split" && resolved.files && resolved.paths) {
98
+ const current = resolved.files.project.auth;
99
+ if (!current || current.strategy === "unknown") {
100
+ const auth = enrichAuthLoginHandoff({
101
+ strategy: authDetection.system,
102
+ sessionFields: authDetection.sessionFields,
103
+ guestAllowed: authDetection.guestAllowed,
104
+ tokenExpirySeconds: 300,
105
+ }, [...detectLoginRoutes(root), ...(resolved.files.shell?.routes ?? [])], resolved.files.shell?.deeplinks ?? []);
106
+ const nextProject = { ...resolved.files.project, auth };
107
+ await fs.writeFile(resolved.paths.project, renderProjectFile(nextProject), "utf-8");
108
+ const login = auth.loginRoutePath;
109
+ console.log(chalk.green(` updated duct/project.ts auth.strategy = ${authDetection.system}${login ? `, loginRoutePath = ${login}` : ""}`));
110
+ resolved = await resolveProjectConfig(root);
111
+ }
112
+ }
113
+ const config = normalizeDuctConfigForCodegen(resolved.config);
114
+ const plan = buildWiringPlan(outputPaths, framework, authDetection, "duct-consent");
115
+ await writeIfAbsent(root, outputPaths.tokenRoutePath, generateTokenRoute(config, framework), force);
116
+ await writeIfAbsent(root, outputPaths.receiverPath, generateReceiver(config, framework), force);
117
+ await writeIfAbsent(root, path.join(root, plan.middlewareSnippetPath), plan.middlewareSnippet, force);
118
+ if (plan.uctSnippet && plan.uctSnippetPath) {
119
+ await writeIfAbsent(root, path.join(root, plan.uctSnippetPath), plan.uctSnippet, force);
120
+ }
121
+ await appendEnvTemplate(outputPaths.envTemplatePath, generateEnvTemplateForFramework(config, framework));
122
+ console.log(chalk.bold("\n Next"));
123
+ console.log(` 1. Put ${chalk.cyan("DUCT_SECRET_KEY")} (shown once when the shell was created; rotate it under Dashboard → Shell → Credentials) in your env.`);
124
+ console.log(` 2. Wire the snippet in ${plan.middlewareSnippetPath} into ${authDetection.middlewarePath ?? "your API auth middleware"}.`);
125
+ console.log(" 3. npx @duct-sdk/sdk push → npx @duct-sdk/sdk test\n");
126
+ return;
127
+ }
128
+ // ── shell ──────────────────────────────────────────────────────
129
+ if (resolved.layout === "split" && resolved.paths && !existsSync(resolved.paths.shell)) {
130
+ await fs.writeFile(resolved.paths.shell, renderShellFile({
131
+ widget: { welcomeMessage: `Ask me anything about ${resolved.files?.project.product.name ?? "your account"}.`, theme: "system" },
132
+ routes: [],
133
+ deeplinks: [],
134
+ }), "utf-8");
135
+ console.log(chalk.green(" wrote duct/shell.ts"));
136
+ resolved = await resolveProjectConfig(root);
137
+ }
138
+ const config = normalizeDuctConfigForCodegen(resolved.config);
139
+ if (frameworkHasShellComponent(framework)) {
140
+ await writeIfAbsent(root, outputPaths.shellComponentPath, generateShell(config, framework), force);
141
+ }
142
+ else {
143
+ console.log(chalk.gray(" This looks like a backend-only project — mount <DuctShell /> in your frontend app instead."));
144
+ }
145
+ await appendEnvTemplate(outputPaths.envTemplatePath, generateEnvTemplateForFramework(config, framework));
146
+ console.log(chalk.bold("\n Next"));
147
+ console.log(frameworkHasShellComponent(framework)
148
+ ? ` 1. Render the component from ${path.relative(root, outputPaths.shellComponentPath)} in your root layout.`
149
+ : " 1. Add <DuctShell /> from @duct-sdk/sdk/react to your frontend.");
150
+ console.log(" 2. Users need identity for actions on their data: npx @duct-sdk/sdk add identity");
151
+ console.log(" 3. npx @duct-sdk/sdk push\n");
152
+ }
@@ -0,0 +1,3 @@
1
+ export declare function buildAgentPrompt(opts: {
2
+ hasProject: boolean;
3
+ }): string;