import { randomBytes } from 'node:crypto' import fs from 'node:fs' import path from 'node:path' import { JoseKey } from '@atproto/oauth-client-node' /** * Secrets the server can make for itself. Each is created once, saved in the data directory * (readable only by this user) and reused, so a deployment only has to provide the bot password. */ function readOrCreate(dataDir: string, name: string, create: () => string | Promise): string | Promise { const file = path.join(dataDir, name) if (fs.existsSync(file)) return fs.readFileSync(file, 'utf8').trim() fs.mkdirSync(dataDir, { recursive: true }) const write = (value: string) => { fs.writeFileSync(file, value, { mode: 0o600 }) console.log(`[secrets] created ${file}`) return value } const value = create() return typeof value === 'string' ? write(value) : value.then(write) } export function sessionSecret(dataDir: string): string { return readOrCreate(dataDir, 'session-secret', () => randomBytes(32).toString('hex')) as string } /** An ES256 private JWK for the confidential OAuth client (longer streamer sessions). */ export async function oauthPrivateJwk(dataDir: string): Promise { return readOrCreate(dataDir, 'oauth-private-jwk.json', async () => JSON.stringify((await JoseKey.generate(['ES256'], `key-${Date.now()}`)).privateJwk)) }