'use client' import { useCallback, useEffect, useRef } from 'react' import Matter from 'matter-js' import { useFluxStore } from '@/store/useFluxStore' import { randomRange } from '@/lib/utils' interface DetectedBlock { x: number y: number width: number height: number area: number } interface UsePhysicsResult { canvasRef: React.RefObject initPhysics: (canvas: HTMLCanvasElement) => void cleanup: () => void updateDetectedBlocks: (blocks: DetectedBlock[]) => void spawnBall: () => void clearBalls: () => void } export function usePhysics(): UsePhysicsResult { const canvasRef = useRef(null) const engineRef = useRef(null) const renderRef = useRef(null) const runnerRef = useRef(null) const blocksRef = useRef([]) const ballsRef = useRef([]) const spawnIntervalRef = useRef(null) const { spawnMode, spawnInterval, spawnPositionX, bounciness, gravity, ballSize, boxOpacity, showDetection, isStreaming, } = useFluxStore() const initPhysics = useCallback((canvas: HTMLCanvasElement) => { canvasRef.current = canvas // Clean up existing if (runnerRef.current) Matter.Runner.stop(runnerRef.current) if (renderRef.current) Matter.Render.stop(renderRef.current) if (engineRef.current) { Matter.World.clear(engineRef.current.world, false) Matter.Engine.clear(engineRef.current) } const engine = Matter.Engine.create({ gravity: { x: 0, y: gravity } }) const render = Matter.Render.create({ canvas, engine, options: { width: canvas.width, height: canvas.height, wireframes: false, background: 'transparent', }, }) // Walls const wallThickness = 50 Matter.Composite.add(engine.world, [ Matter.Bodies.rectangle(-wallThickness / 2, canvas.height / 2, wallThickness, canvas.height * 2, { isStatic: true, render: { visible: false } }), Matter.Bodies.rectangle(canvas.width + wallThickness / 2, canvas.height / 2, wallThickness, canvas.height * 2, { isStatic: true, render: { visible: false } }), ]) const runner = Matter.Runner.create() Matter.Render.run(render) Matter.Runner.run(runner, engine) 'use client' import { useCallback, useRef, useEffect, useState } from 'react' import { useFluxStore } from '@/store/useFluxStore' import { getWebcamConstraints } from '@/lib/utils' interface UseWebcamResult { videoRef: React.RefObject startWebcam: () => Promise stopWebcam: () => void switchCamera: (deviceId: string) => Promise refreshCameras: () => Promise error: string | null } export function useWebcam(): UseWebcamResult { const videoRef = useRef(null) const streamRef = useRef(null) const [error, setError] = useState(null) const { selectedCamera, webcamQuality, setStreaming, setSelectedCamera, setAvailableCameras, } = useFluxStore() const refreshCameras = useCallback(async () => { try { // Request permission first to get full device list await navigator.mediaDevices.getUserMedia({ video: true, audio: false }) const devices = await navigator.mediaDevices.enumerateDevices() const cameras = devices.filter((d) => d.kind === 'videoinput') setAvailableCameras(cameras) // Select first camera if none selected if (!selectedCamera && cameras.length > 0) { setSelectedCamera(cameras[0].deviceId) } } catch (err) { console.error('Failed to enumerate cameras:', err) setError('Camera access denied') } }, [selectedCamera, setAvailableCameras, setSelectedCamera]) const stopWebcam = useCallback(() => { if (streamRef.current) { streamRef.current.getTracks().forEach((track) => track.stop()) streamRef.current = null } if (videoRef.current) { videoRef.current.srcObject = null } setStreaming(false) setError(null) }, [setStreaming]) const startWebcam = useCallback(async () => { setError(null) stopWebcam() try { const constraints = getWebcamConstraints(webcamQuality, selectedCamera) const stream = await navigator.mediaDevices.getUserMedia(constraints) if (videoRef.current) { videoRef.current.srcObject = stream await videoRef.current.play() streamRef.current = stream setStreaming(true) // Log actual video settings const track = stream.getVideoTracks()[0] const settings = track.getSettings() console.log('Webcam started with settings:', { width: settings.width, height: settings.height, frameRate: settings.frameRate, deviceId: settings.deviceId, 'use client' import { useEffect, useRef, useCallback } from 'react' import { useFluxStore } from '@/store/useFluxStore' import { cn } from '@/lib/utils' interface CanvasProps { videoRef: React.RefObject physicsCanvasRef: React.RefObject onResize?: (width: number, height: number) => void } export function Canvas({ videoRef, physicsCanvasRef, onResize }: CanvasProps) { const containerRef = useRef(null) const backgroundCanvasRef = useRef(null) const animationFrameRef = useRef(undefined) const { isStreaming, showBackground, videoRotation, flipHorizontal, flipVertical, } = useFluxStore() useEffect(() => { const handleResize = () => { if (!containerRef.current) return const { width, height } = containerRef.current.getBoundingClientRect() if (backgroundCanvasRef.current) { backgroundCanvasRef.current.width = width backgroundCanvasRef.current.height = height } if (physicsCanvasRef.current) { physicsCanvasRef.current.width = width physicsCanvasRef.current.height = height } onResize?.(width, height) } handleResize() window.addEventListener('resize', handleResize) return () => window.removeEventListener('resize', handleResize) }, [physicsCanvasRef, onResize]) const renderBackground = useCallback(() => { if (!backgroundCanvasRef.current || !videoRef.current || !isStreaming || !showBackground) { return } const canvas = backgroundCanvasRef.current const ctx = canvas.getContext('2d') const video = videoRef.current if (!ctx || video.readyState < 2) return ctx.save() ctx.fillStyle = '#0B0B0C' ctx.fillRect(0, 0, canvas.width, canvas.height) const centerX = canvas.width / 2 const centerY = canvas.height / 2 ctx.translate(centerX, centerY) ctx.rotate((videoRotation * Math.PI) / 180) ctx.scale(flipHorizontal ? -1 : 1, flipVertical ? -1 : 1) const videoAspect = video.videoWidth / video.videoHeight const canvasAspect = canvas.width / canvas.height const effectiveCanvasAspect = videoRotation === 90 || videoRotation === 270 ? canvas.height / canvas.width : canvasAspect let drawWidth: number let drawHeight: number if (videoAspect > effectiveCanvasAspect) { drawHeight = canvas.height drawWidth = drawHeight * videoAspect } else { drawWidth = canvas.width /** * End-to-end encryption for ArcJournal, built on WebCrypto only. * * Every journal has one random 256-bit AES-GCM key (the journal key). Entries * are sealed with it on the device before they are sent. The server keeps the * journal key twice, never in the clear: * - wrapped by a key derived from the passphrase (PBKDF2-SHA256), and * - wrapped by the recovery key, 32 random bytes shown to the user once. * Losing both means nobody, including Arcnode, can read the journal again. */ const subtle = globalThis.crypto.subtle; const encoder = new TextEncoder(); const decoder = new TextDecoder(); export const KDF_ITERATIONS = 600_000; const VAULT_VERSION = 1; const AAD_PASSPHRASE = encoder.encode('arcjournal:vault:v1:passphrase'); const AAD_RECOVERY = encoder.encode('arcjournal:vault:v1:recovery'); export class WrongSecretError extends Error { constructor(message = 'That passphrase or recovery key is not right') { super(message); this.name = 'WrongSecretError'; } } // ── Encoding ────────────────────────────────────────────── export function toBase64(bytes) { const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes); let binary = ''; for (let i = 0; i < view.length; i += 0x8000) { binary += String.fromCharCode.apply(null, view.subarray(i, i + 0x8000)); } return btoa(binary); } export function fromBase64(text) { const binary = atob(text); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); return bytes; } function random(length) { return globalThis.crypto.getRandomValues(new Uint8Array(length)); } // Crockford base32: no I, L, O or U, so a written-down key is hard to misread. const ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; export function formatRecoveryKey(bytes) { let bits = 0; let value = 0; let out = ''; for (const byte of bytes) { value = (value << 8) | byte; bits += 8; while (bits >= 5) { out += ALPHABET[(value >>> (bits - 5)) & 31]; bits -= 5; } } if (bits > 0) out += ALPHABET[(value << (5 - bits)) & 31]; return out.match(/.{1,4}/g).join('-'); } export function parseRecoveryKey(text) { const clean = String(text) .toUpperCase() .replace(/[\s-]/g, '') .replace(/[IL]/g, '1') .replace(/O/g, '0'); if (clean.length !== 52 || [...clean].some((c) => !ALPHABET.includes(c))) { throw new WrongSecretError('A recovery key has 52 letters and numbers'); } let bits = 0; let value = 0; const bytes = []; /** * Automatic updates from GitHub Releases, on every platform. * * - Windows: Squirrel downloads updates in the background from * update.electronjs.org; they apply on restart. * - macOS: the app is not signed, so Squirrel.Mac cannot be used. The app * downloads the new universal zip itself, checks it against the release's * SHA256SUMS, and swaps the .app bundle after it quits. * - Linux zip: the same, swapping the app's folder. * - Linux .deb / .rpm: the new package is downloaded and checked, then * installed with pkexec, which asks for the user's password. * * Downloads start by themselves; the renderer shows progress and a button to * restart (or install) once the update is ready. When an update cannot be * applied automatically, the button opens the release page instead. */ const fs = require('fs'); const os = require('os'); const path = require('path'); const crypto = require('crypto'); const { spawn, execFile } = require('child_process'); const { Readable } = require('stream'); const { pipeline } = require('stream/promises'); const { app, autoUpdater, shell } = require('electron'); const { repository } = require('../package.json'); const { newer, installKind, pickAsset, parseSums, verifySums } = require('./update-plan'); const REPO = repository.url.replace(/^.*github\.com\//, '').replace(/\.git$/, ''); const CHECK_EVERY = 6 * 60 * 60 * 1000; const HEADERS = () => ({ Accept: 'application/vnd.github+json', 'User-Agent': `ArcJournal/${app.getVersion()}` }); let send = () => {}; let state = null; // { version, status: downloading|ready|manual, percent?, action?, url? } let staged = null; // what install() applies let busy = false; function update(next) { state = next; send('update-available', state); } const install = { kind: 'manual' }; function writable(dir) { try { fs.accessSync(dir, fs.constants.W_OK); return true; } catch { return false; } } async function download(url, file, onProgress) { const res = await fetch(url, { headers: { 'User-Agent': HEADERS()['User-Agent'] }, redirect: 'follow' }); if (!res.ok || !res.body) throw new Error(`Download failed (${res.status})`); const total = Number(res.headers.get('content-length')) || 0; let received = 0; const hash = crypto.createHash('sha256'); const body = Readable.fromWeb(res.body); body.on('data', (chunk) => { received += chunk.length; hash.update(chunk); if (total) onProgress(Math.round((received / total) * 100)); }); await pipeline(body, fs.createWriteStream(file)); return hash.digest('hex'); } function run(cmd, args) { return new Promise((resolve, reject) => { execFile(cmd, args, { maxBuffer: 1024 * 1024 }, (err, stdout) => (err ? reject(err) : resolve(stdout))); }); } async function checkGitHub() { const res = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, { headers: HEADERS(), signal: AbortSignal.timeout(15000), }); if (!res.ok) return; /** * "Sign in with Arcnode" for a desktop app: OAuth 2.0 authorization code flow * with PKCE through the system browser (RFC 8252). ArcJournal is a public * client, so it has no secret; the browser redirects back to a one-off server * on 127.0.0.1. The refresh token is kept encrypted with the OS keychain * (safeStorage) and never reaches the renderer. */ const http = require('http'); const crypto = require('crypto'); const { shell } = require('electron'); const secrets = require('./secrets'); const { arcnode } = require('../package.json'); const ISSUER = process.env.ARCNODE_ISSUER || arcnode.issuer; const CLIENT_ID = process.env.ARCJOURNAL_CLIENT_ID || arcnode.clientId; // Backboard matches redirect URIs exactly; the second port is the fallback. const PORTS = arcnode.redirectPorts; const SCOPE = 'openid profile email'; const SIGN_IN_TIMEOUT = 5 * 60 * 1000; const SESSION = 'arcnode-session'; const b64url = (buf) => buf.toString('base64url'); let access = null; // { token, expiresAt } let refreshing = null; let pending = null; // the sign-in waiting for the browser class AuthError extends Error {} async function tokenRequest(params) { const res = await fetch(`${ISSUER}/oauth/token`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ client_id: CLIENT_ID, ...params }), signal: AbortSignal.timeout(15000), }); const body = await res.json().catch(() => ({})); if (!res.ok) { const err = new AuthError(body.error_description || 'Sign-in failed'); err.code = body.error; throw err; } return body; } function store(tokens) { access = { token: tokens.access_token, expiresAt: Date.now() + (tokens.expires_in || 3600) * 1000 }; if (tokens.refresh_token) secrets.write(SESSION, tokens.refresh_token); } function listen(server) { return new Promise((resolve, reject) => { let i = 0; const tryNext = () => { if (i >= PORTS.length) return reject(new AuthError('Close other apps signing in to Arcnode and try again.')); const port = PORTS[i++]; server.once('error', tryNext); server.listen(port, '127.0.0.1', () => { server.off('error', tryNext); resolve(port); }); }; tryNext(); }); } const page = (title, text) => `${title}

${title}

${text}

`; /** Opens the browser and resolves once the user approved ArcJournal. */ async function signIn() { if (!CLIENT_ID) throw new AuthError('This build of ArcJournal has no Arcnode client ID.'); cancel(); const verifier = b64url(crypto.randomBytes(32)); const challenge = b64url(crypto.createHash('sha256').update(verifier).digest()); const state = b64url(crypto.randomBytes(16)); import { TreeNode, ZipEntryItem } from "./types"; type MutableTreeNode = TreeNode & { childrenMap?: Map; }; export function buildTree(entries: ZipEntryItem[]): TreeNode { const root: MutableTreeNode = { name: "", path: "", type: "folder", children: [], childrenMap: new Map(), }; for (const entry of entries) { const cleanPath = entry.path.replace(/\/$/, ""); if (!cleanPath) continue; const parts = cleanPath.split("/"); let current = root; let currentPath = ""; parts.forEach((part, index) => { currentPath = currentPath ? `${currentPath}/${part}` : part; const isLast = index === parts.length - 1; const shouldBeFile = isLast && !entry.isDir; if (!current.childrenMap?.has(part)) { const node: MutableTreeNode = { name: part, path: currentPath, type: shouldBeFile ? "file" : "folder", children: [], childrenMap: new Map(), entry: shouldBeFile ? entry : undefined, }; current.childrenMap?.set(part, node); current.children.push(node); } const nextNode = current.childrenMap?.get(part); if (!nextNode) return; if (shouldBeFile) { nextNode.type = "file"; nextNode.entry = entry; } current = nextNode; }); } sortTree(root); cleanupTree(root); return root; } function sortTree(node: MutableTreeNode) { node.children.sort((a, b) => { if (a.type !== b.type) return a.type === "folder" ? -1 : 1; return a.name.localeCompare(b.name); }); node.children.forEach((child) => sortTree(child as MutableTreeNode)); } function cleanupTree(node: MutableTreeNode) { delete node.childrenMap; node.children.forEach((child) => cleanupTree(child as MutableTreeNode)); } export function filterTree(node: TreeNode, query: string): TreeNode | null { if (!query) return node; if (node.type === "file") { return node.path.toLowerCase().includes(query) ? node : null; } export const TEXT_EXTENSIONS = new Set([ "txt", "md", "csv", "log", "xml", "html", "htm", "css", "js", "mjs", "cjs", "ts", "tsx", "jsx", "py", "java", "cs", "cpp", "c", "h", "hpp", "php", "rb", "go", "rs", "swift", "kt", "sql", "yaml", "yml", "ini", "env", "toml", "sh", "bat", "ps1", "json", ]); export const IMAGE_EXTENSIONS = new Set([ "png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", ]); export const VIDEO_EXTENSIONS = new Set(["mp4", "webm", "ogg", "mov", "m4v"]); export const AUDIO_EXTENSIONS = new Set(["mp3", "wav", "ogg", "m4a", "aac", "flac"]); export const PDF_EXTENSIONS = new Set(["pdf"]); export function getBaseName(path: string) { const clean = path.replace(/\/$/, ""); const parts = clean.split("/"); return parts[parts.length - 1] || clean; } export function getExtension(path: string) { const name = getBaseName(path); const idx = name.lastIndexOf("."); return idx === -1 ? "" : name.slice(idx + 1).toLowerCase(); } export function detectFileKind(ext: string) { if (IMAGE_EXTENSIONS.has(ext)) return "image"; if (VIDEO_EXTENSIONS.has(ext)) return "video"; if (AUDIO_EXTENSIONS.has(ext)) return "audio"; if (PDF_EXTENSIONS.has(ext)) return "pdf"; if (ext === "json") return "json"; if (TEXT_EXTENSIONS.has(ext)) return "text"; return "unknown"; } export function getMimeType(ext: string) { const map: Record = { png: "image/png", // Draws the profile cards as SVG files, so the README needs no outside // widgets: a neofetch-style card with an ASCII portrait, and a heatmap of the // last year of contributions. Runs daily from .github/workflows/profile.yml. // // GITHUB_TOKEN=... node scripts/generate.mjs [outDir] // // Writes card-dark.svg, card-light.svg, heatmap-dark.svg and heatmap-light.svg. import { readFile, writeFile, mkdir } from 'node:fs/promises'; import { pathToFileURL } from 'node:url'; const LOGIN = 'stinoooo'; const BORN = '2002-10-09'; const out = process.argv[2] || 'dist'; // Everything here is said by hand and kept true; the numbers come from GitHub. const PROFILE = { name: 'stijn', host: 'the Netherlands', role: 'software engineering student', languages: 'TypeScript, JavaScript, Rust, PHP, Python, GDScript, SQL', web: 'Next.js, React, Tailwind CSS, Motion, Zustand, React Hook Form', backend: 'Node.js, Express, Hono, Zod, Prisma, WordPress', desktop: 'Tauri, Electron, Electron Forge, Vite', games: 'Godot 4, Blender (models built in Python), synthesized sound', bots: 'discord.js, discord.py', data: 'PostgreSQL, MySQL, MongoDB, Redis, Upstash, Cloudflare R2', testing: 'Vitest, Playwright, node:test', ships: 'Vercel, Railway, Cloudflare, Docker, GitHub Actions', tools: 'Turborepo, Sentry, ESLint, Prettier, Git', learning: 'Java for school, deeper Rust, Godot shaders, how LLMs work', into: 'games, desktop apps, AI', making: 'Exit Only, Arcnode Games', shipped: 'ArcJournal 2.0, Exit Only 0.5.0, Arcnode Games 0.1.0', dog: 'Banjer, head of quality assurance', }; const THEMES = { dark: { bg: '#1f1a17', border: '#3a302a', text: '#f3e7d9', muted: '#a8968a', key: '#f4a261', accent: '#e9c46a', rule: '#4a3d34', cells: ['#2b241f', '#5c3a22', '#9a5a2c', '#d9822b', '#f6b26b'], }, light: { bg: '#fbf5ec', border: '#eadccb', text: '#3d2f25', muted: '#8a7462', key: '#c4622d', accent: '#b5832a', rule: '#e6d6c3', cells: ['#efe4d6', '#f6cfa1', '#eda564', '#d9782f', '#a8501c'], }, }; const FONT = "ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, 'Liberation Mono', monospace"; const esc = (s) => String(s).replace(/&/g, '&').replace(//g, '>'); async function github(query) { const token = process.env.GITHUB_TOKEN; if (!token) throw new Error('GITHUB_TOKEN is not set'); const res = await fetch('https://api.github.com/graphql', { method: 'POST', headers: { Authorization: `bearer ${token}`, 'Content-Type': 'application/json', 'User-Agent': LOGIN }, body: JSON.stringify({ query }), }); const body = await res.json(); if (!res.ok || body.errors) throw new Error(JSON.stringify(body.errors || body)); return body.data; } function uptime(today = new Date()) { const born = new Date(`${BORN}T00:00:00Z`); let years = today.getUTCFullYear() - born.getUTCFullYear(); let months = today.getUTCMonth() - born.getUTCMonth(); let days = today.getUTCDate() - born.getUTCDate(); if (days < 0) { months -= 1; days += new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), 0)).getUTCDate(); } if (months < 0) { years -= 1; months += 12; } const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`; return `${plural(years, 'year')}, ${plural(months, 'month')}, ${plural(days, 'day')}`; } // The portrait sits on its own dark panel in both themes: colored ASCII // Builds the Rosa product icon font from the line drawings in icons/product. // A font only keeps filled shapes, so each drawing is traced to an outline // first. Writes fonts/rosa-icons.woff and product-icons.json, points the // rosa-sprout icon in package.json at the sauropod, and draws icon.png from // the sprout sprite. // // Run: node build-icons.mjs (needs the devDependencies in package.json) import { createReadStream, createWriteStream, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import SVGFixer from 'oslllo-svg-fixer'; import { SVGIcons2SVGFontStream } from 'svgicons2svgfont'; import svg2ttf from 'svg2ttf'; import ttf2woff from 'ttf2woff'; import { Resvg } from '@resvg/resvg-js'; const here = dirname(fileURLToPath(import.meta.url)); const source = join(here, 'icons', 'product'); const traced = join(here, '.traced'); // Drawing file -> the VS Code icon ids it replaces. const ICONS = { explorer: ['explorer-view-icon'], search: ['search-view-icon'], 'source-control': ['source-control-view-icon'], run: ['run-view-icon'], extensions: ['extensions-view-icon'], testing: ['testing-view-icon'], remote: ['remote-explorer-view-icon'], account: ['accounts-view-bar-icon'], settings: ['settings-view-bar-icon'], }; rmSync(traced, { recursive: true, force: true }); mkdirSync(traced, { recursive: true }); await SVGFixer(source, traced, { showProgressBar: false, traceResolution: 1200 }).fix(); const glyphs = readdirSync(traced).filter((f) => f.endsWith('.svg')).sort(); const names = glyphs.map((f) => f.replace(/\.svg$/, '')); for (const name of Object.keys(ICONS)) { if (!names.includes(name)) throw new Error(`No drawing for ${name}`); } for (const name of ['account', 'egg']) { if (!names.includes(name)) throw new Error(`No drawing for the status bar ${name}`); } const svgFont = await new Promise((resolve, reject) => { const chunks = []; const stream = new SVGIcons2SVGFontStream({ fontName: 'rosa-icons', fontHeight: 1000, normalize: true, log: () => {} }); stream.on('data', (c) => chunks.push(c)).on('end', () => resolve(chunks.map(String).join(""))).on('error', reject); names.forEach((name, i) => { const glyph = createReadStream(join(traced, `${name}.svg`)); glyph.metadata = { name, unicode: [String.fromCodePoint(0xe000 + i)] }; stream.write(glyph); }); stream.end(); }); const ttf = svg2ttf(svgFont, {}); mkdirSync(join(here, 'fonts'), { recursive: true }); writeFileSync(join(here, 'fonts', 'rosa-icons.woff'), Buffer.from(ttf2woff(new Uint8Array(ttf.buffer)).buffer)); // VS Code wants the code point written as a backslash and hex, like "\e000". const glyphCode = (i) => `\\${(0xe000 + i).toString(16)}`; const iconDefinitions = {}; names.forEach((name, i) => { for (const id of ICONS[name] ?? []) { iconDefinitions[id] = { fontCharacter: glyphCode(i) }; } }); const theme = { fonts: [{ id: 'rosa-icons', src: [{ path: './fonts/rosa-icons.woff', format: 'woff' }], weight: 'normal', style: 'normal' }], iconDefinitions, }; writeFileSync(join(here, 'product-icons.json'), `${JSON.stringify(theme, null, 2)}\n`); rmSync(traced, { recursive: true, force: true }); // The status bar shows the egg until it hatches, then the account sauropod. const pkgPath = join(here, 'package.json');