@deepdynamic/cli 0.0.0-stage → 0.1.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 (82) 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 +180 -0
  7. package/dist/agents/setup.js +29 -0
  8. package/dist/agents/targets.js +91 -0
  9. package/dist/auth/credentials.js +63 -0
  10. package/dist/auth/session.js +49 -0
  11. package/dist/cli.js +198 -0
  12. package/dist/commands/account.js +96 -0
  13. package/dist/commands/activity.js +80 -0
  14. package/dist/commands/blocked.js +89 -0
  15. package/dist/commands/deploy/agents.js +11 -0
  16. package/dist/commands/deploy/files.js +62 -0
  17. package/dist/commands/deploy/index.js +95 -0
  18. package/dist/commands/deploy/manifest.js +24 -0
  19. package/dist/commands/deploy/minify.js +27 -0
  20. package/dist/commands/deploy/progress.js +85 -0
  21. package/dist/commands/deploy/ship.js +117 -0
  22. package/dist/commands/deploy/upload.js +125 -0
  23. package/dist/commands/deployments.js +59 -0
  24. package/dist/commands/dns.js +791 -0
  25. package/dist/commands/domains.js +711 -0
  26. package/dist/commands/emails.js +74 -0
  27. package/dist/commands/env.js +194 -0
  28. package/dist/commands/help.js +149 -0
  29. package/dist/commands/keys.js +269 -0
  30. package/dist/commands/login/flow.js +155 -0
  31. package/dist/commands/login/index.js +26 -0
  32. package/dist/commands/logout.js +71 -0
  33. package/dist/commands/mail.js +241 -0
  34. package/dist/commands/notifications.js +132 -0
  35. package/dist/commands/plan.js +371 -0
  36. package/dist/commands/projects.js +836 -0
  37. package/dist/commands/reference.js +2180 -0
  38. package/dist/commands/search.js +75 -0
  39. package/dist/commands/server.js +314 -0
  40. package/dist/commands/sessions.js +120 -0
  41. package/dist/commands/sites.js +102 -0
  42. package/dist/commands/sms.js +65 -0
  43. package/dist/commands/status.js +87 -0
  44. package/dist/commands/support.js +115 -0
  45. package/dist/commands/update.js +98 -0
  46. package/dist/commands/usage.js +51 -0
  47. package/dist/commands/verify.js +149 -0
  48. package/dist/commands/version.js +6 -0
  49. package/dist/guide.js +76 -0
  50. package/dist/http/call.js +6 -0
  51. package/dist/http/request.js +54 -0
  52. package/dist/index.js +11 -0
  53. package/dist/metadata.js +4 -0
  54. package/dist/output.js +9 -0
  55. package/dist/pretty.js +70 -0
  56. package/dist/registry.js +760 -0
  57. package/dist/runtime/browser.js +15 -0
  58. package/dist/runtime/card-request.js +55 -0
  59. package/dist/runtime/confirm.js +21 -0
  60. package/dist/runtime/development.js +13 -0
  61. package/dist/runtime/domain-name.js +5 -0
  62. package/dist/runtime/dry-run.js +28 -0
  63. package/dist/runtime/env-file.js +58 -0
  64. package/dist/runtime/error-hints.js +26 -0
  65. package/dist/runtime/flags.js +50 -0
  66. package/dist/runtime/login-screen.js +78 -0
  67. package/dist/runtime/page.js +18 -0
  68. package/dist/runtime/project-name.js +1 -0
  69. package/dist/runtime/run-mode.js +7 -0
  70. package/dist/runtime/server-options.js +32 -0
  71. package/dist/runtime/spinner.js +15 -0
  72. package/dist/runtime/suggest.js +22 -0
  73. package/dist/runtime/support.js +14 -0
  74. package/dist/runtime/text-file.js +20 -0
  75. package/dist/runtime/timeout.js +22 -0
  76. package/dist/runtime/update-check.js +124 -0
  77. package/dist/runtime/update-install.js +50 -0
  78. package/dist/runtime/usage-error.js +9 -0
  79. package/dist/setup-agents.js +8 -0
  80. package/dist/site.js +1 -0
  81. package/dist/update-refresh.js +5 -0
  82. package/package.json +46 -3
@@ -0,0 +1,269 @@
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 { fail, rehearsed } from "./dns.js";
10
+ export const KEYS_PATH = '/api/v1/keys';
11
+ const KINDS = {
12
+ dns: { name: 'DNS Control API key', label: 'DNS Control API 키', prefix: 'dd_dns_' },
13
+ s3: { name: 'S3 Control API key', label: 'S3 Control API 키', prefix: 'dd_s3_' },
14
+ pay: { name: 'Pay Control API key', label: 'Pay Control API 키', prefix: 'dd_pay_' }
15
+ };
16
+ const EXPIRIES = {
17
+ '10m': { minutes: 10, label: '10분' },
18
+ '1h': { minutes: 60, label: '1시간' },
19
+ '6h': { minutes: 360, label: '6시간' },
20
+ '1d': { minutes: 1440, label: '1일' }
21
+ };
22
+ const DEFAULT_EXPIRY = '10m';
23
+ const SCOPES = { 'dns:read': 'DNS 조회', 'dns:write': 'DNS 변경', 's3:read': '저장소 조회', 's3:write': '저장소 변경', 'pay:write': '결제 합산' };
24
+ const CUSTOM_PREFIX = 'dd_key_';
25
+ const KIND_LABELS = { dns: 'DNS Control', s3: 'S3 Control', pay: 'Pay Control', 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 = '키 값은 지금만 보여 드립니다. 안전한 곳에 보관하세요. deepdynamic keys 에는 앞부분만 나옵니다.';
32
+ const KEY_NOT_FOUND = {
33
+ code: 'key_not_found',
34
+ message: 'No key with that ID is among your keys. Check them with deepdynamic keys.',
35
+ display: '내 키 목록에 없는 키 ID 입니다.'
36
+ };
37
+ const KEY_EXISTS = {
38
+ code: 'key_exists',
39
+ message: 'That key is already issued. Revoke it with deepdynamic keys revoke <key-id> --yes before issuing it again.',
40
+ display: '이미 발급된 키입니다. deepdynamic keys revoke <키 ID> --yes 로 취소한 뒤 다시 발급하세요.'
41
+ };
42
+ const ISSUE_STEPS = [
43
+ { stage: 'validate_kind', message: '키 종류를 확인하고 있습니다.' },
44
+ { stage: 'resolve_prefix', message: '키 접두사를 정하고 있습니다.' },
45
+ { stage: 'prepare_request', message: '발급 요청을 준비하고 있습니다.' }
46
+ ];
47
+ const PAY_STEPS = [
48
+ ...ISSUE_STEPS.slice(0, 2),
49
+ { stage: 'compute_expiry', message: '유효기간을 계산하고 있습니다.' },
50
+ { stage: 'check_consent', message: '결제 합산 동의를 확인하고 있습니다.' },
51
+ ...ISSUE_STEPS.slice(2)
52
+ ];
53
+ const CREATE_STEPS = [
54
+ { stage: 'validate_name', message: '키 이름을 확인하고 있습니다.' },
55
+ { stage: 'normalize_scopes', message: '권한을 정리하고 있습니다.' },
56
+ { stage: 'prepare_request', message: '생성 요청을 준비하고 있습니다.' }
57
+ ];
58
+ const REVOKE_STEPS = [
59
+ { stage: 'validate_id', message: '키 ID 형식을 확인하고 있습니다.' },
60
+ { stage: 'summarize_impact', message: '취소하면 막히는 접근을 정리하고 있습니다.' },
61
+ { stage: 'prepare_request', message: '취소 요청을 준비하고 있습니다.' }
62
+ ];
63
+ const valuesOf = (entries, flag) => entries.filter(([name]) => name === flag).map(([, value]) => value);
64
+ const keyUrl = (siteUrl, suffix = '') => new URL(`${KEYS_PATH}${suffix}`, siteUrl).href;
65
+ const keyOf = (body) => body.key;
66
+ const scopeNames = (scopes) => scopes.map((scope) => SCOPES[scope] ?? scope).join(', ');
67
+ const when = (iso) => iso.replace('T', ' ').replace(/\.\d{3}Z$/, ' UTC');
68
+ function parseIssue(args, pretty) {
69
+ const consented = args.includes('--yes');
70
+ const [kind, ...rest] = args.filter((arg) => arg !== '--yes');
71
+ if (kind === undefined || kind.startsWith('-'))
72
+ return fail(pretty, 'Specify the key kind: dns, s3 or pay.', '발급할 키 종류(dns, s3, pay)를 지정하세요.');
73
+ if (!Object.hasOwn(KINDS, kind))
74
+ return fail(pretty, `Unknown key kind: ${kind}. Use dns, s3 or pay.`, `알 수 없는 키 종류입니다: ${kind}. dns, s3, pay 중 하나를 지정하세요.`);
75
+ const parsed = parseFlags(rest, ['--expires'], pretty);
76
+ if ('error' in parsed)
77
+ return parsed;
78
+ const values = valuesOf(parsed.entries, '--expires');
79
+ if (values.length > 1)
80
+ return fail(pretty, '--expires can be given only once.', '--expires 는 한 번만 지정하세요.');
81
+ if (kind !== 'pay' && (values.length || consented)) {
82
+ const flag = values.length ? '--expires' : '--yes';
83
+ return fail(pretty, `${flag} is only for pay keys.`, `${flag} 는 pay 키에만 씁니다.`);
84
+ }
85
+ const [expires = DEFAULT_EXPIRY] = values;
86
+ if (!Object.hasOwn(EXPIRIES, expires))
87
+ return fail(pretty, `--expires must be 10m, 1h, 6h or 1d: ${expires}`, `--expires 에는 10m, 1h, 6h, 1d 중 하나를 지정하세요: ${expires}`);
88
+ return { kind: kind, expiry: kind === 'pay' ? EXPIRIES[expires] : null, consented };
89
+ }
90
+ function parseCreate(args, pretty) {
91
+ const parsed = parseFlags(args, ['--label', '--scope'], pretty);
92
+ if ('error' in parsed)
93
+ return parsed;
94
+ const names = valuesOf(parsed.entries, '--label');
95
+ const given = valuesOf(parsed.entries, '--scope');
96
+ if (names.length === 0)
97
+ return fail(pretty, '--label is required.', '--label 을 지정하세요.');
98
+ if (names.length > 1)
99
+ return fail(pretty, '--label can be given only once.', '--label 은 한 번만 지정하세요.');
100
+ const name = names[0].trim();
101
+ if (CONTROL.test(name))
102
+ return fail(pretty, 'The key name cannot contain control characters such as line breaks.', '키 이름에는 줄바꿈 같은 제어 문자를 쓸 수 없습니다.');
103
+ if (!name || name.length > NAME_MAX)
104
+ return fail(pretty, `--label must be 1-${NAME_MAX} characters.`, `--label 은 1~${NAME_MAX}자로 지정하세요.`);
105
+ if (given.length === 0)
106
+ return fail(pretty, 'At least one --scope is required.', '--scope 를 하나 이상 지정하세요.');
107
+ const pay = given.find((scope) => PAY_SCOPE.test(scope));
108
+ if (pay)
109
+ return fail(pretty, `Payment scopes such as ${pay} are issued only with a temporary Pay Control key. Use deepdynamic keys issue pay.`, '결제 권한은 Pay Control 임시 키로만 발급됩니다. deepdynamic keys issue pay 를 쓰세요.');
110
+ const unknown = given.find((scope) => !Object.hasOwn(SCOPES, scope));
111
+ if (unknown)
112
+ return fail(pretty, `Unknown scope: ${unknown}. Use dns:read, dns:write, s3:read or s3:write.`, `알 수 없는 권한입니다: ${unknown}. dns:read, dns:write, s3:read, s3:write 중에서 고르세요.`);
113
+ return { name, scopes: Object.keys(SCOPES).filter((scope) => scope !== 'pay:write' && given.includes(scope)) };
114
+ }
115
+ function parseRevoke(args, pretty) {
116
+ const option = args.find((arg) => arg.startsWith('-'));
117
+ if (option)
118
+ return { error: unknownArgument(option, pretty) };
119
+ if (args.length !== 1)
120
+ return fail(pretty, 'Specify exactly one key ID.', '취소할 키 ID 를 하나만 지정하세요.');
121
+ if (KEY_VALUE.test(args[0]))
122
+ return fail(pretty, 'Pass the key ID listed by deepdynamic keys, not the key value.', '키 값이 아니라 deepdynamic keys 에 나오는 키 ID 를 지정하세요.');
123
+ const id = args[0].toLowerCase();
124
+ if (!KEY_ID.test(id))
125
+ return fail(pretty, 'Key IDs are UUIDs as listed by deepdynamic keys.', '키 ID 는 deepdynamic keys 에 나오는 UUID 형식입니다.');
126
+ return id;
127
+ }
128
+ function keyRows(key) {
129
+ return [
130
+ ['키', `${KIND_LABELS[key.kind] ?? key.kind} · ${key.name}`],
131
+ ['키 ID', key.id],
132
+ ...(key.token ? [['키 값', key.token], ['주의', ONCE]] : [['앞부분', `${key.prefix}…`]]),
133
+ ['권한', scopeNames(key.scopes)],
134
+ ['발급', when(key.createdAt)],
135
+ ['만료', when(key.expiresAt)]
136
+ ];
137
+ }
138
+ function issued(command, pretty, depth, message, body, siteUrl) {
139
+ const key = keyOf(body);
140
+ return pretty
141
+ ? prettyResult(0, depth, command, message, [['서버', siteUrl], ...keyRows(key)])
142
+ : agentResult(0, { command, siteUrl, applied: true, key });
143
+ }
144
+ export async function runKeysList(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
145
+ const command = 'keys';
146
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
147
+ const page = parsePage(rest, pretty);
148
+ if (typeof page !== 'number')
149
+ return page;
150
+ const listUrl = (siteUrl) => `${keyUrl(siteUrl)}?page=${page}`;
151
+ return {
152
+ steps: [{ stage: 'prepare_request', message: '키 목록 요청을 준비하고 있습니다.' }],
153
+ result: (siteUrl) => plannedRequest(command, pretty, depth, siteUrl, listUrl(siteUrl)),
154
+ send: {
155
+ method: 'GET',
156
+ url: listUrl,
157
+ spinner: '발급한 키를 불러오고 있습니다.',
158
+ failed: '발급한 키를 불러오지 못했습니다.',
159
+ notFound: httpFailure(404),
160
+ done: (body, siteUrl) => {
161
+ const { keys, ...paged } = body;
162
+ const paging = pagination(paged, command);
163
+ if (!pretty)
164
+ return agentResult(0, { command, siteUrl, ...paging, keys });
165
+ return prettyResult(0, depth, command, keys.length ? `발급한 키 ${keys.length}개를 불러왔습니다.` : '발급한 키가 없습니다. deepdynamic keys issue 나 deepdynamic keys create 로 발급할 수 있습니다.', [
166
+ ['서버', siteUrl],
167
+ ...keys.map((key) => [key.id, `${KIND_LABELS[key.kind] ?? key.kind} · ${key.name} · ${key.prefix}… · ${scopeNames(key.scopes)} · 만료 ${when(key.expiresAt)}`]),
168
+ ...pageRows(paging)
169
+ ]);
170
+ }
171
+ }
172
+ };
173
+ });
174
+ }
175
+ export async function runKeysIssue(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
176
+ const command = 'keys issue';
177
+ const { args: rest, dryRun } = splitDryRun(args);
178
+ const pre = parseIssue(rest, pretty);
179
+ if (!('error' in pre) && pre.expiry && !pre.consented && !dryRun) {
180
+ return confirmationRequired(command, rest, pretty, depth, {
181
+ message: 'A pay key needs the consent to paid services and consolidated billing, and it can charge the account.',
182
+ display: 'pay 키를 발급하려면 유료 서비스 이용과 결제 합산에 동의해야 합니다. 사용자에게 확인한 뒤 --yes 를 붙여 실행하세요.'
183
+ });
184
+ }
185
+ return rehearsed(command, args, pretty, depth, deps, (plain) => {
186
+ const parsed = parseIssue(plain, pretty);
187
+ if ('error' in parsed)
188
+ return parsed;
189
+ const { kind, expiry, consented } = parsed;
190
+ const { name, label, prefix } = KINDS[kind];
191
+ const term = expiry ? { expiresInMinutes: expiry.minutes } : {};
192
+ const consent = expiry ? { consentRequired: true, consented } : {};
193
+ const body = { kind, ...term, ...(expiry && consented ? { consented: true } : {}) };
194
+ const payRows = expiry
195
+ ? [
196
+ ['유효기간', expiry.label],
197
+ ['결제 합산', consented ? '동의함 (--yes)' : '필요합니다. 유료 서비스 이용과 결제 합산에 동의하면 --yes 를 붙이세요.'],
198
+ ['주의', '이 키로 계정에 요금이 청구될 수 있습니다.']
199
+ ]
200
+ : [];
201
+ return {
202
+ steps: expiry ? PAY_STEPS : ISSUE_STEPS,
203
+ result: (siteUrl) => plannedChange(command, pretty, depth, siteUrl, { url: keyUrl(siteUrl), body }, '키 발급 요청을 확인했습니다. 발급하지 않았습니다.', [['키', label], ['접두사', prefix], ...payRows], { kind, name, prefix, ...term, ...consent }),
204
+ send: {
205
+ method: 'POST',
206
+ url: (siteUrl) => keyUrl(siteUrl),
207
+ body,
208
+ spinner: '키를 발급하고 있습니다.',
209
+ failed: '키를 발급하지 못했습니다.',
210
+ notFound: httpFailure(404),
211
+ conflict: KEY_EXISTS,
212
+ done: (result, siteUrl) => issued(command, pretty, depth, `${label}를 발급했습니다.`, result, siteUrl)
213
+ }
214
+ };
215
+ });
216
+ }
217
+ export async function runKeysCreate(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
218
+ const command = 'keys create';
219
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
220
+ const parsed = parseCreate(rest, pretty);
221
+ if ('error' in parsed)
222
+ return parsed;
223
+ const { name, scopes } = parsed;
224
+ const body = { kind: 'custom', name, scopes };
225
+ return {
226
+ steps: CREATE_STEPS,
227
+ result: (siteUrl) => plannedChange(command, pretty, depth, siteUrl, { url: keyUrl(siteUrl), body }, '키 생성 요청을 확인했습니다. 만들지 않았습니다.', [['키 이름', name], ['접두사', CUSTOM_PREFIX], ['권한', scopeNames(scopes)]], { name, prefix: CUSTOM_PREFIX, scopes }),
228
+ send: {
229
+ method: 'POST',
230
+ url: (siteUrl) => keyUrl(siteUrl),
231
+ body,
232
+ spinner: '키를 만들고 있습니다.',
233
+ failed: '키를 만들지 못했습니다.',
234
+ notFound: httpFailure(404),
235
+ conflict: KEY_EXISTS,
236
+ done: (result, siteUrl) => issued(command, pretty, depth, `${name} 키를 만들었습니다.`, result, siteUrl)
237
+ }
238
+ };
239
+ });
240
+ }
241
+ export async function runKeysRevoke(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
242
+ const command = 'keys revoke';
243
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
244
+ const id = parseRevoke(rest, pretty);
245
+ if (typeof id !== 'string')
246
+ return id;
247
+ return {
248
+ steps: REVOKE_STEPS,
249
+ result: (siteUrl) => plannedChange(command, pretty, depth, siteUrl, { url: keyUrl(siteUrl, `/${encodeURIComponent(id)}/revoke`), body: {} }, '키 취소 요청을 확인했습니다. 취소하지 않았습니다.', [['키 ID', id], ['영향', '취소하면 이 키를 쓰는 에이전트와 도구가 바로 막힙니다.']], { keyId: id }),
250
+ send: {
251
+ method: 'POST',
252
+ url: (siteUrl) => keyUrl(siteUrl, `/${encodeURIComponent(id)}/revoke`),
253
+ body: {},
254
+ spinner: '키를 취소하고 있습니다.',
255
+ failed: '키를 취소하지 못했습니다.',
256
+ notFound: KEY_NOT_FOUND,
257
+ done: (result, siteUrl) => {
258
+ const key = keyOf(result);
259
+ return pretty
260
+ ? prettyResult(0, depth, command, `${key.name}를 취소했습니다.`, [['서버', siteUrl], ['키 ID', key.id], ['키', `${KIND_LABELS[key.kind] ?? key.kind} · ${key.name}`], ['영향', '이 키를 쓰던 에이전트와 도구는 바로 막힙니다.']])
261
+ : agentResult(0, { command, siteUrl, applied: true, keyId: key.id, key });
262
+ }
263
+ }
264
+ };
265
+ }, {
266
+ message: 'Revoking blocks every agent and tool that uses the key at once.',
267
+ display: '취소하면 이 키를 쓰는 에이전트와 도구가 바로 막힙니다. 사용자에게 확인한 뒤 --yes 를 붙여 실행하세요.'
268
+ });
269
+ }
@@ -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 { supportDisplay, 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, prettyMessage) => pretty
24
+ ? prettyResult(1, depth, 'login', prettyMessage)
25
+ : agentResult(1, { command: 'login', error: { code, message } });
26
+ const supportResult = (pretty, depth, code) => failure(pretty, depth, code, supportMessage(code), supportDisplay(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', '로그인했습니다.', [
90
+ ['계정', me.user.email ?? me.user.name ?? '이메일 없는 계정'],
91
+ ['인증 정보', 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('잘못된 요청입니다.');
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 = `브라우저에서 DeepDynamic Cloud 로그인을 마무리하세요.\n브라우저가 열리지 않으면 아래 주소를 직접 여세요.\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.', '제한 시간 안에 로그인을 마치지 못했습니다. deepdynamic login 을 다시 실행하세요.');
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, prettyUsage } = spec('login');
8
+ export async function runLogin(args, pretty, depth, loginDeps) {
9
+ const { args: rest, dryRun } = splitDryRun(args);
10
+ const options = parseServerArgs(rest, pretty);
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, [['사용법', prettyUsage]]);
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, prettyUsage } = 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], pretty);
17
+ return pretty
18
+ ? prettyResult(2, depth, 'logout', message, [['사용법', prettyUsage]])
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', '이미 로그아웃 상태입니다.')
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', '요청을 보내지 않고 확인만 했습니다.', [['서버', siteUrl], ['요청', `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 ? '토큰을 폐기하고 있습니다.' : 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', '로그인 정보는 지웠지만 서버에서 토큰을 폐기하지 못했습니다.', [
51
+ ['서버', siteUrl],
52
+ ['원인', failure.display],
53
+ ['직접 폐기', 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', '로그아웃했습니다.', [['계정', email ?? '이메일 없는 계정'], ['삭제한 인증 정보', path]])
70
+ : agentResult(0, { command: 'logout', account: { email }, siteUrl, credentialsPath: path, revoked: true });
71
+ }