codepen-commander 0.0.0-stage → 1.0.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/config/auth.js ADDED
@@ -0,0 +1,470 @@
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { CliError } from '../utils/json.js';
5
+ import { extractCodePenOwnerFromUrl } from './project.js';
6
+ export const CODEPEN_API_SETTINGS_URL = 'https://codepen.io/settings/api';
7
+ export const API_KEY_ENV_VAR = 'CODEPEN_API_KEY';
8
+ export const API_KEY_FILENAME = '.cdpn';
9
+ export const DEFAULT_PROFILE_NAME = 'default';
10
+ const FORBIDDEN_PROFILE_NAMES = new Set(['__proto__', 'constructor', 'prototype']);
11
+ const PROFILE_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
12
+ const SINGLE_KEY_FIELDS = ['api_key', 'apiKey', 'key', 'token'];
13
+ export function getApiKeyFilePath(homeDir) {
14
+ return path.join(homeDir ?? os.homedir(), API_KEY_FILENAME);
15
+ }
16
+ export function getKeyType(apiKey) {
17
+ if (apiKey.startsWith('cp_user_'))
18
+ return 'User';
19
+ if (apiKey.startsWith('cp_team_'))
20
+ return 'Team';
21
+ return 'Unknown';
22
+ }
23
+ export function isRecognizedKeyFormat(apiKey) {
24
+ const trimmed = apiKey.trim();
25
+ return (trimmed.startsWith('cp_user_') || trimmed.startsWith('cp_team_')) && trimmed.length >= 16;
26
+ }
27
+ export function isValidProfileName(name) {
28
+ const trimmed = name.trim();
29
+ if (!trimmed)
30
+ return false;
31
+ if (FORBIDDEN_PROFILE_NAMES.has(trimmed.toLowerCase()))
32
+ return false;
33
+ return PROFILE_NAME_PATTERN.test(trimmed);
34
+ }
35
+ export function validateProfileName(name) {
36
+ const trimmed = name.trim();
37
+ if (!isValidProfileName(trimmed)) {
38
+ throw new CliError(400, `Invalid profile name "${name}". Use 1-64 characters: letters, numbers, hyphens, underscores, or dots (starting with a letter or number).`);
39
+ }
40
+ return trimmed;
41
+ }
42
+ /**
43
+ * Masks an API key so the full secret is never printed to terminal output or logs.
44
+ */
45
+ export function maskApiKey(apiKey) {
46
+ const trimmed = apiKey.trim();
47
+ if (trimmed.length <= 8) {
48
+ return '********';
49
+ }
50
+ const suffix = trimmed.slice(-4);
51
+ if (trimmed.startsWith('cp_user_')) {
52
+ return `cp_user_••••••••${suffix}`;
53
+ }
54
+ if (trimmed.startsWith('cp_team_')) {
55
+ return `cp_team_••••••••${suffix}`;
56
+ }
57
+ return `••••••••${suffix}`;
58
+ }
59
+ function extractKeyFromValue(value) {
60
+ if (typeof value === 'string') {
61
+ const trimmed = value.trim();
62
+ return trimmed || null;
63
+ }
64
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
65
+ const obj = value;
66
+ for (const field of SINGLE_KEY_FIELDS) {
67
+ const candidate = obj[field];
68
+ if (typeof candidate === 'string' && candidate.trim()) {
69
+ return candidate.trim();
70
+ }
71
+ }
72
+ }
73
+ return null;
74
+ }
75
+ function createEmptyStore() {
76
+ return {
77
+ defaultProfile: null,
78
+ profiles: Object.create(null),
79
+ };
80
+ }
81
+ /**
82
+ * Parses `~/.cdpn` content into a normalized multi-profile `AuthStore`.
83
+ *
84
+ * Supported formats:
85
+ * - Multi-profile JSON (canonical format written by `cdpn auth login`):
86
+ * `{ "default": "bramus", "profiles": { "bramus": "cp_user_...", "username": "cp_team_..." } }`
87
+ * - Flat JSON map of profile names to API keys:
88
+ * `{ "bramus": "cp_user_...", "username": "cp_team_..." }`
89
+ * - Single-key JSON (`{ "api_key": "..." }`, `{ "key": "..." }`, `{ "token": "..." }`)
90
+ * - Plain raw key (`cp_user_...`) or env assignment (`export CODEPEN_API_KEY="..."`)
91
+ */
92
+ export function parseAuthStoreContent(raw) {
93
+ const trimmed = raw.trim();
94
+ if (!trimmed) {
95
+ return createEmptyStore();
96
+ }
97
+ if (trimmed.startsWith('{')) {
98
+ try {
99
+ const parsed = JSON.parse(trimmed);
100
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
101
+ return createEmptyStore();
102
+ }
103
+ const record = parsed;
104
+ const profiles = Object.create(null);
105
+ // Format 1: { "default": "...", "profiles": { "bramus": "cp_user_...", ... } }
106
+ if (record.profiles && typeof record.profiles === 'object' && !Array.isArray(record.profiles)) {
107
+ for (const [name, entry] of Object.entries(record.profiles)) {
108
+ if (!isValidProfileName(name))
109
+ continue;
110
+ const key = extractKeyFromValue(entry);
111
+ if (key) {
112
+ profiles[name.trim()] = key;
113
+ }
114
+ }
115
+ const profileNames = Object.keys(profiles);
116
+ const rawDefault = typeof record.default === 'string'
117
+ ? record.default.trim()
118
+ : typeof record.defaultProfile === 'string'
119
+ ? record.defaultProfile.trim()
120
+ : typeof record.default_profile === 'string'
121
+ ? record.default_profile.trim()
122
+ : '';
123
+ const defaultProfile = rawDefault && Object.hasOwn(profiles, rawDefault)
124
+ ? rawDefault
125
+ : (profileNames[0] ?? null);
126
+ return { defaultProfile, profiles };
127
+ }
128
+ // Format 2: Single-key JSON ({ "api_key": "..." })
129
+ for (const field of SINGLE_KEY_FIELDS) {
130
+ const value = record[field];
131
+ if (typeof value === 'string' && value.trim()) {
132
+ profiles[DEFAULT_PROFILE_NAME] = value.trim();
133
+ return { defaultProfile: DEFAULT_PROFILE_NAME, profiles };
134
+ }
135
+ }
136
+ // Format 3: Flat map JSON ({ "bramus": "cp_user_...", "username": "cp_team_..." })
137
+ const metaKeys = new Set(['default', 'defaultProfile', 'default_profile']);
138
+ for (const [name, entry] of Object.entries(record)) {
139
+ if (metaKeys.has(name) || !isValidProfileName(name))
140
+ continue;
141
+ const key = extractKeyFromValue(entry);
142
+ if (key) {
143
+ profiles[name.trim()] = key;
144
+ }
145
+ }
146
+ const profileNames = Object.keys(profiles);
147
+ if (profileNames.length > 0) {
148
+ const rawDefault = typeof record.default === 'string' ? record.default.trim() : '';
149
+ const defaultProfile = rawDefault && Object.hasOwn(profiles, rawDefault)
150
+ ? rawDefault
151
+ : (profileNames[0] ?? null);
152
+ return { defaultProfile, profiles };
153
+ }
154
+ return createEmptyStore();
155
+ }
156
+ catch {
157
+ return createEmptyStore();
158
+ }
159
+ }
160
+ // Format 4: Plain key or env assignment line
161
+ for (const line of trimmed.split(/\r?\n/)) {
162
+ const cleanLine = line.trim();
163
+ if (!cleanLine || cleanLine.startsWith('#'))
164
+ continue;
165
+ const envMatch = cleanLine.match(/^(?:export\s+)?CODEPEN_API_KEY\s*=\s*(.+)$/);
166
+ const key = envMatch?.[1]
167
+ ? envMatch[1].trim().replace(/^['"]|['"]$/g, '').trim()
168
+ : cleanLine.replace(/^['"]|['"]$/g, '').trim();
169
+ if (key) {
170
+ const profiles = Object.create(null);
171
+ profiles[DEFAULT_PROFILE_NAME] = key;
172
+ return { defaultProfile: DEFAULT_PROFILE_NAME, profiles };
173
+ }
174
+ }
175
+ return createEmptyStore();
176
+ }
177
+ /**
178
+ * Extracts the default (or sole) API key from `~/.cdpn` content.
179
+ */
180
+ export function parseKeyFileContent(raw) {
181
+ const store = parseAuthStoreContent(raw);
182
+ if (store.defaultProfile && Object.hasOwn(store.profiles, store.defaultProfile)) {
183
+ return store.profiles[store.defaultProfile] ?? null;
184
+ }
185
+ const first = Object.keys(store.profiles)[0];
186
+ return first ? (store.profiles[first] ?? null) : null;
187
+ }
188
+ export async function readAuthStore(options = {}) {
189
+ const filePath = getApiKeyFilePath(options.homeDir);
190
+ try {
191
+ const stat = await fs.lstat(filePath);
192
+ if (!stat.isFile()) {
193
+ return {
194
+ store: createEmptyStore(),
195
+ filePath,
196
+ exists: false,
197
+ insecurePermissions: false,
198
+ };
199
+ }
200
+ const content = await fs.readFile(filePath, 'utf8');
201
+ const insecurePermissions = process.platform !== 'win32' && (stat.mode & 0o077) !== 0;
202
+ return {
203
+ store: parseAuthStoreContent(content),
204
+ filePath,
205
+ exists: true,
206
+ insecurePermissions,
207
+ };
208
+ }
209
+ catch (error) {
210
+ if (error.code === 'ENOENT') {
211
+ return {
212
+ store: createEmptyStore(),
213
+ filePath,
214
+ exists: false,
215
+ insecurePermissions: false,
216
+ };
217
+ }
218
+ throw error;
219
+ }
220
+ }
221
+ export async function readApiKeyFile(options = {}) {
222
+ const result = await readAuthStore(options);
223
+ const { store } = result;
224
+ const activeProfile = store.defaultProfile ?? Object.keys(store.profiles)[0] ?? null;
225
+ const apiKey = activeProfile && Object.hasOwn(store.profiles, activeProfile)
226
+ ? (store.profiles[activeProfile] ?? null)
227
+ : null;
228
+ return {
229
+ apiKey,
230
+ filePath: result.filePath,
231
+ exists: result.exists,
232
+ insecurePermissions: result.insecurePermissions,
233
+ };
234
+ }
235
+ /**
236
+ * Writes the multi-profile store to `~/.cdpn` with strict owner-only (`0o600`) file permissions.
237
+ */
238
+ export async function writeAuthStore(store, options = {}) {
239
+ const filePath = getApiKeyFilePath(options.homeDir);
240
+ const sortedProfiles = {};
241
+ for (const name of Object.keys(store.profiles).sort((a, b) => a.localeCompare(b))) {
242
+ const validName = validateProfileName(name);
243
+ const key = store.profiles[name]?.trim();
244
+ if (key) {
245
+ sortedProfiles[validName] = key;
246
+ }
247
+ }
248
+ const names = Object.keys(sortedProfiles);
249
+ const resolvedDefault = store.defaultProfile && Object.hasOwn(sortedProfiles, store.defaultProfile)
250
+ ? store.defaultProfile
251
+ : (names[0] ?? null);
252
+ const payload = {
253
+ ...(resolvedDefault ? { default: resolvedDefault } : {}),
254
+ profiles: sortedProfiles,
255
+ };
256
+ await fs.writeFile(filePath, `${JSON.stringify(payload, null, 2)}\n`, {
257
+ encoding: 'utf8',
258
+ mode: 0o600,
259
+ });
260
+ if (process.platform !== 'win32') {
261
+ await fs.chmod(filePath, 0o600);
262
+ }
263
+ return filePath;
264
+ }
265
+ /**
266
+ * Adds or updates a named profile inside `~/.cdpn` (creating the file with `0o600` permissions).
267
+ */
268
+ export async function saveProfileToFile(profileName, apiKey, options = {}) {
269
+ const validProfile = validateProfileName(profileName);
270
+ const trimmedKey = apiKey.trim();
271
+ if (!trimmedKey) {
272
+ throw new CliError(400, 'Cannot save an empty API key.');
273
+ }
274
+ const { store } = await readAuthStore({ homeDir: options.homeDir });
275
+ store.profiles[validProfile] = trimmedKey;
276
+ const hasValidDefault = Boolean(store.defaultProfile && Object.hasOwn(store.profiles, store.defaultProfile));
277
+ if (options.setAsDefault || !hasValidDefault) {
278
+ store.defaultProfile = validProfile;
279
+ }
280
+ const filePath = await writeAuthStore(store, { homeDir: options.homeDir });
281
+ return {
282
+ filePath,
283
+ profile: validProfile,
284
+ isDefault: store.defaultProfile === validProfile,
285
+ };
286
+ }
287
+ /**
288
+ * Persists an API key to `~/.cdpn` under `options.profile` (default `"default"`) with `0o600` permissions.
289
+ */
290
+ export async function saveApiKeyToFile(apiKey, options = {}) {
291
+ const result = await saveProfileToFile(options.profile ?? DEFAULT_PROFILE_NAME, apiKey, options);
292
+ return result.filePath;
293
+ }
294
+ export async function setDefaultProfile(profileName, options = {}) {
295
+ const validProfile = validateProfileName(profileName);
296
+ const { store } = await readAuthStore(options);
297
+ if (!Object.hasOwn(store.profiles, validProfile)) {
298
+ const available = Object.keys(store.profiles);
299
+ const hint = available.length > 0
300
+ ? ` Available profiles: ${available.join(', ')}.`
301
+ : ` Run \`cdpn auth login --profile ${validProfile}\` first.`;
302
+ throw new CliError(404, `Profile "${validProfile}" not found in ~/${API_KEY_FILENAME}.${hint}`, {
303
+ requested_profile: validProfile,
304
+ available_profiles: available,
305
+ });
306
+ }
307
+ store.defaultProfile = validProfile;
308
+ return writeAuthStore(store, options);
309
+ }
310
+ export async function removeProfileFromFile(profileName, options = {}) {
311
+ const validProfile = validateProfileName(profileName);
312
+ const { store, exists } = await readAuthStore(options);
313
+ if (!exists || !Object.hasOwn(store.profiles, validProfile)) {
314
+ return {
315
+ removed: false,
316
+ remainingProfiles: Object.keys(store.profiles),
317
+ newDefault: store.defaultProfile,
318
+ };
319
+ }
320
+ delete store.profiles[validProfile];
321
+ const remaining = Object.keys(store.profiles).sort((a, b) => a.localeCompare(b));
322
+ if (remaining.length === 0) {
323
+ await removeApiKeyFile(options);
324
+ return { removed: true, remainingProfiles: [], newDefault: null };
325
+ }
326
+ if (store.defaultProfile === validProfile) {
327
+ store.defaultProfile = remaining[0] ?? null;
328
+ }
329
+ await writeAuthStore(store, options);
330
+ return {
331
+ removed: true,
332
+ remainingProfiles: remaining,
333
+ newDefault: store.defaultProfile,
334
+ };
335
+ }
336
+ export async function removeApiKeyFile(options = {}) {
337
+ const filePath = getApiKeyFilePath(options.homeDir);
338
+ try {
339
+ await fs.unlink(filePath);
340
+ return true;
341
+ }
342
+ catch (error) {
343
+ if (error.code === 'ENOENT') {
344
+ return false;
345
+ }
346
+ throw error;
347
+ }
348
+ }
349
+ /**
350
+ * Matches a CodePen URL's owner segment (user or team slug) against stored profile names.
351
+ */
352
+ export function findMatchingProfile(availableProfiles, urlHint) {
353
+ if (!urlHint || availableProfiles.length === 0)
354
+ return null;
355
+ const owner = extractCodePenOwnerFromUrl(urlHint);
356
+ if (!owner)
357
+ return null;
358
+ const exact = availableProfiles.find((p) => p === owner);
359
+ if (exact)
360
+ return exact;
361
+ const lower = owner.toLowerCase();
362
+ return availableProfiles.find((p) => p.toLowerCase() === lower) ?? null;
363
+ }
364
+ /**
365
+ * Resolves CodePen API credentials non-interactively.
366
+ *
367
+ * Precedence:
368
+ * 1. Explicit `options.profile` from `~/.cdpn` (returns `null` if that profile does not exist).
369
+ * 2. `CODEPEN_API_KEY` environment variable.
370
+ * 3. Default (or sole) profile in `~/.cdpn`.
371
+ */
372
+ export async function resolveAuth(options = {}) {
373
+ const env = options.env ?? process.env;
374
+ const envKey = env[API_KEY_ENV_VAR]?.trim() || '';
375
+ const { store, filePath, insecurePermissions } = await readAuthStore({
376
+ homeDir: options.homeDir,
377
+ });
378
+ const availableProfiles = Object.keys(store.profiles).sort((a, b) => a.localeCompare(b));
379
+ const hasEnv = Boolean(envKey);
380
+ const hasFile = availableProfiles.length > 0;
381
+ if (options.profile !== undefined) {
382
+ const requestedProfile = validateProfileName(options.profile);
383
+ if (Object.hasOwn(store.profiles, requestedProfile)) {
384
+ return {
385
+ apiKey: store.profiles[requestedProfile],
386
+ source: 'file',
387
+ profile: requestedProfile,
388
+ filePath,
389
+ hasEnv,
390
+ hasFile,
391
+ availableProfiles,
392
+ defaultProfile: store.defaultProfile,
393
+ insecureFilePermissions: insecurePermissions,
394
+ };
395
+ }
396
+ return null;
397
+ }
398
+ if (hasEnv) {
399
+ return {
400
+ apiKey: envKey,
401
+ source: 'env',
402
+ profile: null,
403
+ filePath,
404
+ hasEnv,
405
+ hasFile,
406
+ availableProfiles,
407
+ defaultProfile: store.defaultProfile,
408
+ insecureFilePermissions: insecurePermissions,
409
+ };
410
+ }
411
+ if (hasFile) {
412
+ const chosen = store.defaultProfile && Object.hasOwn(store.profiles, store.defaultProfile)
413
+ ? store.defaultProfile
414
+ : availableProfiles[0];
415
+ return {
416
+ apiKey: store.profiles[chosen],
417
+ source: 'file',
418
+ profile: chosen,
419
+ filePath,
420
+ hasEnv,
421
+ hasFile,
422
+ availableProfiles,
423
+ defaultProfile: store.defaultProfile,
424
+ insecureFilePermissions: insecurePermissions,
425
+ };
426
+ }
427
+ return null;
428
+ }
429
+ export async function requireAuth(options = {}) {
430
+ const auth = await resolveAuth(options);
431
+ if (!auth) {
432
+ if (options.profile) {
433
+ const { store } = await readAuthStore({ homeDir: options.homeDir });
434
+ const available = Object.keys(store.profiles).sort((a, b) => a.localeCompare(b));
435
+ const availableNote = available.length > 0 ? ` Available profiles: ${available.join(', ')}.` : '';
436
+ throw new CliError(404, `Profile "${options.profile}" not found in ~/${API_KEY_FILENAME}.${availableNote}\n` +
437
+ `Run \`cdpn auth login --profile ${options.profile}\` to add it.`, { requested_profile: options.profile, available_profiles: available });
438
+ }
439
+ throw new CliError(401, `No CodePen API key found. Run \`cdpn auth login\` or set the ${API_KEY_ENV_VAR} environment variable.`);
440
+ }
441
+ return auth;
442
+ }
443
+ export function getShellExportSnippets(apiKey, shellPath = process.env.SHELL ?? '') {
444
+ const escapedPosix = apiKey.replaceAll("'", "'\\''");
445
+ const all = [
446
+ {
447
+ shell: 'zsh',
448
+ rcFile: '~/.zshrc',
449
+ line: `export ${API_KEY_ENV_VAR}='${escapedPosix}'`,
450
+ },
451
+ {
452
+ shell: 'bash',
453
+ rcFile: '~/.bashrc',
454
+ line: `export ${API_KEY_ENV_VAR}='${escapedPosix}'`,
455
+ },
456
+ {
457
+ shell: 'fish',
458
+ rcFile: '~/.config/fish/config.fish',
459
+ line: `set -gx ${API_KEY_ENV_VAR} '${escapedPosix}'`,
460
+ },
461
+ ];
462
+ const base = path.basename(shellPath).toLowerCase();
463
+ const preferredIdx = all.findIndex((s) => s.shell === base);
464
+ if (preferredIdx > 0) {
465
+ const [preferred] = all.splice(preferredIdx, 1);
466
+ if (preferred)
467
+ all.unshift(preferred);
468
+ }
469
+ return all;
470
+ }