@joripspace/cli 0.5.6 → 0.5.8

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/bin/joripspace.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ const { message } = require('../lib/locale');
2
3
 
3
4
  const fs = require('node:fs');
4
5
  const os = require('node:os');
@@ -16,6 +17,7 @@ const { createTemplateCommands } = require('../lib/template-commands');
16
17
  const { createCheckpointCommands } = require('../lib/checkpoint-commands');
17
18
  const { createRealtimeV2Commands } = require('../lib/realtime-v2-commands');
18
19
  const { createGithubCommands } = require('../lib/github-commands');
20
+ const { createProjectCommand } = require('../lib/project-create');
19
21
  const {
20
22
  assertDeployableProjectPath,
21
23
  assertDeployableSourceFilePath,
@@ -32,6 +34,8 @@ const {
32
34
  safeProjectRelativePath,
33
35
  } = require('../lib/project-paths');
34
36
  const { ensureProjectEnvIgnored, readProjectEnv, updateDotEnvFile } = require('../lib/project-env');
37
+ const { createCredentialStore, normalizeCredentialApiUrl } = require('../lib/credential-store');
38
+ const credentialStore = createCredentialStore();
35
39
  const { createStartProjectCommand } = require('../lib/start-command');
36
40
  const { legacyCredentialSessionConnection, readProjectMarker } = require('../lib/start');
37
41
  const { buildTemplateDeployRequest, listTemplates } = loadTemplatesPackage();
@@ -103,6 +107,13 @@ const githubCommand = createGithubCommands({
103
107
  });
104
108
 
105
109
  const DEFAULT_API_URL = 'https://api.joripspace.com';
110
+ const createProject = createProjectCommand({
111
+ apiRequest,
112
+ output,
113
+ requireApiToken,
114
+ resolveConnection,
115
+ stringFlag,
116
+ });
106
117
  const GENERAL_REQUEST_TIMEOUT_MS = 25_000;
107
118
  const SESSION_COOKIE_PREFIX = 'joripspace_session=';
108
119
  function loadTemplatesPackage() {
@@ -155,6 +166,9 @@ async function main() {
155
166
  case 'login':
156
167
  await login(flags);
157
168
  return;
169
+ case 'logout':
170
+ logout(flags);
171
+ return;
158
172
  case 'me':
159
173
  await getMe(flags);
160
174
  return;
@@ -162,13 +176,13 @@ async function main() {
162
176
  await listMyProjects(flags);
163
177
  return;
164
178
  case 'billing-projects':
165
- webOnlyCommand('결제 프로젝트');
179
+ webOnlyCommand(message('Billing projects', '결제 프로젝트'));
166
180
  return;
167
181
  case 'billing-usage':
168
- webOnlyCommand('결제 사용량');
182
+ webOnlyCommand(message('Billing usage', '결제 사용량'));
169
183
  return;
170
184
  case 'invoices':
171
- webOnlyCommand('청구서');
185
+ webOnlyCommand(message('Invoices', '청구서'));
172
186
  return;
173
187
  case 'link':
174
188
  await linkProject(flags);
@@ -177,7 +191,7 @@ async function main() {
177
191
  await startProjectCommand(rest, flags);
178
192
  return;
179
193
  case 'create':
180
- webOnlyCommand('프로젝트 생성');
194
+ await createProject(flags);
181
195
  return;
182
196
  case 'get':
183
197
  await getProject(flags);
@@ -242,7 +256,10 @@ async function main() {
242
256
  await checkpointCommands.command(rest, flags);
243
257
  return;
244
258
  case 'realtime-v2':
245
- await createRealtimeV2Commands({apiRequest,output,projectAuth,requireProjectId,stringFlag})(rest,flags);
259
+ await createRealtimeV2Commands({ apiRequest, output, projectAuth, requireProjectId, stringFlag })(
260
+ rest,
261
+ flags
262
+ );
246
263
  return;
247
264
  case 'github':
248
265
  await githubCommand(rest, flags);
@@ -255,7 +272,7 @@ async function main() {
255
272
  await listRuntimeEvents(flags);
256
273
  return;
257
274
  case 'usage':
258
- webOnlyCommand('일일 사용량 상세');
275
+ webOnlyCommand(message('Daily usage details', '일일 사용량 상세'));
259
276
  return;
260
277
  case 'usage-summary':
261
278
  await getUsageSummary(flags);
@@ -264,7 +281,7 @@ async function main() {
264
281
  await getUsageBreakdown(flags);
265
282
  return;
266
283
  case 'tokens':
267
- webOnlyCommand('API 토큰 관리');
284
+ webOnlyCommand(message('API token administration', 'API 토큰 관리'));
268
285
  return;
269
286
  case 'crons':
270
287
  await remoteCommands.listCrons(flags);
@@ -279,10 +296,10 @@ async function main() {
279
296
  await remoteCommands.mail(rest, flags);
280
297
  return;
281
298
  case 'webhooks':
282
- webOnlyCommand('웹훅 관리');
299
+ webOnlyCommand(message('Webhook administration', '웹훅 관리'));
283
300
  return;
284
301
  case 'token':
285
- webOnlyCommand('API 토큰 관리');
302
+ webOnlyCommand(message('API token administration', 'API 토큰 관리'));
286
303
  return;
287
304
  case 'secret':
288
305
  await remoteCommands.secrets(rest, flags);
@@ -294,10 +311,10 @@ async function main() {
294
311
  await remoteCommands.domains(rest, flags);
295
312
  return;
296
313
  case 'webhook':
297
- webOnlyCommand('웹훅 관리');
314
+ webOnlyCommand(message('Webhook administration', '웹훅 관리'));
298
315
  return;
299
316
  case 'delete':
300
- webOnlyCommand('프로젝트 삭제');
317
+ webOnlyCommand(message('Project deletion', '프로젝트 삭제'));
301
318
  return;
302
319
  default:
303
320
  throw new Error(`Unknown command: ${command}`);
@@ -308,7 +325,7 @@ async function login(flags) {
308
325
  const connectionCode = stringFlag(flags, 'code');
309
326
  if (connectionCode) {
310
327
  ensureProjectEnvIgnored(projectWorkspaceDir(flags, { discover: false }));
311
- const exchangeApiBaseUrl = unauthenticatedApiBaseUrl(flags);
328
+ const exchangeApiBaseUrl = normalizeCredentialApiUrl(unauthenticatedApiBaseUrl(flags));
312
329
  const exchange = await apiRequest(flags, '/v1/auth/connection-code/exchange', {
313
330
  method: 'POST',
314
331
  body: { code: normalizeConnectionCode(connectionCode) },
@@ -325,6 +342,21 @@ async function login(flags) {
325
342
  await saveBrowserConnectToken(flags, normalizeConnectToken(connectToken));
326
343
  return;
327
344
  }
345
+ const existing = resolveConnection(flags);
346
+ if (existing.apiToken) {
347
+ await saveBrowserConnectToken(
348
+ flags,
349
+ normalizeConnectToken(existing.apiToken),
350
+ existing.source,
351
+ existing.apiBaseUrl
352
+ );
353
+ return;
354
+ }
355
+ const enteredCode = await promptConnectionCode(flags);
356
+ if (enteredCode !== null) {
357
+ await login({ ...flags, code: normalizeConnectionCode(enteredCode) });
358
+ return;
359
+ }
328
360
  output(flags, browserConnectInstructions(), printBrowserConnectInstructions);
329
361
  }
330
362
 
@@ -332,6 +364,67 @@ async function saveBrowserConnectToken(flags, apiToken, source = 'browser-connec
332
364
  return saveBrowserConnectTokenWithOptions(flags, apiToken, source, selectedApiBaseUrl);
333
365
  }
334
366
 
367
+ function logout(flags) {
368
+ if (
369
+ stringFlag(flags, 'token') ||
370
+ stringFlag(flags, 'api-token') ||
371
+ stringFlag(flags, 'connect-token') ||
372
+ process.env.JORIPSPACE_API_TOKEN ||
373
+ process.env.JORIPSPACE_CONNECT_TOKEN
374
+ ) {
375
+ const error = new Error(
376
+ message(
377
+ 'The CLI cannot remove tokens supplied through environment variables or command-line arguments. Unset those tokens, then run logout.',
378
+ '환경 변수나 명령행으로 제공한 토큰은 CLI에서 제거할 수 없습니다. 해당 토큰 설정을 해제한 뒤 logout을 실행하세요.'
379
+ )
380
+ );
381
+ error.code = 'logout_external_token';
382
+ throw error;
383
+ }
384
+ const workspaceDir = projectWorkspaceDir(flags);
385
+ const env = readProjectEnv(workspaceDir);
386
+ const legacyProject = readLegacyProjectSessionConnection(workspaceDir);
387
+ const legacyGlobal = readGlobalSession(flags);
388
+ const connection = resolveConnection(flags);
389
+ const apiUrl = normalizeCredentialApiUrl(connection.apiBaseUrl);
390
+ const stored = credentialStore.load(apiUrl, connection.accountId || env.JORIPSPACE_ACCOUNT_ID || '');
391
+ const token = connection.apiToken || stored?.apiToken;
392
+ const sameConnection = (candidate) =>
393
+ candidate?.apiToken === token && trimTrailingSlash(candidate.apiBaseUrl) === apiUrl;
394
+ const clearLegacyProject = token && sameConnection(legacyProject);
395
+ const globalToken = legacyGlobal?.api_token || legacyGlobal?.connect_token;
396
+ const clearLegacyGlobal =
397
+ token &&
398
+ globalToken === token &&
399
+ trimTrailingSlash(legacyGlobal.api_base_url || DEFAULT_API_URL) === apiUrl;
400
+ const legacyProjectPath = clearLegacyProject
401
+ ? managedProjectFilePath(workspaceDir, '.joripspace/agent-session.json')
402
+ : null;
403
+ if (clearLegacyGlobal) managedProjectFilePath(os.homedir(), '.joripspace/session.json');
404
+ managedProjectFilePath(workspaceDir, '.env.joripspace');
405
+ const accountId =
406
+ connection.accountId || env.JORIPSPACE_ACCOUNT_ID || (stored?.apiToken === token ? stored.accountId : '');
407
+ if (accountId) credentialStore.remove(apiUrl, accountId);
408
+ else if (!connection.apiToken) credentialStore.remove(apiUrl);
409
+ updateDotEnvFile(path.join(workspaceDir, '.env.joripspace'), {
410
+ JORIPSPACE_API_BASE_URL: apiUrl,
411
+ JORIPSPACE_API_TOKEN: null,
412
+ JORIPSPACE_CONNECT_TOKEN: null,
413
+ JORIPSPACE_CONNECTION_SOURCE: 'logged-out',
414
+ JORIPSPACE_ACCOUNT_ID: accountId || undefined,
415
+ });
416
+ if (legacyProjectPath) fs.unlinkSync(legacyProjectPath);
417
+ if (clearLegacyGlobal) scrubGlobalSessionToken();
418
+ output(flags, { status: 'logged_out' }, () =>
419
+ console.log(
420
+ message(
421
+ 'Logged out: the current saved connection was removed from this device.',
422
+ '로그아웃 완료: 이 기기에 저장된 현재 연결을 삭제했습니다.'
423
+ )
424
+ )
425
+ );
426
+ }
427
+
335
428
  async function saveBrowserConnectTokenWithOptions(
336
429
  flags,
337
430
  apiToken,
@@ -340,8 +433,9 @@ async function saveBrowserConnectTokenWithOptions(
340
433
  options = {}
341
434
  ) {
342
435
  const connection = selectedApiBaseUrl
343
- ? { apiBaseUrl: trimTrailingSlash(selectedApiBaseUrl), apiToken, source }
436
+ ? { apiBaseUrl: normalizeCredentialApiUrl(selectedApiBaseUrl), apiToken, source }
344
437
  : connectionForExplicitToken(flags, apiToken);
438
+ connection.apiBaseUrl = normalizeCredentialApiUrl(connection.apiBaseUrl);
345
439
  const workspaceDir = projectWorkspaceDir(flags, { discover: false });
346
440
  managedProjectFilePath(workspaceDir, '.env.joripspace');
347
441
  managedProjectFilePath(workspaceDir, '.gitignore');
@@ -361,19 +455,36 @@ async function saveBrowserConnectTokenWithOptions(
361
455
  ? projects[0]
362
456
  : null;
363
457
  if (requestedProject && !selected) throw new Error(`project is not accessible: ${requestedProject}`);
458
+ credentialStore.save({ ...connection, accountId: body.account_id });
364
459
  updateDotEnvFile(path.join(workspaceDir, '.env.joripspace'), {
365
460
  JORIPSPACE_API_BASE_URL: connection.apiBaseUrl,
366
- JORIPSPACE_API_TOKEN: apiToken,
461
+ JORIPSPACE_API_TOKEN: null,
462
+ JORIPSPACE_CONNECT_TOKEN: null,
367
463
  JORIPSPACE_ACCOUNT_ID: body.account_id,
368
- JORIPSPACE_CONNECTION_SOURCE: source,
464
+ JORIPSPACE_CONNECTION_SOURCE: 'os-credential-store',
369
465
  });
370
466
  scrubGlobalSessionToken();
371
467
  if (options.output !== false) {
372
468
  output(flags, body, (value) => {
373
- console.log(`연결 완료: ${value.account_id}`);
374
- console.log(`저장 위치: ${path.join(workspaceDir, '.env.joripspace')}`);
375
- console.log('이 폴더에서 joripspace projects 또는 joripspace start 명령을 실행하세요.');
376
- console.log('회원정보와 API 토큰 관리는 웹 프로필에서만 가능합니다.');
469
+ console.log(message(`Connected: ${value.account_id}`, `연결 완료: ${value.account_id}`));
470
+ console.log(
471
+ message(
472
+ 'Token storage: OS credential store (reused across project folders)',
473
+ '토큰 저장 위치: OS 보안 저장소 (다른 프로젝트 폴더에서도 재사용)'
474
+ )
475
+ );
476
+ console.log(
477
+ message(
478
+ 'Run joripspace projects or joripspace start in this folder.',
479
+ '이 폴더에서 joripspace projects 또는 joripspace start 명령을 실행하세요.'
480
+ )
481
+ );
482
+ console.log(
483
+ message(
484
+ 'Manage account details and API tokens in your web profile.',
485
+ '회원정보와 API 토큰 관리는 웹 프로필에서만 가능합니다.'
486
+ )
487
+ );
377
488
  });
378
489
  }
379
490
  return body;
@@ -408,7 +519,10 @@ async function listMyProjects(flags) {
408
519
 
409
520
  function webOnlyCommand(label) {
410
521
  throw new Error(
411
- `${label} 기능은 웹 화면에서만 사용할 수 있습니다. CLI는 개발, DB/스토리지 작업, 서버 배포, 사용량, 로그 조회용입니다.`
522
+ message(
523
+ `${label} is available only in the web UI. Use the CLI for development, DB/storage operations, server deployment, usage, and logs.`,
524
+ `${label} 기능은 웹 화면에서만 사용할 수 있습니다. CLI는 개발, DB/스토리지 작업, 서버 배포, 사용량, 로그 조회용입니다.`
525
+ )
412
526
  );
413
527
  }
414
528
 
@@ -660,7 +774,8 @@ async function deployCode(flags, options = {}) {
660
774
  }
661
775
 
662
776
  function printDeploymentWarnings(warnings) {
663
- for (const warning of warnings || []) console.warn(`경고: ${warning.message}`);
777
+ for (const warning of warnings || [])
778
+ console.warn(message(`Warning: ${warning.message}`, `경고: ${warning.message}`));
664
779
  }
665
780
 
666
781
  async function listDeployments(flags) {
@@ -680,8 +795,14 @@ async function listDeployments(flags) {
680
795
  console.log(
681
796
  `${deployment.version}\t${deployment.deployment_id}\t${deployment.status}\trollback=${deployment.rollback_available}\t${deployment.created_at}`
682
797
  );
683
- if (deployment.error_message) console.log(`${deployment.error_stage || 'unknown'} / ${deployment.error_code || 'unknown'}: ${deployment.error_message}`);
684
- if (deployment.github) console.log(`GitHub: ${deployment.github.commit_sha} ${deployment.github.run_url} (${deployment.github.diagnostic_status || 'pending'})`);
798
+ if (deployment.error_message)
799
+ console.log(
800
+ `${deployment.error_stage || 'unknown'} / ${deployment.error_code || 'unknown'}: ${deployment.error_message}`
801
+ );
802
+ if (deployment.github)
803
+ console.log(
804
+ `GitHub: ${deployment.github.commit_sha} ${deployment.github.run_url} (${deployment.github.diagnostic_status || 'pending'})`
805
+ );
685
806
  if (deployment.error_details) console.log(deployment.error_details);
686
807
  }
687
808
  });
@@ -959,16 +1080,29 @@ function printWebhookDelivery(delivery) {
959
1080
 
960
1081
  async function listTokens(flags) {
961
1082
  throw new Error(
962
- 'API 토큰은 웹 프로필에서 발급하거나 사용 중지해주세요. CLI 토큰은 프로젝트 관리 전용입니다.'
1083
+ message(
1084
+ 'Issue or disable API tokens in your web profile. CLI tokens are for project management.',
1085
+ 'API 토큰은 웹 프로필에서 발급하거나 사용 중지해주세요. CLI 토큰은 프로젝트 관리 전용입니다.'
1086
+ )
963
1087
  );
964
1088
  }
965
1089
 
966
1090
  async function createToken(flags) {
967
- throw new Error('API 토큰은 웹 프로필에서 발급해주세요. CLI 토큰으로 새 토큰을 만들 수 없습니다.');
1091
+ throw new Error(
1092
+ message(
1093
+ 'Issue API tokens in your web profile. A CLI token cannot create new tokens.',
1094
+ 'API 토큰은 웹 프로필에서 발급해주세요. CLI 토큰으로 새 토큰을 만들 수 없습니다.'
1095
+ )
1096
+ );
968
1097
  }
969
1098
 
970
1099
  async function revokeToken(flags) {
971
- throw new Error('API 토큰은 웹 프로필에서 사용 중지해주세요. CLI 토큰으로 토큰을 폐기할 수 없습니다.');
1100
+ throw new Error(
1101
+ message(
1102
+ 'Disable API tokens in your web profile. A CLI token cannot revoke tokens.',
1103
+ 'API 토큰은 웹 프로필에서 사용 중지해주세요. CLI 토큰으로 토큰을 폐기할 수 없습니다.'
1104
+ )
1105
+ );
972
1106
  }
973
1107
 
974
1108
  async function deleteProject(flags) {
@@ -997,7 +1131,10 @@ async function apiRequest(flags, apiPath, options) {
997
1131
  'X-Joripspace-Session-Context': 'cli',
998
1132
  };
999
1133
 
1000
- const timeoutMs = options.timeoutMs ?? (isDeploymentRequest(apiPath) ? null : GENERAL_REQUEST_TIMEOUT_MS);
1134
+ const timeoutMs =
1135
+ options.timeoutMs === null
1136
+ ? null
1137
+ : (options.timeoutMs ?? (isDeploymentRequest(apiPath) ? null : GENERAL_REQUEST_TIMEOUT_MS));
1001
1138
  const controller = new AbortController();
1002
1139
  const timer = timeoutMs === null ? undefined : setTimeout(() => controller.abort(), timeoutMs);
1003
1140
  let response;
@@ -1007,6 +1144,7 @@ async function apiRequest(flags, apiPath, options) {
1007
1144
  headers,
1008
1145
  body: options.body ? JSON.stringify(options.body) : undefined,
1009
1146
  signal: controller.signal,
1147
+ redirect: 'error',
1010
1148
  });
1011
1149
  } catch (error) {
1012
1150
  if (error?.name === 'AbortError') {
@@ -1019,7 +1157,12 @@ async function apiRequest(flags, apiPath, options) {
1019
1157
  timeoutError.code = 'request_timeout';
1020
1158
  throw timeoutError;
1021
1159
  }
1022
- const requestError = new Error(error instanceof Error ? error.message : String(error));
1160
+ const requestError = new Error(
1161
+ redactAuthError(error instanceof Error ? error.message : String(error), [
1162
+ options.apiToken,
1163
+ options.body?.code,
1164
+ ])
1165
+ );
1023
1166
  requestError.code = 'request_failed';
1024
1167
  throw requestError;
1025
1168
  } finally {
@@ -1029,11 +1172,13 @@ async function apiRequest(flags, apiPath, options) {
1029
1172
  const body = text ? parseJson(text) : {};
1030
1173
 
1031
1174
  if (!response.ok) {
1032
- const message = body?.error?.message || body?.message || text || `HTTP ${response.status}`;
1033
- const apiError = new Error(formatDeploymentFailure(message, body?.error?.details));
1034
- apiError.code = body?.error?.code || 'http_error';
1175
+ const safe = redactAuthError(body, [options.apiToken, options.body?.code]);
1176
+ const message =
1177
+ safe?.error?.message || safe?.message || JSON.stringify(safe) || `HTTP ${response.status}`;
1178
+ const apiError = new Error(formatDeploymentFailure(message, safe?.error?.details));
1179
+ apiError.code = safe?.error?.code || 'http_error';
1035
1180
  apiError.status = response.status;
1036
- if (body?.error?.details !== undefined) apiError.details = body.error.details;
1181
+ if (safe?.error?.details !== undefined) apiError.details = safe.error.details;
1037
1182
  throw apiError;
1038
1183
  }
1039
1184
 
@@ -1044,6 +1189,23 @@ async function apiRequest(flags, apiPath, options) {
1044
1189
  return body;
1045
1190
  }
1046
1191
 
1192
+ function redactAuthError(value, secrets) {
1193
+ if (typeof value === 'string') {
1194
+ for (const secret of secrets.filter(Boolean)) value = value.split(secret).join('[REDACTED]');
1195
+ return value;
1196
+ }
1197
+ if (Array.isArray(value)) return value.map((item) => redactAuthError(item, secrets));
1198
+ if (value && typeof value === 'object') {
1199
+ return Object.fromEntries(
1200
+ Object.entries(value).map(([key, item]) => [
1201
+ redactAuthError(key, secrets),
1202
+ redactAuthError(item, secrets),
1203
+ ])
1204
+ );
1205
+ }
1206
+ return value;
1207
+ }
1208
+
1047
1209
  function isDeploymentRequest(apiPath) {
1048
1210
  return /\/deploy(?:ments)?(?:[/?]|$)|\/checkpoints\/[^/]+\/deploy(?:[/?]|$)/.test(apiPath);
1049
1211
  }
@@ -1056,17 +1218,34 @@ function browserConnectInstructions() {
1056
1218
  return {
1057
1219
  status: 'browser_connection_required',
1058
1220
  connect_url: 'https://joripspace.com/connect/',
1059
- message:
1060
- '이메일 주소는 필요 없습니다. 브라우저에서 JoripSpace에 로그인한 뒤 연결을 승인하고 5분 일회용 연결 코드를 복사하세요.',
1061
- save_command: 'joripspace login --code "복사한_연결_코드"',
1221
+ message: message(
1222
+ 'No email address is required. Sign in to JoripSpace in your browser, approve the connection, and copy the one-time code, valid for five minutes.',
1223
+ '이메일 주소는 필요 없습니다. 브라우저에서 JoripSpace에 로그인한 뒤 연결을 승인하고 5분 일회용 연결 코드를 복사하세요.'
1224
+ ),
1225
+ save_command: 'joripspace login --code "CONNECTION_CODE"',
1062
1226
  };
1063
1227
  }
1064
1228
 
1065
1229
  function printBrowserConnectInstructions(value) {
1066
- console.log('브라우저에서 JoripSpace 연결을 승인하세요.');
1067
- console.log('이메일 주소 입력이나 메일 확인은 필요 없습니다.');
1068
- console.log(`연결 페이지: ${value.connect_url}`);
1069
- console.log('승인 후 화면에 표시되는 5분 일회용 연결 코드를 아래 명령으로 교환하세요.');
1230
+ console.log(
1231
+ message(
1232
+ 'Approve the JoripSpace connection in your browser.',
1233
+ '브라우저에서 JoripSpace 연결을 승인하세요.'
1234
+ )
1235
+ );
1236
+ console.log(
1237
+ message(
1238
+ 'No email address or email verification is required.',
1239
+ '이메일 주소 입력이나 메일 확인은 필요 없습니다.'
1240
+ )
1241
+ );
1242
+ console.log(message(`Connection page: ${value.connect_url}`, `연결 페이지: ${value.connect_url}`));
1243
+ console.log(
1244
+ message(
1245
+ 'After approval, exchange the displayed five-minute one-time code using this command.',
1246
+ '승인 후 화면에 표시되는 5분 일회용 연결 코드를 아래 명령으로 교환하세요.'
1247
+ )
1248
+ );
1070
1249
  console.log(value.save_command);
1071
1250
  }
1072
1251
 
@@ -1077,11 +1256,15 @@ function normalizeConnectToken(value) {
1077
1256
  }
1078
1257
  if (
1079
1258
  token.startsWith(SESSION_COOKIE_PREFIX) ||
1259
+ /[\u0000-\u0020\u007f]/.test(token) ||
1080
1260
  /^bearer\s+/i.test(token) ||
1081
1261
  ['dummy', 'test', 'token', 'undefined', 'null'].includes(token.toLowerCase())
1082
1262
  ) {
1083
1263
  throw new Error(
1084
- '브라우저 쿠키, Bearer 문자열, 빈 자리표시자, 테스트 값은 CLI 연결 토큰으로 사용할 수 없습니다. /connect/에서 새 연결 토큰을 발급하세요.'
1264
+ message(
1265
+ 'Browser cookies, Bearer strings, empty placeholders, and test values cannot be used as CLI connection tokens. Get a new connection token at /connect/.',
1266
+ '브라우저 쿠키, Bearer 문자열, 빈 자리표시자, 테스트 값은 CLI 연결 토큰으로 사용할 수 없습니다. /connect/에서 새 연결 토큰을 발급하세요.'
1267
+ )
1085
1268
  );
1086
1269
  }
1087
1270
  return token;
@@ -1092,7 +1275,12 @@ function normalizeConnectionCode(value) {
1092
1275
  .replace(/[\s-]+/g, '')
1093
1276
  .toUpperCase();
1094
1277
  if (!/^[0-9A-HJKMNP-TV-Z]{16}$/.test(normalized)) {
1095
- throw new Error('연결 코드는 화면에 표시된 16자리 영숫자 값이어야 합니다.');
1278
+ throw new Error(
1279
+ message(
1280
+ 'The connection code must be the 16-character alphanumeric value shown on the connection page.',
1281
+ '연결 코드는 화면에 표시된 16자리 영숫자 값이어야 합니다.'
1282
+ )
1283
+ );
1096
1284
  }
1097
1285
  return normalized.match(/.{1,4}/g).join('-');
1098
1286
  }
@@ -1260,33 +1448,44 @@ function resolveConnection(flags) {
1260
1448
  apiToken: projectEnv.JORIPSPACE_API_TOKEN,
1261
1449
  apiBaseUrl: trimTrailingSlash(projectEnv.JORIPSPACE_API_BASE_URL || DEFAULT_API_URL),
1262
1450
  source: 'project-env',
1451
+ accountId: projectEnv.JORIPSPACE_ACCOUNT_ID,
1263
1452
  workspaceDir,
1264
1453
  };
1265
1454
  }
1266
1455
 
1267
- const legacyProjectConnection = readLegacyProjectSessionConnection(workspaceDir);
1456
+ const managedOsConnection = ['os-credential-store', 'logged-out'].includes(
1457
+ projectEnv.JORIPSPACE_CONNECTION_SOURCE
1458
+ );
1459
+ const legacyProjectConnection = managedOsConnection
1460
+ ? null
1461
+ : readLegacyProjectSessionConnection(workspaceDir);
1268
1462
  if (legacyProjectConnection) return legacyProjectConnection;
1269
1463
 
1270
- const legacy = readGlobalSession(flags);
1464
+ const legacy = managedOsConnection ? null : readGlobalSession(flags);
1271
1465
  const legacyToken = legacy?.api_token || legacy?.connect_token;
1272
1466
  if (legacyToken) {
1273
1467
  return {
1274
1468
  apiToken: legacyToken,
1275
1469
  apiBaseUrl: trimTrailingSlash(legacy.api_base_url || DEFAULT_API_URL),
1276
1470
  source: 'legacy-global-session',
1471
+ accountId: legacy.account?.account_id || legacy.account_id,
1277
1472
  workspaceDir,
1278
1473
  };
1279
1474
  }
1280
1475
 
1476
+ const selectedApiBaseUrl = trimTrailingSlash(
1477
+ projectEnv.JORIPSPACE_API_BASE_URL ||
1478
+ stringFlag(flags, 'api-url') ||
1479
+ process.env.JORIPSPACE_API_URL ||
1480
+ process.env.JORIPSPACE_API_BASE_URL ||
1481
+ DEFAULT_API_URL
1482
+ );
1483
+ const stored = credentialStore.load(selectedApiBaseUrl, projectEnv.JORIPSPACE_ACCOUNT_ID || '');
1484
+ if (stored) return { ...stored, workspaceDir };
1485
+
1281
1486
  return {
1282
1487
  apiToken: '',
1283
- apiBaseUrl: trimTrailingSlash(
1284
- stringFlag(flags, 'api-url') ||
1285
- process.env.JORIPSPACE_API_URL ||
1286
- process.env.JORIPSPACE_API_BASE_URL ||
1287
- projectEnv.JORIPSPACE_API_BASE_URL ||
1288
- DEFAULT_API_URL
1289
- ),
1488
+ apiBaseUrl: selectedApiBaseUrl,
1290
1489
  source: 'none',
1291
1490
  workspaceDir,
1292
1491
  };
@@ -1338,20 +1537,27 @@ function scrubGlobalSessionToken() {
1338
1537
  return true;
1339
1538
  }
1340
1539
 
1341
- function persistStartConnection(flags, connection) {
1540
+ function persistStartConnection(flags, connection, context = {}) {
1342
1541
  if (
1343
- !['legacy-global-session', 'legacy-project-session'].includes(connection?.source) ||
1542
+ !['project-env', 'legacy-global-session', 'legacy-project-session', 'os-credential-store'].includes(
1543
+ connection?.source
1544
+ ) ||
1344
1545
  !connection.apiToken
1345
1546
  ) {
1346
1547
  return false;
1347
1548
  }
1348
1549
  const workspaceDir = path.resolve(stringFlag(flags, 'cwd') || projectWorkspaceDir(flags));
1349
1550
  ensureProjectEnvIgnored(workspaceDir);
1551
+ const stored =
1552
+ connection.source === 'os-credential-store'
1553
+ ? connection
1554
+ : credentialStore.save({ ...connection, accountId: context.accountId || connection.accountId });
1350
1555
  updateDotEnvFile(path.join(workspaceDir, '.env.joripspace'), {
1351
- JORIPSPACE_API_BASE_URL: connection.apiBaseUrl,
1352
- JORIPSPACE_API_TOKEN: connection.apiToken,
1353
- JORIPSPACE_ACCOUNT_ID: connection.accountId,
1354
- JORIPSPACE_CONNECTION_SOURCE: `${connection.source}-migration`,
1556
+ JORIPSPACE_API_BASE_URL: stored.apiBaseUrl,
1557
+ JORIPSPACE_API_TOKEN: null,
1558
+ JORIPSPACE_CONNECT_TOKEN: null,
1559
+ JORIPSPACE_ACCOUNT_ID: stored.accountId,
1560
+ JORIPSPACE_CONNECTION_SOURCE: 'os-credential-store',
1355
1561
  });
1356
1562
  if (connection.source === 'legacy-global-session') scrubGlobalSessionToken();
1357
1563
  return true;
@@ -1405,24 +1611,12 @@ function canonicalWorkspaceEntry(directory, expected) {
1405
1611
 
1406
1612
  async function connectForStart(flags, context) {
1407
1613
  let connectionCode = stringFlag(flags, 'code');
1408
- const interactive = !flags.json && Boolean(process.stdin.isTTY && process.stdout.isTTY);
1409
- if (!connectionCode && !interactive) return resolveConnection(flags);
1410
-
1411
1614
  if (!connectionCode) {
1412
- const instructions = browserConnectInstructions();
1413
- console.log('브라우저에서 JoripSpace 연결을 승인하세요.');
1414
- console.log(`연결 페이지: ${instructions.connect_url}`);
1415
- console.log('승인 후 표시된 5분 일회용 연결 코드를 이 터미널에 붙여 넣으세요.');
1416
- openExternalUrl(instructions.connect_url);
1417
- const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
1418
- try {
1419
- connectionCode = await prompt.question('연결 코드: ');
1420
- } finally {
1421
- prompt.close();
1422
- }
1615
+ connectionCode = await promptConnectionCode(flags);
1616
+ if (connectionCode === null) return resolveConnection(flags);
1423
1617
  }
1424
1618
 
1425
- const exchangeApiBaseUrl = unauthenticatedApiBaseUrl(flags);
1619
+ const exchangeApiBaseUrl = normalizeCredentialApiUrl(unauthenticatedApiBaseUrl(flags));
1426
1620
  ensureProjectEnvIgnored(context.cwd);
1427
1621
  const exchange = await apiRequest(flags, '/v1/auth/connection-code/exchange', {
1428
1622
  method: 'POST',
@@ -1440,6 +1634,48 @@ async function connectForStart(flags, context) {
1440
1634
  return resolveConnection({ ...flags, cwd: context.cwd });
1441
1635
  }
1442
1636
 
1637
+ async function promptConnectionCode(flags) {
1638
+ if (flags.json || !process.stdin.isTTY || !process.stdout.isTTY) return null;
1639
+ const instructions = browserConnectInstructions();
1640
+ console.log(
1641
+ message(
1642
+ 'Approve the JoripSpace connection in your browser.',
1643
+ '브라우저에서 JoripSpace 연결을 승인하세요.'
1644
+ )
1645
+ );
1646
+ console.log(
1647
+ message(`Connection page: ${instructions.connect_url}`, `연결 페이지: ${instructions.connect_url}`)
1648
+ );
1649
+ console.log(
1650
+ message(
1651
+ 'After approval, paste the displayed five-minute one-time code into this terminal.',
1652
+ '승인 후 표시된 5분 일회용 연결 코드를 이 터미널에 붙여 넣으세요.'
1653
+ )
1654
+ );
1655
+ openExternalUrl(instructions.connect_url);
1656
+ const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
1657
+ const cancellation = new AbortController();
1658
+ prompt.once('close', () => cancellation.abort());
1659
+ try {
1660
+ return await prompt.question(message('Connection code: ', '연결 코드: '), {
1661
+ signal: cancellation.signal,
1662
+ });
1663
+ } catch (error) {
1664
+ if (error?.code !== 'ABORT_ERR') throw error;
1665
+ const cancelled = new Error(
1666
+ message(
1667
+ 'Connection code entry was cancelled. Run login again.',
1668
+ '연결 코드 입력이 취소되었습니다. login을 다시 실행하세요.'
1669
+ )
1670
+ );
1671
+ cancelled.code = 'connection_required';
1672
+ cancelled.exitCode = 2;
1673
+ throw cancelled;
1674
+ } finally {
1675
+ prompt.close();
1676
+ }
1677
+ }
1678
+
1443
1679
  function openExternalUrl(url) {
1444
1680
  const command =
1445
1681
  process.platform === 'win32'