@joripspace/cli 0.5.6 → 0.5.7

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/lib/help.js CHANGED
@@ -1,18 +1,22 @@
1
1
  const DEFAULT_API_URL = 'https://api.joripspace.com';
2
+ const { message } = require('./locale');
2
3
 
3
4
  function printHelp() {
4
5
  console.log(`JoripSpace CLI
5
6
 
6
7
  Usage:
7
8
  joripspace login
8
- joripspace login --code "복사한_연결_코드" --cwd PROJECT_FOLDER
9
- joripspace login --connect-token "복사한_연결_토큰" --cwd PROJECT_FOLDER
9
+ joripspace login --code "CONNECTION_CODE" --cwd PROJECT_FOLDER
10
+ joripspace login --connect-token "CONNECTION_TOKEN" --cwd PROJECT_FOLDER
11
+ joripspace logout
10
12
  joripspace me
11
13
  joripspace projects
14
+ joripspace create --name NAME
15
+ joripspace create --name NAME --agree-noncommercial --agree-billing --agree-retention --json
12
16
  joripspace link --project PROJECT --cwd PATH
13
17
  joripspace start PROJECT --cwd PATH --json
14
18
  joripspace github prepare --project PROJECT --cwd PATH [--entrypoint worker.js]
15
- joripspace knowledge search --query "사용자 요청"
19
+ joripspace knowledge search --query "USER_REQUEST"
16
20
  joripspace realtime-v2 docs
17
21
  joripspace realtime-v2 status --project PROJECT
18
22
  joripspace realtime-v2 activate --project PROJECT
@@ -26,22 +30,22 @@ Usage:
26
30
  joripspace storage put --project PROJECT --token TOKEN --key uploads/hello.txt --text "hello"
27
31
  joripspace storage get --project PROJECT --token TOKEN --key uploads/hello.txt --out hello.txt
28
32
  joripspace storage delete --project PROJECT --token TOKEN --key uploads/hello.txt
29
- joripspace deploy --project PROJECT --token TOKEN --source worker.js --label "첫 배포"
33
+ joripspace deploy --project PROJECT --token TOKEN --source worker.js --label "First deployment"
30
34
  joripspace templates
31
35
  joripspace template list --project PROJECT --cursor CURSOR
32
- joripspace deploy-template --project PROJECT --token TOKEN --template basic-worker --label "기본 템플릿 배포" --var MESSAGE=Hello
36
+ joripspace deploy-template --project PROJECT --token TOKEN --template basic-worker --label "Deploy basic template" --var MESSAGE=Hello
33
37
  joripspace install-template --project PROJECT --token TOKEN --template TEMPLATE --dir . --deploy
34
38
  joripspace install-template --project PROJECT --token TOKEN --template TEMPLATE --dir . --files-only
35
39
  joripspace template pull --project PROJECT --token TOKEN --dir . [--yes]
36
40
  joripspace get --project PROJECT --token TOKEN
37
- joripspace report --project PROJECT --category bug --summary "문제 요약" [--details TEXT] [--expected TEXT] [--actual TEXT] [--error-code CODE]
41
+ joripspace report --project PROJECT --category bug --summary "ISSUE_SUMMARY" [--details TEXT] [--expected TEXT] [--actual TEXT] [--error-code CODE]
38
42
  joripspace deployments --project PROJECT --token TOKEN [--include-failure-details] [--json]
39
43
  joripspace deployment get --project PROJECT --deployment DEPLOYMENT_ID --json
40
44
  joripspace deployment pull --project PROJECT --deployment DEPLOYMENT_ID --cwd PATH [--force]
41
- joripspace checkpoint save --project PROJECT --token TOKEN --label "작업 완료"
45
+ joripspace checkpoint save --project PROJECT --token TOKEN --label "Work completed"
42
46
  joripspace checkpoint list --project PROJECT --token TOKEN --limit 20
43
47
  joripspace checkpoint get --project PROJECT --token TOKEN --checkpoint CHECKPOINT_ID
44
- joripspace checkpoint update --project PROJECT --token TOKEN --checkpoint CHECKPOINT_ID --label "이름"
48
+ joripspace checkpoint update --project PROJECT --token TOKEN --checkpoint CHECKPOINT_ID --label "Checkpoint name"
45
49
  joripspace checkpoint restore --project PROJECT --token TOKEN --checkpoint CHECKPOINT_ID
46
50
  joripspace checkpoint deploy --project PROJECT --token TOKEN --checkpoint CHECKPOINT_ID
47
51
  joripspace checkpoint delete --project PROJECT --token TOKEN --checkpoint CHECKPOINT_ID --yes
@@ -72,13 +76,32 @@ Environment:
72
76
  JORIPSPACE_CONNECT_TOKEN Used when no API token is provided
73
77
 
74
78
  Login:
75
- Run "joripspace login", open the shown link in a logged-in browser, approve connection,
76
- then exchange the displayed 5-minute connection code with --code.
79
+ Run "joripspace login" in a terminal, approve the browser connection,
80
+ then paste the displayed 5-minute connection code at the prompt.
81
+ Agents use --json and pass the connection code with --code; they are never prompted.
77
82
  Existing connection tokens can still be saved with --connect-token.
78
83
  If a token is missing, do not inspect cookies, browser storage, or profile pages to find it.
79
84
  Open https://joripspace.com/connect/ and ask the user to paste the displayed connection code.
80
- The token and matching API URL are stored only in PROJECT_FOLDER/.env.joripspace. The CLI searches
81
- parent folders for this file. It never reads a generic application .env file for authentication.
85
+ New logins store tokens in Windows Credential Manager, macOS Keychain, or Linux Secret Service.
86
+ 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.
88
+ Existing token-bearing .env.joripspace files and process environment tokens remain supported.
89
+ Run login in an existing connected folder to move its token to the OS store without a new code.
90
+ 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.
92
+ A successful connection also logs you in; no separate login step is required.
93
+ logout removes the current account's OS credential and the current folder's legacy credentials.
94
+ It does not revoke server tokens or remove credentials in other legacy project folders.
95
+ Environment/command-line tokens must be unset by the caller before logout.
96
+
97
+ Project creation:
98
+ create only creates a Free project; start only connects to an existing project.
99
+ Login is verified with the server before any agreements are shown. Run login first if required.
100
+ Names follow the same 3-50 character format, reserved-name, brand, and duplicate checks as the web.
101
+ Terminals ask for each required agreement. JSON/agent calls return all agreement texts first.
102
+ Agents must translate the full agreements into the user's language and get explicit consent
103
+ before passing --agree-noncommercial, --agree-billing, and --agree-retention.
104
+ --yes does not accept these agreements. Creation does not link or modify local project source.
82
105
 
83
106
  Security:
84
107
  CLI tokens are for project lookup, workspace linking, project DB/storage work, server deployment, usage, and logs.
@@ -87,10 +110,14 @@ Security:
87
110
  Manage custom domains with the domain command.
88
111
  Manage members, billing, API tokens, external Secret values, webhooks, and project deletion in the web UI.
89
112
 
113
+ ${message('Language', '언어')}:
114
+ ${message('Messages follow the OS default locale: Korean or English. Unsupported locales use English.', '안내는 OS 기본 로캘에 따라 한국어 또는 영어로 표시합니다. 미지원 로캘은 영어를 사용합니다.')}
115
+ ${message("Agents should explain results in the user's conversation language.", '에이전트는 사용자의 대화 언어로 결과를 설명해야 합니다.')}
116
+
90
117
  Global flags:
91
118
  --api-url URL
92
119
  --cwd PATH
93
- --json
120
+ --json Machine-readable output; never opens a browser or prompts for input.
94
121
  --help
95
122
  `);
96
123
  }
@@ -99,7 +126,7 @@ function printDeployHelp() {
99
126
  console.log(`JoripSpace deploy
100
127
 
101
128
  Usage:
102
- joripspace deploy --project PROJECT --token TOKEN --source worker.js --label "첫 배포"
129
+ joripspace deploy --project PROJECT --token TOKEN --source worker.js --label "First deployment"
103
130
 
104
131
  Options:
105
132
  --source PATH Deploy one source file. Entrypoint defaults to the file basename.
@@ -115,7 +142,7 @@ function printDeployTemplateHelp() {
115
142
 
116
143
  Usage:
117
144
  joripspace templates
118
- joripspace deploy-template --project PROJECT --token TOKEN --template basic-worker --label "메시지 변경" --var MESSAGE=Hello
145
+ joripspace deploy-template --project PROJECT --token TOKEN --template basic-worker --label "Update message" --var MESSAGE=Hello
119
146
 
120
147
  Options:
121
148
  --template ID Template id from the templates command.
package/lib/locale.js ADDED
@@ -0,0 +1,35 @@
1
+ function detectLanguage(locale) {
2
+ try {
3
+ const selected = locale === undefined ? Intl.DateTimeFormat().resolvedOptions().locale : locale;
4
+ return /^ko(?:[-_]|$)/i.test(String(selected || '')) ? 'ko' : 'en';
5
+ } catch {
6
+ return 'en';
7
+ }
8
+ }
9
+
10
+ const language = detectLanguage();
11
+
12
+ function message(english, korean) {
13
+ return language === 'ko' && korean ? korean : english;
14
+ }
15
+
16
+ const NAME_POLICY_MESSAGES = {
17
+ '조립스페이스 브랜드나 운영 주체로 오해될 수 있는 이름은 사용할 수 없습니다.':
18
+ 'This name could be mistaken for the JoripSpace brand or operator and cannot be used.',
19
+ '서비스 운영에 쓰는 예약어라서 프로젝트 이름으로 사용할 수 없습니다.':
20
+ 'This name is reserved for service operations and cannot be used as a project name.',
21
+ '로그인, 결제, 보안, 고객지원으로 오해될 수 있는 단어는 사칭 위험 때문에 사용할 수 없습니다.':
22
+ 'Names that could impersonate login, billing, security, or customer support cannot be used.',
23
+ '다른 회사나 서비스 이름을 포함하면 공식 서비스처럼 보일 수 있어 사용할 수 없습니다.':
24
+ 'Names containing another company or service brand cannot be used because they could appear official.',
25
+ '불법 또는 유해한 목적으로 오해될 수 있는 단어는 사용할 수 없습니다.':
26
+ 'Names that could imply illegal or harmful purposes cannot be used.',
27
+ '불법, 성인, 도박, 약물, 무기 관련 단어는 사용할 수 없습니다.':
28
+ 'Names related to illegal activities, adult content, gambling, drugs, or weapons cannot be used.',
29
+ };
30
+
31
+ function projectNameMessage(original) {
32
+ return message(NAME_POLICY_MESSAGES[original] || 'This project name is not allowed.', original);
33
+ }
34
+
35
+ module.exports = { detectLanguage, language, message, projectNameMessage };
package/lib/mcp-config.js CHANGED
@@ -588,7 +588,7 @@ function findDuplicateJsonProperty(node, currentPath = []) {
588
588
 
589
589
  function parseTomlConfigSource(source) {
590
590
  try {
591
- const value = parseToml(String(source || ''));
591
+ const value = normalizeTomlTables(parseToml(String(source || '')));
592
592
  if (!isPlainObject(value)) throw new Error('root is not a table');
593
593
  return { ok: true, value };
594
594
  } catch {
@@ -601,6 +601,12 @@ function parseTomlConfigSource(source) {
601
601
  }
602
602
  }
603
603
 
604
+ function normalizeTomlTables(value) {
605
+ if (Array.isArray(value)) return value.map(normalizeTomlTables);
606
+ if (!isPlainObject(value)) return value;
607
+ return Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, normalizeTomlTables(nested)]));
608
+ }
609
+
604
610
  function removeTomlTableTree(source, targetPath) {
605
611
  const lines = String(source || '').match(/[^\n]*\n|[^\n]+$/g) || [];
606
612
  const kept = [];
@@ -0,0 +1,116 @@
1
+ // Matches packages/core/src/validation.ts; checked by scripts/check-cli-project-create.mjs.
2
+ const PROJECT_NAME_RULES = [
3
+ {
4
+ mode: 'contains',
5
+ terms: ['joripspace', 'jspace', 'cosmosfarm'],
6
+ message: '조립스페이스 브랜드나 운영 주체로 오해될 수 있는 이름은 사용할 수 없습니다.',
7
+ },
8
+ {
9
+ mode: 'exact',
10
+ terms: [
11
+ 'www',
12
+ 'api',
13
+ 'mcp',
14
+ 'cli',
15
+ 'app',
16
+ 'admin',
17
+ 'administrator',
18
+ 'root',
19
+ 'system',
20
+ 'console',
21
+ 'dashboard',
22
+ 'static',
23
+ 'assets',
24
+ 'cdn',
25
+ 'mail',
26
+ 'smtp',
27
+ 'email',
28
+ 'webhook',
29
+ 'worker',
30
+ 'server',
31
+ 'db',
32
+ 'database',
33
+ 'storage',
34
+ ],
35
+ message: '서비스 운영에 쓰는 예약어라서 프로젝트 이름으로 사용할 수 없습니다.',
36
+ },
37
+ {
38
+ mode: 'contains',
39
+ terms: [
40
+ 'login',
41
+ 'logout',
42
+ 'signup',
43
+ 'register',
44
+ 'auth',
45
+ 'verify',
46
+ 'password',
47
+ 'token',
48
+ 'otp',
49
+ 'cert',
50
+ 'account',
51
+ 'billing',
52
+ 'payment',
53
+ 'support',
54
+ 'official',
55
+ 'security',
56
+ 'bank',
57
+ 'card',
58
+ ],
59
+ message: '로그인, 결제, 보안, 고객지원으로 오해될 수 있는 단어는 사칭 위험 때문에 사용할 수 없습니다.',
60
+ },
61
+ {
62
+ mode: 'contains',
63
+ terms: [
64
+ 'naver',
65
+ 'kakao',
66
+ 'google',
67
+ 'apple',
68
+ 'microsoft',
69
+ 'openai',
70
+ 'cloudflare',
71
+ 'paypal',
72
+ 'stripe',
73
+ 'nicepay',
74
+ 'solapi',
75
+ 'claude',
76
+ 'cursor',
77
+ 'anthropic',
78
+ ],
79
+ message: '다른 회사나 서비스 이름을 포함하면 공식 서비스처럼 보일 수 있어 사용할 수 없습니다.',
80
+ },
81
+ {
82
+ mode: 'contains',
83
+ terms: ['phishing', 'scam', 'fraud', 'malware', 'virus', 'ransomware', 'exploit', 'spam'],
84
+ message: '불법 또는 유해한 목적으로 오해될 수 있는 단어는 사용할 수 없습니다.',
85
+ },
86
+ {
87
+ mode: 'token',
88
+ terms: ['hack', 'crack', 'adult', 'porn', 'casino', 'gambling', 'drug', 'weapon'],
89
+ message: '불법, 성인, 도박, 약물, 무기 관련 단어는 사용할 수 없습니다.',
90
+ },
91
+ ];
92
+
93
+ const PROJECT_CREATE_AGREEMENTS = [
94
+ {
95
+ id: 'free_project_noncommercial_agreement',
96
+ flag: 'agree-noncommercial',
97
+ text: '무료 프로젝트는 개인 및 비상업적 용도로만 이용할 수 있음에 동의합니다.',
98
+ text_en: 'I agree that free projects may only be used for personal and non-commercial purposes.',
99
+ },
100
+ {
101
+ id: 'billing_agreement',
102
+ flag: 'agree-billing',
103
+ text: '요금제 제공량을 초과하면 자동으로 추가 결제되지 않고 관련 기능이 제한되며, 종량제는 직접 활성화한 경우에만 적용됨에 동의합니다.',
104
+ text_en:
105
+ "I agree that exceeding the plan's included allowances restricts the relevant features without automatic additional charges, and usage-based billing applies only when I explicitly enable it.",
106
+ },
107
+ {
108
+ id: 'free_project_retention_agreement',
109
+ flag: 'agree-retention',
110
+ text: '30일 이상 조립스페이스에 로그인하지 않은 무료 프로젝트는 사전 안내 후 삭제될 수 있으며, 삭제된 데이터는 복구되지 않을 수 있음에 동의합니다.',
111
+ text_en:
112
+ 'I agree that free projects may be deleted after advance notice if I do not log in to JoripSpace for 30 days or more, and deleted data may not be recoverable.',
113
+ },
114
+ ];
115
+
116
+ module.exports = { PROJECT_NAME_RULES, PROJECT_CREATE_AGREEMENTS };
@@ -0,0 +1,203 @@
1
+ const { message, projectNameMessage } = require('./locale');
2
+ const readline = require('node:readline/promises');
3
+ const { PROJECT_NAME_RULES, PROJECT_CREATE_AGREEMENTS } = require('./project-create-policy');
4
+
5
+ function normalizeProjectName(value) {
6
+ const name = String(value || '')
7
+ .trim()
8
+ .toLowerCase();
9
+ if (name.length < 3 || name.length > 50 || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(name)) {
10
+ throw createError(
11
+ 'invalid_project_name',
12
+ message(
13
+ 'Project names must contain 3-50 lowercase letters, digits, or hyphens, and start and end with a letter or digit.',
14
+ '프로젝트 이름은 영문 소문자, 숫자, 하이픈(-)만 사용해 3-50자로 입력해주세요.'
15
+ )
16
+ );
17
+ }
18
+ const tokens = name.split('-').filter(Boolean);
19
+ for (const rule of PROJECT_NAME_RULES) {
20
+ if (
21
+ rule.terms.some((term) =>
22
+ rule.mode === 'contains'
23
+ ? name.includes(term)
24
+ : rule.mode === 'token'
25
+ ? tokens.includes(term)
26
+ : name === term
27
+ )
28
+ ) {
29
+ throw createError('reserved_project_name', projectNameMessage(rule.message));
30
+ }
31
+ }
32
+ return name;
33
+ }
34
+
35
+ function createProjectCommand(deps) {
36
+ return async function createProject(flags) {
37
+ const name = normalizeProjectName(deps.stringFlag(flags, 'name'));
38
+ if (deps.stringFlag(flags, 'plan') && deps.stringFlag(flags, 'plan') !== 'free') {
39
+ throw createError(
40
+ 'free_project_only',
41
+ message('The CLI can create only Free projects.', 'CLI에서는 무료 프로젝트만 생성할 수 있습니다.')
42
+ );
43
+ }
44
+ const connection = deps.resolveConnection(flags);
45
+ if (!connection.apiToken) throw loginRequired(name);
46
+ const auth = {
47
+ apiToken: deps.requireApiToken(flags, connection),
48
+ apiBaseUrl: connection.apiBaseUrl,
49
+ };
50
+ try {
51
+ await deps.apiRequest(flags, '/v1/me/projects', { method: 'GET', ...auth });
52
+ } catch (error) {
53
+ if (error.status === 401) throw loginRequired(name);
54
+ throw error;
55
+ }
56
+ const missing = PROJECT_CREATE_AGREEMENTS.filter(({ flag }) => !explicitAgreement(flags[flag]));
57
+ if (missing.length) {
58
+ if (flags.json || !process.stdin.isTTY || !process.stdout.isTTY) {
59
+ const error = createError(
60
+ 'project_agreements_required',
61
+ message(
62
+ 'Obtain explicit user consent to all three required web agreements, then run the command again.',
63
+ '웹과 동일한 필수 동의 3개를 사용자에게 확인받은 뒤 다시 실행하세요.'
64
+ )
65
+ );
66
+ error.exitCode = 2;
67
+ error.details = {
68
+ name,
69
+ plan: 'free',
70
+ terms_url: 'https://joripspace.com/terms/',
71
+ language: 'en',
72
+ original_language: 'ko',
73
+ agent_instruction:
74
+ "Translate every agreement faithfully into the user's language and ask for explicit consent. Do not infer consent from a request to create a project or set agreement flags automatically.",
75
+ agreements: PROJECT_CREATE_AGREEMENTS.map(({ id, flag, text, text_en }) => ({
76
+ id,
77
+ flag,
78
+ text: text_en,
79
+ original_text: text,
80
+ required: true,
81
+ accepted: explicitAgreement(flags[flag]),
82
+ })),
83
+ next_action: 'show-agreements-and-ask-user; pass-each-agreement-only-after-explicit-consent',
84
+ resume_args: [
85
+ 'create',
86
+ '--name',
87
+ name,
88
+ ...PROJECT_CREATE_AGREEMENTS.map(({ flag }) => `--${flag}`),
89
+ '--json',
90
+ ],
91
+ };
92
+ throw error;
93
+ }
94
+ await askAgreements(missing);
95
+ }
96
+ let result;
97
+ try {
98
+ result = await deps.apiRequest(flags, '/v1/projects', {
99
+ method: 'POST',
100
+ ...auth,
101
+ timeoutMs: null,
102
+ body: { name, ...Object.fromEntries(PROJECT_CREATE_AGREEMENTS.map(({ id }) => [id, true])) },
103
+ });
104
+ } catch (error) {
105
+ if (error.code === 'request_failed' || error.code === 'request_timeout' || error.status >= 500) {
106
+ error.details = {
107
+ ...error.details,
108
+ name,
109
+ next_action: 'list-projects-and-check-name-before-retrying-create',
110
+ };
111
+ }
112
+ throw error;
113
+ }
114
+ deps.output(flags, result, (value) => {
115
+ console.log(
116
+ message(
117
+ `Project created: ${value.project_slug || value.project_id}`,
118
+ `프로젝트 생성 완료: ${value.project_slug || value.project_id}`
119
+ )
120
+ );
121
+ if (value.default_url)
122
+ console.log(message(`Project URL: ${value.default_url}`, `프로젝트 주소: ${value.default_url}`));
123
+ console.log(
124
+ message(
125
+ 'Run start to connect this project to a local folder.',
126
+ '이 프로젝트를 로컬 폴더에 연결하려면 start를 실행하세요.'
127
+ )
128
+ );
129
+ });
130
+ };
131
+ }
132
+
133
+ function loginRequired(name) {
134
+ const error = createError(
135
+ 'connection_required',
136
+ message(
137
+ 'Run joripspace login before creating a project.',
138
+ '프로젝트를 생성하려면 먼저 joripspace login으로 로그인하세요.'
139
+ )
140
+ );
141
+ error.exitCode = 2;
142
+ error.details = {
143
+ connect_url: 'https://joripspace.com/connect/',
144
+ login_args: ['login', '--json'],
145
+ resume_args: ['create', '--name', name, '--json'],
146
+ next_action: 'login-then-retry-create; obtain-explicit-agreement-after-login',
147
+ };
148
+ return error;
149
+ }
150
+
151
+ function explicitAgreement(value) {
152
+ return value === true || value === 'true';
153
+ }
154
+
155
+ async function askAgreements(agreements) {
156
+ console.log(
157
+ message(
158
+ 'Required agreements for a free project. Terms: https://joripspace.com/terms/',
159
+ '무료 프로젝트 생성에 필요한 동의입니다. 이용약관: https://joripspace.com/terms/'
160
+ )
161
+ );
162
+ const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
163
+ const cancellation = new AbortController();
164
+ prompt.once('close', () => cancellation.abort());
165
+ try {
166
+ for (const { text, text_en } of agreements) {
167
+ const answer = await prompt.question(
168
+ `${message(text_en, text)}\n${message('Do you agree? [y/N]: ', '동의하십니까? [y/N]: ')}`,
169
+ {
170
+ signal: cancellation.signal,
171
+ }
172
+ );
173
+ if (!['y', 'yes', '예', '네', '동의'].includes(answer.trim().toLowerCase())) {
174
+ throw createError(
175
+ 'project_agreement_declined',
176
+ message(
177
+ 'A required agreement was declined. No project was created.',
178
+ '필수 항목에 동의하지 않아 프로젝트를 생성하지 않았습니다.'
179
+ )
180
+ );
181
+ }
182
+ }
183
+ } catch (error) {
184
+ if (error.code !== 'ABORT_ERR') throw error;
185
+ throw createError(
186
+ 'project_agreement_cancelled',
187
+ message(
188
+ 'Agreement entry was cancelled. No project was created.',
189
+ '동의 입력이 취소되어 프로젝트를 생성하지 않았습니다.'
190
+ )
191
+ );
192
+ } finally {
193
+ prompt.close();
194
+ }
195
+ }
196
+
197
+ function createError(code, message) {
198
+ const error = new Error(message);
199
+ error.code = code;
200
+ return error;
201
+ }
202
+
203
+ module.exports = { createProjectCommand, normalizeProjectName };
@@ -37,9 +37,7 @@ function updateDotEnvFile(filePath, updates) {
37
37
  try {
38
38
  lines = fs.readFileSync(filePath, 'utf8').split(/\r?\n/);
39
39
  } catch {}
40
- const pending = new Map(
41
- Object.entries(updates).filter(([, value]) => value !== undefined && value !== null && value !== '')
42
- );
40
+ const pending = new Map(Object.entries(updates).filter(([, value]) => value !== undefined && value !== ''));
43
41
  const written = new Set();
44
42
  const next = lines
45
43
  .filter((line, index) => index < lines.length - 1 || line !== '')
@@ -49,15 +47,17 @@ function updateDotEnvFile(filePath, updates) {
49
47
  if (written.has(match[1])) return [];
50
48
  const value = pending.get(match[1]);
51
49
  written.add(match[1]);
50
+ if (value === null) return [];
52
51
  return [`${match[1]}=${formatDotEnvValue(value)}`];
53
52
  });
54
53
  for (const [key, value] of pending) {
55
- if (!written.has(key)) next.push(`${key}=${formatDotEnvValue(value)}`);
54
+ if (!written.has(key) && value !== null) next.push(`${key}=${formatDotEnvValue(value)}`);
56
55
  }
57
56
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
58
57
  const temporaryPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
59
58
  fs.writeFileSync(temporaryPath, `${next.join('\n')}\n`, { encoding: 'utf8', mode: 0o600 });
60
- replaceFileAtomically(temporaryPath, filePath);
59
+ // Never move a token-bearing environment file into a persistent .bak copy.
60
+ replaceFileAtomically(temporaryPath, filePath, path.basename(filePath) !== PROJECT_ENV_FILE);
61
61
  if (process.platform !== 'win32') fs.chmodSync(filePath, 0o600);
62
62
  }
63
63
 
@@ -144,11 +144,15 @@ function git(workspaceDir, args) {
144
144
  });
145
145
  }
146
146
 
147
- function replaceFileAtomically(temporaryPath, filePath) {
147
+ function replaceFileAtomically(temporaryPath, filePath, allowBackup = true) {
148
148
  try {
149
149
  fs.renameSync(temporaryPath, filePath);
150
150
  return;
151
151
  } catch (error) {
152
+ if (!allowBackup) {
153
+ fs.rmSync(temporaryPath, { force: true });
154
+ throw error;
155
+ }
152
156
  const backupPath = `${filePath}.bak-${process.pid}-${Date.now()}`;
153
157
  try {
154
158
  if (fs.existsSync(filePath)) fs.renameSync(filePath, backupPath);
@@ -45,17 +45,17 @@ function resolveProjectFileTarget(root, value, errorPrefix = 'unsafe project fil
45
45
  `project path contains a symbolic link or junction: ${parts.slice(0, index + 1).join('/')}`
46
46
  );
47
47
  }
48
+ assertCanonicalProjectPath(rootPath, current, relative);
48
49
  const isTarget = index === parts.length - 1;
49
50
  if ((!isTarget && !stat.isDirectory()) || (isTarget && !stat.isFile())) {
50
51
  blockers.push(parts.slice(0, index + 1).join('/'));
51
52
  break;
52
53
  }
53
- assertContained(rootPath, fs.realpathSync.native(current), relative);
54
54
  }
55
55
  return { blockers, relative, root: rootPath, target };
56
56
  }
57
57
 
58
- function backupAndRemoveProjectPaths(root, relatives, backupRoot) {
58
+ function backupAndRemoveProjectPaths(root, relatives, backupRoot, isProtected = () => false) {
59
59
  const selected = minimalPaths(relatives);
60
60
  const rootPath = realProjectRoot(root);
61
61
  if (!path.isAbsolute(backupRoot)) {
@@ -70,7 +70,18 @@ function backupAndRemoveProjectPaths(root, relatives, backupRoot) {
70
70
  if (!backupStat.isDirectory() || backupStat.isSymbolicLink()) {
71
71
  throw new Error('project backup target is not a safe directory');
72
72
  }
73
+ function inspect(relative) {
74
+ if (isProtected(relative)) throw new Error(`protected local path cannot be replaced: ${relative}`);
75
+ const location = resolveExistingProjectPath(root, relative);
76
+ if (!location) return;
77
+ if (location.stat.isDirectory()) {
78
+ for (const name of fs.readdirSync(location.target)) inspect(`${relative}/${name}`);
79
+ }
80
+ }
81
+ // Check the entire removal plan before copying or deleting its first member.
82
+ selected.forEach(inspect);
73
83
  for (const relative of selected) {
84
+ inspect(relative);
74
85
  const location = resolveExistingProjectPath(root, relative);
75
86
  if (!location) continue;
76
87
  const backup = path.join(backupLocation, ...relative.split('/'));
@@ -156,7 +167,7 @@ function resolveProjectDirectoryTarget(root, value) {
156
167
  );
157
168
  }
158
169
  if (!stat.isDirectory()) throw new Error(`project directory path is blocked by a file: ${relative}`);
159
- assertContained(rootPath, fs.realpathSync.native(current), relative);
170
+ assertCanonicalProjectPath(rootPath, current, relative);
160
171
  }
161
172
  return { relative, root: rootPath, target };
162
173
  }
@@ -175,7 +186,7 @@ function resolveExistingProjectPath(root, value) {
175
186
  `project path contains a symbolic link or junction: ${parts.slice(0, index + 1).join('/')}`
176
187
  );
177
188
  }
178
- assertContained(rootPath, fs.realpathSync.native(current), relative);
189
+ assertCanonicalProjectPath(rootPath, current, relative);
179
190
  if (index < parts.length - 1 && !stat.isDirectory()) return null;
180
191
  if (index === parts.length - 1) return { relative, root: rootPath, stat, target: current };
181
192
  }
@@ -224,6 +235,14 @@ function realProjectRoot(root) {
224
235
  return fs.realpathSync.native(resolved);
225
236
  }
226
237
 
238
+ function assertCanonicalProjectPath(root, target, relative) {
239
+ const canonical = fs.realpathSync.native(target);
240
+ assertContained(root, canonical, relative);
241
+ if (process.platform === 'win32' && canonical.toLowerCase() !== target.toLowerCase()) {
242
+ throw new Error(`project path uses a filesystem alias: ${relative}`);
243
+ }
244
+ }
245
+
227
246
  function assertContained(root, target, relative) {
228
247
  const fromRoot = path.relative(root, target);
229
248
  if (fromRoot === '..' || fromRoot.startsWith(`..${path.sep}`) || path.isAbsolute(fromRoot)) {
@@ -1,3 +1,4 @@
1
+ const { message } = require('./locale');
1
2
  const fs = require('node:fs');
2
3
  const path = require('node:path');
3
4
  const {
@@ -33,7 +34,11 @@ function createRemoteCommands(deps) {
33
34
  const project = deps.requireProjectId(flags);
34
35
  const id = deps.stringFlag(flags, 'deployment') || deps.stringFlag(flags, 'deployment-id');
35
36
  if (!id) throw new Error('deployment get requires --deployment');
36
- const body = await deps.apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/deployments/${encodeURIComponent(id)}`, { method: 'GET', ...deps.projectAuth(flags) });
37
+ const body = await deps.apiRequest(
38
+ flags,
39
+ `/v1/projects/${encodeURIComponent(project)}/deployments/${encodeURIComponent(id)}`,
40
+ { method: 'GET', ...deps.projectAuth(flags) }
41
+ );
37
42
  deps.output(flags, body, (value) => console.log(JSON.stringify(value, null, 2)));
38
43
  return;
39
44
  }
@@ -103,7 +108,12 @@ function createRemoteCommands(deps) {
103
108
  let backedUp = [];
104
109
  if (conflictPaths.size) {
105
110
  backupRoot = createExternalBackupRoot(workspaceDir, 'deployment-pull');
106
- backedUp = backupAndRemoveProjectPaths(workspaceDir, [...conflictPaths], backupRoot);
111
+ backedUp = backupAndRemoveProjectPaths(
112
+ workspaceDir,
113
+ [...conflictPaths],
114
+ backupRoot,
115
+ deps.isProtectedProjectPath
116
+ );
107
117
  }
108
118
  for (const [relative, content] of planned) {
109
119
  const location = resolveProjectFileTarget(workspaceDir, relative);
@@ -134,7 +144,8 @@ function createRemoteCommands(deps) {
134
144
  const subcommand = rest[0] || 'list';
135
145
  if (subcommand === 'list') return listSecrets(flags);
136
146
  if (subcommand === 'generate') return generateSecret(flags);
137
- if (subcommand === 'set' || subcommand === 'delete') return deps.webOnlyCommand('외부 시크릿 값 관리');
147
+ if (subcommand === 'set' || subcommand === 'delete')
148
+ return deps.webOnlyCommand(message('External secret value management', '외부 시크릿 값 관리'));
138
149
  throw new Error('secret command requires: list or generate');
139
150
  }
140
151