Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

4.5 KB
Raw Blame
import * as p from '@clack/prompts'
import type { Command } from 'commander'
import { printTable } from 'console-table-printer'
import pc from 'picocolors'
import { spreeTask } from '../backend.js'
import { mintApiKey } from '../config.js'
import { detectProject } from '../context.js'
import { captureTask } from '../docker.js'

export function registerApiKeyCommand(program: Command): void {
  const apiKey = program.command('api-key').description('Manage API keys')

  apiKey
    .command('create')
    .description('Create an API key')
    .option('--name <name>', 'key name')
    .option('--type <type>', 'key type: publishable or secret')
    .option(
      '--scopes <scopes>',
      'comma-separated scopes for secret keys (e.g. read_all or read_orders,write_products)',
    )
    .action(async (flags: { name?: string; type?: string; scopes?: string }) => {
      const ctx = detectProject()

      let name = flags.name
      let keyType = flags.type
      let scopes = flags.scopes

      if (!name) {
        const result = await p.text({
          message: 'Key name:',
          placeholder: 'My Storefront',
          validate(value) {
            if (!value) return 'Name is required'
            return undefined
          },
        })
        if (p.isCancel(result)) {
          p.cancel('Cancelled.')
          process.exit(0)
        }
        name = result
      }

      if (!keyType) {
        const result = await p.select({
          message: 'Key type:',
          options: [
            { value: 'publishable', label: 'Publishable (for storefronts)' },
            { value: 'secret', label: 'Secret (for server-to-server)' },
          ],
        })
        if (p.isCancel(result)) {
          p.cancel('Cancelled.')
          process.exit(0)
        }
        keyType = result as string
      }

      if (keyType !== 'publishable' && keyType !== 'secret') {
        throw new Error('Key type must be "publishable" or "secret".')
      }

      // Secret keys require at least one scope (server-side validation).
      if (keyType === 'secret' && !scopes) {
        const result = await p.text({
          message: 'Scopes (comma-separated):',
          placeholder: 'read_all',
          initialValue: 'read_all',
          validate(value) {
            if (!value) return 'Secret keys require at least one scope'
            return undefined
          },
        })
        if (p.isCancel(result)) {
          p.cancel('Cancelled.')
          process.exit(0)
        }
        scopes = result
      }

      const s = p.spinner()
      s.start('Creating API key...')

      const token = await mintApiKey(ctx.projectDir, {
        name,
        keyType,
        scopes:
          keyType === 'secret' && scopes ? scopes.split(',').map((scope) => scope.trim()) : [],
      })

      s.stop('API key created.')

      const lines = [
        `${pc.bold('Name:')}  ${name}`,
        `${pc.bold('Type:')}  ${keyType}`,
        `${pc.bold('Token:')} ${pc.cyan(token)}`,
      ]

      if (keyType === 'secret') {
        lines.push(`${pc.bold('Scopes:')} ${scopes}`)
        lines.push('')
        lines.push(pc.yellow('Save this token now — secret keys cannot be retrieved later.'))
      }

      p.note(lines.join('\n'), 'API Key')
    })

  apiKey
    .command('list')
    .description('List API keys')
    .action(async () => {
      const ctx = detectProject()

      const s = p.spinner()
      s.start('Fetching API keys...')

      const stdout = await captureTask(spreeTask('cli:list_api_keys'), ctx.projectDir)
      s.stop('')

      const lines = stdout.trim().split('\n').filter(Boolean)

      if (lines.length === 0) {
        p.log.info('No API keys found.')
        return
      }

      const rows = lines.map((line) => {
        const [id, name, type, token, created, status] = line.split('|')
        return {
          ID: id ?? '',
          Name: name ?? '',
          Type: type ?? '',
          Token: token ?? '',
          Created: created ?? '',
          Status: status === 'active' ? pc.green(status) : pc.red(status ?? ''),
        }
      })

      printTable(rows)
    })

  apiKey
    .command('revoke')
    .description('Revoke an API key')
    .argument('<id>', 'ID of the key to revoke (from api-key list)')
    .action(async (id: string) => {
      const ctx = detectProject()

      const s = p.spinner()
      s.start('Revoking API key...')

      const stdout = await captureTask(spreeTask('cli:revoke_api_key'), ctx.projectDir, {
        ID: id,
      })
      const name = stdout.trim()

      s.stop(`API key "${name}" revoked.`)
    })
}