@duct-sdk/sdk 0.5.12 → 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 (159) hide show
  1. package/CHANGELOG.md +385 -336
  2. package/README.md +418 -264
  3. package/TOKEN_SPEC.md +243 -237
  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 +402 -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 +533 -1
  59. package/dist/core/config.js +32 -12
  60. package/dist/core/hosted-upstream-check.d.ts +3 -0
  61. package/dist/core/hosted-upstream-check.js +35 -0
  62. package/dist/core/login-handoff.d.ts +1 -1
  63. package/dist/core/login-handoff.js +1 -1
  64. package/dist/core/project.d.ts +1798 -0
  65. package/dist/core/project.js +278 -0
  66. package/dist/core/readiness-checks.js +2 -2
  67. package/dist/core/types.d.ts +26 -1
  68. package/dist/index.d.ts +6 -0
  69. package/dist/index.js +16 -0
  70. package/dist/project.d.ts +4 -0
  71. package/dist/project.js +8 -0
  72. package/dist/server.d.ts +2 -0
  73. package/dist/server.js +1 -0
  74. package/fixtures/token-conformance-vectors.json +26 -0
  75. package/package.json +94 -94
  76. package/dist/adapters/react/page-context-guard.test.d.ts +0 -1
  77. package/dist/adapters/react/page-context-guard.test.js +0 -15
  78. package/dist/cli/agents/api-agent.d.ts +0 -22
  79. package/dist/cli/agents/api-agent.js +0 -761
  80. package/dist/cli/agents/auth-agent.d.ts +0 -7
  81. package/dist/cli/agents/auth-agent.js +0 -212
  82. package/dist/cli/agents/deeplink-agent.d.ts +0 -6
  83. package/dist/cli/agents/deeplink-agent.js +0 -285
  84. package/dist/cli/agents/llm.d.ts +0 -33
  85. package/dist/cli/agents/llm.js +0 -309
  86. package/dist/cli/agents/pipeline.d.ts +0 -72
  87. package/dist/cli/agents/pipeline.js +0 -421
  88. package/dist/cli/agents/reviewer-agent.d.ts +0 -13
  89. package/dist/cli/agents/reviewer-agent.js +0 -450
  90. package/dist/cli/agents/route-agent.d.ts +0 -17
  91. package/dist/cli/agents/route-agent.js +0 -383
  92. package/dist/cli/config-loader.test.d.ts +0 -1
  93. package/dist/cli/config-loader.test.js +0 -63
  94. package/dist/cli/detectors/topology.d.ts +0 -46
  95. package/dist/cli/detectors/topology.js +0 -417
  96. package/dist/cli/generators/config.test.d.ts +0 -1
  97. package/dist/cli/generators/config.test.js +0 -222
  98. package/dist/cli/generators/shell.test.d.ts +0 -1
  99. package/dist/cli/generators/shell.test.js +0 -73
  100. package/dist/cli/generators/token-route.test.d.ts +0 -1
  101. package/dist/cli/generators/token-route.test.js +0 -53
  102. package/dist/cli/generators/wiring-snippets.test.d.ts +0 -1
  103. package/dist/cli/generators/wiring-snippets.test.js +0 -80
  104. package/dist/cli/init.d.ts +0 -32
  105. package/dist/cli/init.js +0 -1336
  106. package/dist/cli/manifest-diff.test.d.ts +0 -1
  107. package/dist/cli/manifest-diff.test.js +0 -144
  108. package/dist/cli/processors/curl-parser.test.d.ts +0 -1
  109. package/dist/cli/processors/curl-parser.test.js +0 -24
  110. package/dist/cli/processors/integration-audit.test.d.ts +0 -1
  111. package/dist/cli/processors/integration-audit.test.js +0 -154
  112. package/dist/cli/processors/postprocess.d.ts +0 -22
  113. package/dist/cli/processors/postprocess.js +0 -107
  114. package/dist/cli/processors/prisma-parser.d.ts +0 -35
  115. package/dist/cli/processors/prisma-parser.js +0 -117
  116. package/dist/cli/processors/verify-discovery.d.ts +0 -33
  117. package/dist/cli/processors/verify-discovery.js +0 -193
  118. package/dist/cli/processors/verify-discovery.test.d.ts +0 -1
  119. package/dist/cli/processors/verify-discovery.test.js +0 -153
  120. package/dist/cli/processors/zod-extractor.d.ts +0 -27
  121. package/dist/cli/processors/zod-extractor.js +0 -153
  122. package/dist/cli/prompts/review.d.ts +0 -61
  123. package/dist/cli/prompts/review.js +0 -410
  124. package/dist/cli/selectors/express.d.ts +0 -12
  125. package/dist/cli/selectors/express.js +0 -117
  126. package/dist/cli/selectors/fastapi.d.ts +0 -12
  127. package/dist/cli/selectors/fastapi.js +0 -122
  128. package/dist/cli/selectors/generic.d.ts +0 -10
  129. package/dist/cli/selectors/generic.js +0 -74
  130. package/dist/cli/selectors/index.d.ts +0 -37
  131. package/dist/cli/selectors/index.js +0 -315
  132. package/dist/cli/selectors/next.d.ts +0 -12
  133. package/dist/cli/selectors/next.js +0 -130
  134. package/dist/core/config-policy.test.d.ts +0 -1
  135. package/dist/core/config-policy.test.js +0 -101
  136. package/dist/core/config-roundtrip.test.d.ts +0 -1
  137. package/dist/core/config-roundtrip.test.js +0 -180
  138. package/dist/core/endpoint-guard.test.d.ts +0 -1
  139. package/dist/core/endpoint-guard.test.js +0 -57
  140. package/dist/core/env-diagnostics.test.d.ts +0 -1
  141. package/dist/core/env-diagnostics.test.js +0 -31
  142. package/dist/core/evidence-bundle.conformance.test.d.ts +0 -1
  143. package/dist/core/evidence-bundle.conformance.test.js +0 -110
  144. package/dist/core/evidence-bundle.test.d.ts +0 -1
  145. package/dist/core/evidence-bundle.test.js +0 -58
  146. package/dist/core/invariants.test.d.ts +0 -1
  147. package/dist/core/invariants.test.js +0 -217
  148. package/dist/core/login-handoff.test.d.ts +0 -1
  149. package/dist/core/login-handoff.test.js +0 -31
  150. package/dist/core/profile.test.d.ts +0 -1
  151. package/dist/core/profile.test.js +0 -95
  152. package/dist/core/readiness-checks.test.d.ts +0 -1
  153. package/dist/core/readiness-checks.test.js +0 -106
  154. package/dist/core/receipt.test.d.ts +0 -1
  155. package/dist/core/receipt.test.js +0 -75
  156. package/dist/core/side-effects-review.test.d.ts +0 -1
  157. package/dist/core/side-effects-review.test.js +0 -28
  158. package/dist/core/token.test.d.ts +0 -1
  159. package/dist/core/token.test.js +0 -66
@@ -0,0 +1,298 @@
1
+ // ============================================================
2
+ // @duct-sdk/sdk — Duct cloud client for the CLI
3
+ //
4
+ // One place for credentials (~/.duct/auth.json) and every HTTP call the
5
+ // CLI makes: account shells, manifest push, and `duct test` checks.
6
+ // ============================================================
7
+ import * as fs from "fs/promises";
8
+ import * as os from "os";
9
+ import * as path from "path";
10
+ import { getActiveAuthBase, getCandidateAuthBases, getConfiguredDashboard, getManifestApiBases, } from "../core/endpoints.js";
11
+ export const DUCT_AUTH_FILE = path.join(os.homedir(), ".duct", "auth.json");
12
+ const REQUEST_TIMEOUT_MS = 15_000;
13
+ export class CloudError extends Error {
14
+ status;
15
+ code;
16
+ body;
17
+ constructor(message, status, code, body) {
18
+ super(message);
19
+ this.status = status;
20
+ this.code = code;
21
+ this.body = body;
22
+ this.name = "CloudError";
23
+ }
24
+ }
25
+ // ----------------------------------------------------------------
26
+ // Credentials
27
+ // ----------------------------------------------------------------
28
+ export async function readAuth() {
29
+ try {
30
+ return JSON.parse(await fs.readFile(DUCT_AUTH_FILE, "utf-8"));
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ export async function saveAuth(auth) {
37
+ await fs.mkdir(path.dirname(DUCT_AUTH_FILE), { recursive: true });
38
+ await fs.writeFile(DUCT_AUTH_FILE, JSON.stringify(auth, null, 2), "utf-8");
39
+ // Owner-only on Unix/macOS. Windows ignores chmod; NTFS ACLs on the profile dir apply.
40
+ try {
41
+ await fs.chmod(DUCT_AUTH_FILE, 0o600);
42
+ }
43
+ catch {
44
+ /* non-fatal */
45
+ }
46
+ }
47
+ export async function clearAuth() {
48
+ try {
49
+ await fs.unlink(DUCT_AUTH_FILE);
50
+ }
51
+ catch {
52
+ /* already gone */
53
+ }
54
+ }
55
+ /** API key for this run: DUCT_API_KEY (CI) wins over the saved login. */
56
+ export function resolveApiKey(auth) {
57
+ return process.env["DUCT_API_KEY"] || auth?.token || null;
58
+ }
59
+ async function requestJson(url, init) {
60
+ const { apiKey, ...rest } = init;
61
+ let res;
62
+ try {
63
+ res = await fetch(url, {
64
+ ...rest,
65
+ headers: {
66
+ Authorization: `Bearer ${apiKey}`,
67
+ ...(rest.body ? { "Content-Type": "application/json" } : {}),
68
+ ...(rest.headers ?? {}),
69
+ },
70
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
71
+ });
72
+ }
73
+ catch (err) {
74
+ const reason = err instanceof Error && err.name === "TimeoutError" ? "timed out" : "could not connect";
75
+ throw new CloudError(`${new URL(url).origin} ${reason}`);
76
+ }
77
+ const text = await res.text();
78
+ let data = null;
79
+ try {
80
+ data = text ? JSON.parse(text) : null;
81
+ }
82
+ catch {
83
+ data = null;
84
+ }
85
+ return { status: res.status, data, text };
86
+ }
87
+ function errorFrom(status, data, text, fallback) {
88
+ const body = (data && typeof data === "object" ? data : {});
89
+ const message = body.message ?? (text && text.length < 300 ? text : fallback);
90
+ return new CloudError(message, status, body.error, data);
91
+ }
92
+ /** Validate a dk_live_ key against the first auth base that answers, then persist it. */
93
+ export async function loginWithKey(rawKey, existing) {
94
+ let lastError = null;
95
+ for (const base of getCandidateAuthBases(existing)) {
96
+ try {
97
+ const { status, data, text } = await requestJson(`${base}/v1/auth/validate`, { method: "GET", apiKey: rawKey });
98
+ if (status !== 200 || !data) {
99
+ lastError = errorFrom(status, data, text, "Invalid API key");
100
+ continue;
101
+ }
102
+ const auth = {
103
+ token: rawKey,
104
+ email: data.email ?? "unknown",
105
+ companyId: data.company_id ?? "",
106
+ slug: data.slug ?? "",
107
+ apiBase: base,
108
+ dashboardUrl: getConfiguredDashboard(existing),
109
+ savedAt: new Date().toISOString(),
110
+ };
111
+ await saveAuth(auth);
112
+ return auth;
113
+ }
114
+ catch (err) {
115
+ lastError = err;
116
+ }
117
+ }
118
+ throw lastError instanceof Error ? lastError : new CloudError("Invalid API key");
119
+ }
120
+ // ----------------------------------------------------------------
121
+ // Account
122
+ // ----------------------------------------------------------------
123
+ export async function listAccountShells(auth, apiKey) {
124
+ const base = getActiveAuthBase(auth);
125
+ const { status, data, text } = await requestJson(`${base}/v1/account/shells`, {
126
+ method: "GET",
127
+ apiKey,
128
+ });
129
+ if (status === 401 || status === 403) {
130
+ throw new CloudError("Your Duct API key was rejected. Run `npx @duct-sdk/sdk login` again.", status);
131
+ }
132
+ if (status !== 200)
133
+ throw errorFrom(status, data, text, `Could not list shells (HTTP ${status})`);
134
+ return data?.shells ?? [];
135
+ }
136
+ /** Create a shell. A duplicate name raises CloudError with code shell_exists (and the existing id in body). */
137
+ export async function provisionShell(auth, apiKey, name, domains) {
138
+ const base = getActiveAuthBase(auth);
139
+ const { status, data, text } = await requestJson(`${base}/v1/shells/provision`, {
140
+ method: "POST",
141
+ apiKey,
142
+ body: JSON.stringify({ environment: name, registered_domain: domains[0], registered_domains: domains }),
143
+ });
144
+ if (status === 201 || status === 200) {
145
+ if (!data?.shell_id || !data.secret_key)
146
+ throw new CloudError("Duct did not return the new shell's credentials.", status);
147
+ return data;
148
+ }
149
+ if (status === 401 || status === 403) {
150
+ throw new CloudError("Your Duct API key cannot create shells. Owners and admins can; run `npx @duct-sdk/sdk login` again.", status);
151
+ }
152
+ throw errorFrom(status, data, text, `Could not create the shell (HTTP ${status})`);
153
+ }
154
+ // ----------------------------------------------------------------
155
+ // Manifest + checks (Duct API) — try each manifest base until one answers
156
+ // ----------------------------------------------------------------
157
+ /** A JSON body with an `error` code means a Duct service answered (not a stray host). */
158
+ function isDuctAnswer(data) {
159
+ return Boolean(data && typeof data === "object" && typeof data.error === "string");
160
+ }
161
+ async function callManifestApi(auth, apiKey, pathAndQuery, init) {
162
+ let httpError = null;
163
+ let connectError = null;
164
+ for (const base of getManifestApiBases(auth)) {
165
+ let response;
166
+ try {
167
+ response = await requestJson(`${base}${pathAndQuery}`, {
168
+ method: init.method,
169
+ apiKey,
170
+ ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
171
+ });
172
+ }
173
+ catch (err) {
174
+ // Fallback bases (e.g. local dev ports) may simply not exist — keep the first real answer.
175
+ connectError ??= err instanceof CloudError ? err : new CloudError(String(err));
176
+ continue;
177
+ }
178
+ const { status, data, text } = response;
179
+ if (status >= 200 && status < 300 && data)
180
+ return data;
181
+ const error = errorFrom(status, data, text, `HTTP ${status} from ${base}`);
182
+ // A non-JSON 404 means "this host doesn't serve the API" — try the next base.
183
+ // A JSON 404 is Duct saying the resource doesn't exist — that is the answer.
184
+ if (status === 404 && !isDuctAnswer(data)) {
185
+ httpError ??= error;
186
+ continue;
187
+ }
188
+ throw error;
189
+ }
190
+ throw httpError ?? connectError ?? new CloudError("No Duct API endpoint responded");
191
+ }
192
+ /**
193
+ * The full live manifest (owner-only), or null when nothing has been pushed yet.
194
+ * The newest push-timeline entry is what is live (pushes, rollbacks and dashboard network
195
+ * changes all append to it); its snapshot carries every enforcement field, unlike the
196
+ * public GET /manifest view which drops policy fields such as approveIf and agentPermissions.
197
+ */
198
+ export async function fetchLiveFullManifest(auth, apiKey, shellId) {
199
+ const shell = encodeURIComponent(shellId);
200
+ let history;
201
+ try {
202
+ history = await callManifestApi(auth, apiKey, `/v1/shells/${shell}/manifest/history`, { method: "GET" });
203
+ }
204
+ catch (err) {
205
+ if (err instanceof CloudError && err.status === 404)
206
+ return null;
207
+ throw err;
208
+ }
209
+ const latest = history.history?.[0]?.hash;
210
+ if (!latest)
211
+ return null;
212
+ const record = await callManifestApi(auth, apiKey, `/v1/shells/${shell}/manifest/history/${encodeURIComponent(latest)}`, { method: "GET" });
213
+ return record.manifest ?? null;
214
+ }
215
+ /** Public live manifest (filtered view), or null when nothing has been pushed yet. */
216
+ export async function fetchLiveManifest(auth, apiKey, shellId) {
217
+ try {
218
+ const data = await callManifestApi(auth, apiKey, `/v1/shells/${encodeURIComponent(shellId)}/manifest`, { method: "GET" });
219
+ return data.manifest ?? null;
220
+ }
221
+ catch (err) {
222
+ if (err instanceof CloudError && err.status === 404)
223
+ return null;
224
+ throw err;
225
+ }
226
+ }
227
+ export async function pushManifest(auth, apiKey, shellId, config, opts = {}) {
228
+ return callManifestApi(auth, apiKey, `/v1/shells/${encodeURIComponent(shellId)}/manifest`, {
229
+ method: "PUT",
230
+ body: {
231
+ config,
232
+ ...(opts.forceDashboardNetworkOverride ? { force_dashboard_network_override: true } : {}),
233
+ },
234
+ });
235
+ }
236
+ /**
237
+ * A policy decision depends on the action being checked and the shell-wide settings, not on
238
+ * every other action. Sending only the actions the cases name keeps check requests small
239
+ * however large the API is.
240
+ */
241
+ export function configForCases(config, cases) {
242
+ if (!Array.isArray(config.actions))
243
+ return config;
244
+ const needed = new Set(cases.map((c) => c.action));
245
+ return {
246
+ ...config,
247
+ actions: config.actions.filter((a) => typeof a.id === "string" && needed.has(a.id)),
248
+ };
249
+ }
250
+ /** The reachability probe only needs where the API lives. */
251
+ export function upstreamSlice(config) {
252
+ const product = (config.product && typeof config.product === "object" ? config.product : {});
253
+ return {
254
+ ...(typeof config.shellId === "string" ? { shellId: config.shellId } : {}),
255
+ product: { apiBaseUrl: product.apiBaseUrl, baseUrl: product.baseUrl },
256
+ ...(config.apiBaseUrl !== undefined ? { apiBaseUrl: config.apiBaseUrl } : {}),
257
+ ...(config.baseUrl !== undefined ? { baseUrl: config.baseUrl } : {}),
258
+ };
259
+ }
260
+ export async function checkPolicy(auth, apiKey, shellId, config, cases) {
261
+ const data = await callManifestApi(auth, apiKey, `/v1/shells/${encodeURIComponent(shellId)}/checks/policy`, { method: "POST", body: { ...(config ? { config: configForCases(config, cases) } : {}), cases } });
262
+ return data.results ?? [];
263
+ }
264
+ export async function checkUpstream(auth, apiKey, shellId, config) {
265
+ return callManifestApi(auth, apiKey, `/v1/shells/${encodeURIComponent(shellId)}/checks/upstream`, { method: "POST", body: config ? { config: upstreamSlice(config) } : {} });
266
+ }
267
+ export async function getShellWebhooks(auth, apiKey, shellId) {
268
+ const data = await callManifestApi(auth, apiKey, `/v1/shells/${encodeURIComponent(shellId)}/manifest/webhooks`, { method: "GET" });
269
+ return (data.webhooks ?? { deeplinkCallback: "", eventStream: "", consentCallback: "", identityUrl: "", secretConfigured: false, secretPreview: null });
270
+ }
271
+ export async function patchShellWebhooks(auth, apiKey, shellId, patch) {
272
+ const data = await callManifestApi(auth, apiKey, `/v1/shells/${encodeURIComponent(shellId)}/manifest/webhooks`, { method: "PATCH", body: patch });
273
+ if (!data.webhooks)
274
+ throw new CloudError("Duct did not confirm the change.");
275
+ return data.webhooks;
276
+ }
277
+ export async function runConnectionChecks(auth, apiKey, shellId, targets) {
278
+ const data = await callManifestApi(auth, apiKey, `/v1/shells/${encodeURIComponent(shellId)}/checks/connections`, { method: "POST", body: targets?.length ? { targets } : {} });
279
+ return { ok: Boolean(data.ok), results: data.results ?? [] };
280
+ }
281
+ export async function listPartnerProfiles(auth, apiKey, shellId) {
282
+ const base = getActiveAuthBase(auth);
283
+ const { status, data, text } = await requestJson(`${base}/v1/agent-access-profiles/${encodeURIComponent(shellId)}`, { method: "GET", apiKey });
284
+ if (status !== 200)
285
+ throw errorFrom(status, data, text, `Could not list partner profiles (HTTP ${status})`);
286
+ return (data?.profiles ?? []).filter((p) => p.active !== false);
287
+ }
288
+ export async function createPartnerProfile(auth, apiKey, shellId, profile) {
289
+ const base = getActiveAuthBase(auth);
290
+ const { status, data, text } = await requestJson(`${base}/v1/agent-access-profiles`, {
291
+ method: "POST",
292
+ apiKey,
293
+ body: JSON.stringify({ shellId, ...profile }),
294
+ });
295
+ if (status !== 200 && status !== 201)
296
+ throw errorFrom(status, data, text, `Could not create the profile (HTTP ${status})`);
297
+ return { name: data?.name ?? profile.name, profile_id: data?.profile_id ?? "" };
298
+ }
@@ -3,6 +3,20 @@ export declare class ConfigRuntimeReferenceError extends Error {
3
3
  }
4
4
  export declare function configSourceHasRuntimeReferences(source: string): boolean;
5
5
  export declare function extractConfigObjectLiteral(source: string): string | null;
6
+ /**
7
+ * Extract the object literal passed to `marker` (e.g. `definePolicy(`) without executing
8
+ * the file. Shared by duct.config.ts and every duct/*.ts project file.
9
+ */
10
+ export declare function extractDefinedObjectLiteral(source: string, marker: string): string | null;
11
+ export declare class StaticDefinitionError extends Error {
12
+ readonly filePath: string;
13
+ constructor(filePath: string, message: string);
14
+ }
15
+ /**
16
+ * Load `marker({...})` from a project file statically. Throws StaticDefinitionError with a
17
+ * human-readable reason when the file is missing the marker or uses runtime values.
18
+ */
19
+ export declare function loadStaticDefinition(filePath: string, marker: string): Promise<Record<string, unknown>>;
6
20
  /**
7
21
  * Parse `defineDuctConfig({...})` as a JSON-safe object literal.
8
22
  * Rejects configs that reference runtime values; does not expose `process`.
@@ -1,5 +1,5 @@
1
1
  // ============================================================
2
- // @duct/sdk — duct.config.ts static loader (no arbitrary code exec)
2
+ // @duct-sdk/sdk — static loader for duct.config.ts and duct/*.ts (no code exec)
3
3
  // ============================================================
4
4
  import * as fs from "fs/promises";
5
5
  import * as path from "path";
@@ -13,7 +13,12 @@ export class ConfigRuntimeReferenceError extends Error {
13
13
  }
14
14
  }
15
15
  export function configSourceHasRuntimeReferences(source) {
16
+ // Ignore words inside quoted strings ("We process refunds" is data, not code) and comments.
17
+ // Template literals are kept: `${...}` can hold expressions. The sandbox still has no
18
+ // process/require/fetch, so this check is defense in depth.
16
19
  const stripped = source
20
+ .replace(/'(?:[^'\\\n]|\\.)*'/g, "''")
21
+ .replace(/"(?:[^"\\\n]|\\.)*"/g, '""')
17
22
  .replace(/\/\*[\s\S]*?\*\//g, "")
18
23
  .replace(/\/\/.*$/gm, "");
19
24
  return (/\bprocess\b/.test(stripped) ||
@@ -22,7 +27,13 @@ export function configSourceHasRuntimeReferences(source) {
22
27
  /\bimport\s*\(/.test(stripped));
23
28
  }
24
29
  export function extractConfigObjectLiteral(source) {
25
- const marker = "defineDuctConfig(";
30
+ return extractDefinedObjectLiteral(source, "defineDuctConfig(");
31
+ }
32
+ /**
33
+ * Extract the object literal passed to `marker` (e.g. `definePolicy(`) without executing
34
+ * the file. Shared by duct.config.ts and every duct/*.ts project file.
35
+ */
36
+ export function extractDefinedObjectLiteral(source, marker) {
26
37
  const markerIndex = source.indexOf(marker);
27
38
  if (markerIndex === -1)
28
39
  return null;
@@ -110,6 +121,48 @@ function toCompiledCandidates(configPath) {
110
121
  .replace(/\.(ts|tsx)$/i, ".js");
111
122
  return [...new Set([jsSibling, mjsSibling, cjsSibling, distStyle])];
112
123
  }
124
+ export class StaticDefinitionError extends Error {
125
+ filePath;
126
+ constructor(filePath, message) {
127
+ super(message);
128
+ this.filePath = filePath;
129
+ this.name = "StaticDefinitionError";
130
+ }
131
+ }
132
+ /** Evaluate an extracted object literal in an empty sandbox (no process, require, fetch, import). */
133
+ function evaluateObjectLiteral(objectLiteral, filename) {
134
+ const script = new vm.Script(`(${objectLiteral})`, { filename });
135
+ return script.runInNewContext(Object.freeze({ Math, Date, JSON }), {
136
+ timeout: 1000,
137
+ codeGeneration: { strings: false },
138
+ });
139
+ }
140
+ /**
141
+ * Load `marker({...})` from a project file statically. Throws StaticDefinitionError with a
142
+ * human-readable reason when the file is missing the marker or uses runtime values.
143
+ */
144
+ export async function loadStaticDefinition(filePath, marker) {
145
+ const source = await fs.readFile(filePath, "utf-8");
146
+ if (configSourceHasRuntimeReferences(source)) {
147
+ throw new StaticDefinitionError(filePath, `${path.basename(filePath)} references runtime values (process, require, fetch, import()). ` +
148
+ "Project files are read statically and never executed — use literal values only.");
149
+ }
150
+ const objectLiteral = extractDefinedObjectLiteral(source, marker);
151
+ if (!objectLiteral) {
152
+ throw new StaticDefinitionError(filePath, `${path.basename(filePath)} must export ${marker}{ ... }) with an object literal.`);
153
+ }
154
+ let evaluated;
155
+ try {
156
+ evaluated = evaluateObjectLiteral(objectLiteral, filePath);
157
+ }
158
+ catch (err) {
159
+ throw new StaticDefinitionError(filePath, `${path.basename(filePath)} could not be read: ${err instanceof Error ? err.message : String(err)}`);
160
+ }
161
+ if (!evaluated || typeof evaluated !== "object" || Array.isArray(evaluated)) {
162
+ throw new StaticDefinitionError(filePath, `${path.basename(filePath)}: ${marker}...) must receive an object.`);
163
+ }
164
+ return evaluated;
165
+ }
113
166
  /**
114
167
  * Parse `defineDuctConfig({...})` as a JSON-safe object literal.
115
168
  * Rejects configs that reference runtime values; does not expose `process`.
@@ -126,11 +179,7 @@ export async function loadConfigFromSource(configPath) {
126
179
  if (configSourceHasRuntimeReferences(objectLiteral)) {
127
180
  throw new ConfigRuntimeReferenceError();
128
181
  }
129
- const script = new vm.Script(`(${objectLiteral})`, { filename: configPath });
130
- const evaluated = script.runInNewContext(Object.freeze({ Math, Date, JSON }), {
131
- timeout: 1000,
132
- codeGeneration: { strings: false },
133
- });
182
+ const evaluated = evaluateObjectLiteral(objectLiteral, configPath);
134
183
  if (!evaluated || typeof evaluated !== "object") {
135
184
  return null;
136
185
  }
@@ -0,0 +1,17 @@
1
+ import { type DuctAuth } from "./cloud.js";
2
+ export interface DeviceStart {
3
+ device_code: string;
4
+ user_code: string;
5
+ verification_uri: string;
6
+ verification_uri_complete: string;
7
+ expires_in: number;
8
+ interval: number;
9
+ }
10
+ /** Best effort: open the URL in the default browser; the URL is always printed as well. */
11
+ export declare function openBrowser(url: string): void;
12
+ export declare function startDeviceLogin(existing: DuctAuth | null): Promise<{
13
+ base: string;
14
+ start: DeviceStart;
15
+ }>;
16
+ /** Poll until the request is approved, denied, or expires; then validate and save the key. */
17
+ export declare function waitForDeviceApproval(base: string, start: DeviceStart, existing: DuctAuth | null): Promise<DuctAuth>;
@@ -0,0 +1,75 @@
1
+ // ============================================================
2
+ // @duct-sdk/sdk — sign in through the browser
3
+ //
4
+ // `duct login` asks Duct for a short code, opens the dashboard so a signed-in owner or admin can
5
+ // approve this machine, and polls until Duct hands back an API key made for this device. Nothing
6
+ // is pasted into the terminal, other keys keep working, and the dashboard records who approved
7
+ // which machine. CI and SSH sessions keep using DUCT_API_KEY or `login --token`.
8
+ // ============================================================
9
+ import { spawn } from "child_process";
10
+ import * as os from "os";
11
+ import { getCandidateAuthBases } from "../core/endpoints.js";
12
+ import { CloudError, loginWithKey } from "./cloud.js";
13
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
14
+ /** Best effort: open the URL in the default browser; the URL is always printed as well. */
15
+ export function openBrowser(url) {
16
+ if (process.env.CI === "true" || process.env.DUCT_NO_BROWSER === "1")
17
+ return;
18
+ try {
19
+ const [cmd, args] = process.platform === "win32"
20
+ ? ["cmd", ["/c", "start", "", url]]
21
+ : process.platform === "darwin"
22
+ ? ["open", [url]]
23
+ : ["xdg-open", [url]];
24
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
25
+ child.on("error", () => { });
26
+ child.unref();
27
+ }
28
+ catch {
29
+ /* printed URL is the fallback */
30
+ }
31
+ }
32
+ async function postJson(url, body) {
33
+ const res = await fetch(url, {
34
+ method: "POST",
35
+ headers: { "Content-Type": "application/json" },
36
+ body: JSON.stringify(body),
37
+ signal: AbortSignal.timeout(15_000),
38
+ });
39
+ return { status: res.status, data: (await res.json().catch(() => ({}))) };
40
+ }
41
+ export async function startDeviceLogin(existing) {
42
+ let lastError = null;
43
+ const clientName = `${os.userInfo().username}@${os.hostname()}`.slice(0, 80);
44
+ for (const base of getCandidateAuthBases(existing)) {
45
+ try {
46
+ const { status, data } = await postJson(`${base}/v1/cli/device`, { client_name: clientName });
47
+ if (status === 201 && data.device_code)
48
+ return { base, start: data };
49
+ lastError = new CloudError(data.message ?? `Could not start sign-in (HTTP ${status})`, status);
50
+ }
51
+ catch (err) {
52
+ lastError = err;
53
+ }
54
+ }
55
+ throw lastError instanceof Error ? lastError : new CloudError("Could not reach Duct to start sign-in.");
56
+ }
57
+ /** Poll until the request is approved, denied, or expires; then validate and save the key. */
58
+ export async function waitForDeviceApproval(base, start, existing) {
59
+ let interval = Math.max(1, start.interval) * 1000;
60
+ const deadline = Date.now() + start.expires_in * 1000;
61
+ while (Date.now() < deadline) {
62
+ await sleep(interval);
63
+ const { status, data } = await postJson(`${base}/v1/cli/device/token`, { device_code: start.device_code });
64
+ if (status === 200 && data.api_key)
65
+ return loginWithKey(data.api_key, existing);
66
+ if (data.error === "authorization_pending")
67
+ continue;
68
+ if (data.error === "slow_down") {
69
+ interval = Math.max(interval + 5000, (data.interval ?? 0) * 1000);
70
+ continue;
71
+ }
72
+ throw new CloudError(data.message ?? "Sign-in did not complete.", status, data.error);
73
+ }
74
+ throw new CloudError("The sign-in code expired. Run `npx @duct-sdk/sdk login` again.", 400, "expired_token");
75
+ }
package/dist/cli/drift.js CHANGED
@@ -300,7 +300,7 @@ export async function runDriftCheck(config) {
300
300
  // ----------------------------------------------------------------
301
301
  export function printDriftReport(report) {
302
302
  const { drifted, routeDrifted, ok } = report;
303
- console.log(`\n ◆ Drift Report\n`);
303
+ console.log(`\n Drift Report\n`);
304
304
  if (report.totalActions === 0 && report.totalRoutes === 0) {
305
305
  console.log(chalk.gray(" No actions or routes defined in config.\n"));
306
306
  return;
@@ -310,7 +310,7 @@ export function printDriftReport(report) {
310
310
  console.log(chalk.bold(" API Actions:"));
311
311
  for (const r of drifted) {
312
312
  const color = r.status === "missing" ? chalk.red : chalk.yellow;
313
- console.log(` ${color("⚠")} [${r.endpoint}] ${color(r.code ?? r.status)}`);
313
+ console.log(` ${color("!")} [${r.endpoint}] ${color(r.code ?? r.status)}`);
314
314
  if (r.detail)
315
315
  console.log(` ${chalk.gray(r.detail)}`);
316
316
  }
@@ -321,7 +321,7 @@ export function printDriftReport(report) {
321
321
  console.log(chalk.bold(" Routes:"));
322
322
  for (const r of routeDrifted) {
323
323
  const color = r.status === "missing" ? chalk.red : chalk.yellow;
324
- console.log(` ${color("⚠")} [${r.routePath}] ${color(r.code ?? r.status)}`);
324
+ console.log(` ${color("!")} [${r.routePath}] ${color(r.code ?? r.status)}`);
325
325
  if (r.detail)
326
326
  console.log(` ${chalk.gray(r.detail)}`);
327
327
  }
@@ -340,7 +340,7 @@ export function printDriftReport(report) {
340
340
  console.log(` ${chalk.gray("–")} ${r.entityId} (${r.discoveryActionId}): ${chalk.gray("auth required — skipped")}`);
341
341
  }
342
342
  for (const r of dataIssues) {
343
- const icon = r.status === "empty" ? chalk.yellow("⚠") : chalk.red("✗");
343
+ const icon = r.status === "empty" ? chalk.yellow("!") : chalk.red("✗");
344
344
  const label = r.status === "empty" ? chalk.yellow("EMPTY") : chalk.red(r.status.toUpperCase());
345
345
  console.log(` ${icon} ${r.entityId} (${r.discoveryActionId}): ${label}`);
346
346
  if (r.detail)
@@ -350,8 +350,8 @@ export function printDriftReport(report) {
350
350
  }
351
351
  // Summary
352
352
  if (report.hasDrift) {
353
- console.log(chalk.gray(` Run "npx duct init --update" to regenerate config`));
354
- console.log(chalk.gray(` Run "npx duct push" to sync with Duct cloud\n`));
353
+ console.log(chalk.gray(` Run "npx @duct-sdk/sdk sync" to refresh actions from your API spec`));
354
+ console.log(chalk.gray(` Run "npx @duct-sdk/sdk push" to sync with Duct cloud\n`));
355
355
  }
356
356
  else {
357
357
  const total = ok.length + report.unreachable.length;
@@ -0,0 +1,3 @@
1
+ import type { DuctConfig } from "../../core/types.js";
2
+ export declare function generateIdentityContract(config: DuctConfig): string;
3
+ export declare function generateShellEmbed(config: DuctConfig, shellOrigin: string): string;
@@ -0,0 +1,97 @@
1
+ // ============================================================
2
+ // Language-neutral integration files for stacks the CLI has no template for
3
+ // (Django, Rails, Laravel, Spring, Go, .NET, mobile backends, plain HTML, ...).
4
+ //
5
+ // Duct only needs HTTP behaviour from your product, so instead of guessing a framework
6
+ // we describe the exact contract to implement in whatever you use.
7
+ // ============================================================
8
+ export function generateIdentityContract(config) {
9
+ const shellId = config.shellId ?? "<your shell id>";
10
+ const ttl = config.auth?.tokenExpirySeconds ?? 60;
11
+ return `# Duct identity — what your backend needs to do
12
+
13
+ Your stack was not recognised by the CLI, so this describes the integration in plain HTTP.
14
+ Implement it in any language. Shell: \`${shellId}\`. Secret: \`DUCT_SECRET_KEY\`
15
+ (Dashboard → Shell → Settings) — server-side only, never in client code.
16
+
17
+ The authoritative token format is TOKEN_SPEC.md in the @duct-sdk/sdk package, with
18
+ conformance vectors in fixtures/token-conformance-vectors.json — test your implementation
19
+ against them.
20
+
21
+ ## 1. Token endpoint — tell Duct who the signed-in user is
22
+
23
+ \`POST /api/duct/token\` (any path; configure it in the shell embed). Requires your normal
24
+ session. Respond \`401\` when nobody is signed in.
25
+
26
+ Response: \`{ "token": "<jwt>", "expiresAt": "<ISO 8601>" }\`
27
+
28
+ The token is a JWT signed with HS256 using \`DUCT_SECRET_KEY\`:
29
+
30
+ | Claim | Value |
31
+ |-----------|---------------------------------------------------------|
32
+ | \`type\` | \`"duct_delegated"\` |
33
+ | \`sub\` | your user id |
34
+ | \`iss\` | \`"${shellId}"\` |
35
+ | \`iat\` | now (unix seconds) |
36
+ | \`exp\` | now + ${ttl} seconds |
37
+ | \`session\` | object with the session fields Duct may forward (scalars only) |
38
+
39
+ ## 2. Deeplink receiver — land users on the right page
40
+
41
+ When Duct hands a user off to a page in your app it opens your receiver URL with a signed
42
+ token. Verify it (HS256, \`DUCT_SECRET_KEY\`, \`iss\` and \`aud\` equal \`${shellId}\`, \`exp\` in the
43
+ future), then redirect to the page named by \`deeplink_id\` with its parameters.
44
+
45
+ ## 3. Verify Duct calls on your API
46
+
47
+ Requests Duct forwards for a user carry the delegated token. On routes agents can reach,
48
+ verify it the same way (signature, \`type\`, \`iss\`, \`exp\`) and authorise the request as that
49
+ user, exactly as you would for your own session.
50
+
51
+ Node.js? \`@duct-sdk/sdk/server\` has \`generateDuctToken\`, \`verifyDuctToken\`, and
52
+ \`verifyDeeplinkToken\` for all three.
53
+ `;
54
+ }
55
+ export function generateShellEmbed(config, shellOrigin) {
56
+ const shellId = config.shellId ?? "<your shell id>";
57
+ return `<!--
58
+ Duct chat shell — plain HTML embed for any frontend (server-rendered pages, Angular,
59
+ jQuery, static sites). Mobile apps: load ${shellOrigin}/${shellId} in a WebView and bridge
60
+ the same two messages (DUCT_REQUEST_TOKEN, DUCT_DEEPLINK_NAVIGATE) to native code.
61
+ Paste before </body>. The token endpoint is the one from \`npx @duct-sdk/sdk add identity\`.
62
+ -->
63
+ <div id="duct-root"></div>
64
+ <script>
65
+ (function () {
66
+ var shellId = ${JSON.stringify(shellId)};
67
+ var shellOrigin = ${JSON.stringify(shellOrigin)};
68
+ var tokenEndpoint = '/api/duct/token';
69
+ var iframe = document.createElement('iframe');
70
+ iframe.src = shellOrigin + '/' + shellId;
71
+ iframe.title = 'Assistant';
72
+ iframe.style.cssText = 'position:fixed;right:24px;bottom:24px;width:380px;height:620px;border:0;border-radius:18px;z-index:9999';
73
+ document.getElementById('duct-root').appendChild(iframe);
74
+
75
+ window.addEventListener('message', function (event) {
76
+ if (event.origin !== shellOrigin || event.source !== iframe.contentWindow) return;
77
+ var message = event.data || {};
78
+ if (message.type === 'DUCT_REQUEST_TOKEN') {
79
+ fetch(tokenEndpoint, { method: 'POST', credentials: 'same-origin' })
80
+ .then(function (res) { return res.ok ? res.json() : {}; })
81
+ .then(function (data) {
82
+ iframe.contentWindow.postMessage(
83
+ { type: 'DUCT_TOKEN_RESPONSE', requestId: message.requestId, token: data.token || '' },
84
+ shellOrigin
85
+ );
86
+ });
87
+ }
88
+ // Only follow http(s) or same-site paths — never javascript: or data: URLs.
89
+ if (message.type === 'DUCT_DEEPLINK_NAVIGATE' && typeof message.url === 'string' &&
90
+ (/^https?:\\/\\//.test(message.url) || /^\\/(?!\\/)/.test(message.url))) {
91
+ window.location.href = message.url;
92
+ }
93
+ });
94
+ })();
95
+ </script>
96
+ `;
97
+ }