@joripspace/cli 0.5.8 → 0.6.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/README.md CHANGED
@@ -53,9 +53,9 @@ npx -y @joripspace/cli@latest get --cwd "my project" --json
53
53
 
54
54
  Follow the link from `login` to [JoripSpace Connect](https://joripspace.com/connect/), approve the connection, and copy the one-time code, which expires after five minutes. Replace `my-app` with your existing project slug.
55
55
 
56
- `login --code` stores the connection token in the OS credential store: Windows Credential Manager, macOS Keychain, or Linux Secret Service. The project's Git-ignored `.env.joripspace` contains only the API URL, account ID, and connection source, without the token. A regular `.env` file is not used for authentication. Subsequent npx runs reuse the saved connection, so you do not need to log in each time. Credentials and project state are not stored inside the npm package or cache.
56
+ `login --code` prefers the OS credential store: Windows Credential Manager, macOS Keychain, or Linux Secret Service. When available, the project's Git-ignored `.env.joripspace` contains only the API URL, account ID, and connection source, without the token. A regular `.env` file is not used for authentication. Subsequent npx runs reuse the saved connection, so you do not need to log in each time. Credentials and project state are not stored inside the npm package or cache.
57
57
 
58
- If the OS credential store is unavailable, login stops without saving a plaintext token. For automation, supply `JORIPSPACE_API_TOKEN` and the matching `JORIPSPACE_API_URL` through the process environment.
58
+ If the OS credential store is unavailable before writing, login saves the token in the project-local `.env.joripspace` instead. This fallback is reused only in that project and remains Git-ignored and excluded from deployment and checkpoints. Login returns `credential_storage: project-env-fallback` or `os-credential-store`. `logout` removes all saved token entries from the current project file and the matching OS account credential when available. OS login is shared across folders, including previously logged-out folders. If the OS store becomes available, running `login` migrates the token back and removes it from the file. Failed OS writes or readback verification still stop without falling back. For automation, supply `JORIPSPACE_API_TOKEN` and the matching `JORIPSPACE_API_URL` through the process environment.
59
59
 
60
60
  Without `--cwd`, the CLI uses your current working directory and searches parent directories for the project connection. Existing `.joripspace/project` markers, the `--project` alias, environment variables, and legacy credential validation and migration remain supported. The default API is `https://api.joripspace.com`; use the existing `--api-url` option or `JORIPSPACE_API_URL` environment variable to override it.
61
61
 
@@ -94,6 +94,22 @@ checks apply. Creation does not link or change local project source; use `start`
94
94
 
95
95
  ## Commands and compatibility
96
96
 
97
+ ### Project secrets
98
+
99
+ Use `joripspace secret generate --name SESSION_SECRET --json` to generate and store an internal random value without
100
+ seeing it. Existing active values are preserved. Use `joripspace secret set --name API_KEY --value-stdin --json`
101
+ (alias: `secret update`) to create or replace a value received from an external server, provider, or another system.
102
+ Send the exact value through process stdin; never put it in command arguments, chat, logs, source, or temporary project
103
+ files. Input must be 1-5120 UTF-8 bytes. Whitespace and newlines are preserved. Values are never returned.
104
+
105
+ `start` onboarding and Secret command responses include the selected project's `secret_management_url`. Agents should
106
+ show it as a clickable link after creation/replacement and whenever the user needs to enter a value, explaining the
107
+ exact key name and purpose. The user can enter a value on that page and click **Register or replace**. Confirm the name,
108
+ status, and change time with `joripspace secret list --json`, then verify the relevant integration. Secret deletion
109
+ remains a web operation. Registration and replacement still require project access and valid, non-reserved key names.
110
+
111
+ ### Other commands
112
+
97
113
  Use `--help`, `deploy --help`, `deploy-template --help`, or `install-template --help` for the supported commands and options. Existing functionality includes authentication, project inspection, deployment, templates, checkpoints, databases, storage, realtime v2, secrets, cron jobs, domains, mail, usage, and events. Operations restricted to the web interface remain restricted.
98
114
 
99
115
  The CLI preserves existing result fields and exit codes `0`, `1`, and `2`, with the additive `onboarding` object described above. With `--json`, successful results go to stdout and errors go to stderr. User-facing explanations should follow the user's language; the shared agent guide is English.
package/bin/joripspace.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  const { message } = require('../lib/locale');
3
+ const { redactAuthError } = require('../lib/auth-redaction');
3
4
 
4
5
  const fs = require('node:fs');
5
6
  const os = require('node:os');
@@ -36,6 +37,7 @@ const {
36
37
  const { ensureProjectEnvIgnored, readProjectEnv, updateDotEnvFile } = require('../lib/project-env');
37
38
  const { createCredentialStore, normalizeCredentialApiUrl } = require('../lib/credential-store');
38
39
  const credentialStore = createCredentialStore();
40
+ const { persistProjectConnection } = require('../lib/connection-persistence');
39
41
  const { createStartProjectCommand } = require('../lib/start-command');
40
42
  const { legacyCredentialSessionConnection, readProjectMarker } = require('../lib/start');
41
43
  const { buildTemplateDeployRequest, listTemplates } = loadTemplatesPackage();
@@ -342,8 +344,14 @@ async function login(flags) {
342
344
  await saveBrowserConnectToken(flags, normalizeConnectToken(connectToken));
343
345
  return;
344
346
  }
345
- const existing = resolveConnection(flags);
346
- if (existing.apiToken) {
347
+ let existing;
348
+ try {
349
+ existing = resolveConnection(flags);
350
+ } catch (error) {
351
+ if (error.code !== 'credential_store_unavailable') throw error;
352
+ // Reauthentication can obtain a new token even when an older OS login is inaccessible.
353
+ }
354
+ if (existing?.apiToken) {
347
355
  await saveBrowserConnectToken(
348
356
  flags,
349
357
  normalizeConnectToken(existing.apiToken),
@@ -387,7 +395,14 @@ function logout(flags) {
387
395
  const legacyGlobal = readGlobalSession(flags);
388
396
  const connection = resolveConnection(flags);
389
397
  const apiUrl = normalizeCredentialApiUrl(connection.apiBaseUrl);
390
- const stored = credentialStore.load(apiUrl, connection.accountId || env.JORIPSPACE_ACCOUNT_ID || '');
398
+ let stored = null;
399
+ let osCredentialStatus = 'not_found';
400
+ try {
401
+ stored = credentialStore.load(apiUrl, connection.accountId || env.JORIPSPACE_ACCOUNT_ID || '');
402
+ } catch (error) {
403
+ if (error.code !== 'credential_store_unavailable' || connection.source === 'os-credential-store') throw error;
404
+ osCredentialStatus = 'unavailable';
405
+ }
391
406
  const token = connection.apiToken || stored?.apiToken;
392
407
  const sameConnection = (candidate) =>
393
408
  candidate?.apiToken === token && trimTrailingSlash(candidate.apiBaseUrl) === apiUrl;
@@ -404,8 +419,10 @@ function logout(flags) {
404
419
  managedProjectFilePath(workspaceDir, '.env.joripspace');
405
420
  const accountId =
406
421
  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);
422
+ if (stored) {
423
+ credentialStore.remove(apiUrl, stored.accountId);
424
+ osCredentialStatus = 'removed';
425
+ }
409
426
  updateDotEnvFile(path.join(workspaceDir, '.env.joripspace'), {
410
427
  JORIPSPACE_API_BASE_URL: apiUrl,
411
428
  JORIPSPACE_API_TOKEN: null,
@@ -415,11 +432,14 @@ function logout(flags) {
415
432
  });
416
433
  if (legacyProjectPath) fs.unlinkSync(legacyProjectPath);
417
434
  if (clearLegacyGlobal) scrubGlobalSessionToken();
418
- output(flags, { status: 'logged_out' }, () =>
435
+ output(flags, { status: 'logged_out', project_credentials_cleared: true, os_credential_status: osCredentialStatus }, () =>
419
436
  console.log(
420
- message(
421
- 'Logged out: the current saved connection was removed from this device.',
422
- '로그아웃 완료: 이 기기에 저장된 현재 연결을 삭제했습니다.'
437
+ osCredentialStatus === 'unavailable' ? message(
438
+ 'Logged out: saved project credentials were removed. The OS credential store is unavailable and could not be checked.',
439
+ '로그아웃 완료: 프로젝트에 저장된 인증 정보를 삭제했습니다. OS 보안 저장소는 사용할 수 없어 확인하지 못했습니다.'
440
+ ) : message(
441
+ 'Logged out: the current saved connection was removed.',
442
+ '로그아웃 완료: 저장된 현재 연결을 삭제했습니다.'
423
443
  )
424
444
  )
425
445
  );
@@ -455,20 +475,16 @@ async function saveBrowserConnectTokenWithOptions(
455
475
  ? projects[0]
456
476
  : null;
457
477
  if (requestedProject && !selected) throw new Error(`project is not accessible: ${requestedProject}`);
458
- credentialStore.save({ ...connection, accountId: body.account_id });
459
- updateDotEnvFile(path.join(workspaceDir, '.env.joripspace'), {
460
- JORIPSPACE_API_BASE_URL: connection.apiBaseUrl,
461
- JORIPSPACE_API_TOKEN: null,
462
- JORIPSPACE_CONNECT_TOKEN: null,
463
- JORIPSPACE_ACCOUNT_ID: body.account_id,
464
- JORIPSPACE_CONNECTION_SOURCE: 'os-credential-store',
465
- });
478
+ const storage = persistProjectConnection(credentialStore, workspaceDir, { ...connection, accountId: body.account_id });
466
479
  scrubGlobalSessionToken();
467
480
  if (options.output !== false) {
468
- output(flags, body, (value) => {
481
+ output(flags, { ...body, credential_storage: storage }, (value) => {
469
482
  console.log(message(`Connected: ${value.account_id}`, `연결 완료: ${value.account_id}`));
470
483
  console.log(
471
- message(
484
+ storage === 'project-env-fallback' ? message(
485
+ 'Token storage: .env.joripspace (OS credential store unavailable; reused in this project)',
486
+ '토큰 저장 위치: .env.joripspace (OS 보안 저장소를 사용할 수 없어 이 프로젝트에서 재사용)'
487
+ ) : message(
472
488
  'Token storage: OS credential store (reused across project folders)',
473
489
  '토큰 저장 위치: OS 보안 저장소 (다른 프로젝트 폴더에서도 재사용)'
474
490
  )
@@ -1160,6 +1176,7 @@ async function apiRequest(flags, apiPath, options) {
1160
1176
  const requestError = new Error(
1161
1177
  redactAuthError(error instanceof Error ? error.message : String(error), [
1162
1178
  options.apiToken,
1179
+ options.adminToken,
1163
1180
  options.body?.code,
1164
1181
  ])
1165
1182
  );
@@ -1172,7 +1189,7 @@ async function apiRequest(flags, apiPath, options) {
1172
1189
  const body = text ? parseJson(text) : {};
1173
1190
 
1174
1191
  if (!response.ok) {
1175
- const safe = redactAuthError(body, [options.apiToken, options.body?.code]);
1192
+ const safe = redactAuthError(body, [options.apiToken, options.adminToken, options.body?.code]);
1176
1193
  const message =
1177
1194
  safe?.error?.message || safe?.message || JSON.stringify(safe) || `HTTP ${response.status}`;
1178
1195
  const apiError = new Error(formatDeploymentFailure(message, safe?.error?.details));
@@ -1189,23 +1206,6 @@ async function apiRequest(flags, apiPath, options) {
1189
1206
  return body;
1190
1207
  }
1191
1208
 
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
-
1209
1209
  function isDeploymentRequest(apiPath) {
1210
1210
  return /\/deploy(?:ments)?(?:[/?]|$)|\/checkpoints\/[^/]+\/deploy(?:[/?]|$)/.test(apiPath);
1211
1211
  }
@@ -1453,7 +1453,7 @@ function resolveConnection(flags) {
1453
1453
  };
1454
1454
  }
1455
1455
 
1456
- const managedOsConnection = ['os-credential-store', 'logged-out'].includes(
1456
+ const managedOsConnection = ['os-credential-store', 'project-env-fallback', 'logged-out'].includes(
1457
1457
  projectEnv.JORIPSPACE_CONNECTION_SOURCE
1458
1458
  );
1459
1459
  const legacyProjectConnection = managedOsConnection
@@ -1480,7 +1480,12 @@ function resolveConnection(flags) {
1480
1480
  process.env.JORIPSPACE_API_BASE_URL ||
1481
1481
  DEFAULT_API_URL
1482
1482
  );
1483
- const stored = credentialStore.load(selectedApiBaseUrl, projectEnv.JORIPSPACE_ACCOUNT_ID || '');
1483
+ let stored = null;
1484
+ try {
1485
+ stored = credentialStore.load(selectedApiBaseUrl, projectEnv.JORIPSPACE_ACCOUNT_ID || '');
1486
+ } catch (error) {
1487
+ if (error.code !== 'credential_store_unavailable' || projectEnv.JORIPSPACE_CONNECTION_SOURCE === 'os-credential-store') throw error;
1488
+ }
1484
1489
  if (stored) return { ...stored, workspaceDir };
1485
1490
 
1486
1491
  return {
@@ -1548,16 +1553,8 @@ function persistStartConnection(flags, connection, context = {}) {
1548
1553
  }
1549
1554
  const workspaceDir = path.resolve(stringFlag(flags, 'cwd') || projectWorkspaceDir(flags));
1550
1555
  ensureProjectEnvIgnored(workspaceDir);
1551
- const stored =
1552
- connection.source === 'os-credential-store'
1553
- ? connection
1554
- : credentialStore.save({ ...connection, accountId: context.accountId || connection.accountId });
1555
- updateDotEnvFile(path.join(workspaceDir, '.env.joripspace'), {
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',
1556
+ persistProjectConnection(credentialStore, workspaceDir, {
1557
+ ...connection, accountId: context.accountId || connection.accountId,
1561
1558
  });
1562
1559
  if (connection.source === 'legacy-global-session') scrubGlobalSessionToken();
1563
1560
  return true;
@@ -0,0 +1 @@
1
+ module.exports = require('../vendor/core/auth-redaction.cjs');
@@ -11,6 +11,7 @@ const {
11
11
  safeProjectRelativePath,
12
12
  } = require('./project-paths');
13
13
  const { ensureProjectEnvIgnored } = require('./project-env');
14
+ const { redactAuthError } = require('./auth-redaction');
14
15
 
15
16
  const HARD_DIRS = new Set(['.git', 'node_modules', '.wrangler', '.cache', 'coverage', 'tmp', 'temp']);
16
17
  const HARD_FILES = new Set(['.ds_store', 'thumbs.db', 'desktop.ini']);
@@ -173,6 +174,13 @@ async function restoreCheckpoint(options) {
173
174
  }
174
175
 
175
176
  function projectFiles(root) {
177
+ return projectFileEntries(root).map(({ relative, path: filePath }) => [
178
+ relative, new Uint8Array(fs.readFileSync(filePath)),
179
+ ]);
180
+ }
181
+
182
+ function projectFileEntries(root) {
183
+ root = path.resolve(root);
176
184
  const files = [];
177
185
  function walk(directory, inherited = []) {
178
186
  const names = directory === root ? ['.gitignore', '.ignore', '.joripspaceignore'] : ['.gitignore'];
@@ -196,7 +204,7 @@ function projectFiles(root) {
196
204
  if (entry.isDirectory()) {
197
205
  walk(full, rules);
198
206
  } else if (entry.isFile()) {
199
- files.push([relative, new Uint8Array(fs.readFileSync(full))]);
207
+ files.push({ relative, path: full, size: stat.size });
200
208
  }
201
209
  }
202
210
  }
@@ -383,6 +391,7 @@ async function apiFetch(options, route, request = {}) {
383
391
  },
384
392
  body: request.bytes || (request.json === undefined ? undefined : JSON.stringify(request.json)),
385
393
  signal: controller.signal,
394
+ redirect: 'error',
386
395
  });
387
396
  } catch (error) {
388
397
  if (error?.name === 'AbortError') {
@@ -390,7 +399,9 @@ async function apiFetch(options, route, request = {}) {
390
399
  timeoutError.code = 'request_timeout';
391
400
  throw timeoutError;
392
401
  }
393
- const requestError = new Error(error instanceof Error ? error.message : String(error));
402
+ const requestError = new Error(redactAuthError(
403
+ error instanceof Error ? error.message : String(error), [options.apiToken]
404
+ ));
394
405
  requestError.code = 'request_failed';
395
406
  throw requestError;
396
407
  } finally {
@@ -413,6 +424,7 @@ async function apiFetch(options, route, request = {}) {
413
424
  body = { message: text };
414
425
  }
415
426
  if (!response.ok) {
427
+ body = redactAuthError(body, [options.apiToken]);
416
428
  const apiError = new Error(
417
429
  body?.error?.message || body?.message || `checkpoint request failed (HTTP ${response.status})`
418
430
  );
@@ -431,6 +443,7 @@ function toPosix(value) {
431
443
  module.exports = {
432
444
  hardExcluded,
433
445
  projectFiles,
446
+ projectFileEntries,
434
447
  runCheckpointOperation,
435
448
  safeRestorePath,
436
449
  verifyRestoreArchive,
@@ -0,0 +1,36 @@
1
+ const path = require('node:path');
2
+ const { normalizeCredentialApiUrl } = require('./credential-store');
3
+ const { ensureProjectEnvIgnored, updateDotEnvFile } = require('./project-env');
4
+
5
+ function persistProjectConnection(store, workspaceDir, connection) {
6
+ ensureProjectEnvIgnored(workspaceDir);
7
+ const apiBaseUrl = normalizeCredentialApiUrl(connection.apiBaseUrl);
8
+ if (!connection.accountId || typeof connection.accountId !== 'string' ||
9
+ typeof connection.apiToken !== 'string' || !connection.apiToken.trim() || /[\r\n]/.test(connection.apiToken)) {
10
+ const error = new Error('Invalid connection credentials. Reconnect with login --code.');
11
+ error.code = 'credential_store_invalid';
12
+ throw error;
13
+ }
14
+ let storage = 'os-credential-store';
15
+ try {
16
+ store.load(apiBaseUrl, connection.accountId);
17
+ } catch (error) {
18
+ if (error.code === 'credential_store_unavailable') storage = 'project-env-fallback';
19
+ // A newly verified login may repair an invalid OS record, but must not
20
+ // downgrade it to plaintext. Save/readback failures below also stay fatal.
21
+ else if (error.code !== 'credential_store_invalid') throw error;
22
+ }
23
+ if (storage === 'os-credential-store' && connection.source !== 'os-credential-store') {
24
+ store.save({ ...connection, apiBaseUrl });
25
+ }
26
+ updateDotEnvFile(path.join(workspaceDir, '.env.joripspace'), {
27
+ JORIPSPACE_API_BASE_URL: apiBaseUrl,
28
+ JORIPSPACE_API_TOKEN: storage === 'project-env-fallback' ? connection.apiToken : null,
29
+ JORIPSPACE_CONNECT_TOKEN: null,
30
+ JORIPSPACE_ACCOUNT_ID: connection.accountId,
31
+ JORIPSPACE_CONNECTION_SOURCE: storage,
32
+ });
33
+ return storage;
34
+ }
35
+
36
+ module.exports = { persistProjectConnection };
@@ -11,8 +11,8 @@ function storeError(code = 'credential_store_unavailable') {
11
11
  'OS 보안 저장소의 JoripSpace 연결 정보가 올바르지 않습니다. login --code로 다시 연결하세요.'
12
12
  )
13
13
  : message(
14
- 'The OS credential store is unavailable. Check Windows Credential Manager, macOS Keychain, or Linux Secret Service. No plaintext fallback is used. For automation, provide JORIPSPACE_API_TOKEN and its API URL through environment variables.',
15
- 'OS 보안 저장소를 사용할 수 없습니다. Windows 자격 증명 관리자, macOS Keychain 또는 Linux Secret Service를 확인하세요. 평문 파일에는 저장하지 않습니다. 자동화에서는 JORIPSPACE_API_TOKEN과 해당 API URL을 환경 변수로 제공할 수 있습니다.'
14
+ 'The OS credential store could not complete this operation. Check Windows Credential Manager, macOS Keychain, or Linux Secret Service. Login uses .env.joripspace only when the store is unavailable before writing; failed writes or verification are not bypassed.',
15
+ 'OS 보안 저장소에서 작업을 완료하지 못했습니다. Windows 자격 증명 관리자, macOS Keychain 또는 Linux Secret Service를 확인하세요. 로그인은 쓰기 전 저장소 사용 불가가 확인된 경우에만 .env.joripspace를 사용하며, 쓰기나 검증 실패를 우회하지 않습니다.'
16
16
  )
17
17
  );
18
18
  error.code = code;
@@ -1,6 +1,7 @@
1
1
  const fs = require('node:fs');
2
2
  const path = require('node:path');
3
3
  const { safeProjectRelativePath } = require('./project-paths');
4
+ const { projectFileEntries } = require('./checkpoint-client');
4
5
 
5
6
  const INLINE_FILE_LIMIT = 16_000;
6
7
  const INLINE_TOTAL_LIMIT = 64_000;
@@ -166,17 +167,10 @@ function findUnresolvedPackageImports(files) {
166
167
  return [...unresolved].sort();
167
168
  }
168
169
 
169
- function walkFiles(root, base = path.resolve(root)) {
170
- const files = [];
171
- for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
172
- const fullPath = path.join(root, entry.name);
173
- const relative = toPosix(path.relative(base, fullPath));
174
- if (entry.isDirectory() && IGNORED_DIRS.has(entry.name.toLowerCase())) continue;
175
- if (isProtectedProjectPath(relative)) continue;
176
- if (entry.isDirectory()) files.push(...walkFiles(fullPath, base));
177
- else if (entry.isFile()) files.push(resolveDeploySourceFile(fullPath, base));
178
- }
179
- return files;
170
+ function walkFiles(root) {
171
+ return projectFileEntries(root)
172
+ .filter(({ relative }) => !isProtectedProjectPath(relative))
173
+ .map(({ path: filePath }) => resolveDeploySourceFile(filePath, root));
180
174
  }
181
175
 
182
176
  function assertDeployableProjectPath(value) {
package/lib/help.js CHANGED
@@ -53,6 +53,8 @@ Usage:
53
53
  joripspace secrets --project PROJECT
54
54
  joripspace secret list --project PROJECT
55
55
  joripspace secret generate --project PROJECT --name SESSION_SECRET
56
+ joripspace secret set --project PROJECT --name API_KEY --value-stdin
57
+ joripspace secret update --project PROJECT --name API_KEY --value-stdin
56
58
  joripspace crons --project PROJECT
57
59
  joripspace cron create --project PROJECT --schedule "0 * * * *" --path /jobs/hourly
58
60
  joripspace cron run --project PROJECT --cron-id CRON_ID
@@ -84,11 +86,12 @@ Login:
84
86
  Open https://joripspace.com/connect/ and ask the user to paste the displayed connection code.
85
87
  New logins store tokens in Windows Credential Manager, macOS Keychain, or Linux Secret Service.
86
88
  Saved connections are reused in other project folders on the same OS user account.
87
- PROJECT_FOLDER/.env.joripspace stores only the API URL and account reference for new logins.
89
+ New logins prefer the OS credential store. If unavailable before writing, the token is saved
90
+ in the ignored PROJECT_FOLDER/.env.joripspace instead. logout removes the saved token.
88
91
  Existing token-bearing .env.joripspace files and process environment tokens remain supported.
89
92
  Run login in an existing connected folder to move its token to the OS store without a new code.
90
93
  The CLI searches parent folders and never reads an ordinary application .env for authentication.
91
- If the OS store is unavailable or locked, new logins fail without a plaintext fallback.
94
+ Failed OS writes or readback verification stop login without creating a file fallback.
92
95
  A successful connection also logs you in; no separate login step is required.
93
96
  logout removes the current account's OS credential and the current folder's legacy credentials.
94
97
  It does not revoke server tokens or remove credentials in other legacy project folders.
@@ -106,9 +109,11 @@ Project creation:
106
109
  Security:
107
110
  CLI tokens are for project lookup, workspace linking, project DB/storage work, server deployment, usage, and logs.
108
111
  Project checkpoints can be saved, restored locally, and deployed independently with the checkpoint command.
109
- Deployment rollback, value-blind Secret generation/listing, crons, domains, and mail status/test are available.
112
+ Deployment rollback, Secret generation/listing and stdin registration/replacement, crons, domains, and mail status/test are available.
110
113
  Manage custom domains with the domain command.
111
- Manage members, billing, API tokens, external Secret values, webhooks, and project deletion in the web UI.
114
+ Use secret set or secret update --name NAME --value-stdin for Secret registration/replacement.
115
+ Secret values are never returned. Secret deletion remains in the project web Secret page.
116
+ Manage members, billing, API tokens, webhooks, and project deletion in the web UI.
112
117
 
113
118
  ${message('Language', '언어')}:
114
119
  ${message('Messages follow the OS default locale: Korean or English. Unsupported locales use English.', '안내는 OS 기본 로캘에 따라 한국어 또는 영어로 표시합니다. 미지원 로캘은 영어를 사용합니다.')}
@@ -9,8 +9,10 @@ const {
9
9
  safeProjectRelativePath,
10
10
  } = require('./project-paths');
11
11
  const { ensureProjectEnvIgnored } = require('./project-env');
12
+ const { createSecretCommands } = require('./secret-commands');
12
13
 
13
14
  function createRemoteCommands(deps) {
15
+ const secrets = createSecretCommands(deps);
14
16
  async function knowledge(rest, flags) {
15
17
  const subcommand = rest[0] || 'search';
16
18
  if (subcommand !== 'search') throw new Error('knowledge command requires: search');
@@ -140,47 +142,6 @@ function createRemoteCommands(deps) {
140
142
  }
141
143
  }
142
144
 
143
- async function secrets(rest, flags) {
144
- const subcommand = rest[0] || 'list';
145
- if (subcommand === 'list') return listSecrets(flags);
146
- if (subcommand === 'generate') return generateSecret(flags);
147
- if (subcommand === 'set' || subcommand === 'delete')
148
- return deps.webOnlyCommand(message('External secret value management', '외부 시크릿 값 관리'));
149
- throw new Error('secret command requires: list or generate');
150
- }
151
-
152
- async function generateSecret(flags) {
153
- const project = deps.requireProjectId(flags);
154
- const name = deps.stringFlag(flags, 'name');
155
- if (!name) throw new Error('secret generate requires --name');
156
- const body = await deps.apiRequest(
157
- flags,
158
- `/v1/projects/${encodeURIComponent(project)}/secrets/generate`,
159
- {
160
- method: 'POST',
161
- ...deps.projectAuth(flags),
162
- body: { name },
163
- }
164
- );
165
- deps.output(flags, body, (value) => {
166
- console.log(`Secret: ${value.name || name}`);
167
- console.log(`Status: ${value.status || (value.generated ? 'generated' : 'preserved')}`);
168
- });
169
- }
170
-
171
- async function listSecrets(flags) {
172
- const project = deps.requireProjectId(flags);
173
- const body = await deps.apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/secrets`, {
174
- method: 'GET',
175
- ...deps.projectAuth(flags),
176
- });
177
- deps.output(flags, body, (value) => {
178
- for (const secret of value.secrets || []) {
179
- console.log(`${secret.name}\tcreated=${secret.created_at}\tupdated=${secret.updated_at}`);
180
- }
181
- });
182
- }
183
-
184
145
  async function crons(rest, flags) {
185
146
  const subcommand = rest[0] || 'list';
186
147
  if (subcommand === 'list') return listCrons(flags);
@@ -402,7 +363,7 @@ function createRemoteCommands(deps) {
402
363
  knowledge,
403
364
  listCrons,
404
365
  listDomains,
405
- listSecrets,
366
+ listSecrets: (flags) => secrets(['list'], flags),
406
367
  mail,
407
368
  pullDeploymentSource,
408
369
  secrets,
@@ -0,0 +1,96 @@
1
+ const { message } = require('./locale');
2
+
3
+ function secretManagementUrl(project) {
4
+ return `https://joripspace.com/projects/${encodeURIComponent(project)}/?tab=secrets`;
5
+ }
6
+
7
+ function createSecretCommands(deps) {
8
+ return async function secrets(rest, flags) {
9
+ const subcommand = rest[0] || 'list';
10
+ if (subcommand === 'delete') {
11
+ return deps.webOnlyCommand(message('Secret deletion', '비밀 키 삭제'));
12
+ }
13
+ if (!['list', 'generate', 'set', 'update'].includes(subcommand)) {
14
+ throw new Error('secret command requires: list, generate, set, or update');
15
+ }
16
+ const project = deps.requireProjectId(flags);
17
+ const url = secretManagementUrl(project);
18
+ const auth = deps.projectAuth(flags);
19
+ const endpoint = `/v1/projects/${encodeURIComponent(project)}/secrets`;
20
+ let result;
21
+ if (subcommand === 'list') {
22
+ result = await deps.apiRequest(flags, endpoint, { method: 'GET', ...auth });
23
+ } else {
24
+ const name = deps.stringFlag(flags, 'name').toUpperCase();
25
+ if (!name || !/^[_A-Z][_A-Z0-9]{0,127}$/.test(name)) {
26
+ throw new Error('secret requires --name matching [_A-Z][_A-Z0-9]* (at most 128 characters)');
27
+ }
28
+ if (subcommand === 'generate') {
29
+ result = await deps.apiRequest(flags, `${endpoint}/generate`, {
30
+ method: 'POST', ...auth, body: { name },
31
+ });
32
+ } else {
33
+ if (!deps.booleanFlag(flags, 'value-stdin') || flags.value !== undefined) {
34
+ throw new Error(message(
35
+ 'Use --value-stdin to supply the secret through standard input, never a command-line value.',
36
+ '--value-stdin으로 비밀 키 값을 표준 입력으로 전달하세요. 명령 인자에는 값을 넣지 마세요.'
37
+ ));
38
+ }
39
+ const value = await readSecretValue(process.stdin);
40
+ try {
41
+ await deps.apiRequest(flags, endpoint, { method: 'POST', ...auth, body: { name, value } });
42
+ } catch (cause) {
43
+ // An upstream failure may echo all or part of a value. Report only safe metadata.
44
+ const error = new Error(message('The secret could not be saved.', '비밀 키를 저장하지 못했습니다.'));
45
+ error.code = 'secret_set_failed';
46
+ error.details = {
47
+ name, secret_management_url: url,
48
+ ...(Number.isInteger(cause?.status) ? { http_status: cause.status } : {}),
49
+ };
50
+ throw error;
51
+ }
52
+ result = { status: 'success', project_id: project, name };
53
+ }
54
+ }
55
+ result = { ...result, secret_management_url: url };
56
+ deps.output(flags, result, (body) => {
57
+ if (subcommand === 'list') {
58
+ for (const secret of body.secrets || []) {
59
+ console.log(`${secret.name}\tcreated=${secret.created_at}\tupdated=${secret.updated_at}`);
60
+ }
61
+ } else {
62
+ console.log(`Secret: ${body.name}`);
63
+ console.log(`Status: ${body.status || (body.created || body.generated ? 'generated' : 'preserved')}`);
64
+ }
65
+ console.log(`${message('Secret management', '비밀 키 관리')}: ${url}`);
66
+ });
67
+ };
68
+ }
69
+
70
+ async function readSecretValue(input) {
71
+ if (input.isTTY) {
72
+ throw new Error(message('Pipe the secret value to standard input.', '비밀 키 값을 표준 입력으로 전달하세요.'));
73
+ }
74
+ const chunks = [];
75
+ let size = 0;
76
+ try {
77
+ for await (const chunk of input) {
78
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
79
+ chunks.push(bytes);
80
+ size += bytes.length;
81
+ if (size > 5120) throw new Error('invalid size');
82
+ }
83
+ if (!size) throw new Error('empty value');
84
+ // Preserve whitespace and newlines, including multi-line provider keys.
85
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(Buffer.concat(chunks));
86
+ } catch {
87
+ throw new Error(message(
88
+ 'Secret input must contain 1-5120 UTF-8 bytes.',
89
+ '비밀 키 값은 UTF-8 기준 1~5120바이트여야 합니다.'
90
+ ));
91
+ } finally {
92
+ for (const chunk of chunks) chunk.fill(0);
93
+ }
94
+ }
95
+
96
+ module.exports = { createSecretCommands, secretManagementUrl };
package/lib/start.js CHANGED
@@ -1,6 +1,7 @@
1
1
  const fs = require('node:fs');
2
2
  const path = require('node:path');
3
3
  const { projectAgentsFile, JORIPSPACE_CLI_GUIDE } = require('../vendor/core/onboarding.cjs');
4
+ const { secretManagementUrl } = require('./secret-commands');
4
5
  const crypto = require('node:crypto');
5
6
  const { spawnSync } = require('node:child_process');
6
7
  const { ensureProjectEnvIgnored, removeGitignoreEntries } = require('./project-env');
@@ -1480,6 +1481,7 @@ function createStartOnboarding(executable, cwd, project, connected = false, apiB
1480
1481
  return {
1481
1482
  schema_version: 1,
1482
1483
  instructions: JORIPSPACE_CLI_GUIDE,
1484
+ secret_management_url: secretManagementUrl(project),
1483
1485
  read_files: connected ? [path.join(cwd, 'AGENTS.md'), path.join(cwd, 'CLAUDE.md')] : [],
1484
1486
  invocation,
1485
1487
  commands: {
@@ -4,6 +4,8 @@ const os = require('node:os');
4
4
  const path = require('node:path');
5
5
  const { spawnSync } = require('node:child_process');
6
6
  const zlib = require('node:zlib');
7
+ const { redactAuthError } = require('./auth-redaction');
8
+ const responseAuthSecrets = new WeakMap();
7
9
  const {
8
10
  assertNonOverlappingFilePlan,
9
11
  resolveProjectFileTarget,
@@ -122,12 +124,7 @@ function createTemplateCommands(deps) {
122
124
  { method: 'GET', headers }
123
125
  );
124
126
  if (!response.ok) {
125
- const text = await response.text();
126
- let parsed = {};
127
- try {
128
- parsed = text ? JSON.parse(text) : {};
129
- } catch {}
130
- throw new Error(parsed?.error?.message || parsed?.message || text || `HTTP ${response.status}`);
127
+ throw await fetchError(response);
131
128
  }
132
129
  const template = parseArchive(Buffer.from(await response.arrayBuffer()));
133
130
  writeFiles(targetDir, template.files, deps.booleanFlag(flags, 'force'));
@@ -240,14 +237,21 @@ async function downloadBundleGrant(apiUrl, headers, templateSlug, project) {
240
237
  }
241
238
 
242
239
  async function timedFetch(url, options, timeoutMs = 25_000) {
240
+ const authorization = new Headers(options.headers).get('authorization');
241
+ const secrets = authorization ? [authorization, authorization.replace(/^Bearer\s+/i, '')] : [];
243
242
  const controller = new AbortController();
244
243
  const timer = setTimeout(() => controller.abort(), timeoutMs);
245
244
  try {
246
- return await fetch(url, { ...options, signal: controller.signal });
245
+ const response = await fetch(url, {
246
+ ...options, signal: controller.signal,
247
+ ...(authorization ? { redirect: 'error' } : {}),
248
+ });
249
+ responseAuthSecrets.set(response, secrets);
250
+ return response;
247
251
  } catch (error) {
248
252
  if (error?.name === 'AbortError')
249
253
  throw new Error(`template request timed out after ${Math.round(timeoutMs / 1000)} seconds`);
250
- throw error;
254
+ throw new Error(redactAuthError(error instanceof Error ? error.message : String(error), secrets));
251
255
  } finally {
252
256
  clearTimeout(timer);
253
257
  }
@@ -699,7 +703,9 @@ async function fetchError(response) {
699
703
  try {
700
704
  parsed = text ? JSON.parse(text) : {};
701
705
  } catch {}
702
- return new Error(parsed?.error?.message || parsed?.message || text || `HTTP ${response.status}`);
706
+ const secrets = responseAuthSecrets.get(response) || [];
707
+ const safe = redactAuthError(parsed, secrets);
708
+ return new Error(safe?.error?.message || safe?.message || redactAuthError(text, secrets) || `HTTP ${response.status}`);
703
709
  }
704
710
 
705
711
  function parseArchive(archive) {