import { randomBytes } from 'node:crypto' import Computer from '#models/computer' /** * Generates a URL-safe, non-guessable share token. */ function generateShareToken(): string { return randomBytes(24).toString('base64url') } /** * Enables sharing for a computer, generating a share token if it doesn't * already have one. Idempotent: calling it again just updates the display * options without rotating the existing token. */ async function enableSharing( computer: Computer, options: { showSellPrice: boolean; showCost: boolean } ) { if (!computer.shareToken) { computer.shareToken = generateShareToken() } computer.shareEnabled = true computer.shareShowSellPrice = options.showSellPrice computer.shareShowCost = options.showCost await computer.save() return computer } /** * Disables sharing for a computer. The share token is kept so re-enabling * later doesn't require distributing a new link, but the public route only * resolves computers where shareEnabled is true. */ async function disableSharing(computer: Computer) { computer.shareEnabled = false await computer.save() return computer } /** * Rotates the share token, invalidating any previously distributed link. */ async function rotateShareToken(computer: Computer) { computer.shareToken = generateShareToken() await computer.save() return computer } export { enableSharing, disableSharing, rotateShareToken }