Files
git-forge-plugin/credential-helper.mjs

32 lines
1.3 KiB
JavaScript

#!/usr/bin/env node
// git credential helper: answers `get` with the token of a gh / tea-cli account
// whose host matches the request. Prints nothing (git falls through) otherwise.
import { listAccounts } from './forge.mjs'
const op = process.argv[2]
if (op !== 'get') process.exit(0)
let input = ''
process.stdin.setEncoding('utf8')
for await (const chunk of process.stdin) input += chunk
const req = {}
for (const line of input.split('\n')) {
const i = line.indexOf('=')
if (i > 0) req[line.slice(0, i)] = line.slice(i + 1)
}
if (!req.host || (req.protocol && !/^https?$/.test(req.protocol))) process.exit(0)
const accounts = await listAccounts().catch(() => [])
const host = req.host.toLowerCase()
const owner = (req.path || '').split('/')[0]?.toLowerCase()
const matches = accounts.filter((a) => a.host.toLowerCase() === host || a.host.split(':')[0].toLowerCase() === host)
const want = req.username?.toLowerCase()
const acct = (want && matches.find((a) => a.user.toLowerCase() === want))
|| (owner && matches.find((a) => a.user.toLowerCase() === owner))
|| matches.find((a) => a.active !== false)
|| matches[0]
if (!acct) process.exit(0)
const username = acct.kind === 'github' ? 'x-access-token' : (acct.user || 'oauth2')
process.stdout.write(`username=${username}\npassword=${acct.token}\n`)