@odyssey365/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.
package/dist/index.js ADDED
@@ -0,0 +1,412 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Odyssey CLI — MCP 커넥터의 CLI 판.
4
+ *
5
+ * MCP 커넥터는 연결 하나 = 계정 하나라, 개인 계정과 운영(admin) 계정을 한 세션에서 오갈 수 없었다.
6
+ * CLI 는 같은 서버(`mcp_streamable`)의 같은 도구를 부르되 **호출마다 프로필(계정)을 고른다**:
7
+ *
8
+ * odyssey login # 개인 계정 → 프로필 default
9
+ * odyssey login -p admin # 운영 계정 → 프로필 admin
10
+ * odyssey list_todos --status inProgress
11
+ * odyssey -p admin list_snapshots
12
+ *
13
+ * 도구 정의는 서버가 정본이다(tools/list). CLI 는 이름·스키마를 받아 플래그를 맞출 뿐이라
14
+ * 서버에 도구가 늘면 CLI 배포 없이 바로 쓸 수 있다.
15
+ *
16
+ * 이력: document/90-process/work-log/261010 Odyssey CLI 다계정 프로필 MCP CLI판.md
17
+ */
18
+ import { readFileSync } from 'node:fs';
19
+ import { dirname, join } from 'node:path';
20
+ import { fileURLToPath } from 'node:url';
21
+ import { createInterface } from 'node:readline';
22
+ import { AuthRequiredError, DEFAULT_PROFILE, DEFAULT_SERVER, UsageError, assertProfileName, credentialsPath, loadCredentials, normalizeServer, updateCredentials, } from './config.js';
23
+ import { extractGlobals, parseToolArgs, takeFlag } from './args.js';
24
+ import { discover, fetchUserInfo, interactiveLogin, registerClient, revokeTokenRemote } from './oauth.js';
25
+ import { NetworkError } from './rpc.js';
26
+ import { envServer, OdysseyClient, resolveTarget, selectedProfileName } from './session.js';
27
+ import { findTool, getTools, renderToolDetail, renderToolList, toolListJson } from './tools.js';
28
+ import { printToolResult, writeJson } from './output.js';
29
+ const __dirname = dirname(fileURLToPath(import.meta.url));
30
+ const VERSION = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8')).version;
31
+ const HELP = `Odyssey CLI v${VERSION} — Odyssey 계정의 할일·메모·보드·스냅샷을 터미널과 AI 에이전트에서 다룬다.
32
+
33
+ 사용법
34
+ odyssey <도구> [--파라미터 값 ...] 도구 실행 (예: odyssey list_todos --status inProgress)
35
+ odyssey tools [검색어] 도구 목록
36
+ odyssey describe <도구> 도구 설명·파라미터
37
+
38
+ 계정
39
+ odyssey login [-p 이름] 브라우저로 로그인해 프로필에 저장
40
+ --no-browser(URL만 출력) · --with-key(API 키, 표준입력) · --default
41
+ odyssey logout [-p 이름] [--all] 로그아웃(서버 토큰 회수 + 로컬 삭제)
42
+ odyssey whoami [-p 이름] 프로필의 계정·연결 확인
43
+ odyssey profiles 로그인된 프로필 목록
44
+ odyssey use <이름> 기본 프로필 바꾸기
45
+
46
+ 전역 옵션
47
+ -p, --profile <이름> 이번 실행의 계정. 기본: ODYSSEY_PROFILE → odyssey use 값 → default
48
+ -o, --output <형식> json(기본) · text(요약 텍스트) · raw(MCP 결과 전체)
49
+ --json <JSON> 파라미터를 JSON 객체로 한 번에 (플래그가 그 위에 덮인다)
50
+ --input <파일|-> 파라미터 JSON 을 파일·표준입력에서
51
+ --refresh-tools 도구 목록 캐시를 새로 받기
52
+ --server <URL> 서버 (기본 ${DEFAULT_SERVER})
53
+
54
+ 파라미터 적는 법
55
+ --key 값 · --key=값 · --flag · --no-flag · 반복 --tags a --tags b · 점 경로 --deadline.endTime <ISO>
56
+ JSON 값 --checklist '[{"title":"a"}]' · null --deadline null
57
+ 필수 파라미터가 하나면 위치 인자로: odyssey get_todo <todoId>
58
+ 도구 파라미터가 전역 옵션과 겹치면 -- 뒤에 적는다
59
+
60
+ 환경변수
61
+ ODYSSEY_PROFILE · ODYSSEY_TOKEN(저장 없이 토큰 직접: odk_ API 키 / oat_ 토큰) · ODYSSEY_MCP_URL
62
+ ODYSSEY_CONFIG_DIR(기본 ~/.odyssey/cli) · ODYSSEY_OUTPUT_DIR(이미지 저장) · ODYSSEY_TIMEOUT_MS · ODYSSEY_PRETTY=1
63
+
64
+ 출력: 결과는 stdout(JSON — 파이프면 한 줄), 안내·오류는 stderr.
65
+ 종료 코드: 0 성공 · 1 도구 오류 · 2 사용법 · 3 로그인 필요 · 4 네트워크
66
+ `;
67
+ function err(line) {
68
+ process.stderr.write(line + '\n');
69
+ }
70
+ function profileFlag(name) {
71
+ return name === DEFAULT_PROFILE ? '' : ` -p ${name}`;
72
+ }
73
+ async function readStdin() {
74
+ const chunks = [];
75
+ for await (const c of process.stdin)
76
+ chunks.push(c);
77
+ return Buffer.concat(chunks).toString('utf-8');
78
+ }
79
+ /** 화면에 찍지 않고 한 줄 입력받는다(API 키). */
80
+ async function promptHidden(question) {
81
+ const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
82
+ const anyRl = rl;
83
+ let muted = false;
84
+ const orig = anyRl._writeToOutput.bind(rl);
85
+ anyRl._writeToOutput = (s) => {
86
+ if (!muted)
87
+ orig(s);
88
+ };
89
+ return new Promise((resolve) => {
90
+ rl.question(question, (answer) => {
91
+ rl.close();
92
+ process.stderr.write('\n');
93
+ resolve(answer.trim());
94
+ });
95
+ muted = true;
96
+ });
97
+ }
98
+ async function readInputObject(g) {
99
+ let raw;
100
+ let label = '';
101
+ if (g.inputFile !== undefined) {
102
+ raw = g.inputFile === '-' ? await readStdin() : readFileSync(g.inputFile, 'utf-8');
103
+ label = `--input ${g.inputFile}`;
104
+ }
105
+ let base = {};
106
+ const parse = (text, from) => {
107
+ let v;
108
+ try {
109
+ v = JSON.parse(text);
110
+ }
111
+ catch (e) {
112
+ throw new UsageError(`${from} 의 JSON 을 읽지 못했습니다: ${e.message}`);
113
+ }
114
+ if (!v || typeof v !== 'object' || Array.isArray(v)) {
115
+ throw new UsageError(`${from} 는 JSON 객체여야 합니다.`);
116
+ }
117
+ return v;
118
+ };
119
+ if (raw !== undefined)
120
+ base = parse(raw, label);
121
+ if (g.inputJson !== undefined)
122
+ base = { ...base, ...parse(g.inputJson, '--json') };
123
+ return base;
124
+ }
125
+ // ── 계정 명령 ────────────────────────────────────────────────────────────────
126
+ async function cmdLogin(g, args) {
127
+ const withKey = takeFlag(args, '--with-key');
128
+ const noBrowser = takeFlag(args, '--no-browser');
129
+ const makeDefault = takeFlag(args, '--default');
130
+ if (args.length)
131
+ throw new UsageError(`login 이 모르는 인자: ${args.join(' ')}`);
132
+ const name = g.profile ?? process.env.ODYSSEY_PROFILE?.trim() ?? DEFAULT_PROFILE;
133
+ assertProfileName(name);
134
+ const before = loadCredentials();
135
+ const previous = before.profiles[name];
136
+ const server = normalizeServer(g.server ?? envServer() ?? previous?.server ?? DEFAULT_SERVER);
137
+ let credential;
138
+ let account;
139
+ if (withKey) {
140
+ const key = process.stdin.isTTY ? await promptHidden('API 키(odk_…): ') : (await readStdin()).trim();
141
+ if (!key)
142
+ throw new UsageError('API 키가 비어 있습니다. Odyssey 앱 › 설정 › MCP 연동에서 발급하세요.');
143
+ credential = { type: 'apiKey', apiKey: key };
144
+ const probe = new OdysseyClient({ profileName: name, server, profile: { server, credential, savedAt: '' } }, VERSION);
145
+ await probe.ping();
146
+ }
147
+ else {
148
+ err(`프로필 "${name}" 로그인 — ${server}`);
149
+ const meta = await discover(server);
150
+ const clientId = await registerClient(server, meta, VERSION);
151
+ const tokens = await interactiveLogin({
152
+ server,
153
+ meta,
154
+ clientId,
155
+ launchBrowser: !noBrowser,
156
+ onAuthorizeUrl: (url) => {
157
+ err(noBrowser ? '아래 주소를 이 컴퓨터의 브라우저에서 여세요:' : '브라우저에서 로그인하세요. 열리지 않으면 아래 주소를 여세요:');
158
+ err(url);
159
+ err('로그인을 기다리는 중… (10분)');
160
+ },
161
+ });
162
+ credential = {
163
+ type: 'oauth',
164
+ clientId,
165
+ accessToken: tokens.access_token,
166
+ ...(tokens.refresh_token ? { refreshToken: tokens.refresh_token } : {}),
167
+ ...(tokens.expires_in ? { expiresAt: new Date(Date.now() + tokens.expires_in * 1000).toISOString() } : {}),
168
+ ...(tokens.scope ? { scope: tokens.scope } : {}),
169
+ };
170
+ account = (await fetchUserInfo(server, meta, tokens.access_token)) ?? undefined;
171
+ }
172
+ const isDefault = updateCredentials((file) => {
173
+ file.profiles[name] = { server, credential, ...(account ? { account } : {}), savedAt: new Date().toISOString() };
174
+ if (makeDefault || !file.defaultProfile || !file.profiles[file.defaultProfile])
175
+ file.defaultProfile = name;
176
+ return file.defaultProfile === name;
177
+ });
178
+ // 같은 프로필 이름에 다른 계정이 들어왔으면 알린다(운영 계정 자리에 개인 계정을 넣는 실수).
179
+ if (previous?.account && account && previous.account.uid !== account.uid) {
180
+ err(`주의: 프로필 "${name}" 은 원래 ${previous.account.email ?? previous.account.uid} 였습니다 — 이제 ${account.email ?? account.uid} 입니다.`);
181
+ }
182
+ const who = account ? `${account.email ?? '(이메일 없음)'} · uid ${account.uid}` : 'API 키';
183
+ process.stdout.write(`✓ 프로필 "${name}" 로그인: ${who}${isDefault ? ' (기본 프로필)' : ''}\n`);
184
+ if (!isDefault)
185
+ process.stdout.write(` 사용: odyssey -p ${name} <도구> · 기본으로: odyssey use ${name}\n`);
186
+ return 0;
187
+ }
188
+ async function cmdLogout(g, args) {
189
+ const all = takeFlag(args, '--all');
190
+ if (args.length)
191
+ throw new UsageError(`logout 이 모르는 인자: ${args.join(' ')}`);
192
+ const file = loadCredentials();
193
+ const names = all ? Object.keys(file.profiles) : [selectedProfileName(g)];
194
+ if (names.length === 0) {
195
+ err('로그인된 프로필이 없습니다.');
196
+ return 0;
197
+ }
198
+ for (const name of names) {
199
+ const p = file.profiles[name];
200
+ if (!p) {
201
+ err(`프로필 "${name}" 은 로그인되어 있지 않습니다.`);
202
+ continue;
203
+ }
204
+ let remote = '';
205
+ if (p.credential.type === 'oauth') {
206
+ try {
207
+ const meta = await discover(p.server);
208
+ // 리프레시를 회수하면 서버가 짝 액세스 토큰도 함께 회수한다.
209
+ const token = p.credential.refreshToken ?? p.credential.accessToken;
210
+ const revoked = await revokeTokenRemote(p.server, meta, p.credential.clientId, token);
211
+ remote = revoked ? ' · 서버 토큰 회수됨' : ' · 서버가 회수를 지원하지 않아 로컬에서만 지웠습니다';
212
+ }
213
+ catch (e) {
214
+ remote = ` · 서버 토큰 회수 실패(${e.message}) — 로컬에서만 지웠습니다`;
215
+ }
216
+ }
217
+ else {
218
+ remote = ' · API 키는 앱 › 설정 › MCP 연동에서 폐기하세요';
219
+ }
220
+ updateCredentials((f) => {
221
+ delete f.profiles[name];
222
+ if (f.defaultProfile === name)
223
+ delete f.defaultProfile;
224
+ });
225
+ process.stdout.write(`✓ 프로필 "${name}" 로그아웃${remote}\n`);
226
+ }
227
+ return 0;
228
+ }
229
+ async function cmdWhoami(g, args) {
230
+ if (args.length)
231
+ throw new UsageError(`whoami 가 모르는 인자: ${args.join(' ')}`);
232
+ const target = resolveTarget(g);
233
+ const client = new OdysseyClient(target, VERSION);
234
+ const cred = target.profile?.credential;
235
+ let account = target.profile?.account;
236
+ if (cred?.type === 'oauth') {
237
+ const info = await client.userInfo();
238
+ if (!info)
239
+ throw new AuthRequiredError(`프로필 "${target.profileName}" 의 로그인이 풀렸습니다. 다시 로그인: odyssey login${profileFlag(target.profileName)}`);
240
+ account = info;
241
+ }
242
+ else {
243
+ await client.ping();
244
+ }
245
+ const after = target.profile?.credential;
246
+ writeJson({
247
+ profile: target.profileName,
248
+ server: target.server,
249
+ auth: target.envToken ? 'env' : cred?.type,
250
+ uid: account?.uid ?? null,
251
+ email: account?.email ?? null,
252
+ ...(after?.type === 'oauth' && after.expiresAt ? { accessTokenExpiresAt: after.expiresAt } : {}),
253
+ ok: true,
254
+ });
255
+ return 0;
256
+ }
257
+ function cmdProfiles(g, args) {
258
+ if (args.length)
259
+ throw new UsageError(`profiles 가 모르는 인자: ${args.join(' ')}`);
260
+ const file = loadCredentials();
261
+ const entries = Object.entries(file.profiles);
262
+ if (g.output === 'json') {
263
+ writeJson(entries.map(([name, p]) => ({
264
+ name,
265
+ default: file.defaultProfile === name,
266
+ server: p.server,
267
+ auth: p.credential.type,
268
+ uid: p.account?.uid ?? null,
269
+ email: p.account?.email ?? null,
270
+ })));
271
+ return 0;
272
+ }
273
+ if (entries.length === 0) {
274
+ process.stdout.write('로그인된 프로필이 없습니다. 먼저: odyssey login\n');
275
+ return 0;
276
+ }
277
+ const width = Math.max(...entries.map(([n]) => n.length));
278
+ for (const [name, p] of entries) {
279
+ const mark = file.defaultProfile === name ? '*' : ' ';
280
+ const who = p.account ? `${p.account.email ?? '(이메일 없음)'} ${p.account.uid}` : '(API 키)';
281
+ const server = normalizeServer(p.server) === DEFAULT_SERVER ? '' : ` ${p.server}`;
282
+ process.stdout.write(`${mark} ${name.padEnd(width)} ${who}${server}\n`);
283
+ }
284
+ process.stdout.write(`\n* = 기본 프로필 · 자격증명: ${credentialsPath()}\n`);
285
+ return 0;
286
+ }
287
+ function cmdUse(_g, args) {
288
+ const name = args[0];
289
+ if (!name || args.length > 1)
290
+ throw new UsageError('사용법: odyssey use <프로필>');
291
+ assertProfileName(name);
292
+ updateCredentials((file) => {
293
+ if (!file.profiles[name]) {
294
+ throw new AuthRequiredError(`프로필 "${name}" 에 로그인되어 있지 않습니다. 먼저: odyssey login${profileFlag(name)}`);
295
+ }
296
+ file.defaultProfile = name;
297
+ });
298
+ process.stdout.write(`✓ 기본 프로필: ${name}\n`);
299
+ return 0;
300
+ }
301
+ // ── 도구 명령 ────────────────────────────────────────────────────────────────
302
+ async function cmdTools(g, args) {
303
+ if (args.length > 1)
304
+ throw new UsageError('사용법: odyssey tools [검색어]');
305
+ const client = new OdysseyClient(resolveTarget(g), VERSION);
306
+ const tools = await getTools(client, { refresh: g.refreshTools });
307
+ if (g.output === 'json' || g.output === 'raw') {
308
+ writeJson(g.output === 'raw' ? tools : toolListJson(tools));
309
+ }
310
+ else {
311
+ process.stdout.write(renderToolList(tools, args[0]) + '\n');
312
+ }
313
+ return 0;
314
+ }
315
+ async function cmdDescribe(g, args) {
316
+ if (args.length !== 1)
317
+ throw new UsageError('사용법: odyssey describe <도구>');
318
+ const client = new OdysseyClient(resolveTarget(g), VERSION);
319
+ const tool = await findTool(client, args[0], { refresh: g.refreshTools });
320
+ if (g.output === 'json' || g.output === 'raw')
321
+ writeJson(tool);
322
+ else
323
+ process.stdout.write(renderToolDetail(tool) + '\n');
324
+ return 0;
325
+ }
326
+ async function cmdCall(g, toolName, tokens) {
327
+ const client = new OdysseyClient(resolveTarget(g), VERSION);
328
+ const tool = await findTool(client, toolName, { refresh: g.refreshTools });
329
+ const base = await readInputObject(g);
330
+ const { args, positionals } = parseToolArgs(tokens, tool.inputSchema, base);
331
+ if (positionals.length) {
332
+ const req = tool.inputSchema?.required ?? [];
333
+ throw new UsageError(`${tool.name} 에 위치 인자 ${positionals.map((p) => JSON.stringify(p)).join(' ')} 를 둘 자리가 없습니다.` +
334
+ (req.length ? ` 필수 파라미터: ${req.map((k) => `--${k}`).join(' ')}` : '') +
335
+ `\n자세히: odyssey describe ${tool.name}`);
336
+ }
337
+ // 필수 누락은 서버의 zod 오류 덤프 대신 여기서 바로 알린다(최상위만 — 안쪽은 서버가 본다).
338
+ const missing = (tool.inputSchema?.required ?? []).filter((k) => args[k] === undefined);
339
+ if (missing.length) {
340
+ throw new UsageError(`${tool.name} 에 필수 파라미터가 빠졌습니다: ${missing.map((k) => `--${k}`).join(' ')}` +
341
+ (missing.length === 1 && (tool.inputSchema?.required ?? []).length === 1 ? ' (위치 인자로도 됩니다)' : '') +
342
+ `\n자세히: odyssey describe ${tool.name}`);
343
+ }
344
+ const result = await client.callTool(tool.name, args);
345
+ return printToolResult(result, g.output ?? 'json', tool.name);
346
+ }
347
+ // ── 진입 ─────────────────────────────────────────────────────────────────────
348
+ const ACCOUNT_COMMANDS = new Set(['login', 'logout', 'whoami', 'profiles', 'use']);
349
+ async function main(argv) {
350
+ const { globals: g, rest } = extractGlobals(argv);
351
+ if (g.profile !== undefined)
352
+ assertProfileName(g.profile);
353
+ const [command, ...args] = rest;
354
+ if (g.version && !command) {
355
+ process.stdout.write(`${VERSION}\n`);
356
+ return 0;
357
+ }
358
+ if (!command || command === 'help') {
359
+ if (command === 'help' && args[0])
360
+ return cmdDescribe(g, [args[0]]);
361
+ process.stdout.write(HELP);
362
+ return command || g.help ? 0 : 2;
363
+ }
364
+ if (g.help) {
365
+ // odyssey <도구> --help → 그 도구 설명
366
+ if (!ACCOUNT_COMMANDS.has(command) && command !== 'tools' && command !== 'describe' && command !== 'call') {
367
+ return cmdDescribe(g, [command]);
368
+ }
369
+ process.stdout.write(HELP);
370
+ return 0;
371
+ }
372
+ switch (command) {
373
+ case 'login':
374
+ return cmdLogin(g, args);
375
+ case 'logout':
376
+ return cmdLogout(g, args);
377
+ case 'whoami':
378
+ return cmdWhoami(g, args);
379
+ case 'profiles':
380
+ return cmdProfiles(g, args);
381
+ case 'use':
382
+ return cmdUse(g, args);
383
+ case 'tools':
384
+ return cmdTools(g, args);
385
+ case 'describe':
386
+ return cmdDescribe(g, args);
387
+ case 'call': {
388
+ const [toolName, ...tokens] = args;
389
+ if (!toolName)
390
+ throw new UsageError('사용법: odyssey call <도구> [--파라미터 값 ...]');
391
+ return cmdCall(g, toolName, tokens);
392
+ }
393
+ default:
394
+ return cmdCall(g, command, args);
395
+ }
396
+ }
397
+ main(process.argv.slice(2))
398
+ .then((code) => {
399
+ process.exitCode = code;
400
+ })
401
+ .catch((e) => {
402
+ const message = e instanceof Error ? e.message : String(e);
403
+ err(`odyssey: ${message}`);
404
+ if (e instanceof UsageError)
405
+ process.exitCode = 2;
406
+ else if (e instanceof AuthRequiredError)
407
+ process.exitCode = 3;
408
+ else if (e instanceof NetworkError)
409
+ process.exitCode = 4;
410
+ else
411
+ process.exitCode = 1;
412
+ });
package/dist/oauth.js ADDED
@@ -0,0 +1,265 @@
1
+ /**
2
+ * 브라우저 로그인(OAuth 2.1 인가 코드 + PKCE, 루프백 리다이렉트 RFC 8252).
3
+ *
4
+ * 서버(`mcp_streamable`)가 claude.ai 커넥터에 쓰는 그 인증서버를 그대로 쓴다 — 서버 변경 없이 된다:
5
+ * - DCR(/register): 로그인마다 공개 클라이언트(none)로 새로 등록한다. 리프레시 토큰이 clientId 에
6
+ * 묶이므로 clientId 는 프로필 자격증명에 함께 둔다(로그인은 드물어 등록 문서가 쌓일 일이 적다).
7
+ * - redirect_uri: `http://127.0.0.1/callback` 으로 등록하고 실제로는 임의 포트를 쓴다
8
+ * (서버 redirectUriMatches 가 루프백끼리는 포트를 완화한다).
9
+ * - 로그인 페이지(auth.odyssey365.app)는 매번 새로 로그인시키고(세션 영속 없음) 루프백 앱에는
10
+ * "확인되지 않은 앱" 경고를 띄우지 않는다 — 운영 계정으로 바꿔 로그인하기 쉽다.
11
+ * - 스코프 `mcp openid email`: openid·email 은 /userinfo 로 "누구로 로그인했나"를 받기 위해서다.
12
+ *
13
+ * 토큰: 액세스 60일 · 리프레시 무기한(회수 시까지). 리프레시는 회전하지 않는다(같은 값 재사용).
14
+ */
15
+ import { createHash, randomBytes } from 'node:crypto';
16
+ import { createServer } from 'node:http';
17
+ import { spawn } from 'node:child_process';
18
+ import { errorMessageFromBody, describeFetchError, NetworkError, timeoutMs } from './rpc.js';
19
+ export const CLIENT_NAME = 'Odyssey CLI';
20
+ export const LOGIN_SCOPE = 'mcp openid email';
21
+ const REGISTERED_REDIRECT = 'http://127.0.0.1/callback';
22
+ const CALLBACK_PATH = '/callback';
23
+ /** 서버의 로그인 세션 수명(10분)과 같다 — 그 뒤엔 어차피 code 를 못 받는다. */
24
+ const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
25
+ export class OAuthFlowError extends Error {
26
+ oauthError;
27
+ constructor(message, oauthError) {
28
+ super(message);
29
+ this.oauthError = oauthError;
30
+ this.name = 'OAuthFlowError';
31
+ }
32
+ }
33
+ function base64url(buf) {
34
+ return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
35
+ }
36
+ export function createPkce() {
37
+ const verifier = base64url(randomBytes(32));
38
+ const challenge = base64url(createHash('sha256').update(verifier).digest());
39
+ return { verifier, challenge };
40
+ }
41
+ async function fetchJson(url, init, server) {
42
+ let res;
43
+ try {
44
+ res = await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs()) });
45
+ }
46
+ catch (e) {
47
+ throw new NetworkError(describeFetchError(e, server));
48
+ }
49
+ const body = await res.text();
50
+ let json = null;
51
+ try {
52
+ json = JSON.parse(body);
53
+ }
54
+ catch {
55
+ // 비 JSON
56
+ }
57
+ return { status: res.status, body, json };
58
+ }
59
+ /** RFC 8414 메타데이터. 없으면 관례 경로로 폴백한다. */
60
+ export async function discover(server) {
61
+ const base = server.replace(/\/+$/, '');
62
+ const fallback = {
63
+ authorization_endpoint: `${base}/authorize`,
64
+ token_endpoint: `${base}/token`,
65
+ registration_endpoint: `${base}/register`,
66
+ userinfo_endpoint: `${base}/userinfo`,
67
+ };
68
+ const r = await fetchJson(`${base}/.well-known/oauth-authorization-server`, { method: 'GET' }, server);
69
+ if (r.status !== 200 || !r.json?.authorization_endpoint || !r.json?.token_endpoint)
70
+ return fallback;
71
+ return {
72
+ authorization_endpoint: r.json.authorization_endpoint,
73
+ token_endpoint: r.json.token_endpoint,
74
+ registration_endpoint: r.json.registration_endpoint ?? fallback.registration_endpoint,
75
+ userinfo_endpoint: r.json.userinfo_endpoint ?? fallback.userinfo_endpoint,
76
+ revocation_endpoint: r.json.revocation_endpoint,
77
+ };
78
+ }
79
+ /** RFC 7591 동적 등록 — 공개 클라이언트(PKCE). */
80
+ export async function registerClient(server, meta, version) {
81
+ if (!meta.registration_endpoint) {
82
+ throw new OAuthFlowError('서버가 클라이언트 등록(DCR)을 지원하지 않습니다.');
83
+ }
84
+ const r = await fetchJson(meta.registration_endpoint, {
85
+ method: 'POST',
86
+ headers: { 'Content-Type': 'application/json' },
87
+ body: JSON.stringify({
88
+ client_name: CLIENT_NAME,
89
+ redirect_uris: [REGISTERED_REDIRECT],
90
+ grant_types: ['authorization_code', 'refresh_token'],
91
+ response_types: ['code'],
92
+ token_endpoint_auth_method: 'none',
93
+ scope: LOGIN_SCOPE,
94
+ software_id: 'app.odyssey365.cli',
95
+ software_version: version,
96
+ }),
97
+ }, server);
98
+ if (r.status !== 201 && r.status !== 200) {
99
+ throw new OAuthFlowError(`클라이언트 등록 실패 (${r.status}): ${errorMessageFromBody(r.body)}`);
100
+ }
101
+ if (typeof r.json?.client_id !== 'string') {
102
+ throw new OAuthFlowError('클라이언트 등록 응답에 client_id 가 없습니다.');
103
+ }
104
+ return r.json.client_id;
105
+ }
106
+ async function postToken(server, meta, form) {
107
+ const r = await fetchJson(meta.token_endpoint, {
108
+ method: 'POST',
109
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
110
+ body: new URLSearchParams(form).toString(),
111
+ }, server);
112
+ if (r.status !== 200 || typeof r.json?.access_token !== 'string') {
113
+ throw new OAuthFlowError(`토큰 발급 실패 (${r.status}): ${errorMessageFromBody(r.body)}`, typeof r.json?.error === 'string' ? r.json.error : undefined);
114
+ }
115
+ return r.json;
116
+ }
117
+ export function refreshAccessToken(server, meta, clientId, refreshToken) {
118
+ return postToken(server, meta, {
119
+ grant_type: 'refresh_token',
120
+ client_id: clientId,
121
+ refresh_token: refreshToken,
122
+ resource: server.replace(/\/+$/, ''),
123
+ });
124
+ }
125
+ export async function fetchUserInfo(server, meta, accessToken) {
126
+ if (!meta.userinfo_endpoint)
127
+ return null;
128
+ const r = await fetchJson(meta.userinfo_endpoint, { method: 'GET', headers: { Authorization: `Bearer ${accessToken}` } }, server);
129
+ if (r.status !== 200 || typeof r.json?.sub !== 'string')
130
+ return null;
131
+ return { uid: r.json.sub, ...(typeof r.json.email === 'string' ? { email: r.json.email } : {}) };
132
+ }
133
+ /**
134
+ * RFC 7009 토큰 회수. 서버가 엔드포인트를 광고하지 않으면 false(로컬 삭제만 하게 된다).
135
+ * 리프레시 토큰을 보내면 서버가 짝 액세스 토큰까지 함께 회수한다.
136
+ */
137
+ export async function revokeTokenRemote(server, meta, clientId, token) {
138
+ if (!meta.revocation_endpoint)
139
+ return false;
140
+ const r = await fetchJson(meta.revocation_endpoint, {
141
+ method: 'POST',
142
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
143
+ body: new URLSearchParams({ token, client_id: clientId }).toString(),
144
+ }, server);
145
+ if (r.status !== 200) {
146
+ throw new OAuthFlowError(`토큰 회수 실패 (${r.status}): ${errorMessageFromBody(r.body)}`);
147
+ }
148
+ return true;
149
+ }
150
+ /** 기본 브라우저로 URL 을 연다. 실패해도 조용히 넘어간다(URL 은 이미 화면에 찍혀 있다). */
151
+ export function openBrowser(url) {
152
+ let cmd;
153
+ let args;
154
+ if (process.platform === 'darwin') {
155
+ cmd = 'open';
156
+ args = [url];
157
+ }
158
+ else if (process.platform === 'win32') {
159
+ // cmd /c start 는 URL 의 & 를 명령 구분자로 읽는다 — rundll32 는 셸을 거치지 않는다.
160
+ cmd = 'rundll32';
161
+ args = ['url.dll,FileProtocolHandler', url];
162
+ }
163
+ else {
164
+ cmd = 'xdg-open';
165
+ args = [url];
166
+ }
167
+ try {
168
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
169
+ child.on('error', () => { });
170
+ child.unref();
171
+ }
172
+ catch {
173
+ // 무시
174
+ }
175
+ }
176
+ const RESULT_PAGE = (ok, message) => `<!doctype html>
177
+ <html lang="ko"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
178
+ <title>Odyssey CLI</title>
179
+ <style>
180
+ :root{color-scheme:light dark;--bg:#f6f6f4;--fg:#1d1d1f;--sub:#6e6e73;--accent:${ok ? '#2e7d4f' : '#b3261e'}}
181
+ @media (prefers-color-scheme:dark){:root{--bg:#161618;--fg:#f2f2f2;--sub:#a1a1a6;--accent:${ok ? '#6fcf97' : '#f2b8b5'}}}
182
+ body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--fg);font:16px/1.5 -apple-system,BlinkMacSystemFont,"Apple SD Gothic Neo","Segoe UI",sans-serif}
183
+ main{max-width:420px;padding:32px 16px;text-align:center}
184
+ h1{font-size:20px;margin:0 0 8px;color:var(--accent)}p{margin:0;color:var(--sub)}
185
+ </style></head><body><main><h1>${ok ? '로그인되었습니다' : '로그인하지 못했습니다'}</h1><p>${message}</p></main></body></html>`;
186
+ function escapeHtml(s) {
187
+ return s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
188
+ }
189
+ /**
190
+ * 루프백 서버를 띄우고 → 브라우저로 인가 페이지를 연 뒤 → code 를 받아 토큰으로 바꾼다.
191
+ */
192
+ export async function interactiveLogin(opts) {
193
+ const { verifier, challenge } = createPkce();
194
+ const state = base64url(randomBytes(16));
195
+ let settle;
196
+ const codePromise = new Promise((resolve, reject) => {
197
+ settle = { resolve, reject };
198
+ });
199
+ const http = createServer((req, res) => {
200
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
201
+ if (url.pathname !== CALLBACK_PATH) {
202
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }).end('not found');
203
+ return;
204
+ }
205
+ const send = (ok, message) => {
206
+ res.writeHead(ok ? 200 : 400, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
207
+ res.end(RESULT_PAGE(ok, escapeHtml(message)));
208
+ };
209
+ // state 가 다르면 이 로그인의 응답이 아니다 — 무시하고 계속 기다린다(다른 탭의 잔여 리다이렉트 등).
210
+ if (url.searchParams.get('state') !== state) {
211
+ send(false, '이 로그인 요청의 응답이 아닙니다. 터미널에서 다시 시도하세요.');
212
+ return;
213
+ }
214
+ const error = url.searchParams.get('error');
215
+ if (error) {
216
+ const desc = url.searchParams.get('error_description') ?? error;
217
+ send(false, desc);
218
+ settle.reject(new OAuthFlowError(`로그인이 거절되었습니다: ${desc}`, error));
219
+ return;
220
+ }
221
+ const code = url.searchParams.get('code');
222
+ if (!code) {
223
+ send(false, '인가 코드가 없습니다.');
224
+ settle.reject(new OAuthFlowError('콜백에 인가 코드가 없습니다.'));
225
+ return;
226
+ }
227
+ send(true, '이 창을 닫고 터미널로 돌아가세요.');
228
+ settle.resolve(code);
229
+ });
230
+ await new Promise((resolve, reject) => {
231
+ http.once('error', reject);
232
+ http.listen(0, '127.0.0.1', () => resolve());
233
+ });
234
+ const port = http.address().port;
235
+ const redirectUri = `http://127.0.0.1:${port}${CALLBACK_PATH}`;
236
+ const authUrl = new URL(opts.meta.authorization_endpoint);
237
+ authUrl.searchParams.set('response_type', 'code');
238
+ authUrl.searchParams.set('client_id', opts.clientId);
239
+ authUrl.searchParams.set('redirect_uri', redirectUri);
240
+ authUrl.searchParams.set('code_challenge', challenge);
241
+ authUrl.searchParams.set('code_challenge_method', 'S256');
242
+ authUrl.searchParams.set('state', state);
243
+ authUrl.searchParams.set('scope', LOGIN_SCOPE);
244
+ authUrl.searchParams.set('resource', opts.server.replace(/\/+$/, ''));
245
+ opts.onAuthorizeUrl(authUrl.toString());
246
+ if (opts.launchBrowser)
247
+ openBrowser(authUrl.toString());
248
+ const timer = setTimeout(() => settle.reject(new OAuthFlowError('10분 안에 로그인이 끝나지 않았습니다. 다시 시도하세요.')), LOGIN_TIMEOUT_MS);
249
+ try {
250
+ const code = await codePromise;
251
+ return await postToken(opts.server, opts.meta, {
252
+ grant_type: 'authorization_code',
253
+ client_id: opts.clientId,
254
+ code,
255
+ redirect_uri: redirectUri,
256
+ code_verifier: verifier,
257
+ resource: opts.server.replace(/\/+$/, ''),
258
+ });
259
+ }
260
+ finally {
261
+ clearTimeout(timer);
262
+ http.closeAllConnections?.();
263
+ http.close();
264
+ }
265
+ }