Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

credentials.ts

57 lines1.3 KB

1/**
2 * Credential storage for the modelschemas CLI:
3 * ~/.config/modelschemas/credentials.json, chmod 0600.
4 */
5import {
6 chmodSync,
7 existsSync,
8 mkdirSync,
9 readFileSync,
10 writeFileSync,
11} from 'node:fs'
12import { homedir } from 'node:os'
13import { join } from 'node:path'
14import type { JWK } from 'jose'
15​
16export interface AgentCredentials {
17 type: 'agent'
18 baseUrl: string
19 agentId: string
20 hostId: string
21 /** Ed25519 private key (JWK) used to mint per-request JWTs. */
22 privateKeyJwk: JWK
24​
25export interface ApiKeyCredentials {
26 type: 'api-key'
27 baseUrl: string
28 apiKey: string
30​
31export type Credentials = AgentCredentials | ApiKeyCredentials
32​
33export function credentialsPath(): string {
34 return join(
35 process.env.MODELSCHEMAS_CONFIG_DIR ??
36 join(homedir(), '.config', 'modelschemas'),
37 'credentials.json',
38 )
40​
41export function saveCredentials(credentials: Credentials): string {
42 const path = credentialsPath()
43 mkdirSync(join(path, '..'), { recursive: true })
44 writeFileSync(path, JSON.stringify(credentials, null, 2) + '\n')
45 chmodSync(path, 0o600)
46 return path
48​
49export function loadCredentials(): Credentials | null {
50 const path = credentialsPath()
51 if (!existsSync(path)) return null
52 try {
53 return JSON.parse(readFileSync(path, 'utf8')) as Credentials
54 } catch {
55 return null
56 }