OverviewFilesCommitsIssuesDocsReleasesPeers

pgh / lib / commands / token.js

54 lines · javascript ref:
/** pgh token list|create|revoke — personal access tokens for HTTPS git push */

export const usage = `pgh token — personal access tokens (HTTPS git push/clone)

  pgh token list                                List your active tokens
  pgh token create [--name <n>] [--scope write|read] [--ttl-days <d>] [--no-expiry]
                                                Mint a token (default: write, 90 days).
                                                The secret is shown ONCE — copy it now.
  pgh token revoke <tok:...>                    Revoke a token by its id

Over UDS (the local daemon) the token is minted for the daemon OWNER.
Use the token as the PASSWORD for HTTPS git:
  git clone https://<host>/git/<repo>.git
  Username: <anything>   Password: <the pgv3_… token>`

function parseFlags (args) {
  const out = { scope: 'write' }
  for (let i = 0; i < args.length; i++) {
    const a = args[i]
    if (a === '--name' && args[i + 1]) { out.name = args[++i]; continue }
    if (a === '--scope' && args[i + 1]) { out.scope = args[++i]; continue }
    if (a === '--ttl-days' && args[i + 1]) { out.ttlDays = parseInt(args[++i], 10); continue }
    if (a === '--no-expiry') { out.ttlDays = 0; continue }
  }
  return out
}

export async function run (client, args) {
  const sub = args[0] || 'list'

  if (sub === 'list') {
    return client.call('list-access-tokens', {})
  }

  if (sub === 'create') {
    const f = parseFlags(args.slice(1))
    if (f.scope !== 'write' && f.scope !== 'read') {
      throw new Error('--scope must be "write" or "read"')
    }
    const params = { name: f.name, scope: f.scope }
    if (typeof f.ttlDays === 'number' && !Number.isNaN(f.ttlDays)) params.ttlDays = f.ttlDays
    return client.call('create-access-token', params)
  }

  if (sub === 'revoke') {
    const id = args[1]
    if (!id) throw new Error('usage: pgh token revoke <tok:…>')
    if (id.indexOf('tok:') !== 0) throw new Error('token id must look like "tok:<hash>" (see `pgh token list`)')
    return client.call('revoke-access-token', { identityId: id })
  }

  throw new Error('unknown token subcommand: ' + sub + '\n\n' + usage)
}