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' })
BF memory: a newer save brings its own bits, bits reach the account when you leave, room for them A project that comes in with the same circuit open (a newer save from another computer, a savegame restored in place, a shared link opened again) now runs from the bits it brings. Before, the running circuit went on with this computer's old bits and wrote them over the newer ones at the next save, and a savegame could not undo Power off and on. Bits changed only by buttons or a clock are sent to the account when the page is hidden or closed, when you leave the project, and before signing out, so they are no longer lost by "remove from this browser" and reach the other computer. A running clock alone still sends nothing. Bits alone keep the project's save time, so an edit saved on another computer wins over them and they end up in its savegames. What circuits hold has its own room of 500 KB per project on top of the 2 MB limit, in the browser, the account and share links. When it is full, the circuits left longest ago start from 0; a circuit that holds more than that on its own says so once. A project can no longer become too large to load because of its memory. A savegame opened as a copy saves the project it leaves first, like every other way of switching projects. Tests now run the editor itself (in a stand-in browser with an account server) for going into components and back, reloads, two projects, other computers, savegames, signing out and the room limit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:44:43 +00:00
if (raw.length > LIMITS.bytes + LIMITS.state) 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 })
}
}