Files
dsh-infstarapi/scripts/stored-key.mjs
T
Coldsmile_7 c340aec110
CI / test (push) Canceled after 0s
release: dsh-infstarapi 0.2.0
2026-11-26 08:24:56 +08:00

35 lines
1.5 KiB
JavaScript

/** Read only the plugin-owned key record; never use a reference or ambient key. */
import { readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
import { parseDocument } from 'yaml'
import { Geek2APIKeyRing } from '../lib/index.js'
export async function readStoredKey({
filePath = join(process.env.DSH_HOME || join(homedir(), '.dsh'), '.credentials.yaml'),
label,
} = {}) {
let record
try {
const doc = parseDocument(readFileSync(filePath, 'utf8'), { prettyErrors: false, logLevel: 'silent' })
if (doc.errors.length) throw new Error('invalid credential document')
record = doc.toJS()?.records?.['infstarapi/keys']
} catch {
// YAML diagnostics can quote source lines containing secrets.
throw new Error('InfStarAPI plugin credentials could not be read safely')
}
const ring = new Geek2APIKeyRing({
readRecord: async id => id === 'infstarapi/keys' ? record : undefined,
modifyRecord: async () => { throw new Error('InfStarAPI live checks cannot change stored credentials') },
})
if (label !== undefined) {
const matches = (await ring.secrets()).filter(entry => entry.label === label && !entry.disabled)
if (matches.length !== 1) throw new Error('InfStarAPI live check needs one usable key with that label')
return matches[0].key
}
const active = await ring.activeKey()
if (active === undefined) throw new Error('InfStarAPI live check needs a usable key added under Settings → InfStarAPI')
return active.key
}