@dexto/agent-management 1.14.6 → 1.15.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/auth/dexto-accounts.cjs +277 -0
  2. package/dist/auth/dexto-accounts.d.ts +144 -0
  3. package/dist/auth/dexto-accounts.d.ts.map +1 -0
  4. package/dist/auth/dexto-accounts.js +230 -0
  5. package/dist/auth/dexto-cloud.cjs +51 -0
  6. package/dist/auth/dexto-cloud.d.ts +9 -0
  7. package/dist/auth/dexto-cloud.d.ts.map +1 -0
  8. package/dist/auth/dexto-cloud.js +27 -0
  9. package/dist/auth/dexto-gateway.cjs +162 -0
  10. package/dist/auth/dexto-gateway.d.ts +55 -0
  11. package/dist/auth/dexto-gateway.d.ts.map +1 -0
  12. package/dist/auth/dexto-gateway.js +133 -0
  13. package/dist/auth/dexto-mcp.cjs +77 -0
  14. package/dist/auth/dexto-mcp.d.ts +23 -0
  15. package/dist/auth/dexto-mcp.d.ts.map +1 -0
  16. package/dist/auth/dexto-mcp.js +49 -0
  17. package/dist/auth/dexto-sign-in.cjs +324 -0
  18. package/dist/auth/dexto-sign-in.d.ts +63 -0
  19. package/dist/auth/dexto-sign-in.d.ts.map +1 -0
  20. package/dist/auth/dexto-sign-in.js +295 -0
  21. package/dist/auth/index.cjs +25 -0
  22. package/dist/auth/index.d.ts +6 -0
  23. package/dist/auth/index.d.ts.map +1 -1
  24. package/dist/auth/index.js +10 -0
  25. package/dist/auth/model-auth-handlers.cjs +3 -1
  26. package/dist/auth/model-auth-handlers.d.ts +6 -1
  27. package/dist/auth/model-auth-handlers.d.ts.map +1 -1
  28. package/dist/auth/model-auth-handlers.js +6 -1
  29. package/dist/index.cjs +38 -29
  30. package/dist/index.d.ts +2 -1
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +7 -6
  33. package/dist/tool-factories/agent-spawner/factory.cjs +1 -218
  34. package/dist/tool-factories/agent-spawner/factory.d.ts.map +1 -1
  35. package/dist/tool-factories/agent-spawner/factory.js +1 -228
  36. package/dist/utils/dexto-auth.cjs +3 -58
  37. package/dist/utils/dexto-auth.d.ts +4 -18
  38. package/dist/utils/dexto-auth.d.ts.map +1 -1
  39. package/dist/utils/dexto-auth.js +3 -57
  40. package/package.json +5 -6
@@ -0,0 +1,277 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var dexto_accounts_exports = {};
30
+ __export(dexto_accounts_exports, {
31
+ DEFAULT_PROFILE: () => DEFAULT_PROFILE,
32
+ SignedInAsSchema: () => SignedInAsSchema,
33
+ carryOverCloudCliLogins: () => carryOverCloudCliLogins,
34
+ carryOverDexto1ApiKey: () => carryOverDexto1ApiKey,
35
+ forgetLogin: () => forgetLogin,
36
+ listAccounts: () => listAccounts,
37
+ profileNameFor: () => profileNameFor,
38
+ readCurrentProfile: () => readCurrentProfile,
39
+ readLogin: () => readLogin,
40
+ requireProfileName: () => requireProfileName,
41
+ resolveCredential: () => resolveCredential,
42
+ resolveProfile: () => resolveProfile,
43
+ writeCurrentProfile: () => writeCurrentProfile,
44
+ writeLogin: () => writeLogin
45
+ });
46
+ module.exports = __toCommonJS(dexto_accounts_exports);
47
+ var import_node_crypto = require("node:crypto");
48
+ var import_promises = require("node:fs/promises");
49
+ var import_node_path = __toESM(require("node:path"), 1);
50
+ var import_zod = require("zod");
51
+ const DEFAULT_PROFILE = "default";
52
+ const SignedInAsSchema = import_zod.z.object({
53
+ account: import_zod.z.object({ email: import_zod.z.string(), id: import_zod.z.string(), name: import_zod.z.string() }),
54
+ organization: import_zod.z.object({ id: import_zod.z.string(), name: import_zod.z.string(), slug: import_zod.z.string() })
55
+ });
56
+ const OAuthLoginSchema = import_zod.z.object({
57
+ kind: import_zod.z.literal("oauth"),
58
+ accessToken: import_zod.z.string().min(1),
59
+ refreshToken: import_zod.z.string().min(1),
60
+ /** When the access token stops working, ISO 8601. */
61
+ expiresAt: import_zod.z.string(),
62
+ /** `dexto-cli`, or the client an older `dexto-cloud` sign-in registered. */
63
+ clientId: import_zod.z.string().min(1),
64
+ /** The Dexto app origin: its authorization server and MCP. */
65
+ appUrl: import_zod.z.string().url(),
66
+ apiBaseUrl: import_zod.z.string().url(),
67
+ /** The MCP resource the tokens were issued for. */
68
+ resource: import_zod.z.string().url(),
69
+ tokenEndpoint: import_zod.z.string().url(),
70
+ scopes: import_zod.z.array(import_zod.z.string()),
71
+ savedAt: import_zod.z.string(),
72
+ /** Null when the server didn't say. */
73
+ signedInAs: SignedInAsSchema.nullable(),
74
+ /** The Cloud project Dexto models bill; null when the organization has none to use. */
75
+ cloudProject: import_zod.z.object({ id: import_zod.z.string(), name: import_zod.z.string() }).strict().nullable()
76
+ }).strict();
77
+ const ApiKeyLoginSchema = import_zod.z.object({
78
+ kind: import_zod.z.literal("api_key"),
79
+ apiKey: import_zod.z.string().min(1),
80
+ apiBaseUrl: import_zod.z.string().url(),
81
+ savedAt: import_zod.z.string()
82
+ }).strict();
83
+ const StoredLoginSchema = import_zod.z.discriminatedUnion("kind", [OAuthLoginSchema, ApiKeyLoginSchema]);
84
+ const PROFILE_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/u;
85
+ function requireProfileName(name) {
86
+ if (!PROFILE_NAME.test(name))
87
+ throw new Error(
88
+ `${name} can't name a profile: use up to 64 lowercase letters, digits, ".", "_" and "-".`
89
+ );
90
+ return name;
91
+ }
92
+ function profileNameFor(organization) {
93
+ const name = organization.toLowerCase().replaceAll(/[^a-z0-9._-]+/gu, "-").replaceAll(/^[._-]+|-+$/gu, "").slice(0, 64);
94
+ if (name.length > 0) return requireProfileName(name);
95
+ return `org-${(0, import_node_crypto.createHash)("sha256").update(organization).digest("hex").slice(0, 8)}`;
96
+ }
97
+ function loginFile(dir, profile) {
98
+ return import_node_path.default.join(dir, `${requireProfileName(profile)}.json`);
99
+ }
100
+ function currentFile(dir) {
101
+ return import_node_path.default.join(dir, "current");
102
+ }
103
+ async function readLogin(dir, profile) {
104
+ const file = loginFile(dir, profile);
105
+ const text = await readOptional(file);
106
+ if (text === null) return null;
107
+ const parsed = StoredLoginSchema.safeParse(JSON.parse(text));
108
+ if (!parsed.success) throw new Error(`${file} is not a saved login. Run dexto login again.`);
109
+ return parsed.data;
110
+ }
111
+ async function writeLogin(dir, profile, login) {
112
+ await writePrivate(loginFile(dir, profile), `${JSON.stringify(login, null, 4)}
113
+ `);
114
+ }
115
+ async function forgetLogin(dir, profile) {
116
+ try {
117
+ await (0, import_promises.rm)(loginFile(dir, profile));
118
+ return true;
119
+ } catch (error) {
120
+ if (isMissingFile(error)) return false;
121
+ throw error;
122
+ }
123
+ }
124
+ async function listAccounts(dir) {
125
+ const names = (await readDirectory(dir)).filter((file) => file.endsWith(".json")).map((file) => file.slice(0, -".json".length)).filter((name) => PROFILE_NAME.test(name)).sort((a, b) => a === DEFAULT_PROFILE ? -1 : b === DEFAULT_PROFILE ? 1 : a < b ? -1 : 1);
126
+ const accounts = [];
127
+ for (const name of names) {
128
+ const login = await readLogin(dir, name);
129
+ if (login !== null) accounts.push({ name, login });
130
+ }
131
+ return accounts;
132
+ }
133
+ async function readCurrentProfile(dir) {
134
+ const text = await readOptional(currentFile(dir));
135
+ if (text === null) return DEFAULT_PROFILE;
136
+ const name = text.trim();
137
+ if (!PROFILE_NAME.test(name))
138
+ throw new Error(`${currentFile(dir)} names no profile. Run dexto accounts use <name>.`);
139
+ return name;
140
+ }
141
+ async function writeCurrentProfile(dir, profile) {
142
+ await writePrivate(currentFile(dir), `${requireProfileName(profile)}
143
+ `);
144
+ }
145
+ async function resolveProfile(dir, profile, environment) {
146
+ const chosen = profile ?? nonEmpty(environment.DEXTO_PROFILE);
147
+ return chosen === null ? await readCurrentProfile(dir) : requireProfileName(chosen);
148
+ }
149
+ const CloudCliOAuthLoginSchema = OAuthLoginSchema.omit({ signedInAs: true }).strip();
150
+ const CloudCliLoginSchema = import_zod.z.union([CloudCliOAuthLoginSchema, ApiKeyLoginSchema]);
151
+ const CloudCliSignedInAsSchema = SignedInAsSchema.extend({ clientId: import_zod.z.string() });
152
+ async function carryOverCloudCliLogins(dir, cloudCliDir) {
153
+ if ((await listAccounts(dir)).length > 0) return [];
154
+ const profileFiles = (await readDirectory(import_node_path.default.join(cloudCliDir, "profiles"))).filter((file) => file.endsWith(".json")).map((file) => file.slice(0, -".json".length)).filter((name) => name !== DEFAULT_PROFILE && PROFILE_NAME.test(name)).sort();
155
+ const copied = [];
156
+ for (const name of [DEFAULT_PROFILE, ...profileFiles]) {
157
+ const file = name === DEFAULT_PROFILE ? import_node_path.default.join(cloudCliDir, "credentials.json") : import_node_path.default.join(cloudCliDir, "profiles", `${name}.json`);
158
+ const text = await readOptional(file);
159
+ if (text === null) continue;
160
+ const parsed = CloudCliLoginSchema.safeParse(JSON.parse(text));
161
+ if (!parsed.success) continue;
162
+ const login = parsed.data;
163
+ if (login.kind === "api_key") {
164
+ await writeLogin(dir, name, login);
165
+ } else {
166
+ await writeLogin(dir, name, {
167
+ ...login,
168
+ signedInAs: await readCloudCliSignedInAs(cloudCliDir, name, login.clientId)
169
+ });
170
+ }
171
+ copied.push(name);
172
+ }
173
+ const current = await readOptional(import_node_path.default.join(cloudCliDir, "current"));
174
+ if (current !== null && copied.includes(current.trim()))
175
+ await writeCurrentProfile(dir, current.trim());
176
+ return copied;
177
+ }
178
+ const Dexto1AuthSchema = import_zod.z.object({
179
+ dextoApiKey: import_zod.z.string().min(1).optional(),
180
+ dextoPlatformUrl: import_zod.z.string().url().optional()
181
+ });
182
+ async function carryOverDexto1ApiKey(dir, authFile, apiBaseUrl) {
183
+ if ((await listAccounts(dir)).length > 0) return false;
184
+ const text = await readOptional(authFile);
185
+ if (text === null) return false;
186
+ const parsed = Dexto1AuthSchema.safeParse(JSON.parse(text));
187
+ if (!parsed.success || parsed.data.dextoApiKey === void 0) return false;
188
+ await writeLogin(dir, DEFAULT_PROFILE, {
189
+ kind: "api_key",
190
+ apiKey: parsed.data.dextoApiKey,
191
+ apiBaseUrl: parsed.data.dextoPlatformUrl ?? apiBaseUrl,
192
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
193
+ });
194
+ return true;
195
+ }
196
+ async function readCloudCliSignedInAs(cloudCliDir, profile, clientId) {
197
+ const text = await readOptional(import_node_path.default.join(cloudCliDir, "accounts", `${profile}.json`));
198
+ if (text === null) return null;
199
+ const parsed = CloudCliSignedInAsSchema.safeParse(JSON.parse(text));
200
+ if (!parsed.success || parsed.data.clientId !== clientId) return null;
201
+ return { account: parsed.data.account, organization: parsed.data.organization };
202
+ }
203
+ async function resolveCredential(input) {
204
+ const profile = await resolveProfile(input.dir, input.profile, input.environment);
205
+ if (input.apiKey !== null)
206
+ return { kind: "api_key", token: input.apiKey, source: "flag", profile };
207
+ const environmentKey = nonEmpty(input.environment.DEXTO_API_KEY);
208
+ if (environmentKey !== null)
209
+ return { kind: "api_key", token: environmentKey, source: "environment", profile };
210
+ const stored = await readLogin(input.dir, profile);
211
+ if (stored === null) return null;
212
+ if (stored.kind === "api_key")
213
+ return { kind: "api_key", token: stored.apiKey, source: "login", profile };
214
+ const login = isExpiring(stored) ? await refreshSaved(input.dir, profile, stored, input.refresh) : stored;
215
+ return { kind: "oauth", token: login.accessToken, source: "login", profile, login };
216
+ }
217
+ const REFRESH_MARGIN_MS = 6e4;
218
+ function isExpiring(login) {
219
+ return Date.parse(login.expiresAt) - Date.now() < REFRESH_MARGIN_MS;
220
+ }
221
+ async function refreshSaved(dir, profile, stored, refresh) {
222
+ try {
223
+ const refreshed = await refresh(stored);
224
+ await writeLogin(dir, profile, refreshed);
225
+ return refreshed;
226
+ } catch (error) {
227
+ const current = await readLogin(dir, profile);
228
+ if (current?.kind === "oauth" && current.refreshToken !== stored.refreshToken && !isExpiring(current))
229
+ return current;
230
+ throw error;
231
+ }
232
+ }
233
+ async function readOptional(file) {
234
+ try {
235
+ return await (0, import_promises.readFile)(file, "utf8");
236
+ } catch (error) {
237
+ if (isMissingFile(error)) return null;
238
+ throw error;
239
+ }
240
+ }
241
+ async function readDirectory(dir) {
242
+ try {
243
+ return await (0, import_promises.readdir)(dir);
244
+ } catch (error) {
245
+ if (isMissingFile(error)) return [];
246
+ throw error;
247
+ }
248
+ }
249
+ async function writePrivate(file, text) {
250
+ await (0, import_promises.mkdir)(import_node_path.default.dirname(file), { mode: 448, recursive: true });
251
+ await (0, import_promises.chmod)(import_node_path.default.dirname(file), 448);
252
+ await (0, import_promises.writeFile)(file, text, { mode: 384 });
253
+ await (0, import_promises.chmod)(file, 384);
254
+ }
255
+ function nonEmpty(value) {
256
+ return value === void 0 || value.length === 0 ? null : value;
257
+ }
258
+ function isMissingFile(error) {
259
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
260
+ }
261
+ // Annotate the CommonJS export names for ESM import in node:
262
+ 0 && (module.exports = {
263
+ DEFAULT_PROFILE,
264
+ SignedInAsSchema,
265
+ carryOverCloudCliLogins,
266
+ carryOverDexto1ApiKey,
267
+ forgetLogin,
268
+ listAccounts,
269
+ profileNameFor,
270
+ readCurrentProfile,
271
+ readLogin,
272
+ requireProfileName,
273
+ resolveCredential,
274
+ resolveProfile,
275
+ writeCurrentProfile,
276
+ writeLogin
277
+ });
@@ -0,0 +1,144 @@
1
+ import { z } from 'zod';
2
+ export declare const DEFAULT_PROFILE = "default";
3
+ /** Who a sign-in acts as: one account in one organization, as the token response says. */
4
+ export declare const SignedInAsSchema: z.ZodObject<{
5
+ account: z.ZodObject<{
6
+ email: z.ZodString;
7
+ id: z.ZodString;
8
+ name: z.ZodString;
9
+ }, z.core.$strip>;
10
+ organization: z.ZodObject<{
11
+ id: z.ZodString;
12
+ name: z.ZodString;
13
+ slug: z.ZodString;
14
+ }, z.core.$strip>;
15
+ }, z.core.$strip>;
16
+ export type SignedInAs = z.output<typeof SignedInAsSchema>;
17
+ declare const OAuthLoginSchema: z.ZodObject<{
18
+ kind: z.ZodLiteral<"oauth">;
19
+ accessToken: z.ZodString;
20
+ refreshToken: z.ZodString;
21
+ expiresAt: z.ZodString;
22
+ clientId: z.ZodString;
23
+ appUrl: z.ZodString;
24
+ apiBaseUrl: z.ZodString;
25
+ resource: z.ZodString;
26
+ tokenEndpoint: z.ZodString;
27
+ scopes: z.ZodArray<z.ZodString>;
28
+ savedAt: z.ZodString;
29
+ signedInAs: z.ZodNullable<z.ZodObject<{
30
+ account: z.ZodObject<{
31
+ email: z.ZodString;
32
+ id: z.ZodString;
33
+ name: z.ZodString;
34
+ }, z.core.$strip>;
35
+ organization: z.ZodObject<{
36
+ id: z.ZodString;
37
+ name: z.ZodString;
38
+ slug: z.ZodString;
39
+ }, z.core.$strip>;
40
+ }, z.core.$strip>>;
41
+ cloudProject: z.ZodNullable<z.ZodObject<{
42
+ id: z.ZodString;
43
+ name: z.ZodString;
44
+ }, z.core.$strict>>;
45
+ }, z.core.$strict>;
46
+ declare const StoredLoginSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
47
+ kind: z.ZodLiteral<"oauth">;
48
+ accessToken: z.ZodString;
49
+ refreshToken: z.ZodString;
50
+ expiresAt: z.ZodString;
51
+ clientId: z.ZodString;
52
+ appUrl: z.ZodString;
53
+ apiBaseUrl: z.ZodString;
54
+ resource: z.ZodString;
55
+ tokenEndpoint: z.ZodString;
56
+ scopes: z.ZodArray<z.ZodString>;
57
+ savedAt: z.ZodString;
58
+ signedInAs: z.ZodNullable<z.ZodObject<{
59
+ account: z.ZodObject<{
60
+ email: z.ZodString;
61
+ id: z.ZodString;
62
+ name: z.ZodString;
63
+ }, z.core.$strip>;
64
+ organization: z.ZodObject<{
65
+ id: z.ZodString;
66
+ name: z.ZodString;
67
+ slug: z.ZodString;
68
+ }, z.core.$strip>;
69
+ }, z.core.$strip>>;
70
+ cloudProject: z.ZodNullable<z.ZodObject<{
71
+ id: z.ZodString;
72
+ name: z.ZodString;
73
+ }, z.core.$strict>>;
74
+ }, z.core.$strict>, z.ZodObject<{
75
+ kind: z.ZodLiteral<"api_key">;
76
+ apiKey: z.ZodString;
77
+ apiBaseUrl: z.ZodString;
78
+ savedAt: z.ZodString;
79
+ }, z.core.$strict>], "kind">;
80
+ export type OAuthLogin = z.output<typeof OAuthLoginSchema>;
81
+ export type StoredLogin = z.output<typeof StoredLoginSchema>;
82
+ export interface SavedAccount {
83
+ readonly name: string;
84
+ readonly login: StoredLogin;
85
+ }
86
+ /** A profile name as given, refused unless it is one; names are also file names. */
87
+ export declare function requireProfileName(name: string): string;
88
+ /**
89
+ * The profile a sign-in for an organization gets when none is named: the organization's word, or
90
+ * `org-` and a short hash of it when it has no letters or digits a profile name can use.
91
+ */
92
+ export declare function profileNameFor(organization: string): string;
93
+ export declare function readLogin(dir: string, profile: string): Promise<StoredLogin | null>;
94
+ /** Saves the login readable only by this user. */
95
+ export declare function writeLogin(dir: string, profile: string, login: StoredLogin): Promise<void>;
96
+ /** Forgets a profile's login; false when it had none. */
97
+ export declare function forgetLogin(dir: string, profile: string): Promise<boolean>;
98
+ /** Every profile with a saved login, `default` first. */
99
+ export declare function listAccounts(dir: string): Promise<SavedAccount[]>;
100
+ /** The profile `accounts use` chose, or `default`. */
101
+ export declare function readCurrentProfile(dir: string): Promise<string>;
102
+ export declare function writeCurrentProfile(dir: string, profile: string): Promise<void>;
103
+ /** --profile, then DEXTO_PROFILE, then the current profile. */
104
+ export declare function resolveProfile(dir: string, profile: string | null, environment: Readonly<Record<string, string | undefined>>): Promise<string>;
105
+ /**
106
+ * Copies the internal `dexto-cloud` CLI's sign-ins (`~/.config/dexto-cloud`) into `dir`, once:
107
+ * only when `dir` has no sign-in yet. Its files stay as they were. Returns the profiles copied.
108
+ */
109
+ export declare function carryOverCloudCliLogins(dir: string, cloudCliDir: string): Promise<string[]>;
110
+ /**
111
+ * Copies dexto 1.x's saved API key (`~/.dexto/auth.json`) into `dir` as the default profile, once:
112
+ * only when `dir` has no sign-in yet. Its Supabase token, if any, is left behind. True when copied.
113
+ */
114
+ export declare function carryOverDexto1ApiKey(dir: string, authFile: string, apiBaseUrl: string): Promise<boolean>;
115
+ /** Where a command's credential came from, so `whoami` can say. */
116
+ export type CredentialSource = 'flag' | 'environment' | 'login';
117
+ export type Credential = {
118
+ readonly kind: 'api_key';
119
+ readonly token: string;
120
+ readonly source: CredentialSource;
121
+ readonly profile: string;
122
+ } | {
123
+ readonly kind: 'oauth';
124
+ readonly token: string;
125
+ readonly source: 'login';
126
+ readonly profile: string;
127
+ readonly login: OAuthLogin;
128
+ };
129
+ export interface ResolveCredentialInput {
130
+ readonly dir: string;
131
+ /** The global --api-key value. */
132
+ readonly apiKey: string | null;
133
+ /** The global --profile value. */
134
+ readonly profile: string | null;
135
+ readonly environment: Readonly<Record<string, string | undefined>>;
136
+ readonly refresh: (login: OAuthLogin) => Promise<OAuthLogin>;
137
+ }
138
+ /**
139
+ * --api-key, then DEXTO_API_KEY, then the profile's saved login; null when signed out. A saved
140
+ * sign-in is refreshed first when its access token has expired or is about to.
141
+ */
142
+ export declare function resolveCredential(input: ResolveCredentialInput): Promise<Credential | null>;
143
+ export {};
144
+ //# sourceMappingURL=dexto-accounts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dexto-accounts.d.ts","sourceRoot":"","sources":["../../src/auth/dexto-accounts.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,230 @@
1
+ import { createHash } from "node:crypto";
2
+ import { chmod, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { z } from "zod";
5
+ const DEFAULT_PROFILE = "default";
6
+ const SignedInAsSchema = z.object({
7
+ account: z.object({ email: z.string(), id: z.string(), name: z.string() }),
8
+ organization: z.object({ id: z.string(), name: z.string(), slug: z.string() })
9
+ });
10
+ const OAuthLoginSchema = z.object({
11
+ kind: z.literal("oauth"),
12
+ accessToken: z.string().min(1),
13
+ refreshToken: z.string().min(1),
14
+ /** When the access token stops working, ISO 8601. */
15
+ expiresAt: z.string(),
16
+ /** `dexto-cli`, or the client an older `dexto-cloud` sign-in registered. */
17
+ clientId: z.string().min(1),
18
+ /** The Dexto app origin: its authorization server and MCP. */
19
+ appUrl: z.string().url(),
20
+ apiBaseUrl: z.string().url(),
21
+ /** The MCP resource the tokens were issued for. */
22
+ resource: z.string().url(),
23
+ tokenEndpoint: z.string().url(),
24
+ scopes: z.array(z.string()),
25
+ savedAt: z.string(),
26
+ /** Null when the server didn't say. */
27
+ signedInAs: SignedInAsSchema.nullable(),
28
+ /** The Cloud project Dexto models bill; null when the organization has none to use. */
29
+ cloudProject: z.object({ id: z.string(), name: z.string() }).strict().nullable()
30
+ }).strict();
31
+ const ApiKeyLoginSchema = z.object({
32
+ kind: z.literal("api_key"),
33
+ apiKey: z.string().min(1),
34
+ apiBaseUrl: z.string().url(),
35
+ savedAt: z.string()
36
+ }).strict();
37
+ const StoredLoginSchema = z.discriminatedUnion("kind", [OAuthLoginSchema, ApiKeyLoginSchema]);
38
+ const PROFILE_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/u;
39
+ function requireProfileName(name) {
40
+ if (!PROFILE_NAME.test(name))
41
+ throw new Error(
42
+ `${name} can't name a profile: use up to 64 lowercase letters, digits, ".", "_" and "-".`
43
+ );
44
+ return name;
45
+ }
46
+ function profileNameFor(organization) {
47
+ const name = organization.toLowerCase().replaceAll(/[^a-z0-9._-]+/gu, "-").replaceAll(/^[._-]+|-+$/gu, "").slice(0, 64);
48
+ if (name.length > 0) return requireProfileName(name);
49
+ return `org-${createHash("sha256").update(organization).digest("hex").slice(0, 8)}`;
50
+ }
51
+ function loginFile(dir, profile) {
52
+ return path.join(dir, `${requireProfileName(profile)}.json`);
53
+ }
54
+ function currentFile(dir) {
55
+ return path.join(dir, "current");
56
+ }
57
+ async function readLogin(dir, profile) {
58
+ const file = loginFile(dir, profile);
59
+ const text = await readOptional(file);
60
+ if (text === null) return null;
61
+ const parsed = StoredLoginSchema.safeParse(JSON.parse(text));
62
+ if (!parsed.success) throw new Error(`${file} is not a saved login. Run dexto login again.`);
63
+ return parsed.data;
64
+ }
65
+ async function writeLogin(dir, profile, login) {
66
+ await writePrivate(loginFile(dir, profile), `${JSON.stringify(login, null, 4)}
67
+ `);
68
+ }
69
+ async function forgetLogin(dir, profile) {
70
+ try {
71
+ await rm(loginFile(dir, profile));
72
+ return true;
73
+ } catch (error) {
74
+ if (isMissingFile(error)) return false;
75
+ throw error;
76
+ }
77
+ }
78
+ async function listAccounts(dir) {
79
+ const names = (await readDirectory(dir)).filter((file) => file.endsWith(".json")).map((file) => file.slice(0, -".json".length)).filter((name) => PROFILE_NAME.test(name)).sort((a, b) => a === DEFAULT_PROFILE ? -1 : b === DEFAULT_PROFILE ? 1 : a < b ? -1 : 1);
80
+ const accounts = [];
81
+ for (const name of names) {
82
+ const login = await readLogin(dir, name);
83
+ if (login !== null) accounts.push({ name, login });
84
+ }
85
+ return accounts;
86
+ }
87
+ async function readCurrentProfile(dir) {
88
+ const text = await readOptional(currentFile(dir));
89
+ if (text === null) return DEFAULT_PROFILE;
90
+ const name = text.trim();
91
+ if (!PROFILE_NAME.test(name))
92
+ throw new Error(`${currentFile(dir)} names no profile. Run dexto accounts use <name>.`);
93
+ return name;
94
+ }
95
+ async function writeCurrentProfile(dir, profile) {
96
+ await writePrivate(currentFile(dir), `${requireProfileName(profile)}
97
+ `);
98
+ }
99
+ async function resolveProfile(dir, profile, environment) {
100
+ const chosen = profile ?? nonEmpty(environment.DEXTO_PROFILE);
101
+ return chosen === null ? await readCurrentProfile(dir) : requireProfileName(chosen);
102
+ }
103
+ const CloudCliOAuthLoginSchema = OAuthLoginSchema.omit({ signedInAs: true }).strip();
104
+ const CloudCliLoginSchema = z.union([CloudCliOAuthLoginSchema, ApiKeyLoginSchema]);
105
+ const CloudCliSignedInAsSchema = SignedInAsSchema.extend({ clientId: z.string() });
106
+ async function carryOverCloudCliLogins(dir, cloudCliDir) {
107
+ if ((await listAccounts(dir)).length > 0) return [];
108
+ const profileFiles = (await readDirectory(path.join(cloudCliDir, "profiles"))).filter((file) => file.endsWith(".json")).map((file) => file.slice(0, -".json".length)).filter((name) => name !== DEFAULT_PROFILE && PROFILE_NAME.test(name)).sort();
109
+ const copied = [];
110
+ for (const name of [DEFAULT_PROFILE, ...profileFiles]) {
111
+ const file = name === DEFAULT_PROFILE ? path.join(cloudCliDir, "credentials.json") : path.join(cloudCliDir, "profiles", `${name}.json`);
112
+ const text = await readOptional(file);
113
+ if (text === null) continue;
114
+ const parsed = CloudCliLoginSchema.safeParse(JSON.parse(text));
115
+ if (!parsed.success) continue;
116
+ const login = parsed.data;
117
+ if (login.kind === "api_key") {
118
+ await writeLogin(dir, name, login);
119
+ } else {
120
+ await writeLogin(dir, name, {
121
+ ...login,
122
+ signedInAs: await readCloudCliSignedInAs(cloudCliDir, name, login.clientId)
123
+ });
124
+ }
125
+ copied.push(name);
126
+ }
127
+ const current = await readOptional(path.join(cloudCliDir, "current"));
128
+ if (current !== null && copied.includes(current.trim()))
129
+ await writeCurrentProfile(dir, current.trim());
130
+ return copied;
131
+ }
132
+ const Dexto1AuthSchema = z.object({
133
+ dextoApiKey: z.string().min(1).optional(),
134
+ dextoPlatformUrl: z.string().url().optional()
135
+ });
136
+ async function carryOverDexto1ApiKey(dir, authFile, apiBaseUrl) {
137
+ if ((await listAccounts(dir)).length > 0) return false;
138
+ const text = await readOptional(authFile);
139
+ if (text === null) return false;
140
+ const parsed = Dexto1AuthSchema.safeParse(JSON.parse(text));
141
+ if (!parsed.success || parsed.data.dextoApiKey === void 0) return false;
142
+ await writeLogin(dir, DEFAULT_PROFILE, {
143
+ kind: "api_key",
144
+ apiKey: parsed.data.dextoApiKey,
145
+ apiBaseUrl: parsed.data.dextoPlatformUrl ?? apiBaseUrl,
146
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
147
+ });
148
+ return true;
149
+ }
150
+ async function readCloudCliSignedInAs(cloudCliDir, profile, clientId) {
151
+ const text = await readOptional(path.join(cloudCliDir, "accounts", `${profile}.json`));
152
+ if (text === null) return null;
153
+ const parsed = CloudCliSignedInAsSchema.safeParse(JSON.parse(text));
154
+ if (!parsed.success || parsed.data.clientId !== clientId) return null;
155
+ return { account: parsed.data.account, organization: parsed.data.organization };
156
+ }
157
+ async function resolveCredential(input) {
158
+ const profile = await resolveProfile(input.dir, input.profile, input.environment);
159
+ if (input.apiKey !== null)
160
+ return { kind: "api_key", token: input.apiKey, source: "flag", profile };
161
+ const environmentKey = nonEmpty(input.environment.DEXTO_API_KEY);
162
+ if (environmentKey !== null)
163
+ return { kind: "api_key", token: environmentKey, source: "environment", profile };
164
+ const stored = await readLogin(input.dir, profile);
165
+ if (stored === null) return null;
166
+ if (stored.kind === "api_key")
167
+ return { kind: "api_key", token: stored.apiKey, source: "login", profile };
168
+ const login = isExpiring(stored) ? await refreshSaved(input.dir, profile, stored, input.refresh) : stored;
169
+ return { kind: "oauth", token: login.accessToken, source: "login", profile, login };
170
+ }
171
+ const REFRESH_MARGIN_MS = 6e4;
172
+ function isExpiring(login) {
173
+ return Date.parse(login.expiresAt) - Date.now() < REFRESH_MARGIN_MS;
174
+ }
175
+ async function refreshSaved(dir, profile, stored, refresh) {
176
+ try {
177
+ const refreshed = await refresh(stored);
178
+ await writeLogin(dir, profile, refreshed);
179
+ return refreshed;
180
+ } catch (error) {
181
+ const current = await readLogin(dir, profile);
182
+ if (current?.kind === "oauth" && current.refreshToken !== stored.refreshToken && !isExpiring(current))
183
+ return current;
184
+ throw error;
185
+ }
186
+ }
187
+ async function readOptional(file) {
188
+ try {
189
+ return await readFile(file, "utf8");
190
+ } catch (error) {
191
+ if (isMissingFile(error)) return null;
192
+ throw error;
193
+ }
194
+ }
195
+ async function readDirectory(dir) {
196
+ try {
197
+ return await readdir(dir);
198
+ } catch (error) {
199
+ if (isMissingFile(error)) return [];
200
+ throw error;
201
+ }
202
+ }
203
+ async function writePrivate(file, text) {
204
+ await mkdir(path.dirname(file), { mode: 448, recursive: true });
205
+ await chmod(path.dirname(file), 448);
206
+ await writeFile(file, text, { mode: 384 });
207
+ await chmod(file, 384);
208
+ }
209
+ function nonEmpty(value) {
210
+ return value === void 0 || value.length === 0 ? null : value;
211
+ }
212
+ function isMissingFile(error) {
213
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
214
+ }
215
+ export {
216
+ DEFAULT_PROFILE,
217
+ SignedInAsSchema,
218
+ carryOverCloudCliLogins,
219
+ carryOverDexto1ApiKey,
220
+ forgetLogin,
221
+ listAccounts,
222
+ profileNameFor,
223
+ readCurrentProfile,
224
+ readLogin,
225
+ requireProfileName,
226
+ resolveCredential,
227
+ resolveProfile,
228
+ writeCurrentProfile,
229
+ writeLogin
230
+ };