promptlike 0.6.3 → 0.8.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.
@@ -27,6 +27,10 @@ exports.importPrompts = importPrompts;
27
27
  exports.getImportedHashes = getImportedHashes;
28
28
  exports.getAccountHeadroom = getAccountHeadroom;
29
29
  exports.listProjects = listProjects;
30
+ exports.toRepoDetail = toRepoDetail;
31
+ exports.listProjectsDetailed = listProjectsDetailed;
32
+ exports.createProject = createProject;
33
+ exports.setProjectVisibility = setProjectVisibility;
30
34
  exports.getPromptById = getPromptById;
31
35
  exports.getPromptHistory = getPromptHistory;
32
36
  exports.rollbackPrompt = rollbackPrompt;
@@ -34,6 +38,7 @@ exports.buildUseEventBody = buildUseEventBody;
34
38
  exports.recordPromptUse = recordPromptUse;
35
39
  exports.getUsageInsights = getUsageInsights;
36
40
  const constants_1 = require("./constants");
41
+ const format_1 = require("./format");
37
42
  const config_1 = require("./config");
38
43
  const NOT_LOGGED_IN = 'Not logged in. Run `ple login` first.';
39
44
  const SESSION_EXPIRED = 'Session expired. Log in again: `ple login`';
@@ -206,8 +211,27 @@ function getAccessTokenOrThrow() {
206
211
  throw new Error(NOT_LOGGED_IN);
207
212
  return config.access_token;
208
213
  }
214
+ /**
215
+ * The auth endpoints are the one place where a malformed (or hostile) response
216
+ * would be written to disk as our session. Check the shape first; the message
217
+ * never echoes the body (it may contain tokens).
218
+ */
219
+ function assertAuthResponse(data) {
220
+ const d = data;
221
+ const ok = typeof d === 'object' &&
222
+ d !== null &&
223
+ typeof d.access_token === 'string' &&
224
+ d.access_token.length > 0 &&
225
+ typeof d.refresh_token === 'string' &&
226
+ d.refresh_token.length > 0 &&
227
+ (d.expires_at === undefined || (typeof d.expires_at === 'number' && Number.isFinite(d.expires_at)));
228
+ if (!ok) {
229
+ throw new ApiError('The server sent an unexpected sign-in response. Update the CLI (npm i -g promptlike) and try again.', 502);
230
+ }
231
+ }
209
232
  /** Persist a fresh auth payload to the local config file. */
210
233
  function persist(data) {
234
+ assertAuthResponse(data);
211
235
  const previous = (0, config_1.readConfig)();
212
236
  const config = {
213
237
  access_token: data.access_token,
@@ -244,12 +268,15 @@ async function refreshSession() {
244
268
  if (err instanceof NetworkError)
245
269
  throw new NetworkError(err.detail, exports.REFRESH_NETWORK_ADVICE);
246
270
  // 503 / 429 / 5xx / tanınmayan yanıt: geçici; yerel oturum korunur.
247
- throw new Error(refreshUnavailableMessage(err instanceof Error ? err.message : String(err)));
271
+ throw new ApiError(refreshUnavailableMessage(err instanceof Error ? err.message : String(err)), 503);
248
272
  }
249
273
  persist(data);
250
274
  }
251
275
  /** Core request helper. See module doc for behavior. */
252
276
  async function apiFetch(path, opts = {}) {
277
+ // An unusable PROMPTLIKE_API_URL is reported BEFORE a request (and a token) exists.
278
+ if (constants_1.API_BASE_URL_ERROR)
279
+ throw new Error(constants_1.API_BASE_URL_ERROR);
253
280
  const { method = 'GET', body, query, auth = true } = opts;
254
281
  const timeoutMs = opts.timeoutMs ?? (method === 'GET' ? exports.READ_TIMEOUT_MS : exports.WRITE_TIMEOUT_MS);
255
282
  const signal = AbortSignal.timeout(timeoutMs);
@@ -270,6 +297,9 @@ async function apiFetch(path, opts = {}) {
270
297
  body: body === undefined ? undefined : JSON.stringify(body),
271
298
  // Süre başlıkla sınırlı değil: gövde okuması da aynı sinyalle kesilir.
272
299
  signal,
300
+ // Never follow redirects automatically: a 307/308 would replay the POST body
301
+ // (email + password on login) at a Location the server chose.
302
+ redirect: 'manual',
273
303
  });
274
304
  }
275
305
  catch (err) {
@@ -277,6 +307,10 @@ async function apiFetch(path, opts = {}) {
277
307
  throw new RequestTimeoutError(timeoutMs, method);
278
308
  throw new NetworkError(err instanceof Error ? err.message : String(err));
279
309
  }
310
+ if (res.status >= 300 && res.status < 400) {
311
+ throw new ApiError(`The server answered with a redirect (HTTP ${res.status}); the CLI does not follow redirects. ` +
312
+ `Check PROMPTLIKE_API_URL (currently ${constants_1.API_BASE_URL}).`, res.status);
313
+ }
280
314
  // Reactive refresh: expired/invalid access token → refresh once, retry once.
281
315
  if (res.status === 401 && auth) {
282
316
  if (opts._retried)
@@ -286,7 +320,8 @@ async function apiFetch(path, opts = {}) {
286
320
  }
287
321
  if (res.status === 429) {
288
322
  const retryAfter = res.headers.get('retry-after');
289
- throw new Error(`Rate limited. Try again${retryAfter ? ` in ${retryAfter}s` : ' in a moment'}.`);
323
+ const wait = retryAfter && /^\d{1,6}$/.test(retryAfter.trim()) ? retryAfter.trim() : undefined;
324
+ throw new ApiError(`Rate limited. Try again${wait ? ` in ${wait}s` : ' in a moment'}.`, 429, 'RATE_LIMITED');
290
325
  }
291
326
  if (!res.ok) {
292
327
  throw await toError(res);
@@ -326,6 +361,20 @@ async function ensureAuthed() {
326
361
  await refreshSession();
327
362
  }
328
363
  }
364
+ /**
365
+ * Titles, descriptions and repo names come from the server (and, for shared
366
+ * repos, from other people). Strip terminal control sequences once, at the
367
+ * boundary, so no command can print an escape code by accident. Prompt BODIES
368
+ * are left alone here: `get`/`copy` must hand them over byte for byte.
369
+ */
370
+ function cleanPrompt(p) {
371
+ return {
372
+ ...p,
373
+ title: typeof p.title === 'string' ? (0, format_1.safeText)(p.title) : '',
374
+ description: typeof p.description === 'string' ? (0, format_1.safeText)(p.description) : p.description,
375
+ project_name: typeof p.project_name === 'string' ? (0, format_1.safeText)(p.project_name) : p.project_name,
376
+ };
377
+ }
329
378
  /** GET /api/prompts — list the user's prompts (optionally by tag / search / project). */
330
379
  async function listPrompts(params = {}) {
331
380
  const res = await apiFetch('/api/prompts', {
@@ -337,7 +386,7 @@ async function listPrompts(params = {}) {
337
386
  projectId: params.projectId,
338
387
  },
339
388
  });
340
- return res.prompts ?? [];
389
+ return (Array.isArray(res.prompts) ? res.prompts : []).map(cleanPrompt);
341
390
  }
342
391
  /**
343
392
  * POST /api/prompts/import — bulk-upload prompts into the account.
@@ -396,11 +445,66 @@ async function listProjects() {
396
445
  });
397
446
  return res.projects ?? [];
398
447
  }
448
+ const ROLES = ['owner', 'admin', 'editor', 'viewer'];
449
+ /**
450
+ * Validate one project row from the server instead of trusting its shape: a
451
+ * row without a string id/name is dropped, unknown visibility/role values fall
452
+ * back to the most restrictive reading ('private' / 'viewer').
453
+ */
454
+ function toRepoDetail(raw) {
455
+ if (typeof raw !== 'object' || raw === null)
456
+ return null;
457
+ const r = raw;
458
+ if (typeof r.id !== 'string' || !r.id || typeof r.name !== 'string')
459
+ return null;
460
+ const role = ROLES.includes(r.role) ? r.role : 'viewer';
461
+ return {
462
+ id: r.id,
463
+ name: (0, format_1.safeText)(r.name),
464
+ slug: typeof r.slug === 'string' ? (0, format_1.safeText)(r.slug) : null,
465
+ description: typeof r.description === 'string' ? (0, format_1.safeText)(r.description) : null,
466
+ visibility: r.visibility === 'public' ? 'public' : 'private',
467
+ role,
468
+ prompt_count: typeof r.prompt_count === 'number' ? r.prompt_count : 0,
469
+ member_count: typeof r.member_count === 'number' ? r.member_count : 0,
470
+ created_at: typeof r.created_at === 'string' ? r.created_at : null,
471
+ updated_at: typeof r.updated_at === 'string' ? r.updated_at : null,
472
+ };
473
+ }
474
+ /** GET /api/projects — every repo you own or belong to, with visibility, role and counts. */
475
+ async function listProjectsDetailed() {
476
+ const res = await apiFetch('/api/projects', { query: { limit: 100 } });
477
+ return (Array.isArray(res.projects) ? res.projects : [])
478
+ .map(toRepoDetail)
479
+ .filter((p) => p !== null);
480
+ }
481
+ /** POST /api/projects — create a repo. The server enforces plan limit, name rules and slug uniqueness. */
482
+ async function createProject(input) {
483
+ const res = await apiFetch('/api/projects', {
484
+ method: 'POST',
485
+ body: {
486
+ name: input.name,
487
+ visibility: input.visibility,
488
+ ...(input.description ? { description: input.description } : {}),
489
+ },
490
+ });
491
+ const project = toRepoDetail(res.project);
492
+ if (!project)
493
+ throw new ApiError('The server created the repo but sent an unexpected response. Run `ple repo list` to check.', 502);
494
+ return { ...project, role: 'owner' };
495
+ }
496
+ /** PATCH /api/projects/{id} — change visibility (the server allows the owner only). */
497
+ async function setProjectVisibility(id, visibility) {
498
+ await apiFetch(`/api/projects/${encodeURIComponent(id)}`, {
499
+ method: 'PATCH',
500
+ body: { visibility },
501
+ });
502
+ }
399
503
  /** GET /api/prompts/{id} — full detail; returns null when not found (404). */
400
504
  async function getPromptById(id) {
401
505
  try {
402
506
  const res = await apiFetch(`/api/prompts/${id}`);
403
- return res.prompt ?? null;
507
+ return res.prompt ? cleanPrompt(res.prompt) : null;
404
508
  }
405
509
  catch (err) {
406
510
  if (err instanceof Error && /not found/i.test(err.message))
@@ -415,7 +519,7 @@ async function getPromptHistory(id) {
415
519
  throw new Error('Prompt not found.');
416
520
  return {
417
521
  id: res.prompt.id,
418
- title: res.prompt.title,
522
+ title: (0, format_1.safeText)(String(res.prompt.title ?? '')),
419
523
  current_version_id: res.prompt.current_version_id ?? null,
420
524
  versions: Array.isArray(res.prompt.versions) ? res.prompt.versions : [],
421
525
  };
@@ -40,32 +40,54 @@ exports.writeConfig = writeConfig;
40
40
  exports.clearConfig = clearConfig;
41
41
  exports.isTokenExpiringSoon = isTokenExpiringSoon;
42
42
  const fs = __importStar(require("fs"));
43
- const os = __importStar(require("os"));
44
43
  const path = __importStar(require("path"));
45
- const CONFIG_DIR = path.join(os.homedir(), '.config', 'promptlike');
46
- const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
44
+ const fsSafe_1 = require("./fsSafe");
45
+ const settings_1 = require("./settings");
46
+ /**
47
+ * Resolved lazily (not at import) so `PROMPTLIKE_CONFIG_DIR` can redirect the
48
+ * session file — the tests rely on it, and so can people who keep their dotfiles
49
+ * elsewhere. Same directory as settings.json and the library cache.
50
+ */
51
+ function configFile() {
52
+ return path.join((0, settings_1.configDir)(), 'config.json');
53
+ }
47
54
  /** Config dosyasının tam yolu — debug çıktılarında göstermek için. */
48
55
  function getConfigPath() {
49
- return CONFIG_FILE;
56
+ return configFile();
50
57
  }
51
- /**
52
- * Config'i diskten oku. Yoksa null döner — login gerekli demektir.
53
- * Bozuk JSON varsa null döner ve dosyayı silmiyoruz; kullanıcı `ple logout`
54
- * çağırsın diye log'ı sessiz tutuyoruz.
55
- */
56
- function readConfig() {
58
+ /** Parse + shape-check the session file. Anything unexpected → null (never throws). */
59
+ function parseConfig(raw) {
60
+ let parsed;
57
61
  try {
58
- if (!fs.existsSync(CONFIG_FILE))
59
- return null;
60
- const raw = fs.readFileSync(CONFIG_FILE, 'utf-8');
61
- const parsed = JSON.parse(raw);
62
- if (!parsed.access_token || !parsed.refresh_token)
63
- return null;
64
- return parsed;
62
+ parsed = JSON.parse(raw);
65
63
  }
66
64
  catch {
67
65
  return null;
68
66
  }
67
+ if (typeof parsed !== 'object' || parsed === null)
68
+ return null;
69
+ const o = parsed;
70
+ if (typeof o.access_token !== 'string' || !o.access_token)
71
+ return null;
72
+ if (typeof o.refresh_token !== 'string' || !o.refresh_token)
73
+ return null;
74
+ return {
75
+ access_token: o.access_token,
76
+ refresh_token: o.refresh_token,
77
+ email: typeof o.email === 'string' ? o.email : '',
78
+ user_id: typeof o.user_id === 'string' ? o.user_id : '',
79
+ expires_at: typeof o.expires_at === 'number' && Number.isFinite(o.expires_at) ? o.expires_at : 0,
80
+ };
81
+ }
82
+ /**
83
+ * Config'i diskten oku. Yoksa null döner — login gerekli demektir.
84
+ * Bozuk JSON, symlink ya da düzenli olmayan dosya varsa null döner ve dosyaya
85
+ * dokunulmaz; kullanıcı `ple logout` çağırsın diye log'ı sessiz tutuyoruz.
86
+ * Grup/dünya erişimi açık bir dosya okunurken 0600'e sıkılaştırılır.
87
+ */
88
+ function readConfig() {
89
+ const raw = (0, fsSafe_1.readPrivateFile)(configFile());
90
+ return raw === null ? null : parseConfig(raw);
69
91
  }
70
92
  /**
71
93
  * Three-way session state, for callers that must NOT treat "file is corrupt"
@@ -75,27 +97,28 @@ function readConfig() {
75
97
  * gone. 'invalid' lets the router warn first.
76
98
  */
77
99
  function configStatus() {
78
- if (!fs.existsSync(CONFIG_FILE))
100
+ if (!(0, fsSafe_1.pathExists)(configFile()))
79
101
  return 'absent';
80
102
  return readConfig() ? 'valid' : 'invalid';
81
103
  }
82
104
  /**
83
- * Config'i diske yaz. Klasör yoksa oluştur, dosya izinlerini 0600 yap
84
- * (sadece kullanıcı okuyabilir — token sızıntısı önlemi).
105
+ * Config'i diske yaz: atomik (geçici dosya + rename), 0600, klasör 0700.
106
+ * Hedefte bir symlink varsa onun üzerinden YAZILMAZ — link rename ile değiştirilir.
85
107
  */
86
108
  function writeConfig(config) {
87
- if (!fs.existsSync(CONFIG_DIR)) {
88
- fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
89
- }
90
- fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), {
91
- mode: 0o600,
92
- });
109
+ (0, fsSafe_1.writePrivateFile)(configFile(), JSON.stringify(config, null, 2));
93
110
  }
94
- /** `ple logout` için: config dosyasını ve klasörünü sil. */
111
+ /**
112
+ * `ple logout` için: oturum dosyasını sil. Bozuk ya da symlink olsa bile silinir
113
+ * (symlink'te yalnız bağlantının kendisi; hedefe dokunulmaz). Silinen bir şey
114
+ * varsa true döner.
115
+ */
95
116
  function clearConfig() {
96
- if (fs.existsSync(CONFIG_FILE)) {
97
- fs.unlinkSync(CONFIG_FILE);
98
- }
117
+ const file = configFile();
118
+ if (!(0, fsSafe_1.pathExists)(file))
119
+ return false;
120
+ fs.unlinkSync(file);
121
+ return true;
99
122
  }
100
123
  /** Token'ın 60 saniye içinde sona erecek olup olmadığını kontrol et. */
101
124
  function isTokenExpiringSoon(config) {
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.confirm = confirm;
37
+ const readline = __importStar(require("readline"));
38
+ /**
39
+ * Ask a yes/no question on the terminal. Only `y` / `yes` count as yes; Enter,
40
+ * anything else and Ctrl-D are no. Callers decide what a non-interactive run does
41
+ * (scripts must pass `--yes`) before calling this.
42
+ */
43
+ function confirm(question) {
44
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
45
+ return new Promise((resolve) => {
46
+ rl.once('close', () => resolve(false));
47
+ rl.question(question, (answer) => {
48
+ rl.removeAllListeners('close');
49
+ rl.close();
50
+ resolve(/^y(es)?$/i.test(answer.trim()));
51
+ });
52
+ });
53
+ }
@@ -11,8 +11,45 @@
11
11
  * 2. `BAKED_API_URL` below — the public production URL.
12
12
  */
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.WEB_APP_URL = exports.CLI_VERSION = exports.CLI_NAME = exports.API_BASE_URL = void 0;
14
+ exports.WEB_APP_URL = exports.CLI_VERSION = exports.CLI_NAME = exports.API_BASE_URL = exports.API_BASE_URL_ERROR = void 0;
15
+ exports.validateApiBaseUrl = validateApiBaseUrl;
15
16
  const BAKED_API_URL = 'https://promptlikeengineer.com';
17
+ /** Hosts for which plain http is allowed (local development only). */
18
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
19
+ /**
20
+ * Validate an API base URL before ANY request is built from it. The CLI sends a
21
+ * bearer token and a refresh token to this origin, so a typo or a hostile
22
+ * `PROMPTLIKE_API_URL` must not turn into a plaintext token leak.
23
+ *
24
+ * - https is required; http is accepted ONLY for localhost / 127.0.0.1 / [::1].
25
+ * - No credentials in the URL (`https://user:pw@host`), no query or fragment.
26
+ * - Only the origin plus an optional path prefix is kept (trailing slashes dropped).
27
+ *
28
+ * Returns the cleaned URL, or an error message that says how to fix it.
29
+ */
30
+ function validateApiBaseUrl(raw) {
31
+ let u;
32
+ try {
33
+ u = new URL(raw);
34
+ }
35
+ catch {
36
+ return { error: `PROMPTLIKE_API_URL is not a valid URL: '${raw}'. Example: https://promptlikeengineer.com` };
37
+ }
38
+ const loopback = LOOPBACK_HOSTS.has(u.hostname);
39
+ if (u.protocol !== 'https:' && !(u.protocol === 'http:' && loopback)) {
40
+ return {
41
+ error: `PROMPTLIKE_API_URL must use https (plain http is allowed only for localhost): '${raw}'. ` +
42
+ 'Your login token would otherwise travel unencrypted.',
43
+ };
44
+ }
45
+ if (u.username || u.password) {
46
+ return { error: 'PROMPTLIKE_API_URL must not contain a username or password.' };
47
+ }
48
+ if (u.search || u.hash) {
49
+ return { error: 'PROMPTLIKE_API_URL must not contain a query string or fragment.' };
50
+ }
51
+ return { url: (u.origin + u.pathname).replace(/\/+$/, '') };
52
+ }
16
53
  function resolveEnv(key, fallback) {
17
54
  const value = process.env[key];
18
55
  if (typeof value === 'string' && value.trim().length > 0) {
@@ -20,8 +57,16 @@ function resolveEnv(key, fallback) {
20
57
  }
21
58
  return fallback;
22
59
  }
60
+ const resolvedApi = validateApiBaseUrl(resolveEnv('PROMPTLIKE_API_URL', BAKED_API_URL));
61
+ /**
62
+ * Set when `PROMPTLIKE_API_URL` is unusable. The API client throws it before it
63
+ * builds a request, so nothing — least of all a token — is ever sent to a URL
64
+ * that failed validation. (Not thrown here: an import-time crash would print a
65
+ * stack trace and break `--help`/`--version` and the offline commands.)
66
+ */
67
+ exports.API_BASE_URL_ERROR = 'error' in resolvedApi ? resolvedApi.error : null;
23
68
  /** Base URL of the web API the CLI calls (no trailing slash). */
24
- exports.API_BASE_URL = resolveEnv('PROMPTLIKE_API_URL', BAKED_API_URL).replace(/\/+$/, '');
69
+ exports.API_BASE_URL = 'url' in resolvedApi ? resolvedApi.url : BAKED_API_URL;
25
70
  exports.CLI_NAME = 'ple';
26
71
  /**
27
72
  * Sürüm TEK KAYNAKTAN: package.json. Eskiden elle yazılan sabitti ve kayıyordu
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.exitCodeFor = exitCodeFor;
4
+ /**
5
+ * Exit codes — one place, documented in the README:
6
+ * 0 success
7
+ * 1 you can fix it: bad input, not signed in, not found, not allowed, plan limit, conflict
8
+ * 2 not your fault / try again: no network, timeout, rate limit, server error (5xx)
9
+ */
10
+ const api_client_1 = require("./api-client");
11
+ function exitCodeFor(err) {
12
+ if (err instanceof api_client_1.NetworkError || err instanceof api_client_1.RequestTimeoutError)
13
+ return 2;
14
+ if (err instanceof api_client_1.ApiError && (err.status >= 500 || err.status === 429))
15
+ return 2;
16
+ return 1;
17
+ }
@@ -8,6 +8,7 @@ exports.timeAgo = timeAgo;
8
8
  exports.shortId = shortId;
9
9
  exports.truncate = truncate;
10
10
  exports.joinPromptParts = joinPromptParts;
11
+ exports.safeText = safeText;
11
12
  const chalk_1 = __importDefault(require("chalk"));
12
13
  /**
13
14
  * Tutarlı renk paleti — komutlar arasında aynı vurguları kullanmak için.
@@ -70,3 +71,18 @@ function joinPromptParts(parts) {
70
71
  return segments.join('\n\n---\n\n');
71
72
  return parts.content && parts.content.trim() ? parts.content.trim() : '';
72
73
  }
74
+ /**
75
+ * Make server- or file-provided text safe to print on a terminal. A title such
76
+ * as "\u001b]0;pwned\u0007" or "\u001b[2J" would otherwise be interpreted by the
77
+ * terminal (retitle the window, clear the screen, hide earlier output). ANSI
78
+ * escape sequences and control characters are removed; with `keepNewlines`
79
+ * line breaks and tabs survive (for multi-line bodies).
80
+ */
81
+ function safeText(input, keepNewlines = false) {
82
+ const noAnsi = input
83
+ // OSC (… BEL | ST), CSI (… final byte), and any other lone ESC sequence
84
+ .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g, '')
85
+ .replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '')
86
+ .replace(/\u001b[@-~]?/g, '');
87
+ return noAnsi.replace(/[\u0000-\u001f\u007f-\u009f]/g, (ch) => (keepNewlines && (ch === '\n' || ch === '\t') ? ch : ''));
88
+ }
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ /**
3
+ * Safe file helpers for everything the CLI keeps on disk (session, settings,
4
+ * cache, local prompts, history, exports).
5
+ *
6
+ * Threats covered (each has a test in fsSafe.test.ts):
7
+ * - SYMLINK: a link planted at the target path (e.g. `config.json -> ~/.bashrc`)
8
+ * must never make the CLI write through it. Writes go to a fresh temp file
9
+ * that is `rename`d over the target; rename replaces the link itself and
10
+ * never follows it.
11
+ * - LOOSE PERMISSIONS: `mkdir`/`writeFile` modes only apply on creation. A
12
+ * directory or file that already exists with group/world access is tightened
13
+ * to 0700 / 0600 on the next write.
14
+ * - TORN WRITES: a crash mid-write must not leave a half token file (the temp
15
+ * file is only renamed once fully written).
16
+ *
17
+ * POSIX permission bits do not exist on Windows; chmod there is a no-op and the
18
+ * checks are skipped (the per-user profile ACLs apply instead).
19
+ */
20
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ var desc = Object.getOwnPropertyDescriptor(m, k);
23
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
24
+ desc = { enumerable: true, get: function() { return m[k]; } };
25
+ }
26
+ Object.defineProperty(o, k2, desc);
27
+ }) : (function(o, m, k, k2) {
28
+ if (k2 === undefined) k2 = k;
29
+ o[k2] = m[k];
30
+ }));
31
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
32
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
33
+ }) : function(o, v) {
34
+ o["default"] = v;
35
+ });
36
+ var __importStar = (this && this.__importStar) || (function () {
37
+ var ownKeys = function(o) {
38
+ ownKeys = Object.getOwnPropertyNames || function (o) {
39
+ var ar = [];
40
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
41
+ return ar;
42
+ };
43
+ return ownKeys(o);
44
+ };
45
+ return function (mod) {
46
+ if (mod && mod.__esModule) return mod;
47
+ var result = {};
48
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
49
+ __setModuleDefault(result, mod);
50
+ return result;
51
+ };
52
+ })();
53
+ Object.defineProperty(exports, "__esModule", { value: true });
54
+ exports.isSymlink = isSymlink;
55
+ exports.pathExists = pathExists;
56
+ exports.ensurePrivateDir = ensurePrivateDir;
57
+ exports.writePrivateFile = writePrivateFile;
58
+ exports.createPrivateFileExclusive = createPrivateFileExclusive;
59
+ exports.readPrivateFile = readPrivateFile;
60
+ exports.assertNotSymlink = assertNotSymlink;
61
+ const fs = __importStar(require("fs"));
62
+ const path = __importStar(require("path"));
63
+ const IS_WINDOWS = process.platform === 'win32';
64
+ /** True when `p` exists and is itself a symbolic link (does not follow it). */
65
+ function isSymlink(p) {
66
+ try {
67
+ return fs.lstatSync(p).isSymbolicLink();
68
+ }
69
+ catch {
70
+ return false;
71
+ }
72
+ }
73
+ /** True when anything (file, dir, link — even a dangling link) exists at `p`. */
74
+ function pathExists(p) {
75
+ try {
76
+ fs.lstatSync(p);
77
+ return true;
78
+ }
79
+ catch {
80
+ return false;
81
+ }
82
+ }
83
+ /**
84
+ * Create `dir` (and parents) with mode 0700, and tighten it when it already
85
+ * exists with group/world bits. Only the LEAF directory is tightened — parents
86
+ * such as `~/.config` belong to the user and other tools.
87
+ */
88
+ function ensurePrivateDir(dir) {
89
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
90
+ if (IS_WINDOWS)
91
+ return;
92
+ try {
93
+ const st = fs.statSync(dir);
94
+ if (st.isDirectory() && (st.mode & 0o077) !== 0)
95
+ fs.chmodSync(dir, 0o700);
96
+ }
97
+ catch {
98
+ /* a directory we cannot stat is reported by the write that follows */
99
+ }
100
+ }
101
+ /**
102
+ * Write `data` to `file` atomically with mode 0600 (replaces an existing file
103
+ * or symlink; never writes through a link). The parent directory is created
104
+ * 0700 and tightened if needed.
105
+ */
106
+ function writePrivateFile(file, data) {
107
+ ensurePrivateDir(path.dirname(file));
108
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
109
+ // 'wx' = create exclusively, so an attacker-planted file or link at the temp
110
+ // name makes the write fail instead of being followed.
111
+ fs.writeFileSync(tmp, data, { mode: 0o600, flag: 'wx' });
112
+ try {
113
+ fs.renameSync(tmp, file);
114
+ }
115
+ catch (err) {
116
+ try {
117
+ fs.unlinkSync(tmp);
118
+ }
119
+ catch {
120
+ /* best effort */
121
+ }
122
+ throw err;
123
+ }
124
+ }
125
+ /**
126
+ * Create `file` with mode 0600 only if it does not exist; fails with EEXIST
127
+ * otherwise, and never follows a link (O_EXCL). Used for append-only history.
128
+ */
129
+ function createPrivateFileExclusive(file, data) {
130
+ ensurePrivateDir(path.dirname(file));
131
+ fs.writeFileSync(file, data, { flag: 'wx', mode: 0o600 });
132
+ }
133
+ /**
134
+ * Read a private file without following a symlink at the final path component.
135
+ * Returns null when the file is missing, is a link, or is not a regular file.
136
+ * A regular file that is group/world accessible is tightened to 0600.
137
+ */
138
+ function readPrivateFile(file) {
139
+ let st;
140
+ try {
141
+ st = fs.lstatSync(file);
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ if (st.isSymbolicLink() || !st.isFile())
147
+ return null;
148
+ if (!IS_WINDOWS && (st.mode & 0o077) !== 0) {
149
+ try {
150
+ fs.chmodSync(file, 0o600);
151
+ }
152
+ catch {
153
+ /* read-only filesystem: still readable */
154
+ }
155
+ }
156
+ try {
157
+ return fs.readFileSync(file, 'utf-8');
158
+ }
159
+ catch {
160
+ return null;
161
+ }
162
+ }
163
+ /**
164
+ * Refuse to write an export over a symlink. `existsSync` follows links, so a
165
+ * dangling link looked like "nothing there" and the write created its target.
166
+ */
167
+ function assertNotSymlink(target) {
168
+ if (isSymlink(target)) {
169
+ throw new Error(`${target} is a symbolic link — refusing to write through it. Remove the link or choose another path.`);
170
+ }
171
+ }