logigate/server/utils/shares.ts

66 lines
2.5 KiB
TypeScript
Raw Permalink Normal View History

// Share links: projects stored as JSON files under data/shares, one per id.
// Whoever creates a link gets an edit key; only its hash is stored.
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
import type { H3Event } from 'h3'
import { LIMITS, toProject } from '../../app/lib/logic/project'
import type { Project } from '../../app/lib/logic/types'
export interface ShareRecord {
project: Project
keyHash: string
created: number
updated: number
}
const ALPHABET = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'
export function newShareId(length = 8): string {
return [...randomBytes(length)].map(b => ALPHABET[b % ALPHABET.length]).join('')
}
export const newEditKey = () => randomBytes(18).toString('base64url')
export const hashKey = (key: string) => createHash('sha256').update(key).digest('hex')
export const isShareId = (id: unknown): id is string => typeof id === 'string' && /^[A-Za-z0-9]{6,16}$/.test(id)
export const shareStorage = () => useStorage<ShareRecord>('shares')
export function keyMatches(key: string | undefined, hash: string): boolean {
if (!key) return false
const a = Buffer.from(hashKey(key))
const b = Buffer.from(hash)
return a.length === b.length && timingSafeEqual(a, b)
}
// Per-IP request budget, kept in memory. Enough to stop a script from
// filling the disk; resets when the container restarts.
const hits = new Map<string, { n: number; reset: number }>()
export function rateLimit(event: H3Event, bucket: string, max: number, windowMs: number) {
const now = Date.now()
if (hits.size > 10_000) for (const [k, h] of hits) if (h.reset < now) hits.delete(k)
const key = `${bucket}:${getRequestIP(event, { xForwardedFor: true }) ?? 'unknown'}`
const h = hits.get(key)
if (!h || h.reset < now) {
hits.set(key, { n: 1, reset: now + windowMs })
return
}
if (++h.n > max) throw createError({ statusCode: 429, message: 'Too many requests. Try again in a few minutes.' })
}
export async function readProjectBody(event: H3Event): Promise<Project> {
const raw = await readRawBody(event, 'utf8')
if (!raw) throw createError({ statusCode: 400, message: 'Empty request' })
if (raw.length > LIMITS.bytes) throw createError({ statusCode: 413, message: 'Project too large to share' })
let body: { project?: unknown }
try {
body = JSON.parse(raw)
} catch {
throw createError({ statusCode: 400, message: 'Not valid JSON' })
}
try {
return toProject(body.project)
} catch (e) {
throw createError({ statusCode: 400, message: (e as Error).message })
}
}