@deepdynamic/cli 0.0.0-stage → 0.1.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 (84) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +32 -2
  3. package/THIRD_PARTY_NOTICES.txt +102 -0
  4. package/dist/agents/content.js +12 -0
  5. package/dist/agents/edit.js +140 -0
  6. package/dist/agents/install.js +190 -0
  7. package/dist/agents/refresh.js +20 -0
  8. package/dist/agents/setup.js +29 -0
  9. package/dist/agents/targets.js +91 -0
  10. package/dist/auth/credentials.js +63 -0
  11. package/dist/auth/session.js +49 -0
  12. package/dist/cli.js +198 -0
  13. package/dist/commands/account.js +96 -0
  14. package/dist/commands/activity.js +80 -0
  15. package/dist/commands/blocked.js +89 -0
  16. package/dist/commands/deploy/agents.js +11 -0
  17. package/dist/commands/deploy/files.js +62 -0
  18. package/dist/commands/deploy/index.js +95 -0
  19. package/dist/commands/deploy/manifest.js +24 -0
  20. package/dist/commands/deploy/minify.js +27 -0
  21. package/dist/commands/deploy/progress.js +85 -0
  22. package/dist/commands/deploy/ship.js +117 -0
  23. package/dist/commands/deploy/upload.js +125 -0
  24. package/dist/commands/deployments.js +60 -0
  25. package/dist/commands/dns.js +777 -0
  26. package/dist/commands/domains.js +639 -0
  27. package/dist/commands/emails.js +74 -0
  28. package/dist/commands/env.js +194 -0
  29. package/dist/commands/help.js +148 -0
  30. package/dist/commands/keys.js +263 -0
  31. package/dist/commands/login/flow.js +155 -0
  32. package/dist/commands/login/index.js +26 -0
  33. package/dist/commands/logout.js +71 -0
  34. package/dist/commands/mail.js +241 -0
  35. package/dist/commands/notifications.js +133 -0
  36. package/dist/commands/plan.js +355 -0
  37. package/dist/commands/projects.js +838 -0
  38. package/dist/commands/reference.js +2187 -0
  39. package/dist/commands/search.js +86 -0
  40. package/dist/commands/server.js +301 -0
  41. package/dist/commands/sessions.js +114 -0
  42. package/dist/commands/sites.js +102 -0
  43. package/dist/commands/sms.js +65 -0
  44. package/dist/commands/status.js +87 -0
  45. package/dist/commands/support.js +115 -0
  46. package/dist/commands/update.js +100 -0
  47. package/dist/commands/usage.js +51 -0
  48. package/dist/commands/verify.js +149 -0
  49. package/dist/commands/version.js +6 -0
  50. package/dist/guide.js +37 -0
  51. package/dist/http/call.js +6 -0
  52. package/dist/http/request.js +54 -0
  53. package/dist/index.js +11 -0
  54. package/dist/metadata.js +4 -0
  55. package/dist/output.js +9 -0
  56. package/dist/pretty.js +70 -0
  57. package/dist/refresh-skills.js +5 -0
  58. package/dist/registry.js +688 -0
  59. package/dist/runtime/browser.js +15 -0
  60. package/dist/runtime/card-request.js +55 -0
  61. package/dist/runtime/confirm.js +21 -0
  62. package/dist/runtime/development.js +13 -0
  63. package/dist/runtime/domain-name.js +5 -0
  64. package/dist/runtime/dry-run.js +28 -0
  65. package/dist/runtime/env-file.js +55 -0
  66. package/dist/runtime/error-hints.js +26 -0
  67. package/dist/runtime/flags.js +48 -0
  68. package/dist/runtime/login-screen.js +78 -0
  69. package/dist/runtime/page.js +18 -0
  70. package/dist/runtime/project-name.js +1 -0
  71. package/dist/runtime/run-mode.js +7 -0
  72. package/dist/runtime/server-options.js +28 -0
  73. package/dist/runtime/spinner.js +17 -0
  74. package/dist/runtime/suggest.js +22 -0
  75. package/dist/runtime/support.js +13 -0
  76. package/dist/runtime/text-file.js +20 -0
  77. package/dist/runtime/timeout.js +22 -0
  78. package/dist/runtime/update-check.js +158 -0
  79. package/dist/runtime/update-install.js +80 -0
  80. package/dist/runtime/usage-error.js +9 -0
  81. package/dist/setup-agents.js +15 -0
  82. package/dist/site.js +1 -0
  83. package/dist/update-refresh.js +5 -0
  84. package/package.json +46 -3
@@ -0,0 +1,263 @@
1
+ import { defaultAuthDeps } from "../auth/session.js";
2
+ import { httpFailure } from "../http/request.js";
3
+ import { agentResult } from "../output.js";
4
+ import { prettyResult } from "../pretty.js";
5
+ import { confirmationRequired } from "../runtime/confirm.js";
6
+ import { pageRows, pagination, parsePage } from "../runtime/page.js";
7
+ import { plannedChange, plannedRequest, splitDryRun } from "../runtime/dry-run.js";
8
+ import { parseFlags, unknownArgument } from "../runtime/flags.js";
9
+ import { rehearsed } from "./dns.js";
10
+ export const KEYS_PATH = '/api/v1/keys';
11
+ const KINDS = {
12
+ dns: { name: 'DNS Control API key', prefix: 'dd_dns_' },
13
+ s3: { name: 'S3 Control API key', prefix: 'dd_s3_' },
14
+ pay: { name: 'Pay Control API key', prefix: 'dd_pay_' }
15
+ };
16
+ const EXPIRIES = {
17
+ '10m': { minutes: 10, label: '10 minutes' },
18
+ '1h': { minutes: 60, label: '1 hour' },
19
+ '6h': { minutes: 360, label: '6 hours' },
20
+ '1d': { minutes: 1440, label: '1 day' }
21
+ };
22
+ const DEFAULT_EXPIRY = '10m';
23
+ const SCOPES = { 'dns:read': 'DNS read', 'dns:write': 'DNS write', 's3:read': 'Storage read', 's3:write': 'Storage write', 'pay:write': 'Consolidated billing' };
24
+ const CUSTOM_PREFIX = 'dd_key_';
25
+ const KIND_LABELS = { dns: 'DNS Control', s3: 'S3 Control', pay: 'Pay Control', custom: 'Custom' };
26
+ const PAY_SCOPE = /^pay(:|$)/i;
27
+ const KEY_VALUE = /^dd_/i;
28
+ const KEY_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
29
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
30
+ const NAME_MAX = 60;
31
+ const ONCE = 'The key value is shown only now. Store it somewhere safe. deepdynamic keys shows only its prefix.';
32
+ const failure = (code, message) => ({ code, message, display: message });
33
+ const KEY_NOT_FOUND = failure('key_not_found', 'No key with that ID is among your keys. Check them with deepdynamic keys.');
34
+ const KEY_EXISTS = failure('key_exists', 'That key is already issued. Revoke it with deepdynamic keys revoke <key-id> --yes before issuing it again.');
35
+ const ISSUE_STEPS = [
36
+ { stage: 'validate_kind', message: 'Checking the key kind.' },
37
+ { stage: 'resolve_prefix', message: 'Resolving the key prefix.' },
38
+ { stage: 'prepare_request', message: 'Preparing the issue request.' }
39
+ ];
40
+ const PAY_STEPS = [
41
+ ...ISSUE_STEPS.slice(0, 2),
42
+ { stage: 'compute_expiry', message: 'Calculating the expiry.' },
43
+ { stage: 'check_consent', message: 'Checking consent to consolidated billing.' },
44
+ ...ISSUE_STEPS.slice(2)
45
+ ];
46
+ const CREATE_STEPS = [
47
+ { stage: 'validate_name', message: 'Checking the key name.' },
48
+ { stage: 'normalize_scopes', message: 'Normalizing the scopes.' },
49
+ { stage: 'prepare_request', message: 'Preparing the create request.' }
50
+ ];
51
+ const REVOKE_STEPS = [
52
+ { stage: 'validate_id', message: 'Checking the key ID format.' },
53
+ { stage: 'summarize_impact', message: 'Summarizing the access that revoking blocks.' },
54
+ { stage: 'prepare_request', message: 'Preparing the revoke request.' }
55
+ ];
56
+ const valuesOf = (entries, flag) => entries.filter(([name]) => name === flag).map(([, value]) => value);
57
+ const keyUrl = (siteUrl, suffix = '') => new URL(`${KEYS_PATH}${suffix}`, siteUrl).href;
58
+ const keyOf = (body) => body.key;
59
+ const scopeNames = (scopes) => scopes.map((scope) => SCOPES[scope] ?? scope).join(', ');
60
+ const when = (iso) => iso.replace('T', ' ').replace(/\.\d{3}Z$/, ' UTC');
61
+ const count = (amount, noun) => `${amount} ${noun}${amount === 1 ? '' : 's'}`;
62
+ function parseIssue(args) {
63
+ const consented = args.includes('--yes');
64
+ const [kind, ...rest] = args.filter((arg) => arg !== '--yes');
65
+ if (kind === undefined || kind.startsWith('-'))
66
+ return { error: 'Specify the key kind: dns, s3 or pay.' };
67
+ if (!Object.hasOwn(KINDS, kind))
68
+ return { error: `Unknown key kind: ${kind}. Use dns, s3 or pay.` };
69
+ const parsed = parseFlags(rest, ['--expires']);
70
+ if ('error' in parsed)
71
+ return parsed;
72
+ const values = valuesOf(parsed.entries, '--expires');
73
+ if (values.length > 1)
74
+ return { error: '--expires can be given only once.' };
75
+ if (kind !== 'pay' && (values.length || consented)) {
76
+ const flag = values.length ? '--expires' : '--yes';
77
+ return { error: `${flag} is only for pay keys.` };
78
+ }
79
+ const [expires = DEFAULT_EXPIRY] = values;
80
+ if (!Object.hasOwn(EXPIRIES, expires))
81
+ return { error: `--expires must be 10m, 1h, 6h or 1d: ${expires}` };
82
+ return { kind: kind, expiry: kind === 'pay' ? EXPIRIES[expires] : null, consented };
83
+ }
84
+ function parseCreate(args) {
85
+ const parsed = parseFlags(args, ['--label', '--scope']);
86
+ if ('error' in parsed)
87
+ return parsed;
88
+ const names = valuesOf(parsed.entries, '--label');
89
+ const given = valuesOf(parsed.entries, '--scope');
90
+ if (names.length === 0)
91
+ return { error: '--label is required.' };
92
+ if (names.length > 1)
93
+ return { error: '--label can be given only once.' };
94
+ const name = names[0].trim();
95
+ if (CONTROL.test(name))
96
+ return { error: 'The key name cannot contain control characters such as line breaks.' };
97
+ if (!name || name.length > NAME_MAX)
98
+ return { error: `--label must be 1-${NAME_MAX} characters.` };
99
+ if (given.length === 0)
100
+ return { error: 'At least one --scope is required.' };
101
+ const pay = given.find((scope) => PAY_SCOPE.test(scope));
102
+ if (pay)
103
+ return { error: `Payment scopes such as ${pay} are issued only with a temporary Pay Control key. Use deepdynamic keys issue pay.` };
104
+ const unknown = given.find((scope) => !Object.hasOwn(SCOPES, scope));
105
+ if (unknown)
106
+ return { error: `Unknown scope: ${unknown}. Use dns:read, dns:write, s3:read or s3:write.` };
107
+ return { name, scopes: Object.keys(SCOPES).filter((scope) => scope !== 'pay:write' && given.includes(scope)) };
108
+ }
109
+ function parseRevoke(args) {
110
+ const option = args.find((arg) => arg.startsWith('-'));
111
+ if (option)
112
+ return { error: unknownArgument(option) };
113
+ if (args.length !== 1)
114
+ return { error: 'Specify exactly one key ID.' };
115
+ if (KEY_VALUE.test(args[0]))
116
+ return { error: 'Pass the key ID listed by deepdynamic keys, not the key value.' };
117
+ const id = args[0].toLowerCase();
118
+ if (!KEY_ID.test(id))
119
+ return { error: 'Key IDs are UUIDs as listed by deepdynamic keys.' };
120
+ return id;
121
+ }
122
+ function keyRows(key) {
123
+ return [
124
+ ['Key', `${KIND_LABELS[key.kind] ?? key.kind} · ${key.name}`],
125
+ ['Key ID', key.id],
126
+ ...(key.token ? [['Key value', key.token], ['Warning', ONCE]] : [['Prefix', `${key.prefix}…`]]),
127
+ ['Scopes', scopeNames(key.scopes)],
128
+ ['Issued', when(key.createdAt)],
129
+ ['Expires', when(key.expiresAt)]
130
+ ];
131
+ }
132
+ function issued(command, pretty, depth, message, body, siteUrl) {
133
+ const key = keyOf(body);
134
+ return pretty
135
+ ? prettyResult(0, depth, command, message, [['Server', siteUrl], ...keyRows(key)])
136
+ : agentResult(0, { command, siteUrl, applied: true, key });
137
+ }
138
+ export async function runKeysList(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
139
+ const command = 'keys';
140
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
141
+ const page = parsePage(rest);
142
+ if (typeof page !== 'number')
143
+ return page;
144
+ const listUrl = (siteUrl) => `${keyUrl(siteUrl)}?page=${page}`;
145
+ return {
146
+ steps: [{ stage: 'prepare_request', message: 'Preparing the key list request.' }],
147
+ result: (siteUrl) => plannedRequest(command, pretty, depth, siteUrl, listUrl(siteUrl)),
148
+ send: {
149
+ method: 'GET',
150
+ url: listUrl,
151
+ spinner: 'Loading your API keys.',
152
+ failed: 'Could not load your API keys.',
153
+ notFound: httpFailure(404),
154
+ done: (body, siteUrl) => {
155
+ const { keys, ...paged } = body;
156
+ const paging = pagination(paged, command);
157
+ if (!pretty)
158
+ return agentResult(0, { command, siteUrl, ...paging, keys });
159
+ return prettyResult(0, depth, command, keys.length ? `Loaded ${count(keys.length, 'key')}.` : 'You have no API keys. Issue one with deepdynamic keys issue or deepdynamic keys create.', [
160
+ ['Server', siteUrl],
161
+ ...keys.map((key) => [key.id, `${KIND_LABELS[key.kind] ?? key.kind} · ${key.name} · ${key.prefix}… · ${scopeNames(key.scopes)} · Expires ${when(key.expiresAt)}`]),
162
+ ...pageRows(paging)
163
+ ]);
164
+ }
165
+ }
166
+ };
167
+ });
168
+ }
169
+ export async function runKeysIssue(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
170
+ const command = 'keys issue';
171
+ const { args: rest, dryRun } = splitDryRun(args);
172
+ const pre = parseIssue(rest);
173
+ if (!('error' in pre) && pre.expiry && !pre.consented && !dryRun) {
174
+ return confirmationRequired(command, rest, pretty, depth, {
175
+ message: 'A pay key needs the consent to paid services and consolidated billing, and it can charge the account.',
176
+ display: 'Issuing a pay key needs consent to paid services and consolidated billing. Confirm with the user, then run it with --yes.'
177
+ });
178
+ }
179
+ return rehearsed(command, args, pretty, depth, deps, (plain) => {
180
+ const parsed = parseIssue(plain);
181
+ if ('error' in parsed)
182
+ return parsed;
183
+ const { kind, expiry, consented } = parsed;
184
+ const { name, prefix } = KINDS[kind];
185
+ const term = expiry ? { expiresInMinutes: expiry.minutes } : {};
186
+ const consent = expiry ? { consentRequired: true, consented } : {};
187
+ const body = { kind, ...term, ...(expiry && consented ? { consented: true } : {}) };
188
+ const payRows = expiry
189
+ ? [
190
+ ['Valid for', expiry.label],
191
+ ['Consolidated billing', consented ? 'Agreed (--yes)' : 'Required. Add --yes once the user agrees to paid services and consolidated billing.'],
192
+ ['Warning', 'This key can charge the account.']
193
+ ]
194
+ : [];
195
+ return {
196
+ steps: expiry ? PAY_STEPS : ISSUE_STEPS,
197
+ result: (siteUrl) => plannedChange(command, pretty, depth, siteUrl, { url: keyUrl(siteUrl), body }, 'Checked the key issue request. No key was issued.', [['Key', name], ['Prefix', prefix], ...payRows], { kind, name, prefix, ...term, ...consent }),
198
+ send: {
199
+ method: 'POST',
200
+ url: (siteUrl) => keyUrl(siteUrl),
201
+ body,
202
+ spinner: 'Issuing the key.',
203
+ failed: 'Could not issue the key.',
204
+ notFound: httpFailure(404),
205
+ conflict: KEY_EXISTS,
206
+ done: (result, siteUrl) => issued(command, pretty, depth, `Issued the ${name}.`, result, siteUrl)
207
+ }
208
+ };
209
+ });
210
+ }
211
+ export async function runKeysCreate(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
212
+ const command = 'keys create';
213
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
214
+ const parsed = parseCreate(rest);
215
+ if ('error' in parsed)
216
+ return parsed;
217
+ const { name, scopes } = parsed;
218
+ const body = { kind: 'custom', name, scopes };
219
+ return {
220
+ steps: CREATE_STEPS,
221
+ result: (siteUrl) => plannedChange(command, pretty, depth, siteUrl, { url: keyUrl(siteUrl), body }, 'Checked the key create request. No key was created.', [['Name', name], ['Prefix', CUSTOM_PREFIX], ['Scopes', scopeNames(scopes)]], { name, prefix: CUSTOM_PREFIX, scopes }),
222
+ send: {
223
+ method: 'POST',
224
+ url: (siteUrl) => keyUrl(siteUrl),
225
+ body,
226
+ spinner: 'Creating the key.',
227
+ failed: 'Could not create the key.',
228
+ notFound: httpFailure(404),
229
+ conflict: KEY_EXISTS,
230
+ done: (result, siteUrl) => issued(command, pretty, depth, `Created the key ${name}.`, result, siteUrl)
231
+ }
232
+ };
233
+ });
234
+ }
235
+ export async function runKeysRevoke(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
236
+ const command = 'keys revoke';
237
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
238
+ const id = parseRevoke(rest);
239
+ if (typeof id !== 'string')
240
+ return id;
241
+ return {
242
+ steps: REVOKE_STEPS,
243
+ result: (siteUrl) => plannedChange(command, pretty, depth, siteUrl, { url: keyUrl(siteUrl, `/${encodeURIComponent(id)}/revoke`), body: {} }, 'Checked the key revoke request. The key was not revoked.', [['Key ID', id], ['Impact', 'Revoking blocks every agent and tool that uses this key at once.']], { keyId: id }),
244
+ send: {
245
+ method: 'POST',
246
+ url: (siteUrl) => keyUrl(siteUrl, `/${encodeURIComponent(id)}/revoke`),
247
+ body: {},
248
+ spinner: 'Revoking the key.',
249
+ failed: 'Could not revoke the key.',
250
+ notFound: KEY_NOT_FOUND,
251
+ done: (result, siteUrl) => {
252
+ const key = keyOf(result);
253
+ return pretty
254
+ ? prettyResult(0, depth, command, `Revoked the key ${key.name}.`, [['Server', siteUrl], ['Key ID', key.id], ['Key', `${KIND_LABELS[key.kind] ?? key.kind} · ${key.name}`], ['Impact', 'Agents and tools that used this key are now blocked.']])
255
+ : agentResult(0, { command, siteUrl, applied: true, keyId: key.id, key });
256
+ }
257
+ }
258
+ };
259
+ }, {
260
+ message: 'Revoking blocks every agent and tool that uses the key at once.',
261
+ display: 'Revoking blocks every agent and tool that uses the key at once. Confirm with the user, then run it with --yes.'
262
+ });
263
+ }
@@ -0,0 +1,155 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import { finished } from 'node:stream';
4
+ import { saveCredentials } from "../../auth/credentials.js";
5
+ import { call } from "../../http/call.js";
6
+ import { SITE_URL } from "../../metadata.js";
7
+ import { agentResult } from "../../output.js";
8
+ import { prettyResult } from "../../pretty.js";
9
+ import { openBrowser } from "../../runtime/browser.js";
10
+ import { startLoginScreen } from "../../runtime/login-screen.js";
11
+ import { supportMessage } from "../../runtime/support.js";
12
+ export const CLIENT_ID = 'dd-cli';
13
+ export const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
14
+ export const defaultLoginDeps = () => ({
15
+ siteUrl: SITE_URL,
16
+ fetch,
17
+ openBrowser,
18
+ saveCredentials: (credentials) => saveCredentials(credentials),
19
+ log: (text) => process.stderr.write(text),
20
+ stream: process.stdout.isTTY ? process.stderr : undefined,
21
+ timeoutMs: LOGIN_TIMEOUT_MS
22
+ });
23
+ const failure = (pretty, depth, code, message) => pretty
24
+ ? prettyResult(1, depth, 'login', message)
25
+ : agentResult(1, { command: 'login', error: { code, message } });
26
+ const supportResult = (pretty, depth, code) => failure(pretty, depth, code, supportMessage(code));
27
+ export const redirectUri = (port) => `http://127.0.0.1:${port}/callback`;
28
+ export function authorizeUrl(siteUrl, port, challenge, state, agent = false) {
29
+ const url = new URL('/login/device', siteUrl);
30
+ url.search = new URLSearchParams({
31
+ response_type: 'code',
32
+ client_id: CLIENT_ID,
33
+ redirect_uri: redirectUri(port),
34
+ code_challenge: challenge,
35
+ code_challenge_method: 'S256',
36
+ state,
37
+ ...(agent ? { requested_by: 'agent' } : {})
38
+ }).toString();
39
+ return url.href;
40
+ }
41
+ function land(response, siteUrl, status) {
42
+ const url = new URL('/login/device', siteUrl);
43
+ if (status)
44
+ url.searchParams.set('status', status);
45
+ return new Promise((resolve) => {
46
+ finished(response, () => resolve());
47
+ response.writeHead(302, { Location: url.href, Connection: 'close' }).end();
48
+ });
49
+ }
50
+ async function finish(deps, code, verifier, port, pretty, depth) {
51
+ const tokenResponse = await call(new URL('/login/token', deps.siteUrl).href, {
52
+ method: 'POST',
53
+ headers: { 'content-type': 'application/json' },
54
+ body: JSON.stringify({
55
+ grant_type: 'authorization_code',
56
+ client_id: CLIENT_ID,
57
+ code,
58
+ redirect_uri: redirectUri(port),
59
+ code_verifier: verifier
60
+ }),
61
+ redirect: 'manual'
62
+ }, deps.fetch);
63
+ const token = (await tokenResponse.json().catch(() => null));
64
+ if (!tokenResponse.ok || typeof token?.access_token !== 'string' || typeof token.expires_in !== 'number') {
65
+ return supportResult(pretty, depth, 'token_exchange_failed');
66
+ }
67
+ const meResponse = await call(new URL('/api/v1/me', deps.siteUrl).href, {
68
+ headers: { authorization: `Bearer ${token.access_token}` },
69
+ redirect: 'manual'
70
+ }, deps.fetch);
71
+ const me = (await meResponse.json().catch(() => null));
72
+ if (!meResponse.ok || !me?.user) {
73
+ return supportResult(pretty, depth, 'account_fetch_failed');
74
+ }
75
+ const path = await deps.saveCredentials({
76
+ siteUrl: deps.siteUrl,
77
+ email: me.user.email,
78
+ accessToken: token.access_token,
79
+ expiresAt: new Date(Date.now() + token.expires_in * 1000).toISOString()
80
+ });
81
+ if (!pretty) {
82
+ return agentResult(0, {
83
+ command: 'login',
84
+ account: { email: me.user.email },
85
+ siteUrl: deps.siteUrl,
86
+ credentialsPath: path
87
+ });
88
+ }
89
+ return prettyResult(0, depth, 'login', 'Logged in.', [
90
+ ['Account', me.user.email ?? me.user.name ?? 'Account without email'],
91
+ ['Credentials', path]
92
+ ]);
93
+ }
94
+ export async function login(deps, pretty = false, depth = 1) {
95
+ const verifier = randomBytes(32).toString('base64url');
96
+ const challenge = createHash('sha256').update(verifier).digest('base64url');
97
+ const state = randomBytes(32).toString('base64url');
98
+ let settle = () => { };
99
+ const received = new Promise((resolve) => {
100
+ settle = resolve;
101
+ });
102
+ let done = false;
103
+ const server = createServer((request, response) => {
104
+ const url = new URL(request.url ?? '/', 'http://127.0.0.1');
105
+ const code = url.searchParams.get('code');
106
+ const error = url.searchParams.get('error');
107
+ if (done || url.pathname !== '/callback' || url.searchParams.get('state') !== state || (!code && !error)) {
108
+ response.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' }).end('Invalid request.');
109
+ return;
110
+ }
111
+ done = true;
112
+ settle(code ? { response, code } : { response, error: error });
113
+ });
114
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
115
+ const { port } = server.address();
116
+ const timer = setTimeout(() => settle(null), deps.timeoutMs);
117
+ const url = authorizeUrl(deps.siteUrl, port, challenge, state, !pretty);
118
+ const notice = `Finish logging in to DeepDynamic Cloud in your browser.\nIf the browser does not open, open this URL yourself.\n ${url}\n`;
119
+ let stop;
120
+ try {
121
+ stop = pretty ? startLoginScreen(url, deps.stream) : undefined;
122
+ if (!stop) {
123
+ deps.log(pretty
124
+ ? notice
125
+ : `${JSON.stringify({
126
+ event: 'login_required',
127
+ message: 'Ask the user to sign in to DeepDynamic Cloud in the browser window that opened. If it did not open, give them the URL.',
128
+ url,
129
+ timeoutMs: deps.timeoutMs
130
+ })}\n`);
131
+ }
132
+ deps.openBrowser(url);
133
+ const callback = await received;
134
+ clearTimeout(timer);
135
+ if (!callback) {
136
+ return failure(pretty, depth, 'login_timeout', 'Login timed out. Run deepdynamic login to try again.');
137
+ }
138
+ if ('error' in callback) {
139
+ const cancelled = callback.error === 'access_denied';
140
+ await land(callback.response, deps.siteUrl, cancelled ? 'cancelled' : null);
141
+ return cancelled
142
+ ? failure(pretty, depth, 'login_cancelled', 'Login was cancelled.')
143
+ : supportResult(pretty, depth, 'login_failed');
144
+ }
145
+ const result = await finish(deps, callback.code, verifier, port, pretty, depth).catch(() => supportResult(pretty, depth, 'login_failed'));
146
+ await land(callback.response, deps.siteUrl, result.code === 0 ? 'connected' : null);
147
+ return result;
148
+ }
149
+ finally {
150
+ clearTimeout(timer);
151
+ server.close();
152
+ server.closeAllConnections();
153
+ stop?.();
154
+ }
155
+ }
@@ -0,0 +1,26 @@
1
+ import { agentResult } from "../../output.js";
2
+ import { prettyResult } from "../../pretty.js";
3
+ import { spec } from "../../registry.js";
4
+ import { plannedRequest, splitDryRun } from "../../runtime/dry-run.js";
5
+ import { parseServerArgs } from "../../runtime/server-options.js";
6
+ import { defaultLoginDeps, login } from "./flow.js";
7
+ const { name: command, usage } = spec('login');
8
+ export async function runLogin(args, pretty, depth, loginDeps) {
9
+ const { args: rest, dryRun } = splitDryRun(args);
10
+ const options = parseServerArgs(rest);
11
+ if ('error' in options) {
12
+ if (!pretty) {
13
+ return agentResult(2, {
14
+ command,
15
+ error: { code: 'invalid_arguments', message: options.error },
16
+ usage
17
+ });
18
+ }
19
+ return prettyResult(2, depth, command, options.error, [['Usage', usage]]);
20
+ }
21
+ const deps = loginDeps ?? defaultLoginDeps();
22
+ const siteUrl = options.siteUrl ?? deps.siteUrl;
23
+ if (dryRun)
24
+ return plannedRequest(command, pretty, depth, siteUrl, new URL('/login/device', siteUrl).href);
25
+ return login({ ...deps, siteUrl }, pretty, depth);
26
+ }
@@ -0,0 +1,71 @@
1
+ import { credentialsPath, readAccessToken, readAccountEmail, removeCredentials } from "../auth/credentials.js";
2
+ import { loginSiteUrl } from "../auth/session.js";
3
+ import { accepted, httpFailure, request } from "../http/request.js";
4
+ import { agentResult } from "../output.js";
5
+ import { prettyResult } from "../pretty.js";
6
+ import { spec } from "../registry.js";
7
+ import { splitDryRun } from "../runtime/dry-run.js";
8
+ import { unknownArgument } from "../runtime/flags.js";
9
+ import { CLIENT_ID } from "./login/flow.js";
10
+ const { usage } = spec('logout');
11
+ const LOGOUT_PATH = '/login/revoke';
12
+ const TOKEN_SETTINGS_PATH = '/projects';
13
+ export async function runLogout(args, pretty, depth, deps) {
14
+ const { args: rest, dryRun } = splitDryRun(args);
15
+ if (rest.length > 0) {
16
+ const message = unknownArgument(rest[0]);
17
+ return pretty
18
+ ? prettyResult(2, depth, 'logout', message, [['Usage', usage]])
19
+ : agentResult(2, { command: 'logout', error: { code: 'invalid_arguments', message }, usage });
20
+ }
21
+ const path = credentialsPath();
22
+ const token = await readAccessToken(path);
23
+ if (!token) {
24
+ if (!dryRun)
25
+ await removeCredentials(path);
26
+ return pretty
27
+ ? prettyResult(0, depth, 'logout', 'Already logged out.')
28
+ : agentResult(0, { command: 'logout', account: null, credentialsPath: path, ...(dryRun ? { dryRun: true } : {}) });
29
+ }
30
+ const email = await readAccountEmail(path);
31
+ const siteUrl = await loginSiteUrl();
32
+ const url = new URL(LOGOUT_PATH, siteUrl).href;
33
+ if (dryRun) {
34
+ return pretty
35
+ ? prettyResult(0, depth, 'logout', 'Checked without sending the request.', [['Server', siteUrl], ['Request', `POST ${url}`]])
36
+ : agentResult(0, { command: 'logout', account: { email }, siteUrl, credentialsPath: path, dryRun: true, request: { method: 'POST', url } });
37
+ }
38
+ const result = await request(url, {
39
+ method: 'POST',
40
+ headers: { 'content-type': 'application/json' },
41
+ body: JSON.stringify({ client_id: CLIENT_ID, token })
42
+ }, deps, pretty ? 'Revoking the access token.' : null);
43
+ await removeCredentials(path);
44
+ const failure = 'failure' in result
45
+ ? result.failure
46
+ : accepted(result) ? null : httpFailure(result.status);
47
+ const settings = new URL(TOKEN_SETTINGS_PATH, siteUrl).href;
48
+ if (failure) {
49
+ return pretty
50
+ ? prettyResult(1, depth, 'logout', 'Deleted the saved login, but could not revoke the access token on the server.', [
51
+ ['Server', siteUrl],
52
+ ['Reason', failure.display],
53
+ ['Revoke at', settings]
54
+ ])
55
+ : agentResult(1, {
56
+ command: 'logout',
57
+ account: { email },
58
+ siteUrl,
59
+ credentialsPath: path,
60
+ revoked: false,
61
+ error: {
62
+ code: failure.code,
63
+ message: `${failure.message} The saved login was removed, but the token is still valid on the server. Revoke the "DeepDynamic CLI" token at ${settings}.`,
64
+ retryable: false
65
+ }
66
+ });
67
+ }
68
+ return pretty
69
+ ? prettyResult(0, depth, 'logout', 'Logged out.', [['Account', email ?? 'Account without email'], ['Deleted', path]])
70
+ : agentResult(0, { command: 'logout', account: { email }, siteUrl, credentialsPath: path, revoked: true });
71
+ }