-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.ts
556 lines (467 loc) · 17.2 KB
/
config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
import * as S3 from '@aws-sdk/client-s3'
import TOML from '@iarna/toml'
import getos from 'getos'
import { parse as parseINI } from 'ini'
import inquirer from 'inquirer'
import { execFileSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import { Err, Ok, Result } from 'ts-results'
import { ArgumentsCamelCase } from 'yargs'
async function touchPath(p: string): Promise<void> {
const fd = await new Promise<number>((resolve, reject) =>
fs.open(p, 'a', undefined, (err, fd) => {
if (err) {
reject(err)
} else {
resolve(fd)
}
})
)
return new Promise<void>((resolve, reject) => {
fs.close(fd, (err) => {
if (err) {
reject(err)
} else {
resolve()
}
})
})
}
async function readTextFile(p: string): Promise<string> {
const chunks: Buffer[] = []
return new Promise<string>((resolve, reject) => {
fs.readFile(p, { encoding: 'utf8' }, (err, data) => {
if (err) { reject(err) }
resolve(data)
})
})
}
async function writeTextFile(p: string, contents: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
fs.writeFile(p, contents, { encoding: 'utf8' }, (err) => {
if (err) { reject(err) }
resolve()
})
})
}
class CandidatePaths {
private readonly projectFolder: string
private readonly local: string
private readonly winAppDataPath: string | undefined
private readonly xdgConfigPath: string | undefined
private readonly homePaths: string[]
constructor(projectFolder: string, configName: string) {
this.projectFolder = projectFolder
this.local = `${configName}`
if (process.platform === 'win32' && process.env['APPDATA']) {
this.winAppDataPath = `${process.env['APPDATA']}/${projectFolder}/${configName}`
}
if (process.env['XDG_CONFIG_HOME']) {
this.xdgConfigPath = `${process.env['XDG_CONFIG_HOME']}/${projectFolder}/${configName}`
}
let home = process.env['HOME'] ||
process.env['USERPROFILE'] ||
(process.env['HOMEDRIVE'] && process.env['HOMEPATH'] ?
path.join(process.env['HOMEDRIVE'], process.env['HOMEPATH']) :
undefined)
if (home !== undefined) {
this.homePaths = [`${home}/.config/${projectFolder}/${configName}`, `${home}/.${configName}`]
} else {
this.homePaths = []
}
}
get candidatePaths(): string[] {
return [this.local, this.winAppDataPath, this.xdgConfigPath, ...this.homePaths].flatMap((v) =>
v !== undefined ? [v] : []
)
}
async findExistingConfig(): Promise<string | undefined> {
for (const p of [this.local, this.winAppDataPath, this.xdgConfigPath, ...this.homePaths]) {
if (p === undefined) {
continue
}
const exists = await new Promise<boolean>((resolve) =>
fs.access(p, fs.constants.R_OK, (err) => err ? resolve(false) : resolve(true))
)
if (exists) {
return p
}
}
return undefined
}
async createInitialConfig(): Promise<Result<string, Error>> {
if (this.projectFolder !== 'cloudflare') {
throw new Error(`Attempt to touch someone else's project`)
}
let candidatePaths = []
if (process.platform === 'win32') {
candidatePaths.push(this.winAppDataPath)
candidatePaths.push(this.homePaths[0])
} else {
candidatePaths.push(this.xdgConfigPath)
candidatePaths.push(this.homePaths[0])
}
for (const p of candidatePaths) {
if (p === undefined) {
continue
}
const parentDir = path.dirname(p)
try {
await new Promise<void>((resolve, reject) => fs.mkdir(parentDir, (err) => err ? reject(err) : resolve()))
} catch (e) {
if (Object.prototype.hasOwnProperty.call(e, 'code') && (e as NodeJS.ErrnoException).code === 'EEXIST') {
} else {
console.warn('Trouble creating path', parentDir, e)
continue
}
}
// Touch the file
try {
await touchPath(p)
} catch (e) {
console.warn('Trouble touching config path', p, e)
continue
}
return Ok(p)
}
if (this.homePaths[1]) {
const p = this.homePaths[1]
try {
await touchPath(p)
return Ok(p)
} catch (e) {
console.warn('Trouble touching config path', p, e)
}
}
return Err(new Error('Failed on all possible candidate paths'))
}
}
function accountForR2URL(r2Url: string): string {
const url = new URL(r2Url)
return url.hostname.split('.')[0]
}
interface Config {
profile: string
account_id: string
access_key_id: string
secret_access_key: string
}
async function loadKeytar(): Promise<Result<typeof import('keytar'), Error>> {
const distro = await new Promise<getos.Os>((resolve, reject) => {
getos((e, os) => {
if (e) { reject(e) }
else { resolve(os) }
})
})
if (distro.os === 'linux') {
const libsecretFile = '/usr/lib/libsecret-1.so'
if (!fs.existsSync(libsecretFile)) {
let installCommand = (() => {
switch (distro.dist) {
case 'Arch Linux':
return ['pacman', '-S', 'libsecret']
case 'Ubuntu':
case 'Debian GNU/Linux':
return ['apt', 'install', 'libsecret-1-dev']
case 'Fedora':
return ['yum', 'install', 'libsecret-devel']
default:
console.error(
`libsecret doesn't appear to be installed and not a currently supported Linux distribution at this time`,
)
return undefined
}
})()
if (installCommand === undefined) {
return Err(new Error('libsecret required and not available'))
}
console.log(
`Running ${
['/usr/bin/sudo', ...installCommand].join(' ')
} to install libsecret. You may be prompted for a password.`,
)
execFileSync('/usr/bin/sudo', installCommand, { encoding: 'utf-8', input: 'inherit', stdio: 'inherit' })
}
}
return Ok((await import('keytar')).default)
}
async function saveCreds(config: Omit<Config, 'profile'>): Promise<void> {
const endpoint = `https://${config.account_id}.r2.cloudflarestorage.com`
console.log(`Validating credential ${config.access_key_id} for ${endpoint}`)
const s3 = new S3.S3({
endpoint,
credentials: { accessKeyId: config.access_key_id, secretAccessKey: config.secret_access_key },
})
try {
await s3.listBuckets({})
} catch (e) {
console.error('Credentials failed to validate.', (e as Error).message)
process.exit(1)
}
console.log(
`Securely saving R2 token with id ${config.access_key_id} for ${endpoint} in your OS encrypted password storage.`,
)
const keytar = await loadKeytar()
if (keytar.err) {
process.exitCode = 1
return
}
await keytar.val.setPassword(endpoint, config.access_key_id, config.secret_access_key)
}
async function retrieveCreds(config: { account_id: string; access_key_id: string }): Promise<Result<string, Error>> {
const endpoint = `https://${config.account_id}.r2.cloudflarestorage.com`
console.log(
`Retrieving R2 token secret with id ${config.access_key_id} for ${endpoint} from your OS encrypted password storage.`,
)
const keytar = await loadKeytar()
if (keytar.err) {
return keytar
}
const secret_access_key = await keytar.val.getPassword(endpoint, config.access_key_id)
if (secret_access_key === null) {
return Err(new Error('No credentials found'))
}
return Ok(secret_access_key)
}
async function removeCred(config: { account_id: string; access_key_id: string }): Promise<Result<void, Error>> {
const endpoint = `https://${config.account_id}.r2.cloudflarestorage.com`
console.log(
`Removing R2 token secret with id ${config.access_key_id} for ${endpoint} from your OS encrypted password storage.`,
)
const keytar = await loadKeytar()
if (keytar.err) {
return keytar
}
if (await keytar.val.deletePassword(endpoint, config.access_key_id)) {
return Ok.EMPTY
}
return Err(new Error('Unknown problem removing token secret'))
}
async function listCreds(account: string): Promise<Result<string[], Error>> {
const keytar = await loadKeytar()
if (keytar.err) {
return keytar
}
const endpoint = `https://${account}.r2.cloudflarestorage.com`
const creds = await keytar.val.findCredentials(endpoint)
return Ok(creds.map(({ account }) => account))
}
export async function listCredsCommand(argv: ArgumentsCamelCase<{ account: string }>): Promise<void> {
const keytar = await loadKeytar()
if (keytar.err) {
process.exitCode = 1
return
}
const endpoint = `https://${argv.account}.r2.cloudflarestorage.com`
for (const cred of await keytar.val.findCredentials(endpoint)) {
console.info(`Found token id ${cred.account}`)
}
}
export async function removeCredCommand(
argv: ArgumentsCamelCase<{ account: string; 'access-key-id'?: string }>,
): Promise<void> {
let access_key_id = argv['access-key-id']
if (access_key_id === undefined) {
const choices = await listCreds(argv.account)
if (choices.err) {
process.exitCode = 1
return
}
if (choices.val.length === 0) {
console.info('No credentials found')
return
}
const prompt = inquirer.createPromptModule()
const answer = await prompt({
name: 'id',
message: `Which access key would you like to remove for account ${argv.account}`,
type: 'list',
choices: choices.val,
})
access_key_id = answer.id as string
}
const result = await removeCred({ account_id: argv.account, access_key_id })
if (result.err) {
process.exitCode = 1
return
}
}
export async function importConfig(argv: ArgumentsCamelCase): Promise<void> {
const r2ConfigPaths = new CandidatePaths('cloudflare', 'r2.toml')
const configFilePath = (await r2ConfigPaths.createInitialConfig()).unwrap()
const existingConfig = TOML.parse(await readTextFile(configFilePath))
let importSource
let numConfigurationsImported = 0
if (argv['rclone']) {
importSource = 'rclone'
const rclonePaths = new CandidatePaths('rclone', 'rclone.conf')
const rcloneConfigFile = await rclonePaths.findExistingConfig()
if (rcloneConfigFile === undefined) {
console.error(`No existing rclone configuration found in ${rclonePaths.candidatePaths.join(', ')}`)
process.exitCode = 1
return
}
let rcloneConfig = await (async (): Promise<Record<string, Record<string, string>> | undefined> => {
try {
return parseINI(await readTextFile(rcloneConfigFile))
} catch (e) {
console.error('Trouble parsing rclone config file', rcloneConfigFile, e)
process.exitCode = 1
return undefined
}
})()
if (rcloneConfig === undefined) {
return
}
const r2Profiles: Record<string, Record<string, string>> = {}
for (const [profileName, profile] of Object.entries(rcloneConfig)) {
if (profile['endpoint'].endsWith('.r2.cloudflarestorage.com')) {
r2Profiles[profileName] = profile
}
}
switch (Object.keys(r2Profiles).length) {
case 0:
console.error('No Cloudflare R2 profiles found in', rcloneConfigFile)
process.exitCode = 1
return
default:
numConfigurationsImported = Object.keys(r2Profiles).length
for (const [name, details] of Object.entries(r2Profiles)) {
console.log(`Importing RClone configuration ${name}`)
await saveCreds({
account_id: accountForR2URL(details['endpoint']),
access_key_id: details['access_key_id'],
secret_access_key: details['secret_access_key'],
})
existingConfig[name] = {
account_id: accountForR2URL(details['endpoint']),
access_key_id: details['access_key_id'],
}
}
}
} else {
console.error('No import source provided')
process.exitCode = 1
return
}
await writeTextFile(configFilePath, TOML.stringify(existingConfig))
console.info(`Imported ${numConfigurationsImported} ${importSource} configurations into ${configFilePath}`)
}
export async function initConfigCommand(argv: ArgumentsCamelCase): Promise<void> {
// TODO: It would be nice to just navigate you through available accounts like wrangler does.
// TODO: Use wrangler creds from ~/.wrangler/config/default.toml to communicate with the API.
const name = argv['name'] as string
const account_id = argv['account'] as string
console.info(`Tokens can be generated at https://dash.cloudflare.com/${account_id}/r2/api-tokens`)
const prompt = inquirer.createPromptModule()
const { access_key_id, secret_access_key } = await prompt([{
name: 'access_key_id',
message: 'What is the "Access Key ID" of your token?',
}, { name: 'secret_access_key', message: 'What is the "Secret Access Key" of your token?' }])
const r2ConfigPaths = new CandidatePaths('cloudflare', 'r2.toml')
const configFilePath = (await r2ConfigPaths.createInitialConfig()).unwrap()
const existingConfig = TOML.parse(await readTextFile(configFilePath))
await saveCreds({ account_id, access_key_id, secret_access_key })
existingConfig[name] = { account: account_id, access_key_id: access_key_id }
await writeTextFile(configFilePath, TOML.stringify(existingConfig))
console.info(`Added configuration ${name} to ${configFilePath}`)
}
export async function listConfigsCommand(): Promise<void> {
const r2ConfigPaths = new CandidatePaths('cloudflare', 'r2.toml')
const configFilePath = (await r2ConfigPaths.createInitialConfig()).unwrap()
console.log(await readTextFile(configFilePath))
}
export async function retrieveOnlyConfig(): Promise<Result<Config, Error>> {
const r2ConfigPaths = new CandidatePaths('cloudflare', 'r2.toml')
const configFilePath = (await r2ConfigPaths.createInitialConfig()).unwrap()
const existingConfig = TOML.parse(await readTextFile(configFilePath)) as Record<
string,
{ account: string; access_key_id: string }
>
let configIdx: number
const configs = Object.entries(existingConfig)
if (configs.length === 0) {
return Err(new Error(`No profiles found in ${configFilePath}`))
}
if (configs.length === 1) {
configIdx = 0
} else {
const prompt = inquirer.createPromptModule()
const choices = configs.map(([profile, info]) => `${info.account}: ${profile}`)
const selected = await prompt([{
name: 'choice',
message: 'Found more than one profile. Which would you like to use?',
type: 'list',
choices,
}])
configIdx = choices.indexOf(selected['choice'])
}
const [profile, info] = configs[configIdx]
const secretAccessKey = await retrieveCreds({ account_id: info.account, access_key_id: info.access_key_id })
if (secretAccessKey.err) {
console.warn(`Profile ${profile} for account ${info.account} appears to be missing credentials.`)
return Err(new Error())
}
return Ok({
profile,
account_id: info.account,
access_key_id: info.access_key_id,
secret_access_key: secretAccessKey.val,
})
}
export async function removeConfigCommand(argv: ArgumentsCamelCase<{ name: string }>): Promise<void> {
const config = await retrieveConfig(argv.name)
if (config.err) {
process.exitCode = 1
return
}
const r2ConfigPaths = new CandidatePaths('cloudflare', 'r2.toml')
const configFilePath = (await r2ConfigPaths.createInitialConfig()).unwrap()
const existingConfig = TOML.parse(await readTextFile(configFilePath)) as Record<
string,
{ account: string; access_key_id: string }
>
delete existingConfig[config.val.profile]
const removal = await removeCred(config.val)
if (removal.err) {
process.exitCode = 1
console.error(`Failed to remove creds for token ${config.val.access_key_id}`)
return
}
await writeTextFile(configFilePath, TOML.stringify(existingConfig))
}
export async function retrieveConfig(accountOrProfile: string): Promise<Result<Config, Error>> {
const r2ConfigPaths = new CandidatePaths('cloudflare', 'r2.toml')
const configFilePath = (await r2ConfigPaths.createInitialConfig()).unwrap()
const existingConfig = TOML.parse(await readTextFile(configFilePath)) as Record<
string,
{ account: string; access_key_id: string }
>
if (accountOrProfile in existingConfig) {
const { account: account_id, access_key_id } = existingConfig[accountOrProfile]
const secretAccessKey = await retrieveCreds({ account_id, access_key_id })
if (secretAccessKey.err) {
return secretAccessKey
}
return Ok({ profile: accountOrProfile, account_id, access_key_id, secret_access_key: secretAccessKey.val })
} else {
for (const [profile, info] of Object.entries(existingConfig)) {
if (info.account === accountOrProfile) {
const secretAccessKey = await retrieveCreds({ account_id: info.account, access_key_id: info.access_key_id })
if (secretAccessKey.err) {
console.warn(`Profile ${profile} matches account ${accountOrProfile} appears to be missing credentials.`)
continue
}
return Ok({
profile: accountOrProfile,
account_id: info.account,
access_key_id: info.access_key_id,
secret_access_key: secretAccessKey.val,
})
}
}
}
const type = accountOrProfile.match(/^[0-9A-Fa-f]{32}$/) ? 'Account' : 'Profile'
return Err(new Error(`${type} '${accountOrProfile}' not found in ${configFilePath}`))
}