import { serve } from '@hono/node-server' import { Hono, type Context } from 'hono' import { logger } from 'hono/logger' import { HTTPException } from 'hono/http-exception' import { Agent } from '@atproto/api' import { TID } from '@atproto/common-web' import { appSessions, devices, hides, globalHides, hostSubs, nearFor, notifPrefs, placePrefs, type Place, REPORT_REASONS, reports, NOTIF_KINDS, type HideKind, type NotifPrefs, type PushEnv } from './db.ts' import { startNotifier } from './notifier.ts' import { apnsEnabled } from './apns.ts' import { fcmEnabled } from './fcm.ts' import { oauthClient, PORT, PUBLIC_URL, APP_CALLBACK, SCOPE, baseUrl } from './oauth.ts' import { AppviewError, EVENT, RSVP, appview, bskyProfile, typeahead, type RsvpStatus } from './appview.ts' type Env = { Variables: { did: string; agent: Agent; authServer: string } } import { privacyPage, supportPage } from './pages.ts' import { mountAdmin } from './admin.ts' const app = new Hono() app.use(logger()) app.onError((err, c) => { if (err instanceof HTTPException) return c.json({ error: err.message }, err.status) if (err instanceof AppviewError) return c.json({ error: err.message }, err.status === 404 ? 404 : 502) console.error(err) return c.json({ error: 'internal error' }, 500) }) // ---------- OAuth client metadata ---------- app.get('/', (c) => c.html(`Juno

Juno ✦

SupportPrivacy

`), ) app.get('/privacy', (c) => c.html(privacyPage)) app.get('/support', (c) => c.html(supportPage)) mountAdmin(app) app.get('/oauth-client-metadata.json', (c) => c.json(oauthClient.clientMetadata)) app.get('/jwks.json', (c) => c.json(oauthClient.jwks)) app.get('/health', (c) => c.text('ok')) // Checks the private-network hop to the appview too. app.get('/health/deep', async (c) => { try { return c.json({ server: 'ok', appview: await appview.stats() }) } catch (err) { return c.json({ server: 'ok', appview: String(err) }, 503) } }) // ---------- sign in ---------- const appRedirect = (params: Record) => `${APP_CALLBACK}?${new URLSearchParams(params)}` app.get('/oauth/login', async (c) => { // `create=1` sends people to bsky.social's sign-up flow; they come back signed in. const create = c.req.query('create') === '1' const handle = create ? 'https://bsky.social' : c.req.query('handle')?.trim().replace(/^@/, '') || 'https://bsky.social' // Adding a second account: `prompt=select_account` (or `login`) so the account host shows its // picker instead of silently signing the browser's current account back in. const asked = c.req.query('prompt') const prompt = create ? 'create' : asked === 'select_account' || asked === 'login' ? asked : undefined try { const url = await oauthClient.authorize(handle, { scope: SCOPE, prompt }) return c.redirect(url.toString()) } catch (err) { console.warn('authorize failed', err) return c.redirect(appRedirect({ error: `Couldn't find an account for “${handle}”` })) } }) app.get('/oauth/callback', async (c) => { const params = new URL(c.req.url).searchParams try { const { session } = await oauthClient.callback(params) const token = appSessions.create(session.did) return c.redirect(appRedirect({ token, did: session.did })) } catch (err) { console.warn('callback failed', err) return c.redirect(appRedirect({ error: params.get('error_description') ?? 'Sign in was cancelled' })) } }) // ---------- authenticated API ---------- /** Network trouble rather than a dead session: walks the error's cause chain. */ function isTransient(err: unknown): boolean { const transient = new Set(['FetchRequestError', 'OAuthResolverError', 'TimeoutError', 'AbortError']) for (let e: any = err, depth = 0; e && depth < 8; e = e.cause, depth++) { if (transient.has(e.name) || transient.has(e.constructor?.name)) return true if (e instanceof TypeError && /fetch failed/i.test(e.message)) return true if (typeof e.code === 'string' && /^(ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|UND_ERR)/.test(e.code)) return true } return false } const api = new Hono() api.use(async (c, next) => { const token = c.req.header('authorization')?.replace(/^Bearer\s+/i, '') const did = token ? appSessions.lookup(token) : undefined if (!did) throw new HTTPException(401, { message: 'signed out' }) try { const session = await oauthClient.restore(did) c.set('did', did) c.set('agent', new Agent(session)) c.set('authServer', session.serverMetadata.issuer) } catch (err) { console.warn('restore failed', did, err) // Couldn't reach the account's auth server (timeout, DNS, outage): keep everyone signed in and // let the app retry. Only a session the auth server has actually rejected signs people out. if (isTransient(err)) throw new HTTPException(503, { message: "Couldn't reach your account host. Try again in a moment." }) appSessions.revokeAllFor(did) throw new HTTPException(401, { message: 'session expired' }) } await next() }) api.get('/me', async (c) => c.json(await bskyProfile(c.get('did')))) // Where to manage the account itself (handle, password, deletion): the account host's own pages. api.get('/account', (c) => c.json({ manageUrl: new URL('/account', c.get('authServer')).toString() })) // Report an event. Stored for review; the event is also hidden for the reporter straight away. api.post('/reports', async (c) => { const body = await c.req.json<{ uri?: string; reason?: string; details?: string }>().catch(() => ({}) as any) const uri = typeof body.uri === 'string' && body.uri.startsWith('at://') ? body.uri : undefined const reason = REPORT_REASONS.find((r) => r === body.reason) if (!uri || !reason) throw new HTTPException(400, { message: 'uri (at://) and a valid reason are required' }) const subjectDid = uri.slice('at://'.length).split('/')[0] const details = typeof body.details === 'string' ? body.details.trim().slice(0, 2000) || undefined : undefined reports.add({ reporter: c.get('did'), uri, did: subjectDid, reason, details }) hides.add(c.get('did'), 'event', uri) return c.json(hides.list(c.get('did'))) }) api.post('/logout', async (c) => { const token = c.req.header('authorization')!.replace(/^Bearer\s+/i, '') const body = await c.req.json<{ deviceToken?: string }>().catch(() => ({}) as { deviceToken?: string }) if (body.deviceToken) devices.removeFor(body.deviceToken, c.get('did')) appSessions.revoke(token) await oauthClient.revoke(c.get('did')).catch(() => {}) return c.json({ ok: true }) }) // Accounts hidden by these people are treated as spam for everyone (still findable by search). const CURATORS = (process.env.CURATOR_DIDS ?? '').split(',').map((s) => s.trim()).filter((s) => s.startsWith('did:')) api.get('/feed', async (c) => { const did = c.get('did') const hidden = hides.list(did) const res = await appview.feed(did, c.req.query('cursor'), c.req.query('q') || undefined, { actors: hidden.actors, events: [...hidden.events, ...globalHides.list()], // admin-hidden events are gone for everyone curated: hides.curatedActors(CURATORS), near: nearFor(did), }) const events = new Set(hidden.events) const actors = new Set(hidden.actors) const visible = (e: { uri: string; did: string }) => !events.has(e.uri) && !actors.has(e.did) return c.json({ ...res, featured: res.featured.filter(visible), following: (res.following ?? []).filter(visible), nearby: res.nearby?.filter(visible), events: res.events.filter(visible), }) }) // ---------- places ("events near me") ---------- api.get('/places', (c) => c.json(placePrefs.get(c.get('did')))) /** Replace the account's places (home first). An empty list = onboarding skipped. */ api.put('/places', async (c) => { const body = await c.req.json<{ places?: { country?: string; cityId?: number }[] }>().catch(() => ({}) as { places?: undefined }) const input = (Array.isArray(body.places) ? body.places : []).slice(0, 10) if (!input.every((p) => typeof p?.country === 'string' && /^[A-Za-z]{2}$/.test(p.country) && (p.cityId === undefined || p.cityId === null || Number.isInteger(p.cityId)))) { throw new HTTPException(400, { message: 'places: [{ country: ISO-2, cityId?: GeoNames id }]' }) } const ids = input.flatMap((p) => (p.cityId ? [p.cityId] : [])) const cities = new Map((ids.length ? await appview.cities(ids) : []).map((ct) => [ct.id, ct])) const places: Place[] = [] for (const p of input) { const city = p.cityId ? cities.get(p.cityId) : undefined if (p.cityId && !city) throw new HTTPException(400, { message: `unknown city ${p.cityId}` }) const place: Place = { country: city?.country ?? p.country!.toUpperCase(), city } // No duplicates (the same city twice, or the same whole country twice). if (!places.some((q) => q.country === place.country && q.city?.id === place.city?.id)) places.push(place) } return c.json(placePrefs.set(c.get('did'), places)) }) /** "Use my location": the city at a coarse location. The coordinates aren't stored or logged. */ api.get('/places/nearest', async (c) => { const lat = Number(c.req.query('lat')) const lng = Number(c.req.query('lng')) if (!Number.isFinite(lat) || !Number.isFinite(lng)) throw new HTTPException(400, { message: 'lat, lng required' }) try { return c.json(await appview.cityAt(lat, lng)) } catch (err) { if (err instanceof AppviewError && err.status === 404) throw new HTTPException(404, { message: 'No city found near you' }) throw err } }) api.get('/places/cities', async (c) => { const country = c.req.query('country') return c.json(await appview.searchCities(c.req.query('q') ?? '', country && /^[A-Za-z]{2}$/.test(country) ? country : undefined)) }) // Hidden events / people. Your own RSVPs and hosting are never filtered. api.get('/hides', (c) => c.json(hides.list(c.get('did')))) const hideBody = async (c: Context) => { const { kind, subject } = await c.req.json<{ kind: HideKind; subject: string }>() const ok = (kind === 'event' && typeof subject === 'string' && subject.startsWith('at://')) || (kind === 'actor' && typeof subject === 'string' && subject.startsWith('did:')) if (!ok) throw new HTTPException(400, { message: 'kind must be event (at:// uri) or actor (did)' }) return { kind, subject } } api.put('/hides', async (c) => { const { kind, subject } = await hideBody(c) hides.add(c.get('did'), kind, subject) return c.json(hides.list(c.get('did'))) }) api.delete('/hides', async (c) => { const { kind, subject } = await hideBody(c) hides.remove(c.get('did'), kind, subject) return c.json(hides.list(c.get('did'))) }) api.get('/me/events', async (c) => { const did = c.get('did') const res = await appview.actorEvents(did, did) const byStart = (a: any, b: any) => (a.startsAt ?? '').localeCompare(b.startsAt ?? '') return c.json({ attending: res.attending.sort(byStart), hosting: res.hosting.sort(byStart) }) }) api.get('/event', async (c) => { const uri = c.req.query('uri') if (!uri?.startsWith('at://')) throw new HTTPException(400, { message: 'uri required' }) return c.json(await appview.event(uri, c.get('did'))) }) // ---------- writes ---------- api.post('/blob', async (c) => { const type = c.req.header('content-type') ?? 'image/jpeg' if (!type.startsWith('image/')) throw new HTTPException(400, { message: 'images only' }) const bytes = new Uint8Array(await c.req.arrayBuffer()) if (bytes.byteLength > 10_000_000) throw new HTTPException(413, { message: 'image too large' }) const res = await c.get('agent').com.atproto.repo.uploadBlob(bytes, { encoding: type }) return c.json({ blob: res.data.blob.toJSON() }) }) type EventInput = { name: string description?: string startsAt: string endsAt?: string mode?: 'inperson' | 'virtual' | 'hybrid' address?: { name?: string; street?: string; locality?: string; region?: string; postalCode?: string; country?: string } geo?: { latitude: number; longitude: number; name?: string } link?: { uri: string; name?: string } header?: { blob: unknown; width?: number; height?: number; alt?: string } vibe?: { palette?: number; emoji?: string } /** Edit only: keep the record's existing physical location(s) / header image untouched. */ keepPlace?: boolean keepHeader?: boolean } const LOCATION_PLACE_TYPES = ['community.lexicon.location.address', 'community.lexicon.location.geo', 'community.lexicon.location.fsq', 'community.lexicon.location.hthree'] function validateEventInput(input: EventInput) { if (!input.name?.trim() || Number.isNaN(Date.parse(input.startsAt))) { throw new HTTPException(400, { message: 'name and startsAt are required' }) } if (input.endsAt && Number.isNaN(Date.parse(input.endsAt))) throw new HTTPException(400, { message: 'bad endsAt' }) } /** New place locations from the input (address + geo). */ function placeLocations(input: EventInput): unknown[] { const out: unknown[] = [] if (input.address) out.push({ $type: 'community.lexicon.location.address', country: input.address.country ?? '', ...input.address }) if (input.geo) { out.push({ $type: 'community.lexicon.location.geo', latitude: String(input.geo.latitude), longitude: String(input.geo.longitude), name: input.geo.name, }) } return out } function headerMedia(header: NonNullable) { return { role: 'header', content: header.blob, alt: header.alt, aspect_ratio: header.width && header.height ? { width: Math.round(header.width), height: Math.round(header.height) } : undefined, } } api.post('/event', async (c) => { const input = await c.req.json() validateEventInput(input) const did = c.get('did') const agent = c.get('agent') const locations = [...placeLocations(input), ...(input.link ? [{ $type: `${EVENT}#uri`, ...input.link }] : [])] const record = { $type: EVENT, name: input.name.trim(), description: input.description?.trim() || undefined, createdAt: new Date().toISOString(), startsAt: new Date(input.startsAt).toISOString(), endsAt: input.endsAt ? new Date(input.endsAt).toISOString() : undefined, mode: `${EVENT}#${input.mode ?? 'inperson'}`, status: `${EVENT}#scheduled`, locations, uris: input.link ? [input.link] : undefined, media: input.header ? [headerMedia(input.header)] : undefined, rsvpExpected: true, // Juno extension: the colour palette + emoji the host picked. Other clients ignore it. juno: input.vibe, createdWith: baseUrl, } const rkey = TID.nextStr() const res = await agent.com.atproto.repo.putRecord({ repo: did, collection: EVENT, rkey, record, validate: false }) await appview.notify(res.data.uri) return c.json(await appview.event(res.data.uri, did)) }) /** * Edit an event in place (same rkey). Starts from the record as it is on the PDS, so * fields we don't manage — createdAt, status, other apps' extensions, extra media — survive. */ api.put('/event', async (c) => { const uri = c.req.query('uri') ?? '' const did = c.get('did') const agent = c.get('agent') const [, , repo, collection, rkey] = uri.split('/') if (repo !== did || collection !== EVENT || !rkey) throw new HTTPException(403, { message: 'not your event' }) const input = await c.req.json() validateEventInput(input) const current = await agent.com.atproto.repo.getRecord({ repo: did, collection: EVENT, rkey }) const existing = (current.data.value ?? {}) as Record const oldLocations: any[] = Array.isArray(existing.locations) ? existing.locations : [] const oldMedia: any[] = Array.isArray(existing.media) ? existing.media : [] const oldUris: any[] = Array.isArray(existing.uris) ? existing.uris : [] const oldOnline = oldLocations.find((l) => typeof l?.$type === 'string' && l.$type.endsWith('#uri'))?.uri // Physical place: replaced, kept, or cleared. Online link: always as sent. const places = input.address || input.geo ? placeLocations(input) : input.keepPlace ? oldLocations.filter((l) => LOCATION_PLACE_TYPES.includes(l?.$type) || (!l?.$type?.endsWith?.('#uri') && l?.name)) : [] const locations = [...places, ...(input.link ? [{ $type: `${EVENT}#uri`, ...input.link }] : [])] // Header image: replaced, kept, or removed. Other media roles are left alone. const otherMedia = oldMedia.filter((m) => m?.role !== 'header') const headers = input.header ? [headerMedia(input.header)] : input.keepHeader ? oldMedia.filter((m) => m?.role === 'header') : [] const media = [...headers, ...otherMedia] // Links: drop the previous online link, put the new one first, keep the rest. const uris = [ ...(input.link ? [input.link] : []), ...oldUris.filter((u) => u?.uri !== oldOnline && u?.uri !== input.link?.uri), ] const record = { ...existing, $type: EVENT, name: input.name.trim(), description: input.description?.trim() || undefined, startsAt: new Date(input.startsAt).toISOString(), endsAt: input.endsAt ? new Date(input.endsAt).toISOString() : undefined, mode: `${EVENT}#${input.mode ?? 'inperson'}`, locations, uris: uris.length ? uris : undefined, media: media.length ? media : undefined, juno: input.vibe ?? existing.juno, } const res = await agent.com.atproto.repo.putRecord({ repo: did, collection: EVENT, rkey, record, validate: false, swapRecord: current.data.cid, // don't clobber a concurrent edit from another app }) await appview.notify(res.data.uri) return c.json(await appview.event(res.data.uri, did)) }) api.delete('/event', async (c) => { const uri = c.req.query('uri') ?? '' const did = c.get('did') const [, , repo, collection, rkey] = uri.split('/') if (repo !== did || collection !== EVENT) throw new HTTPException(403, { message: 'not your event' }) await c.get('agent').com.atproto.repo.deleteRecord({ repo: did, collection: EVENT, rkey }) await appview.notify(uri).catch(() => {}) return c.json({ ok: true }) }) /** Find all of my RSVP records pointing at an event, straight from my PDS. */ async function myRsvpsFor(agent: Agent, did: string, subjectUri: string) { const found: string[] = [] let cursor: string | undefined for (let page = 0; page < 5; page++) { const res = await agent.com.atproto.repo.listRecords({ repo: did, collection: RSVP, limit: 100, cursor }) for (const r of res.data.records) { if ((r.value as any)?.subject?.uri === subjectUri) found.push(r.uri.split('/').pop()!) } cursor = res.data.cursor if (!cursor || res.data.records.length < 100) break } return found } api.put('/rsvp', async (c) => { const { eventUri, eventCid, status } = await c.req.json<{ eventUri: string eventCid: string status: RsvpStatus | null }>() if (!eventUri?.startsWith('at://') || !eventCid) throw new HTTPException(400, { message: 'eventUri and eventCid required' }) if (status && !['going', 'interested', 'notgoing'].includes(status)) throw new HTTPException(400, { message: 'bad status' }) const did = c.get('did') const agent = c.get('agent') const existing = await myRsvpsFor(agent, did, eventUri) const touched: string[] = [] if (status === null) { await Promise.all(existing.map((rkey) => agent.com.atproto.repo.deleteRecord({ repo: did, collection: RSVP, rkey }))) touched.push(...existing.map((rkey) => `at://${did}/${RSVP}/${rkey}`)) } else { const [keep, ...dupes] = existing const record = { $type: RSVP, status: `${RSVP}#${status}`, subject: { uri: eventUri, cid: eventCid }, createdAt: new Date().toISOString(), createdWith: baseUrl, } const put = await agent.com.atproto.repo.putRecord({ repo: did, collection: RSVP, rkey: keep ?? TID.nextStr(), record, validate: false, }) await Promise.all(dupes.map((rkey) => agent.com.atproto.repo.deleteRecord({ repo: did, collection: RSVP, rkey }))) touched.push(put.data.uri, ...dupes.map((rkey) => `at://${did}/${RSVP}/${rkey}`)) } if (touched.length) await appview.notify(...touched).catch((err) => console.warn('notify failed', err)) // Going/maybe subscribes you to the host's future events — unless you've explicitly opted out of them. if (status === 'going' || status === 'interested') hostSubs.autoSubscribe(did, eventUri.split('/')[2]) return c.json({ ok: true, status }) }) // ---------- profiles ---------- api.get('/profile', async (c) => { const actor = c.req.query('actor') ?? '' if (!actor.startsWith('did:')) throw new HTTPException(400, { message: 'actor (DID) required' }) const did = c.get('did') const [profile, events] = await Promise.all([bskyProfile(actor), appview.actorEvents(actor, did)]) const now = Date.now() - 3 * 3600_000 const soon = (e: any) => e.startsAt && Date.parse(e.startsAt) >= now const byStart = (a: any, b: any) => (a.startsAt ?? '').localeCompare(b.startsAt ?? '') const sub = hostSubs.get(did, actor) return c.json({ profile, hosting: events.hosting.filter(soon).sort(byStart), attending: events.attending.filter(soon).sort(byStart), notify: sub ? sub.subscribed === 1 : false, }) }) // ---------- notifications ---------- api.post('/devices', async (c) => { const { token, env, tz } = await c.req.json<{ token: string; env: PushEnv; tz?: string }>() // APNs tokens are hex; FCM registration tokens are long base64url-ish strings with a colon. const valid = env === 'fcm' ? /^[\w:-]{20,4096}$/.test(token ?? '') : ['sandbox', 'production'].includes(env) && /^[0-9a-f]{32,200}$/i.test(token ?? '') if (!valid) throw new HTTPException(400, { message: 'bad device token' }) devices.upsert({ token, env, did: c.get('did'), tz: tz || 'UTC' }) return c.json({ ok: true, delivering: env === 'fcm' ? fcmEnabled : apnsEnabled }) }) api.get('/notifications/prefs', (c) => c.json(notifPrefs.get(c.get('did')))) api.put('/notifications/prefs', async (c) => { const body = await c.req.json>() const clean = Object.fromEntries(Object.entries(body).filter(([k, v]) => (NOTIF_KINDS as readonly string[]).includes(k) && typeof v === 'boolean')) return c.json(notifPrefs.set(c.get('did'), clean)) }) /** Hosts you get "new event" pushes for (and ones you've turned off). */ api.get('/subscriptions', async (c) => { const subs = hostSubs.subscriptionsOf(c.get('did')).slice(0, 200) const profiles = await Promise.all(subs.map((s) => bskyProfile(s.host).catch(() => ({ did: s.host })))) return c.json({ hosts: subs.map((s, i) => ({ profile: profiles[i], notify: s.subscribed === 1 })) }) }) api.put('/subscriptions', async (c) => { const { host, notify } = await c.req.json<{ host: string; notify: boolean }>() if (!host?.startsWith('did:')) throw new HTTPException(400, { message: 'host (DID) required' }) hostSubs.setExplicit(c.get('did'), host, !!notify) return c.json({ host, notify: !!notify }) }) // Public: handle typeahead for the sign-in screen. app.get('/api/typeahead', async (c) => c.json({ actors: await typeahead(c.req.query('q') ?? '') })) app.route('/api', api) serve({ fetch: app.fetch, port: PORT, hostname: PUBLIC_URL ? '0.0.0.0' : '127.0.0.1' }, () => { console.log(`juno server on ${baseUrl}${PUBLIC_URL ? '' : ' (loopback OAuth client)'} — push ${apnsEnabled ? 'enabled' : 'dry-run'}`) }) startNotifier()