@dexto/agent-management 1.15.0-beta.0 → 1.15.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 (37) hide show
  1. package/dist/auth/index.cjs +0 -25
  2. package/dist/auth/index.d.ts +0 -6
  3. package/dist/auth/index.d.ts.map +1 -1
  4. package/dist/auth/index.js +0 -10
  5. package/dist/auth/model-auth-handlers.cjs +1 -3
  6. package/dist/auth/model-auth-handlers.d.ts +1 -6
  7. package/dist/auth/model-auth-handlers.d.ts.map +1 -1
  8. package/dist/auth/model-auth-handlers.js +1 -6
  9. package/dist/index.cjs +29 -38
  10. package/dist/index.d.ts +1 -2
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +6 -7
  13. package/dist/utils/dexto-auth.cjs +58 -3
  14. package/dist/utils/dexto-auth.d.ts +18 -4
  15. package/dist/utils/dexto-auth.d.ts.map +1 -1
  16. package/dist/utils/dexto-auth.js +57 -3
  17. package/package.json +6 -6
  18. package/dist/auth/dexto-accounts.cjs +0 -277
  19. package/dist/auth/dexto-accounts.d.ts +0 -144
  20. package/dist/auth/dexto-accounts.d.ts.map +0 -1
  21. package/dist/auth/dexto-accounts.js +0 -230
  22. package/dist/auth/dexto-cloud.cjs +0 -51
  23. package/dist/auth/dexto-cloud.d.ts +0 -9
  24. package/dist/auth/dexto-cloud.d.ts.map +0 -1
  25. package/dist/auth/dexto-cloud.js +0 -27
  26. package/dist/auth/dexto-gateway.cjs +0 -162
  27. package/dist/auth/dexto-gateway.d.ts +0 -55
  28. package/dist/auth/dexto-gateway.d.ts.map +0 -1
  29. package/dist/auth/dexto-gateway.js +0 -133
  30. package/dist/auth/dexto-mcp.cjs +0 -77
  31. package/dist/auth/dexto-mcp.d.ts +0 -23
  32. package/dist/auth/dexto-mcp.d.ts.map +0 -1
  33. package/dist/auth/dexto-mcp.js +0 -49
  34. package/dist/auth/dexto-sign-in.cjs +0 -317
  35. package/dist/auth/dexto-sign-in.d.ts +0 -63
  36. package/dist/auth/dexto-sign-in.d.ts.map +0 -1
  37. package/dist/auth/dexto-sign-in.js +0 -288
@@ -1,317 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var dexto_sign_in_exports = {};
20
- __export(dexto_sign_in_exports, {
21
- DEXTO_CLI_CLIENT_ID: () => DEXTO_CLI_CLIENT_ID,
22
- OAuthHttpError: () => OAuthHttpError,
23
- endSignIn: () => endSignIn,
24
- refreshSignIn: () => refreshSignIn,
25
- signInWithBrowser: () => signInWithBrowser,
26
- signInWithDevice: () => signInWithDevice
27
- });
28
- module.exports = __toCommonJS(dexto_sign_in_exports);
29
- var import_node_crypto = require("node:crypto");
30
- var import_zod = require("zod");
31
- var import_dexto_accounts = require("./dexto-accounts.js");
32
- const DEXTO_CLI_CLIENT_ID = "dexto-cli";
33
- const BASE_CLOUD_SCOPES = ["cloud:read"];
34
- const DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
35
- const LOGIN_TIMEOUT_MS = 5 * 6e4;
36
- const END_SIGN_IN_TIMEOUT_MS = 1e4;
37
- const ProtectedResourceSchema = import_zod.z.object({
38
- authorization_servers: import_zod.z.array(import_zod.z.string().url()).min(1),
39
- resource: import_zod.z.string().url(),
40
- scopes_supported: import_zod.z.array(import_zod.z.string())
41
- });
42
- const AuthorizationServerSchema = import_zod.z.object({
43
- authorization_endpoint: import_zod.z.string().url(),
44
- device_authorization_endpoint: import_zod.z.string().url(),
45
- revocation_endpoint: import_zod.z.string().url(),
46
- token_endpoint: import_zod.z.string().url()
47
- });
48
- const TokenResponseSchema = import_zod.z.object({
49
- access_token: import_zod.z.string().min(1),
50
- refresh_token: import_zod.z.string().min(1),
51
- expires_in: import_zod.z.number().int().positive(),
52
- scope: import_zod.z.string(),
53
- /** Who the tokens act as. */
54
- dexto_account: import_dexto_accounts.SignedInAsSchema.shape.account.optional(),
55
- dexto_organization: import_dexto_accounts.SignedInAsSchema.shape.organization.optional()
56
- });
57
- const DeviceAuthorizationSchema = import_zod.z.object({
58
- device_code: import_zod.z.string().min(1),
59
- user_code: import_zod.z.string().min(1),
60
- expires_in: import_zod.z.number().int().positive(),
61
- interval: import_zod.z.number().int().positive().optional(),
62
- verification_uri: import_zod.z.string().url(),
63
- verification_uri_complete: import_zod.z.string().url().optional()
64
- });
65
- async function readMetadata(runtime, appUrl) {
66
- const resource = ProtectedResourceSchema.parse(
67
- await getJson(runtime, `${appUrl}/.well-known/oauth-protected-resource/mcp`)
68
- );
69
- const issuer = (resource.authorization_servers[0] ?? appUrl).replace(/\/+$/u, "");
70
- const server = AuthorizationServerSchema.parse(
71
- await getJson(runtime, `${issuer}/.well-known/oauth-authorization-server`)
72
- );
73
- return { resource, server };
74
- }
75
- async function discover(runtime, input) {
76
- const appUrl = input.appUrl.replace(/\/+$/u, "");
77
- const { resource, server } = await readMetadata(runtime, appUrl);
78
- const reading = resource.scopes_supported.filter((scope) => scope.endsWith(":read"));
79
- const scopes = [.../* @__PURE__ */ new Set([...reading, ...BASE_CLOUD_SCOPES, ...input.extraScopes])];
80
- return { appUrl, resource: resource.resource, scopes, server };
81
- }
82
- async function signInWithBrowser(runtime, input) {
83
- const { appUrl, resource, scopes, server } = await discover(runtime, input);
84
- const redirect = await runtime.listenForRedirect();
85
- try {
86
- const verifier = (0, import_node_crypto.randomBytes)(32).toString("base64url");
87
- const state = (0, import_node_crypto.randomBytes)(16).toString("base64url");
88
- const authorizeUrl = new URL(server.authorization_endpoint);
89
- for (const [name, value] of Object.entries({
90
- client_id: DEXTO_CLI_CLIENT_ID,
91
- code_challenge: (0, import_node_crypto.createHash)("sha256").update(verifier).digest("base64url"),
92
- code_challenge_method: "S256",
93
- redirect_uri: redirect.redirectUri,
94
- resource,
95
- response_type: "code",
96
- scope: scopes.join(" "),
97
- state,
98
- ...input.organization === null ? {} : { organization: input.organization }
99
- }))
100
- authorizeUrl.searchParams.set(name, value);
101
- runtime.note(
102
- `Sign in to Dexto in your browser. If it doesn't open, visit:
103
- ${authorizeUrl}`
104
- );
105
- if (input.openBrowser) await runtime.openBrowser(authorizeUrl.toString());
106
- const params = await withTimeout(redirect.result, LOGIN_TIMEOUT_MS, runtime.signal);
107
- if (params.get("state") !== state)
108
- throw new Error("The sign-in reply didn't match this login.");
109
- const error = params.get("error");
110
- if (error !== null)
111
- throw new Error(
112
- error === "access_denied" ? "Sign-in was declined." : `Sign-in failed: ${params.get("error_description") ?? error}.`
113
- );
114
- const code = params.get("code");
115
- if (code === null) throw new Error("The sign-in reply had no code.");
116
- const tokens = TokenResponseSchema.parse(
117
- await postForm(runtime, server.token_endpoint, {
118
- client_id: DEXTO_CLI_CLIENT_ID,
119
- code,
120
- code_verifier: verifier,
121
- grant_type: "authorization_code",
122
- redirect_uri: redirect.redirectUri,
123
- resource
124
- })
125
- );
126
- return toLogin(tokens, {
127
- apiBaseUrl: input.apiBaseUrl,
128
- appUrl,
129
- resource,
130
- tokenEndpoint: server.token_endpoint
131
- });
132
- } finally {
133
- redirect.close();
134
- }
135
- }
136
- async function signInWithDevice(runtime, input) {
137
- const { appUrl, resource, scopes, server } = await discover(runtime, input);
138
- const device = DeviceAuthorizationSchema.parse(
139
- await postForm(runtime, server.device_authorization_endpoint, {
140
- client_id: DEXTO_CLI_CLIENT_ID,
141
- resource,
142
- scope: scopes.join(" "),
143
- ...input.organization === null ? {} : { organization: input.organization }
144
- })
145
- );
146
- runtime.note(
147
- [
148
- device.verification_uri_complete === void 0 ? `To sign in, open this link on any device and enter ${device.user_code}:
149
- ${device.verification_uri}` : `To sign in, open this link on any device and check it shows ${device.user_code}:
150
- ${device.verification_uri_complete}`,
151
- "Only approve this if you just ran dexto login."
152
- ].join("\n")
153
- );
154
- const deadline = Date.now() + device.expires_in * 1e3;
155
- let intervalSeconds = device.interval ?? 5;
156
- while (Date.now() < deadline) {
157
- await runtime.sleep(intervalSeconds * 1e3);
158
- try {
159
- const tokens = TokenResponseSchema.parse(
160
- await postForm(runtime, server.token_endpoint, {
161
- client_id: DEXTO_CLI_CLIENT_ID,
162
- device_code: device.device_code,
163
- grant_type: DEVICE_CODE_GRANT_TYPE,
164
- resource
165
- })
166
- );
167
- return toLogin(tokens, {
168
- apiBaseUrl: input.apiBaseUrl,
169
- appUrl,
170
- resource,
171
- tokenEndpoint: server.token_endpoint
172
- });
173
- } catch (error) {
174
- if (!(error instanceof OAuthHttpError)) throw error;
175
- if (error.code === "authorization_pending") continue;
176
- if (error.code === "slow_down") {
177
- intervalSeconds += 5;
178
- continue;
179
- }
180
- if (error.code === "access_denied") throw new Error("Sign-in was declined.");
181
- if (error.code !== "expired_token") throw error;
182
- break;
183
- }
184
- }
185
- throw new Error("The sign-in code expired. Run dexto login --device again.");
186
- }
187
- function toLogin(tokens, client) {
188
- return {
189
- kind: "oauth",
190
- ...client,
191
- clientId: DEXTO_CLI_CLIENT_ID,
192
- accessToken: tokens.access_token,
193
- refreshToken: tokens.refresh_token,
194
- expiresAt: expiresAt(tokens.expires_in),
195
- scopes: splitScopes(tokens.scope),
196
- savedAt: (/* @__PURE__ */ new Date()).toISOString(),
197
- signedInAs: signedInAsFrom(tokens),
198
- cloudProject: null
199
- };
200
- }
201
- function signedInAsFrom(tokens) {
202
- return tokens.dexto_account === void 0 || tokens.dexto_organization === void 0 ? null : { account: tokens.dexto_account, organization: tokens.dexto_organization };
203
- }
204
- async function refreshSignIn(runtime, login) {
205
- let body;
206
- try {
207
- body = await postForm(runtime, login.tokenEndpoint, {
208
- client_id: login.clientId,
209
- grant_type: "refresh_token",
210
- refresh_token: login.refreshToken,
211
- resource: login.resource
212
- });
213
- } catch (error) {
214
- if (error instanceof OAuthHttpError && error.status === 400)
215
- throw new Error("Your Dexto sign-in has expired. Run dexto login again.");
216
- throw error;
217
- }
218
- const tokens = TokenResponseSchema.parse(body);
219
- return {
220
- ...login,
221
- accessToken: tokens.access_token,
222
- refreshToken: tokens.refresh_token,
223
- expiresAt: expiresAt(tokens.expires_in),
224
- scopes: splitScopes(tokens.scope),
225
- signedInAs: signedInAsFrom(tokens) ?? login.signedInAs
226
- };
227
- }
228
- async function endSignIn(runtime, login) {
229
- const bounded = {
230
- ...runtime,
231
- signal: AbortSignal.any([runtime.signal, AbortSignal.timeout(END_SIGN_IN_TIMEOUT_MS)])
232
- };
233
- try {
234
- const { server } = await readMetadata(bounded, login.appUrl.replace(/\/+$/u, ""));
235
- await postForm(bounded, server.revocation_endpoint, {
236
- client_id: login.clientId,
237
- token: login.refreshToken,
238
- token_type_hint: "refresh_token"
239
- });
240
- return { status: "ended" };
241
- } catch (error) {
242
- return { status: "failed", reason: error instanceof Error ? error.message : String(error) };
243
- }
244
- }
245
- class OAuthHttpError extends Error {
246
- /** The OAuth `error` code, such as `authorization_pending`; null when the reply had none. */
247
- code;
248
- status;
249
- constructor(status, code, message) {
250
- super(message);
251
- this.name = "OAuthHttpError";
252
- this.code = code;
253
- this.status = status;
254
- }
255
- }
256
- async function getJson(runtime, url) {
257
- return await readJson(
258
- await runtime.fetch(url, {
259
- headers: { accept: "application/json" },
260
- signal: runtime.signal
261
- }),
262
- url
263
- );
264
- }
265
- async function postForm(runtime, url, fields) {
266
- return await readJson(
267
- await runtime.fetch(url, {
268
- body: new URLSearchParams(fields),
269
- headers: { accept: "application/json" },
270
- method: "POST",
271
- signal: runtime.signal
272
- }),
273
- url
274
- );
275
- }
276
- const OAuthErrorSchema = import_zod.z.object({
277
- error: import_zod.z.string().optional(),
278
- error_description: import_zod.z.string().optional()
279
- });
280
- async function readJson(response, url) {
281
- const text = await response.text();
282
- const body = text.length === 0 ? null : JSON.parse(text);
283
- if (response.ok) return body;
284
- const reply = OAuthErrorSchema.safeParse(body);
285
- const code = reply.success ? reply.data.error ?? null : null;
286
- const description = (reply.success ? reply.data.error_description : void 0) ?? code ?? `HTTP ${response.status}`;
287
- throw new OAuthHttpError(response.status, code, `${new URL(url).pathname}: ${description}`);
288
- }
289
- async function withTimeout(promise, ms, signal) {
290
- let timer;
291
- const stop = new Promise((_, reject) => {
292
- timer = setTimeout(() => reject(new Error("Sign-in timed out.")), ms);
293
- signal.addEventListener("abort", () => reject(new Error("Sign-in was cancelled.")), {
294
- once: true
295
- });
296
- });
297
- try {
298
- return await Promise.race([promise, stop]);
299
- } finally {
300
- clearTimeout(timer);
301
- }
302
- }
303
- function splitScopes(scope) {
304
- return scope.split(" ").filter((each) => each.length > 0);
305
- }
306
- function expiresAt(expiresInSeconds) {
307
- return new Date(Date.now() + expiresInSeconds * 1e3).toISOString();
308
- }
309
- // Annotate the CommonJS export names for ESM import in node:
310
- 0 && (module.exports = {
311
- DEXTO_CLI_CLIENT_ID,
312
- OAuthHttpError,
313
- endSignIn,
314
- refreshSignIn,
315
- signInWithBrowser,
316
- signInWithDevice
317
- });
@@ -1,63 +0,0 @@
1
- import { type OAuthLogin } from './dexto-accounts.js';
2
- /** Dexto's pre-registered public client for this CLI: no secret, no registration. */
3
- export declare const DEXTO_CLI_CLIENT_ID = "dexto-cli";
4
- /** A loopback listener for the browser's redirect back to the CLI. */
5
- export interface RedirectListener {
6
- /** `http://127.0.0.1:<port>/callback`. */
7
- readonly redirectUri: string;
8
- /** The redirect's query parameters. */
9
- readonly result: Promise<URLSearchParams>;
10
- readonly close: () => void;
11
- }
12
- /** What talking to the OAuth server needs: refreshing and ending a sign-in need only this. */
13
- export interface OAuthServerRuntime {
14
- readonly fetch: typeof globalThis.fetch;
15
- readonly signal: AbortSignal;
16
- }
17
- /** What signing in does outside this module, injected so it can be tested. */
18
- export interface SignInRuntime extends OAuthServerRuntime {
19
- readonly note: (text: string) => void;
20
- readonly openBrowser: (url: string) => Promise<void>;
21
- readonly listenForRedirect: () => Promise<RedirectListener>;
22
- readonly sleep: (ms: number) => Promise<void>;
23
- }
24
- export interface SignInInput {
25
- /** The Dexto app origin, home of its authorization server and MCP. */
26
- readonly appUrl: string;
27
- /** The public API the login is saved for. */
28
- readonly apiBaseUrl: string;
29
- /** The organization to sign in for (id, slug or name), where the approval page starts. */
30
- readonly organization: string | null;
31
- /** Scopes asked for on purpose, besides reading the workspace and Cloud. */
32
- readonly extraScopes: readonly string[];
33
- }
34
- export interface BrowserSignInInput extends SignInInput {
35
- /** Open the browser; when false the URL is only printed. */
36
- readonly openBrowser: boolean;
37
- }
38
- export declare function signInWithBrowser(runtime: SignInRuntime, input: BrowserSignInInput): Promise<OAuthLogin>;
39
- export declare function signInWithDevice(runtime: SignInRuntime, input: SignInInput): Promise<OAuthLogin>;
40
- /**
41
- * Trades the refresh token for new tokens, as the client that signed in; the old refresh token
42
- * stops working.
43
- */
44
- export declare function refreshSignIn(runtime: OAuthServerRuntime, login: OAuthLogin): Promise<OAuthLogin>;
45
- /** What became of a sign-in on its server when logging out. */
46
- export type EndedSignIn = {
47
- readonly status: 'ended';
48
- } | {
49
- readonly status: 'failed';
50
- readonly reason: string;
51
- };
52
- /**
53
- * Ends the sign-in on its server (RFC 7009), so its tokens stop working everywhere. Never throws:
54
- * the login is forgotten either way, and the caller says what happened.
55
- */
56
- export declare function endSignIn(runtime: OAuthServerRuntime, login: OAuthLogin): Promise<EndedSignIn>;
57
- export declare class OAuthHttpError extends Error {
58
- /** The OAuth `error` code, such as `authorization_pending`; null when the reply had none. */
59
- readonly code: string | null;
60
- readonly status: number;
61
- constructor(status: number, code: string | null, message: string);
62
-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T_ID = "dexto-cli";
5
- const BASE_CLOUD_SCOPES = ["cloud:read"];
6
- const DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
7
- const LOGIN_TIMEOUT_MS = 5 * 6e4;
8
- const END_SIGN_IN_TIMEOUT_MS = 1e4;
9
- const ProtectedResourceSchema = z.object({
10
- authorization_servers: z.array(z.string().url()).min(1),
11
- resource: z.string().url(),
12
- scopes_supported: z.array(z.string())
13
- });
14
- const AuthorizationServerSchema = z.object({
15
- authorization_endpoint: z.string().url(),
16
- device_authorization_endpoint: z.string().url(),
17
- revocation_endpoint: z.string().url(),
18
- token_endpoint: z.string().url()
19
- });
20
- const TokenResponseSchema = z.object({
21
- access_token: z.string().min(1),
22
- refresh_token: z.string().min(1),
23
- expires_in: z.number().int().positive(),
24
- scope: z.string(),
25
- /** Who the tokens act as. */
26
- dexto_account: SignedInAsSchema.shape.account.optional(),
27
- dexto_organization: SignedInAsSchema.shape.organization.optional()
28
- });
29
- const DeviceAuthorizationSchema = z.object({
30
- device_code: z.string().min(1),
31
- user_code: z.string().min(1),
32
- expires_in: z.number().int().positive(),
33
- interval: z.number().int().positive().optional(),
34
- verification_uri: z.string().url(),
35
- verification_uri_complete: z.string().url().optional()
36
- });
37
- async function readMetadata(runtime, appUrl) {
38
- const resource = ProtectedResourceSchema.parse(
39
- await getJson(runtime, `${appUrl}/.well-known/oauth-protected-resource/mcp`)
40
- );
41
- const issuer = (resource.authorization_servers[0] ?? appUrl).replace(/\/+$/u, "");
42
- const server = AuthorizationServerSchema.parse(
43
- await getJson(runtime, `${issuer}/.well-known/oauth-authorization-server`)
44
- );
45
- return { resource, server };
46
- }
47
- async function discover(runtime, input) {
48
- const appUrl = input.appUrl.replace(/\/+$/u, "");
49
- const { resource, server } = await readMetadata(runtime, appUrl);
50
- const reading = resource.scopes_supported.filter((scope) => scope.endsWith(":read"));
51
- const scopes = [.../* @__PURE__ */ new Set([...reading, ...BASE_CLOUD_SCOPES, ...input.extraScopes])];
52
- return { appUrl, resource: resource.resource, scopes, server };
53
- }
54
- async function signInWithBrowser(runtime, input) {
55
- const { appUrl, resource, scopes, server } = await discover(runtime, input);
56
- const redirect = await runtime.listenForRedirect();
57
- try {
58
- const verifier = randomBytes(32).toString("base64url");
59
- const state = randomBytes(16).toString("base64url");
60
- const authorizeUrl = new URL(server.authorization_endpoint);
61
- for (const [name, value] of Object.entries({
62
- client_id: DEXTO_CLI_CLIENT_ID,
63
- code_challenge: createHash("sha256").update(verifier).digest("base64url"),
64
- code_challenge_method: "S256",
65
- redirect_uri: redirect.redirectUri,
66
- resource,
67
- response_type: "code",
68
- scope: scopes.join(" "),
69
- state,
70
- ...input.organization === null ? {} : { organization: input.organization }
71
- }))
72
- authorizeUrl.searchParams.set(name, value);
73
- runtime.note(
74
- `Sign in to Dexto in your browser. If it doesn't open, visit:
75
- ${authorizeUrl}`
76
- );
77
- if (input.openBrowser) await runtime.openBrowser(authorizeUrl.toString());
78
- const params = await withTimeout(redirect.result, LOGIN_TIMEOUT_MS, runtime.signal);
79
- if (params.get("state") !== state)
80
- throw new Error("The sign-in reply didn't match this login.");
81
- const error = params.get("error");
82
- if (error !== null)
83
- throw new Error(
84
- error === "access_denied" ? "Sign-in was declined." : `Sign-in failed: ${params.get("error_description") ?? error}.`
85
- );
86
- const code = params.get("code");
87
- if (code === null) throw new Error("The sign-in reply had no code.");
88
- const tokens = TokenResponseSchema.parse(
89
- await postForm(runtime, server.token_endpoint, {
90
- client_id: DEXTO_CLI_CLIENT_ID,
91
- code,
92
- code_verifier: verifier,
93
- grant_type: "authorization_code",
94
- redirect_uri: redirect.redirectUri,
95
- resource
96
- })
97
- );
98
- return toLogin(tokens, {
99
- apiBaseUrl: input.apiBaseUrl,
100
- appUrl,
101
- resource,
102
- tokenEndpoint: server.token_endpoint
103
- });
104
- } finally {
105
- redirect.close();
106
- }
107
- }
108
- async function signInWithDevice(runtime, input) {
109
- const { appUrl, resource, scopes, server } = await discover(runtime, input);
110
- const device = DeviceAuthorizationSchema.parse(
111
- await postForm(runtime, server.device_authorization_endpoint, {
112
- client_id: DEXTO_CLI_CLIENT_ID,
113
- resource,
114
- scope: scopes.join(" "),
115
- ...input.organization === null ? {} : { organization: input.organization }
116
- })
117
- );
118
- runtime.note(
119
- [
120
- device.verification_uri_complete === void 0 ? `To sign in, open this link on any device and enter ${device.user_code}:
121
- ${device.verification_uri}` : `To sign in, open this link on any device and check it shows ${device.user_code}:
122
- ${device.verification_uri_complete}`,
123
- "Only approve this if you just ran dexto login."
124
- ].join("\n")
125
- );
126
- const deadline = Date.now() + device.expires_in * 1e3;
127
- let intervalSeconds = device.interval ?? 5;
128
- while (Date.now() < deadline) {
129
- await runtime.sleep(intervalSeconds * 1e3);
130
- try {
131
- const tokens = TokenResponseSchema.parse(
132
- await postForm(runtime, server.token_endpoint, {
133
- client_id: DEXTO_CLI_CLIENT_ID,
134
- device_code: device.device_code,
135
- grant_type: DEVICE_CODE_GRANT_TYPE,
136
- resource
137
- })
138
- );
139
- return toLogin(tokens, {
140
- apiBaseUrl: input.apiBaseUrl,
141
- appUrl,
142
- resource,
143
- tokenEndpoint: server.token_endpoint
144
- });
145
- } catch (error) {
146
- if (!(error instanceof OAuthHttpError)) throw error;
147
- if (error.code === "authorization_pending") continue;
148
- if (error.code === "slow_down") {
149
- intervalSeconds += 5;
150
- continue;
151
- }
152
- if (error.code === "access_denied") throw new Error("Sign-in was declined.");
153
- if (error.code !== "expired_token") throw error;
154
- break;
155
- }
156
- }
157
- throw new Error("The sign-in code expired. Run dexto login --device again.");
158
- }
159
- function toLogin(tokens, client) {
160
- return {
161
- kind: "oauth",
162
- ...client,
163
- clientId: DEXTO_CLI_CLIENT_ID,
164
- accessToken: tokens.access_token,
165
- refreshToken: tokens.refresh_token,
166
- expiresAt: expiresAt(tokens.expires_in),
167
- scopes: splitScopes(tokens.scope),
168
- savedAt: (/* @__PURE__ */ new Date()).toISOString(),
169
- signedInAs: signedInAsFrom(tokens),
170
- cloudProject: null
171
- };
172
- }
173
- function signedInAsFrom(tokens) {
174
- return tokens.dexto_account === void 0 || tokens.dexto_organization === void 0 ? null : { account: tokens.dexto_account, organization: tokens.dexto_organization };
175
- }
176
- async function refreshSignIn(runtime, login) {
177
- let body;
178
- try {
179
- body = await postForm(runtime, login.tokenEndpoint, {
180
- client_id: login.clientId,
181
- grant_type: "refresh_token",
182
- refresh_token: login.refreshToken,
183
- resource: login.resource
184
- });
185
- } catch (error) {
186
- if (error instanceof OAuthHttpError && error.status === 400)
187
- throw new Error("Your Dexto sign-in has expired. Run dexto login again.");
188
- throw error;
189
- }
190
- const tokens = TokenResponseSchema.parse(body);
191
- return {
192
- ...login,
193
- accessToken: tokens.access_token,
194
- refreshToken: tokens.refresh_token,
195
- expiresAt: expiresAt(tokens.expires_in),
196
- scopes: splitScopes(tokens.scope),
197
- signedInAs: signedInAsFrom(tokens) ?? login.signedInAs
198
- };
199
- }
200
- async function endSignIn(runtime, login) {
201
- const bounded = {
202
- ...runtime,
203
- signal: AbortSignal.any([runtime.signal, AbortSignal.timeout(END_SIGN_IN_TIMEOUT_MS)])
204
- };
205
- try {
206
- const { server } = await readMetadata(bounded, login.appUrl.replace(/\/+$/u, ""));
207
- await postForm(bounded, server.revocation_endpoint, {
208
- client_id: login.clientId,
209
- token: login.refreshToken,
210
- token_type_hint: "refresh_token"
211
- });
212
- return { status: "ended" };
213
- } catch (error) {
214
- return { status: "failed", reason: error instanceof Error ? error.message : String(error) };
215
- }
216
- }
217
- class OAuthHttpError extends Error {
218
- /** The OAuth `error` code, such as `authorization_pending`; null when the reply had none. */
219
- code;
220
- status;
221
- constructor(status, code, message) {
222
- super(message);
223
- this.name = "OAuthHttpError";
224
- this.code = code;
225
- this.status = status;
226
- }
227
- }
228
- async function getJson(runtime, url) {
229
- return await readJson(
230
- await runtime.fetch(url, {
231
- headers: { accept: "application/json" },
232
- signal: runtime.signal
233
- }),
234
- url
235
- );
236
- }
237
- async function postForm(runtime, url, fields) {
238
- return await readJson(
239
- await runtime.fetch(url, {
240
- body: new URLSearchParams(fields),
241
- headers: { accept: "application/json" },
242
- method: "POST",
243
- signal: runtime.signal
244
- }),
245
- url
246
- );
247
- }
248
- const OAuthErrorSchema = z.object({
249
- error: z.string().optional(),
250
- error_description: z.string().optional()
251
- });
252
- async function readJson(response, url) {
253
- const text = await response.text();
254
- const body = text.length === 0 ? null : JSON.parse(text);
255
- if (response.ok) return body;
256
- const reply = OAuthErrorSchema.safeParse(body);
257
- const code = reply.success ? reply.data.error ?? null : null;
258
- const description = (reply.success ? reply.data.error_description : void 0) ?? code ?? `HTTP ${response.status}`;
259
- throw new OAuthHttpError(response.status, code, `${new URL(url).pathname}: ${description}`);
260
- }
261
- async function withTimeout(promise, ms, signal) {
262
- let timer;
263
- const stop = new Promise((_, reject) => {
264
- timer = setTimeout(() => reject(new Error("Sign-in timed out.")), ms);
265
- signal.addEventListener("abort", () => reject(new Error("Sign-in was cancelled.")), {
266
- once: true
267
- });
268
- });
269
- try {
270
- return await Promise.race([promise, stop]);
271
- } finally {
272
- clearTimeout(timer);
273
- }
274
- }
275
- function splitScopes(scope) {
276
- return scope.split(" ").filter((each) => each.length > 0);
277
- }
278
- function expiresAt(expiresInSeconds) {
279
- return new Date(Date.now() + expiresInSeconds * 1e3).toISOString();
280
- }
281
- export {
282
- DEXTO_CLI_CLIENT_ID,
283
- OAuthHttpError,
284
- endSignIn,
285
- refreshSignIn,
286
- signInWithBrowser,
287
- signInWithDevice
288
- };