@duct-sdk/sdk 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +92 -0
- package/dist/adapters/next/index.d.ts +4 -0
- package/dist/adapters/next/index.js +5 -0
- package/dist/adapters/next/receiver.d.ts +44 -0
- package/dist/adapters/next/receiver.js +162 -0
- package/dist/adapters/next/shell.d.ts +88 -0
- package/dist/adapters/next/shell.js +255 -0
- package/dist/adapters/react/index.d.ts +2 -0
- package/dist/adapters/react/index.js +4 -0
- package/dist/adapters/react/shell.d.ts +88 -0
- package/dist/adapters/react/shell.js +255 -0
- package/dist/adapters/remix/index.d.ts +2 -0
- package/dist/adapters/remix/index.js +4 -0
- package/dist/adapters/remix/receiver.d.ts +44 -0
- package/dist/adapters/remix/receiver.js +153 -0
- package/dist/adapters/sveltekit/index.d.ts +2 -0
- package/dist/adapters/sveltekit/index.js +4 -0
- package/dist/adapters/sveltekit/receiver.d.ts +56 -0
- package/dist/adapters/sveltekit/receiver.js +154 -0
- package/dist/adapters/vite/index.d.ts +2 -0
- package/dist/adapters/vite/index.js +4 -0
- package/dist/adapters/vite/receiver.d.ts +82 -0
- package/dist/adapters/vite/receiver.js +164 -0
- package/dist/assets/logo.d.ts +1 -0
- package/dist/assets/logo.js +1 -0
- package/dist/cli/agents/api-agent.d.ts +14 -0
- package/dist/cli/agents/api-agent.js +656 -0
- package/dist/cli/agents/auth-agent.d.ts +6 -0
- package/dist/cli/agents/auth-agent.js +198 -0
- package/dist/cli/agents/deeplink-agent.d.ts +6 -0
- package/dist/cli/agents/deeplink-agent.js +263 -0
- package/dist/cli/agents/llm.d.ts +33 -0
- package/dist/cli/agents/llm.js +276 -0
- package/dist/cli/agents/pipeline.d.ts +51 -0
- package/dist/cli/agents/pipeline.js +236 -0
- package/dist/cli/agents/reviewer-agent.d.ts +11 -0
- package/dist/cli/agents/reviewer-agent.js +442 -0
- package/dist/cli/agents/route-agent.d.ts +13 -0
- package/dist/cli/agents/route-agent.js +346 -0
- package/dist/cli/detectors/auth.d.ts +18 -0
- package/dist/cli/detectors/auth.js +273 -0
- package/dist/cli/detectors/framework.d.ts +22 -0
- package/dist/cli/detectors/framework.js +242 -0
- package/dist/cli/drift.d.ts +39 -0
- package/dist/cli/drift.js +247 -0
- package/dist/cli/fs/sandbox.d.ts +77 -0
- package/dist/cli/fs/sandbox.js +295 -0
- package/dist/cli/generators/config.d.ts +7 -0
- package/dist/cli/generators/config.js +255 -0
- package/dist/cli/generators/receiver.d.ts +12 -0
- package/dist/cli/generators/receiver.js +683 -0
- package/dist/cli/generators/shell.d.ts +18 -0
- package/dist/cli/generators/shell.js +672 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +603 -0
- package/dist/cli/init.d.ts +26 -0
- package/dist/cli/init.js +835 -0
- package/dist/core/action.d.ts +37 -0
- package/dist/core/action.js +140 -0
- package/dist/core/config.d.ts +514 -0
- package/dist/core/config.js +221 -0
- package/dist/core/endpoints.d.ts +17 -0
- package/dist/core/endpoints.js +128 -0
- package/dist/core/token.d.ts +70 -0
- package/dist/core/token.js +174 -0
- package/dist/core/types.d.ts +450 -0
- package/dist/core/types.js +11 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +9 -0
- package/package.json +84 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @duct/sdk — Config Definition and Validation
|
|
3
|
+
// ============================================================
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
// ----------------------------------------------------------------
|
|
6
|
+
// Zod Schemas
|
|
7
|
+
// ----------------------------------------------------------------
|
|
8
|
+
const UIStateHintSchema = z.enum([
|
|
9
|
+
"form",
|
|
10
|
+
"list",
|
|
11
|
+
"detail",
|
|
12
|
+
"dashboard",
|
|
13
|
+
"modal",
|
|
14
|
+
"wizard",
|
|
15
|
+
"empty",
|
|
16
|
+
"error",
|
|
17
|
+
"auth",
|
|
18
|
+
"checkout",
|
|
19
|
+
"profile",
|
|
20
|
+
"settings",
|
|
21
|
+
"search",
|
|
22
|
+
]);
|
|
23
|
+
const RouteParamSchema = z.object({
|
|
24
|
+
name: z.string().min(1),
|
|
25
|
+
type: z.enum(["string", "number", "uuid", "slug"]),
|
|
26
|
+
required: z.boolean(),
|
|
27
|
+
description: z.string().optional(),
|
|
28
|
+
});
|
|
29
|
+
const QueryParamSchema = z.object({
|
|
30
|
+
name: z.string().min(1),
|
|
31
|
+
type: z.enum(["string", "number", "boolean", "string[]"]),
|
|
32
|
+
required: z.boolean(),
|
|
33
|
+
description: z.string().optional(),
|
|
34
|
+
defaultValue: z.union([z.string(), z.number(), z.boolean()]).optional(),
|
|
35
|
+
});
|
|
36
|
+
const RouteManifestSchema = z.object({
|
|
37
|
+
path: z.string().min(1).startsWith("/"),
|
|
38
|
+
name: z.string().min(1),
|
|
39
|
+
description: z.string().min(1),
|
|
40
|
+
params: z.array(RouteParamSchema).default([]),
|
|
41
|
+
queryParams: z.array(QueryParamSchema).default([]),
|
|
42
|
+
uiStateHint: UIStateHintSchema,
|
|
43
|
+
requiresAuth: z.boolean(),
|
|
44
|
+
deeplinkable: z.boolean(),
|
|
45
|
+
methods: z.array(z.string()).optional(),
|
|
46
|
+
});
|
|
47
|
+
const SensitivityLevelSchema = z.enum([
|
|
48
|
+
"none",
|
|
49
|
+
"low",
|
|
50
|
+
"medium",
|
|
51
|
+
"high",
|
|
52
|
+
"critical",
|
|
53
|
+
]);
|
|
54
|
+
const ActionParamSchema = z.object({
|
|
55
|
+
name: z.string().min(1),
|
|
56
|
+
type: z.enum(["string", "number", "boolean", "object", "array"]),
|
|
57
|
+
required: z.boolean(),
|
|
58
|
+
description: z.string().optional(),
|
|
59
|
+
schema: z.record(z.unknown()).optional(),
|
|
60
|
+
});
|
|
61
|
+
const ActionManifestSchema = z.object({
|
|
62
|
+
id: z
|
|
63
|
+
.string()
|
|
64
|
+
.min(1)
|
|
65
|
+
.regex(/^[a-z_][a-z0-9_]*$/, "Action IDs must be snake_case"),
|
|
66
|
+
name: z.string().min(1),
|
|
67
|
+
description: z.string().min(1),
|
|
68
|
+
method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]),
|
|
69
|
+
path: z.string().min(1).startsWith("/"),
|
|
70
|
+
agentAccessible: z.boolean(),
|
|
71
|
+
sideEffects: z.boolean(),
|
|
72
|
+
sensitivityLevel: SensitivityLevelSchema,
|
|
73
|
+
params: z.array(ActionParamSchema).default([]),
|
|
74
|
+
responseSchema: z.record(z.unknown()).optional(),
|
|
75
|
+
requiresAuth: z.boolean(),
|
|
76
|
+
rateLimit: z.number().positive().optional(),
|
|
77
|
+
});
|
|
78
|
+
const AuthStrategySchema = z.enum([
|
|
79
|
+
"nextauth",
|
|
80
|
+
"clerk",
|
|
81
|
+
"auth0",
|
|
82
|
+
"custom-jwt",
|
|
83
|
+
"session-cookie",
|
|
84
|
+
"none",
|
|
85
|
+
"unknown",
|
|
86
|
+
]);
|
|
87
|
+
const AuthSchemaSchema = z.object({
|
|
88
|
+
strategy: AuthStrategySchema,
|
|
89
|
+
sessionFields: z.array(z.string()).default([]),
|
|
90
|
+
guestAllowed: z.boolean(),
|
|
91
|
+
tokenExpirySeconds: z.number().positive().default(60),
|
|
92
|
+
tokenEndpoint: z.string().url().optional(),
|
|
93
|
+
customClaims: z.record(z.string()).optional(),
|
|
94
|
+
});
|
|
95
|
+
const StateFieldSchema = z.object({
|
|
96
|
+
key: z.string().min(1),
|
|
97
|
+
type: z.enum(["string", "number", "boolean", "object"]),
|
|
98
|
+
required: z.boolean(),
|
|
99
|
+
description: z.string().optional(),
|
|
100
|
+
sessionSource: z.string().optional(),
|
|
101
|
+
});
|
|
102
|
+
const DeeplinkDefinitionSchema = z.object({
|
|
103
|
+
id: z
|
|
104
|
+
.string()
|
|
105
|
+
.min(1)
|
|
106
|
+
.regex(/^[a-z_][a-z0-9_]*$/, "Deeplink IDs must be snake_case"),
|
|
107
|
+
name: z.string().min(1),
|
|
108
|
+
description: z.string().min(1),
|
|
109
|
+
targetRoute: z.string().min(1).startsWith("/"),
|
|
110
|
+
stateFields: z.array(StateFieldSchema).default([]),
|
|
111
|
+
expirySeconds: z.number().positive().default(300),
|
|
112
|
+
requiresAuth: z.boolean(),
|
|
113
|
+
intent: z.string().optional(),
|
|
114
|
+
});
|
|
115
|
+
const AgentPermissionLevelSchema = z.enum([
|
|
116
|
+
"none",
|
|
117
|
+
"read",
|
|
118
|
+
"write",
|
|
119
|
+
"admin",
|
|
120
|
+
]);
|
|
121
|
+
const AgentPermissionsSchema = z.object({
|
|
122
|
+
defaultLevel: AgentPermissionLevelSchema,
|
|
123
|
+
actionOverrides: z.record(AgentPermissionLevelSchema).optional(),
|
|
124
|
+
allowedAgents: z.array(z.string()).optional(),
|
|
125
|
+
requireUserConsent: z.boolean(),
|
|
126
|
+
allowedActions: z.array(z.string()).optional(),
|
|
127
|
+
});
|
|
128
|
+
const WidgetConfigSchema = z.object({
|
|
129
|
+
primaryColor: z.string().optional(),
|
|
130
|
+
position: z
|
|
131
|
+
.enum(["bottom-right", "bottom-left", "top-right", "top-left"])
|
|
132
|
+
.optional(),
|
|
133
|
+
defaultOpen: z.boolean().optional(),
|
|
134
|
+
launcherText: z.string().optional(),
|
|
135
|
+
welcomeMessage: z.string().optional(),
|
|
136
|
+
hideLauncher: z.boolean().optional(),
|
|
137
|
+
});
|
|
138
|
+
const ProductConfigSchema = z.object({
|
|
139
|
+
name: z.string().min(1),
|
|
140
|
+
description: z.string().min(1),
|
|
141
|
+
baseUrl: z.string().url(),
|
|
142
|
+
locale: z.string().optional(),
|
|
143
|
+
industry: z.string().optional(),
|
|
144
|
+
});
|
|
145
|
+
export const DuctConfigSchema = z.object({
|
|
146
|
+
shellId: z
|
|
147
|
+
.string()
|
|
148
|
+
.min(1)
|
|
149
|
+
.regex(/^shell_[a-z0-9_]+$/, 'Shell IDs must match pattern: shell_<company>_<env>'),
|
|
150
|
+
product: ProductConfigSchema,
|
|
151
|
+
auth: AuthSchemaSchema,
|
|
152
|
+
routes: z.array(RouteManifestSchema).default([]),
|
|
153
|
+
actions: z.array(ActionManifestSchema).default([]),
|
|
154
|
+
deeplinks: z.array(DeeplinkDefinitionSchema).default([]),
|
|
155
|
+
agentPermissions: AgentPermissionsSchema,
|
|
156
|
+
widget: WidgetConfigSchema.optional(),
|
|
157
|
+
});
|
|
158
|
+
/**
|
|
159
|
+
* Define and validate a Duct configuration.
|
|
160
|
+
* This is the primary entrypoint for companies configuring their Duct shell.
|
|
161
|
+
*
|
|
162
|
+
* @example
|
|
163
|
+
* ```ts
|
|
164
|
+
* import { defineDuctConfig } from '@duct/sdk';
|
|
165
|
+
*
|
|
166
|
+
* export default defineDuctConfig({
|
|
167
|
+
* shellId: 'shell_acme_prod',
|
|
168
|
+
* product: {
|
|
169
|
+
* name: 'Acme Corp',
|
|
170
|
+
* description: 'B2B SaaS for widget management',
|
|
171
|
+
* baseUrl: 'https://app.acme.com',
|
|
172
|
+
* },
|
|
173
|
+
* auth: {
|
|
174
|
+
* strategy: 'nextauth',
|
|
175
|
+
* sessionFields: ['id', 'email', 'orgId'],
|
|
176
|
+
* guestAllowed: false,
|
|
177
|
+
* tokenExpirySeconds: 300,
|
|
178
|
+
* },
|
|
179
|
+
* routes: [...],
|
|
180
|
+
* actions: [...],
|
|
181
|
+
* deeplinks: [...],
|
|
182
|
+
* agentPermissions: {
|
|
183
|
+
* defaultLevel: 'none',
|
|
184
|
+
* requireUserConsent: true,
|
|
185
|
+
* },
|
|
186
|
+
* });
|
|
187
|
+
* ```
|
|
188
|
+
*/
|
|
189
|
+
export function defineDuctConfig(config) {
|
|
190
|
+
const result = DuctConfigSchema.safeParse(config);
|
|
191
|
+
if (!result.success) {
|
|
192
|
+
const formatted = result.error.errors
|
|
193
|
+
.map((e) => ` • [${e.path.join(".")}] ${e.message}`)
|
|
194
|
+
.join("\n");
|
|
195
|
+
throw new Error(`Invalid Duct configuration:\n${formatted}\n\nSee https://docs.duct.sh/config for reference.`);
|
|
196
|
+
}
|
|
197
|
+
// Cross-validate: deeplink target routes must exist in routes list
|
|
198
|
+
const routePaths = new Set(result.data.routes.map((r) => r.path));
|
|
199
|
+
const deeplinkErrors = [];
|
|
200
|
+
for (const deeplink of result.data.deeplinks) {
|
|
201
|
+
// Normalize dynamic segments for comparison
|
|
202
|
+
const normalizedTarget = deeplink.targetRoute.replace(/\[([^\]]+)\]/g, ":$1");
|
|
203
|
+
const normalizedRoutes = Array.from(routePaths).map((p) => p.replace(/\[([^\]]+)\]/g, ":$1"));
|
|
204
|
+
if (!normalizedRoutes.some((r) => r === normalizedTarget || routePaths.has(deeplink.targetRoute))) {
|
|
205
|
+
deeplinkErrors.push(`Deeplink "${deeplink.id}" targets route "${deeplink.targetRoute}" which is not defined in routes[]`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (deeplinkErrors.length > 0) {
|
|
209
|
+
throw new Error(`Duct configuration validation errors:\n${deeplinkErrors.map((e) => ` • ${e}`).join("\n")}`);
|
|
210
|
+
}
|
|
211
|
+
// Cross-validate: agent permission actionOverrides must reference valid action IDs
|
|
212
|
+
const actionIds = new Set(result.data.actions.map((a) => a.id));
|
|
213
|
+
if (result.data.agentPermissions.actionOverrides) {
|
|
214
|
+
for (const actionId of Object.keys(result.data.agentPermissions.actionOverrides)) {
|
|
215
|
+
if (!actionIds.has(actionId)) {
|
|
216
|
+
throw new Error(`agentPermissions.actionOverrides references unknown action ID: "${actionId}"`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return result.data;
|
|
221
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface EndpointProfile {
|
|
2
|
+
apiBase?: string;
|
|
3
|
+
dashboardUrl?: string;
|
|
4
|
+
}
|
|
5
|
+
export declare function getAuthUrl(): string;
|
|
6
|
+
export declare function getActiveApiBase(profile?: EndpointProfile | null): string;
|
|
7
|
+
export declare function getManifestApiBase(profile?: EndpointProfile | null): string;
|
|
8
|
+
export declare function getShellRuntimeUrl(): string;
|
|
9
|
+
export declare function getRegistryUrl(): string;
|
|
10
|
+
export declare function getConfiguredDashboard(profile?: EndpointProfile | null): string;
|
|
11
|
+
export declare function getManifestApiBases(profile?: EndpointProfile | null): string[];
|
|
12
|
+
export declare function getCandidateApiBases(profile?: EndpointProfile | null): string[];
|
|
13
|
+
export declare function getCandidateAuthBases(profile?: EndpointProfile | null): string[];
|
|
14
|
+
export declare const DUCT_ENDPOINT_DEFAULTS: {
|
|
15
|
+
readonly apiBase: string;
|
|
16
|
+
readonly dashboardUrl: string;
|
|
17
|
+
};
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @duct/sdk — Endpoint Resolution
|
|
3
|
+
//
|
|
4
|
+
// Single-source-of-truth: set DUCT_URL in your .env and all
|
|
5
|
+
// sub-service URLs are derived automatically from it.
|
|
6
|
+
//
|
|
7
|
+
// Override any individual service URL explicitly if needed:
|
|
8
|
+
// DUCT_AUTH_URL — auth service (default: {base}/auth or :3001)
|
|
9
|
+
// DUCT_API_URL — agent-proxy (default: {base}/api or :3002)
|
|
10
|
+
// DUCT_SHELL_URL — shell runtime (default: {base}/shell or :3000)
|
|
11
|
+
// DUCT_REGISTRY_URL — shell registry (default: {base}/registry or :3003)
|
|
12
|
+
// DUCT_DASHBOARD_URL— dashboard (default: {base}/dash or :3004)
|
|
13
|
+
//
|
|
14
|
+
// Priority (highest wins):
|
|
15
|
+
// 1. Explicit service URL env var (e.g. DUCT_API_URL)
|
|
16
|
+
// 2. Saved auth profile (~/.duct/auth.json, written by `duct login`)
|
|
17
|
+
// 3. DUCT_URL base + subdomain derivation
|
|
18
|
+
// 4. Localhost fallbacks for local dev
|
|
19
|
+
// ============================================================
|
|
20
|
+
// ── Core helpers ─────────────────────────────────────────────────
|
|
21
|
+
function stripTrailingSlash(s) {
|
|
22
|
+
return s.trim().replace(/\/+$/, "");
|
|
23
|
+
}
|
|
24
|
+
function env(key) {
|
|
25
|
+
return stripTrailingSlash(process.env[key] ?? "");
|
|
26
|
+
}
|
|
27
|
+
function toApiCandidates(base) {
|
|
28
|
+
const normalized = stripTrailingSlash(base);
|
|
29
|
+
if (!normalized)
|
|
30
|
+
return [];
|
|
31
|
+
const candidates = [];
|
|
32
|
+
if (normalized.includes(":3001")) {
|
|
33
|
+
candidates.push(normalized.replace(":3001", ":3002"));
|
|
34
|
+
}
|
|
35
|
+
if (normalized.includes("//auth.")) {
|
|
36
|
+
candidates.push(normalized.replace("//auth.", "//api."));
|
|
37
|
+
}
|
|
38
|
+
candidates.push(normalized);
|
|
39
|
+
return [...new Set(candidates)];
|
|
40
|
+
}
|
|
41
|
+
function toAuthCandidates(base) {
|
|
42
|
+
const normalized = stripTrailingSlash(base);
|
|
43
|
+
if (!normalized)
|
|
44
|
+
return [];
|
|
45
|
+
const candidates = [];
|
|
46
|
+
if (normalized.includes(":3002")) {
|
|
47
|
+
candidates.push(normalized.replace(":3002", ":3001"));
|
|
48
|
+
}
|
|
49
|
+
if (normalized.includes("//api.")) {
|
|
50
|
+
candidates.push(normalized.replace("//api.", "//auth."));
|
|
51
|
+
}
|
|
52
|
+
candidates.push(normalized);
|
|
53
|
+
return [...new Set(candidates)];
|
|
54
|
+
}
|
|
55
|
+
// ── Base URL derivation ──────────────────────────────────────────
|
|
56
|
+
//
|
|
57
|
+
// If DUCT_URL=https://myco.com → services get subdomains
|
|
58
|
+
// auth.myco.com / api.myco.com / shell.myco.com etc.
|
|
59
|
+
// If DUCT_URL is not set → localhost defaults
|
|
60
|
+
function getDuctBaseUrl() {
|
|
61
|
+
return env("DUCT_URL");
|
|
62
|
+
}
|
|
63
|
+
function deriveSubdomain(base, sub, localPort) {
|
|
64
|
+
if (!base)
|
|
65
|
+
return `http://localhost:${localPort}`;
|
|
66
|
+
try {
|
|
67
|
+
const url = new URL(base);
|
|
68
|
+
// e.g. https://myco.com → https://api.myco.com
|
|
69
|
+
return `${url.protocol}//${sub}.${url.host}`;
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return `http://localhost:${localPort}`;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
// ── Service URL resolution ───────────────────────────────────────
|
|
76
|
+
export function getAuthUrl() {
|
|
77
|
+
return env("DUCT_AUTH_URL") || deriveSubdomain(getDuctBaseUrl(), "auth", 3001);
|
|
78
|
+
}
|
|
79
|
+
export function getActiveApiBase(profile) {
|
|
80
|
+
const candidates = getManifestApiBases(profile);
|
|
81
|
+
return candidates[0] ?? "http://localhost:3002";
|
|
82
|
+
}
|
|
83
|
+
export function getManifestApiBase(profile) {
|
|
84
|
+
// Manifest lives in agent-proxy — same as the API base
|
|
85
|
+
const bases = getManifestApiBases(profile);
|
|
86
|
+
return bases[0] ?? "http://localhost:3002";
|
|
87
|
+
}
|
|
88
|
+
export function getShellRuntimeUrl() {
|
|
89
|
+
return env("DUCT_SHELL_URL") || deriveSubdomain(getDuctBaseUrl(), "shell", 3000);
|
|
90
|
+
}
|
|
91
|
+
export function getRegistryUrl() {
|
|
92
|
+
return env("DUCT_REGISTRY_URL") || deriveSubdomain(getDuctBaseUrl(), "registry", 3003);
|
|
93
|
+
}
|
|
94
|
+
export function getConfiguredDashboard(profile) {
|
|
95
|
+
return (env("DUCT_DASHBOARD_URL") ||
|
|
96
|
+
stripTrailingSlash(profile?.dashboardUrl ?? "") ||
|
|
97
|
+
deriveSubdomain(getDuctBaseUrl(), "dash", 3004));
|
|
98
|
+
}
|
|
99
|
+
// ── Backward-compat helpers (used internally) ────────────────────
|
|
100
|
+
export function getManifestApiBases(profile) {
|
|
101
|
+
const configured = [
|
|
102
|
+
env("DUCT_MANIFEST_URL"),
|
|
103
|
+
env("DUCT_API_URL"),
|
|
104
|
+
stripTrailingSlash(profile?.apiBase ?? ""),
|
|
105
|
+
deriveSubdomain(getDuctBaseUrl(), "api", 3002),
|
|
106
|
+
"http://localhost:3002",
|
|
107
|
+
].filter(Boolean);
|
|
108
|
+
const expanded = configured.flatMap((base) => toApiCandidates(base));
|
|
109
|
+
return [...new Set(expanded)].filter(Boolean);
|
|
110
|
+
}
|
|
111
|
+
export function getCandidateApiBases(profile) {
|
|
112
|
+
return getManifestApiBases(profile);
|
|
113
|
+
}
|
|
114
|
+
export function getCandidateAuthBases(profile) {
|
|
115
|
+
const configured = [
|
|
116
|
+
env("DUCT_AUTH_URL"),
|
|
117
|
+
stripTrailingSlash(profile?.apiBase ?? ""),
|
|
118
|
+
deriveSubdomain(getDuctBaseUrl(), "auth", 3001),
|
|
119
|
+
"http://localhost:3001",
|
|
120
|
+
].filter(Boolean);
|
|
121
|
+
const expanded = configured.flatMap((base) => toAuthCandidates(base));
|
|
122
|
+
return [...new Set(expanded)].filter(Boolean);
|
|
123
|
+
}
|
|
124
|
+
// Legacy export kept for any existing imports
|
|
125
|
+
export const DUCT_ENDPOINT_DEFAULTS = {
|
|
126
|
+
get apiBase() { return getActiveApiBase(); },
|
|
127
|
+
get dashboardUrl() { return getConfiguredDashboard(); },
|
|
128
|
+
};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { DuctTokenPayload, DeeplinkTokenPayload } from "./types.js";
|
|
2
|
+
export interface GenerateTokenOptions {
|
|
3
|
+
/** HMAC-SHA256 secret key (at least 32 characters recommended) */
|
|
4
|
+
secretKey: string;
|
|
5
|
+
/** User session data — only scalar values will be included */
|
|
6
|
+
userSession: Record<string, unknown> & {
|
|
7
|
+
id?: string;
|
|
8
|
+
sub?: string;
|
|
9
|
+
};
|
|
10
|
+
/** Shell ID (issuer) */
|
|
11
|
+
shellId: string;
|
|
12
|
+
/** Token expiry in seconds (default: 60) */
|
|
13
|
+
expirySeconds?: number;
|
|
14
|
+
/** Action IDs this token is permitted to invoke */
|
|
15
|
+
allowedActions?: string[];
|
|
16
|
+
}
|
|
17
|
+
export interface GenerateTokenResult {
|
|
18
|
+
token: string;
|
|
19
|
+
expiresAt: Date;
|
|
20
|
+
payload: Omit<DuctTokenPayload, "iat" | "exp">;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Generate a Duct delegated token for a user session.
|
|
24
|
+
* This token is passed to the Duct shell to authenticate the user.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* const { token } = await generateDuctToken({
|
|
29
|
+
* secretKey: process.env.DUCT_SECRET_KEY!,
|
|
30
|
+
* shellId: 'shell_acme_prod',
|
|
31
|
+
* userSession: { id: user.id, email: user.email, orgId: user.orgId },
|
|
32
|
+
* expirySeconds: 300,
|
|
33
|
+
* allowedActions: ['get_orders', 'get_profile'],
|
|
34
|
+
* });
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export declare function generateDuctToken(options: GenerateTokenOptions): Promise<GenerateTokenResult>;
|
|
38
|
+
export interface VerifyTokenOptions {
|
|
39
|
+
/** HMAC-SHA256 secret key */
|
|
40
|
+
secretKey: string;
|
|
41
|
+
/** Expected issuer (shell ID) */
|
|
42
|
+
expectedShellId?: string;
|
|
43
|
+
}
|
|
44
|
+
export interface VerifyTokenResult {
|
|
45
|
+
valid: boolean;
|
|
46
|
+
payload?: DuctTokenPayload;
|
|
47
|
+
error?: string;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Verify a Duct delegated token.
|
|
51
|
+
* Returns the decoded payload if valid, or an error message if not.
|
|
52
|
+
*/
|
|
53
|
+
export declare function verifyDuctToken(token: string, options: VerifyTokenOptions): Promise<VerifyTokenResult>;
|
|
54
|
+
export interface VerifyDeeplinkTokenOptions {
|
|
55
|
+
/** HMAC-SHA256 secret key */
|
|
56
|
+
secretKey: string;
|
|
57
|
+
/** Expected issuer (shell ID) */
|
|
58
|
+
expectedShellId?: string;
|
|
59
|
+
/** Expected deeplink ID */
|
|
60
|
+
expectedDeeplinkId?: string;
|
|
61
|
+
}
|
|
62
|
+
export interface VerifyDeeplinkResult {
|
|
63
|
+
valid: boolean;
|
|
64
|
+
payload?: DeeplinkTokenPayload;
|
|
65
|
+
error?: string;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Verify a Duct deeplink token (received at the receiver endpoint).
|
|
69
|
+
*/
|
|
70
|
+
export declare function verifyDeeplinkToken(token: string, options: VerifyDeeplinkTokenOptions): Promise<VerifyDeeplinkResult>;
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @duct/sdk — Token Generation and Verification
|
|
3
|
+
// ============================================================
|
|
4
|
+
import { SignJWT, jwtVerify } from "jose";
|
|
5
|
+
// ----------------------------------------------------------------
|
|
6
|
+
// Helpers
|
|
7
|
+
// ----------------------------------------------------------------
|
|
8
|
+
/**
|
|
9
|
+
* Convert a secret string to a Uint8Array for jose.
|
|
10
|
+
*/
|
|
11
|
+
function encodeSecret(secret) {
|
|
12
|
+
return new TextEncoder().encode(secret);
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Filter a session object to only scalar values (no nested objects, arrays,
|
|
16
|
+
* or token-like strings). Prevents leaking sensitive data into JWTs.
|
|
17
|
+
*/
|
|
18
|
+
function filterScalars(session) {
|
|
19
|
+
const result = {};
|
|
20
|
+
for (const [key, value] of Object.entries(session)) {
|
|
21
|
+
// Skip anything that looks like a token, password, or secret
|
|
22
|
+
const lowerKey = key.toLowerCase();
|
|
23
|
+
if (lowerKey.includes("token") ||
|
|
24
|
+
lowerKey.includes("secret") ||
|
|
25
|
+
lowerKey.includes("password") ||
|
|
26
|
+
lowerKey.includes("key") ||
|
|
27
|
+
lowerKey.includes("hash") ||
|
|
28
|
+
lowerKey.includes("salt") ||
|
|
29
|
+
lowerKey.includes("credential")) {
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
// Only accept scalar values
|
|
33
|
+
if (typeof value === "string" ||
|
|
34
|
+
typeof value === "number" ||
|
|
35
|
+
typeof value === "boolean" ||
|
|
36
|
+
value === null) {
|
|
37
|
+
result[key] = value;
|
|
38
|
+
}
|
|
39
|
+
// Skip nested objects, arrays, undefined, functions, symbols
|
|
40
|
+
}
|
|
41
|
+
return result;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Generate a Duct delegated token for a user session.
|
|
45
|
+
* This token is passed to the Duct shell to authenticate the user.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```ts
|
|
49
|
+
* const { token } = await generateDuctToken({
|
|
50
|
+
* secretKey: process.env.DUCT_SECRET_KEY!,
|
|
51
|
+
* shellId: 'shell_acme_prod',
|
|
52
|
+
* userSession: { id: user.id, email: user.email, orgId: user.orgId },
|
|
53
|
+
* expirySeconds: 300,
|
|
54
|
+
* allowedActions: ['get_orders', 'get_profile'],
|
|
55
|
+
* });
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
export async function generateDuctToken(options) {
|
|
59
|
+
const { secretKey, userSession, shellId, expirySeconds = 60, allowedActions, } = options;
|
|
60
|
+
if (!secretKey || secretKey.length < 16) {
|
|
61
|
+
throw new Error("DUCT_SECRET_KEY must be at least 16 characters. Use a strong random secret in production.");
|
|
62
|
+
}
|
|
63
|
+
const sub = String(userSession.id ?? userSession.sub ?? "anonymous");
|
|
64
|
+
const filteredSession = filterScalars(userSession);
|
|
65
|
+
const now = Math.floor(Date.now() / 1000);
|
|
66
|
+
const exp = now + expirySeconds;
|
|
67
|
+
const payload = {
|
|
68
|
+
type: "duct_delegated",
|
|
69
|
+
session: filteredSession,
|
|
70
|
+
};
|
|
71
|
+
if (allowedActions && allowedActions.length > 0) {
|
|
72
|
+
payload.allowedActions = allowedActions;
|
|
73
|
+
}
|
|
74
|
+
const token = await new SignJWT(payload)
|
|
75
|
+
.setProtectedHeader({ alg: "HS256" })
|
|
76
|
+
.setSubject(sub)
|
|
77
|
+
.setIssuer(shellId)
|
|
78
|
+
.setIssuedAt(now)
|
|
79
|
+
.setExpirationTime(exp)
|
|
80
|
+
.sign(encodeSecret(secretKey));
|
|
81
|
+
return {
|
|
82
|
+
token,
|
|
83
|
+
expiresAt: new Date(exp * 1000),
|
|
84
|
+
payload: {
|
|
85
|
+
type: "duct_delegated",
|
|
86
|
+
sub,
|
|
87
|
+
iss: shellId,
|
|
88
|
+
session: filteredSession,
|
|
89
|
+
allowedActions,
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Verify a Duct delegated token.
|
|
95
|
+
* Returns the decoded payload if valid, or an error message if not.
|
|
96
|
+
*/
|
|
97
|
+
export async function verifyDuctToken(token, options) {
|
|
98
|
+
const { secretKey, expectedShellId } = options;
|
|
99
|
+
try {
|
|
100
|
+
const { payload } = await jwtVerify(token, encodeSecret(secretKey), {
|
|
101
|
+
algorithms: ["HS256"],
|
|
102
|
+
issuer: expectedShellId,
|
|
103
|
+
});
|
|
104
|
+
const typedPayload = payload;
|
|
105
|
+
if (typedPayload.type !== "duct_delegated") {
|
|
106
|
+
return {
|
|
107
|
+
valid: false,
|
|
108
|
+
error: `Invalid token type: expected "duct_delegated", got "${typedPayload.type}"`,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
valid: true,
|
|
113
|
+
payload: {
|
|
114
|
+
type: "duct_delegated",
|
|
115
|
+
sub: typedPayload.sub ?? "",
|
|
116
|
+
iss: typedPayload.iss ?? "",
|
|
117
|
+
iat: typedPayload.iat ?? 0,
|
|
118
|
+
exp: typedPayload.exp ?? 0,
|
|
119
|
+
session: typedPayload.session ?? {},
|
|
120
|
+
allowedActions: typedPayload.allowedActions,
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
catch (err) {
|
|
125
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
126
|
+
return {
|
|
127
|
+
valid: false,
|
|
128
|
+
error: `Token verification failed: ${message}`,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Verify a Duct deeplink token (received at the receiver endpoint).
|
|
134
|
+
*/
|
|
135
|
+
export async function verifyDeeplinkToken(token, options) {
|
|
136
|
+
const { secretKey, expectedShellId, expectedDeeplinkId } = options;
|
|
137
|
+
try {
|
|
138
|
+
const { payload } = await jwtVerify(token, encodeSecret(secretKey), {
|
|
139
|
+
algorithms: ["HS256"],
|
|
140
|
+
issuer: expectedShellId,
|
|
141
|
+
});
|
|
142
|
+
const typedPayload = payload;
|
|
143
|
+
if (!typedPayload.deeplink_id) {
|
|
144
|
+
return {
|
|
145
|
+
valid: false,
|
|
146
|
+
error: "Token is missing deeplink_id claim",
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
if (expectedDeeplinkId && typedPayload.deeplink_id !== expectedDeeplinkId) {
|
|
150
|
+
return {
|
|
151
|
+
valid: false,
|
|
152
|
+
error: `Deeplink ID mismatch: expected "${expectedDeeplinkId}", got "${typedPayload.deeplink_id}"`,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
valid: true,
|
|
157
|
+
payload: {
|
|
158
|
+
deeplink_id: typedPayload.deeplink_id,
|
|
159
|
+
sub: typedPayload.sub ?? "",
|
|
160
|
+
iss: typedPayload.iss ?? "",
|
|
161
|
+
iat: typedPayload.iat ?? 0,
|
|
162
|
+
exp: typedPayload.exp ?? 0,
|
|
163
|
+
state: typedPayload.state ?? {},
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
catch (err) {
|
|
168
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
169
|
+
return {
|
|
170
|
+
valid: false,
|
|
171
|
+
error: `Deeplink token verification failed: ${message}`,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
}
|