From acec775b05ba59fe708d54c40b15d5e258baccd0 Mon Sep 17 00:00:00 2001 From: botandbang <337765928+botandbang@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:58:04 -0600 Subject: [PATCH 01/22] feat(web): roll inbox email, dms and userinput.app reports out behind flags Adds three ops flags named for the on state: inboxEmail, inboxDm and userinputReports. The outbox checks the recipient's flag when it sends, and marks the item skipped for good when it's off, so it stays in the site inbox and nothing piles up to go out at once when the flag turns on. The notification settings and inbox pages only offer or mention a channel that's rolled out to the viewer, a forged post can't turn one on, and anyone rolled back can still turn theirs off. The report page and its allow and send actions use userinput.app only when the site has a space and the flag is on for the reporter. Otherwise they send the reporter to GitHub's form with what they wrote. Turning the flag off for everyone is the switch for when userinput.app is down. Fixes LOC-314 Fixes LOC-315 --- apps/web/.env.example | 4 +- apps/web/README.md | 12 +-- apps/web/docs/diagrams/shows-and-inbox.md | 2 +- apps/web/playwright.config.ts | 2 + .../lib/components/DmSettings.stories.svelte | 3 + apps/web/src/lib/components/DmSettings.svelte | 7 +- .../components/EmailSettings.stories.svelte | 3 + .../src/lib/components/EmailSettings.svelte | 14 +-- apps/web/src/lib/server/app.ts | 2 + .../lib/server/notifications/outbox.test.ts | 67 ++++++++++++-- .../src/lib/server/notifications/outbox.ts | 32 ++++++- .../src/lib/server/services/bug-reports.ts | 4 +- .../account/notifications/+page.server.ts | 43 ++++++--- .../account/notifications/page.server.test.ts | 88 +++++++++++++++++-- .../account/notifications/page.svelte.test.ts | 18 +++- .../routes/dashboard/inbox/+page.server.ts | 10 +-- .../dashboard/inbox/page.server.test.ts | 15 +++- apps/web/src/routes/report/+page.server.ts | 18 +++- .../web/src/routes/report/page.server.test.ts | 49 ++++++++++- flags/catalog/inboxDm.json | 6 ++ flags/catalog/inboxEmail.json | 6 ++ flags/catalog/userinputReports.json | 6 ++ 22 files changed, 352 insertions(+), 59 deletions(-) create mode 100644 flags/catalog/inboxDm.json create mode 100644 flags/catalog/inboxEmail.json create mode 100644 flags/catalog/userinputReports.json diff --git a/apps/web/.env.example b/apps/web/.env.example index 61f2afd0b..5ce92c1ac 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -41,8 +41,8 @@ HAPPYVIEW_URL=https://localnetwork.hpy.at # HAPPYVIEW_CLIENT_SECRET=hvs_... # Optional: Local Network's space on userinput.app (at:///app.userinput.space/). -# With it, signed-in people post bug reports there from their own account; without -# it, "Report a bug" opens GitHub's issue form for everyone. +# With it, signed-in people the userinputReports flag is on for post bug reports there +# from their own account; without it, "Report a bug" opens GitHub's issue form for everyone. # USERINPUT_SPACE= # Optional: Local Network's clients at the services locallibrary plugins sign in to diff --git a/apps/web/README.md b/apps/web/README.md index 207c9816c..ee0edcad1 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -17,7 +17,7 @@ All data lives on the AT Protocol. Public profiles are ordinary atproto records; ### Dashboard - Signing in lands on `/dashboard`, where every change to what a public page shows happens: each project you manage (`/dashboard/projects/`, with its profile, shows and press kits), your inbox, booking threads and planner. Account (`/dashboard/account`) holds notification settings, your activity in plain sentences, what the root holds on your behalf with counts by type (`/dashboard/account/data`), your requests to staff, and sign out. The pages' old addresses, which emails and DMs may still link to, redirect with a 308. The first page, Overview, ends with a locallibrary card: when your playing stats and sets were last published, a link to your newest set, "Get locallibrary" while you've published neither, and a link to preview a mix export. Staff work in the staff console at `/admin`, on the same sidebar layout. -- The inbox (`/dashboard/inbox`) tells each participant in a booking thread about a new inquiry, message or status change from someone else in it, with a dot in the sidebar while anything is unread. It shows one row per thread, saying in a sentence what happened since you last read it. An item names the performer, never which of its managers wrote, and holds none of what was written. Opening a row, or its thread, marks the thread read; it doesn't change whose turn it is. Read items go after 90 days and unread ones after 180. People can also have new items emailed: the address comes from their account's host, read only after they approve it, and nothing goes to it until they open a link we email it, which works for a day. New items wait two minutes so a burst goes as one email. Anything older than six hours when it's indexed stays on the site. They can also have them sent as Bluesky DMs from the root account, a minute apart at most; when Bluesky chat says the root can't DM them yet, the settings page asks them to allow DMs from people they follow and to follow the root. The site asks chat alone, not the AppView, so it doesn't know which of the two is missing. `/dashboard/account/notifications` has a grid of inbox sections by Email and Bluesky DM that saves as you tick, and turns each of the two on and off and sends a test. +- The inbox (`/dashboard/inbox`) tells each participant in a booking thread about a new inquiry, message or status change from someone else in it, with a dot in the sidebar while anything is unread. It shows one row per thread, saying in a sentence what happened since you last read it. An item names the performer, never which of its managers wrote, and holds none of what was written. Opening a row, or its thread, marks the thread read; it doesn't change whose turn it is. Read items go after 90 days and unread ones after 180. People can also have new items emailed: the address comes from their account's host, read only after they approve it, and nothing goes to it until they open a link we email it, which works for a day. New items wait two minutes so a burst goes as one email. Anything older than six hours when it's indexed stays on the site. They can also have them sent as Bluesky DMs from the root account, a minute apart at most; when Bluesky chat says the root can't DM them yet, the settings page asks them to allow DMs from people they follow and to follow the root. The site asks chat alone, not the AppView, so it doesn't know which of the two is missing. `/dashboard/account/notifications` has a grid of inbox sections by Email and Bluesky DM that saves as you tick, and turns each of the two on and off and sends a test. Email and DMs roll out an account at a time behind the `inboxEmail` and `inboxDm` flags. Where a channel's flag is off for someone, the settings page doesn't offer it (only turning it off, if they turned it on before), and the outbox skips what would have gone to them by it: it stays in their site inbox, and turning the flag back on sends only what comes after. - People edit their profile at `/dashboard/profile`: the basics, and the DJ and promoter sections they turn on, each adding its own fields (the project form is built from the same basics and performer fields). Turning a section off asks first, since saving deletes what was in it. The profile goes to the account's own repo with its session, over the version the form opened on. A session from before profiles is offered "Sign in again" when the page opens. Someone without a profile makes one from the first step of the checklist on `/dashboard`, from their Bluesky name and picture, read once from their own repo. The sections decide the dashboard sidebar: a DJ's projects under Yours, and for a promoter a Promoter section with Book DJs (`/dashboard/promoter`: the Find DJs search, Match a show, the inquiries they sent and their planned shows) and the planner. Until there's a profile, the planner and List a project show anyway, and projects someone manages always do. Saving the profile with the promoter section newly on points to Book DJs. On a phone the sidebar's main items become tabs along the bottom, and Menu opens the rest in a sheet. - A DJ asks staff to list them in Find DJs from their profile editor, once their profile has the DJ section on: a `list` request in the moderation space that names their profile and the version they asked with. Staff review it at `/admin/requests` like any other, seeing the profile as it is now, with a note when it changed since the request and when the same account manages a solo project, which would put them in Find DJs twice. Approving writes the root's `computer.localnetwork.listing.profile` for them and has HappyView read their profile again; `/admin/listings/` (staff's Manage link on a profile) shows the listing and takes them out again. Both are audited. - Public pages only read, apart from Follow and Save. A project's managers get a Manage link to its dashboard there, and staff one to the staff console. A project that isn't public shows its managers and staff a "Not public yet" banner; everyone else gets a 404. @@ -77,7 +77,7 @@ All data lives on the AT Protocol. Public profiles are ordinary atproto records; ### Bug reports -- "Report a bug" in the footer opens `/report`. Signed in, it posts the report from the person's own account to Local Network's space on [userinput.app](https://userinput.app) (an `app.userinput.discussion` record in their repo, tagged `bug` and `web`, with the page they came from and their browser), then links to it there. Signed out (where the link reads "Report a bug on GitHub"), or without `USERINPUT_SPACE`, it opens GitHub's website bug form with the page and browser filled in, and so does a report that fails to post, with what they wrote. +- "Report a bug" in the footer opens `/report`. Signed in, it posts the report from the person's own account to Local Network's space on [userinput.app](https://userinput.app) (an `app.userinput.discussion` record in their repo, tagged `bug` and `web`, with the page they came from and their browser), then links to it there. Signed out (where the link reads "Report a bug on GitHub"), without `USERINPUT_SPACE`, or with the `userinputReports` flag off for them, it opens GitHub's website bug form with the page and browser filled in, and so does a report that fails to post, with what they wrote. Turning `userinputReports` off for everyone sends every report to GitHub while userinput.app is down. - Posting asks for one more OAuth scope, `repo:app.userinput.discussion?action=create`, the first time someone sends a report, not at sign-in: sessions from before it keep working, and the client metadata lists it so the PDS allows the request. ### Flags @@ -278,6 +278,8 @@ pnpm dev `harbour.test`, `pirate.test`, and `glasshouse.test` (passwords `harbour-pass` and so on) manage Harbour Lights, Pirate Signal, and Glasshouse and have sets of their own, so `/charts` has tracks several DJs played. Every other demo project has a manager too (`velvet.test`, `tunde.test` and so on; the dev network prints them all). Each manager got there through a claim ada.test approved, and each solo project's DJ claimed it as themselves. +Inbox email and DMs go to the log locally, and bug reports to the stand-in space, once their flags (`inboxEmail`, `inboxDm`, `userinputReports`) are on for you: turn them on at `/admin/flags` as ada.test, or start with `FLAG_OVERRIDES=inboxEmail=on,inboxDm=on,userinputReports=on`. + The network is temporary; Ctrl-C stops it, and restarting resets everything (and the dev database). To restart the app without resetting the network, run `pnpm dev:network` in one terminal and `pnpm dev:app` in another. ## Scripts @@ -357,9 +359,9 @@ See [`.env.example`](.env.example) for every option. The essentials: - `HAPPYVIEW_API_KEY`: a HappyView API key with `lexicons:read`, `lexicons:create`, `scripts:read`, `scripts:manage`, `backfill:create`, `backfill:read`, `stats:read`, `dead-letters:read`, and `metrics:read`. Optional; without it, upload the lexicons and scripts yourself, the set picker only lists sets HappyView heard about over Jetstream, and `requestIndex` answers `indexed: false` without re-reading anything. - `HAPPYVIEW_CLIENT_KEY` and `HAPPYVIEW_CLIENT_SECRET`: a HappyView API client's key and secret, sent with each directory query (`X-Client-Key`, `X-Client-Secret`) so it counts as that client's. Optional, set together; needed once the instance refuses anonymous XRPC calls. - `LOCALLIBRARY_HOST`: [locallibrary's own host](#tools-pages-and-hosts) (default `locallibrary.localnetwork.computer`). -- `USERINPUT_SPACE`: Local Network's space on [userinput.app](https://userinput.app), as `at:///app.userinput.space/`. See [Bug reports](#bug-reports). Optional; without it, "Report a bug" opens GitHub's issue form. -- `RESEND_API_KEY` (and optionally `EMAIL_FROM`, `EMAIL_PROVIDER`): sends inbox email through [Resend](https://resend.com) for people who turn it on. Optional; in production without it, email is off and the settings page says so. Outside production, email goes to the log. -- `DM_PROVIDER` (and optionally `CHAT_SERVICE_DID`): `bluesky` sends inbox DMs from the root account through Bluesky chat. Off in production until set; first check that Bluesky's relay and AppView know the root account and that it can call `chat.bsky.convo.getConvoAvailability`. Outside production, DMs go to the log. +- `USERINPUT_SPACE`: Local Network's space on [userinput.app](https://userinput.app), as `at:///app.userinput.space/`. See [Bug reports](#bug-reports). Optional; without it, "Report a bug" opens GitHub's issue form. With it, reports go there only for accounts `userinputReports` is on for. +- `RESEND_API_KEY` (and optionally `EMAIL_FROM`, `EMAIL_PROVIDER`): sends inbox email through [Resend](https://resend.com) for people who turn it on and `inboxEmail` is on for. Optional; in production without it, email is off and the settings page says so. Outside production, email goes to the log. +- `DM_PROVIDER` (and optionally `CHAT_SERVICE_DID`): `bluesky` sends inbox DMs from the root account through Bluesky chat, to accounts `inboxDm` is on for. Off in production until set; first check that Bluesky's relay and AppView know the root account and that it can call `chat.bsky.convo.getConvoAvailability`. Outside production, DMs go to the log. - `ACTOR_SEARCH`: where sign-in's account suggestions come from, `bluesky` (the default) or `none`. - `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`, `MIXCLOUD_CLIENT_ID` / `MIXCLOUD_CLIENT_SECRET`, `SOUNDCLOUD_CLIENT_ID` / `SOUNDCLOUD_CLIENT_SECRET`: Local Network's clients at the services locallibrary plugins sign in to through the [token exchange](#token-exchange). Optional; a service without both answers that it isn't set up yet. diff --git a/apps/web/docs/diagrams/shows-and-inbox.md b/apps/web/docs/diagrams/shows-and-inbox.md index 453fffa64..e05ebffdc 100644 --- a/apps/web/docs/diagrams/shows-and-inbox.md +++ b/apps/web/docs/diagrams/shows-and-inbox.md @@ -93,7 +93,7 @@ One item on its way out by one channel. A batch keeps its items and key through ```mermaid stateDiagram-v2 [*] --> pending - pending --> skipped: read already, or channel off or paused + pending --> skipped: read already, channel off or paused, or its flag off for them pending --> sending: claimed in a batch sending --> sent: service took it sending --> pending: retryable, under 8 attempts diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.ts index f14c48a3a..453a26646 100644 --- a/apps/web/playwright.config.ts +++ b/apps/web/playwright.config.ts @@ -44,6 +44,8 @@ export default defineConfig({ DEV_ENV_FILE: '', GEOCODER: 'none', ACTOR_SEARCH: 'none', + // The bug report tests post to the stand-in userinput.app space, which is rolled out behind this flag. + FLAG_OVERRIDES: 'userinputReports=on', LOG_LEVEL: 'warn' } } diff --git a/apps/web/src/lib/components/DmSettings.stories.svelte b/apps/web/src/lib/components/DmSettings.stories.svelte index 4f313756b..880eb926d 100644 --- a/apps/web/src/lib/components/DmSettings.stories.svelte +++ b/apps/web/src/lib/components/DmSettings.stories.svelte @@ -45,6 +45,9 @@ + + + @@ -76,6 +78,7 @@ {/if} {#if !available} + {#if channel}
{/if} {:else if !channel}
{:else if channel.status === 'paused'} diff --git a/apps/web/src/lib/components/EmailSettings.stories.svelte b/apps/web/src/lib/components/EmailSettings.stories.svelte index 4334cda5d..3526083aa 100644 --- a/apps/web/src/lib/components/EmailSettings.stories.svelte +++ b/apps/web/src/lib/components/EmailSettings.stories.svelte @@ -38,6 +38,9 @@ + + + diff --git a/apps/web/src/lib/components/EmailSettings.svelte b/apps/web/src/lib/components/EmailSettings.svelte index 7392e73e4..51a674d5b 100644 --- a/apps/web/src/lib/components/EmailSettings.svelte +++ b/apps/web/src/lib/components/EmailSettings.svelte @@ -15,9 +15,10 @@ import FormMessage from './FormMessage.svelte'; /** - * Someone's email setting for their inbox. `available` is false when the site can't send email. `returned` says how - * asking their account's host for the address just went, when it didn't go through. Turning email on (or checking - * again) is a full page POST: it goes on to their account's host, which client-side navigation can't follow. + * Someone's email setting for their inbox. `available` is false when the site can't send email, or hasn't rolled it + * out to them; email they turned on before that can still be turned off. `returned` says how asking their account's + * host for the address just went, when it didn't go through. Turning email on (or checking again) is a full page + * POST: it goes on to their account's host, which client-side navigation can't follow. */ let { available, @@ -39,7 +40,9 @@ const status = $derived( !available - ? 'Not set up on this site.' + ? channel + ? 'Paused on this site for now.' + : 'Not set up on this site.' : !channel ? 'Get your inbox by email too.' : channel.pausedReason === 'email_unverified' @@ -61,7 +64,8 @@ {#if returned === 'limited' && !form}

We can't send a confirmation link to that address right now. Try again tomorrow.

{/if} {#if !available} - + + {#if channel}
{/if} {:else if !channel} {#if returned === 'declined'}

You didn't allow sharing your email address, so email is still off.

{/if}
diff --git a/apps/web/src/lib/server/app.ts b/apps/web/src/lib/server/app.ts index 41ece6a4b..c9efbeac5 100644 --- a/apps/web/src/lib/server/app.ts +++ b/apps/web/src/lib/server/app.ts @@ -170,6 +170,8 @@ export async function createApp(options: CreateAppOptions) { db, logger: logger.child({ component: 'outbox' }), channels: notificationChannels, + // The outbox only sends from its timers, which start after `flags` below exists. + flags: { evaluate: (did) => flags.evaluate(did) }, senders }); diff --git a/apps/web/src/lib/server/notifications/outbox.test.ts b/apps/web/src/lib/server/notifications/outbox.test.ts index a8d625982..79e1cd034 100644 --- a/apps/web/src/lib/server/notifications/outbox.test.ts +++ b/apps/web/src/lib/server/notifications/outbox.test.ts @@ -1,11 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { flagsOff } from '#lib/testing/flags.ts'; import type { NotificationView } from '#lib/types.ts'; import { type Db, openDatabase } from '../db'; import { silentLogger } from '../logger'; import { RateLimiter } from '../rate-limit'; import { NotificationChannels } from './channels'; import { Notifier, type NotifyInput } from './notifier'; -import { type ChannelSender, Outbox, type Recipient, type SendOutcome } from './outbox'; +import { type ChannelFlags, type ChannelSender, Outbox, type Recipient, type SendOutcome } from './outbox'; const MINUTE = 60_000; @@ -37,6 +38,16 @@ describe('Outbox', () => { let sender: FakeSender; let outbox: Outbox; let inbox: Notifier; + /** Who each channel's rollout flag is off for. It's on for everyone else. */ + let offFor: Record<'inboxEmail' | 'inboxDm', string[]>; + + const flags: ChannelFlags = { + evaluate: async (did) => ({ + ...flagsOff, + inboxEmail: !offFor.inboxEmail.includes(did), + inboxDm: !offFor.inboxDm.includes(did) + }) + }; const message = (key: string, overrides: Partial> = {}) => inbox.notify({ @@ -52,6 +63,14 @@ describe('Outbox', () => { const later = (ms: number) => vi.setSystemTime(Date.now() + ms); + /** Each delivery's recipient, channel and status, in that order. */ + const deliveries = async () => + db + .selectFrom('notificationDelivery') + .select(['did', 'channel', 'status']) + .orderBy(['did', 'channel', 'id']) + .execute(); + const statuses = async () => (await db.selectFrom('notificationDelivery').select('status').orderBy('id').execute()).map((row) => row.status); @@ -87,7 +106,8 @@ describe('Outbox', () => { db = await openDatabase(':memory:'); await optIn(neon); sender = new FakeSender(); - outbox = new Outbox({ db, logger: silentLogger, channels, senders: { email: sender }, maxAttempts: 3 }); + offFor = { inboxEmail: [], inboxDm: [] }; + outbox = new Outbox({ db, logger: silentLogger, channels, flags, senders: { email: sender }, maxAttempts: 3 }); inbox = new Notifier({ db, logger: silentLogger, outbox }); }); @@ -222,13 +242,13 @@ describe('Outbox', () => { it('sends as soon as something comes due, without waiting for the next round', async () => { vi.useRealTimers(); const quick = Object.assign(new FakeSender(), { windowMs: 0 }); - outbox = new Outbox({ db, logger: silentLogger, channels, senders: { email: quick } }); + outbox = new Outbox({ db, logger: silentLogger, channels, flags, senders: { email: quick } }); inbox = new Notifier({ db, logger: silentLogger, outbox }); await message('now'); await vi.waitFor(() => expect(quick.messages).toHaveLength(1)); await outbox.kick(); - expect(new Outbox({ db, logger: silentLogger, channels, senders: {} }).configured).toEqual([]); + expect(new Outbox({ db, logger: silentLogger, channels, flags, senders: {} }).configured).toEqual([]); }); it('sends a test right away to someone with email on, and pauses an address that refuses it', async () => { @@ -250,7 +270,7 @@ describe('Outbox', () => { it('sends by every channel someone turned on, each on its own clock', async () => { const dm = Object.assign(new FakeSender(), { windowMs: MINUTE }); - outbox = new Outbox({ db, logger: silentLogger, channels, senders: { email: sender, dm } }); + outbox = new Outbox({ db, logger: silentLogger, channels, flags, senders: { email: sender, dm } }); inbox = new Notifier({ db, logger: silentLogger, outbox }); await channels.enableDm(neon, true); expect(outbox.configured).toEqual(['email', 'dm']); @@ -266,6 +286,43 @@ describe('Outbox', () => { expect([sender.messages.length, dm.messages.length]).toEqual([1, 1]); }); + it("skips for good what's due by a channel whose flag is off for its recipient, and keeps it in their inbox", async () => { + const dm = Object.assign(new FakeSender(), { windowMs: 2 * MINUTE }); + outbox = new Outbox({ db, logger: silentLogger, channels, flags, senders: { email: sender, dm } }); + inbox = new Notifier({ db, logger: silentLogger, outbox }); + await optIn(remy); + await channels.enableDm(neon, true); + await channels.enableDm(remy, true); + // Off for Neon on both channels, and for Remy on DMs only. + offFor = { inboxEmail: [neon], inboxDm: [neon, remy] }; + + await message('rolling out'); + later(2 * MINUTE); + await outbox.processDue(); + + expect(sender.messages.map((out) => out.to.did)).toEqual([remy]); + expect(dm.messages).toEqual([]); + expect(await deliveries()).toEqual([ + { did: neon, channel: 'dm', status: 'skipped' }, + { did: neon, channel: 'email', status: 'skipped' }, + { did: remy, channel: 'dm', status: 'skipped' }, + { did: remy, channel: 'email', status: 'sent' } + ]); + expect(await inbox.unreadCount(neon)).toBe(1); + + // Turning the flags back on sends only what comes after, so nothing skipped goes out in a burst. + offFor = { inboxEmail: [], inboxDm: [] }; + later(2 * MINUTE); + await outbox.processDue(); + expect([sender.messages.length, dm.messages.length]).toEqual([1, 0]); + + await message('rolled out'); + later(2 * MINUTE); + await outbox.processDue(); + expect(sender.messages.map((out) => out.to.did)).toEqual([remy, neon, remy]); + expect(dm.messages.map((out) => out.to.did)).toEqual([neon, remy]); + }); + it('keeps finished deliveries for 30 days', async () => { await message('done'); later(2 * MINUTE); diff --git a/apps/web/src/lib/server/notifications/outbox.ts b/apps/web/src/lib/server/notifications/outbox.ts index 49f87c096..d2faea8b3 100644 --- a/apps/web/src/lib/server/notifications/outbox.ts +++ b/apps/web/src/lib/server/notifications/outbox.ts @@ -1,11 +1,13 @@ import { createHash } from 'node:crypto'; import { TID } from '@atproto/common-web'; import type { Kysely } from 'kysely'; +import type { FlagKey } from '#lib/flags/keys.generated.ts'; import type { NotificationChannel, NotificationTopic, NotificationView, PausedReason } from '#lib/types.ts'; import { backoffMs } from '../audit/log'; import { type Db, nowIso, parseJson } from '../db'; import type { Database, NotificationChannelRow } from '../db/schema'; import type { Logger } from '../logger'; +import type { FlagService } from '../services/flags'; import type { NotificationChannels } from './channels'; import { view } from './notifier'; @@ -57,6 +59,21 @@ const KEEP_MS = 30 * 86_400_000; const CHANNELS: NotificationChannel[] = ['email', 'dm']; +/** The flag each channel rolls out behind, a recipient at a time. */ +const CHANNEL_FLAG = { email: 'inboxEmail', dm: 'inboxDm' } as const satisfies Record; + +/** Where the outbox reads who each channel's flag is on for. */ +export type ChannelFlags = { evaluate(did: string): ReturnType }; + +/** + * The channels a page offers or mentions to the viewer: the ones this site sends by and has rolled out to them. `dm` + * is Bluesky chat, for asking whether the root's DMs reach them. + */ +export const offeredChannels = ({ app, flags }: Pick) => ({ + email: flags[CHANNEL_FLAG.email] && app.outbox.configured.includes('email'), + dm: flags[CHANNEL_FLAG.dm] ? app.dm : null +}); + type Due = { id: string; notificationId: string; @@ -82,6 +99,7 @@ export class Outbox { db: Db; logger: Logger; channels: NotificationChannels; + flags: ChannelFlags; senders: Partial>; maxAttempts?: number; } @@ -286,12 +304,22 @@ export class Outbox { const sender = this.deps.senders[channel]; const recipient = await this.deps.channels.get(did, channel); const fresh = !batch[0].batchId; - // Read on the site already, or the channel's off, paused, or no longer set up here: nothing to send. - const skipped = batch.filter((row) => !sender || recipient?.status !== 'active' || (fresh && row.readAt)); + const rolledOut = (await this.deps.flags.evaluate(did))[CHANNEL_FLAG[channel]]; + + // Read on the site already, or the channel's off, paused, not rolled out to them, or no longer set up here: + // nothing to send. Not rolled out is skipped for good, not held, or everything held would go out at once when + // the flag came on. + const skipped = batch.filter( + (row) => !sender || !rolledOut || recipient?.status !== 'active' || (fresh && row.readAt) + ); + const sending = batch.filter((row) => !skipped.includes(row)); if (skipped.length > 0) await this.finish(skipped, { status: 'skipped' }); + if (!rolledOut) + logger.info('skipped notifications: the channel is off for them', { did, channel, items: skipped.length }); + if (!sender || !recipient || sending.length === 0) return; const ids = sending.map((row) => row.id); const batchId = sending[0].batchId ?? createHash('sha256').update(ids.toSorted().join(',')).digest('hex'); diff --git a/apps/web/src/lib/server/services/bug-reports.ts b/apps/web/src/lib/server/services/bug-reports.ts index d1e172a0a..5698d4e95 100644 --- a/apps/web/src/lib/server/services/bug-reports.ts +++ b/apps/web/src/lib/server/services/bug-reports.ts @@ -25,8 +25,8 @@ export function browserLabel(userAgent: string | null | undefined): string | und /** * Bug reports from signed-in people, posted from their own account into Local Network's space on - * userinput.app (a feedback board on the AT Protocol). Without a space configured, the site sends - * everyone to GitHub's issue form instead. + * userinput.app (a feedback board on the AT Protocol). Without a space configured, or for someone the + * `userinputReports` flag is off for, the report page sends them to GitHub's issue form instead. */ export class BugReportService { constructor( diff --git a/apps/web/src/routes/dashboard/account/notifications/+page.server.ts b/apps/web/src/routes/dashboard/account/notifications/+page.server.ts index 0e520cf86..d04ae104d 100644 --- a/apps/web/src/routes/dashboard/account/notifications/+page.server.ts +++ b/apps/web/src/routes/dashboard/account/notifications/+page.server.ts @@ -3,6 +3,7 @@ import { fail, redirect } from '@sveltejs/kit'; import { grantsEmail, OptionalScopeUnsupported } from '#lib/server/atproto/oauth.ts'; import { requireViewer } from '#lib/server/http.ts'; import { KIND_TOPICS } from '#lib/server/notifications/kinds.ts'; +import { offeredChannels } from '#lib/server/notifications/outbox.ts'; import type { NotificationChannel, NotificationTopic } from '#lib/types.ts'; import type { Action, Actions, PageServerLoad } from './$types'; @@ -32,6 +33,24 @@ const WORDS: Record = { + email: "Email isn't set up on this site.", + dm: "Bluesky DMs aren't set up on this site." +}; + +/** + * Refuses `action` while the page doesn't offer `channel` to the viewer, so a forged post can't turn on or change a + * channel that isn't rolled out to them. Turning one off needs no check: it only forgets. + */ +const whenOffered = + (channel: NotificationChannel, action: Action): Action => + (event) => { + requireViewer(event.locals, event.url); + + return offeredChannels(event.locals)[channel] ? action(event) : failed(400, channel, MISSING[channel]); + }; + const topicsFor = (channel: NotificationChannel): Action => async ({ locals, url, request }) => { @@ -75,20 +94,21 @@ const offFor = export const load: PageServerLoad = async ({ locals, url }) => { const viewer = requireViewer(locals, url); const { app } = locals; + const offered = offeredChannels(locals); const dm = await app.notificationChannels.view(viewer.did, 'dm'); return { topics: KIND_TOPICS, email: { - available: app.outbox.configured.includes('email'), + available: offered.email, channel: await app.notificationChannels.view(viewer.did, 'email'), returned: returned(url.searchParams.get('email')) }, dm: { - available: Boolean(app.dm), + available: Boolean(offered.dm), channel: dm, // Streamed: Bluesky chat can be slow, and the rest of the page doesn't wait on it. - availability: app.dm ? app.dm.availability(viewer.did) : null, + availability: offered.dm ? offered.dm.availability(viewer.did) : null, root: app.rootAccount.handle ?? app.rootDid } }; @@ -99,7 +119,7 @@ export const actions: Actions = { * Reads the viewer's address with the session they have when it already allows that, and otherwise sends them to * their account's host to allow it, coming back through the sign-in callback. */ - emailOn: async ({ locals, url }) => { + emailOn: whenOffered('email', async ({ locals, url }) => { const viewer = requireViewer(locals, url); const { app, log } = locals; @@ -147,24 +167,25 @@ export const actions: Actions = { } redirect(303, to, { external: true }); - }, + }), - emailTopics: topicsFor('email'), - emailTest: testFor('email'), + emailTopics: whenOffered('email', topicsFor('email')), + emailTest: whenOffered('email', testFor('email')), emailOff: offFor('email'), /** Turns DMs on, or holds them until the viewer's Bluesky chat settings let the root's DMs through. */ dmOn: async ({ locals, url }) => { const viewer = requireViewer(locals, url); const { app } = locals; + const chat = offeredChannels(locals).dm; - if (!app.dm) return failed(400, 'dm', "Bluesky DMs aren't set up on this site."); + if (!chat) return failed(400, 'dm', MISSING.dm); if (!app.limits.optIn.take(`optIn:${viewer.did}`)) { return failed(429, 'dm', 'Too many tries. Wait a few minutes, then try again.'); } - const availability = await app.dm.availability(viewer.did); + const availability = await chat.availability(viewer.did); if (availability === 'unavailable') return failed(502, 'dm', "We couldn't reach Bluesky chat. Try again in a minute."); @@ -174,7 +195,7 @@ export const actions: Actions = { ? done('dm', 'DMs are on.') : failed(400, 'dm', "Bluesky chat won't deliver our DMs to you yet."); }, - dmTopics: topicsFor('dm'), - dmTest: testFor('dm'), + dmTopics: whenOffered('dm', topicsFor('dm')), + dmTest: whenOffered('dm', testFor('dm')), dmOff: offFor('dm') }; diff --git a/apps/web/src/routes/dashboard/account/notifications/page.server.test.ts b/apps/web/src/routes/dashboard/account/notifications/page.server.test.ts index b0894a044..2bd10f525 100644 --- a/apps/web/src/routes/dashboard/account/notifications/page.server.test.ts +++ b/apps/web/src/routes/dashboard/account/notifications/page.server.test.ts @@ -7,12 +7,15 @@ import { type ChannelSender, Outbox, type SendOutcome } from '#lib/server/notifi import { RateLimiter } from '#lib/server/rate-limit.ts'; import { createTestServices, ROOT } from '#lib/server/testing/core.ts'; import { callRoute, loadRoute } from '#lib/testing/route-event.ts'; -import type { DmAvailability, NotificationChannel } from '#lib/types.ts'; +import type { DmAvailability, Flags, NotificationChannel } from '#lib/types.ts'; import { actions, load } from './+page.server.ts'; import type { PageServerData } from './$types'; const DJ = 'did:plc:dj'; +/** Email and DMs rolled out to the DJ. */ +const ROLLED_OUT: Partial = { inboxEmail: true, inboxDm: true }; + /** A grant that lets the app read the account's email address. */ const WITH_EMAIL = 'atproto account:email?action=read'; @@ -83,6 +86,7 @@ beforeEach(async () => { db: t.db, logger: silentLogger, channels, + flags: t.flags, senders: { email: sender('email'), dm: sender('dm') } }); }); @@ -148,20 +152,22 @@ const signedIn = (scope: string) => type ActionName = keyof typeof actions; -/** Runs the settings action `name` as the DJ, with `form`, on `site` (the default app unless given). */ -const run = async (name: ActionName, form: Record = {}, site = app()) => +/** Runs the settings action `name` as the DJ, with `form`, on `site` (the default app unless given), with `flags` theirs. */ +const run = async (name: ActionName, form: Record = {}, site = app(), flags = ROLLED_OUT) => callRoute(actions[name], { app: site, viewer: await t.viewer(DJ), url: `/dashboard/account/notifications?/${name}`, - form + form, + flags }); it('shows both channels as off and available, with the account to follow for DMs', async () => { const data = await loadRoute(load, { app: app(), viewer: await t.viewer(DJ), - url: '/dashboard/account/notifications' + url: '/dashboard/account/notifications', + flags: ROLLED_OUT }); expect(data).toMatchObject({ @@ -175,7 +181,7 @@ it('shows both channels as off and available, with the account to follow for DMs it("says how asking for the address went, and what's off on a site without email or DMs", async () => { const bare = app({ - outbox: new Outbox({ db: t.db, logger: silentLogger, channels, senders: {} }), + outbox: new Outbox({ db: t.db, logger: silentLogger, channels, flags: t.flags, senders: {} }), dm: null, rootAccount: { handle: null } }); @@ -186,7 +192,8 @@ it("says how asking for the address went, and what's off on a site without email const declined = await loadRoute(load, { app: bare, viewer, - url: '/dashboard/account/notifications?email=declined' + url: '/dashboard/account/notifications?email=declined', + flags: ROLLED_OUT }); expect(declined.email).toMatchObject({ available: false, returned: 'declined' }); @@ -200,18 +207,81 @@ it("says how asking for the address went, and what's off on a site without email const limited = await loadRoute(load, { app: bare, viewer, - url: '/dashboard/account/notifications?email=limited' + url: '/dashboard/account/notifications?email=limited', + flags: ROLLED_OUT }); const unknown = await loadRoute(load, { app: bare, viewer, - url: '/dashboard/account/notifications?email=yes' + url: '/dashboard/account/notifications?email=yes', + flags: ROLLED_OUT }); expect([limited.email.returned, unknown.email.returned]).toEqual(['limited', null]); }); +it("doesn't offer email or DMs to someone they aren't rolled out to, on a site that sends both", async () => { + const data = await loadRoute(load, { + app: app(), + viewer: await t.viewer(DJ), + url: '/dashboard/account/notifications', + flags: { inboxDm: true } + }); + + expect(data.email.available).toBe(false); + expect(data.dm.available).toBe(true); + + const neither = await loadRoute(load, { + app: app(), + viewer: await t.viewer(DJ), + url: '/dashboard/account/notifications' + }); + + expect(neither.email.available).toBe(false); + expect(neither.dm).toMatchObject({ available: false, availability: null }); +}); + +it("won't turn on, save or test a channel for a post while it isn't rolled out to them, but turns it off", async () => { + await signedIn(WITH_EMAIL); + await run('emailOn'); + await channels.enableDm(DJ, true); + const topics = async (channel: NotificationChannel) => (await channels.view(DJ, channel))?.topics; + const picked = await topics('email'); + const emailOff = { status: 400, data: { channel: 'email', error: "Email isn't set up on this site." } }; + const dmOff = { status: 400, data: { channel: 'dm', error: "Bluesky DMs aren't set up on this site." } }; + + expect(await run('emailOn', {}, app(), { inboxDm: true })).toMatchObject(emailOff); + expect(await run('emailTopics', {}, app(), { inboxDm: true })).toMatchObject(emailOff); + expect(await run('emailTest', {}, app(), { inboxDm: true })).toMatchObject(emailOff); + expect(links).toHaveLength(1); + expect(await topics('email')).toEqual(picked); + + // The other channel's flag doesn't hold it back. + expect(await run('dmTopics', {}, app(), { inboxDm: true })).toMatchObject({ + channel: 'dm', + success: expect.any(String) + }); + expect(await topics('dm')).toEqual([]); + + await run('dmTopics', { topic: 'bookings' }); + expect(await run('dmTopics', {}, app(), {})).toMatchObject(dmOff); + expect(await run('dmTest', {}, app(), {})).toMatchObject(dmOff); + expect(await topics('dm')).toEqual(['bookings']); + + await channels.disable(DJ, 'dm'); + + expect(await run('dmOn', {}, app(), {})).toMatchObject(dmOff); + expect(await channels.view(DJ, 'dm')).toBeNull(); + + // Turned on before it was rolled back, a channel can still be turned off. + expect(await run('emailOff', {}, app(), {})).toEqual({ + channel: 'email', + success: "Email's off. We've deleted your address." + }); + expect(await channels.view(DJ, 'email')).toBeNull(); +}); + it('sends someone signed out to sign in', async () => { await expect(callRoute(load, { app: app(), url: '/dashboard/account/notifications' })).rejects.toMatchObject({ status: 303, diff --git a/apps/web/src/routes/dashboard/account/notifications/page.svelte.test.ts b/apps/web/src/routes/dashboard/account/notifications/page.svelte.test.ts index 36d5f2090..fd2a45e3e 100644 --- a/apps/web/src/routes/dashboard/account/notifications/page.svelte.test.ts +++ b/apps/web/src/routes/dashboard/account/notifications/page.svelte.test.ts @@ -2,14 +2,15 @@ import { page } from 'vitest/browser'; import { expect, it } from 'vitest'; import { render } from 'vitest-browser-svelte'; import { accountLayout } from '#lib/testing/account.ts'; +import type { ChannelView } from '#lib/types.ts'; import type { PageProps } from './$types'; import Page from './+page.svelte'; -const data = (available: boolean): PageProps['data'] => ({ +const data = (available: boolean, channel: ChannelView | null = null): PageProps['data'] => ({ ...accountLayout, topics: ['bookings'], - email: { available, channel: null, returned: null }, - dm: { available, channel: null, availability: Promise.resolve('ok'), root: 'localnetwork.computer' } + email: { available, channel, returned: null }, + dm: { available, channel, availability: Promise.resolve('ok'), root: 'localnetwork.computer' } }); it('offers the grid while email or Bluesky DM can be set up', async () => { @@ -24,3 +25,14 @@ it('leaves the grid out when neither can be set up here', async () => { await expect.element(page.getByRole('heading', { name: 'Notifications', level: 1 })).toBeVisible(); await expect.element(page.getByRole('heading', { name: 'What goes where' })).not.toBeInTheDocument(); }); + +it('lets someone turn off a channel they turned on before it stopped being offered to them', async () => { + const on: ChannelView = { status: 'active', pausedReason: null, address: 'neon@example.test', topics: ['bookings'] }; + + await render(Page, { params: {}, form: null, data: data(false, on) }); + + await expect.element(page.getByText('Paused on this site for now.').first()).toBeVisible(); + await expect.element(page.getByRole('button', { name: 'Turn off email' })).toBeVisible(); + await expect.element(page.getByRole('button', { name: 'Turn off DMs' })).toBeVisible(); + await expect.element(page.getByRole('button', { name: 'Send a test' })).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/routes/dashboard/inbox/+page.server.ts b/apps/web/src/routes/dashboard/inbox/+page.server.ts index 9c3e2d705..16a21b23e 100644 --- a/apps/web/src/routes/dashboard/inbox/+page.server.ts +++ b/apps/web/src/routes/dashboard/inbox/+page.server.ts @@ -1,6 +1,7 @@ import { redirect } from '@sveltejs/kit'; import { soon } from '#lib/server/home.ts'; import { requireViewer, safeNext, text } from '#lib/server/http.ts'; +import { offeredChannels } from '#lib/server/notifications/outbox.ts'; import type { NotificationChannel } from '#lib/types.ts'; import type { Actions, PageServerLoad } from './$types'; @@ -23,7 +24,9 @@ export const load: PageServerLoad = async ({ locals, url }) => { app.notificationChannels.view(viewer.did, 'dm') ]); - // Only what the site can send and would send something on, so the line under the list never promises more. + // Only what the site sends them by and would send something on, so the line under the list never promises more. + const offered = offeredChannels(locals); + const sending = (channel: NotificationChannel, view: typeof email, available: boolean) => available && view?.status === 'active' && view.topics.length > 0 ? [channel] : []; @@ -33,10 +36,7 @@ export const load: PageServerLoad = async ({ locals, url }) => { paused: [email, dm].flatMap((channel) => channel?.status === 'paused' && channel.pausedReason ? [channel.pausedReason] : [] ), - alsoSent: [ - ...sending('email', email, app.outbox.configured.includes('email')), - ...sending('dm', dm, Boolean(app.dm)) - ] + alsoSent: [...sending('email', email, offered.email), ...sending('dm', dm, Boolean(offered.dm))] }; }; diff --git a/apps/web/src/routes/dashboard/inbox/page.server.test.ts b/apps/web/src/routes/dashboard/inbox/page.server.test.ts index f503a825f..7477e94f0 100644 --- a/apps/web/src/routes/dashboard/inbox/page.server.test.ts +++ b/apps/web/src/routes/dashboard/inbox/page.server.test.ts @@ -4,6 +4,7 @@ import { NotificationChannels } from '#lib/server/notifications/channels.ts'; import { RateLimiter } from '#lib/server/rate-limit.ts'; import { createTestServices } from '#lib/server/testing/core.ts'; import { callRoute, loadRoute } from '#lib/testing/route-event.ts'; +import type { Flags } from '#lib/types.ts'; import { actions, load } from './+page.server.ts'; import type { PageServerData } from './$types'; @@ -61,9 +62,12 @@ async function inquiries(count: number) { return t.notifications.list(DJ, { limit: count }); } -/** The DJ's inbox at `url`, the rows awaited. */ -const opened = async (url = '/dashboard/inbox', sends: ('email' | 'dm')[] = []) => { - const data = await loadRoute(load, { app: app(sends), viewer: await t.viewer(DJ), url }); +/** Both channels rolled out to the DJ. */ +const ROLLED_OUT: Partial = { inboxEmail: true, inboxDm: true }; + +/** The DJ's inbox at `url`, the rows awaited, with `flags` theirs. */ +const opened = async (url = '/dashboard/inbox', sends: ('email' | 'dm')[] = [], flags = ROLLED_OUT) => { + const data = await loadRoute(load, { app: app(sends), viewer: await t.viewer(DJ), url, flags }); return { ...data, ...(await data.inbox) }; }; @@ -134,6 +138,11 @@ it('says where else the inbox goes only where the site sends and the account wou await notificationChannels.setTopics(DJ, 'email', []); expect((await opened(undefined, ['email', 'dm'])).alsoSent).toEqual(['dm']); + + // Nor by a channel whose flag is off for them, since the outbox skips it. + await notificationChannels.setTopics(DJ, 'email', ['bookings']); + expect((await opened(undefined, ['email', 'dm'], { inboxEmail: true })).alsoSent).toEqual(['email']); + expect((await opened(undefined, ['email', 'dm'], {})).alsoSent).toEqual([]); }); it('sends someone signed out to sign in', async () => { diff --git a/apps/web/src/routes/report/+page.server.ts b/apps/web/src/routes/report/+page.server.ts index a92806630..e84c62bb8 100644 --- a/apps/web/src/routes/report/+page.server.ts +++ b/apps/web/src/routes/report/+page.server.ts @@ -11,22 +11,31 @@ const factsOf = (request: Request, from: string | null): ReportFacts => ({ browser: browserLabel(request.headers.get('user-agent')) }); +/** + * Whether a signed-in viewer's report goes to userinput.app: the site has a space to post to, and it's rolled out to + * them. Off, it goes to GitHub, which is also how staff send everyone there while userinput.app is down. + */ +const postsToUserinput = ({ app, flags }: App.Locals) => app.bugReports.enabled && flags.userinputReports; + export const load: PageServerLoad = async ({ locals, request, url }) => { const facts = factsOf(request, url.searchParams.get('from')); const github = githubIssueUrl(facts); const { app, viewer } = locals; - // Signed out, or with no space to post to, a report goes to GitHub. - if (!viewer || !app.bugReports.enabled) redirect(303, github, { external: true }); + // Signed out, or with reports to userinput.app off for them, a report goes to GitHub. + if (!viewer || !postsToUserinput(locals)) redirect(303, github, { external: true }); return { github, facts, canPost: await app.bugReports.canPost(viewer.did) }; }; export const actions: Actions = { /** Sends the viewer through sign-in to approve posting to userinput.app, then back here. */ - allow: async ({ locals, url }) => { + allow: async ({ locals, request, url }) => { const viewer = requireViewer(locals, url); const from = url.searchParams.get('from'); + + if (!postsToUserinput(locals)) redirect(303, githubIssueUrl(factsOf(request, from)), { external: true }); + const next = `/report${from ? `?from=${encodeURIComponent(from)}` : ''}`; let to: URL; const account = await locals.app.accounts.get(viewer.did); @@ -52,6 +61,9 @@ export const actions: Actions = { const values = { title: text(form, 'title', REPORT_LIMITS.title), body: text(form, 'body', REPORT_LIMITS.body) }; const facts = factsOf(request, url.searchParams.get('from')); + // What they wrote goes with them. + if (!postsToUserinput(locals)) redirect(303, githubIssueUrl(facts, values), { external: true }); + if (!values.title) return fail(400, { error: 'Add a title.', values, github: githubIssueUrl(facts, values) }); try { diff --git a/apps/web/src/routes/report/page.server.test.ts b/apps/web/src/routes/report/page.server.test.ts index 31db544cb..57a2f9281 100644 --- a/apps/web/src/routes/report/page.server.test.ts +++ b/apps/web/src/routes/report/page.server.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, expect, it } from 'vitest'; import { OptionalScopeUnsupported, type OptionalScope, type SignedInAccount } from '#lib/server/atproto/oauth.ts'; import { createTestServices } from '#lib/server/testing/core.ts'; import { callRoute, loadRoute } from '#lib/testing/route-event.ts'; +import type { Flags } from '#lib/types.ts'; import type { PageServerData } from './$types'; import { actions, load } from './+page.server.ts'; @@ -54,6 +55,9 @@ class FakeBugReports { } } +/** Reports to userinput.app rolled out to the DJ. */ +const ROLLED_OUT: Partial = { userinputReports: true }; + let t: Awaited>; beforeEach(async () => { @@ -72,6 +76,7 @@ it('shows the form, with what the report will say about the page and browser', a const data = await loadRoute(load, { app: app(), viewer: await t.viewer(DJ), + flags: ROLLED_OUT, url: '/report?from=/shows', headers: { 'user-agent': FIREFOX } }); @@ -87,6 +92,7 @@ it('leaves the page out when it came from somewhere else', async () => { const data = await loadRoute(load, { app: app(new FakeBugReports(true, [])), viewer: await t.viewer(DJ), + flags: ROLLED_OUT, url: '/report?from=https://evil.test' }); @@ -100,10 +106,44 @@ it('sends someone signed out, or a site with no board to post to, to GitHub', as }); await expect( - callRoute(load, { app: app(new FakeBugReports(false)), viewer: await t.viewer(DJ), url: '/report' }) + callRoute(load, { + app: app(new FakeBugReports(false)), + viewer: await t.viewer(DJ), + url: '/report', + flags: ROLLED_OUT + }) ).rejects.toMatchObject({ status: 303, location: expect.stringContaining('https://github.com/') }); }); +it("sends someone reports to userinput.app aren't rolled out to on to GitHub, posting nothing", async () => { + const bugReports = new FakeBugReports(); + const oauth = new FakeOAuth(); + const viewer = await t.viewer(DJ); + + const github = { + status: 303, + location: expect.stringContaining('https://github.com/cutenode/localnetwork/issues/new') + }; + + await expect( + callRoute(load, { app: app(bugReports, oauth), viewer, url: '/report?from=/shows' }) + ).rejects.toMatchObject(github); + await expect( + callRoute(actions.allow, { app: app(bugReports, oauth), viewer, url: '/report?/allow', form: {} }) + ).rejects.toMatchObject(github); + await expect( + callRoute(actions.send, { + app: app(bugReports, oauth), + viewer, + url: '/report?/send&from=/shows', + form: { title: 'Map is blank', body: 'Never loads.' } + }) + ).rejects.toMatchObject({ status: 303, location: expect.stringContaining('title=Map+is+blank') }); + + expect(bugReports.posts).toEqual([]); + expect(oauth.started).toEqual([]); +}); + it('sends the viewer to approve posting bug reports, then back to the report', async () => { const oauth = new FakeOAuth(); @@ -111,6 +151,7 @@ it('sends the viewer to approve posting bug reports, then back to the report', a callRoute(actions.allow, { app: app(undefined, oauth), viewer: await t.viewer(DJ), + flags: ROLLED_OUT, url: '/report?/allow&from=/shows', form: {} }) @@ -133,6 +174,7 @@ it('comes back to the bare report page when it was opened from nowhere in partic callRoute(actions.allow, { app: app(undefined, oauth), viewer: await t.viewer(DJ), + flags: ROLLED_OUT, url: '/report?/allow', form: {} }) @@ -148,6 +190,7 @@ it("says so when the viewer's server won't let apps post bug reports, or can't b await callRoute(actions.allow, { app: app(undefined, new FakeOAuth('refusesBugReports')), viewer, + flags: ROLLED_OUT, url: '/report?/allow', form: {} }) @@ -157,6 +200,7 @@ it("says so when the viewer's server won't let apps post bug reports, or can't b await callRoute(actions.allow, { app: app(undefined, new FakeOAuth('down')), viewer, + flags: ROLLED_OUT, url: '/report?/allow', form: {} }) @@ -182,6 +226,7 @@ it('posts the report with the page and browser under it', async () => { const result = await callRoute(actions.send, { app: app(bugReports), viewer: await t.viewer(DJ), + flags: ROLLED_OUT, url: '/report?/send&from=/shows', headers: { 'user-agent': FIREFOX }, form: { title: ' Map is blank ', body: 'The map on the shows page never loads.' } @@ -201,6 +246,7 @@ it('asks for a title, keeping what was typed', async () => { const result = await callRoute(actions.send, { app: app(), viewer: await t.viewer(DJ), + flags: ROLLED_OUT, url: '/report?/send', form: { title: ' ', body: 'Something broke.' } }); @@ -222,6 +268,7 @@ it("offers GitHub instead when the report can't be posted", async () => { const result = await callRoute(actions.send, { app: app(bugReports), viewer: await t.viewer(DJ), + flags: ROLLED_OUT, url: '/report?/send', form: { title: 'Map is blank', body: 'Never loads.' } }); diff --git a/flags/catalog/inboxDm.json b/flags/catalog/inboxDm.json new file mode 100644 index 000000000..6ed7acf64 --- /dev/null +++ b/flags/catalog/inboxDm.json @@ -0,0 +1,6 @@ +{ + "$schema": "../flag.schema.json", + "key": "inboxDm", + "description": "Inbox items as Bluesky DMs from the root account. Off for an account, its settings don't offer DMs and the outbox skips what would have gone to it, which stays in the site inbox. Roll it out slowly: a burst of DMs could get the root rate limited or reported.", + "type": "ops" +} diff --git a/flags/catalog/inboxEmail.json b/flags/catalog/inboxEmail.json new file mode 100644 index 000000000..7e8ae14ab --- /dev/null +++ b/flags/catalog/inboxEmail.json @@ -0,0 +1,6 @@ +{ + "$schema": "../flag.schema.json", + "key": "inboxEmail", + "description": "Inbox email through Resend. Off for an account, its settings don't offer email and the outbox skips what would have gone to it, which stays in the site inbox. Turning it back on sends only what comes after.", + "type": "ops" +} diff --git a/flags/catalog/userinputReports.json b/flags/catalog/userinputReports.json new file mode 100644 index 000000000..7d8f75c3d --- /dev/null +++ b/flags/catalog/userinputReports.json @@ -0,0 +1,6 @@ +{ + "$schema": "../flag.schema.json", + "key": "userinputReports", + "description": "Bug reports posted to userinput.app from the reporter's own account, once USERINPUT_SPACE is set. Off for an account, Report a bug opens GitHub's issue form instead. Turn it off for everyone to send all reports to GitHub while userinput.app is down.", + "type": "ops" +} From fc4e0d29b66cbd93c6df57125a031cbd42fe4e5f Mon Sep 17 00:00:00 2001 From: botandbang <337765928+botandbang@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:58:09 -0600 Subject: [PATCH 02/22] feat(web): add kill switches for streaming, cards and happyview work, and stop caching pages for their editors pauseRecordingStream makes /media/audio answer 503 without reading the recording and leaves a DJ's own recording out of set and mix players, so their links play. pauseOgCards sends any card not already kept to the site's card without drawing it, and pages point og:image there. The site card is still drawn and kept for a day. pauseRequestIndex makes requestIndex answer indexed false after checking the token. pauseBackfills stops the set picker's and requestIndex's re-reads, refreshRecords at boot and on the directory round, and the boot's re-read of every manager's shows. pauseReconcilers skips the rounds that fix drift in the root's repo (staff, manager and shared spaces, listings, calendar copies) and moving press kit spaces, at boot and on every round. Each skip logs the flag and the round. The venue and mix pages pass who can edit them to cacheBriefly, so owners, people with a role on the page and staff get no-store, as on party and event pages. Visitors keep private caching and signed-out people public. Fixes LOC-313 Fixes LOC-323 Fixes LOC-652 --- apps/web/README.md | 10 +- apps/web/docs/diagrams/jobs-and-directory.md | 10 +- apps/web/docs/diagrams/mixes-and-sets.md | 2 +- apps/web/docs/diagrams/requests-and-routes.md | 6 +- apps/web/docs/diagrams/staff-and-upkeep.md | 3 + apps/web/docs/edit-mode.md | 2 +- apps/web/src/lib/server/app.test.ts | 118 ++++++++++++++++++ apps/web/src/lib/server/app.ts | 64 ++++++---- .../web/src/lib/server/happyview/backfills.ts | 19 ++- .../server/happyview/request-index.test.ts | 10 ++ .../src/lib/server/happyview/request-index.ts | 10 +- apps/web/src/lib/server/media/audio.ts | 11 ++ apps/web/src/lib/server/meta.test.ts | 20 +++ apps/web/src/lib/server/meta.ts | 33 +++-- apps/web/src/lib/server/og/serve.test.ts | 10 +- apps/web/src/lib/server/og/serve.ts | 11 ++ .../lib/server/services/recordings.test.ts | 33 +++++ .../web/src/lib/server/services/recordings.ts | 34 +++-- .../artists/name/[[name]]/+page.server.ts | 8 +- .../artists/name/[[name]]/page.server.test.ts | 12 ++ .../routes/media/audio/[did]/[cid]/+server.ts | 3 +- .../media/audio/[did]/[cid]/server.test.ts | 20 +++ .../routes/og/artist/[mbid].png/+server.ts | 7 +- apps/web/src/routes/og/cards.test.ts | 92 +++++++++++++- .../og/mix/[slug]/[n]/[cid].png/+server.ts | 4 +- .../[slug]/[rkey]/[cid].png/+server.ts | 4 +- .../og/project/[slug]/[cid].png/+server.ts | 4 +- .../party/[key]/[...rest]/page.server.test.ts | 22 ++++ .../projects/[slug]/mixes/[n]/+page.server.ts | 10 +- .../[slug]/mixes/[n]/page.server.test.ts | 15 +++ .../sets/[did]/[rkey]/player.json/+server.ts | 2 +- .../[did]/[rkey]/player.json/server.test.ts | 32 +++++ .../venue/[key]/[[name]]/+page.server.ts | 23 ++-- .../venue/[key]/[[name]]/page.server.test.ts | 23 ++++ .../+server.ts | 3 +- .../server.test.ts | 43 ++++++- flags/catalog/pauseBackfills.json | 6 + flags/catalog/pauseOgCards.json | 6 + flags/catalog/pauseReconcilers.json | 6 + flags/catalog/pauseRecordingStream.json | 6 + flags/catalog/pauseRequestIndex.json | 6 + 41 files changed, 674 insertions(+), 89 deletions(-) create mode 100644 flags/catalog/pauseBackfills.json create mode 100644 flags/catalog/pauseOgCards.json create mode 100644 flags/catalog/pauseReconcilers.json create mode 100644 flags/catalog/pauseRecordingStream.json create mode 100644 flags/catalog/pauseRequestIndex.json diff --git a/apps/web/README.md b/apps/web/README.md index ee0edcad1..5e15b8a19 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -40,13 +40,13 @@ All data lives on the AT Protocol. Public profiles are ordinary atproto records; - `/for/djs` makes the case for joining: a real listing from the directory, what promoters search on, the profile being the DJ's own, press kits, locallibrary with its captures, the month's most played tracks, the next shows, and how listing works. The listing, the shows and the charts stream in, so the page paints first. - List a new project, or claim one an admin added. Several managers per project (crews, agents). - When a project's managers change, a new manager joins its booking threads that are still being worked out or confirmed for an upcoming show, and a manager who leaves is taken out of all of them. The promoter always stays. The same step keeps the project's backstage, its press kit request space and its press kit spaces to the current managers, leaving the people granted a press kit. The app repeats this at startup, every hour, and on the System page's bootstrap, so a change that failed part way still finishes. A thread follows the project named in the root's opening record, which the promoter can't rewrite, or for a thread opened before that record named one, in its `booking.create` audit entry (written by the app, and rebuilt only from the root's copy). A thread with neither, or where the two disagree, is left as it is. -- Acts, parties and venues each get a space under the root. Their pages ship dark behind two release flags: `spacePages` for the public act, party, venue and event pages, and `peopleSpaces` for the member pages (inviting people, invite links, asking to join, people lists). A route behind one calls `requireFlag` (`src/lib/server/http.ts`), which answers 404 while the flag is off for the viewer. A performer's space also holds the root's `computer.localnetwork.performer` record, which says whether it's an act (with what its page shows) or a DJ's own space for their backstage and managers. A venue's space holds the root's `computer.localnetwork.venue` record: its name, address and coordinates, its Foursquare place once known, and whether events naming it show at once (Anyone can list) or only once confirmed (Venue approves). Names repeat ([ADR 0016](../../docs/adr/0016-names-repeat-keys-and-handles-identify.md)): an act, party or venue goes by its space key, and its page is `///` (`spacePagePath` in `src/lib/space-paths.ts`), where the name part is only there to read: any other name, or none, redirects to the current one. Anyone signed in can add a venue, which puts nobody in its space (owning one takes a confirmed claim). Adding a place that's already a venue gives back that venue, and so does adding the same name in the same city and country unless the two are different Foursquare places. Forms pick one with the venue picker (`src/lib/components/VenuePicker.svelte`): an existing venue by name, with its city on a second line to tell same-named ones apart, or a new one by its name and its city from the city search, both through `/api/venues`, which answers 404 while `spacePages` is off. A new venue's Foursquare place stays empty until staff add it. A party's space holds the root's `computer.localnetwork.party` record: its basics (name, picture, bio, area and links) and, once it's published, when. Without that it's a draft, which only its people and staff can open; everyone else gets a 404. Its page, `/party//`, is the first built in place ([docs/edit-mode.md](docs/edit-mode.md)): its people with page.edit, or staff with Edit as staff, edit its name, picture, bio, area and links where they're shown, and Publish a draft. It also shows its hosts and cohosts who haven't hidden. `/party/new` (signed in) opens the same page empty in edit mode: Save draft starts the party as a draft with its creator as host and goes on editing it at its own address, and Publish starts it published. The dashboard's sidebar offers it while `spacePages` is on. A party's events have their pages under it at `/party///`, the event's record key and then its name to read, built in place the same way (`src/lib/server/event-page.ts`): its people with events.manage edit the name, the venue, the date and times (on the venue's clock, or until there's a venue, a time zone picked with them, which a new draft takes from its party's area, else its creator's, else UTC), the lineup (each performer by handle or act page link), the ticket link, what it's about and who can see it, and outside edit mode copy or reset a private event's link and cancel a published one. Its people and staff open any of its events; anyone else opens a published public one, or a private one from its link's `?t=` token, and gets a 404 for the rest. The page says whether the venue has confirmed it or it's waiting for the venue, and never more (ADR 0014), and links the venue's page. A listed event (published, public, not Never confirmed, and under Venue approves only once confirmed) has a public copy, a `community.lexicon.calendar.event` the root keeps in its own repo under the event's record key with its name, what it's about, its times, its status, the venue's address, coordinates and page, and its ticket link and page here (`calendarCopy` in `src/lib/server/services/events.ts`), so other calendar apps can show it. Each save and the venue confirming it rewrite it, and it's deleted once the event isn't listed. What changes listing without either (the night ending while it waits for the venue, the venue's mode or blocks) is caught by `reconcileCalendarCopies`, which runs at startup, every hour, and for the venue after its settings change, and writes only where a copy differs. While it's listed, until its night is over, and unless it's cancelled, the page has Going and Interested beside its tickets, with how many said each (`src/lib/server/services/rsvps.ts`): each writes a `community.lexicon.calendar.rsvp`, the record other AT Protocol calendar apps write, to the guest's own repo, answering the public copy, and pressing the pressed one takes the answer back. They're forms, so they work without scripts; signed out, they link to sign-in and back. A private event has neither, since an RSVP in a guest's public repo would show anyone who's going. An RSVP to a copy that's since been taken down stays in the guest's repo, counted nowhere. A night ends at 6:00 the next morning on the venue's clock (`nightEnd` in `src/lib/server/venue-time.ts`), and an event still waiting for the venue then is Never confirmed: it leaves every list, and only its party's people and staff can open it, marked so. A confirmed one just becomes a past event. The party's page lists its events until their night ends, its drafts, private ones and ones never confirmed marked for its people, and `/party//new` opens an empty event page in edit mode for its people with events.manage: Save draft makes the event as a draft and Publish makes it published. A save that would move the times onto another clock (picking a venue in another time zone, another venue, or another zone for the draft) comes back asking whether to keep them as entered or at the same moments, and each answer saves again. A venue's page, `/venue//`, shows its address, an OpenStreetMap link when its coordinates are known, and the events listed there until their night ends, each with its party and marked waiting for the venue or Confirmed. It links the venue's dashboard pages for the people who can use them (claiming it for anyone else signed in) while `peopleSpaces` is on, and leaves its owners off until they can choose to show. A performer's booking details go in a separate booking details space with the same key, which only the root is in, so members can't read them from another client ([ADR 0011](../../docs/adr/0011-booking-details-stay-out-of-the-performer-space.md)). Each space's people records say who's in it, in what role, with which capabilities, and whether they're hidden from everyone outside it. The root writes every record there, for someone who holds the capability the change needs or for staff, whose changes the audit log marks with their role. Someone always has to be left who can manage its people, unless staff decide otherwise. The space's members follow its people: everyone reads, and those with a capability that writes also write. The app repeats that at startup and every hour, so a member update that failed part way still finishes. +- Acts, parties and venues each get a space under the root. Their pages ship dark behind two release flags: `spacePages` for the public act, party, venue and event pages, and `peopleSpaces` for the member pages (inviting people, invite links, asking to join, people lists). A route behind one calls `requireFlag` (`src/lib/server/http.ts`), which answers 404 while the flag is off for the viewer. A performer's space also holds the root's `computer.localnetwork.performer` record, which says whether it's an act (with what its page shows) or a DJ's own space for their backstage and managers. A venue's space holds the root's `computer.localnetwork.venue` record: its name, address and coordinates, its Foursquare place once known, and whether events naming it show at once (Anyone can list) or only once confirmed (Venue approves). Names repeat ([ADR 0016](../../docs/adr/0016-names-repeat-keys-and-handles-identify.md)): an act, party or venue goes by its space key, and its page is `///` (`spacePagePath` in `src/lib/space-paths.ts`), where the name part is only there to read: any other name, or none, redirects to the current one. Anyone signed in can add a venue, which puts nobody in its space (owning one takes a confirmed claim). Adding a place that's already a venue gives back that venue, and so does adding the same name in the same city and country unless the two are different Foursquare places. Forms pick one with the venue picker (`src/lib/components/VenuePicker.svelte`): an existing venue by name, with its city on a second line to tell same-named ones apart, or a new one by its name and its city from the city search, both through `/api/venues`, which answers 404 while `spacePages` is off. A new venue's Foursquare place stays empty until staff add it. A party's space holds the root's `computer.localnetwork.party` record: its basics (name, picture, bio, area and links) and, once it's published, when. Without that it's a draft, which only its people and staff can open; everyone else gets a 404. Its page, `/party//`, is the first built in place ([docs/edit-mode.md](docs/edit-mode.md)): its people with page.edit, or staff with Edit as staff, edit its name, picture, bio, area and links where they're shown, and Publish a draft. It also shows its hosts and cohosts who haven't hidden. `/party/new` (signed in) opens the same page empty in edit mode: Save draft starts the party as a draft with its creator as host and goes on editing it at its own address, and Publish starts it published. The dashboard's sidebar offers it while `spacePages` is on. A party's events have their pages under it at `/party///`, the event's record key and then its name to read, built in place the same way (`src/lib/server/event-page.ts`): its people with events.manage edit the name, the venue, the date and times (on the venue's clock, or until there's a venue, a time zone picked with them, which a new draft takes from its party's area, else its creator's, else UTC), the lineup (each performer by handle or act page link), the ticket link, what it's about and who can see it, and outside edit mode copy or reset a private event's link and cancel a published one. Its people and staff open any of its events; anyone else opens a published public one, or a private one from its link's `?t=` token, and gets a 404 for the rest. The page says whether the venue has confirmed it or it's waiting for the venue, and never more (ADR 0014), and links the venue's page. A listed event (published, public, not Never confirmed, and under Venue approves only once confirmed) has a public copy, a `community.lexicon.calendar.event` the root keeps in its own repo under the event's record key with its name, what it's about, its times, its status, the venue's address, coordinates and page, and its ticket link and page here (`calendarCopy` in `src/lib/server/services/events.ts`), so other calendar apps can show it. Each save and the venue confirming it rewrite it, and it's deleted once the event isn't listed. What changes listing without either (the night ending while it waits for the venue, the venue's mode or blocks) is caught by `reconcileCalendarCopies`, which runs at startup, every hour, and for the venue after its settings change, and writes only where a copy differs. While it's listed, until its night is over, and unless it's cancelled, the page has Going and Interested beside its tickets, with how many said each (`src/lib/server/services/rsvps.ts`): each writes a `community.lexicon.calendar.rsvp`, the record other AT Protocol calendar apps write, to the guest's own repo, answering the public copy, and pressing the pressed one takes the answer back. They're forms, so they work without scripts; signed out, they link to sign-in and back. A private event has neither, since an RSVP in a guest's public repo would show anyone who's going. An RSVP to a copy that's since been taken down stays in the guest's repo, counted nowhere. A night ends at 6:00 the next morning on the venue's clock (`nightEnd` in `src/lib/server/venue-time.ts`), and an event still waiting for the venue then is Never confirmed: it leaves every list, and only its party's people and staff can open it, marked so. A confirmed one just becomes a past event. The party's page lists its events until their night ends, its drafts, private ones and ones never confirmed marked for its people, and `/party//new` opens an empty event page in edit mode for its people with events.manage: Save draft makes the event as a draft and Publish makes it published. A save that would move the times onto another clock (picking a venue in another time zone, another venue, or another zone for the draft) comes back asking whether to keep them as entered or at the same moments, and each answer saves again. A venue's page, `/venue//`, shows its address, an OpenStreetMap link when its coordinates are known, and the events listed there until their night ends, each with its party and marked waiting for the venue or Confirmed. It links the venue's dashboard pages for the people who can use them (claiming it for anyone else signed in) while `peopleSpaces` is on, and leaves its owners off until they can choose to show. A performer's booking details go in a separate booking details space with the same key, which only the root is in, so members can't read them from another client ([ADR 0011](../../docs/adr/0011-booking-details-stay-out-of-the-performer-space.md)). Each space's people records say who's in it, in what role, with which capabilities, and whether they're hidden from everyone outside it. The root writes every record there, for someone who holds the capability the change needs or for staff, whose changes the audit log marks with their role. Someone always has to be left who can manage its people, unless staff decide otherwise. The space's members follow its people: everyone reads, and those with a capability that writes also write. The app repeats that at startup and every hour, so a member update that failed part way still finishes. The `pauseReconcilers` flag stops that, and every other round that fixes drift in the root's repo, without a deploy. - People come into one by an invite to their account, an invite link, or a request to join that someone with people.manage approves, and choose then whether to be hidden. A link's token is shown once and only its hash is kept, and a link never lets anyone manage people. Invites last 30 days and links 7 unless their maker picks up to 90, someone can have 50 open in a space at once, and both go when their maker can no longer add people, unless staff made them. - When staff list one, the root writes a `computer.localnetwork.listing` record to its public repo with what its public page shows, the people in a listed role (an act's members, a party's hosts and cohosts) who haven't hidden, and an act's managers who haven't. It's rewritten only when that changes, and checked every hour. A listing points at a public page, so none is written until `spacePages` is on for everyone, and turning it off takes them down at the next hourly check. Acts, parties and venues have something to list: an act's form, basics and performer sections, a published party's basics (each avatar is a blob the root uploaded), and a venue's name, address and coordinates. A published party is public at its address before it's listed; a draft is never listed. A venue is listed as soon as it's added, since it's a public place, and a DJ's own space is never listed. HappyView keeps only the root's listings (`lua/computer/localnetwork/listing.lua`). Staff see every space and its people, hidden ones marked, at `/admin/spaces`, where they add and remove people, change roles, and list or unlist it. - Profiles cover genres, city and travel radius, set types and lengths, formats, room sizes, any number of fee levels (each a tier, with an optional label and range), links, playable SoundCloud/Mixcloud/YouTube mixes, highlights, photo. - A mix can carry a tracklist: a mix report exported from [locallibrary](../locallibrary) (`locallibrary mix … --export`), shown at `/projects//mixes/` with the waveform and track lanes, tempo, key moves on the Camelot wheel, and every transition. `/mixes/preview` renders an export locally without uploading it. - A mix can also link a set a manager published with locallibrary (`locallibrary sets publish`), picked from a list on the new-project and edit forms. The profile shows when and where it was played, and says so if the set changed after it was linked. -- Sets with a recording play on the site, with the tracklist following along and a track's start to jump to. The server picks what plays when someone presses Play (`/sets///player.json`): the set's `recording` record first (an `fm.plyr.track`, whose file comes from plyr.fm's CDN, or plyr's own player when the track is gated; or a `computer.localnetwork.dj.recording` on the DJ's PDS, streamed through `/media/audio//`), then its links (archive.org downloads play directly, SoundCloud, Mixcloud, YouTube and plyr.fm in their own players). Audio the page plays itself always wins over a platform's player. SoundCloud's and Mixcloud's widget APIs let the tracklist follow those players too. `/sets///chapters.json` serves the tracklist as Podcasting 2.0 JSON chapters. +- Sets with a recording play on the site, with the tracklist following along and a track's start to jump to. The server picks what plays when someone presses Play (`/sets///player.json`): the set's `recording` record first (an `fm.plyr.track`, whose file comes from plyr.fm's CDN, or plyr's own player when the track is gated; or a `computer.localnetwork.dj.recording` on the DJ's PDS, streamed through `/media/audio//`), then its links (archive.org downloads play directly, SoundCloud, Mixcloud, YouTube and plyr.fm in their own players). Audio the page plays itself always wins over a platform's player. While the `pauseRecordingStream` flag is on, a recording on a PDS is left out, so the links play, and `/media/audio` answers 503 without reading anything. SoundCloud's and Mixcloud's widget APIs let the tracklist follow those players too. `/sets///chapters.json` serves the tracklist as Podcasting 2.0 JSON chapters. - Private booking details (email, phone, rates, tech rider, hospitality), shown to the project's managers and staff on its pages, and to everyone else only inside a press kit they've been let into, so each look at them leaves a receipt. - The project form and the booking inquiry keep unsent changes as a draft in the browser (`localStorage`, per account), so a reload or a trip to another page doesn't lose them. Files have to be picked again, and the draft goes once the form is sent, discarded, or back to its saved values, or its account signs out (the sign-out response sets an `ln_signed_out` cookie naming the account, and the next page load drops its drafts, so it works even if Sign out was pressed before the page's scripts ran). - A project page shows how its DJs play: the playing stats and recent sets each manager publishes from locallibrary (`computer.localnetwork.dj.profile` and `dj.set`), read from HappyView when the page loads and streamed in, so a slow answer never holds the page up. The app stores none of it; a few minutes' cache in memory keeps busy pages from asking again. @@ -233,8 +233,8 @@ Published projects, the DJ stats, sets, press kits, shows, calendar events, foll - `dj/recording.lua` keeps every account's set recordings, which locallibrary uploads and a set's `recording` points at: the audio blob as written, how long it plays and `createdAt`, and nothing else. A recording without an audio blob isn't kept. - `profile.lua` keeps every account's Local Network profile at the key `self`, as written, when each field the site reads has the type it expects. `listing/profile.lua` keeps only the root's DJ listings, each keyed by the DID it names. - `dj/profile.lua` and `locallibrary/settings.lua` keep every account's DJ stats and rekordbox settings as written, at the key `self`. `epk.lua` keeps press kits of the root's projects: the root's own, and legacy ones by an account that manages the project they name. -- Jetstream only brings records written after HappyView started keeping them, so the app has HappyView re-read the root's and the managers' sets, recordings, stats, press kits, calendar events, profiles and Bluesky profiles from their PDS: for each of them once per version of each one's record script (one job per 500 accounts per collection, retried until all start, the version kept in the app database), and when a project gains a manager and HappyView serves it (their follows too). The same goes, once per script version, for the follows of the managers of projects whose press kits read follows, the root's verifications and DJ listings, and the bug report space. The edit form's set picker also re-reads its accounts' sets when it opens (one backfill for all of them, each account at most every ten minutes); publishing a project's first press kit that reads follows re-reads its managers' follows; and a profile or the space HappyView doesn't have yet is re-read, and waited for, when it's needed. -- locallibrary reads its account's sets, recordings, stats and settings back from HappyView before replacing them, so it first calls `computer.localnetwork.directory.requestIndex`, a procedure this app answers itself (`src/routes/xrpc/`) with inter-service auth from the account's PDS. It has HappyView re-read those four collections from the caller's repo, and only theirs, under the picker's limit (each account and collection at most every ten minutes; a call in between answers from the last re-read), and waits up to 5 seconds: `indexed` says whether it finished. +- Jetstream only brings records written after HappyView started keeping them, so the app has HappyView re-read the root's and the managers' sets, recordings, stats, press kits, calendar events, profiles and Bluesky profiles from their PDS: for each of them once per version of each one's record script (one job per 500 accounts per collection, retried until all start, the version kept in the app database), and when a project gains a manager and HappyView serves it (their follows too). The same goes, once per script version, for the follows of the managers of projects whose press kits read follows, the root's verifications and DJ listings, and the bug report space. The edit form's set picker also re-reads its accounts' sets when it opens (one backfill for all of them, each account at most every ten minutes); publishing a project's first press kit that reads follows re-reads its managers' follows; and a profile or the space HappyView doesn't have yet is re-read, and waited for, when it's needed. The `pauseBackfills` flag stops the re-reads for a new script version, the boot's re-read of every manager's shows, and the set picker's and requestIndex's without a deploy; the re-reads that follow one change still run. +- locallibrary reads its account's sets, recordings, stats and settings back from HappyView before replacing them, so it first calls `computer.localnetwork.directory.requestIndex`, a procedure this app answers itself (`src/routes/xrpc/`) with inter-service auth from the account's PDS. It has HappyView re-read those four collections from the caller's repo, and only theirs, under the picker's limit (each account and collection at most every ten minutes; a call in between answers from the last re-read), and waits up to 5 seconds: `indexed` says whether it finished. While the `pauseRequestIndex` flag is on, it answers `indexed: false` without re-reading anything. - `show.lua` keeps only shows with coordinates and an RFC 3339 start time by an account that manages the project they name, and only http(s) ticket links; `follow.lua` keeps only follows of the root's projects and of the profiles HappyView keeps, leaving out an account following its own. Jetstream sends every account's calendar events, from every calendar app, so `community/lexicon/calendar/event.lua` keeps only the root's (party events' public copies) and events by an account that manages one of the root's projects, as written. It checks the author rather than a show naming the event, so it doesn't matter which of the two HappyView hears of first. Listings read each show's own copy; the event is for the announce form, and the show's strongRef to it says when it changed since. `community/lexicon/calendar/rsvp.lua` keeps RSVPs from any calendar app to the root's calendar events, by the subject's URI, with just the event and the answer. - Other apps' records get gates too, since Jetstream sends every account's. `app/bsky/graph/verification.lua` keeps only the root's verifications. `app/bsky/actor/profile.lua` keeps every account's Bluesky profile (at the key `self`) as written: the hosted instance backfills all of them and keeps them current, so an account that becomes a manager, gets verified or makes a profile here later already has one. The site reads only the display names and pronouns: profile pages show the pronouns and verification statuses compare the names. Saving a profile has HappyView re-read that account's Bluesky profile. The profile form shows the pronouns but can't change them yet. `app/bsky/graph/follow.lua` keeps only the subject and date of follows by the managers of a project with a press kit that treats people they follow differently from anyone, since any of them following someone counts. `app/userinput/space.lua` keeps only `USERINPUT_SPACE`, whose version each bug report pins (record scripts get it beside `ROOT_DID`). Follows and profiles are busy: on 2026-10-24 Bluesky carried about 42 follow events and 1.3 profile changes a second. HappyView runs a script for each, which cost about 1.3 ms of CPU on a laptop under HappyView 2, nearly all of it HappyView's own cost per script run; the profile script now only checks the record key. The follow gate first looks up the root projects the follower manages, which ends it for nearly every follow. On the shared store a gate only hides records it has run over, so an account's raw follows show up in `listRecords` until it has; the site only reads follows by manager, for press kits that read them. HappyView 3 writes an event log row for each run only with verbose event logging on, so keep that off. - `listShows` lists upcoming shows by project, near a place, or by the projects an account follows, and checks again that each show's announcer still manages its active project. `getShows` looks shows up by URI, `getFollowStatus` counts a project's or a profile's followers and finds an account's follow, and `getRsvpStatus` counts who's going to and interested in a party event, each account once by its latest RSVP, and finds an account's RSVPs to it. Anyone can follow or RSVP, so those counts page through `happyview.db` rather than SQL keyed by account. @@ -467,7 +467,7 @@ src/lib/server/meta.ts What each public page tells link previews and se src/lib/server/meta-records.ts The records behind a public page, written into its head as at-tags (`at:canonical`, `at:alternate`, `at:author`) src/lib/server/structured-data.ts The schema.org structured data (JSON-LD) a performer, profile, mix or artist page adds to its `meta` src/lib/og/cards/ The link-preview pictures (1200×630), one Svelte component each, with their stories -src/lib/server/og/ Draws them as PNGs for src/routes/og/, keeping recent ones in memory +src/lib/server/og/ Draws them as PNGs for src/routes/og/, keeping recent ones in memory; with `pauseOgCards` on, only the site's card is drawn and pages point to it src/routes/ SvelteKit 3 pages, form actions, and endpoints tests/integration/ Flows against an in-process spaces PDS and a HappyView container tests/e2e/ Playwright diff --git a/apps/web/docs/diagrams/jobs-and-directory.md b/apps/web/docs/diagrams/jobs-and-directory.md index 8680e4530..e4f0447a1 100644 --- a/apps/web/docs/diagrams/jobs-and-directory.md +++ b/apps/web/docs/diagrams/jobs-and-directory.md @@ -12,7 +12,7 @@ Startup, scheduled jobs and HappyView. The rest are listed in the [README](../.. ## Startup -What happens when the process starts. A failed start leaves the setup page up, and the next request tries again. +What happens when the process starts. A failed start leaves the setup page up, and the next request tries again. While the `pauseReconcilers` flag is on for everyone, bootstrap skips the reconcile steps and `moveKitSpaces`, logging each one it skips. ```mermaid flowchart TD @@ -35,7 +35,7 @@ Source: [`src/hooks.server.ts`](../../src/hooks.server.ts), [`src/lib/server/app ## Scheduled jobs -The jobs the app schedules, all in one process. A job still running skips its next turn. +The jobs the app schedules, all in one process. A job still running skips its next turn. While the `pauseReconcilers` flag is on for everyone, the rounds that write to the root's repo (staff-spaces, manager-spaces, shared-spaces, listings, venue-blocks and calendar-copies) skip their turn and log that they did. ```mermaid flowchart LR @@ -59,7 +59,7 @@ Source: [`src/lib/server/app.ts`](../../src/lib/server/app.ts), [`src/lib/server ## Directory sync -What `syncDirectory` does with `HAPPYVIEW_API_KEY` set, at boot and from the System page. A failed upload or root re-read is kept for the System page and retried. The re-reads after it only log a failure. +What `syncDirectory` does with `HAPPYVIEW_API_KEY` set, at boot and from the System page. A failed upload or root re-read is kept for the System page and retried. The re-reads after it only log a failure. While the `pauseBackfills` flag is on for everyone, the shows and refreshRecords re-reads are skipped and logged, here and on the directory-sync round; the root's performers are still re-read, since the directory lists nothing without them. ```mermaid flowchart TD @@ -76,7 +76,7 @@ Source: [`src/lib/server/happyview/sync.ts`](../../src/lib/server/happyview/sync ## HappyView re-reads -What makes the app ask HappyView to read repos again through `/admin/backfill`, up to 500 accounts a job. Jetstream only brings new writes, so these fill the gaps; on the hosted instance's shared Network store, they run the record script over what the store holds. +What makes the app ask HappyView to read repos again through `/admin/backfill`, up to 500 accounts a job. Jetstream only brings new writes, so these fill the gaps; on the hosted instance's shared Network store, they run the record script over what the store holds. The `pauseBackfills` flag stops the ones for a new record script, the managers' shows at boot, the set picker's and requestIndex's; the ones that follow one change (a new manager, a late write, a first press kit, a DJ listing) still run. ```mermaid flowchart LR @@ -107,6 +107,8 @@ sequenceDiagram A->>A: Check audience,
method and signature alt Check fails A-->>L: 401 + else pauseRequestIndex is on + A-->>L: indexed: false else par sets, recordings, stats, settings, all at once A->>H: Backfill the issuer's repo,
unless done in the last 10 minutes diff --git a/apps/web/docs/diagrams/mixes-and-sets.md b/apps/web/docs/diagrams/mixes-and-sets.md index f42540fb5..3d6422c3c 100644 --- a/apps/web/docs/diagrams/mixes-and-sets.md +++ b/apps/web/docs/diagrams/mixes-and-sets.md @@ -83,7 +83,7 @@ flowchart TD Set --> Recording{"Its recording?"} Recording -- "fm.plyr.track" --> Plyr["api.plyr.fm: file on audio.plyr.fm,
or plyr's player if it's gated"] Recording -- "dj.recording by an
active performer's manager" --> Stream["/media/audio/[did]/[cid]"] - Recording -- "none, or it won't resolve" --> Links["Its links: archive.org plays directly,
others in their own players"] + Recording -- "none, it won't resolve, or a dj.recording
while pauseRecordingStream is on" --> Links["Its links: archive.org plays directly,
others in their own players"] Stream --> Blob["getBlob from the DJ's PDS,
Range answered by the app, nothing stored"] ``` diff --git a/apps/web/docs/diagrams/requests-and-routes.md b/apps/web/docs/diagrams/requests-and-routes.md index 62090acd3..9a0e391cd 100644 --- a/apps/web/docs/diagrams/requests-and-routes.md +++ b/apps/web/docs/diagrams/requests-and-routes.md @@ -72,7 +72,7 @@ What each response lets a browser or a shared cache keep. Pages that show the sa ```mermaid flowchart LR Responses["Cache-Control"] - Responses -- "/charts, /artists pages: 60 s" --> Brief["cacheBriefly: public with no session
cookie, else private, Vary: Cookie;
no-store for anyone who can edit it"] + Responses -- "/charts, /artists, party, venue
and event pages: 60 s" --> Brief["cacheBriefly: public with no session
cookie, else private, Vary: Cookie;
no-store for anyone who can edit it"] Responses -- "an active performer's
mix page: 5 minutes" --> Brief Responses -- "/media, recordings, most /og cards" --> Year["public, a year, immutable"] Responses -- "/og artist cards, /og/site.png" --> Hour["public, an hour and a day"] @@ -83,10 +83,10 @@ flowchart LR Responses -- "player.json, chapters.json" --> Sets["public, 1 and 5 minutes"] Responses -- "client metadata, did.json" --> Docs["public, 10 and 5 minutes"] Responses -- "getFlags without a token" --> Flags["public, a minute,
Vary: Authorization"] - Responses -- "/healthz, token exchange, audit export,
getFlags with a token" --> Never["no-store"] + Responses -- "/healthz, token exchange, audit export,
getFlags with a token, paused cards
and recordings" --> Never["no-store"] ``` -Source: [`src/lib/server/http.ts`](../../src/lib/server/http.ts), [`src/routes/charts/+page.server.ts`](../../src/routes/charts/+page.server.ts), [`src/routes/projects/[slug]/mixes/[n]/+page.server.ts`](../../src/routes/projects/[slug]/mixes/[n]/+page.server.ts), [`src/routes/media/[did]/[cid]/+server.ts`](../../src/routes/media/[did]/[cid]/+server.ts), [`src/lib/server/og/serve.ts`](../../src/lib/server/og/serve.ts), [`src/routes/projects/[slug]/press-kits/[rkey]/photos/[cid]/+server.ts`](../../src/routes/projects/[slug]/press-kits/[rkey]/photos/[cid]/+server.ts), [`src/routes/api/places/+server.ts`](../../src/routes/api/places/+server.ts), [`src/routes/sets/[did]/[rkey]/player.json/+server.ts`](../../src/routes/sets/[did]/[rkey]/player.json/+server.ts), [`src/lib/server/flags/get-flags.ts`](../../src/lib/server/flags/get-flags.ts) +Source: [`src/lib/server/http.ts`](../../src/lib/server/http.ts), [`src/routes/charts/+page.server.ts`](../../src/routes/charts/+page.server.ts), [`src/routes/venue/[key]/[[name]]/+page.server.ts`](../../src/routes/venue/[key]/[[name]]/+page.server.ts), [`src/routes/projects/[slug]/mixes/[n]/+page.server.ts`](../../src/routes/projects/[slug]/mixes/[n]/+page.server.ts), [`src/routes/media/[did]/[cid]/+server.ts`](../../src/routes/media/[did]/[cid]/+server.ts), [`src/lib/server/og/serve.ts`](../../src/lib/server/og/serve.ts), [`src/routes/projects/[slug]/press-kits/[rkey]/photos/[cid]/+server.ts`](../../src/routes/projects/[slug]/press-kits/[rkey]/photos/[cid]/+server.ts), [`src/routes/api/places/+server.ts`](../../src/routes/api/places/+server.ts), [`src/routes/sets/[did]/[rkey]/player.json/+server.ts`](../../src/routes/sets/[did]/[rkey]/player.json/+server.ts), [`src/lib/server/flags/get-flags.ts`](../../src/lib/server/flags/get-flags.ts) ## Error paths diff --git a/apps/web/docs/diagrams/staff-and-upkeep.md b/apps/web/docs/diagrams/staff-and-upkeep.md index 6ae4cc448..390e1c2ea 100644 --- a/apps/web/docs/diagrams/staff-and-upkeep.md +++ b/apps/web/docs/diagrams/staff-and-upkeep.md @@ -213,9 +213,12 @@ flowchart TD Head --> Hook["Server hook swaps it for the
marker in app.html"] Meta -- "a profile's picture" --> Avatar["/media/[did]/[cid]"] Meta -- "other pages" --> Card["/og/... PNG"] + Meta -- "pauseOgCards on" --> Site["/og/site.png"] Card --> Cached{"Kept in memory?"} Cached -- "yes" --> Png["Served"] Cached -- "no" --> Draw["Drawn from a Svelte card, then kept,
or 503 when too many are waiting"] + Cached -- "no, pauseOgCards on" --> Site + Site --> Png Draw --> Png ``` diff --git a/apps/web/docs/edit-mode.md b/apps/web/docs/edit-mode.md index 2ffc8cc0f..0a38271f8 100644 --- a/apps/web/docs/edit-mode.md +++ b/apps/web/docs/edit-mode.md @@ -174,7 +174,7 @@ Inside the page the same rule holds: each field takes the box its text took, the ## Caching -`cacheBriefly` lets a signed-in viewer's browser keep a page for 60 seconds (300 on mixes). Someone who can edit a page would then see the old page after saving and reloading, so a page passes the viewer's `can` (`cacheBriefly(event, 60, can)`) and answers with `no-store` whenever it isn't empty. +`cacheBriefly` lets a signed-in viewer's browser keep a page for 60 seconds (300 on mixes). Someone who can edit a page would then see the old page after saving and reloading, so a page passes the viewer's `can` (`cacheBriefly(event, 60, can)`) and answers with `no-store` whenever it isn't empty. Party, event and venue pages pass their `pageContext`'s `can`, so anyone holding a capability in the space gets `no-store`, and so do staff. A venue's people change it from the dashboard rather than in place, but come back to the page to see it. A mix page passes `page.edit` for its project's managers and staff. ## What the server adds diff --git a/apps/web/src/lib/server/app.test.ts b/apps/web/src/lib/server/app.test.ts index 07a8d417a..44e331307 100644 --- a/apps/web/src/lib/server/app.test.ts +++ b/apps/web/src/lib/server/app.test.ts @@ -6,6 +6,7 @@ import { cidForLex } from '@atproto/lex-cbor'; import { jsonToLex } from '@atproto/lex-json'; import { createSpaceCredential } from '@atproto/space'; import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { z } from 'zod'; import { COLLECTION, DIRECTORY, VERIFICATION } from '#lib/nsid.ts'; import { type App, createApp, getApp } from './app'; import { rootSpacePolicies } from './bootstrap'; @@ -470,6 +471,37 @@ describe('syncDirectory', () => { expect(verification).toBeDefined(); }); + it('starts no re-reads of older records or shows while pauseBackfills is on, saying so', async () => { + const collections: string[] = []; + + net.routes.set('POST /admin/backfill', async (request) => { + collections.push(z.object({ collection: z.string() }).parse(await request.json()).collection); + + return Response.json({ id: 'job', status: 'running' }, { status: 201 }); + }); + const { logger, notes } = writtenLog('info'); + const app = await start({ FLAG_OVERRIDES: 'pauseBackfills=on' }, logger); + await app.refreshRecords(); + + const refreshed = await app.db + .selectFrom('kv') + .select('key') + .where('key', 'like', 'happyview_refreshed:%') + .execute(); + + expect(refreshed).toEqual([]); + await vi.waitFor(() => + expect( + notes() + .filter((note) => note.flag === 'pauseBackfills') + .map((note) => z.string().parse(note.round)) + .toSorted((a, b) => a.localeCompare(b)) + ).toEqual(['refresh-records', 'refresh-records', 'reindex-shows']) + ); + // The root's projects still, which the directory needs to list anything. + expect(collections).toEqual([COLLECTION.project]); + }); + it('leaves HappyView alone without an API key', async () => { const app = await start(NO_KEY); @@ -575,6 +607,92 @@ describe('start', () => { expect(getSpaces()).toBe(rootSpacePolicies(app.spaces).length); }); + describe('reconciler rounds', () => { + const STALE = `at://${ROOT}/${COLLECTION.listing}/gone`; + + /** The root's repo has the listing of a space that's gone, which the listings round deletes. */ + beforeEach(() => { + // ast-grep-ignore: no-direct-pds-read + net.routes.set('GET /xrpc/com.atproto.repo.listRecords', (_request, url) => + Response.json({ + records: + url.searchParams.get('collection') === COLLECTION.listing + ? [{ uri: STALE, cid: 'bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm', value: {} }] + : [] + }) + ); + net.routes.set('POST /xrpc/com.atproto.repo.deleteRecord', () => Response.json({})); + }); + + const deletes = () => net.seen.filter((call) => call.path === '/xrpc/com.atproto.repo.deleteRecord').length; + + // No sync round in the hour, so only the hourly rounds reach the root's PDS. + const HOURLY = { ...NO_KEY, SYNC_POLL_INTERVAL_MS: '864000000' }; + + it('fix what drifted in the root repo each hour', async () => { + const app = await start(HOURLY); + app.start(); + + await vi.advanceTimersByTimeAsync(60 * 60_000); + await vi.waitFor(() => expect(deletes()).toBe(1)); + }); + + it('skip every round while pauseReconcilers is on, saying so, and write nothing', async () => { + const { logger, notes } = writtenLog('info'); + const app = await start({ ...HOURLY, FLAG_OVERRIDES: 'pauseReconcilers=on' }, logger); + app.start(); + + await vi.advanceTimersByTimeAsync(60 * 60_000); + const skipped = () => notes().filter((note) => note.flag === 'pauseReconcilers'); + + await vi.waitFor(() => + expect(new Set(skipped().map((note) => note.round))).toEqual( + new Set(['manager-spaces', 'staff-spaces', 'shared-spaces', 'listings', 'venue-blocks', 'calendar-copies']) + ) + ); + expect(deletes()).toBe(0); + expect( + net.seen.some((call) => call.host === 'pds.test' && call.path !== '/xrpc/com.atproto.server.createSession') + ).toBe(false); + }); + + it('skip the rounds a bootstrap runs while pauseReconcilers is on', async () => { + const { logger, notes } = writtenLog('info'); + const app = await start({ ...NO_KEY, FLAG_OVERRIDES: 'pauseReconcilers=on' }, logger); + const policies = new Map(rootSpacePolicies(app.spaces).map(({ uri, policy }) => [uri, policy])); + + net.routes.set('GET /xrpc/com.atproto.space.getSpace', (_request, url) => { + const policy = policies.get(url.searchParams.get('space')!); + + return policy + ? Response.json({ space: url.searchParams.get('space'), policy }) + : Response.json({ error: 'NotFound' }, { status: 404 }); + }); + net.routes.set('GET /xrpc/com.atproto.space.listSpaces', () => Response.json({ spaces: [] })); + + await app.bootstrap(); + + expect( + new Set( + notes() + .filter((note) => note.flag === 'pauseReconcilers') + .map((note) => note.round) + ) + ).toEqual( + new Set([ + 'staff-spaces', + 'manager-spaces', + 'shared-spaces', + 'listings', + 'venue-blocks', + 'calendar-copies', + 'press-kit-spaces' + ]) + ); + expect(deletes()).toBe(0); + }); + }); + it("logs that it couldn't resume notification delivery when the outbox can't be read", async () => { const { logger, notes } = capture(); const app = await start(NO_KEY, logger); diff --git a/apps/web/src/lib/server/app.ts b/apps/web/src/lib/server/app.ts index c9efbeac5..6a3f66fd6 100644 --- a/apps/web/src/lib/server/app.ts +++ b/apps/web/src/lib/server/app.ts @@ -242,14 +242,14 @@ export async function createApp(options: CreateAppOptions) { const happyView = new HappyViewClient(config.happyView); const bundle = () => happyViewBundle(rootDid, config.userinputSpace); - const backfills = new Backfills(happyView, logger.child({ component: 'backfills' })); - const plyr = new PlyrClient(logger.child({ component: 'plyr' })); - const projects = new ProjectService(core, happyView, INDEX_WAIT_MS, backfills, plyr); const staff = new StaffService(core); const flags = new FlagService(core, staff, config.flagOverrides); if (Object.keys(config.flagOverrides).length > 0) logger.warn('flags forced by FLAG_OVERRIDES', { flags: config.flagOverrides }); + const backfills = new Backfills(happyView, logger.child({ component: 'backfills' }), flags); + const plyr = new PlyrClient(logger.child({ component: 'plyr' })); + const projects = new ProjectService(core, happyView, INDEX_WAIT_MS, backfills, plyr); const planner = new PlannerService(core); const projectAdmin = new ProjectAdmin(core, projects); const tracklists = new TracklistService(core); @@ -396,6 +396,23 @@ export async function createApp(options: CreateAppOptions) { timers.push(timer); }; + /** + * Whether `flag`, a kill switch for background work that's only ever on for everyone, has paused `round`. It notes + * the skip, so staff can see the switch working. + */ + const paused = async (flag: 'pauseBackfills' | 'pauseReconcilers', round: string) => { + const on = (await flags.evaluate(null))[flag]; + + if (on) logger.info('paused by a flag', { flag, round }); + + return on; + }; + + /** Runs one of the rounds that fix drift in the root's repo, unless pauseReconcilers is on. */ + const reconcile = async (round: string, work: () => Promise) => { + if (!(await paused('pauseReconcilers', round))) await work(); + }; + const app = { config, logger, @@ -497,9 +514,13 @@ export async function createApp(options: CreateAppOptions) { logger.info('synced the HappyView directory', uploaded); directorySync = { at: nowIso(), error: null }; // In the background: the shows Jetstream missed don't hold the app up. - void logger.job('reindex-shows', () => - shows.reindexManagers().catch((error) => logger.warn('could not re-read shows', { err: error })) - ); + void logger.job('reindex-shows', async () => { + try { + if (!(await paused('pauseBackfills', 'reindex-shows'))) await shows.reindexManagers(); + } catch (error) { + logger.warn('could not re-read shows', { err: error }); + } + }); await app.refreshRecords(uploaded.scripts); } catch (error) { logger.error('could not sync the HappyView directory', { err: error }); @@ -511,10 +532,10 @@ export async function createApp(options: CreateAppOptions) { * Has HappyView re-read, once for each collection's current record script (`uploaded` lists the scripts it just * got), the older records the site reads from other repos (refreshTargets), with the follows of the accounts press * kits' audience checks read. A failure is logged and tried again on the next round, without marking the directory - * sync failed. + * sync failed. pauseBackfills skips it; a script whose version changed gets its re-reads on a round once it's off. */ async refreshRecords(uploaded: string[] = []) { - if (!config.happyView.apiKey) return; + if (!config.happyView.apiKey || (await paused('pauseBackfills', 'refresh-records'))) return; const { scripts } = bundle(); const refreshes = refreshTargets(rootDid, { @@ -540,17 +561,17 @@ export async function createApp(options: CreateAppOptions) { const watched = await ensureRootSpaces(core); for (const space of watched) await syncer.watch(space); - await staff.reconcileMembership(); - await projects.reconcileManagerSpaces(); - await sharedSpaces.reconcile(); + await reconcile('staff-spaces', () => staff.reconcileMembership()); + await reconcile('manager-spaces', () => projects.reconcileManagerSpaces()); + await reconcile('shared-spaces', () => sharedSpaces.reconcile()); bootstrapped = true; await syncer.syncAll(); // After the sync, so the index has every space's people, and the requests and grants left in press kit spaces. - await listings.reconcile(); - await venues.reconcileBlocks(); + await reconcile('listings', () => listings.reconcile()); + await reconcile('venue-blocks', () => venues.reconcileBlocks()); // After the blocks, which decide which events are listed. - await events.reconcileCalendarCopies(); - await moveKitSpaces(core, epks); + await reconcile('calendar-copies', () => events.reconcileCalendarCopies()); + await reconcile('press-kit-spaces', () => moveKitSpaces(core, epks)); }, start() { @@ -574,23 +595,24 @@ export async function createApp(options: CreateAppOptions) { }, 'oauth-state-cleanup' ); + // The rounds through calendar-copies fix drift in the root's repo, and pauseReconcilers skips them. // Finishes manager syncs that failed or raced a new thread. Costs one listRecords of the root's projects and // one listMembers per booking thread, all on the root's own PDS, and writes only where something drifted. - every(60 * 60_000, () => projects.reconcileManagerSpaces(), 'manager-spaces'); + every(60 * 60_000, () => reconcile('manager-spaces', () => projects.reconcileManagerSpaces()), 'manager-spaces'); // Finishes failed removals from the staff spaces, sooner than the rest because of what those spaces hold. Costs one // listSpaceRecords and four listMembers on the root's own PDS, and writes only where something drifted. - every(5 * 60_000, () => staff.reconcileMembership(), 'staff-spaces'); + every(5 * 60_000, () => reconcile('staff-spaces', () => staff.reconcileMembership()), 'staff-spaces'); // Finishes member updates of performers', parties' and venues' spaces that failed part way: a listSpaces per // kind, then one listRecords and one listMembers per space, all on the root's own PDS. - every(60 * 60_000, () => sharedSpaces.reconcile(), 'shared-spaces'); + every(60 * 60_000, () => reconcile('shared-spaces', () => sharedSpaces.reconcile()), 'shared-spaces'); // Rewrites listings that drifted from their spaces: one listRecords of the root's listings, and writes only // where one differs. - every(60 * 60_000, () => listings.reconcile(), 'listings'); + every(60 * 60_000, () => reconcile('listings', () => listings.reconcile()), 'listings'); // Indexes the root's venue blocks and drops ones that are gone: one listRecords of the root's own repo. - every(60 * 60_000, () => venues.reconcileBlocks(), 'venue-blocks'); + every(60 * 60_000, () => reconcile('venue-blocks', () => venues.reconcileBlocks()), 'venue-blocks'); // Takes down the calendar copies of events whose night ended while they waited for the venue, and fixes any that // drifted: one listRecords of the root's own repo, and writes only where a copy differs. - every(60 * 60_000, () => events.reconcileCalendarCopies(), 'calendar-copies'); + every(60 * 60_000, () => reconcile('calendar-copies', () => events.reconcileCalendarCopies()), 'calendar-copies'); every(60 * 60_000, () => epkViews.expire(), 'epk-view-expiry'); every(60 * 60_000, () => Promise.all([notifications.prune(), outbox.prune()]), 'inbox-retention'); every(15_000, () => outbox.processDue(), 'notification-delivery'); diff --git a/apps/web/src/lib/server/happyview/backfills.ts b/apps/web/src/lib/server/happyview/backfills.ts index eaf16c119..6ac54c4cc 100644 --- a/apps/web/src/lib/server/happyview/backfills.ts +++ b/apps/web/src/lib/server/happyview/backfills.ts @@ -1,4 +1,5 @@ import type { Logger } from '../logger'; +import type { FlagService } from '../services/flags'; import { BACKFILL_FAILED, type HappyViewClient } from './client'; /** How long a caller waits for HappyView to read an account's records before going on without them. */ @@ -11,22 +12,32 @@ const EVERY_MS = 10 * 60_000; * Has HappyView re-read accounts' records of a collection from their PDS, for records Jetstream never brought (ones * written before HappyView kept that collection, or while it was down). Only with an API key, and at most every ten * minutes per account and collection: a caller that comes while a re-read runs, or soon after, gets that re-read's - * outcome instead of crawling the repo again. A failed one is forgotten, so the next caller tries again. + * outcome instead of crawling the repo again. A failed one is forgotten, so the next caller tries again. The pauseBackfills + * flag, on for everyone, stops new re-reads without a deploy. */ export class Backfills { private readonly last = new Map }>(); constructor( private readonly directory: HappyViewClient, - private readonly logger: Logger + private readonly logger: Logger, + /** The app's, for pauseBackfills. Without it, re-reads are never paused. */ + private readonly flags?: Pick ) {} /** - * Whether HappyView finished re-reading every account in `dids` within five seconds: false without an API key, after - * a failure, or while it carries on reading. The accounts not read lately are read together, in one job per 500. + * Whether HappyView finished re-reading every account in `dids` within five seconds: false without an API key, while + * paused, after a failure, or while it carries on reading. The accounts not read lately are read together, in one job per 500. */ async backfill(collection: string, dids: string[]): Promise { if (!this.directory.admin) return false; + + if ((await this.flags?.evaluate(null))?.pauseBackfills) { + this.logger.info('HappyView re-reads paused', { collection, accounts: dids.length, flag: 'pauseBackfills' }); + + return false; + } + const reads: Promise[] = []; const due: string[] = []; diff --git a/apps/web/src/lib/server/happyview/request-index.test.ts b/apps/web/src/lib/server/happyview/request-index.test.ts index f6fe52887..9ee00533e 100644 --- a/apps/web/src/lib/server/happyview/request-index.test.ts +++ b/apps/web/src/lib/server/happyview/request-index.test.ts @@ -3,6 +3,7 @@ import type { JsonObject } from '@atproto/lex-json'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { z } from 'zod'; import { COLLECTION, REQUEST_INDEX } from '#lib/nsid.ts'; +import { flagsOff } from '#lib/testing/flags.ts'; import { lexicons } from '../atproto/lexicons'; import { silentLogger } from '../logger'; import { serviceJwt } from '../testing/service-jwt'; @@ -68,6 +69,7 @@ describe('requestIndex', () => { audience: AUDIENCE, getSigningKey: async () => key.did(), backfills, + paused: false, log: silentLogger }); @@ -141,6 +143,14 @@ describe('requestIndex', () => { expect(backfilled).toHaveLength(LOCALLIBRARY.length); }); + it('says nothing was re-read while pauseBackfills is on, and starts none', async () => { + const flags = { evaluate: async () => ({ ...flagsOff, pauseBackfills: true }) }; + const answer = await call(new Backfills(happyView(), silentLogger, flags), await token()); + + expect(answer).toEqual({ status: 200, body: { indexed: false } }); + expect(backfilled).toEqual([]); + }); + it("says nothing was re-read without HappyView's API key", async () => { const answer = await call(new Backfills(happyView({ admin: false }), silentLogger), await token()); diff --git a/apps/web/src/lib/server/happyview/request-index.ts b/apps/web/src/lib/server/happyview/request-index.ts index cf5a863ac..e0d907e4d 100644 --- a/apps/web/src/lib/server/happyview/request-index.ts +++ b/apps/web/src/lib/server/happyview/request-index.ts @@ -16,6 +16,8 @@ type RequestIndexOptions = { audience: string; getSigningKey: (did: string, forceRefresh: boolean) => Promise; backfills: Backfills; + /** pauseRequestIndex: the answer is that nothing was indexed, as without an API key, and HappyView is left alone. */ + paused: boolean; log: Logger; }; @@ -24,7 +26,7 @@ type RequestIndexOptions = { * records, and only theirs, since locallibrary needs the ones Jetstream never brought before it replaces them. */ export async function requestIndex(authorization: string | null, options: RequestIndexOptions): Promise { - const { audience, getSigningKey, backfills, log } = options; + const { audience, getSigningKey, backfills, paused, log } = options; let did: string; try { @@ -35,6 +37,12 @@ export async function requestIndex(authorization: string | null, options: Reques return Response.json({ error: 'AuthenticationRequired', message: 'Invalid service auth' }, { status: 401 }); } + if (paused) { + log.info('requestIndex paused', { did, flag: 'pauseRequestIndex' }); + + return Response.json({ indexed: false }); + } + const done = await Promise.all(LOCALLIBRARY_COLLECTIONS.map((collection) => backfills.backfill(collection, [did]))); const indexed = done.every(Boolean); log.info("had HappyView re-read an account's locallibrary records", { did, indexed }); diff --git a/apps/web/src/lib/server/media/audio.ts b/apps/web/src/lib/server/media/audio.ts index dffa94681..b58b1b1e9 100644 --- a/apps/web/src/lib/server/media/audio.ts +++ b/apps/web/src/lib/server/media/audio.ts @@ -2,6 +2,7 @@ import type { IdentityResolver } from '../atproto/identity'; import { audioResponse, refuse } from '../audio'; import type { Logger } from '../logger'; import type { RecordingAudio } from '../services/recordings'; +import type { Flags } from '#lib/types.ts'; /** A byte range of a file, both ends included. */ export type ByteRange = { start: number; end: number }; @@ -86,6 +87,8 @@ export type AudioRequest = { */ identity: Pick; log: Logger; + /** The request's flags, where pauseRecordingStream stops the streaming. Nothing is paused without them. */ + flags?: Partial; }; /** @@ -98,6 +101,14 @@ export async function recordingAudio(request: AudioRequest): Promise { const { did, cid } = request; const { log } = request; log.set({ recording: { did, cid, range: request.range } }); + + if (request.flags?.pauseRecordingStream) { + log.info('recording stream paused', { flag: 'pauseRecordingStream' }); + + // Not kept, so the recording plays again as soon as the flag goes off. + return refuse(503, 'Recordings are paused', { 'cache-control': 'no-store' }); + } + const audio = await request.audio(did, cid); if (!audio) { diff --git a/apps/web/src/lib/server/meta.test.ts b/apps/web/src/lib/server/meta.test.ts index 7edb41c82..dcae4c7be 100644 --- a/apps/web/src/lib/server/meta.test.ts +++ b/apps/web/src/lib/server/meta.test.ts @@ -242,4 +242,24 @@ describe('listed', () => { expect(await listed(locals, hidden, { records: lookUp, jsonLd: thing })).toBe(hidden); expect(locals.crawlerHead).toBeUndefined(); }); + + it("shows the site's card in place of a drawn one while pauseOgCards is on, and keeps a page's own picture", async () => { + const paused = { pauseOgCards: true }; + + const avatar = profileMeta( + SITE, + { did: 'did:plc:neon', handle: 'neon.test' }, + { record: { basics: {} }, avatarUrl: '/media/a' }, + 'Neon' + ); + + expect((await listed({ flags: paused }, performerMeta(SITE, project), {})).image).toEqual(SITE_CARD); + expect((await listed({ flags: paused }, mixMeta(SITE, project, { title: 'Late Room' }, 1, 3), {})).image).toEqual( + SITE_CARD + ); + expect(await listed({ flags: paused }, avatar, {})).toEqual(avatar); + expect((await listed({ flags: { pauseOgCards: false } }, performerMeta(SITE, project), {})).image?.url).toMatch( + /\/og\/project\// + ); + }); }); diff --git a/apps/web/src/lib/server/meta.ts b/apps/web/src/lib/server/meta.ts index 301a79926..f1a35753a 100644 --- a/apps/web/src/lib/server/meta.ts +++ b/apps/web/src/lib/server/meta.ts @@ -4,7 +4,7 @@ import { formatShowDate, kindLabel, placeLabel, pluralize, profileHref, setHref import { type PageImage, type PageMeta, SITE_NAME } from '#lib/meta.ts'; import { CARD } from '#lib/og/style.ts'; import { bareMbid } from '#lib/supports.ts'; -import type { AccountView, ProfileRecord, ProfileView, ProjectView } from '#lib/types.ts'; +import type { AccountView, Flags, ProfileRecord, ProfileView, ProjectView } from '#lib/types.ts'; import { type PageRecords, recordTags } from './meta-records'; import { isDrawable } from './og/drawable'; import { cardPaths } from './og/paths'; @@ -34,22 +34,33 @@ const SITE_CARD = card(cardPaths.site, `${SITE_NAME}: find local DJs for your sh const performerCard = (project: ProjectView, path: string, alt: string) => project.status === 'active' && isDrawable(project.profile.name) ? card(path, alt) : undefined; +/** `image`, its address made absolute against `base`. */ +const absolute = ({ path, ...picture }: NonNullable, base: string): PageImage => ({ + url: new URL(path, base).href, + ...picture +}); + /** A page's metadata, its addresses made absolute against the site's public URL so every page names the same host. */ export function pageMeta( publicUrl: string, { path, type = 'website', image = SITE_CARD, description, ...rest }: MetaInput ): PageMeta { - const { path: imagePath, ...picture } = image; - return { ...rest, type, description: clip(description), url: new URL(path, publicUrl).href, - image: { url: new URL(imagePath, publicUrl).href, ...picture } + image: absolute(image, publicUrl) }; } +/** Whether `image` is a card the site draws for the page (routes/og), not the site's own or a picture someone uploaded. */ +function isDrawnCard(image: PageImage | undefined): boolean { + const path = image && new URL(image.url).pathname; + + return !!path?.startsWith('/og/') && path !== cardPaths.site; +} + function clip(text: string): string { const flat = text.replace(/\s+/g, ' ').trim(); @@ -219,17 +230,21 @@ export const mixMeta = ( /** * `meta`, with what only a page search engines may list carries set aside for the server hook to write into its head: * the records behind it as at-tags, and its structured data (see crawler-head.ts). A page kept out of search gets - * neither, and its records aren't even looked up. + * neither, and its records aren't even looked up. While pauseOgCards is on, a card drawn for the page gives way to the + * site's, since the card routes don't draw then; nothing is paused without `locals.flags`. */ export async function listed( - locals: Pick, + locals: Pick & { flags?: Partial }, meta: PageMeta, { records, jsonLd }: { records?: () => PageRecords | Promise; jsonLd?: JsonLdBuilder | null } ): Promise { - if (meta.noindex) return meta; - const head = [records && recordTags(await records()), jsonLd && jsonLdScript(jsonLdFor(meta, jsonLd))]; + const shown = + locals.flags?.pauseOgCards && isDrawnCard(meta.image) ? { ...meta, image: absolute(SITE_CARD, meta.url) } : meta; + + if (shown.noindex) return shown; + const head = [records && recordTags(await records()), jsonLd && jsonLdScript(jsonLdFor(shown, jsonLd))]; locals.crawlerHead = head.filter(Boolean).join(''); - return meta; + return shown; } diff --git a/apps/web/src/lib/server/og/serve.test.ts b/apps/web/src/lib/server/og/serve.test.ts index 0643f36cb..9d9664863 100644 --- a/apps/web/src/lib/server/og/serve.test.ts +++ b/apps/web/src/lib/server/og/serve.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; import { silentLogger } from '../logger'; import type { Png } from './render'; -import { createCardServer } from './serve'; +import { createCardServer, sendToSiteCard } from './serve'; /** A card of `bytes` bytes. */ const png = (bytes: number): Png => new Uint8Array(bytes); @@ -75,4 +75,12 @@ describe('the card server', () => { // With room again, the turned-away card is drawn. expect((await server.respond(silentLogger, '/turned-away', async () => png(10))).status).toBe(200); }); + + it("sends a paused card to the site's card, not kept, so the card comes back once drawing does", () => { + const paused = sendToSiteCard(silentLogger, '/og/project/neon-tide/bafy.png'); + + expect(paused.status).toBe(302); + expect(paused.headers.get('location')).toBe('/og/site.png'); + expect(paused.headers.get('cache-control')).toBe('no-store'); + }); }); diff --git a/apps/web/src/lib/server/og/serve.ts b/apps/web/src/lib/server/og/serve.ts index 75334a8c4..796faa553 100644 --- a/apps/web/src/lib/server/og/serve.ts +++ b/apps/web/src/lib/server/og/serve.ts @@ -1,6 +1,7 @@ import { LRUCache } from 'lru-cache'; import PQueue from 'p-queue'; import type { Logger } from '../logger'; +import { cardPaths } from './paths'; import type { Png } from './render'; /** Card URLs that name a record's version: the card at one never changes. */ @@ -30,6 +31,16 @@ class Busy extends Error {} const png = (body: Png, cacheControl: string) => new Response(body, { headers: { 'content-type': 'image/png', 'cache-control': cacheControl } }); +/** + * Where a card goes while drawing is paused (pauseOgCards): to the site's card, which is drawn once and kept, so a + * crawler that read a page before the pause still gets a picture. Not kept, so the card comes back with the flag off. + */ +export function sendToSiteCard(log: Logger, path: string): Response { + log.info('card drawing paused', { card: path, flag: 'pauseOgCards' }); + + return new Response(null, { status: 302, headers: { location: cardPaths.site, 'cache-control': 'no-store' } }); +} + /** * Serves cards from a cache of `budget` bytes, least recently used out first, drawing a missing one with at most * `concurrency` drawing at once and `waiting` more queued. Past that, a request is answered 503 with Retry-After rather diff --git a/apps/web/src/lib/server/services/recordings.test.ts b/apps/web/src/lib/server/services/recordings.test.ts index 86a0f09d5..1b1ecaddd 100644 --- a/apps/web/src/lib/server/services/recordings.test.ts +++ b/apps/web/src/lib/server/services/recordings.test.ts @@ -155,6 +155,22 @@ describe('RecordingService.source', () => { }); }); + it("plays the set's links instead of a PDS recording while pauseRecordingStream is on, and plyr.fm's as before", async () => { + const { recordings } = await service([{ collection: COLLECTION.djRecording, rkey: '3rec', record: recording() }], { + plyrTrack: {} + }); + + const paused = { pauseRecordingStream: true }; + const pds = ref(`at://${DJ}/${COLLECTION.djRecording}/3rec`); + + expect(await recordings.source({ recording: pds, links: [{ uri: SOUNDCLOUD }] }, paused)).toMatchObject({ + kind: 'embed', + platform: 'SoundCloud' + }); + expect(await recordings.source({ recording: pds }, paused)).toBeNull(); + expect(await recordings.source({ recording: ref(PLYR_URI) }, paused)).toMatchObject({ from: 'plyr.fm' }); + }); + it('plays a recording without durationSeconds, which the player reads from the audio', async () => { const { recordings } = await service([ { collection: COLLECTION.djRecording, rkey: '3rec', record: recording({}, {}) } @@ -279,6 +295,23 @@ describe('RecordingService.set and forMix', () => { platform: 'SoundCloud' }); }); + + it("plays a mix's link instead of its own or its set's PDS recording while pauseRecordingStream is on", async () => { + const pds = ref(`at://${DJ}/${COLLECTION.djRecording}/3rec`); + + const { recordings } = await service([ + { collection: COLLECTION.djRecording, rkey: '3rec', record: recording() }, + set({ recording: pds }) + ]); + + const paused = { pauseRecordingStream: true }; + const linked = { uri: `at://${DJ}/${COLLECTION.djSet}/3set`, cid: 'bafyx' }; + + expect(await recordings.forMix({ url: SOUNDCLOUD, recording: pds }, paused)).toMatchObject({ + platform: 'SoundCloud' + }); + expect(await recordings.forMix({ url: SOUNDCLOUD, set: linked }, paused)).toMatchObject({ platform: 'SoundCloud' }); + }); }); describe('RecordingService.audio', () => { diff --git a/apps/web/src/lib/server/services/recordings.ts b/apps/web/src/lib/server/services/recordings.ts index 283b4a562..4938e88ee 100644 --- a/apps/web/src/lib/server/services/recordings.ts +++ b/apps/web/src/lib/server/services/recordings.ts @@ -3,7 +3,7 @@ import type { DjSet } from '#lib/dj.ts'; import { djSetSchema } from '#lib/dj-schema.ts'; import { linkSources, PLYR_TRACK, type PlayerSource, preferred } from '#lib/mix/source.ts'; import { COLLECTION } from '#lib/nsid.ts'; -import type { ProjectMix } from '#lib/types.ts'; +import type { Flags, ProjectMix } from '#lib/types.ts'; import { parsePublicRecordUri } from '../atproto/spaces'; import { RECORDING_MAX_BYTES, RECORDING_TYPES } from '../audio'; import type { IndexedRepo } from '../happyview/indexed'; @@ -64,7 +64,7 @@ class Recent { * Where a set's recording plays, decided when someone presses Play: its `recording` record (an `fm.plyr.track`, asked * of plyr.fm, or a `computer.localnetwork.dj.recording` on the DJ's PDS, served by /media/audio), then its links. * Records are read through HappyView. Recordings on a PDS play only for accounts that manage an active project, since - * the site streams their bytes. + * the site streams their bytes, and not at all while pauseRecordingStream is on, which leaves the set's links to play. */ export class RecordingService { private readonly managers: Recent; @@ -95,26 +95,29 @@ export class RecordingService { return parsed.success ? { ...parsed.data, uri: record.uri } : null; } - /** What a set plays: its recording record, then its links, audio first. */ - async source(set: Pick): Promise { - const recording = set.recording ? await this.recording(set.recording.uri) : null; + /** What a set plays: its recording record, then its links, audio first. Nothing is paused without `flags`. */ + async source(set: Pick, flags: Partial = {}): Promise { + const recording = set.recording ? await this.recording(set.recording.uri, flags) : null; return preferred([recording, ...linkSources(set.links)]); } /** * What a mix on a profile plays: its own recording record, then its linked set's recording or links, else the mix's - * own link. Never rejects, since the mix's page streams it. + * own link. Never rejects, since the mix's page streams it. Nothing is paused without `flags`. */ - async forMix(mix: Pick): Promise { + async forMix( + mix: Pick, + flags: Partial = {} + ): Promise { const own = linkSources([{ uri: mix.url }]); try { - const recording = mix.recording ? await this.recording(mix.recording.uri) : null; + const recording = mix.recording ? await this.recording(mix.recording.uri, flags) : null; const ref = mix.set && parsePublicRecordUri(mix.set.uri); const set = ref && ref.collection === COLLECTION.djSet ? await this.set(ref.did, ref.rkey) : null; - return preferred([recording, set && (await this.source(set)), ...own]); + return preferred([recording, set && (await this.source(set, flags)), ...own]); } catch (error) { this.logger.warn("could not find a mix's linked recording", { err: error, @@ -143,14 +146,21 @@ export class RecordingService { }); } - private async recording(uri: string): Promise { + private async recording(uri: string, flags: Partial): Promise { const ref = parsePublicRecordUri(uri); if (ref?.collection === PLYR_TRACK) return this.plyrTrack(uri); - if (ref?.collection === COLLECTION.djRecording) return this.pdsRecording(ref.did, uri); + if (ref?.collection !== COLLECTION.djRecording) return null; - return null; + // Only a recording on a PDS streams through the site; plyr.fm's play from plyr's CDN. + if (flags.pauseRecordingStream) { + this.logger.info('recording stream paused', { recording: uri, flag: 'pauseRecordingStream' }); + + return null; + } + + return this.pdsRecording(ref.did, uri); } /** A plyr.fm track plays from plyr's CDN, or in plyr's own player when its file isn't public. */ diff --git a/apps/web/src/routes/artists/name/[[name]]/+page.server.ts b/apps/web/src/routes/artists/name/[[name]]/+page.server.ts index 8f8e4b106..ee10d0fba 100644 --- a/apps/web/src/routes/artists/name/[[name]]/+page.server.ts +++ b/apps/web/src/routes/artists/name/[[name]]/+page.server.ts @@ -1,7 +1,7 @@ import { redirect } from '@sveltejs/kit'; import { cacheBriefly } from '#lib/server/http.ts'; import { unlessOffline } from '#lib/server/happyview/offline.ts'; -import { artistMeta } from '#lib/server/meta.ts'; +import { artistMeta, listed } from '#lib/server/meta.ts'; import { artistHref } from '#lib/supports.ts'; import type { PageServerLoad } from './$types'; @@ -20,6 +20,10 @@ export const load: PageServerLoad = async (event) => { return { supports, - meta: artistMeta(locals.app.config.publicUrl, artist.name, artistHref(artist), !!supports?.artist) + meta: await listed( + locals, + artistMeta(locals.app.config.publicUrl, artist.name, artistHref(artist), !!supports?.artist), + {} + ) }; }; diff --git a/apps/web/src/routes/artists/name/[[name]]/page.server.test.ts b/apps/web/src/routes/artists/name/[[name]]/page.server.test.ts index 37da5f062..b2bfc8f0f 100644 --- a/apps/web/src/routes/artists/name/[[name]]/page.server.test.ts +++ b/apps/web/src/routes/artists/name/[[name]]/page.server.test.ts @@ -102,3 +102,15 @@ it('names the page after the address while the directory is offline', async () = expect(data.supports).toBeNull(); expect(data.meta).toMatchObject({ title: 'Ferrule', noindex: true }); }); + +it("shows the site's card in place of the artist's while pauseOgCards is on", async () => { + const data = await loadRoute(load, { + app: app(), + params: { name: 'Ostgut Ton' }, + url: '/artists/name/Ostgut%20Ton', + flags: { pauseOgCards: true } + }); + + expect(data.meta.url).toBe(`https://localnetwork.test/artists/${MBID}`); + expect(data.meta.image?.url).toBe('https://localnetwork.test/og/site.png'); +}); diff --git a/apps/web/src/routes/media/audio/[did]/[cid]/+server.ts b/apps/web/src/routes/media/audio/[did]/[cid]/+server.ts index 01a3da848..9d5e05b93 100644 --- a/apps/web/src/routes/media/audio/[did]/[cid]/+server.ts +++ b/apps/web/src/routes/media/audio/[did]/[cid]/+server.ts @@ -17,6 +17,7 @@ export const GET: RequestHandler = async ({ params, request, locals }) => { range: request.headers.get('range'), audio: (did, cid) => app.recordings.audio(did, cid), identity: app.identity, - log + log, + flags: locals.flags }); }; diff --git a/apps/web/src/routes/media/audio/[did]/[cid]/server.test.ts b/apps/web/src/routes/media/audio/[did]/[cid]/server.test.ts index 077cf52c2..c4b1b02f3 100644 --- a/apps/web/src/routes/media/audio/[did]/[cid]/server.test.ts +++ b/apps/web/src/routes/media/audio/[did]/[cid]/server.test.ts @@ -61,3 +61,23 @@ it("is a 404 for an address that isn't a DID and a blob CID, without looking for await expect(callRoute(GET, { app, params: { did: 'dj.test', cid: CID } })).rejects.toMatchObject({ status: 404 }); await expect(callRoute(GET, { app, params: { did: DJ, cid: 'not-a-cid' } })).rejects.toMatchObject({ status: 404 }); }); + +it('answers 503 while pauseRecordingStream is on, without looking for the recording or reading it', async () => { + const app = { + recordings: { + audio: async () => { + throw new Error('looked for a recording'); + } + }, + identity: { + resolve: async () => { + throw new Error('looked for the PDS'); + } + } + }; + + const response = await callRoute(GET, { app, params: { did: DJ, cid: CID }, flags: { pauseRecordingStream: true } }); + + expect(response.status).toBe(503); + expect(response.headers.get('cache-control')).toBe('no-store'); +}); diff --git a/apps/web/src/routes/og/artist/[mbid].png/+server.ts b/apps/web/src/routes/og/artist/[mbid].png/+server.ts index 37c692683..2f3073fb7 100644 --- a/apps/web/src/routes/og/artist/[mbid].png/+server.ts +++ b/apps/web/src/routes/og/artist/[mbid].png/+server.ts @@ -3,7 +3,7 @@ import ArtistCard from '#lib/og/cards/ArtistCard.svelte'; import { unlessOffline } from '#lib/server/happyview/offline.ts'; import { cardPaths } from '#lib/server/og/paths.ts'; import { renderCard } from '#lib/server/og/render.ts'; -import { cards } from '#lib/server/og/serve.ts'; +import { cards, sendToSiteCard } from '#lib/server/og/serve.ts'; import { bareMbid } from '#lib/supports.ts'; import type { RequestHandler } from './$types'; @@ -14,7 +14,8 @@ const CACHE_CONTROL = `public, max-age=${HOUR}`; /** * An artist's link-preview card, for an artist a set credits by MusicBrainz ID. A kept card is served without asking - * the directory; while the directory is offline, a crawler is asked to come back. + * the directory; while the directory is offline, a crawler is asked to come back, and while drawing is paused it's sent + * to the site's card without asking. */ export const GET: RequestHandler = async ({ params, locals }) => { const { app, log } = locals; @@ -25,6 +26,8 @@ export const GET: RequestHandler = async ({ params, locals }) => { const kept = cards.kept(path, CACHE_CONTROL); if (kept) return kept; + + if (locals.flags.pauseOgCards) return sendToSiteCard(log, path); const supports = await unlessOffline(log, () => app.supports.artist({ mbid })); if (!supports) { diff --git a/apps/web/src/routes/og/cards.test.ts b/apps/web/src/routes/og/cards.test.ts index 7b49f02a1..723f6bf4e 100644 --- a/apps/web/src/routes/og/cards.test.ts +++ b/apps/web/src/routes/og/cards.test.ts @@ -9,11 +9,13 @@ import { COLLECTION } from '#lib/nsid.ts'; import { silentLogger } from '#lib/server/logger.ts'; import { HappyViewError } from '#lib/server/happyview/client.ts'; import { MAX_CARD_BYTES, renderCard } from '#lib/server/og/render.ts'; +import { cards } from '#lib/server/og/serve.ts'; import type { SupportService } from '#lib/server/services/supports.ts'; import type { TracklistService } from '#lib/server/services/tracklists.ts'; import { ROOT } from '#lib/server/testing/core.ts'; import { ADMIN, DJ, pressKitServices } from '#lib/server/testing/press-kits.ts'; -import type { ProjectView, TrackPlays } from '#lib/types.ts'; +import { flagsOff } from '#lib/testing/flags.ts'; +import type { Flags, ProjectView, TrackPlays } from '#lib/types.ts'; import { GET as artistCard } from './artist/[mbid].png/+server.ts'; import { GET as mixCard } from './mix/[slug]/[n]/[cid].png/+server.ts'; import { GET as pressKitCard } from './press-kit/[slug]/[rkey]/[cid].png/+server.ts'; @@ -72,9 +74,15 @@ describe('link-preview cards', () => { const get = async ( handler: (event: never) => Response | Promise, params: Record, - services: { supports?: Pick; tracklists?: Pick } = {} + services: { supports?: Pick; tracklists?: Pick } = {}, + flags: Partial = {} ): Promise => { - const locals = { app: { ...f.t, rootDid: ROOT, ...services }, viewer: null, log: silentLogger }; + const locals = { + app: { ...f.t, rootDid: ROOT, ...services }, + viewer: null, + log: silentLogger, + flags: { ...flagsOff, ...flags } + }; try { // SAFETY: these routes read only params and locals, and the services are the app's own. @@ -298,4 +306,82 @@ describe('link-preview cards', () => { it("the site's is kept for a day", async () => { expect(await card(await get(siteCard, {}))).toBe('public, max-age=86400'); }); + + describe('while pauseOgCards is on', () => { + const paused = { pauseOgCards: true }; + + /** Where a route sent a request, and whether it kept a card at `path`: the site's card, keeping none, while paused. */ + const answer = (outcome: Outcome, path: string) => ({ + status: outcome.status, + location: outcome instanceof Response ? outcome.headers.get('location') : null, + kept: cards.kept(path) !== null + }); + + const SENT_TO_SITE_CARD = { status: 302, location: '/og/site.png', kept: false }; + + /** The project with a `tagline` no other test gives it, so no card at its CID is kept from another test. */ + const retagged = async (tagline: string) => + f.t.projectAdmin.update({ + actor: await f.t.viewer(ADMIN), + project, + profile: { ...project.profile, tagline } + }); + + it("sends a performer's and a mix's card to the site's", async () => { + const current = await retagged('Paused previews'); + + expect( + answer( + await get(projectCard, { slug: current.slug, cid: current.cid }, {}, paused), + `/og/project/${current.slug}/${current.cid}.png` + ) + ).toEqual(SENT_TO_SITE_CARD); + expect( + answer( + await get(mixCard, { slug: current.slug, n: '1', cid: current.cid }, {}, paused), + `/og/mix/${current.slug}/1/${current.cid}.png` + ) + ).toEqual(SENT_TO_SITE_CARD); + }); + + it('still serves a card it kept before the pause', async () => { + const current = await retagged('Kept previews'); + const params = { slug: current.slug, cid: current.cid }; + + await get(projectCard, params); + + expect(await card(await get(projectCard, params, {}, paused))).toBe(IMMUTABLE); + }); + + it("sends a press kit's card to the site's", async () => { + const kit = await f.publish(DJ, { headline: 'Paused previews' }); + + expect( + answer( + await get(pressKitCard, { slug: project.slug, rkey: kit.rkey, cid: kit.cid }, {}, paused), + `/og/press-kit/${project.slug}/${kit.rkey}/${kit.cid}.png` + ) + ).toEqual(SENT_TO_SITE_CARD); + }); + + it("sends an artist's card to the site's without asking the directory", async () => { + const mbid = '9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d'; + + const supports = { + artist: async () => { + throw new Error('asked the directory'); + } + }; + + expect(answer(await get(artistCard, { mbid }, { supports }, paused), `/og/artist/${mbid}.png`)).toEqual( + SENT_TO_SITE_CARD + ); + }); + + it("still draws the site's card, kept for a day", async () => { + cards.cache.delete('/og/site.png'); + + expect(await card(await get(siteCard, {}, {}, paused))).toBe('public, max-age=86400'); + }); + }); }); diff --git a/apps/web/src/routes/og/mix/[slug]/[n]/[cid].png/+server.ts b/apps/web/src/routes/og/mix/[slug]/[n]/[cid].png/+server.ts index 519960ddc..0a1db1d84 100644 --- a/apps/web/src/routes/og/mix/[slug]/[n]/[cid].png/+server.ts +++ b/apps/web/src/routes/og/mix/[slug]/[n]/[cid].png/+server.ts @@ -5,7 +5,7 @@ import { PHOTO_TYPES } from '#lib/server/images.ts'; import { cardImage, dataUrlBytes, projectAvatar } from '#lib/server/og/cards.ts'; import { cardPaths } from '#lib/server/og/paths.ts'; import { renderCard } from '#lib/server/og/render.ts'; -import { cards } from '#lib/server/og/serve.ts'; +import { cards, sendToSiteCard } from '#lib/server/og/serve.ts'; import type { RequestHandler } from './$types'; const COVER = 300; @@ -25,6 +25,8 @@ export const GET: RequestHandler = async ({ params, locals }) => { if (params.cid !== project.cid) redirect(302, path); + if (locals.flags.pauseOgCards) return cards.kept(path) ?? sendToSiteCard(log, path); + try { return await cards.respond(log, path, async () => { const report = await app.tracklists.published(tracklist); diff --git a/apps/web/src/routes/og/press-kit/[slug]/[rkey]/[cid].png/+server.ts b/apps/web/src/routes/og/press-kit/[slug]/[rkey]/[cid].png/+server.ts index 438eb6beb..f529b60b9 100644 --- a/apps/web/src/routes/og/press-kit/[slug]/[rkey]/[cid].png/+server.ts +++ b/apps/web/src/routes/og/press-kit/[slug]/[rkey]/[cid].png/+server.ts @@ -5,7 +5,7 @@ import { PHOTO_TYPES } from '#lib/server/images.ts'; import { cardImage, performerCard, projectAvatar } from '#lib/server/og/cards.ts'; import { cardPaths } from '#lib/server/og/paths.ts'; import { renderCard } from '#lib/server/og/render.ts'; -import { cards } from '#lib/server/og/serve.ts'; +import { cards, sendToSiteCard } from '#lib/server/og/serve.ts'; import type { RequestHandler } from './$types'; /** @@ -22,6 +22,8 @@ export const GET: RequestHandler = async ({ params, locals }) => { if (params.cid !== kit.epk.cid) redirect(302, path); + if (locals.flags.pauseOgCards) return cards.kept(path) ?? sendToSiteCard(log, path); + return cards.respond(log, path, async () => { const first = kit.epk.record.photos?.[0]; const photo = first && (await app.epks.photo(kit.epk, first.image.ref.$link, false)); diff --git a/apps/web/src/routes/og/project/[slug]/[cid].png/+server.ts b/apps/web/src/routes/og/project/[slug]/[cid].png/+server.ts index 8a03ac264..10c65474f 100644 --- a/apps/web/src/routes/og/project/[slug]/[cid].png/+server.ts +++ b/apps/web/src/routes/og/project/[slug]/[cid].png/+server.ts @@ -3,7 +3,7 @@ import PerformerCard from '#lib/og/cards/PerformerCard.svelte'; import { performerCard, projectAvatar } from '#lib/server/og/cards.ts'; import { cardPaths } from '#lib/server/og/paths.ts'; import { renderCard } from '#lib/server/og/render.ts'; -import { cards } from '#lib/server/og/serve.ts'; +import { cards, sendToSiteCard } from '#lib/server/og/serve.ts'; import type { RequestHandler } from './$types'; /** A performer's link-preview card. Only an active project has one, as only its page is public. */ @@ -16,6 +16,8 @@ export const GET: RequestHandler = async ({ params, locals }) => { if (params.cid !== project.cid) redirect(302, path); + if (locals.flags.pauseOgCards) return cards.kept(path) ?? sendToSiteCard(log, path); + return cards.respond(log, path, async () => renderCard(PerformerCard, performerCard(project, await projectAvatar(app.core, project, 360, log))) ); diff --git a/apps/web/src/routes/party/[key]/[...rest]/page.server.test.ts b/apps/web/src/routes/party/[key]/[...rest]/page.server.test.ts index 4e816e4d8..bb1c8658e 100644 --- a/apps/web/src/routes/party/[key]/[...rest]/page.server.test.ts +++ b/apps/web/src/routes/party/[key]/[...rest]/page.server.test.ts @@ -112,6 +112,28 @@ it('gives its people with page.edit the edit bar, and opens the editor at ?edit' expect(await opened(STRANGER, `/party/${key}/night-shift?edit`)).not.toHaveProperty('role'); }); +it('keeps no copy for its people and staff, who can change it, and lets the browser keep one for anyone else', async () => { + await start(true); + + const cacheControl = async (did: string) => { + const { headers, loadData } = routeEvent({ + app: app(), + viewer: await t.viewer(did), + url: `/party/${key}/night-shift`, + params: { key, rest: 'night-shift' }, + flags: on + }); + + await loadData(load); + + return headers['cache-control']; + }; + + expect(await cacheControl(HOST)).toBe('no-store'); + expect(await cacheControl(ADMIN)).toBe('no-store'); + expect(await cacheControl(STRANGER)).toBe('private, max-age=60'); +}); + it('sends any other name, or none, on to the current one, keeping the query', async () => { await start(true); diff --git a/apps/web/src/routes/projects/[slug]/mixes/[n]/+page.server.ts b/apps/web/src/routes/projects/[slug]/mixes/[n]/+page.server.ts index a652b7fc1..dd052b5d8 100644 --- a/apps/web/src/routes/projects/[slug]/mixes/[n]/+page.server.ts +++ b/apps/web/src/routes/projects/[slug]/mixes/[n]/+page.server.ts @@ -14,8 +14,9 @@ export const load: PageServerLoad = async (event) => { if (!project) error(404, 'No project with that name'); const isManager = !!viewer && project.managers.includes(viewer.did); + const canEdit = isManager || !!viewer?.isStaff; - if (project.status !== 'active' && !isManager && !viewer?.isStaff) error(404, 'No project with that name'); + if (project.status !== 'active' && !canEdit) error(404, 'No project with that name'); const n = Number(params.n); const mix = Number.isInteger(n) && n >= 1 ? project.profile.mixes?.[n - 1] : undefined; @@ -25,8 +26,9 @@ export const load: PageServerLoad = async (event) => { try { const report = await app.tracklists.published(mix.tracklist); - // The layout's data is in the page, and a signed-in visitor's viewer and flags are theirs alone. - if (project.status === 'active') cacheBriefly(event, 300); + // The layout's data is in the page, and a signed-in visitor's viewer and flags are theirs alone. Its managers and + // staff, who can change the project, get it uncached. + if (project.status === 'active') cacheBriefly(event, 300, canEdit ? ['page.edit'] : []); return { project: { slug: project.slug, name: project.profile.name, avatarUrl: project.avatarUrl, status: project.status }, @@ -34,7 +36,7 @@ export const load: PageServerLoad = async (event) => { // Streamed, so the report shows while the directory looks up the set. sets: mix.set ? app.sets.linked([mix.set]) : undefined, // What the player plays, streamed too: the mix's or its linked set's recording may be asked of plyr.fm. - source: app.recordings.forMix(mix), + source: app.recordings.forMix(mix, locals.flags), n, report, meta: await listed(locals, mixMeta(app.config.publicUrl, project, mix, n, report.plays.length), { diff --git a/apps/web/src/routes/projects/[slug]/mixes/[n]/page.server.test.ts b/apps/web/src/routes/projects/[slug]/mixes/[n]/page.server.test.ts index 3f659d880..95d4a40b2 100644 --- a/apps/web/src/routes/projects/[slug]/mixes/[n]/page.server.test.ts +++ b/apps/web/src/routes/projects/[slug]/mixes/[n]/page.server.test.ts @@ -84,6 +84,21 @@ it("keeps a signed-in viewer's page out of shared caches", async () => { expect(headers['cache-control']).toBe('private, max-age=300'); }); +it('keeps no copy for its managers and staff, who can change it', async () => { + for (const did of [DJ, ADMIN]) { + const { loadData, headers } = routeEvent({ + app: app(), + viewer: await f.t.viewer(did), + params: { slug: project.slug, n: '1' }, + url: `/projects/${project.slug}/mixes/1` + }); + + await loadData(load); + + expect(headers['cache-control']).toBe('no-store'); + } +}); + it("shows a mix's tracklist, its player and its page's head, cached for five minutes", async () => { const { loadData, headers, locals } = routeEvent({ app: app(), diff --git a/apps/web/src/routes/sets/[did]/[rkey]/player.json/+server.ts b/apps/web/src/routes/sets/[did]/[rkey]/player.json/+server.ts index c3435a514..2e54d93d1 100644 --- a/apps/web/src/routes/sets/[did]/[rkey]/player.json/+server.ts +++ b/apps/web/src/routes/sets/[did]/[rkey]/player.json/+server.ts @@ -7,7 +7,7 @@ export const GET: RequestHandler = async ({ params, locals }) => { const set = await app.recordings.set(params.did, params.rkey); if (!set) error(404, 'No set here'); - const source = await app.recordings.source(set); + const source = await app.recordings.source(set, locals.flags); log.debug('set player source', { set: set.uri, source: source && (source.kind === 'audio' ? source.from : source.platform) diff --git a/apps/web/src/routes/sets/[did]/[rkey]/player.json/server.test.ts b/apps/web/src/routes/sets/[did]/[rkey]/player.json/server.test.ts index 6e7d3d64a..5309298f3 100644 --- a/apps/web/src/routes/sets/[did]/[rkey]/player.json/server.test.ts +++ b/apps/web/src/routes/sets/[did]/[rkey]/player.json/server.test.ts @@ -70,3 +70,35 @@ it('has no source for a set with nothing to play, and is a 404 for a set the dir for (const rkey of ['3kmissing', '..']) await expect(callRoute(GET, { app: app(), params: { did: DJ, rkey } })).rejects.toMatchObject({ status: 404 }); }); + +it("plays a set's links instead of its recording on the DJ's PDS while pauseRecordingStream is on", async () => { + const client = t.net.client(DJ); + const audio = await client.uploadBlob(new Uint8Array(1234), 'audio/mpeg'); + + await client.putRecord({ + collection: COLLECTION.djRecording, + rkey: '3krec', + record: { $type: COLLECTION.djRecording, audio, createdAt: '2026-09-13T00:00:00Z' } + }); + + await client.putRecord({ + collection: COLLECTION.djSet, + rkey: '3krecorded', + record: { + $type: COLLECTION.djSet, + date: '2026-09-12', + tracks: [], + recording: { uri: `at://${DJ}/${COLLECTION.djRecording}/3krec`, cid: 'bafyrec' }, + links: [{ uri: 'https://soundcloud.com/neon/tidal-hours' }], + createdAt: '2026-09-13T00:00:00Z' + } + }); + + const play = async (pauseRecordingStream: boolean) => + ( + await callRoute(GET, { app: app(), params: { did: DJ, rkey: '3krecorded' }, flags: { pauseRecordingStream } }) + ).json(); + + expect(await play(false)).toMatchObject({ source: { kind: 'audio', from: 'pds' } }); + expect(await play(true)).toMatchObject({ source: { kind: 'embed', platform: 'SoundCloud' } }); +}); diff --git a/apps/web/src/routes/venue/[key]/[[name]]/+page.server.ts b/apps/web/src/routes/venue/[key]/[[name]]/+page.server.ts index 840258404..eea9e6ffd 100644 --- a/apps/web/src/routes/venue/[key]/[[name]]/+page.server.ts +++ b/apps/web/src/routes/venue/[key]/[[name]]/+page.server.ts @@ -1,23 +1,22 @@ import { error, redirect } from '@sveltejs/kit'; -import { capabilitiesIn } from '#lib/capabilities.ts'; +import { type Capability, capabilitiesIn } from '#lib/capabilities.ts'; import type { ListedEvent } from '#lib/events.ts'; import { listedEvent } from '#lib/server/events-list.ts'; +import { pageContext } from '#lib/server/edit-mode.ts'; import { cacheBriefly, requireFlag } from '#lib/server/http.ts'; import { pageMeta } from '#lib/server/meta.ts'; import type { VenueView } from '#lib/server/services/venues.ts'; import { spacePagePath } from '#lib/space-paths.ts'; -import type { Viewer } from '#lib/types.ts'; +import type { SpacePerson, Viewer } from '#lib/types.ts'; import type { PageServerLoad } from './$types'; /** * The venue's dashboard pages the viewer can use: its events waiting for it with venue.approve, its settings with * page.edit or venue.block (staff can use both), and otherwise claiming it. */ -async function dashboardLinks(app: App.Locals['app'], venue: VenueView, viewer: Viewer) { +function dashboardLinks(venue: VenueView, viewer: Viewer, person: SpacePerson | undefined, held: Capability[]) { const base = `/dashboard/venues/${venue.skey}`; - const person = (await app.sharedSpaces.people(venue.space, viewer)).find((someone) => someone.did === viewer.did); - const held = capabilitiesIn('venue', person?.capabilities ?? []); - const can = (capability: (typeof held)[number]) => viewer.isStaff || held.includes(capability); + const can = (capability: Capability) => viewer.isStaff || held.includes(capability); return [ ...(can('venue.approve') ? [{ label: 'Events to confirm', href: `${base}/events` }] : []), @@ -46,12 +45,20 @@ export const load: PageServerLoad = async (event) => { const { name, address } = venue; const place = [address.locality, address.country].filter(Boolean).join(', '); - cacheBriefly(event, 60); + const person = viewer + ? (await app.sharedSpaces.people(venue.space, viewer)).find((someone) => someone.did === viewer.did) + : undefined; + + const held = capabilitiesIn('venue', person?.capabilities ?? []); + const { can } = pageContext(locals, 'venue', venue.space, held); + + // Its people and staff change what it shows from the dashboard, and come back to see it. + cacheBriefly(event, 60, can ?? []); return { venue: { name, address, geo: venue.geo ?? null }, events: listed.filter((shown): shown is ListedEvent => !!shown), - dashboard: flags.peopleSpaces && viewer ? await dashboardLinks(app, venue, viewer) : [], + dashboard: flags.peopleSpaces && viewer ? dashboardLinks(venue, viewer, person, held) : [], meta: pageMeta(app.config.publicUrl, { title: name, description: `${name} in ${place}: upcoming events on Local Network.`, diff --git a/apps/web/src/routes/venue/[key]/[[name]]/page.server.test.ts b/apps/web/src/routes/venue/[key]/[[name]]/page.server.test.ts index 0c7529d4b..66d54bc32 100644 --- a/apps/web/src/routes/venue/[key]/[[name]]/page.server.test.ts +++ b/apps/web/src/routes/venue/[key]/[[name]]/page.server.test.ts @@ -140,6 +140,29 @@ it('links its dashboard pages for the people who can use them, and claiming it f expect((await opened(path, { did: OWNER, flags: { spacePages: true } })).dashboard).toEqual([]); }); +it('keeps no copy for its people and staff, who can change what it shows, and lets the browser keep one for anyone else', async () => { + const cacheControl = async (did: string, flags = on) => { + const { headers, loadData } = routeEvent({ + app: app(), + viewer: await t.viewer(did), + url: `/venue/${venue.skey}/tresor`, + params: { key: venue.skey, name: 'tresor' }, + flags + }); + + await loadData(load); + + return headers['cache-control']; + }; + + expect(await cacheControl(OWNER)).toBe('no-store'); + expect(await cacheControl(BOOKER)).toBe('no-store'); + expect(await cacheControl(ADMIN)).toBe('no-store'); + // Its people change it from their dashboard, which they reach without peopleSpaces too. + expect(await cacheControl(OWNER, { spacePages: true })).toBe('no-store'); + expect(await cacheControl(STRANGER)).toBe('private, max-age=60'); +}); + it('sends any other name, or none, on to the current one, and is a 404 for an unknown venue or while spacePages is off', async () => { await expect(opened(`/venue/${venue.skey}?ref=x`)).rejects.toMatchObject({ status: 308, diff --git a/apps/web/src/routes/xrpc/computer.localnetwork.directory.requestIndex/+server.ts b/apps/web/src/routes/xrpc/computer.localnetwork.directory.requestIndex/+server.ts index b57f061ac..5d220b17c 100644 --- a/apps/web/src/routes/xrpc/computer.localnetwork.directory.requestIndex/+server.ts +++ b/apps/web/src/routes/xrpc/computer.localnetwork.directory.requestIndex/+server.ts @@ -2,10 +2,11 @@ import { requestIndex } from '#lib/server/happyview/request-index.ts'; import type { RequestHandler } from './$types'; /** locallibrary asks for its account's records to be read again, with service auth from the account's PDS. */ -export const POST: RequestHandler = ({ request, locals: { app, log } }) => +export const POST: RequestHandler = ({ request, locals: { app, flags, log } }) => requestIndex(request.headers.get('authorization'), { audience: app.config.serviceDid, getSigningKey: (did, force) => app.identity.signingKey(did, force), backfills: app.backfills, + paused: flags.pauseRequestIndex, log }); diff --git a/apps/web/src/routes/xrpc/computer.localnetwork.directory.requestIndex/server.test.ts b/apps/web/src/routes/xrpc/computer.localnetwork.directory.requestIndex/server.test.ts index d8398e942..1437d8516 100644 --- a/apps/web/src/routes/xrpc/computer.localnetwork.directory.requestIndex/server.test.ts +++ b/apps/web/src/routes/xrpc/computer.localnetwork.directory.requestIndex/server.test.ts @@ -2,10 +2,12 @@ import { Secp256k1Keypair } from '@atproto/crypto'; import { afterEach, beforeEach, expect, it } from 'vitest'; import { REQUEST_INDEX } from '#lib/nsid.ts'; import { Backfills } from '#lib/server/happyview/backfills.ts'; +import { HappyViewClient } from '#lib/server/happyview/client.ts'; import { silentLogger } from '#lib/server/logger.ts'; import { createTestServices } from '#lib/server/testing/core.ts'; import { serviceJwt } from '#lib/server/testing/service-jwt.ts'; import { callRoute } from '#lib/testing/route-event.ts'; +import type { Flags } from '#lib/types.ts'; import { POST } from './+server.ts'; const SERVICE_DID = 'did:web:localnetwork.test'; @@ -16,9 +18,13 @@ let t: Awaited>; let key: Secp256k1Keypair; +/** The backfills HappyView was asked to start. */ +let backfills: string[]; + beforeEach(async () => { t = await createTestServices(); key = await Secp256k1Keypair.create(); + backfills = []; }); afterEach(async () => { @@ -27,13 +33,27 @@ afterEach(async () => { }); /** locallibrary asks for DJ's records to be read again, with `authorization`, and gets the status and answer. */ -async function requestIndex(authorization: string) { +async function requestIndex(authorization: string, flags?: Flags) { + // The test's HappyView, watched for the backfills it's asked to start. + const directory = new HappyViewClient({ + url: 'http://happyview.test', + apiKey: 'hv_test', + fetch: async (input, init) => { + const request = new Request(input, init); + + if (new URL(request.url).pathname === '/admin/backfill') backfills.push(request.url); + + return t.happyView.fetch(request); + } + }); + const response = await callRoute(POST, { app: { config: { serviceDid: SERVICE_DID }, identity: { signingKey: async () => key.did() }, - backfills: new Backfills(t.directory, silentLogger) + backfills: new Backfills(directory, silentLogger) }, + flags, request: new Request(`https://localnetwork.test/xrpc/${REQUEST_INDEX}`, { method: 'POST', headers: { authorization } @@ -52,6 +72,25 @@ it("has HappyView re-read the caller's records", async () => { }); expect(await requestIndex(authorization)).toEqual({ status: 200, body: { indexed: true } }); + expect(backfills).not.toEqual([]); +}); + +it('says nothing was indexed, starting no backfill, while pauseRequestIndex is on', async () => { + const paused = await createTestServices({ flagOverrides: { pauseRequestIndex: true } }); + + const authorization = await serviceJwt(key, { + iss: DJ, + aud: SERVICE_DID, + lxm: REQUEST_INDEX, + exp: Math.floor(Date.now() / 1000) + 60 + }); + + expect(await requestIndex(authorization, await paused.flags.evaluate(null))).toEqual({ + status: 200, + body: { indexed: false } + }); + expect(backfills).toEqual([]); + await paused.db.destroy(); }); it('refuses a token minted for another service', async () => { diff --git a/flags/catalog/pauseBackfills.json b/flags/catalog/pauseBackfills.json new file mode 100644 index 000000000..8a6f48470 --- /dev/null +++ b/flags/catalog/pauseBackfills.json @@ -0,0 +1,6 @@ +{ + "$schema": "../flag.schema.json", + "key": "pauseBackfills", + "description": "Stops the site asking HappyView to re-read repos: the refresh at start and on the directory sync round, and the set picker, carry on with what HappyView already has. Turn it on for everyone: the refreshes have no account to check.", + "type": "ops" +} diff --git a/flags/catalog/pauseOgCards.json b/flags/catalog/pauseOgCards.json new file mode 100644 index 000000000..0293af785 --- /dev/null +++ b/flags/catalog/pauseOgCards.json @@ -0,0 +1,6 @@ +{ + "$schema": "../flag.schema.json", + "key": "pauseOgCards", + "description": "Stops drawing link-preview cards for performers, mixes, press kits and artists: pages point their preview at the site's card, and a card not already kept in memory redirects there. Turn it on for everyone: crawlers are signed out.", + "type": "ops" +} diff --git a/flags/catalog/pauseReconcilers.json b/flags/catalog/pauseReconcilers.json new file mode 100644 index 000000000..a8374ed35 --- /dev/null +++ b/flags/catalog/pauseReconcilers.json @@ -0,0 +1,6 @@ +{ + "$schema": "../flag.schema.json", + "key": "pauseReconcilers", + "description": "Stops the rounds that fix drift in the root's repo (manager, staff and shared spaces, listings, venue blocks and calendar copies), at start and every round after. Turn it on for everyone: the rounds have no account to check.", + "type": "ops" +} diff --git a/flags/catalog/pauseRecordingStream.json b/flags/catalog/pauseRecordingStream.json new file mode 100644 index 000000000..acde9ddcc --- /dev/null +++ b/flags/catalog/pauseRecordingStream.json @@ -0,0 +1,6 @@ +{ + "$schema": "../flag.schema.json", + "key": "pauseRecordingStream", + "description": "Stops the site streaming recordings from DJs' servers: the audio route answers 503 without reading anything, and set and mix players play the links instead. plyr.fm recordings still play. Turn it on for everyone: most listeners are signed out.", + "type": "ops" +} diff --git a/flags/catalog/pauseRequestIndex.json b/flags/catalog/pauseRequestIndex.json new file mode 100644 index 000000000..8365b7589 --- /dev/null +++ b/flags/catalog/pauseRequestIndex.json @@ -0,0 +1,6 @@ +{ + "$schema": "../flag.schema.json", + "key": "pauseRequestIndex", + "description": "Stops locallibrary asking HappyView to re-read an account's records: requestIndex answers that nothing was indexed, as it does without a HappyView API key. Turn it on for everyone: the request comes signed out.", + "type": "ops" +} From 75dfe3fe97b13aa74d2f598bee65da1998039bf1 Mon Sep 17 00:00:00 2001 From: botandbang <337765928+botandbang@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:58:11 -0600 Subject: [PATCH 03/22] feat(web): say which pages a flag shows on, and count signed-out visitors in a rollout A flag can list the kinds of page it changes in showsOn: global, or one of the glossary's page types. The schema is generated from one list in lib/flags/shows-on.ts, the flag's page in the staff console shows it under "Shows on", and GLOSSARY.md has the term. While a flag is on for a percentage, a signed-out browser gets a random id in a first-party, httpOnly cookie, ln_flag_visitor, and the rule buckets it like a DID, so it gets the same answer on every visit. Those answers stop being publicly cacheable while that's true. getFlags, xrpc and locallibrary still ask with a DID or nothing. ADR 0018 records the choice, flags/vectors.json gains visitor cases, and the privacy page mentions the cookie. Fixes LOC-655 Fixes LOC-321 --- GLOSSARY.md | 6 +- apps/web/README.md | 4 +- apps/web/docs/diagrams/flags.md | 21 ++-- apps/web/docs/diagrams/requests-and-routes.md | 6 +- apps/web/src/app.d.ts | 2 +- apps/web/src/hooks.server.test.ts | 118 +++++++++++++++++- apps/web/src/hooks.server.ts | 22 +++- .../lib/components/FlagTable.stories.svelte | 1 + .../lib/components/flag-tables.svelte.test.ts | 1 + apps/web/src/lib/flags/shows-on.ts | 20 +++ apps/web/src/lib/server/flags/catalog.test.ts | 19 +++ apps/web/src/lib/server/flags/catalog.ts | 12 +- .../web/src/lib/server/flags/evaluate.test.ts | 22 +++- apps/web/src/lib/server/flags/evaluate.ts | 18 ++- apps/web/src/lib/server/flags/visitor.ts | 30 +++++ .../web/src/lib/server/services/flags.test.ts | 27 +++- apps/web/src/lib/server/services/flags.ts | 22 +++- apps/web/src/lib/server/services/listings.ts | 2 +- apps/web/src/lib/types.ts | 3 + apps/web/src/routes/admin/flags/+page.svelte | 2 +- .../src/routes/admin/flags/[key]/+page.svelte | 13 +- .../admin/flags/[key]/page.stories.svelte | 7 +- .../admin/flags/[key]/page.svelte.test.ts | 53 ++++++++ ...18-signed-out-visitors-get-a-rollout-id.md | 25 ++++ docs/research/feature-flag-platforms.md | 32 ++--- flags/README.md | 15 ++- flags/catalog/parityCanary.json | 3 +- flags/catalog/peopleSpaces.json | 3 +- flags/catalog/spacePages.json | 5 +- flags/flag.schema.json | 18 +++ flags/vectors.json | 56 ++++++++- 31 files changed, 517 insertions(+), 71 deletions(-) create mode 100644 apps/web/src/lib/flags/shows-on.ts create mode 100644 apps/web/src/lib/server/flags/visitor.ts create mode 100644 apps/web/src/routes/admin/flags/[key]/page.svelte.test.ts create mode 100644 docs/adr/0018-signed-out-visitors-get-a-rollout-id.md diff --git a/GLOSSARY.md b/GLOSSARY.md index 095d4a2ff..eb812afd3 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -56,6 +56,10 @@ _Avoid_: admin dashboard, admin panel A switch that turns a feature on for some people before everyone. The website and locallibrary share its key and give an account the same answer. Staff set who it's on for in the staff console. Flags are for rolling something out, not for keeping anyone out. Turning one off for everyone keeps who it was on for, ready for when it's back on. A flag can say which kinds of page it shows on, so staff can switch it from there. _Avoid_: feature toggle, experiment, setting +**Shows on**: +The kinds of page a flag changes: profiles, acts, parties, venues, events, sets, mixes or press kits, or every page. Each flag lists its own in the catalog, and its page in the staff console shows them. +_Avoid_: contexts, placement, scope + **Flag group**: A named list of accounts a flag can be turned on for. It has nothing to do with an act, and the people in it don't know they're in it. _Avoid_: segment, cohort, group (on its own) @@ -69,7 +73,7 @@ A flag that stops something that already works while it's on. It's named for the _Avoid_: circuit breaker, pause flag **Rollout**: -The share of signed-in accounts a flag is on for. An account stays in as the share grows, and has the same chance of being in on every flag. Signed-out visitors are never counted. +The share of people a flag is on for: accounts, and signed-out visitors once per browser. Anyone in stays in as the share grows, and has the same chance of being in on every flag. A visitor who signs in counts as their account from then on. _Avoid_: percentage (in copy), canary, staged release ## People and acts diff --git a/apps/web/README.md b/apps/web/README.md index 5e15b8a19..29270e584 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -82,11 +82,11 @@ All data lives on the AT Protocol. Public profiles are ordinary atproto records; ### Flags -A flag turns a feature on for some people before everyone. The flags themselves are files in [`flags/catalog/`](../../flags/README.md), which locallibrary reads too. Staff set who each is on for at `/admin/flags`: everyone, a percentage of accounts, [flag groups](../../GLOSSARY.md) at `/admin/flags/groups`, or single accounts. "Off for everyone" turns a flag off and keeps all of that for when it's back on. Admins manage all of it, and on the Staff page they can give a moderator either part: flags, or flag groups. Every change is in the audit log. The list marks a flag "Ready to remove" once it's been on for everyone, or every account, for 30 days. +A flag turns a feature on for some people before everyone. The flags themselves are files in [`flags/catalog/`](../../flags/README.md), which locallibrary reads too. Staff set who each is on for at `/admin/flags`: everyone, a percentage of people, [flag groups](../../GLOSSARY.md) at `/admin/flags/groups`, or single accounts. "Off for everyone" turns a flag off and keeps all of that for when it's back on. Admins manage all of it, and on the Staff page they can give a moderator either part: flags, or flag groups. Every change is in the audit log. The list marks a flag "Ready to remove" once it's been on for everyone, or every account, for 30 days. To see a flag without changing it for anyone, staff with the flags grant can turn it on or off for their own browser from its page. The preview is a cookie signed with their session, lasts an hour, shows a banner on every page until it's cleared, and is audited. In development and tests, `FLAG_OVERRIDES=key=on,other=off` forces flags for every request instead; the app won't start with it in production ([ADR 0010](../../docs/adr/0010-flags-turn-off-and-preview-without-touching-targeting.md)). -What's set is kept as `staff.flag` and `staff.group` records in the staff space, indexed into SQLite and held in memory, so reading one on a request costs nothing. Pages read `data.flags?.key` and server code `locals.flags.key`, worked out once per request. A signed-out visitor only gets flags on for everyone. locallibrary can't read the staff space, so `computer.localnetwork.flags.getFlags` tells it the public gates and whether it's targeted ([ADR 0006](../../docs/adr/0006-locallibrary-asks-the-website-for-flags.md)). +What's set is kept as `staff.flag` and `staff.group` records in the staff space, indexed into SQLite and held in memory, so reading one on a request costs nothing. Pages read `data.flags?.key` and server code `locals.flags.key`, worked out once per request. A signed-out visitor counts in a percentage by a random id in the `ln_flag_visitor` cookie, set only while a flag is on for one ([ADR 0018](../../docs/adr/0018-signed-out-visitors-get-a-rollout-id.md)). locallibrary can't read the staff space, so `computer.localnetwork.flags.getFlags` tells it the public gates and whether it's targeted ([ADR 0006](../../docs/adr/0006-locallibrary-asks-the-website-for-flags.md)). ### Staff diff --git a/apps/web/docs/diagrams/flags.md b/apps/web/docs/diagrams/flags.md index b1427c0f9..5fc96d1aa 100644 --- a/apps/web/docs/diagrams/flags.md +++ b/apps/web/docs/diagrams/flags.md @@ -14,7 +14,7 @@ Whether one flag is on for one caller. Only flags in `flags/catalog/` exist: a r ```mermaid flowchart TD - Ask["A catalog flag, for a DID
or a signed-out visitor"] --> Forced{"In FLAG_OVERRIDES?"} + Ask["A catalog flag, for a DID, a signed-out
visitor's id, or no id"] --> Forced{"In FLAG_OVERRIDES?"} Forced -- "forced on" --> On["On"] Forced -- "forced off" --> Off["Off"] Forced -- "no" --> Record{"A staff.flag record?"} @@ -25,22 +25,27 @@ flowchart TD Everyone -- "yes" --> On Everyone -- "no" --> Targeted{"The DID is in its accounts
or one of its groups?"} Targeted -- "yes" --> On - Targeted -- "no" --> Bucket{"Signed in, and SHA-256 of key + DID,
mod 100, under percentage?"} + Targeted -- "no" --> Bucket{"An id, and SHA-256 of key + id,
mod 100, under percentage?"} Bucket -- "yes" --> On Bucket -- "no" --> Off ``` -Source: [`src/lib/server/flags/evaluate.ts`](../../src/lib/server/flags/evaluate.ts), [`src/lib/server/services/flags.ts`](../../src/lib/server/services/flags.ts), [`src/lib/server/flags/catalog.ts`](../../src/lib/server/flags/catalog.ts), [`src/lib/server/config.ts`](../../src/lib/server/config.ts) +Source: [`src/lib/server/flags/evaluate.ts`](../../src/lib/server/flags/evaluate.ts), [`src/lib/server/flags/visitor.ts`](../../src/lib/server/flags/visitor.ts), [`src/lib/server/services/flags.ts`](../../src/lib/server/services/flags.ts), [`src/lib/server/flags/catalog.ts`](../../src/lib/server/flags/catalog.ts), [`src/lib/server/config.ts`](../../src/lib/server/config.ts) ## Flags on a page request -Every request gets every flag decided once, held in memory between record changes. An `/xrpc` call never reads the sign-in cookie, so it gets a signed-out visitor's flags. A staff member's preview changes only their own browser. +Every request gets every flag decided once, held in memory between record changes. An `/xrpc` call never reads a cookie, so it only gets flags on for everyone. A signed-out visitor gets an id of their own while a flag is on for a percentage, and their response stays out of shared caches. A staff member's preview changes only their own browser. ```mermaid flowchart TD - Request["A request"] --> Decide["Decide every flag for the viewer,
or for a signed-out visitor"] - Decide -- "/xrpc, always signed out" --> Route["locals.flags for the route,
no preview"] - Decide -- "not /xrpc" --> Cookie{"ln_flag_preview set?"} + Request["A request"] -- "/xrpc" --> Route["Every flag with no id,
locals.flags for the route, no preview"] + Request -- "signed in" --> Decide["Decide every flag for the viewer"] + Request -- "signed out" --> Share{"A flag on for
a percentage?"} + Share -- "no" --> Nobody["Decide every flag with no id"] + Share -- "yes" --> Visitor["ln_flag_visitor, set if missing:
decide for its visitor id,
no public caching"] + Decide --> Cookie{"ln_flag_preview set?"} + Nobody --> Cookie + Visitor --> Cookie Cookie -- "no" --> Locals["locals.flags, passed to
every page by the root layout"] Cookie -- "yes" --> Valid{"Signed with this session, for this viewer,
under an hour old, and they hold flags?"} Valid -- "yes" --> Merge["Previewed flags replace theirs,
with a banner on every page"] @@ -49,7 +54,7 @@ flowchart TD Drop --> Locals ``` -Source: [`src/hooks.server.ts`](../../src/hooks.server.ts), [`src/lib/server/flags/preview.ts`](../../src/lib/server/flags/preview.ts), [`src/lib/server/services/flags.ts`](../../src/lib/server/services/flags.ts), [`src/routes/+layout.server.ts`](../../src/routes/+layout.server.ts), [`src/routes/+layout.svelte`](../../src/routes/+layout.svelte) +Source: [`src/hooks.server.ts`](../../src/hooks.server.ts), [`src/lib/server/flags/visitor.ts`](../../src/lib/server/flags/visitor.ts), [`src/lib/server/flags/preview.ts`](../../src/lib/server/flags/preview.ts), [`src/lib/server/services/flags.ts`](../../src/lib/server/services/flags.ts), [`src/routes/+layout.server.ts`](../../src/routes/+layout.server.ts), [`src/routes/+layout.svelte`](../../src/routes/+layout.svelte) ## getFlags diff --git a/apps/web/docs/diagrams/requests-and-routes.md b/apps/web/docs/diagrams/requests-and-routes.md index 9a0e391cd..b68553831 100644 --- a/apps/web/docs/diagrams/requests-and-routes.md +++ b/apps/web/docs/diagrams/requests-and-routes.md @@ -31,7 +31,7 @@ flowchart TD Load --> Limit["Write limit for this address"] Limit -- "over it" --> Slow["429"] Limit --> Session["ln_session to a viewer,
skipped on /xrpc/"] - Session --> Flags["Flags for the viewer, a signed-out
visitor's on /xrpc/, and a staff preview
from ln_flag_preview off it"] + Session --> Flags["Flags for the viewer, a signed-out visitor's
ln_flag_visitor id while a flag is on for a
percentage, no id on /xrpc/, and a staff
preview from ln_flag_preview off it"] Flags --> Guard["guardArea by route"] Guard -- "/dashboard or /admin,
signed out" --> Login["303 to /login?next="] Guard -- "/admin, not staff" --> Refused["403"] @@ -67,7 +67,7 @@ Source: [`src/routes/+layout.server.ts`](../../src/routes/+layout.server.ts), [` ## Response caching -What each response lets a browser or a shared cache keep. Pages that show the same thing to everyone use `cacheBriefly`. +What each response lets a browser or a shared cache keep. Pages that show the same thing to everyone use `cacheBriefly`. While a flag is on for a percentage, the server hook turns `public` into `private` on every response to a signed-out visitor outside `/xrpc/`, since their flags come from their own `ln_flag_visitor` cookie. ```mermaid flowchart LR @@ -86,7 +86,7 @@ flowchart LR Responses -- "/healthz, token exchange, audit export,
getFlags with a token, paused cards
and recordings" --> Never["no-store"] ``` -Source: [`src/lib/server/http.ts`](../../src/lib/server/http.ts), [`src/routes/charts/+page.server.ts`](../../src/routes/charts/+page.server.ts), [`src/routes/venue/[key]/[[name]]/+page.server.ts`](../../src/routes/venue/[key]/[[name]]/+page.server.ts), [`src/routes/projects/[slug]/mixes/[n]/+page.server.ts`](../../src/routes/projects/[slug]/mixes/[n]/+page.server.ts), [`src/routes/media/[did]/[cid]/+server.ts`](../../src/routes/media/[did]/[cid]/+server.ts), [`src/lib/server/og/serve.ts`](../../src/lib/server/og/serve.ts), [`src/routes/projects/[slug]/press-kits/[rkey]/photos/[cid]/+server.ts`](../../src/routes/projects/[slug]/press-kits/[rkey]/photos/[cid]/+server.ts), [`src/routes/api/places/+server.ts`](../../src/routes/api/places/+server.ts), [`src/routes/sets/[did]/[rkey]/player.json/+server.ts`](../../src/routes/sets/[did]/[rkey]/player.json/+server.ts), [`src/lib/server/flags/get-flags.ts`](../../src/lib/server/flags/get-flags.ts) +Source: [`src/lib/server/http.ts`](../../src/lib/server/http.ts), [`src/hooks.server.ts`](../../src/hooks.server.ts), [`src/routes/charts/+page.server.ts`](../../src/routes/charts/+page.server.ts), [`src/routes/venue/[key]/[[name]]/+page.server.ts`](../../src/routes/venue/[key]/[[name]]/+page.server.ts), [`src/routes/projects/[slug]/mixes/[n]/+page.server.ts`](../../src/routes/projects/[slug]/mixes/[n]/+page.server.ts), [`src/routes/media/[did]/[cid]/+server.ts`](../../src/routes/media/[did]/[cid]/+server.ts), [`src/lib/server/og/serve.ts`](../../src/lib/server/og/serve.ts), [`src/routes/projects/[slug]/press-kits/[rkey]/photos/[cid]/+server.ts`](../../src/routes/projects/[slug]/press-kits/[rkey]/photos/[cid]/+server.ts), [`src/routes/api/places/+server.ts`](../../src/routes/api/places/+server.ts), [`src/routes/sets/[did]/[rkey]/player.json/+server.ts`](../../src/routes/sets/[did]/[rkey]/player.json/+server.ts), [`src/lib/server/flags/get-flags.ts`](../../src/lib/server/flags/get-flags.ts) ## Error paths diff --git a/apps/web/src/app.d.ts b/apps/web/src/app.d.ts index 25e3e35e3..5dc314dc5 100644 --- a/apps/web/src/app.d.ts +++ b/apps/web/src/app.d.ts @@ -15,7 +15,7 @@ declare global { interface Locals { app: ServerApp; viewer: Viewer | null; - /** Every feature flag for this viewer, or for a signed-out visitor. Not set on XRPC requests. */ + /** Every feature flag for this viewer or signed-out visitor. On XRPC requests, only those on for everyone. */ flags: Flags; /** The flags a staff member is previewing in this browser, already in `flags`. */ flagPreview?: FlagPreview; diff --git a/apps/web/src/hooks.server.test.ts b/apps/web/src/hooks.server.test.ts index b231b8abe..3a7f6bc03 100644 --- a/apps/web/src/hooks.server.test.ts +++ b/apps/web/src/hooks.server.test.ts @@ -9,6 +9,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import { SESSION_COOKIE, WebSessions } from '#lib/server/auth/session.ts'; import { CRAWLER_HEAD } from '#lib/server/crawler-head.ts'; import { PREVIEW_COOKIE, PREVIEW_MS, sealPreview } from '#lib/server/flags/preview.ts'; +import { VISITOR_COOKIE } from '#lib/server/flags/visitor.ts'; import { HappyViewError } from '#lib/server/happyview/client.ts'; import { requireFlag } from '#lib/server/http.ts'; import { RateLimiter } from '#lib/server/rate-limit.ts'; @@ -287,6 +288,95 @@ it("gives an xrpc call a signed-out visitor's flags, and ignores a staff preview expect(resolve).not.toHaveBeenCalled(); }); +it('counts a signed-out visitor in a percentage by their own cookie, the same way on every request', async () => { + const s = await services({ admins: [ADMIN] }); + const { handle } = hooksWith(async () => s.app); + await atPercentage(s, 50); + + for (let request = 0; request < 3; request++) { + const inside = await handledWithLocals(handle, { url: '/', cookies: { [VISITOR_COOKIE]: INSIDE_HALF } }); + const outside = await handledWithLocals(handle, { url: '/', cookies: { [VISITOR_COOKIE]: OUTSIDE_HALF } }); + + expect(inside.locals.flags?.parityCanary).toBe(true); + expect(outside.locals.flags?.parityCanary).toBe(false); + expect(inside.cookies.options.has(VISITOR_COOKIE)).toBe(false); + } +}); + +it('gives a signed-out visitor a first-party id on their first request, and keeps their answer with it', async () => { + const s = await services({ admins: [ADMIN], publicUrl: 'https://localnetwork.test' }); + const { handle } = hooksWith(async () => s.app); + await atPercentage(s, 50); + + for (const cookies of [{}, { [VISITOR_COOKIE]: 'not-a-uuid' }]) { + const first = await handledWithLocals(handle, { url: '/', cookies }); + const id = first.cookies.get(VISITOR_COOKIE); + + expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + expect(first.cookies.options.get(VISITOR_COOKIE)).toEqual({ + path: '/', + httpOnly: true, + sameSite: 'lax', + secure: true, + maxAge: 365 * 86_400 + }); + + const again = await handledWithLocals(handle, { url: '/', cookies: { [VISITOR_COOKIE]: id! } }); + + expect(again.locals.flags?.parityCanary).toBe(first.locals.flags?.parityCanary); + } +}); + +it('gives a visitor no id while no flag is on for a percentage, nor when signed in or over xrpc', async () => { + const s = await services({ admins: [ADMIN] }); + const { handle } = hooksWith(async () => s.app); + const token = await s.sessions.create(DJ, null); + + const setsId = async (request: RouteEventInit) => + (await handledWithLocals(handle, request)).cookies.options.has(VISITOR_COOKIE); + + expect(await setsId({ url: '/' })).toBe(false); + + await atPercentage(s, 50, { enabled: false }); + + expect(await setsId({ url: '/' })).toBe(false); + + await atPercentage(s, 50, { everyone: true }); + + expect(await setsId({ url: '/' })).toBe(false); + + await atPercentage(s, 50); + + expect(await setsId({ url: '/' })).toBe(true); + expect(await setsId({ url: '/', cookies: { [SESSION_COOKIE]: token } })).toBe(false); + + const xrpc = await handledWithLocals(handle, { + url: '/xrpc/computer.localnetwork.flags.getFlags', + cookies: { [VISITOR_COOKIE]: INSIDE_HALF } + }); + + expect(xrpc.locals.flags?.parityCanary).toBe(false); + expect(xrpc.cookies.options.has(VISITOR_COOKIE)).toBe(false); +}); + +it("keeps a signed-out page out of shared caches while it depends on the visitor's own bucket", async () => { + const s = await services({ admins: [ADMIN] }); + const { handle } = hooksWith(async () => s.app); + const cachedBriefly = { 'cache-control': 'public, max-age=60', vary: 'Cookie' }; + + const cacheControl = async (cookies: Record) => + (await handledWithLocals(handle, { url: '/artists', cookies }, 200, cachedBriefly)).response.headers.get( + 'cache-control' + ); + + expect(await cacheControl({})).toBe('public, max-age=60'); + + await atPercentage(s, 50); + + expect(await cacheControl({})).toBe('private, max-age=60'); + expect(await cacheControl({ [VISITOR_COOKIE]: OUTSIDE_HALF })).toBe('private, max-age=60'); +}); + it('limits writes by address, and counts an unknown address as one', async () => { const s = await services({ writes: 1 }); const { handle } = hooksWith(async () => s.app); @@ -527,6 +617,21 @@ const DJ = 'did:plc:dj'; const ADMIN = 'did:plc:admin'; +/** Visitor cookies whose ids sit in parityCanary's buckets 16 and 55: inside a 50% rollout, and outside it. */ +const INSIDE_HALF = '00000000-0000-4000-8000-000000000000'; + +const OUTSIDE_HALF = '00000001-0000-4000-8000-000000000000'; + +/** Puts parityCanary on for `percentage` of everyone, with `gates` on top, as an admin of `s`. */ +async function atPercentage( + s: Awaited>, + percentage: number, + gates: { enabled?: boolean; everyone?: boolean } = {} +) { + const input = { enabled: true, everyone: false, percentage, groups: [], dids: [], ...gates }; + await s.flags.updateFlag(await s.viewer(ADMIN), 'parityCanary', input); +} + /** An account whose OAuth grant lacks scopes the app now asks for, so the app has no viewer for it. */ const STALE = 'did:plc:stale'; @@ -537,7 +642,7 @@ type HookApp = { logger?: Logger; sessions?: WebSessions; limits?: { write: RateLimiter }; - flags?: Pick; + flags?: Pick; viewer?: (did: string) => Promise; config?: { publicUrl: string }; }; @@ -575,12 +680,17 @@ async function services( return { app: parts, sessions, logs, flags: t.flags, viewer: t.viewer }; } -/** Runs the handle hook on a request built from `init`, with a page that answers `status`. */ -async function handledWithLocals(handle: Hooks['handle'], request: RouteEventInit, status = 200) { +/** Runs the handle hook on a request built from `init`, with a page that answers `status` with `headers`. */ +async function handledWithLocals( + handle: Hooks['handle'], + request: RouteEventInit, + status = 200, + headers: Record = {} +) { const { event, cookies } = routeEvent(request); // The hook sets these itself, so they start out unset as SvelteKit leaves them. const locals: Partial = {}; - const resolve = async () => new Response('page', { status, headers: { 'content-type': 'text/plain' } }); + const resolve = async () => new Response('page', { status, headers: { 'content-type': 'text/plain', ...headers } }); // SAFETY: the hook reads the request, URL, route, cookies and client address, all set by routeEvent. const response = await handle({ event: { ...event, locals } as never, resolve }); diff --git a/apps/web/src/hooks.server.ts b/apps/web/src/hooks.server.ts index 41ce5f3ea..051adada0 100644 --- a/apps/web/src/hooks.server.ts +++ b/apps/web/src/hooks.server.ts @@ -6,6 +6,7 @@ import { HappyViewError } from '#lib/server/happyview/client.ts'; import { SESSION_COOKIE } from '#lib/server/auth/session.ts'; import { gzipped } from '#lib/server/compress.ts'; import { PREVIEW_COOKIE } from '#lib/server/flags/preview.ts'; +import { flagVisitor } from '#lib/server/flags/visitor.ts'; import { CRAWLER_HEAD, withCrawlerHead } from '#lib/server/crawler-head.ts'; import { clientIp, guardArea, isUnlisted } from '#lib/server/http.ts'; import { createLogger, type Logger } from '#lib/server/logger.ts'; @@ -86,6 +87,7 @@ export function serverHooks({ const { requestId } = event.locals; const isXrpc = event.url.pathname.startsWith('/xrpc/'); + const isHttps = app.config.publicUrl.startsWith('https:'); if (MUTATING.has(event.request.method) && !isXrpc && !app.limits.write.take(`ip:${clientIp(event)}`)) { return new Response('Too many requests. Slow down a little.', { status: 429, headers: { 'retry-after': '30' } }); @@ -107,10 +109,15 @@ export function serverHooks({ } } - // An xrpc call never reads the sign-in cookie, so it gets the flags a signed-out visitor does. A route that has - // checked a service token can evaluate flags for that token's DID itself. + // An xrpc call never reads a cookie, so it only gets flags on for everyone. A route that has checked a service + // token can evaluate flags for that token's DID itself. A signed-out visitor gets an id of their own while a flag + // is on for a percentage, so they're in or out of it the same way on every request. const { viewer } = event.locals; - event.locals.flags = await app.flags.evaluate(viewer?.did ?? null); + const needsVisitorId = !viewer && !isXrpc && (await app.flags.hasPercentage()); + const visitor = needsVisitorId ? flagVisitor(event.cookies, isHttps) : null; + event.locals.flags = await app.flags.evaluate(viewer?.did ?? visitor?.id ?? null); + + if (visitor) log.set({ flagVisitor: visitor.isNew ? 'new' : 'returning' }); if (!isXrpc) { const cookie = event.cookies.get(PREVIEW_COOKIE); @@ -155,8 +162,15 @@ export function serverHooks({ response.headers.set('permissions-policy', 'camera=(), microphone=(), geolocation=(self), payment=()'); if (isUnlisted(event.route.id)) response.headers.set('x-robots-tag', 'noindex'); + const cacheControl = response.headers.get('cache-control'); + + // The answer now depends on this browser's own cookie, so a shared cache mustn't keep it for the next visitor, + // or hand them the cookie it set. The browser's own cache still can. + if (visitor && cacheControl?.includes('public')) { + response.headers.set('cache-control', cacheControl.replace('public', 'private')); + } - if (app.config.publicUrl.startsWith('https:')) { + if (isHttps) { response.headers.set('strict-transport-security', 'max-age=31536000; includeSubDomains'); } diff --git a/apps/web/src/lib/components/FlagTable.stories.svelte b/apps/web/src/lib/components/FlagTable.stories.svelte index 175f5694c..fdb9d58ef 100644 --- a/apps/web/src/lib/components/FlagTable.stories.svelte +++ b/apps/web/src/lib/components/FlagTable.stories.svelte @@ -10,6 +10,7 @@ const flag = (key: string, description: string, gates: Partial): FlagView => ({ key: key as FlagView['key'], description, + showsOn: [], enabled: true, everyone: false, percentage: 0, diff --git a/apps/web/src/lib/components/flag-tables.svelte.test.ts b/apps/web/src/lib/components/flag-tables.svelte.test.ts index dfc342fbf..44db3cbe3 100644 --- a/apps/web/src/lib/components/flag-tables.svelte.test.ts +++ b/apps/web/src/lib/components/flag-tables.svelte.test.ts @@ -15,6 +15,7 @@ afterEach(() => { const flag = (gates: Partial): FlagView => ({ key: 'parityCanary', description: 'Gates nothing.', + showsOn: [], enabled: true, everyone: false, percentage: 0, diff --git a/apps/web/src/lib/flags/shows-on.ts b/apps/web/src/lib/flags/shows-on.ts new file mode 100644 index 000000000..61be73ef7 --- /dev/null +++ b/apps/web/src/lib/flags/shows-on.ts @@ -0,0 +1,20 @@ +/** + * The kinds of page a flag can show on (its `showsOn` in flags/catalog), with what the staff console calls each: + * `global` for every page, or one of the glossary's page types. `act` is `/projects/` until acts move. + */ +export const SHOWS_ON = { + global: 'Every page', + profile: 'Profile', + act: 'Act', + party: 'Party', + venue: 'Venue', + event: 'Event', + set: 'Set', + mix: 'Mix', + pressKit: 'Press kit' +} as const; + +export type ShowsOn = keyof typeof SHOWS_ON; + +// SAFETY: the keys of a const object literal. +export const SHOWS_ON_KINDS = Object.keys(SHOWS_ON) as [ShowsOn, ...ShowsOn[]]; diff --git a/apps/web/src/lib/server/flags/catalog.test.ts b/apps/web/src/lib/server/flags/catalog.test.ts index f10e7789b..ec54f47a0 100644 --- a/apps/web/src/lib/server/flags/catalog.test.ts +++ b/apps/web/src/lib/server/flags/catalog.test.ts @@ -51,6 +51,25 @@ it('refuses a key that would not work as a property, and a field it does not kno ); }); +it('reads the kinds of page a flag shows on, and refuses one it does not know', () => { + const file = { key: 'a', description: 'x', type: 'ops', showsOn: ['profile'] }; + + expect(parseCatalog([['/flags/catalog/a.json', file]])).toEqual([file]); + expect(parseCatalog([['/flags/catalog/a.json', { ...file, showsOn: ['global'] }]])[0]?.showsOn).toEqual(['global']); + + for (const showsOn of [['planet'], ['project'], ['request'], ['press-kit']]) { + expect(() => parseCatalog([['/flags/catalog/a.json', { ...file, showsOn }]]), showsOn[0]).toThrow('Invalid option'); + } + + expect(() => parseCatalog([['/flags/catalog/a.json', { ...file, showsOn: [] }]])).toThrow('Too small'); +}); + +it('reads showsOn on release flags too', () => { + const file = { key: 'a', description: 'x', type: 'release', removeBy: '2026-12-01', showsOn: ['party', 'venue'] }; + + expect(parseCatalog([['/flags/catalog/a.json', file]])).toEqual([file]); +}); + /** Parses one flag named `a`, with `fields` on top of its key and description. */ const parseFlag = (fields: { type?: string; removeBy?: string }) => parseCatalog([['/flags/catalog/a.json', { key: 'a', description: 'x', ...fields }]]); diff --git a/apps/web/src/lib/server/flags/catalog.ts b/apps/web/src/lib/server/flags/catalog.ts index 2756b483b..9ad90b4c7 100644 --- a/apps/web/src/lib/server/flags/catalog.ts +++ b/apps/web/src/lib/server/flags/catalog.ts @@ -1,5 +1,6 @@ import { z } from 'zod'; import type { FlagKey } from '#lib/flags/keys.generated.ts'; +import { SHOWS_ON_KINDS, type ShowsOn } from '#lib/flags/shows-on.ts'; const flagFields = { $schema: z.string().optional(), @@ -8,7 +9,14 @@ const flagFields = { .regex(/^[a-z][a-zA-Z0-9]*$/) .max(64) .describe('What code asks for: camelCase, the same as the file name.'), - description: z.string().min(1).max(300).describe('What the flag gates, for the staff console.') + description: z.string().min(1).max(300).describe('What the flag gates, for the staff console.'), + showsOn: z + .array(z.enum(SHOWS_ON_KINDS)) + .min(1) + .optional() + .describe( + 'The kinds of page the flag changes, or global for every page. act is a /projects page until acts move. The staff console lists them as Shows on.' + ) }; /** Release flags are meant to go, so they carry a date; ops flags stay and can't. */ @@ -36,7 +44,7 @@ export const flagDefinition = z ]) .describe('A feature flag the website and locallibrary share. Who it is on for is set in the staff console.'); -export type FlagDefinition = { key: FlagKey; description: string } & ( +export type FlagDefinition = { key: FlagKey; description: string; showsOn?: ShowsOn[] } & ( | { type: 'release'; removeBy: string } | { type: 'ops'; removeBy?: undefined } ); diff --git a/apps/web/src/lib/server/flags/evaluate.test.ts b/apps/web/src/lib/server/flags/evaluate.test.ts index abd554b92..a6451c88a 100644 --- a/apps/web/src/lib/server/flags/evaluate.test.ts +++ b/apps/web/src/lib/server/flags/evaluate.test.ts @@ -5,6 +5,9 @@ import { bucket, isOn } from './evaluate'; const did = fc.stringMatching(/^did:plc:[a-z2-7]{24}$/); +/** A signed-out visitor's id, as flagVisitor makes it from their cookie. */ +const visitor = fc.uuid({ version: 4 }).map((uuid) => `visitor:${uuid}`); + const key = fc.stringMatching(/^[a-z][a-zA-Z0-9]{0,20}$/); const percentage = fc.integer({ min: 0, max: 100 }); @@ -62,7 +65,7 @@ describe('rollouts', () => { ); }); - it('never counts a signed-out visitor', () => { + it('never counts a caller with no id', () => { fc.assert( fc.property(key, percentage, (flag, share) => { expect(isOn({ enabled: true, everyone: false, targeted: false, percentage: share }, flag, null)).toBe(false); @@ -70,6 +73,23 @@ describe('rollouts', () => { ); }); + it('takes in every visitor at 100 and none at 0', () => { + fc.assert( + fc.property(key, visitor, (flag, id) => { + const gates = { enabled: true, everyone: false, targeted: false }; + + expect(isOn({ ...gates, percentage: 100 }, flag, id)).toBe(true); + expect(isOn({ ...gates, percentage: 0 }, flag, id)).toBe(false); + }) + ); + }); + + it('puts a visitor somewhere in the rollout, not where every visitor goes', () => { + const visitors = fc.sample(visitor, { numRuns: 50, seed: 1 }); + + expect(new Set(visitors.map((id) => bucket('parityCanary', id))).size).toBeGreaterThan(10); + }); + it('moves an account to a different bucket for a different flag', () => { const account = 'did:plc:z72i7hdynmk6r22z27h6tvur'; diff --git a/apps/web/src/lib/server/flags/evaluate.ts b/apps/web/src/lib/server/flags/evaluate.ts index 83f98c98f..1ce569ae8 100644 --- a/apps/web/src/lib/server/flags/evaluate.ts +++ b/apps/web/src/lib/server/flags/evaluate.ts @@ -6,17 +6,23 @@ import { createHash } from 'node:crypto'; */ export type FlagGates = { enabled: boolean; everyone: boolean; targeted: boolean; percentage: number }; -/** Where `did` sits in `key`'s rollout, 0 to 99. It never changes, so an account stays in as a percentage grows. */ -export function bucket(key: string, did: string): number { +/** + * Where `id`, an account's DID or a signed-out visitor's id (see visitor.ts), sits in `key`'s rollout, 0 to 99. It never + * changes, so an account or a browser stays in as a percentage grows. + */ +export function bucket(key: string, id: string): number { return ( createHash('sha256') - .update(key + did, 'utf8') + .update(key + id, 'utf8') .digest() .readUInt32BE(0) % 100 ); } -/** The rule flags/README.md states. flags/vectors.json holds every tool that decides a flag to it. */ -export function isOn({ enabled, everyone, targeted, percentage }: FlagGates, key: string, did: string | null): boolean { - return enabled && (everyone || targeted || (did !== null && bucket(key, did) < percentage)); +/** + * The rule flags/README.md states. flags/vectors.json holds every tool that decides a flag to it. `id` is null for a + * caller with neither a DID nor a visitor id, who only gets what's on for everyone. + */ +export function isOn({ enabled, everyone, targeted, percentage }: FlagGates, key: string, id: string | null): boolean { + return enabled && (everyone || targeted || (id !== null && bucket(key, id) < percentage)); } diff --git a/apps/web/src/lib/server/flags/visitor.ts b/apps/web/src/lib/server/flags/visitor.ts new file mode 100644 index 000000000..2557ffb9b --- /dev/null +++ b/apps/web/src/lib/server/flags/visitor.ts @@ -0,0 +1,30 @@ +import { randomUUID } from 'node:crypto'; +import type { Cookies } from '@sveltejs/kit'; + +/** A random id for a signed-out browser, so a flag on for a percentage gives it the same answer on every request. */ +export const VISITOR_COOKIE = 'ln_flag_visitor'; + +/** What `randomUUID` makes. A cookie holding anything else is replaced with a new one. */ +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + +/** In front of the cookie's UUID in the id a flag buckets. A DID starts `did:`, so a visitor's id is never an account's. */ +const PREFIX = 'visitor:'; + +/** How long the browser keeps its id: longer than a release flag's rollout runs. */ +const MAX_AGE_S = 365 * 86_400; + +/** + * The id a signed-out visitor is bucketed by, from their cookie, after giving them one if they have none, and whether + * it's new. It's only for rollouts: the server doesn't store it or log it. A visitor who clears it can land on the + * other side of a rollout, which is fine since flags never keep anyone out. + */ +export function flagVisitor(cookies: Pick, secure: boolean) { + const saved = cookies.get(VISITOR_COOKIE); + + if (saved && UUID.test(saved)) return { id: PREFIX + saved, isNew: false }; + const uuid = randomUUID(); + + cookies.set(VISITOR_COOKIE, uuid, { path: '/', httpOnly: true, sameSite: 'lax', secure, maxAge: MAX_AGE_S }); + + return { id: PREFIX + uuid, isNew: true }; +} diff --git a/apps/web/src/lib/server/services/flags.test.ts b/apps/web/src/lib/server/services/flags.test.ts index 89cdf2dfd..844322d93 100644 --- a/apps/web/src/lib/server/services/flags.test.ts +++ b/apps/web/src/lib/server/services/flags.test.ts @@ -105,7 +105,7 @@ describe('FlagService', () => { expect(await t.flags.evaluate(OTHER)).toEqual({ ...flagsOff, [FLAG]: true }); }); - it('shows signed-out visitors only what is on for everyone', async () => { + it('gives a caller with no id only what is on for everyone', async () => { const admin = await t.viewer(ADMIN); await t.flags.updateFlag(admin, FLAG, { ...off, percentage: 100, dids: [DJ] }); @@ -117,6 +117,26 @@ describe('FlagService', () => { expect(await t.flags.evaluate(null)).toEqual({ ...flagsOff, [FLAG]: true }); }); + it('says whether a flag is on for a percentage, which signed-out visitors need an id for', async () => { + const admin = await t.viewer(ADMIN); + + expect(await t.flags.hasPercentage()).toBe(false); + + await t.flags.updateFlag(admin, FLAG, { ...off, percentage: 5 }); + + expect(await t.flags.hasPercentage()).toBe(true); + expect(await new FlagService(t.core, t.staff, { [FLAG]: true }).hasPercentage()).toBe(false); + expect(await new FlagService(t.core, t.staff, { [FLAG]: false }).hasPercentage()).toBe(false); + + await t.flags.updateFlag(admin, FLAG, { ...off, percentage: 5, enabled: false }); + + expect(await t.flags.hasPercentage()).toBe(false); + + await t.flags.updateFlag(admin, FLAG, { ...off, percentage: 5, everyone: true }); + + expect(await t.flags.hasPercentage()).toBe(false); + }); + it('tells a caller its own targeting and never who else', async () => { await t.flags.updateFlag(await t.viewer(ADMIN), FLAG, { ...off, percentage: 25, dids: [DJ] }); @@ -262,6 +282,11 @@ describe('FlagService', () => { expect(await t.flags.group('nope')).toBeNull(); }); + it('lists the kinds of page a flag shows on from its catalog file, and none when it names none', async () => { + expect((await t.flags.flag(FLAG))?.showsOn).toEqual(['profile']); + expect((await t.flags.flag('pauseGoogleTokenExchange'))?.showsOn).toEqual([]); + }); + it('says a flag is ready to remove once it has been on for everyone or every account for 30 days', async () => { const uri = spaceRecordUri(t.spaces.staff, t.core.rootDid, COLLECTION.staffFlag, FLAG); const dids: string[] = []; diff --git a/apps/web/src/lib/server/services/flags.ts b/apps/web/src/lib/server/services/flags.ts index 456f9ccd4..da9d6043c 100644 --- a/apps/web/src/lib/server/services/flags.ts +++ b/apps/web/src/lib/server/services/flags.ts @@ -147,7 +147,7 @@ export class FlagService { }; } - /** Every flag as `did` sees it, or as a signed-out visitor does when it's null. */ + /** Every flag as `did` sees it, or with nothing targeted when it's null. */ async answers(did: string | null): Promise { const { flags, groups } = await this.load(); @@ -173,11 +173,22 @@ export class FlagService { }); } - async evaluate(did: string | null): Promise { - const answers = await this.answers(did); + /** + * Every flag for `id`: an account's DID, a signed-out visitor's id from flagVisitor, or null for a caller with + * neither, who only gets what's on for everyone. + */ + async evaluate(id: string | null): Promise { + const answers = await this.answers(id); // SAFETY: answers has one entry for every FlagKey. - return Object.fromEntries(answers.map((answer) => [answer.key, isOn(answer, answer.key, did)])) as Flags; + return Object.fromEntries(answers.map((answer) => [answer.key, isOn(answer, answer.key, id)])) as Flags; + } + + /** Whether a flag is on for a percentage now, which a signed-out visitor needs an id of their own to be counted in. */ + async hasPercentage(): Promise { + return (await this.answers(null)).some( + ({ enabled, everyone, percentage }) => enabled && !everyone && percentage > 0 + ); } /** Every flag in the catalog, with who it's on for. A flag nobody has set yet is off. */ @@ -186,13 +197,14 @@ export class FlagService { const accounts = await this.core.accounts.views([...flags.values()].flatMap((flag) => flag.dids)); const settled = new Date(Date.now() - READY_TO_REMOVE_MS).toISOString(); - return FLAGS.map(({ key, description }) => { + return FLAGS.map(({ key, description, showsOn = [] }) => { const flag = flags.get(key); const fullyOn = !!flag?.enabled && (flag.everyone || flag.percentage === 100); return { key, description, + showsOn, enabled: flag?.enabled ?? true, everyone: flag?.everyone ?? false, percentage: flag?.percentage ?? 0, diff --git a/apps/web/src/lib/server/services/listings.ts b/apps/web/src/lib/server/services/listings.ts index 61e439391..7457a1e1e 100644 --- a/apps/web/src/lib/server/services/listings.ts +++ b/apps/web/src/lib/server/services/listings.ts @@ -130,7 +130,7 @@ export class ListingWriter { .executeTakeFirst(); const source = status && this.sources[status.kind]; - // As a signed-out visitor sees it, who only gets flags that are on for everyone. + // Only once it's on for everyone: with no id, nothing is counted in a percentage. const { spacePages } = await this.flags.evaluate(null); const fields = status?.listed === 1 && source && spacePages ? await source.publicFields(space) : null; const stored = await db.selectFrom('kv').select('value').where('key', '=', digestKey(space)).executeTakeFirst(); diff --git a/apps/web/src/lib/types.ts b/apps/web/src/lib/types.ts index 6dd9f93a1..1dc182373 100644 --- a/apps/web/src/lib/types.ts +++ b/apps/web/src/lib/types.ts @@ -1,4 +1,5 @@ import type { FlagKey } from '#lib/flags/keys.generated.ts'; +import type { ShowsOn } from '#lib/flags/shows-on.ts'; /** View models shared between server and browser code. */ import type { BlobRef } from '@atproto/lex-data'; @@ -505,6 +506,8 @@ export type FlagAccount = { did: string; handle: string | null }; export type FlagView = { key: FlagKey; description: string; + /** The kinds of page it changes, from its catalog file. Empty when the file names none. */ + showsOn: ShowsOn[]; /** False when it's turned off for everyone. The gates below are kept for when it's back on. */ enabled: boolean; everyone: boolean; diff --git a/apps/web/src/routes/admin/flags/+page.svelte b/apps/web/src/routes/admin/flags/+page.svelte index fdba7076f..0e40b3aaf 100644 --- a/apps/web/src/routes/admin/flags/+page.svelte +++ b/apps/web/src/routes/admin/flags/+page.svelte @@ -9,6 +9,6 @@ Flags · Local Network
- +
diff --git a/apps/web/src/routes/admin/flags/[key]/+page.svelte b/apps/web/src/routes/admin/flags/[key]/+page.svelte index 6644d9e49..2569259a4 100644 --- a/apps/web/src/routes/admin/flags/[key]/+page.svelte +++ b/apps/web/src/routes/admin/flags/[key]/+page.svelte @@ -2,6 +2,7 @@ import { ArrowLeft } from '@lucide/svelte'; import { enhance } from '$app/forms'; import FormMessage from '#lib/components/FormMessage.svelte'; + import { SHOWS_ON } from '#lib/flags/shows-on.ts'; import { formFields } from '#lib/form-fields.svelte.ts'; import SectionHeader from '#lib/ui/SectionHeader.svelte'; import type { PageProps } from './$types'; @@ -10,6 +11,9 @@ const flag = $derived(data.flag); + /** The kinds of page the flag changes, as its catalog file lists them. */ + const showsOn = $derived(flag.showsOn.map((kind) => SHOWS_ON[kind]).join(', ') || 'None listed'); + /** What this browser sees for the flag instead of what's saved, if anything. */ const previewing = $derived(data.flagPreview?.[flag.key]); @@ -28,7 +32,10 @@
Flags - +
+ +

Shows on: {showsOn}

+
({ update }) => update({ reset: false })}>
- + -

Accounts stay in as this grows. Signed-out visitors aren't counted.

+

Signed-out visitors count once per browser. Everyone in stays in as it grows.

Groups diff --git a/apps/web/src/routes/admin/flags/[key]/page.stories.svelte b/apps/web/src/routes/admin/flags/[key]/page.stories.svelte index d8acad1b3..18b38cae3 100644 --- a/apps/web/src/routes/admin/flags/[key]/page.stories.svelte +++ b/apps/web/src/routes/admin/flags/[key]/page.stories.svelte @@ -12,6 +12,7 @@ const flag: FlagView = { key: 'parityCanary', description: 'Gates nothing. Turn it on for an account to check that the website and locallibrary give it the same answer.', + showsOn: ['profile'], enabled: true, everyone: false, percentage: 25, @@ -40,7 +41,7 @@ asChild play={async ({ canvasElement }) => { await expect(within(canvasElement).getByRole('switch', { name: /^Off for everyone/ })).toBeChecked(); - await expect(within(canvasElement).getByLabelText('Percentage of accounts')).toHaveValue(25); + await expect(within(canvasElement).getByLabelText('Percentage of people')).toHaveValue(25); }} > @@ -63,4 +64,8 @@ + + + + diff --git a/apps/web/src/routes/admin/flags/[key]/page.svelte.test.ts b/apps/web/src/routes/admin/flags/[key]/page.svelte.test.ts new file mode 100644 index 000000000..af31527e9 --- /dev/null +++ b/apps/web/src/routes/admin/flags/[key]/page.svelte.test.ts @@ -0,0 +1,53 @@ +import { page } from 'vitest/browser'; +import { expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import { ada } from '#lib/testing/requests.ts'; +import type { FlagView } from '#lib/types.ts'; +import Page from './+page.svelte'; + +it('lists the kinds of page the flag shows on', async () => { + await renderFlag({ showsOn: ['profile'] }); + + await expect.element(page.getByText('Shows on: Profile', { exact: true })).toBeVisible(); +}); + +it('names each kind as the staff console does, and every page for global', async () => { + await renderFlag({ showsOn: ['pressKit', 'party'] }); + + await expect.element(page.getByText('Shows on: Press kit, Party', { exact: true })).toBeVisible(); + + await renderFlag({ showsOn: ['global'] }); + + await expect.element(page.getByText('Shows on: Every page', { exact: true })).toBeVisible(); +}); + +it('says so when the flag lists no kind of page', async () => { + await renderFlag({ showsOn: [] }); + + await expect.element(page.getByText('Shows on: None listed', { exact: true })).toBeVisible(); +}); + +// Helpers + +/** The flag page for parityCanary, with `fields` on top of a flag nobody has set. */ +function renderFlag(fields: Partial) { + const flag: FlagView = { + key: 'parityCanary', + description: 'Gates nothing.', + showsOn: [], + enabled: true, + everyone: false, + percentage: 0, + groups: [], + accounts: [], + updatedAt: null, + readyToRemove: false, + ...fields + }; + + return render(Page, { + params: { key: flag.key }, + form: null, + data: { viewer: ada, pendingRequests: 0, grants: ['flags'], flag, groups: [] } + }); +} diff --git a/docs/adr/0018-signed-out-visitors-get-a-rollout-id.md b/docs/adr/0018-signed-out-visitors-get-a-rollout-id.md new file mode 100644 index 000000000..86f7b8e59 --- /dev/null +++ b/docs/adr/0018-signed-out-visitors-get-a-rollout-id.md @@ -0,0 +1,25 @@ +# Signed-out visitors get a rollout id + +The rule that decides a flag buckets a DID, and a signed-out visitor has none, so a percentage only ever counted accounts. That was fine while new features were for signed-in DJs. Public pages are different: most people who see an act, party, venue or event page aren't signed in, so a flag like `spacePages` could only go from a staff preview straight to everyone. + +So while any flag is on for a percentage, the website gives a signed-out browser an id of its own: a random version 4 UUID in a first-party cookie, `ln_flag_visitor`, for the site's whole path, `HttpOnly`, `SameSite=Lax`, `Secure` over https, kept for a year. The rule buckets `visitor:` followed by that UUID with the same sum it uses for a DID, so a browser gets the same answer on every request and stays in as the percentage grows. A DID starts `did:`, so a visitor's id is never an account's and is never targeted. `flags/vectors.json` has cases for visitor ids, which locallibrary's test reads as it reads any other id. + +Nothing else asks differently. `getFlags` and locallibrary ask with a DID or with nothing, and an xrpc call never reads a cookie, so a caller with neither still only gets flags on for everyone. The cookie is only set for a signed-out visitor outside `/xrpc/`, and only while a flag is enabled, not on for everyone, and above 0%. The server uses the id for flags alone and never stores or logs it; a request's log line only says whether the visitor's id was new. + +A signed-out page that depends on the id can't go in a shared cache. `cacheBriefly` marks signed-out pages `public`, and a visitor's first response sets the cookie, so a cache in front of the site could serve one visitor's answer and their cookie to the next. Nothing caches in front of the site today, but while a visitor id is in use the server hook turns `public` into `private` on the response. Browsers still cache their own copy. + +## Considered options + +- Leaving signed-out visitors out of percentages, as before: no cookie, and no gradual rollout of a public page. +- Bucketing by IP address or user agent: many people share an address, one person's changes between networks, and the hash would be built from personal data. +- An id in local storage, as LaunchDarkly's browser SDK keeps one: pages are rendered on the server, which can't read it on any request. +- Bucketing on the flag key alone, as Statsig does for an empty id: every visitor gets the same answer, so a percentage becomes a switch. +- Setting the cookie on every signed-out request: most of the time no flag needs it, and signed-out pages would never be shared-cacheable. +- Relying on `Vary: Cookie`, which `cacheBriefly` already sends: a cached first response has no cookie to vary on, and carries its `Set-Cookie` to everyone after. + +## Consequences + +- Signing in moves someone from their browser's bucket to their account's, so a feature can appear or disappear for them at that moment. PostHog documents the same problem. +- Crawlers and anything else that drops cookies get a new id on every request, so during a percentage rollout they see the flag on at about that rate. A page that 404s while its flag is off will 404 to a crawler some of the time. `spacePages` writes no directory listing until it's on for everyone, which keeps those pages out of the directory meanwhile. +- A visitor can clear or edit the cookie to land somewhere else. Flags are for rolling something out, not for keeping anyone out, so that's allowed. +- While any flag is on for a percentage, no signed-out response outside `/xrpc/` is shared-cacheable. diff --git a/docs/research/feature-flag-platforms.md b/docs/research/feature-flag-platforms.md index d24852147..19c728779 100644 --- a/docs/research/feature-flag-platforms.md +++ b/docs/research/feature-flag-platforms.md @@ -16,7 +16,7 @@ Every platform in the set evaluates a flag the same way: it checks for a kill or | Reusable audiences | Segments, cohorts, saved groups, often rule-based | Named groups of up to 5000 DIDs | No rule-based membership | No | | Exclusions | Segment `excluded` lists (LD), "none of" (Statsig), `NONE` rules (Flagsmith) | None: any matching gate turns a flag on | Can't pull one account out of a rollout | Low | | Percentage rollout | Hash of salt plus stable id into 100 to 100,000 buckets | `sha256(key + did)`, first 4 bytes, mod 100, which ADR 0006 has locallibrary apply too | Coarse 1% steps, no re-salt | No | -| Signed-out visitors | Random device keys (LD, PostHog), random fallback (Unleash), bucket on salt alone (Statsig) | Only `everyone` applies | No partial rollout to signed-out visitors | Low, by design | +| Signed-out visitors | Random device keys (LD, PostHog), random fallback (Unleash), bucket on salt alone (Statsig) | A random id in a first-party cookie while a flag is on for a percentage, bucketed like a DID | None | None | | Prerequisites | Flag-on-flag dependencies in LD, Statsig, FME, ConfigCat, PostHog, GrowthBook, Unleash | None | None | No | | Kill switch | A dedicated off state that keeps targeting (LD off variation, FME kill, flagd `DISABLED`, GOFF `disable`) | `enabled: false` on the record, which keeps groups, accounts and percentage | None | Done | | Server evaluation | Full ruleset in memory, no network per check | Snapshot from SQLite, reloaded after each write or sync | None | No | @@ -73,7 +73,7 @@ The properties that matter are all there. The flag key acts as a per-flag salt, Shared vectors guard against a failure the platforms have run into, where SDKs in different languages drift apart. flagd changed its hashing in v0.18.0 and now requires flagd and every provider to upgrade together ([flagd fractional](https://flagd.dev/reference/custom-operations/fractional-operation/)). GrowthBook had to ship a second hash version after v1 "had a flaw that caused bias when running experiments in parallel" and pins UTF-16 code units to keep SDKs consistent ([GrowthBook SDK spec](https://docs.growthbook.io/lib/build-your-own)). Flipt's own docs describe its hash input differently from what its v2.14.1 code does ([Flipt concepts](https://docs.flipt.io/v2/concepts) vs [evaluation.go](https://github.com/flipt-io/flipt/blob/v2.14.1/internal/server/evaluation/evaluation.go#L240-L280)). One vectors file that every evaluator must pass is the cheap version of OpenFeature's provider conformance kit. -Two hashing features are missing, and neither matters yet. LaunchDarkly, Statsig and Flagsmith keep a salt separate from the flag key, so a flag can be renamed without reshuffling anyone, and an operator can re-salt on purpose to reshuffle: "To reshuffle all users, you must resalt the gate" ([Statsig FAQ](https://docs.statsig.com/faq/); [LD salt support article](https://support.launchdarkly.com/hc/en-us/articles/36961986486811-How-to-update-the-flag-salt); [Flagsmith models.py](https://github.com/Flagsmith/flagsmith/blob/v2.290.0/api/features/models.py#L774-L781)). In Local Network, renaming a key means a new catalog file and a fresh rollout anyway, so a separate salt would buy nothing. The second is signed-out visitors. LaunchDarkly gives them a random key kept in local storage, PostHog buckets by `$device_id`, Unleash falls back to a random number with no stickiness, and Statsig buckets empty IDs on the salt alone, so every anonymous visitor gets the same answer ([LD anonymous contexts](https://launchdarkly.com/docs/home/flags/anonymous-contexts); [PostHog device bucketing](https://posthog.com/docs/feature-flags/device-bucketing); [Unleash stickiness](https://docs.getunleash.io/reference/stickiness); [Statsig evaluation](https://docs.statsig.com/sdks/how-evaluation-works)). Local Network leaves signed-out visitors out of percentages ([flags/README.md](https://github.com/cutenode/localnetwork/blob/2f9d6c93a3b8dbb68fae3b9806ab85af26398ea5/flags/README.md#L17-L24)), which avoids PostHog's documented problem of a user's bucket changing after sign-in ([PostHog creating flags](https://posthog.com/docs/feature-flags/creating-feature-flags)). That's the right default for a site where new features are aimed at signed-in DJs. +Two hashing features are missing, and neither matters yet. LaunchDarkly, Statsig and Flagsmith keep a salt separate from the flag key, so a flag can be renamed without reshuffling anyone, and an operator can re-salt on purpose to reshuffle: "To reshuffle all users, you must resalt the gate" ([Statsig FAQ](https://docs.statsig.com/faq/); [LD salt support article](https://support.launchdarkly.com/hc/en-us/articles/36961986486811-How-to-update-the-flag-salt); [Flagsmith models.py](https://github.com/Flagsmith/flagsmith/blob/v2.290.0/api/features/models.py#L774-L781)). In Local Network, renaming a key means a new catalog file and a fresh rollout anyway, so a separate salt would buy nothing. The second is signed-out visitors. LaunchDarkly gives them a random key kept in local storage, PostHog buckets by `$device_id`, Unleash falls back to a random number with no stickiness, and Statsig buckets empty IDs on the salt alone, so every anonymous visitor gets the same answer ([LD anonymous contexts](https://launchdarkly.com/docs/home/flags/anonymous-contexts); [PostHog device bucketing](https://posthog.com/docs/feature-flags/device-bucketing); [Unleash stickiness](https://docs.getunleash.io/reference/stickiness); [Statsig evaluation](https://docs.statsig.com/sdks/how-evaluation-works)). Local Network leaves signed-out visitors out of percentages ([flags/README.md](https://github.com/cutenode/localnetwork/blob/2f9d6c93a3b8dbb68fae3b9806ab85af26398ea5/flags/README.md#L17-L24)), which avoids PostHog's documented problem of a user's bucket changing after sign-in ([PostHog creating flags](https://posthog.com/docs/feature-flags/creating-feature-flags)). That's the right default for a site where new features are aimed at signed-in DJs. Public pages changed that: [ADR 0018](../adr/0018-signed-out-visitors-get-a-rollout-id.md) gives a signed-out browser a random id in a cookie while a flag is on for a percentage, and buckets it like a DID. Signing in still moves a visitor to their account's bucket. The time-based rollout tools are where the paid tiers live. LaunchDarkly's progressive rollouts ramp a percentage on a schedule, and its guarded rollouts watch metrics and roll back automatically on a significant regression, which needs Enterprise plus the Guardian add-on ([LD progressive](https://launchdarkly.com/docs/home/releases/progressive-rollouts); [LD guarded](https://launchdarkly.com/docs/home/releases/guarded-rollouts)). Statsig has release pipelines and rollout alerts ([Statsig release pipeline](https://docs.statsig.com/release-pipeline); [rollout alerts](https://docs.statsig.com/metrics/rollout-alerts)). PostHog schedules changes on cron ([PostHog scheduled changes](https://posthog.com/docs/feature-flags/scheduled-flag-changes)), and GO Feature Flag offers `scheduledRollout` and `progressiveRollout` for free ([GOFF internal_flag.go](https://github.com/thomaspoignant/go-feature-flag/blob/v1.58.1/modules/core/flag/internal_flag.go#L209-L262)). Guarded rollouts need a metrics pipeline Local Network doesn't have, and scheduled ramps save a few clicks spread over a week. Neither is worth building. @@ -139,20 +139,20 @@ Staff holding the `flags` grant can preview a flag from `/admin/flags/`, tu ## Gaps ranked for a project this size -The ranking weighs how likely each gap is to bite against what it costs to close. Rows 1 and 3 to 6 are done. Row 2 is open. Rows 7 to 10 are left as designed. - -| # | Gap | Status | When it matters | Fix | -| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------- | -| 1 | `flags/**` was in neither the `web` nor the `locallibrary` CI path filter, so a PR that only touched the catalog or `vectors.json` ran no checks ([ci.yml web](https://github.com/cutenode/localnetwork/blob/2f9d6c93a3b8dbb68fae3b9806ab85af26398ea5/.github/workflows/ci.yml#L177-L199); [ci.yml locallibrary](https://github.com/cutenode/localnetwork/blob/2f9d6c93a3b8dbb68fae3b9806ab85af26398ea5/.github/workflows/ci.yml#L107-L124)). PR #456 promised this as a follow-up | Done | Now | `flags/**` is in both filters of `.github/workflows/ci.yml` | -| 2 | The locallibrary client isn't merged; main has ADR 0006 and the website endpoint, but no Rust code reads flags | Open | Before any locallibrary feature uses a flag | Deploy the website side, pass one live sign-in with a dev build, merge the client | -| 3 | Turning a flag off meant clearing all its targeting | Done | Before the first real rollout | Optional `enabled` on `staff.flag`, checked first, with new vectors and an "Off for everyone" switch | -| 4 | No developer or tester override | Done | Before the first real rollout | `FLAG_OVERRIDES` for development and tests; a signed preview cookie for staff | -| 5 | No type or removal date in the catalog, so nothing failed when a flag outlived its purpose | Done | Past about five flags | `type` and `removeBy` in the schema, plus a time-bomb test | -| 6 | No "fully rolled out" signal in the admin list | Done | Past about five flags | "Ready to remove" for enabled flags at `everyone` or 100% for 30+ days | -| 7 | Every catalog key reaches every browser; public gates are readable through `getFlags` | Left as designed | Only if a key name spoils a launch | Pick neutral key names | -| 8 | No per-account exclusion inside a rollout | Left as designed | If one account in a partial rollout hits a bug | A `notDids` list, only if it comes up | -| 9 | Signed-out visitors can't be in a percentage | Left as designed | Only for a rollout aimed at anonymous visitors | None | -| 10 | 1% steps, flag key as salt, no re-salt | Left as designed | Not at this scale | None | +The ranking weighs how likely each gap is to bite against what it costs to close. Rows 1, 3 to 6 and 9 are done. Row 2 is open. Rows 7, 8 and 10 are left as designed. + +| # | Gap | Status | When it matters | Fix | +| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | +| 1 | `flags/**` was in neither the `web` nor the `locallibrary` CI path filter, so a PR that only touched the catalog or `vectors.json` ran no checks ([ci.yml web](https://github.com/cutenode/localnetwork/blob/2f9d6c93a3b8dbb68fae3b9806ab85af26398ea5/.github/workflows/ci.yml#L177-L199); [ci.yml locallibrary](https://github.com/cutenode/localnetwork/blob/2f9d6c93a3b8dbb68fae3b9806ab85af26398ea5/.github/workflows/ci.yml#L107-L124)). PR #456 promised this as a follow-up | Done | Now | `flags/**` is in both filters of `.github/workflows/ci.yml` | +| 2 | The locallibrary client isn't merged; main has ADR 0006 and the website endpoint, but no Rust code reads flags | Open | Before any locallibrary feature uses a flag | Deploy the website side, pass one live sign-in with a dev build, merge the client | +| 3 | Turning a flag off meant clearing all its targeting | Done | Before the first real rollout | Optional `enabled` on `staff.flag`, checked first, with new vectors and an "Off for everyone" switch | +| 4 | No developer or tester override | Done | Before the first real rollout | `FLAG_OVERRIDES` for development and tests; a signed preview cookie for staff | +| 5 | No type or removal date in the catalog, so nothing failed when a flag outlived its purpose | Done | Past about five flags | `type` and `removeBy` in the schema, plus a time-bomb test | +| 6 | No "fully rolled out" signal in the admin list | Done | Past about five flags | "Ready to remove" for enabled flags at `everyone` or 100% for 30+ days | +| 7 | Every catalog key reaches every browser; public gates are readable through `getFlags` | Left as designed | Only if a key name spoils a launch | Pick neutral key names | +| 8 | No per-account exclusion inside a rollout | Left as designed | If one account in a partial rollout hits a bug | A `notDids` list, only if it comes up | +| 9 | Signed-out visitors can't be in a percentage | Done | Before a public page rolls out to a share of visitors | A random id in a first-party cookie, bucketed like a DID ([ADR 0018](../adr/0018-signed-out-visitors-get-a-rollout-id.md)) | +| 10 | 1% steps, flag key as salt, no re-salt | Left as designed | Not at this scale | None | One smaller problem is also open. PR #456 notes that the pinned PDS doesn't enforce a space type's `collections`, so whether the production PDS accepts the staff collections hasn't been tested. If it refused them, saving a flag would fail and every flag would stay off ([PR #456](https://github.com/cutenode/localnetwork/pull/456)). That one belongs with row 2's live check, since the website deploy is a precondition anyway. diff --git a/flags/README.md b/flags/README.md index 11bfe6f12..2a7636785 100644 --- a/flags/README.md +++ b/flags/README.md @@ -6,6 +6,8 @@ Every flag has a `type`, `release` or `ops`. A `release` flag is meant to go, so A flag nobody has saved reads as off, so name a flag for the state you can switch it to. A kill switch, for something that already works, is named for the paused state, like `pauseRecordingStream`, and is `ops`: the deploy that adds it changes nothing, and turning it on stops the feature. Something that's dark today and should stay switchable after it ships, like inbox email, is named for the on state and is `ops` too, so it has no `removeBy`. Use `release` only for flags that go once the rollout is done. +A flag can list the kinds of page it changes in `showsOn`: `profile`, `act`, `party`, `venue`, `event`, `set`, `mix` or `pressKit`, or `global` for every page. An act's page is still `/projects/` until acts move. The flag's page in the staff console lists them under Shows on. Leave it out when the flag changes no public page, like a kill switch for the token exchange or something in the dashboard. + Who a flag is on for lives in the staff space and is set at `/admin/flags`, not here. Every flag starts off. The list there marks a flag "Ready to remove" once it's been on for everyone, or every account, for 30 days. ```jsonc @@ -14,24 +16,25 @@ Who a flag is on for lives in the staff space and is set at `/admin/flags`, not "key": "newPlanner", "description": "What the flag gates, for the staff console.", "type": "release", - "removeBy": "2027-03-01" + "removeBy": "2027-03-01", + "showsOn": ["profile"] } ``` -Check a flag on the website with `locals.flags.newPlanner` on the server or `data.flags?.newPlanner` in a page. An xrpc route gets the flags a signed-out visitor does, since the website never reads the sign-in cookie there: a flag on or off for everyone works, and targeting and percentages don't. A route that has checked a service token can call `app.flags.evaluate(did)` with that token's DID to get them. +Check a flag on the website with `locals.flags.newPlanner` on the server or `data.flags?.newPlanner` in a page. An xrpc route never reads a cookie, so it only gets flags on for everyone: targeting and percentages don't reach it. A route that has checked a service token can call `app.flags.evaluate(did)` with that token's DID to get them. In locallibrary, use `locallibrary::flags::check(root, flags::keys::NEW_PLANNER)`. A flag in locallibrary is for rolling something out. Anything that has to be enforced belongs on the server, since anyone can change what's on their own computer. ## How a flag is decided ```text -bucket(key, did) = the first 4 bytes of sha256(key + did), big-endian, mod 100 -on = enabled && (everyone || targeted || (did is known && bucket(key, did) < percentage)) +bucket(key, id) = the first 4 bytes of sha256(key + id), big-endian, mod 100 +on = enabled && (everyone || targeted || (id is known && bucket(key, id) < percentage)) ``` -`enabled` is false once someone turns the flag off for everyone, which keeps the other gates for when it's back on. A record that doesn't say is enabled. `targeted` means the account is one of the flag's accounts or in one of its groups. Only the website can know that, since those lists are private; it says so through `computer.localnetwork.flags.getFlags`. Raising a percentage only adds accounts. Signed-out visitors have no DID, so they only get flags on for everyone. +`enabled` is false once someone turns the flag off for everyone, which keeps the other gates for when it's back on. A record that doesn't say is enabled. `targeted` means the account is one of the flag's accounts or in one of its groups. Only the website can know that, since those lists are private; it says so through `computer.localnetwork.flags.getFlags`. `id` is the caller's DID. A signed-out visitor has none, so while any flag is on for a percentage the website gives their browser a random id in a first-party cookie, `ln_flag_visitor`, and buckets `visitor:` followed by it. They get the same answer on every request until they clear it or sign in, when their account's bucket takes over. A caller with neither, like an xrpc call, only gets flags on for everyone. Raising a percentage only adds accounts and browsers. [ADR 0018](../docs/adr/0018-signed-out-visitors-get-a-rollout-id.md) covers why, and what it means for caching and crawlers. -`vectors.json` holds computed answers. The website's and locallibrary's tests both run them, so the two can't come to disagree. A case without `enabled` is enabled. If a case has to change, the rule changed, and accounts will move in or out of every rollout. +`vectors.json` holds computed answers, for DIDs, visitor ids and callers with neither. The website's and locallibrary's tests both run them, so the two can't come to disagree. A case without `enabled` is enabled. If a case has to change, the rule changed, and accounts will move in or out of every rollout. ## Trying a flag diff --git a/flags/catalog/parityCanary.json b/flags/catalog/parityCanary.json index 369332f90..730778e2c 100644 --- a/flags/catalog/parityCanary.json +++ b/flags/catalog/parityCanary.json @@ -2,5 +2,6 @@ "$schema": "../flag.schema.json", "key": "parityCanary", "description": "Gates nothing. Turn it on for an account to check that the website and locallibrary give it the same answer.", - "type": "ops" + "type": "ops", + "showsOn": ["profile"] } diff --git a/flags/catalog/peopleSpaces.json b/flags/catalog/peopleSpaces.json index f17233d9f..e3ae06c2e 100644 --- a/flags/catalog/peopleSpaces.json +++ b/flags/catalog/peopleSpaces.json @@ -3,5 +3,6 @@ "key": "peopleSpaces", "description": "The member pages of acts, parties and venues: inviting people, invite links, asking to join and people lists. Off, they answer 404.", "type": "release", - "removeBy": "2027-02-12" + "removeBy": "2027-02-12", + "showsOn": ["act", "party", "venue"] } diff --git a/flags/catalog/spacePages.json b/flags/catalog/spacePages.json index 15079b1de..287cc1a13 100644 --- a/flags/catalog/spacePages.json +++ b/flags/catalog/spacePages.json @@ -1,7 +1,8 @@ { "$schema": "../flag.schema.json", "key": "spacePages", - "description": "The public act, party, venue and event pages. Off, they answer 404, and no listing is written until it's on for everyone, since a listing points at a public page. Signed-out visitors only see it once it's on for everyone.", + "description": "The public act, party, venue and event pages. Off, they answer 404, and no listing is written until it's on for everyone, since a listing points at a public page.", "type": "release", - "removeBy": "2027-02-12" + "removeBy": "2027-02-12", + "showsOn": ["act", "party", "venue", "event"] } diff --git a/flags/flag.schema.json b/flags/flag.schema.json index 8bebec29a..0bb902162 100644 --- a/flags/flag.schema.json +++ b/flags/flag.schema.json @@ -20,6 +20,15 @@ "maxLength": 300, "description": "What the flag gates, for the staff console." }, + "showsOn": { + "description": "The kinds of page the flag changes, or global for every page. act is a /projects page until acts move. The staff console lists them as Shows on.", + "minItems": 1, + "type": "array", + "items": { + "type": "string", + "enum": ["global", "profile", "act", "party", "venue", "event", "set", "mix", "pressKit"] + } + }, "type": { "type": "string", "const": "release", @@ -53,6 +62,15 @@ "maxLength": 300, "description": "What the flag gates, for the staff console." }, + "showsOn": { + "description": "The kinds of page the flag changes, or global for every page. act is a /projects page until acts move. The staff console lists them as Shows on.", + "minItems": 1, + "type": "array", + "items": { + "type": "string", + "enum": ["global", "profile", "act", "party", "venue", "event", "set", "mix", "pressKit"] + } + }, "type": { "type": "string", "const": "ops", diff --git a/flags/vectors.json b/flags/vectors.json index df1685f4e..ff356d1e1 100644 --- a/flags/vectors.json +++ b/flags/vectors.json @@ -1,5 +1,5 @@ { - "$comment": "Computed answers both the website and locallibrary test themselves against. A case without `enabled` is a record that doesn't say, which counts as true. Add cases freely; changing one means the rule changed, and every account can move.", + "$comment": "Computed answers both the website and locallibrary test themselves against. `did` is the id the rule buckets: an account's DID, a signed-out visitor's `visitor:` id from the website's cookie, or null for a caller with neither. A case without `enabled` is a record that doesn't say, which counts as true. Add cases freely; changing one means the rule changed, and every account can move.", "cases": [ { "key": "parityCanary", @@ -742,6 +742,60 @@ "percentage": 100, "bucket": null, "on": false + }, + { + "key": "parityCanary", + "did": "visitor:00000000-0000-4000-8000-000000000000", + "everyone": false, + "targeted": false, + "percentage": 16, + "bucket": 16, + "on": false + }, + { + "key": "parityCanary", + "did": "visitor:00000000-0000-4000-8000-000000000000", + "everyone": false, + "targeted": false, + "percentage": 17, + "bucket": 16, + "on": true + }, + { + "key": "parityCanary", + "did": "visitor:00000008-0000-4000-8000-000000000000", + "everyone": false, + "targeted": false, + "percentage": 99, + "bucket": 99, + "on": false + }, + { + "key": "parityCanary", + "did": "visitor:00000008-0000-4000-8000-000000000000", + "everyone": false, + "targeted": false, + "percentage": 100, + "bucket": 99, + "on": true + }, + { + "key": "spacePages", + "did": "visitor:00000000-0000-4000-8000-000000000000", + "everyone": false, + "targeted": false, + "percentage": 57, + "bucket": 57, + "on": false + }, + { + "key": "spacePages", + "did": "visitor:00000000-0000-4000-8000-000000000000", + "everyone": false, + "targeted": false, + "percentage": 58, + "bucket": 57, + "on": true } ] } From 7bd4ce3e5f3deacb7c60af8e442b50d42336746b Mon Sep 17 00:00:00 2001 From: botandbang <337765928+botandbang@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:58:12 -0600 Subject: [PATCH 04/22] fix(web): keep press kit answers in the request space, and list what a re-sync can't bring back Declining a press kit request only changed SQLite, so a re-sync turned it back into pending and the asker could ask again. The root now writes a computer.localnetwork.epk.decision record into the project's request space for every answer, approvals included, since revoking deletes the grant. The space-sync projection rebuilds the request's status from the root's decisions only, and a decision can make the request's row itself, so a decline holds even after the asker deletes their request. Deleting a press kit deletes its decisions. TABLE_SOURCE in schema.ts marks every table rebuilt by sync or server-only, so a new table doesn't type-check until it's marked, and SERVER_ONLY_COLUMNS lists the parts of rebuilt tables a re-sync can't bring back. A test checks both against the migrated database. The schema header and the README's state diagram follow, with ADMIN_DIDS noted as config. Migration 022 drops account.display_name and avatar_url, which were only ever written as null. Names and avatars come from profile records through HappyView. Fixes LOC-728 Fixes LOC-765 Fixes LOC-730 --- GLOSSARY.md | 4 + apps/web/README.md | 13 +- apps/web/docs/diagrams/press-kits.md | 6 +- apps/web/docs/diagrams/spaces.md | 1 + apps/web/src/lib/epk-schema.ts | 10 ++ apps/web/src/lib/nsid.ts | 2 + apps/web/src/lib/server/db/db.test.ts | 49 +++++- apps/web/src/lib/server/db/migrations.ts | 7 + apps/web/src/lib/server/db/schema.ts | 85 +++++++++- apps/web/src/lib/server/services/accounts.ts | 4 - .../web/src/lib/server/services/epk-fields.ts | 11 +- apps/web/src/lib/server/services/epk.test.ts | 28 ++++ apps/web/src/lib/server/services/epk.ts | 143 ++++++++++++++--- .../src/lib/server/sync/projections.test.ts | 151 +++++++++++++++++- apps/web/src/lib/server/sync/projections.ts | 12 +- .../computer/localnetwork/epk/decision.json | 35 ++++ .../localnetwork/space/epkRequests.json | 8 +- 17 files changed, 519 insertions(+), 50 deletions(-) create mode 100644 lexicons/computer/localnetwork/epk/decision.json diff --git a/GLOSSARY.md b/GLOSSARY.md index eb812afd3..5d13a604b 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -226,6 +226,10 @@ _Avoid_: edit, revision, review request (those go to staff) Letting one account read one press kit's private part. _Avoid_: access, approval, permission (that's staff) +**Press kit request**: +Asking to see one press kit's private part. A manager approves it, which makes a grant, or declines it. The answer stays after a grant is removed, and someone declined can't ask to see that press kit again, though a manager can still invite them. +_Avoid_: review request (that goes to staff) + ## Music **Set**: diff --git a/apps/web/README.md b/apps/web/README.md index 29270e584..c0e059c01 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -381,7 +381,7 @@ See [`.env.example`](.env.example) for every option. The essentials: docker run -p 3000:3000 -v localnetwork-data:/data --env-file .env localnetwork ``` To try an image first, `pnpm -C apps/web test:docker` runs the one tagged `localnetwork` against the local network with an empty volume and fetches a few pages, as CI does. -5. Run **one** instance (SQLite and in-process background jobs). Give it a bucket for [backups](#backups) of `/data`: it holds OAuth sessions, the audit outbox, and records that exist nowhere else. +5. Run **one** instance (SQLite and in-process background jobs). Give it a bucket for [backups](#backups) of `/data`: it holds OAuth sessions, the audit outbox, and records that exist nowhere else ([Where state lives](#where-state-lives)). 6. Point `locallibrary.localnetwork.computer` at the same deployment (a DNS record, plus the custom domain on your host) for [its client document](#tools-pages-and-hosts). `/healthz` reports database, root-account, HappyView, and backup status (`backup` is `stale` with no backup in two days, `off` without a bucket). It answers 200 either way. @@ -591,7 +591,7 @@ Source: [`vite.config.ts`](vite.config.ts), [`src/lib/bug-report.ts`](src/lib/bu ### Where state lives -Every place the app keeps something, and what rebuilds it. +Every place the app keeps something, and what rebuilds it. `TABLE_SOURCE` in `schema.ts` marks each SQLite table rebuilt or server-only, and `SERVER_ONLY_COLUMNS` the parts of rebuilt tables a re-sync can't bring back; a test fails when a table has neither. ```mermaid flowchart TD @@ -600,10 +600,11 @@ flowchart TD Spaces["Spaces
each writer's repo in each space"] end subgraph Server["On the server"] - Index[("SQLite, rebuilt by sync:
requests, threads, grants, people,
performers, flags and flag groups")] - Only[("SQLite, not rebuilt:
sessions, inboxes, receipts")] - Outbox[("SQLite audit log:
rebuilt from the root's copies")] + Index[("SQLite, rebuilt by sync:
requests and their answers, threads, grants,
people, performers, flags and flag groups")] + Only[("SQLite, not rebuilt:
sessions, accounts, inboxes, email settings,
receipts, the geocode cache, and columns like
deletion marks and booking status as first read")] + Outbox[("SQLite audit log:
delivered entries rebuilt from the root's copies")] Memory["Memory:
rate limits, credentials, caches"] + Config["Environment:
ADMIN_DIDS, secrets"] end subgraph Elsewhere["Elsewhere"] HV[("HappyView:
public records its gates keep")] @@ -621,7 +622,7 @@ flowchart TD Outbox -- "daily" --> Bucket ``` -Source: [`src/lib/server/db/schema.ts`](src/lib/server/db/schema.ts), [`src/lib/server/sync/engine.ts`](src/lib/server/sync/engine.ts), [`src/lib/form-draft.svelte.ts`](src/lib/form-draft.svelte.ts), [`src/lib/server/shows-place.ts`](src/lib/server/shows-place.ts), [`src/lib/server/flags/preview.ts`](src/lib/server/flags/preview.ts) +Source: [`src/lib/server/db/schema.ts`](src/lib/server/db/schema.ts), [`src/lib/server/sync/engine.ts`](src/lib/server/sync/engine.ts), [`src/lib/server/config.ts`](src/lib/server/config.ts), [`src/lib/form-draft.svelte.ts`](src/lib/form-draft.svelte.ts), [`src/lib/server/shows-place.ts`](src/lib/server/shows-place.ts), [`src/lib/server/flags/preview.ts`](src/lib/server/flags/preview.ts) ### Local tables: bookings and press kits diff --git a/apps/web/docs/diagrams/press-kits.md b/apps/web/docs/diagrams/press-kits.md index abb63fbba..c9aedccbe 100644 --- a/apps/web/docs/diagrams/press-kits.md +++ b/apps/web/docs/diagrams/press-kits.md @@ -50,7 +50,9 @@ flowchart TD Audiences -- "review" --> Pending["epk.request in the performer's
request space, waits for a manager"] Audiences -- "auto" --> Auto["epk.request, then a grant at once
(a legacy press kit's waits for its move)"] Pending -- "manager approves" --> Grant["Root adds them to the press kit's space
and writes epk.grant to the request space"] + Pending -- "manager declines" --> Declined["Root writes epk.decision, declined,
to the request space; they can't ask again"] Auto --> Grant + Grant -- "it answered a request" --> Approved["Root writes epk.decision, approved,
which outlasts the grant"] Invite["A manager invites them"] --> Grant ``` @@ -58,7 +60,7 @@ Source: [`src/lib/epk.ts`](../../src/lib/epk.ts), [`src/lib/server/services/epk. ## Press kit grant lifecycle -Where someone stands with one press kit. Someone declined can't ask again, but a manager can still invite them. +Where someone stands with one press kit. Someone declined can't ask again, but a manager can still invite them. The root's decision record keeps a decline through a re-sync, even after the asker deletes their request. ```mermaid stateDiagram-v2 @@ -123,7 +125,7 @@ Any of the performer's managers can delete a press kit the root holds. The space flowchart TD Ask["Delete in the press kit's editor"] --> Check["A manager of the performer,
and not a legacy press kit"] Check --> Space["Root deletes the press kit's space,
which puts everyone out of it"] - Space --> Records["Root deletes the requests it wrote
for people, and the grant records"] + Space --> Records["Root deletes the requests it wrote
for people, its decisions and grant records"] Records --> Public["Root deletes the epk record"] Public --> Wait["Waits for HappyView to stop serving it"] Wait --> Index["Forgets the local rows"] diff --git a/apps/web/docs/diagrams/spaces.md b/apps/web/docs/diagrams/spaces.md index d1367b53f..617858a56 100644 --- a/apps/web/docs/diagrams/spaces.md +++ b/apps/web/docs/diagrams/spaces.md @@ -177,6 +177,7 @@ flowchart LR Sync -- "project.details, root only" --> A5["project_details"] Sync -- "booking.inquiry, message, status,
participants and the root" --> A6["booking_thread, booking_event,
inbox items"] Sync -- "epk.request, and epk.grant
from the authority only" --> A7["epk_request, epk_grant"] + Sync -- "epk.decision in a request space,
root only" --> A11["the request's answer,
its row if it has none"] Sync -- "epk.draft in a backstage" --> A8["epk_draft"] Sync -- "people.*, listing.status,
performer, venue,
venue.approval, party, event,
root only" --> A9["shared space tables,
performer, venue or party,
then its listing"] Sync -- "staff.flag, staff.group,
root only" --> A10["feature_flag, flag_group"] diff --git a/apps/web/src/lib/epk-schema.ts b/apps/web/src/lib/epk-schema.ts index c60b185e2..c32ad81a5 100644 --- a/apps/web/src/lib/epk-schema.ts +++ b/apps/web/src/lib/epk-schema.ts @@ -83,5 +83,15 @@ export const epkGrantSchema = z.object({ createdAt: z.string() }); +/** A press kit request's answer. An outcome this app doesn't know fails to parse, so it changes nothing. */ +export const epkDecisionSchema = z.object({ + request: z.string(), + requester: z.string(), + epk: z.string(), + outcome: z.enum(['approved', 'declined']), + decidedBy: z.string(), + createdAt: z.string() +}); + /** A follow record, for the one field the access rules read. */ export const followSchema = z.object({ subject: z.string() }); diff --git a/apps/web/src/lib/nsid.ts b/apps/web/src/lib/nsid.ts index 306efd018..c67650f82 100644 --- a/apps/web/src/lib/nsid.ts +++ b/apps/web/src/lib/nsid.ts @@ -31,6 +31,8 @@ export const COLLECTION = { epk: `${NS}.epk`, epkContent: `${NS}.epk.content`, epkRequest: `${NS}.epk.request`, + /** The root's record of a manager's answer to a press kit request, in the project's request space. */ + epkDecision: `${NS}.epk.decision`, epkGrant: `${NS}.epk.grant`, /** A manager's unpublished changes to a press kit, in their repo in the project's backstage. */ epkDraft: `${NS}.epk.draft`, diff --git a/apps/web/src/lib/server/db/db.test.ts b/apps/web/src/lib/server/db/db.test.ts index a5d1f48f9..a37ecfa7e 100644 --- a/apps/web/src/lib/server/db/db.test.ts +++ b/apps/web/src/lib/server/db/db.test.ts @@ -3,6 +3,7 @@ import { afterEach, describe, expect, it } from 'vitest'; import { COLLECTION } from '#lib/nsid.ts'; import { type Db, nowIso, openDatabase, parseJson } from './index'; import { migrations } from './migrations'; +import { SERVER_ONLY_COLUMNS, TABLE_SOURCE } from './schema'; describe('database', () => { let db: Db | undefined; @@ -66,6 +67,52 @@ describe('database', () => { ]); }); + // Backups keep what a re-sync can't bring back, so every table has to say which it is. + it('marks every table rebuilt or server-only, and names only columns that exist', async () => { + db = await openDatabase(':memory:'); + + const camel = (name: string) => name.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase()); + const snake = (name: string) => name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`); + + const columns = async (table: string) => + (await sql<{ name: string }>`PRAGMA table_info(${sql.raw(snake(table))})`.execute(db!)).rows.map( + ({ name }) => name + ); + + const tables = await sql<{ name: string }>` + SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT GLOB 'sqlite_*' AND name NOT GLOB 'kysely_*' + `.execute(db); + + expect(tables.rows.map(({ name }) => camel(name)).toSorted()).toEqual(Object.keys(TABLE_SOURCE).toSorted()); + + for (const [table, named] of Object.entries(SERVER_ONLY_COLUMNS)) + expect(await columns(table)).toEqual(expect.arrayContaining(named.map(snake))); + }); + + it("drops the account's display name and avatar columns, keeping every account", async () => { + db = await openDatabase(':memory:'); + + const columns = async () => + (await sql<{ name: string }>`PRAGMA table_info(account)`.execute(db!)).rows.map(({ name }) => name); + + expect(await columns()).not.toContain('display_name'); + expect(await columns()).not.toContain('avatar_url'); + + // Put the table back as 021 left it, with an account in it, and run 022 on its own. + await sql`ALTER TABLE account ADD COLUMN display_name TEXT`.execute(db); + await sql`ALTER TABLE account ADD COLUMN avatar_url TEXT`.execute(db); + await sql`INSERT INTO account (did, handle, created_at, updated_at) VALUES ('did:plc:a', 'a.test', 'now', 'now')`.execute( + db + ); + await migrations['022_account_without_profile'].up(db); + + expect(await columns()).not.toContain('display_name'); + expect(await columns()).not.toContain('avatar_url'); + expect(await db.selectFrom('account').select(['did', 'handle']).execute()).toEqual([ + { did: 'did:plc:a', handle: 'a.test' } + ]); + }); + it('maps camelCase columns, binary values, and booleans', async () => { db = await openDatabase(':memory:'); const lt = new Uint8Array([1, 2, 3]); @@ -89,8 +136,6 @@ describe('database', () => { .values({ did: 'did:plc:a', handle: null, - displayName: null, - avatarUrl: null, pdsUrl: null, // A boolean bound through the adapter is stored as 1. spacesCapable: sql`${true}`, diff --git a/apps/web/src/lib/server/db/migrations.ts b/apps/web/src/lib/server/db/migrations.ts index 5a09eca5b..a0da95229 100644 --- a/apps/web/src/lib/server/db/migrations.ts +++ b/apps/web/src/lib/server/db/migrations.ts @@ -618,6 +618,13 @@ export const migrations = { .execute(db); await sql.raw('CREATE INDEX venue_approval_event ON venue_approval (event_uri)').execute(db); } + }, + // Names and avatars come from profile records through HappyView; these were only ever written null. + '022_account_without_profile': { + async up(db) { + await sql.raw('ALTER TABLE account DROP COLUMN display_name').execute(db); + await sql.raw('ALTER TABLE account DROP COLUMN avatar_url').execute(db); + } } } satisfies Record; diff --git a/apps/web/src/lib/server/db/schema.ts b/apps/web/src/lib/server/db/schema.ts index de7e4f356..a6a16fffc 100644 --- a/apps/web/src/lib/server/db/schema.ts +++ b/apps/web/src/lib/server/db/schema.ts @@ -4,10 +4,10 @@ import type { SpaceKind } from '#lib/capabilities.ts'; import type { NotificationChannel, PausedReason, RequestKind } from '#lib/types.ts'; /** - * Local index. Everything here except sessions, the audit outbox, press kit view receipts and - * people's inboxes is derived from records stored in atproto repos and spaces, and can be - * rebuilt by re-syncing, so those need backing up. Published projects aren't - * here: HappyView indexes them. + * Local index. Most of it is derived from records in atproto repos and spaces and rebuilt by + * re-syncing them; {@link TABLE_SOURCE} marks which tables, and {@link SERVER_ONLY_COLUMNS} the + * parts of rebuilt tables a re-sync can't bring back. Those, and ADMIN_DIDS in the config, are what + * backups have to keep. Published projects aren't here: HappyView indexes them. * Column names are snake_case in SQLite and camelCase in code. */ export interface Database { @@ -52,6 +52,81 @@ export interface Database { notificationDelivery: NotificationDeliveryTable; } +/** + * Where each table's rows come from. `rebuilt` ones come back from records on the network: the space sync, or for venue + * blocks, the root's repo at startup. `server-only` ones live only here, so a restore needs them from a backup. A new + * table has to pick one to type-check. + */ +export const TABLE_SOURCE = { + /** The root's session, when the app first started, HappyView script uploads and listing digests. */ + kv: 'server-only', + /** Who signed in, with which grant. Handles resolve again; the grants don't. */ + account: 'server-only', + webSession: 'server-only', + oauthState: 'server-only', + oauthSession: 'server-only', + projectDetails: 'rebuilt', + request: 'rebuilt', + staffRole: 'rebuilt', + featureFlag: 'rebuilt', + flagGroup: 'rebuilt', + /** The outbox. Entries whose root copy landed come back from it; those still waiting, and every delivery's state, don't. */ + auditEntry: 'server-only', + auditCopy: 'rebuilt', + /** Bootstrap watches the root's spaces again; the sync's own bookkeeping starts over with them. */ + spaceWatch: 'rebuilt', + syncedRepo: 'rebuilt', + syncRepoRetry: 'rebuilt', + pendingProjection: 'rebuilt', + spaceRecord: 'rebuilt', + bookingThread: 'rebuilt', + bookingParticipant: 'rebuilt', + bookingEvent: 'rebuilt', + epkRequest: 'rebuilt', + epkGrant: 'rebuilt', + epkDraft: 'rebuilt', + sharedSpace: 'rebuilt', + spacePerson: 'rebuilt', + performer: 'rebuilt', + venue: 'rebuilt', + venueBlock: 'rebuilt', + party: 'rebuilt', + venueApproval: 'rebuilt', + event: 'rebuilt', + spaceInvite: 'rebuilt', + spaceInviteLink: 'rebuilt', + spaceJoinRequest: 'rebuilt', + /** Press kit view receipts, which never go on atproto. */ + epkView: 'server-only', + /** A cache: lookups fetch again, so a restore can go without it. */ + geocodeCache: 'server-only', + notification: 'server-only', + /** Where each person's inbox also goes, their email address included. */ + notificationChannel: 'server-only', + notificationDelivery: 'server-only' +} as const satisfies Record; + +/** The columns of rebuilt tables that only the server knows, which a re-sync loses or works out differently. */ +export const SERVER_ONLY_COLUMNS = { + /** + * A request whose record is gone keeps its row only here: marked deleted after it was decided, or withdrawn. The + * root's decision on it can't come back without the request. + */ + request: ['deletedAt'], + /** + * The thread's status, judged from status records as first read. A status record rewritten since reads differently on + * a re-sync, and so may the moves it allowed. + */ + bookingThread: ['status'], + bookingEvent: ['kind', 'record'], + /** + * What the press kit's rules said when the request came in; a re-sync reads them as they are then. A press kit + * request's answer, and the decline that stops its asker asking again, come back from the root's decision record. + */ + epkRequest: ['rule'], + epkDraft: ['publishedRkey'] +} as const satisfies { [T in keyof Database]?: readonly (keyof Database[T] & string)[] }; + export interface KvTable { key: string; value: string; @@ -60,8 +135,6 @@ export interface KvTable { export interface AccountTable { did: string; handle: string | null; - displayName: string | null; - avatarUrl: string | null; pdsUrl: string | null; spacesCapable: number; grantedScope: string | null; diff --git a/apps/web/src/lib/server/services/accounts.ts b/apps/web/src/lib/server/services/accounts.ts index 2b3762948..8e3e27c34 100644 --- a/apps/web/src/lib/server/services/accounts.ts +++ b/apps/web/src/lib/server/services/accounts.ts @@ -29,8 +29,6 @@ export class AccountService { .values({ did: input.did, handle: input.handle, - displayName: null, - avatarUrl: null, pdsUrl: input.pdsUrl, spacesCapable: input.spacesCapable ? 1 : 0, grantedScope: input.grantedScope, @@ -98,8 +96,6 @@ export class AccountService { .values({ did, handle: resolved.handle, - displayName: null, - avatarUrl: null, pdsUrl: resolved.pds, spacesCapable: 0, grantedScope: null, diff --git a/apps/web/src/lib/server/services/epk-fields.ts b/apps/web/src/lib/server/services/epk-fields.ts index 74b66b917..1887d73a7 100644 --- a/apps/web/src/lib/server/services/epk-fields.ts +++ b/apps/web/src/lib/server/services/epk-fields.ts @@ -9,7 +9,13 @@ import { type EpkPhoto, type EpkRecord } from '#lib/epk.ts'; -import { type epkDraftSchema, epkFieldsSchema, type epkGrantSchema, type epkRequestSchema } from '#lib/epk-schema.ts'; +import { + type epkDecisionSchema, + type epkDraftSchema, + epkFieldsSchema, + type epkGrantSchema, + type epkRequestSchema +} from '#lib/epk-schema.ts'; import type { JsonObject } from '@atproto/lex-json'; import type { localnetwork } from '#lib/lexicons/computer.ts'; import type { LexiconRead } from '#lib/types.ts'; @@ -29,7 +35,8 @@ type PressKitRecord = | EpkContent | LexiconRead, localnetwork.epk.draft.Main> | LexiconRead, localnetwork.epk.grant.Main> - | LexiconRead, localnetwork.epk.request.Main>; + | LexiconRead, localnetwork.epk.request.Main> + | LexiconRead, localnetwork.epk.decision.Main>; const CONTENT = 'content.'; diff --git a/apps/web/src/lib/server/services/epk.test.ts b/apps/web/src/lib/server/services/epk.test.ts index b1ebb43b3..46ecdea2d 100644 --- a/apps/web/src/lib/server/services/epk.test.ts +++ b/apps/web/src/lib/server/services/epk.test.ts @@ -330,6 +330,34 @@ describe('EpkService', () => { ); }); + it("records every answer to a request as the root's decision in the request space, and an invite as none", async () => { + const kit = f.kit(await f.publish(DJ)); + const open = f.kit(await f.publish(DJ, { title: 'Open', access: preset('open') })); + await f.t.epks.request(await f.t.viewer(STRANGER), kit, {}); + await f.t.epks.request(await f.t.viewer(PROMOTER), kit, {}); + await f.t.epks.request(await f.t.viewer(NO_SPACES), open, {}); + const asked = await f.t.db.selectFrom('epkRequest').select(['uri', 'requesterDid']).execute(); + const uriOf = (did: string) => asked.find((request) => request.requesterDid === did)!.uri; + await f.t.epks.decide(await f.t.viewer(CODJ), kit, uriOf(STRANGER), 'decline'); + await f.t.epks.decide(await f.t.viewer(DJ), kit, uriOf(PROMOTER), 'approve'); + await f.t.epks.invite(await f.t.viewer(DJ), kit, FRIEND); + + const decisions = f.t.net + .spaceRecordsIn(requestSpace(), ROOT) + .filter((record) => record.uri.includes(COLLECTION.epkDecision)) + .map(({ value }) => value); + + expect(decisions).toHaveLength(3); + expect(decisions).toEqual( + expect.arrayContaining([ + expect.objectContaining({ request: uriOf(STRANGER), epk: kit.epk.uri, outcome: 'declined', decidedBy: CODJ }), + expect.objectContaining({ request: uriOf(PROMOTER), epk: kit.epk.uri, outcome: 'approved', decidedBy: DJ }), + // The press kit's rules approved it, so the root did. + expect.objectContaining({ request: uriOf(NO_SPACES), epk: open.epk.uri, outcome: 'approved', decidedBy: ROOT }) + ]) + ); + }); + it("writes the request for someone whose PDS can't, on their behalf", async () => { const kit = f.kit(await f.publish(DJ)); diff --git a/apps/web/src/lib/server/services/epk.ts b/apps/web/src/lib/server/services/epk.ts index 63d0f1746..1d3a0e6e8 100644 --- a/apps/web/src/lib/server/services/epk.ts +++ b/apps/web/src/lib/server/services/epk.ts @@ -1,6 +1,13 @@ import { TID } from '@atproto/common-web'; import type { z } from 'zod'; -import { epkContentSchema, epkGrantSchema, epkRecordSchema, epkRequestSchema, followSchema } from '#lib/epk-schema.ts'; +import { + epkContentSchema, + epkDecisionSchema, + epkGrantSchema, + epkRecordSchema, + epkRequestSchema, + followSchema +} from '#lib/epk-schema.ts'; import type { JsonObject } from '@atproto/lex-json'; import { type AccessRule, @@ -23,8 +30,9 @@ import { import { BSKY_FOLLOW, COLLECTION, EPK_CONTENT_KEY, SPACE_TYPE } from '#lib/nsid.ts'; import type { ProjectView, Viewer } from '#lib/types.ts'; import { RecordValidationError, validateRecord } from '../atproto/lexicons'; -import { memberSpacePolicy, type RepoClient, type StoredRecord } from '../atproto/repo-client'; +import { listAllSpaceRecords, memberSpacePolicy, type RepoClient, type StoredRecord } from '../atproto/repo-client'; import { + epkRequestSpace, epkSpace, parsePublicRecordUri, parseSpaceRecordUri, @@ -70,6 +78,8 @@ export type PressKit = { epk: EpkView; project: ProjectView }; /** A grant as its record holds it. */ export type GrantInput = { subject: string; via: 'auto' | 'approved' | 'invited'; request?: string; createdAt: string }; +type EpkDecision = z.infer; + const newestFirst = (a: EpkView, b: EpkView) => (b.record.updatedAt ?? b.record.createdAt).localeCompare(a.record.updatedAt ?? a.record.createdAt); @@ -97,12 +107,12 @@ function kitOfSpace(space: string): string { * rest in a space per press kit, whose readers are the project's managers and the people granted access. Requests to * see one, and the root's grant records, go into a space per project that only its managers read, so nobody asking or * let in sees anyone else's. Managers change a press kit through drafts ({@link EpkDrafts}), and any of them answers - * requests and grants access, which the root writes as a grant record plus a place in the press kit's space, so access - * is on the protocol, not in this app's database. Press kits made before the root held them stay in their maker's repo - * and space until that manager's next visit ({@link LegacyEpks}); until then they're listed and read as before, but - * only their maker can move them. Every press kit is read through HappyView (lua/computer/localnetwork/epk.lua), - * strictly where a write or an access decision depends on it, so a HappyView that's down fails those instead of - * reading as no press kit. + * requests and grants access, which the root writes as a decision record, and a grant record plus a place in the press + * kit's space, so answers and access are on the protocol, not in this app's database. Press kits made before the root + * held them stay in their maker's repo and space until that manager's next visit ({@link LegacyEpks}); until then + * they're listed and read as before, but only their maker can move them. Every press kit is read through HappyView + * (lua/computer/localnetwork/epk.lua), strictly where a write or an access decision depends on it, so a HappyView + * that's down fails those instead of reading as no press kit. */ export class EpkService { readonly drafts: EpkDrafts; @@ -314,8 +324,8 @@ export class EpkService { } /** - * Deletes a press kit: its space, which takes everyone's access with it, the requests the root wrote for people and - * its grants, then the public record. + * Deletes a press kit: its space, which takes everyone's access with it, the requests the root wrote for people, its + * decisions and grants, then the public record. */ async remove(actor: Viewer, kit: PressKit): Promise { await this.assertCanManage(actor, kit); @@ -324,7 +334,7 @@ export class EpkService { // The space goes first: a failure after it leaves the record, so deleting again finishes the job. if (await root.getSpace(epk.space)) await root.deleteSpace(epk.space); - await this.dropRecords(epk); + await this.dropRecords(kit); await root.deleteRecord({ collection: COLLECTION.epk, rkey: epk.rkey }); await this.indexed.awaitWrite(root.did, COLLECTION.epk, epk.rkey, null); await this.forgetIndex(epk.space); @@ -424,11 +434,7 @@ export class EpkService { return; } - await this.core.db - .updateTable('epkRequest') - .set({ status: 'declined', decidedAt: nowIso() }) - .where('uri', '=', row.uri) - .execute(); + await this.writeDecision(kit, row, 'declined', actor.did); await this.core.audit.record({ actor: actor.did, actorRole: actorRole(actor), @@ -599,6 +605,26 @@ export class EpkService { await this.saveGrant(space, subject, input.uri, via, request, createdAt); } + /** + * Indexes the root's decision synced from a project's request space, for one of that project's press kits. Only the + * root's count; the projection checks who wrote it. + */ + async indexDecision(input: { space: string; value: JsonObject }): Promise { + const decision = epkDecisionSchema.safeParse(input.value); + + if (!decision.success) { + this.core.logger.warn('ignoring a press kit decision this app does not read', { + space: input.space, + outcome: input.value.outcome + }); + + return; + } + + if (!(await this.requestedKit(input.space, decision.data.epk))) return; + await this.saveDecision(input.space, decision.data); + } + async unindexGrant(uri: string): Promise { await this.core.db.deleteFrom('epkGrant').where('uri', '=', uri).execute(); } @@ -771,7 +797,13 @@ export class EpkService { createdAt: row.createdAt, decidedAt: null }) - .onConflict((oc) => oc.column('uri').doNothing()) + // Only a row its decision made, before the request synced, takes what the request says. + .onConflict((oc) => + oc + .column('uri') + .doUpdateSet({ message: row.message, createdAt: row.createdAt, deletedAt: null }) + .where('epkRequest.deletedAt', 'is not', null) + ) .execute(); } @@ -818,6 +850,15 @@ export class EpkService { private async grant(kit: PressKit, grant: Omit, actor: Viewer | null): Promise { await this.writeGrant(kit.project, kit.epk, { ...grant, createdAt: nowIso() }); + + // Revoking deletes the grant, so the request's answer needs a record of its own. + if (grant.request) + await this.writeDecision( + kit, + { uri: grant.request, requesterDid: grant.subject }, + 'approved', + actor?.did ?? this.core.rootDid + ); await this.core.audit.record({ actor: actor?.did ?? this.core.rootDid, actorRole: actor ? actorRole(actor) : 'system', @@ -830,6 +871,58 @@ export class EpkService { }); } + /** Writes the root's record of a request's answer into the project's request space, and indexes it. */ + private async writeDecision( + kit: PressKit, + request: Pick, + outcome: EpkDecision['outcome'], + decidedBy: string + ): Promise { + const root = await this.core.root(); + const space = await this.ensureRequestSpace(kit.project); + + const decision: EpkDecision = { + request: request.uri, + requester: request.requesterDid, + epk: kit.epk.uri, + outcome, + decidedBy, + createdAt: nowIso() + }; + + await root.createSpaceRecord({ + space, + collection: COLLECTION.epkDecision, + record: validateRecord(COLLECTION.epkDecision, toJson(decision)) + }); + await this.saveDecision(space, decision); + } + + /** + * Sets a request's answer. A decision synced before its request, or one that outlived it, makes the row: marked + * deleted, as an answered request whose record is gone is, until the request syncs. So a re-sync keeps a decline, + * and with it the rule that the asker can't ask again, even when the asker deleted their request. + */ + private async saveDecision(space: string, decision: EpkDecision): Promise { + const answer = { status: decision.outcome, decidedAt: decision.createdAt }; + + await this.core.db + .insertInto('epkRequest') + .values({ + uri: decision.request, + spaceUri: space, + epkUri: decision.epk, + requesterDid: decision.requester, + message: null, + rule: 'none', + ...answer, + createdAt: decision.createdAt, + deletedAt: decision.createdAt + }) + .onConflict((oc) => oc.column('uri').doUpdateSet(answer)) + .execute(); + } + private async saveGrant( space: string, subject: string, @@ -890,11 +983,11 @@ export class EpkService { } /** - * Deletes the requests for `epk` the root wrote on people's behalf, and its grants. Each row goes with its record, so a - * delete that stopped part way picks up where it left off. Deleting a record that's gone, with the press kit's space - * or before, does nothing. + * Deletes the requests for the press kit the root wrote on people's behalf, its decisions and its grants. Each row + * goes with its record, and the decisions are read from the root's repo, so a delete that stopped part way picks up + * where it left off. Deleting a record that's gone, with the press kit's space or before, does nothing. */ - private async dropRecords(epk: EpkView): Promise { + private async dropRecords({ epk, project }: PressKit): Promise { const root = await this.core.root(); const { db } = this.core; const requests = await db.selectFrom('epkRequest').select('uri').where('epkUri', '=', epk.uri).execute(); @@ -911,6 +1004,14 @@ export class EpkService { await deleteAt(root, uri); await db.deleteFrom('epkGrant').where('uri', '=', uri).execute(); } + + const space = epkRequestSpace(root.did, project.rkey); + + if (!(await root.getSpace(space))) return; + const decisions = await listAllSpaceRecords(root, { space, repo: root.did, collection: COLLECTION.epkDecision }); + + for (const { rkey, value } of decisions) + if (value.epk === epk.uri) await root.deleteSpaceRecord({ space, collection: COLLECTION.epkDecision, rkey }); } private async assertCanManage(actor: Viewer, kit: PressKit): Promise { diff --git a/apps/web/src/lib/server/sync/projections.test.ts b/apps/web/src/lib/server/sync/projections.test.ts index b7fd7d414..2002fc67e 100644 --- a/apps/web/src/lib/server/sync/projections.test.ts +++ b/apps/web/src/lib/server/sync/projections.test.ts @@ -1,10 +1,17 @@ import type { JsonObject } from '@atproto/lex-json'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { COLLECTION } from '#lib/nsid.ts'; -import { backstageSpace, bookingSpace, epkRequestSpace, epkSpace, sharedSpace } from '../atproto/spaces'; +import { + backstageSpace, + bookingSpace, + epkRequestSpace, + epkSpace, + parseSpaceRecordUri, + sharedSpace +} from '../atproto/spaces'; import { grantKey } from '../services/epk'; import { createTestServices, ROOT } from '../testing/core'; -import { DJ, pressKitServices } from '../testing/press-kits'; +import { CODJ, DJ, FRIEND, NO_SPACES, pressKitServices, STRANGER } from '../testing/press-kits'; import { createProjections } from './projections'; import { flagsOff } from '#lib/testing/flags.ts'; @@ -277,6 +284,146 @@ describe('createProjections', () => { } }); + describe('press kit decisions', () => { + let f: Awaited>; + let kit: ReturnType; + let space: string; + let sync: ReturnType; + + beforeEach(async () => { + f = await pressKitServices(); + kit = f.kit(await f.publish(DJ)); + space = epkRequestSpace(ROOT, f.project.rkey); + sync = createProjections(f.t); + }); + afterEach(async () => { + await f.t.audit.idle(); + await f.t.db.destroy(); + }); + + /** `did` asks to see the press kit; returns their request's URI. */ + const ask = async (did: string) => { + await f.t.epks.request(await f.t.viewer(did), kit, {}); + const rows = await f.t.db.selectFrom('epkRequest').select('uri').where('requesterDid', '=', did).execute(); + + return rows[0].uri; + }; + + const answer = async (did: string, uri: string, outcome: 'approve' | 'decline') => + f.t.epks.decide(await f.t.viewer(did), kit, uri, outcome); + + const states = async () => + Object.fromEntries( + await Promise.all( + [STRANGER, NO_SPACES, FRIEND].map(async (did) => { + const state = await f.t.epks.accessState(kit, await f.t.viewer(did)); + + return [did, state.kind] as const; + }) + ) + ); + + /** + * What the access page shows of each answered request. A request whose record is gone comes back from its decision + * alone, which doesn't say when it was asked or what the rules said then. + */ + const answers = async () => + (await f.t.epks.requests(kit.epk)).map(({ uri, requester, status, decidedAt }) => ({ + uri, + requester: requester.did, + status, + decidedAt + })); + + /** Empties the press kit tables and syncs every record in the request space back in, decisions first or last. */ + const rebuild = async (decisions: 'first' | 'last') => { + await f.t.db.deleteFrom('epkRequest').execute(); + await f.t.db.deleteFrom('epkGrant').execute(); + const isDecision = (uri: string) => parseSpaceRecordUri(uri)?.collection === COLLECTION.epkDecision; + + const records = f.t.net + .spaceRecordsIn(space) + .toSorted((a, b) => Number(isDecision(b.uri)) - Number(isDecision(a.uri))); + + for (const { uri, cid, value } of decisions === 'first' ? records : records.toReversed()) { + const { author, collection, rkey } = parseSpaceRecordUri(uri)!; + await sync({ kind: 'upsert', space, repoDid: author, collection, rkey, uri, cid, value }); + } + }; + + const decision = (request: string, outcome: string) => ({ + request, + requester: STRANGER, + epk: kit.epk.uri, + outcome, + decidedBy: DJ, + createdAt: new Date().toISOString() + }); + + it.each(['first', 'last'] as const)( + 'keeps every answer when the request space syncs again, its decisions %s', + async (decisions) => { + await answer(CODJ, await ask(STRANGER), 'decline'); + // The root holds this one, and its asker deletes it after the decline. + const held = await ask(NO_SPACES); + await answer(DJ, held, 'decline'); + await f.t.heldRecords.delete(await f.t.viewer(NO_SPACES), held); + // Approved, then removed: the grant is gone, but the request was still answered. + await answer(DJ, await ask(FRIEND), 'approve'); + await f.t.epks.revoke(await f.t.viewer(DJ), kit, FRIEND); + const before = { states: await states(), answers: await answers() }; + + await rebuild(decisions); + + expect(before.states).toEqual({ [STRANGER]: 'declined', [NO_SPACES]: 'declined', [FRIEND]: 'canAsk' }); + expect(await states()).toEqual(before.states); + expect(before.answers.map(({ status }) => status)).toEqual(['declined', 'declined']); + expect(await answers()).toEqual(before.answers); + expect(await f.t.epks.waiting(f.project)).toEqual([]); + await expect(f.t.epks.request(await f.t.viewer(STRANGER), kit, {})).rejects.toThrow(/didn't share/); + await expect(f.t.epks.request(await f.t.viewer(NO_SPACES), kit, {})).rejects.toThrow(/didn't share/); + } + ); + + it('gives a request that syncs after its decision back what it says, and back to its asker', async () => { + const asker = await f.t.viewer(NO_SPACES); + await f.t.epks.request(asker, kit, { message: 'For a May date' }); + const [{ uri }] = await f.t.epks.requests(kit.epk); + await answer(DJ, uri, 'decline'); + + await rebuild('first'); + + expect(await f.t.epks.requests(kit.epk)).toMatchObject([{ uri, status: 'declined', message: 'For a May date' }]); + expect((await f.t.heldRecords.list(asker)).map((held) => held.uri)).toEqual([uri]); + }); + + it('takes a decision only from the root, in the request space', async () => { + const request = await ask(STRANGER); + + const upsertDecision = (inSpace: string, repoDid: string, value: JsonObject) => + sync({ + kind: 'upsert', + space: inSpace, + repoDid, + collection: COLLECTION.epkDecision, + rkey: '3dec', + uri: `${inSpace}/${repoDid}/${COLLECTION.epkDecision}/3dec`, + cid: 'bafyreiabc', + value: { $type: COLLECTION.epkDecision, ...value } + }); + + // The request space takes public writes, so anyone could write a decision into it. + await upsertDecision(space, STRANGER, decision(request, 'approved')); + await upsertDecision(space, DJ, decision(request, 'declined')); + await upsertDecision(kit.epk.space, ROOT, decision(request, 'declined')); + await upsertDecision(space, ROOT, decision(request, 'maybe')); + expect((await f.t.epks.accessState(kit, await f.t.viewer(STRANGER))).kind).toBe('pending'); + + await upsertDecision(space, ROOT, decision(request, 'declined')); + expect(await f.t.epks.accessState(kit, await f.t.viewer(STRANGER))).toEqual({ kind: 'declined' }); + }); + }); + it("indexes press kit drafts only from a backstage under the root, and drops them when they're deleted", async () => { const space = backstageSpace(ROOT, '3proj'); const now = new Date().toISOString(); diff --git a/apps/web/src/lib/server/sync/projections.ts b/apps/web/src/lib/server/sync/projections.ts index 42415e635..8b026376c 100644 --- a/apps/web/src/lib/server/sync/projections.ts +++ b/apps/web/src/lib/server/sync/projections.ts @@ -32,9 +32,10 @@ const SHARED_SPACE_COLLECTIONS = new Set([ /** * Maps records synced from spaces onto the local index. Records are checked * against our lexicons, and authority rules are enforced here: only the root - * account's decisions, roles, and details count, only the press kit grants - * of their space's authority, and in a performer's, party's or venue's space, - * only what the root wrote, in a space under the root. + * account's decisions (on moderation and press kit requests), roles, and + * details count, only the press kit grants of their space's authority, and in + * a performer's, party's or venue's space, only what the root wrote, in a + * space under the root. */ export function createProjections(deps: { core: Core; @@ -213,6 +214,11 @@ export function createProjections(deps: { // indexRequest checks the space: a project's request space, or a press kit's, where requests went before. await epks.indexRequest({ space: change.space, uri: change.uri, repoDid: change.repoDid, value }); + return; + case COLLECTION.epkDecision: + if (fromRoot && type === SPACE_TYPE.epkRequests && ref?.authority === rootDid) + await epks.indexDecision({ space: change.space, value }); + return; case COLLECTION.epkGrant: // indexGrant checks the space too: a project's request space, or a press kit's, where grants went before. diff --git a/lexicons/computer/localnetwork/epk/decision.json b/lexicons/computer/localnetwork/epk/decision.json new file mode 100644 index 000000000..e6aa7b838 --- /dev/null +++ b/lexicons/computer/localnetwork/epk/decision.json @@ -0,0 +1,35 @@ +{ + "lexicon": 1, + "id": "computer.localnetwork.epk.decision", + "defs": { + "main": { + "type": "record", + "key": "tid", + "description": "A manager's answer to a request to see the private part of a press kit. Written only by the Local Network root account, into the project's computer.localnetwork.space.epkRequests space beside the request. Someone declined can't ask to see that press kit again.", + "record": { + "type": "object", + "required": ["request", "requester", "epk", "outcome", "decidedBy", "createdAt"], + "properties": { + "request": { + "type": "string", + "format": "at-uri", + "description": "The computer.localnetwork.epk.request record." + }, + "requester": { "type": "string", "format": "did" }, + "epk": { + "type": "string", + "format": "at-uri", + "description": "The computer.localnetwork.epk record it asked to see." + }, + "outcome": { "type": "string", "maxLength": 32, "knownValues": ["approved", "declined"] }, + "decidedBy": { + "type": "string", + "format": "did", + "description": "The manager who answered, or the root account when the press kit's rules approved the request." + }, + "createdAt": { "type": "string", "format": "datetime" } + } + } + } + } +} diff --git a/lexicons/computer/localnetwork/space/epkRequests.json b/lexicons/computer/localnetwork/space/epkRequests.json index 13d6e42f2..e39a133e9 100644 --- a/lexicons/computer/localnetwork/space/epkRequests.json +++ b/lexicons/computer/localnetwork/space/epkRequests.json @@ -4,10 +4,14 @@ "defs": { "main": { "type": "space", - "description": "Requests to see a project's press kits, and the grants that answer them. Owned by the Local Network root account, one space per project, keyed by the project record's key. Anyone signed in can write a request into it, and only the root writes grants; only its members (the project's current managers) can read it, so the people asking, and those granted access, never see each other's requests or grants.", + "description": "Requests to see a project's press kits, and the decisions and grants that answer them. Owned by the Local Network root account, one space per project, keyed by the project record's key. Anyone signed in can write a request into it, and only the root writes decisions and grants; only its members (the project's current managers) can read it, so the people asking, and those granted access, never see each other's requests or grants.", "key": "tid", "title": "Local Network press kit requests", - "collections": ["computer.localnetwork.epk.request", "computer.localnetwork.epk.grant"] + "collections": [ + "computer.localnetwork.epk.request", + "computer.localnetwork.epk.decision", + "computer.localnetwork.epk.grant" + ] } } } From b1166c0e172298e5f868e7f67dce91795153d5ac Mon Sep 17 00:00:00 2001 From: botandbang <337765928+botandbang@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:58:14 -0600 Subject: [PATCH 05/22] feat(web): hide records from accounts that aren't active The website now asks an account's PDS (com.atproto.sync.getRepoStatus) whether it's active and keeps the answer for half an hour. Directory queries take a list of inactive accounts and leave out their sets, shows and listed profiles, so they leave Find DJs, the charts and artist pages, and come back on reactivation without a resync. Profile and set pages answer 404 saying the account isn't active, or 410 once it's deleted. HappyView already removes deleted and taken-down accounts' records, and a reinstated one is re-read. ADR 0020 records the choice. Fixes LOC-455 --- apps/web/README.md | 16 +- apps/web/docs/diagrams/mixes-and-sets.md | 16 +- .../localnetwork/directory/getArtist.lua | 1 + .../localnetwork/directory/getCharts.lua | 1 + .../localnetwork/directory/getSets.lua | 1 + .../localnetwork/directory/listShows.lua | 1 + .../localnetwork/directory/searchArtists.lua | 1 + .../directory/searchPerformers.lua | 12 +- apps/web/lua/happyview.yml | 3 + apps/web/lua/lib/directory.lua | 20 +- apps/web/src/app.d.ts | 2 + apps/web/src/lib/server/app.ts | 22 +- .../lib/server/atproto/account-status.test.ts | 227 ++++++++++++++++++ .../src/lib/server/atproto/account-status.ts | 215 +++++++++++++++++ apps/web/src/lib/server/core.ts | 3 + .../lib/server/happyview/directory.test.ts | 49 ++++ apps/web/src/lib/server/profile-page.ts | 16 +- .../lib/server/services/dj-listings.test.ts | 9 + .../src/lib/server/services/dj-listings.ts | 8 + .../lib/server/services/performers.test.ts | 23 ++ .../web/src/lib/server/services/performers.ts | 13 +- .../web/src/lib/server/services/recordings.ts | 11 +- apps/web/src/lib/server/services/sets.ts | 7 +- apps/web/src/lib/server/services/shows.ts | 3 +- .../src/lib/server/services/supports.test.ts | 6 +- apps/web/src/lib/server/services/supports.ts | 18 +- apps/web/src/lib/server/testing/core.ts | 19 +- apps/web/src/routes/+error.svelte | 9 +- .../src/routes/@[handle]/page.server.test.ts | 33 +++ .../routes/artists/[id]/page.server.test.ts | 2 +- .../artists/name/[[name]]/page.server.test.ts | 2 +- .../src/routes/artists/page.server.test.ts | 2 +- .../web/src/routes/charts/page.server.test.ts | 2 +- apps/web/src/routes/error.stories.svelte | 27 ++- .../integration/inactive-accounts.test.ts | 64 +++++ ...nactive-accounts-are-asked-of-their-pds.md | 17 ++ .../localnetwork/directory/getArtist.json | 6 + .../localnetwork/directory/getCharts.json | 6 + .../localnetwork/directory/getSets.json | 8 +- .../localnetwork/directory/listShows.json | 8 +- .../localnetwork/directory/searchArtists.json | 8 +- .../directory/searchPerformers.json | 8 +- 42 files changed, 865 insertions(+), 60 deletions(-) create mode 100644 apps/web/src/lib/server/atproto/account-status.test.ts create mode 100644 apps/web/src/lib/server/atproto/account-status.ts create mode 100644 apps/web/tests/integration/inactive-accounts.test.ts create mode 100644 docs/adr/0020-inactive-accounts-are-asked-of-their-pds.md diff --git a/apps/web/README.md b/apps/web/README.md index c0e059c01..d744c93d2 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -21,8 +21,8 @@ All data lives on the AT Protocol. Public profiles are ordinary atproto records; - People edit their profile at `/dashboard/profile`: the basics, and the DJ and promoter sections they turn on, each adding its own fields (the project form is built from the same basics and performer fields). Turning a section off asks first, since saving deletes what was in it. The profile goes to the account's own repo with its session, over the version the form opened on. A session from before profiles is offered "Sign in again" when the page opens. Someone without a profile makes one from the first step of the checklist on `/dashboard`, from their Bluesky name and picture, read once from their own repo. The sections decide the dashboard sidebar: a DJ's projects under Yours, and for a promoter a Promoter section with Book DJs (`/dashboard/promoter`: the Find DJs search, Match a show, the inquiries they sent and their planned shows) and the planner. Until there's a profile, the planner and List a project show anyway, and projects someone manages always do. Saving the profile with the promoter section newly on points to Book DJs. On a phone the sidebar's main items become tabs along the bottom, and Menu opens the rest in a sheet. - A DJ asks staff to list them in Find DJs from their profile editor, once their profile has the DJ section on: a `list` request in the moderation space that names their profile and the version they asked with. Staff review it at `/admin/requests` like any other, seeing the profile as it is now, with a note when it changed since the request and when the same account manages a solo project, which would put them in Find DJs twice. Approving writes the root's `computer.localnetwork.listing.profile` for them and has HappyView read their profile again; `/admin/listings/` (staff's Manage link on a profile) shows the listing and takes them out again. Both are audited. - Public pages only read, apart from Follow and Save. A project's managers get a Manage link to its dashboard there, and staff one to the staff console. A project that isn't public shows its managers and staff a "Not public yet" banner; everyone else gets a 404. -- Every account has a profile page at `/@`, showing its `computer.localnetwork.profile`: its basics (with the pronouns from its Bluesky profile, else the ones the profile kept from before), the performer and promoter sections it turned on, the DJ stats and sets it publishes, and the active projects it manages. A DID with a verified handle, and a handle in any other form, redirect there; an account without a verified handle has its page at `/@`. Its sections are tabs (About, Mixes, Sets, How they play, Plays in), each a file in `src/lib/profile-tabs/` that the page collects, so a new tab is a new file; a tab with nothing in it is left out, and `?tab=` opens one, without scripts too. An account without a profile record still gets a page, with its Bluesky display name when the directory keeps one (else its handle), the projects it plays in, and a line saying it hasn't set up a profile; only an address that names no account is a 404. Handles across the site link to these pages. A profile with a record has a Follow button for everyone but its owner. The owner gets a Manage link to their profile editor, and staff one to its Find DJs listing (`/admin/listings/`). A DJ Find DJs lists gets Send inquiry there, for everyone but themself, as an act's page has (Sign in to book when signed out). -- Each published set has a page at `/@/sets/`, redirected the same way: its place and date, the event it names (when HappyView keeps that event), its player and tracklist, and the mixes on its DJ's active projects that link it, each to its tracklist page when it has one. A mix's "Set:" line links there, and so does each set's name wherever sets are listed and each play on an artist's page. A set HappyView doesn't have is a 404. +- Every account has a profile page at `/@`, showing its `computer.localnetwork.profile`: its basics (with the pronouns from its Bluesky profile, else the ones the profile kept from before), the performer and promoter sections it turned on, the DJ stats and sets it publishes, and the active projects it manages. A DID with a verified handle, and a handle in any other form, redirect there; an account without a verified handle has its page at `/@`. Its sections are tabs (About, Mixes, Sets, How they play, Plays in), each a file in `src/lib/profile-tabs/` that the page collects, so a new tab is a new file; a tab with nothing in it is left out, and `?tab=` opens one, without scripts too. An account without a profile record still gets a page, with its Bluesky display name when the directory keeps one (else its handle), the projects it plays in, and a line saying it hasn't set up a profile. An address that names no account is a 404. So is an account that's deactivated, taken down or suspended, whose page says only that the account isn't active, and a deleted account's page is a 410 saying it was deleted ([ADR 0020](../../docs/adr/0020-inactive-accounts-are-asked-of-their-pds.md)). Handles across the site link to these pages. A profile with a record has a Follow button for everyone but its owner. The owner gets a Manage link to their profile editor, and staff one to its Find DJs listing (`/admin/listings/`). A DJ Find DJs lists gets Send inquiry there, for everyone but themself, as an act's page has (Sign in to book when signed out). +- Each published set has a page at `/@/sets/`, redirected the same way: its place and date, the event it names (when HappyView keeps that event), its player and tracklist, and the mixes on its DJ's active projects that link it, each to its tracklist page when it has one. A mix's "Set:" line links there, and so does each set's name wherever sets are listed and each play on an artist's page. A set HappyView doesn't have is a 404, and so is every set of an account that isn't active. ### Promoters @@ -241,6 +241,7 @@ Published projects, the DJ stats, sets, press kits, shows, calendar events, foll - `searchProjects`, `matchProjects`, `getProject`, `getProjects`, and `getStats` do the search, ranking, and lookups. `searchPerformers` searches active projects and listed DJs together: a DJ counts when the root lists them and their profile has the performer section on, as a solo act, by the genres their DJ stats say they play most when the section names none. Both searches share their filters and ranking (`lua/lib/directory.lua`). Match results carry reason codes, which the app turns into text. `getProject` with `counts` also counts the project's press kits and upcoming shows, so the project's pages hold that much room for them while they stream in. `getSets` and `listSets` look up sets by URI and by account, without their tracks. - `getRecords` (up to 25 URIs) and `listRecords` (one account's records of one collection, last record key first, with a cursor) read any record HappyView keeps, as its record script stored it, the way `com.atproto.repo.getRecord` and `listRecords` read a PDS. For calendar events, the bug report space and DJ stats, a record HappyView lacks is read from the account's own PDS instead (`lua/lib/pds.lua`, through the `happyview-http` library plugin), without being stored or gated, so those don't wait for a backfill. The app's `IndexedRepo` (`src/lib/server/happyview/indexed.ts`) wraps them for the DJ stats and sets on project pages, press kits and their managers' follows, shows and their calendar events, verifications and display names, and the bug report space. A HappyView that's down reads as nothing for pages that list them, and fails a read that a change or an access decision depends on (opening one press kit, counting a project's press kits, moving legacy ones, syncing their spaces' members, a press kit's "people you follow" rule, editing a show, verifying, posting a bug report). A press kit draft and a show edit save only over the versions their form was opened on, and publishing a press kit or re-issuing a verification swaps on the version HappyView serves, so none overwrites a change the person hasn't seen: they're asked to reload. - `getCharts`, `getArtist`, and `searchArtists` count supports. They group every stored play by track and artist in SQL on each request (about a third of a second for 2,000 sets of 25 tracks on a laptop, measured on SQLite), so no counts are kept anywhere; the app reuses an answer for a minute, and the pages may be cached for as long. +- HappyView also follows Jetstream's account events. It removes the records of an account that's deleted, taken down or suspended, but keeps a deactivated account's, and a taken-down account's records come back only with a re-read. So the app asks an account's PDS whether it's active (`com.atproto.sync.getRepoStatus`) and keeps each answer in memory for half an hour (`src/lib/server/atproto/account-status.ts`, [ADR 0020](../../docs/adr/0020-inactive-accounts-are-asked-of-their-pds.md)). `searchPerformers`, `getCharts`, `getArtist`, `searchArtists`, `getSets` and `listShows` take an `inactive` list of DIDs and leave out those accounts' sets, shows and listed profiles, along with a solo project that gives way to such a profile. The app sends the inactive ones among the managers and listed DJs, checked eight at a time in the background once the list is half an hour old, so pages never wait on it. A PDS that can't be asked leaves the account as last seen, or active. When a taken-down or suspended account is active again, the app has HappyView re-read its records. - The genre taxonomy and fee tiers are generated into the scripts from `src/lib/taxonomy/`, so TypeScript stays the source of truth. With `HAPPYVIEW_API_KEY` set, the app uploads whichever of its scripts and lexicons changed when it boots (scripts first, so the record gate is in place before ingestion starts), has HappyView track the other authorities' lexicons it needs that it doesn't yet (`POST /admin/network-lexicons`, which resolves them from the network and replaces a copy uploaded by hand), then has HappyView re-read the root's repo and waits for that to finish, and then every manager's shows in one batch. After publishing a project, a show, a follow, an RSVP, or a press kit it waits (up to 5 seconds) for HappyView to index it, so the next page shows it; when a show or its calendar event, a follow, an RSVP, or a press kit doesn't show up in time, HappyView re-reads that collection from that one account's repo. The directory queries are lexicons too, so `pnpm lexicons:publish` publishes a new one with the rest (see [Deploying](#deploying)). @@ -251,6 +252,7 @@ The app reads public records only from HappyView, never straight from a PDS (`co - Blobs in public repos: project images and profile avatars (`/media//`), tracklists and recordings (`/media/audio//`), with `com.atproto.sync.getBlob`, until HappyView serves blobs. Another account's avatar is served only when it's the one its indexed profile names, through the guarded fetch below. - The root's own projects when deciding who's in a booking thread (opening one, and the hourly manager sync), since a directory that's behind could let a removed manager back in. - DID and handle resolution, OAuth, and the root's session. +- Whether an account is active (`com.atproto.sync.getRepoStatus` on its PDS), which HappyView doesn't serve (see above). - HappyView's own re-reads of a repo (`/admin/backfill`, see above), which it makes from the account's PDS. - Tooling: the integration tests, the dev network, and `pnpm lexicons:publish`. @@ -431,7 +433,7 @@ The services are in [`src/lib/server/token-exchange/services.json`](src/lib/serv - OAuth uses DPoP-bound tokens and granular scopes: a permission set ([`permissions.json`](../../lexicons/computer/localnetwork/permissions.json), requested as `include:computer.localnetwork.permissions`) with write-only access to the user's own repos in the audit, moderation, booking, backstage, press kit request, and performer spaces and a self-authority planner space, and to the profile, shows and follows in their public repo and updates to their sets (plus deleting press kits made before the root held them, as they move), plus blob uploads limited to PNG, JPEG, and WebP avatars and JSON tracklists, and calendar events and RSVPs (`repo:community.lexicon.calendar.event` and `.rsvp`, asked for on their own since a permission set can only grant its own namespace). The PDS grants the set as the scopes it lists. The shared spaces it grants writes to are the root's only: `did:web:root.invalid` in the file stands for the root, and each network's root publishes the set with its own DID there (`pnpm lexicons:publish` for production; the dev network and the integration tests publish their own). Accounts without spaces support are asked for `atproto` plus the profile, show, follow, calendar event and RSVP writes and the blob uploads, and fall back to plain `atproto` if their PDS refuses those; they, and anyone who approves only part of the request, have the root account write their space records on their behalf. Sessions granted before the app asked for a new space or blob scope are sent back through sign-in on their next page load. Profile, show, follow, calendar event and RSVP writes, set updates, and drafts in a performer's space are asked for when they're needed instead, with a one-click "Sign in again"; a PDS that still won't grant them after that gets a plain "your account's server doesn't allow this yet". Posting bug reports to userinput.app is asked for separately, when someone first sends one, and only allows creating `app.userinput.discussion` records. Nothing lets the app read other users' data with a user's session; shared spaces are read with credentials issued to the root authority. - Browser sessions are opaque random tokens stored as SHA-256 hashes; cookies are `HttpOnly`, `SameSite=Lax`, and `Secure` on HTTPS, except `ln_signed_out`, which holds only the DIDs whose drafts to drop and is read by the page's scripts. - CSP with per-request nonces, `frame-ancestors 'none'`, `nosniff`, strict referrer policy, HSTS on HTTPS, and SvelteKit's CSRF origin checks. -- Every request to a host from a DID document goes through `@atproto-labs/fetch-node`'s safe fetch in production: no redirects, HTTPS only, and no private or loopback address, checked as it connects so DNS can't swap the address after. Resolving a DID or handle and fetching another account's avatar use the default port only, with responses up to 2 MB. Space credential calls, space sync, blob downloads and streamed recordings from a PDS, and everything the OAuth client sends (identity lookups, PDS and authorization server metadata, authorization and token requests, session requests) allow any port and have no size or time cap of their own, since callers bound what they read and how long they wait. The OAuth client sets no time limit on session requests, so the app gives each of its requests 30 seconds. The OAuth client leaves its requests to follow redirects, so the app makes them refuse redirects instead. ast-grep's [`no-unguarded-fetch`](../../tools/ast-grep/rules/no-unguarded-fetch.yml) rule fails a plain or passed-in `fetch` in any function that reads such a host. did:web hosts and handles that are IP addresses, carry a port, or use `localhost` or a reserved TLD are refused before any request, and `/@` lookups that find no account are rate-limited per IP. +- Every request to a host from a DID document goes through `@atproto-labs/fetch-node`'s safe fetch in production: no redirects, HTTPS only, and no private or loopback address, checked as it connects so DNS can't swap the address after. Resolving a DID or handle and fetching another account's avatar use the default port only, with responses up to 2 MB. Space credential calls, space sync, account status checks, blob downloads and streamed recordings from a PDS, and everything the OAuth client sends (identity lookups, PDS and authorization server metadata, authorization and token requests, session requests) allow any port and have no size or time cap of their own, since callers bound what they read and how long they wait. The OAuth client sets no time limit on session requests, so the app gives each of its requests 30 seconds. The OAuth client leaves its requests to follow redirects, so the app makes them refuse redirects instead. ast-grep's [`no-unguarded-fetch`](../../tools/ast-grep/rules/no-unguarded-fetch.yml) rule fails a plain or passed-in `fetch` in any function that reads such a host. did:web hosts and handles that are IP addresses, carry a port, or use `localhost` or a reserved TLD are refused before any request, and `/@` lookups that find no account are rate-limited per IP. - Links people wrote into their own records (profiles, sets, press kits, shows, requests) are only made clickable when they're http(s) addresses (`src/lib/web-url.ts`). - Uploaded images are type- and magic-byte-checked and capped at 1 MB for avatars and 5 MB for press kit photos. Stored images are served only if their blob's type is one their lexicon accepts (PNG, JPEG or WebP), since a PDS doesn't check, with a sandboxing CSP and `nosniff`. - `/media/audio//` streams only a blob that an indexed `computer.localnetwork.dj.recording` of an active project's manager references, as the type and size that record declares, with Range answered by the app since `getBlob` ignores it. The type and size limits are the lexicon's own (`audio/*` or `video/mp4`, at most 300 MiB); `video/mp4` is what a PDS calls an M4A it can't tell is audio, so it goes out as `audio/mp4`. It stores nothing, and sends a locked-down CSP and `nosniff`. The page CSP allows media only from the site, plyr.fm's CDN and archive.org's download hosts, images only from the site and Bluesky's avatar CDN (for sign-in's account suggestions), and scripts only from SoundCloud's and Mixcloud's widget hosts besides its own. @@ -478,7 +480,7 @@ tests/e2e/ Playwright - Oxfmt doesn't format `.svelte` files yet; it formats everything else. - The spaces alpha has no relay: sync load falls on PDSes, mitigated by notifications and incremental oplog sync. -- Account deactivation/deletion events arrive on the firehose, which this app doesn't subscribe to yet. +- The app doesn't follow account events itself. It asks an account's PDS whether it's active and keeps the answer for half an hour, so a deactivated account leaves Find DJs, the charts and listings, and comes back, up to half an hour late. A taken-down or suspended account's records come back only if this server saw it go and come back, since HappyView drops them and the app has them re-read only then. - The directory scripts' SQL is written for Postgres, so the HappyView instance must use Postgres, not SQLite. - HappyView drops a Jetstream cursor older than 72 hours. The boot backfill recovers new and changed projects after a longer outage, but not deletions (nothing deletes projects today). @@ -522,7 +524,7 @@ flowchart TD App -- "daily backup" --> Bucket App -- "queries, scripts,
re-reads" --> HV App -- "root session" --> Root - App -- "OAuth sessions,
space sync" --> Pds + App -- "OAuth sessions, space sync,
account status" --> Pds Root -- "notifySpaceUpdate" --> App Root --> Jet Pds --> Jet @@ -559,7 +561,7 @@ What the server calls, and why. flowchart LR App["Local Network app"] App -- "DIDs and handles" --> Identity["PLC directory, did:web hosts,
handle resolution"] - App -- "OAuth, writes, blobs, space sync" --> Pds["PDSes"] + App -- "OAuth, writes, blobs, space sync,
account status" --> Pds["PDSes"] App -- "directory" --> HV["HappyView"] App -- "sign-in suggestions" --> Bsky["public.api.bsky.app"] App -- "city search" --> Geo["Open-Meteo or Nominatim"] @@ -570,7 +572,7 @@ flowchart LR App -- "backups" --> S3["S3 bucket"] ``` -Source: [`src/lib/server/atproto/identity.ts`](src/lib/server/atproto/identity.ts), [`src/lib/server/actor-search.ts`](src/lib/server/actor-search.ts), [`src/lib/server/geocode.ts`](src/lib/server/geocode.ts), [`src/lib/server/plyr.ts`](src/lib/server/plyr.ts), [`src/lib/server/notifications/email.ts`](src/lib/server/notifications/email.ts), [`src/lib/server/notifications/dm.ts`](src/lib/server/notifications/dm.ts), [`src/lib/server/token-exchange/services.json`](src/lib/server/token-exchange/services.json), [`src/lib/server/backup/store.ts`](src/lib/server/backup/store.ts) +Source: [`src/lib/server/atproto/identity.ts`](src/lib/server/atproto/identity.ts), [`src/lib/server/atproto/account-status.ts`](src/lib/server/atproto/account-status.ts), [`src/lib/server/actor-search.ts`](src/lib/server/actor-search.ts), [`src/lib/server/geocode.ts`](src/lib/server/geocode.ts), [`src/lib/server/plyr.ts`](src/lib/server/plyr.ts), [`src/lib/server/notifications/email.ts`](src/lib/server/notifications/email.ts), [`src/lib/server/notifications/dm.ts`](src/lib/server/notifications/dm.ts), [`src/lib/server/token-exchange/services.json`](src/lib/server/token-exchange/services.json), [`src/lib/server/backup/store.ts`](src/lib/server/backup/store.ts) ### What the browser reaches diff --git a/apps/web/docs/diagrams/mixes-and-sets.md b/apps/web/docs/diagrams/mixes-and-sets.md index 3d6422c3c..e4450dab3 100644 --- a/apps/web/docs/diagrams/mixes-and-sets.md +++ b/apps/web/docs/diagrams/mixes-and-sets.md @@ -82,7 +82,7 @@ flowchart TD HV --> Set Set --> Recording{"Its recording?"} Recording -- "fm.plyr.track" --> Plyr["api.plyr.fm: file on audio.plyr.fm,
or plyr's player if it's gated"] - Recording -- "dj.recording by an
active performer's manager" --> Stream["/media/audio/[did]/[cid]"] + Recording -- "dj.recording by an active account
managing an active performer" --> Stream["/media/audio/[did]/[cid]"] Recording -- "none, it won't resolve, or a dj.recording
while pauseRecordingStream is on" --> Links["Its links: archive.org plays directly,
others in their own players"] Stream --> Blob["getBlob from the DJ's PDS,
Range answered by the app, nothing stored"] ``` @@ -98,7 +98,10 @@ flowchart TD Visit["/@[handle]/sets/[rkey]"] --> Account{"Names an account?"} Account -- "no" --> Miss["404, counted against
the visitor's lookups"] Account -- "a DID, or another spelling
of the handle" --> Redirect["302 to /@[handle]/sets/[rkey]"] - Account -- "yes" --> Set["recordings.set: the dj.set from HappyView"] + Account -- "yes" --> Active{"Account active?
getRepoStatus, kept 30 minutes"} + Active -- "deactivated, taken
down or suspended" --> Inactive["404: the account isn't active"] + Active -- "deleted" --> Deleted["410: the account was deleted"] + Active -- "yes" --> Set["recordings.set: the dj.set from HappyView"] Set -- "none, or it won't parse" --> Gone["404"] Set --> Render["Rendered: name, date, place,
player and tracklist"] Render -.-> Event["Streamed: the event's name,
when HappyView keeps that event"] @@ -106,15 +109,16 @@ flowchart TD Mixes --> Report["Each links its tracklist page,
else its listen link"] ``` -Source: [`src/routes/@[handle]/sets/[rkey]/+page.server.ts`](../../src/routes/@[handle]/sets/[rkey]/+page.server.ts), [`src/lib/server/profile-page.ts`](../../src/lib/server/profile-page.ts), [`src/lib/server/services/recordings.ts`](../../src/lib/server/services/recordings.ts), [`src/lib/server/services/shows.ts`](../../src/lib/server/services/shows.ts) +Source: [`src/routes/@[handle]/sets/[rkey]/+page.server.ts`](../../src/routes/@[handle]/sets/[rkey]/+page.server.ts), [`src/lib/server/profile-page.ts`](../../src/lib/server/profile-page.ts), [`src/lib/server/atproto/account-status.ts`](../../src/lib/server/atproto/account-status.ts), [`src/lib/server/services/recordings.ts`](../../src/lib/server/services/recordings.ts), [`src/lib/server/services/shows.ts`](../../src/lib/server/services/shows.ts) ## Charts and artist pages -Support counts come straight from the sets HappyView keeps, and nothing stores them. A listed DJ who manages no active performer doesn't count. With HappyView down, the pages say so. +Support counts come straight from the sets HappyView keeps, and nothing stores them. A listed DJ who manages no active performer doesn't count, and neither does a DJ whose account isn't active. With HappyView down, the pages say so. ```mermaid flowchart TD - Sets["dj.set records of active performers' managers,
each named track kept by the gate"] --> Sql["Lua queries group plays in SQL"] + Sets["dj.set records of active performers' managers,
each named track kept by the gate"] --> Sql + Inactive["The app's list of inactive accounts"] -- "inactive param" --> Sql["Lua queries group plays in SQL"] Sql --> Charts["getCharts"] Sql --> Artist["getArtist"] Sql --> Search["searchArtists"] @@ -126,4 +130,4 @@ flowchart TD Memo --> P3["/artists"] ``` -Source: [`src/lib/server/services/supports.ts`](../../src/lib/server/services/supports.ts), [`src/routes/charts/+page.server.ts`](../../src/routes/charts/+page.server.ts), [`lua/computer/localnetwork/directory/getCharts.lua`](../../lua/computer/localnetwork/directory/getCharts.lua), [`lua/computer/localnetwork/directory/getArtist.lua`](../../lua/computer/localnetwork/directory/getArtist.lua) +Source: [`src/lib/server/services/supports.ts`](../../src/lib/server/services/supports.ts), [`src/lib/server/atproto/account-status.ts`](../../src/lib/server/atproto/account-status.ts), [`src/routes/charts/+page.server.ts`](../../src/routes/charts/+page.server.ts), [`lua/computer/localnetwork/directory/getCharts.lua`](../../lua/computer/localnetwork/directory/getCharts.lua), [`lua/computer/localnetwork/directory/getArtist.lua`](../../lua/computer/localnetwork/directory/getArtist.lua) diff --git a/apps/web/lua/computer/localnetwork/directory/getArtist.lua b/apps/web/lua/computer/localnetwork/directory/getArtist.lua index 8b55d7e6c..be341dfa9 100644 --- a/apps/web/lua/computer/localnetwork/directory/getArtist.lua +++ b/apps/web/lua/computer/localnetwork/directory/getArtist.lua @@ -33,6 +33,7 @@ local function managed(dids) end function handle(input) + skipInactive(input) local id = text(input.mbid) and mbid(input.mbid) local wanted = text(input.name) if not (id or wanted and not input.mbid) then return { tracks = json.to_array({}), djs = json.to_array({}) } end diff --git a/apps/web/lua/computer/localnetwork/directory/getCharts.lua b/apps/web/lua/computer/localnetwork/directory/getCharts.lua index ad0b2ab06..e3e37f974 100644 --- a/apps/web/lua/computer/localnetwork/directory/getCharts.lua +++ b/apps/web/lua/computer/localnetwork/directory/getCharts.lua @@ -10,6 +10,7 @@ local function day(value) end function handle(input) + skipInactive(input) local where, args = '', {} local since, before = day(input.since), day(input.before) local city, country = text(input.city), text(input.country) diff --git a/apps/web/lua/computer/localnetwork/directory/getSets.lua b/apps/web/lua/computer/localnetwork/directory/getSets.lua index 54188dfb0..884fc5cef 100644 --- a/apps/web/lua/computer/localnetwork/directory/getSets.lua +++ b/apps/web/lua/computer/localnetwork/directory/getSets.lua @@ -3,6 +3,7 @@ local json = require('internal.json') function handle(input) + skipInactive(input) local uris = input.uris local where, values = atUris(uris, 's.') local byUri = {} diff --git a/apps/web/lua/computer/localnetwork/directory/listShows.lua b/apps/web/lua/computer/localnetwork/directory/listShows.lua index 00ffc1c6d..68ea4d8b5 100644 --- a/apps/web/lua/computer/localnetwork/directory/listShows.lua +++ b/apps/web/lua/computer/localnetwork/directory/listShows.lua @@ -6,6 +6,7 @@ local json = require('internal.json') local SOONEST = ' ORDER BY (s.record::jsonb ->> \'startsAt\')::timestamptz, s.uri COLLATE "C"' function handle(input) + skipInactive(input) local where, args = { UPCOMING }, {} local function filter(clause, values) where[#where + 1] = ' AND ' .. clause diff --git a/apps/web/lua/computer/localnetwork/directory/searchArtists.lua b/apps/web/lua/computer/localnetwork/directory/searchArtists.lua index f304d7660..ea2cd3966 100644 --- a/apps/web/lua/computer/localnetwork/directory/searchArtists.lua +++ b/apps/web/lua/computer/localnetwork/directory/searchArtists.lua @@ -3,6 +3,7 @@ local json = require('internal.json') function handle(input) + skipInactive(input) local q = text(input.q) local limit = pageSize(input.limit, 25, 50) local where, args = '', { limit } diff --git a/apps/web/lua/computer/localnetwork/directory/searchPerformers.lua b/apps/web/lua/computer/localnetwork/directory/searchPerformers.lua index 3dc582e30..b73a02098 100644 --- a/apps/web/lua/computer/localnetwork/directory/searchPerformers.lua +++ b/apps/web/lua/computer/localnetwork/directory/searchPerformers.lua @@ -80,6 +80,7 @@ local function before(a, b, sort) end function handle(input) + skipInactive(input) local projectWhere, projectArgs = { " AND record::jsonb ->> 'status' = 'active'" }, {} local profileWhere, profileArgs = {}, {} local function filter(where, args, clause, values) @@ -121,6 +122,11 @@ function handle(input) djs ) end + -- An inactive DJ's profile is left out, and their solo project still gives way to it, so neither shows. + local shown = {} + for _, did in ipairs(djs) do + if not inactive[did] then shown[#shown + 1] = did end + end if #tiers > 0 then project(inFeeTiers('record', 'profile,fees', tiers, 'profile,fee')) profile(inFeeTiers('p.record', 'performer,fees', tiers)) @@ -164,14 +170,14 @@ function handle(input) end local fromProfiles = {} - if #djs > 0 then + if #shown > 0 then local rows = query( PROFILES - .. marks(#djs) + .. marks(#shown) .. ')' .. table.concat(profileWhere) .. (order == 'name' and PROFILES_BY_NAME or PROFILES_RECENT), - append(append({ ROOT_DID, LISTING, DJ_PROFILE, PROFILE }, djs), profileArgs) + append(append({ ROOT_DID, LISTING, DJ_PROFILE, PROFILE }, shown), profileArgs) ) for _, row in ipairs(rows) do local record = json.decode(row.record) diff --git a/apps/web/lua/happyview.yml b/apps/web/lua/happyview.yml index dc2cf9179..f41b7fa9a 100644 --- a/apps/web/lua/happyview.yml +++ b/apps/web/lua/happyview.yml @@ -137,6 +137,8 @@ globals: property: read-only MIN_DJS_TO_CHART: property: read-only + inactive: + property: read-only fetchThrough: &helper args: - type: '...' @@ -147,6 +149,7 @@ globals: query: *helper append: *helper managers: *helper + skipInactive: *helper number: *helper text: *helper integer: *helper diff --git a/apps/web/lua/lib/directory.lua b/apps/web/lua/lib/directory.lua index e5ecf0a6f..55dc26d56 100644 --- a/apps/web/lua/lib/directory.lua +++ b/apps/web/lua/lib/directory.lua @@ -180,8 +180,20 @@ local function projects(where, args, order) return rows end --- The accounts that manage one of the root's projects (an active one, with `active`), each once: the accounts whose --- records the directory reads beyond the root's own. +-- The accounts the app found inactive (deactivated, taken down, suspended or deleted), as a set. HappyView keeps a +-- deactivated account's records, so the queries that read accounts' records take an `inactive` param and leave theirs +-- out. Each request runs in a fresh VM, so this starts empty every time. +local inactive = {} + +-- Reads a query's `inactive` param into `inactive`. Call it first in handle(). +local function skipInactive(input) + for _, did in ipairs(input.inactive or {}) do + inactive[did] = true + end +end + +-- The accounts that manage one of the root's projects (an active one, with `active`), each once, without inactive +-- ones: the accounts whose records the directory reads beyond the root's own. local function managers(active) local rows = query( "SELECT DISTINCT m AS did FROM happyview_records, jsonb_array_elements_text(record::jsonb -> 'managers') AS m" @@ -191,8 +203,8 @@ local function managers(active) { ROOT_DID, PROJECT } ) local out = {} - for i, row in ipairs(rows) do - out[i] = row.did + for _, row in ipairs(rows) do + if not inactive[row.did] then out[#out + 1] = row.did end end return out end diff --git a/apps/web/src/app.d.ts b/apps/web/src/app.d.ts index 5dc314dc5..43f820e2a 100644 --- a/apps/web/src/app.d.ts +++ b/apps/web/src/app.d.ts @@ -10,6 +10,8 @@ declare global { status: number; message: string; requestId?: string; + /** The error page's heading, when the status alone doesn't say what happened. */ + title?: string; } interface Locals { diff --git a/apps/web/src/lib/server/app.ts b/apps/web/src/lib/server/app.ts index 6a3f66fd6..5f1ae889f 100644 --- a/apps/web/src/lib/server/app.ts +++ b/apps/web/src/lib/server/app.ts @@ -1,6 +1,7 @@ import type { SpaceKind } from '#lib/capabilities.ts'; import type { NotificationChannel, Viewer } from '#lib/types.ts'; import { ActorSearch } from './actor-search'; +import { AccountStatuses, repoStatusLookup } from './atproto/account-status'; import { SpaceCredentialManager } from './atproto/credentials'; import { IdentityResolver } from './atproto/identity'; import { grantsSpaces, OAuthService } from './atproto/oauth'; @@ -19,7 +20,7 @@ import { Backfills } from './happyview/backfills'; import { happyViewBundle } from './happyview/bundle'; import { HappyViewClient } from './happyview/client'; import { INDEX_WAIT_MS, IndexedRepo } from './happyview/indexed'; -import { refreshForScript, refreshTargets } from './happyview/refresh'; +import { MANAGER_COLLECTIONS, refreshForScript, refreshTargets } from './happyview/refresh'; import { syncHappyView } from './happyview/sync'; import { createLogger, type Logger } from './logger'; import { NotificationChannels } from './notifications/channels'; @@ -185,6 +186,17 @@ export async function createApp(options: CreateAppOptions) { notify: (space) => syncer.registration(space) }); + // Services built after `core` list the directory's accounts, and only from their methods. + const accountStatuses = new AccountStatuses({ + lookup: repoStatusLookup(identity), + accounts: async () => [...(await projects.managers()), ...(await djListings.listed())], + logger: logger.child({ component: 'account-status' }), + // HappyView drops a taken-down account's records, so a reinstated one's are read again. + reinstated: (did) => { + for (const collection of MANAGER_COLLECTIONS) void backfills.backfill(collection, [did]); + } + }); + const core: Core = { db, logger, @@ -195,6 +207,7 @@ export async function createApp(options: CreateAppOptions) { userClient, audit, accounts, + accountStatuses, notify: notifications.notify.bind(notifications), // Services only call this from their methods, which run after `syncer` below exists. watchSpace: async (space) => { @@ -263,11 +276,13 @@ export async function createApp(options: CreateAppOptions) { const recordings = new RecordingService( indexedRepo, plyr, - async (did) => (await projects.managedBy(did)).some((project) => project.status === 'active'), + async (did) => + (await accountStatuses.status(did)) === 'active' && + (await projects.managedBy(did)).some((project) => project.status === 'active'), logger.child({ component: 'recordings' }) ); - const supports = new SupportService(happyView, accounts, logger.child({ component: 'supports' })); + const supports = new SupportService(happyView, core, logger.child({ component: 'supports' })); const epks = new EpkService(core, projects, indexedRepo, (identifier) => identity.resolveIdentifier(identifier)); @@ -429,6 +444,7 @@ export async function createApp(options: CreateAppOptions) { backfills, audit, accounts, + accountStatuses, notifications, notificationChannels, outbox, diff --git a/apps/web/src/lib/server/atproto/account-status.test.ts b/apps/web/src/lib/server/atproto/account-status.test.ts new file mode 100644 index 000000000..20d29e73c --- /dev/null +++ b/apps/web/src/lib/server/atproto/account-status.test.ts @@ -0,0 +1,227 @@ +import { describe, expect, it } from 'vitest'; +import { silentLogger } from '../logger'; +import { type AccountStatus, AccountStatuses, repoStatusLookup } from './account-status'; +import type { ResolvedIdentity } from './identity'; + +const MARA = 'did:plc:mara'; + +const OSKAR = 'did:plc:oskar'; + +const PDS = 'https://pds.test'; + +const HALF_HOUR = 30 * 60_000; + +describe('repoStatusLookup', () => { + it('should read an active account as active from the PDS its DID document names', async () => { + // Arrange + const lookup = repoStatusLookup(pdsAnswering(MARA, Response.json({ did: MARA, active: true }))); + + // Act + const status = await lookup(MARA); + + // Assert + expect(status).toBe('active'); + }); + + it.each(['deactivated', 'takendown', 'suspended'] as const)('should read a %s account as such', async (inactive) => { + const lookup = repoStatusLookup(pdsAnswering(MARA, Response.json({ did: MARA, active: false, status: inactive }))); + + expect(await lookup(MARA)).toBe(inactive); + }); + + it('should read an account its PDS no longer has as deleted', async () => { + const answer = Response.json({ error: 'RepoNotFound', message: 'Could not find repo' }, { status: 400 }); + + expect(await repoStatusLookup(pdsAnswering(MARA, answer))(MARA)).toBe('deleted'); + }); + + it('should read a sync condition as active, since the account is still there', async () => { + const answer = Response.json({ did: MARA, active: false, status: 'desynchronized' }); + + expect(await repoStatusLookup(pdsAnswering(MARA, answer))(MARA)).toBe('active'); + }); + + it("should throw when the PDS can't say", async () => { + const lookup = repoStatusLookup(pdsAnswering(MARA, new Response('down', { status: 502 }))); + + await expect(lookup(MARA)).rejects.toThrow('HTTP 502'); + }); +}); + +describe('AccountStatuses', () => { + it("should ask an account's PDS once, and reuse the answer for half an hour", async () => { + // Arrange + const pds = new Map([[MARA, 'deactivated']]); + const { statuses, clock } = tracked(pds); + await statuses.status(MARA); + pds.set(MARA, 'active'); + clock.now = HALF_HOUR - 1; + + // Act + await statuses.refresh(); + + // Assert + expect(await statuses.status(MARA)).toBe('deactivated'); + }); + + it('should answer with the last status while asking again once it is old', async () => { + const pds = new Map([[MARA, 'deactivated']]); + const { statuses, clock } = tracked(pds); + await statuses.status(MARA); + pds.set(MARA, 'active'); + clock.now = HALF_HOUR; + + expect(await statuses.status(MARA)).toBe('deactivated'); + // The lookup here only awaits promises, so the next turn of the event loop finds it done. + await new Promise((resolve) => setImmediate(resolve)); + expect(await statuses.status(MARA)).toBe('active'); + }); + + it("should take an account it never saw as active when its PDS can't be asked", async () => { + const { statuses } = tracked(new Map()); + + expect(await statuses.status(OSKAR)).toBe('active'); + }); + + it("should keep an account as last seen when its PDS can't be asked", async () => { + const pds = new Map([[MARA, 'deactivated']]); + const { statuses, clock } = tracked(pds, { accounts: async () => [MARA] }); + await statuses.status(MARA); + pds.delete(MARA); + clock.now = HALF_HOUR; + + await statuses.refresh(); + + expect(await statuses.status(MARA)).toBe('deactivated'); + }); + + it('should keep a deleted account deleted', async () => { + const pds = new Map([[MARA, 'deleted']]); + const { statuses, clock } = tracked(pds); + await statuses.status(MARA); + pds.set(MARA, 'active'); + clock.now = HALF_HOUR; + + await statuses.refresh(); + + expect(await statuses.status(MARA)).toBe('deleted'); + }); + + it.each(['takendown', 'suspended'] as const)('should say when a %s account is active again', async (inactive) => { + const pds = new Map([[MARA, inactive]]); + const reinstated: string[] = []; + const { statuses, clock } = tracked(pds, { reinstated: (did) => reinstated.push(did) }); + await statuses.refresh(); + pds.set(MARA, 'active'); + clock.now = HALF_HOUR; + + await statuses.refresh(); + + expect(reinstated).toEqual([MARA]); + }); + + it('should not say a deactivated account is reinstated, since its records were kept', async () => { + const pds = new Map([[MARA, 'deactivated']]); + const reinstated: string[] = []; + const { statuses, clock } = tracked(pds, { reinstated: (did) => reinstated.push(did) }); + await statuses.refresh(); + pds.set(MARA, 'active'); + clock.now = HALF_HOUR; + + await statuses.refresh(); + + expect(reinstated).toEqual([]); + }); + + it("should list none of the directory's accounts as inactive until the first check is done", () => { + const { statuses } = tracked(new Map([[MARA, 'deactivated']])); + + expect(statuses.inactive()).toEqual([]); + }); + + it("should list the directory's inactive accounts once checked, and drop one that's active again", async () => { + const pds = new Map([ + [MARA, 'deactivated'], + [OSKAR, 'active'] + ]); + + const { statuses, clock } = tracked(pds); + await statuses.refresh(); + const before = statuses.inactive(); + pds.set(MARA, 'active'); + clock.now = HALF_HOUR; + + await statuses.refresh(); + + expect({ before, after: statuses.inactive() }).toEqual({ before: [MARA], after: [] }); + }); + + it("should keep the last list when the directory can't list its accounts", async () => { + const pds = new Map([[MARA, 'deactivated']]); + let down = false; + + const { statuses, clock } = tracked(pds, { + accounts: async () => { + if (down) throw new Error('directory down'); + + return [...pds.keys()]; + } + }); + + await statuses.refresh(); + down = true; + clock.now = HALF_HOUR; + + await statuses.refresh(); + + expect(statuses.inactive()).toEqual([MARA]); + }); +}); + +// Helpers + +/** An identity resolver whose every account is on PDS, which answers `did`'s getRepoStatus with `answer`. */ +function pdsAnswering(did: string, answer: Response) { + return { + resolve: async (asked: string): Promise => ({ + did: asked, + handle: null, + pds: PDS, + signingKey: 'did:key:z', + kemKey: null + }), + serviceApiFetch: async (input: string | URL | Request) => { + const url = new URL(input instanceof Request ? input.url : input); + const asks = url.origin === PDS && url.pathname === '/xrpc/com.atproto.sync.getRepoStatus'; + + return asks && url.searchParams.get('did') === did ? answer : new Response('not found', { status: 404 }); + } + }; +} + +/** + * AccountStatuses over `pds` (an account it lacks can't be asked), with the directory's accounts being the ones in it + * unless `options` says otherwise, and a clock that only moves when a test moves it. + */ +function tracked( + pds: Map, + options: Partial[0]> = {} +) { + const clock = { now: 0 }; + + const statuses = new AccountStatuses({ + lookup: async (did) => { + const status = pds.get(did); + + if (!status) throw new Error(`no PDS answers for ${did}`); + + return status; + }, + accounts: async () => [...pds.keys()], + logger: silentLogger, + now: () => clock.now, + ...options + }); + + return { statuses, clock }; +} diff --git a/apps/web/src/lib/server/atproto/account-status.ts b/apps/web/src/lib/server/atproto/account-status.ts new file mode 100644 index 000000000..2fcc6db0b --- /dev/null +++ b/apps/web/src/lib/server/atproto/account-status.ts @@ -0,0 +1,215 @@ +import PQueue from 'p-queue'; +import { z } from 'zod'; +import type { Logger } from '../logger'; +import type { IdentityResolver } from './identity'; + +/** + * Whether an account's records show on the site. `deactivated`, `takendown`, `suspended` and `deleted` are the + * `com.atproto.sync.getRepoStatus` statuses that hide them; any other (`desynchronized`, `throttled`) is a sync + * condition of an account still there, so it reads as `active`. + */ +export type AccountStatus = 'active' | 'deactivated' | 'takendown' | 'suspended' | 'deleted'; + +/** Asks where an account lives whether it's active. Throws when it can't tell. */ +type StatusLookup = (did: string) => Promise; + +const INACTIVE = new Set(['deactivated', 'takendown', 'suspended', 'deleted']); + +const isInactive = (status: string | undefined): status is Exclude => + status !== undefined && INACTIVE.has(status); + +const repoStatus = z.object({ active: z.boolean(), status: z.string().optional() }); + +const xrpcError = z.object({ error: z.string() }); + +/** How long one account's status is reused before it's asked again. */ +const FRESH_MS = 30 * 60_000; + +/** How long asking one account's PDS may take. */ +const LOOKUP_TIMEOUT_MS = 5_000; + +/** How many accounts are asked at once when the directory's accounts are checked. */ +const CONCURRENCY = 8; + +/** The most accounts whose status is kept; the oldest go first. */ +const KEPT = 10_000; + +/** The most inactive accounts a directory query takes (its `inactive` param's maxLength). */ +const INACTIVE_PARAM_MAX = 100; + +/** + * `com.atproto.sync.getRepoStatus` from the PDS the account's DID document names, through the guarded fetch. A PDS + * answers `RepoNotFound` for an account it deleted. + */ +export function repoStatusLookup(identity: Pick): StatusLookup { + return async (did) => { + const url = new URL('/xrpc/com.atproto.sync.getRepoStatus', (await identity.resolve(did)).pds); + url.searchParams.set('did', did); + + const response = await identity.serviceApiFetch(url, { + redirect: 'error', + signal: AbortSignal.timeout(LOOKUP_TIMEOUT_MS) + }); + + const body: unknown = await response.json().catch(() => null); + + if (!response.ok) { + if (xrpcError.safeParse(body).data?.error === 'RepoNotFound') return 'deleted'; + throw new Error(`getRepoStatus: HTTP ${response.status}`); + } + + const { active, status } = repoStatus.parse(body); + + return !active && isInactive(status) ? status : 'active'; + }; +} + +type AccountStatusOptions = { + lookup: StatusLookup; + /** Every account whose records the directory reads: the managers of the root's projects and the DJs staff list. */ + accounts: () => Promise; + logger: Logger; + /** Called when an account taken down or suspended is active again, since HappyView dropped its records then. */ + reinstated?: (did: string) => void; + freshMs?: number; + now?: () => number; +}; + +/** + * Which accounts are inactive, asked of their PDS when a page needs to know and kept for half an hour (ADR 0020). + * HappyView keeps a deactivated account's records, so the directory queries are told which accounts to leave out, and + * the account's own pages say it isn't active. A PDS that can't be asked leaves the account as it was last seen, or + * active when it never was: the site fails open. A deleted account stays deleted, since deletion can't be undone. + */ +export class AccountStatuses { + private readonly known = new Map(); + private readonly asking = new Map>(); + private inDirectory?: { dids: string[]; at: number }; + private refreshing?: Promise; + private readonly freshMs: number; + private readonly now: () => number; + + constructor(private readonly options: AccountStatusOptions) { + this.freshMs = options.freshMs ?? FRESH_MS; + this.now = options.now ?? Date.now; + } + + /** + * `did`'s status. A status seen before answers at once, and is asked again in the background once it's older than + * half an hour; only an account never seen waits for its PDS. + */ + async status(did: string): Promise { + const known = this.known.get(did); + + if (!known) return this.ask(did); + + if (!this.isFresh(known.at)) void this.ask(did); + + return known.status; + } + + /** + * The directory's accounts last found inactive, for the queries to leave out: none until the first check is done. + * When the answer is older than half an hour, refresh() starts in the background, so no page waits on a PDS. + */ + inactive(): string[] { + const known = this.inDirectory; + + if (!known || !this.isFresh(known.at)) void this.refresh(); + + return known?.dids ?? []; + } + + /** Checks the directory's accounts again now, asking only the ones not asked lately, and joining a check under way. */ + refresh(): Promise { + this.refreshing ??= this.checkDirectory().finally(() => { + this.refreshing = undefined; + }); + + return this.refreshing; + } + + private isFresh(at: number): boolean { + return this.now() - at < this.freshMs; + } + + private async checkDirectory(): Promise { + let accounts: string[]; + + try { + accounts = [...new Set(await this.options.accounts())]; + } catch (error) { + // Kept as it was for another half hour, so a directory that's down isn't asked on every page. + this.options.logger.warn("could not list the directory's accounts to check", { err: error }); + const dids = this.inDirectory?.dids ?? []; + this.inDirectory = { dids, at: this.now() }; + + return dids; + } + + const queue = new PQueue({ concurrency: CONCURRENCY }); + + const statuses = await Promise.all( + accounts.map((did) => + queue.add(() => { + const known = this.known.get(did); + + return known && this.isFresh(known.at) ? known.status : this.ask(did); + }) + ) + ); + + let dids = accounts.filter((_, index) => statuses[index] !== 'active'); + + if (dids.length > INACTIVE_PARAM_MAX) { + this.options.logger.warn('more inactive accounts than the directory queries take', { inactive: dids.length }); + dids = dids.slice(0, INACTIVE_PARAM_MAX); + } + + this.inDirectory = { dids, at: this.now() }; + this.options.logger.debug("checked the directory's accounts", { accounts: accounts.length, inactive: dids }); + + return dids; + } + + /** Asks `did`'s PDS, once at a time per account, and keeps the answer. */ + private ask(did: string): Promise { + let asking = this.asking.get(did); + + if (!asking) { + asking = this.lookup(did).finally(() => this.asking.delete(did)); + this.asking.set(did, asking); + } + + return asking; + } + + private async lookup(did: string): Promise { + const before = this.known.get(did)?.status; + let status: AccountStatus; + + if (before === 'deleted') { + status = before; + } else { + try { + status = await this.options.lookup(did); + } catch (error) { + status = before ?? 'active'; + this.options.logger.warn("could not check an account's status", { err: error, did, assumed: status }); + } + } + + this.known.delete(did); + this.known.set(did, { status, at: this.now() }); + + if (this.known.size > KEPT) this.known.delete(this.known.keys().next().value!); + + if (before !== undefined && status !== before) { + this.options.logger.info("an account's status changed", { did, from: before, to: status }); + + if (status === 'active' && (before === 'takendown' || before === 'suspended')) this.options.reinstated?.(did); + } + + return status; + } +} diff --git a/apps/web/src/lib/server/core.ts b/apps/web/src/lib/server/core.ts index 1a179c187..70eb9f2e1 100644 --- a/apps/web/src/lib/server/core.ts +++ b/apps/web/src/lib/server/core.ts @@ -1,3 +1,4 @@ +import type { AccountStatuses } from './atproto/account-status'; import type { RepoClient, RootRepoClient, StoredRecord } from './atproto/repo-client'; import type { RootSpaces } from './atproto/spaces'; import type { AuditLog } from './audit/log'; @@ -18,6 +19,8 @@ export type Core = { userClient: (did: string) => Promise; audit: AuditLog; accounts: AccountService; + /** Which accounts are active, asked of their PDS when a page needs to know (ADR 0020). */ + accountStatuses: Pick; /** Puts an item in people's inboxes. */ notify: Notifier['notify']; /** Notifies the syncer that a new space should be watched. */ diff --git a/apps/web/src/lib/server/happyview/directory.test.ts b/apps/web/src/lib/server/happyview/directory.test.ts index c88df8137..dd5c6604c 100644 --- a/apps/web/src/lib/server/happyview/directory.test.ts +++ b/apps/web/src/lib/server/happyview/directory.test.ts @@ -492,6 +492,16 @@ describe('getSets and listSets', () => { expect(sets.map((set) => set.title)).toEqual(['B', 'A']); }); + it("leaves out the sets of accounts the app says aren't active", async () => { + const hv = new FakeHappyView(ROOT); + await publish(hv, {}, { managers: ['did:plc:a', 'did:plc:b'] }); + const a = await publishSet(hv, 'did:plc:a', { title: 'A' }); + const b = await publishSet(hv, 'did:plc:b', { title: 'B' }); + + const { sets } = await query(hv, 'getSets', { uris: [a.uri, b.uri], inactive: 'did:plc:b' }); + expect(sets.map((set) => set.title)).toEqual(['A']); + }); + it('lists only the accounts asked for, most recently played first, up to the limit', async () => { const hv = new FakeHappyView(ROOT); await publish(hv, {}, { managers: ['did:plc:a', 'did:plc:b', 'did:plc:c'] }); @@ -916,6 +926,22 @@ describe('who counts', () => { ]); expect((await query(hv, 'getCharts')).places).toEqual([{ city: 'Berlin', country: 'DE', count: 2 }]); }); + + it("leaves out the sets of accounts the app says aren't active, and counts them again once it doesn't", async () => { + const hv = new FakeHappyView(ROOT); + await acts(hv, 'a', 'b', 'c'); + + for (const dj of ['a', 'b', 'c']) await publishSet(hv, `did:plc:${dj}`, { tracks: [hit] }); + + const inactive = ['did:plc:c']; + const artist = await query(hv, 'getArtist', { name: 'Ferrule', inactive }); + const { artists } = await query<{ artists: { djCount: number }[] }>(hv, 'searchArtists', { inactive }); + + expect((await query(hv, 'getCharts', { inactive })).tracks).toEqual([]); + expect(artist.djs.map((dj) => dj.did).sort()).toEqual(['did:plc:a', 'did:plc:b']); + expect(artists).toMatchObject([{ djCount: 2 }]); + expect(await supports(hv)).toEqual([3]); + }); }); describe('what counts', () => { @@ -1392,6 +1418,17 @@ describe('searchPerformers', () => { expect(await find({ kinds: ['duo'] })).toEqual(['Ada Duo']); expect(await find({ unclaimed: true })).toEqual(['Nobody Yet']); }); + + it("leaves out a listed DJ the app says isn't active, and the solo project that gives way to them", async () => { + const hv = new FakeHappyView(ROOT); + await publish(hv, { name: 'Ada Solo' }, { managers: ['did:plc:ada'] }); + await publish(hv, { name: 'Crew' }); + await listDj(hv, 'did:plc:ada', 'Ada'); + const find = async (params: Params = {}) => performerNames(await search(hv, { sort: 'name', ...params })); + + expect(await find({ inactive: 'did:plc:ada' })).toEqual(['Crew']); + expect(await find()).toEqual(['Ada', 'Crew']); + }); }); describe('matchProjects', () => { @@ -1946,6 +1983,18 @@ describe('listShows and getShows', () => { expect(await list({ project })).toEqual(['Weekender', 'Tonight', 'Sydney', 'Paris']); }); + it("leaves out the shows of accounts the app says aren't active", async () => { + const hv = new FakeHappyView(ROOT); + const project = await publish(hv, {}, { managers: ['did:plc:dj', 'did:plc:co'] }); + await publishShow(hv, 'did:plc:dj', project, { name: 'Tonight', startsAt: fromNow(6) }); + await publishShow(hv, 'did:plc:co', project, { name: 'Later', startsAt: fromNow(72) }); + + const list = async (params: Params = {}) => showNames(await query(hv, 'listShows', params)); + + expect(await list({ inactive: 'did:plc:co' })).toEqual(['Tonight']); + expect(await list()).toEqual(['Tonight', 'Later']); + }); + it('finds shows near a place, and nearest first among the projects someone follows', async () => { const hv = new FakeHappyView(ROOT); const tide = await publish(hv, {}, { managers: ['did:plc:dj'] }); diff --git a/apps/web/src/lib/server/profile-page.ts b/apps/web/src/lib/server/profile-page.ts index 0ea1461f3..8ea412ea5 100644 --- a/apps/web/src/lib/server/profile-page.ts +++ b/apps/web/src/lib/server/profile-page.ts @@ -44,7 +44,8 @@ async function canonicalAccount( /** * The account a page under `/@` is about, redirecting to its canonical address (see canonicalAccount). Each * address that names no account counts against `ip`, since resolving it may have meant asking a host the visitor - * chose; past the limit, the page answers 429 without resolving anything. + * chose; past the limit, the page answers 429 without resolving anything. An account that isn't active answers 404, + * and a deleted one 410, each saying so without saying why (ADR 0020). */ export async function pageAccount(locals: App.Locals, param: string, rest: string, ip: string): Promise { const misses = locals.app.limits.profileMisses; @@ -62,6 +63,19 @@ export async function pageAccount(locals: App.Locals, param: string, rest: strin } misses.refund(ip); + const status = await locals.app.core.accountStatuses.status(account.did); + + if (status === 'deleted') { + error(410, { status: 410, title: 'This account was deleted', message: 'Their profile and sets are gone.' }); + } + + if (status !== 'active') { + error(404, { + status: 404, + title: "This account isn't active", + message: 'Their profile and sets come back when the account does.' + }); + } return account; } diff --git a/apps/web/src/lib/server/services/dj-listings.test.ts b/apps/web/src/lib/server/services/dj-listings.test.ts index ed37b3dcf..5798dd6f5 100644 --- a/apps/web/src/lib/server/services/dj-listings.test.ts +++ b/apps/web/src/lib/server/services/dj-listings.test.ts @@ -175,6 +175,15 @@ describe('asking staff to list a DJ in Find DJs', () => { ]); }); + it('names every DJ staff list, for checking whose account is still active', async () => { + const mod = await t.viewer(MOD); + await t.djListings.list(mod, DJ); + await t.djListings.list(mod, MOD); + await t.djListings.unlist(mod, MOD); + + expect(await t.djListings.listed()).toEqual([DJ]); + }); + it('has the directory read the profile again on listing, in case it missed it', async () => { await saveProfile({}); const request = await ask(); diff --git a/apps/web/src/lib/server/services/dj-listings.ts b/apps/web/src/lib/server/services/dj-listings.ts index 794331158..77b5e79fd 100644 --- a/apps/web/src/lib/server/services/dj-listings.ts +++ b/apps/web/src/lib/server/services/dj-listings.ts @@ -1,3 +1,4 @@ +import { AtUri } from '@atproto/syntax'; import { z } from 'zod'; import { COLLECTION } from '#lib/nsid.ts'; import type { Viewer } from '#lib/types.ts'; @@ -33,6 +34,13 @@ export class DjListings { return { uri: found.uri, cid: found.cid, request: parsed.data.request, createdAt: parsed.data.createdAt }; } + /** The DIDs of every DJ staff list. Throws when the directory can't answer. */ + async listed(): Promise { + const records = await this.repos.listAll(this.core.rootDid, COLLECTION.listingProfile, { strict: true }); + + return records.map((record) => new AtUri(record.uri).rkey); + } + /** * Lists `did` in Find DJs, as `actor` (staff) decided, from the request at `request` when there was one. Their profile * is read again too, in case the directory missed it, so the listing finds it. diff --git a/apps/web/src/lib/server/services/performers.test.ts b/apps/web/src/lib/server/services/performers.test.ts index ba2756023..b8ecb6166 100644 --- a/apps/web/src/lib/server/services/performers.test.ts +++ b/apps/web/src/lib/server/services/performers.test.ts @@ -98,4 +98,27 @@ describe('PerformerSearch', () => { DJ ]); }); + + it("leaves out a DJ while their account isn't active, and shows them again once it is", async () => { + const found = async () => (await t.performers.search({ sort: 'name' })).items.map((item) => item.kind); + + t.accountStatus.set(DJ, 'deactivated'); + await t.accountStatuses.refresh(); + expect(await found()).toEqual(['project']); + + t.accountStatus.set(DJ, 'active'); + await t.accountStatuses.refresh(); + expect(await found()).toEqual(['project', 'dj']); + }); + + it('leaves out a deleted DJ for good, even once their PDS says otherwise', async () => { + const found = async () => (await t.performers.search({ sort: 'name' })).items.map((item) => item.kind); + + t.accountStatus.set(DJ, 'deleted'); + await t.accountStatuses.refresh(); + t.accountStatus.set(DJ, 'active'); + await t.accountStatuses.refresh(); + + expect(await found()).toEqual(['project']); + }); }); diff --git a/apps/web/src/lib/server/services/performers.ts b/apps/web/src/lib/server/services/performers.ts index 940f0711f..13f69b9d6 100644 --- a/apps/web/src/lib/server/services/performers.ts +++ b/apps/web/src/lib/server/services/performers.ts @@ -8,12 +8,12 @@ import { type ProjectSearch, type ProjectService, searchQuery } from './projects export type PerformerSearchResult = { items: PerformerResult[]; total: number; page: number; pageSize: number }; /** - * Find DJs: active projects and the DJs staff list, searched together by the directory (`searchPerformers`), with each - * DJ's handle from the accounts this app knows, for links to their profile. + * Find DJs: active projects and the DJs staff list, searched together by the directory (`searchPerformers`), without + * DJs whose account isn't active, with each DJ's handle from the accounts this app knows, for links to their profile. */ export class PerformerSearch { constructor( - private readonly core: Pick, + private readonly core: Pick, private readonly directory: HappyViewClient, private readonly projects: ProjectService, private readonly profiles: ProfileService @@ -21,7 +21,12 @@ export class PerformerSearch { async search(params: Omit): Promise { const { page, pageSize, query } = searchQuery(params); - const output = await this.directory.query('searchPerformers', query); + + const output = await this.directory.query('searchPerformers', { + ...query, + inactive: this.core.accountStatuses.inactive() + }); + const dids = output.performers.flatMap((found) => ('profile' in found ? [new AtUri(found.profile.uri).host] : [])); const accounts = await this.core.accounts.views(dids); diff --git a/apps/web/src/lib/server/services/recordings.ts b/apps/web/src/lib/server/services/recordings.ts index 4938e88ee..2c5c9fd70 100644 --- a/apps/web/src/lib/server/services/recordings.ts +++ b/apps/web/src/lib/server/services/recordings.ts @@ -63,8 +63,8 @@ class Recent { /** * Where a set's recording plays, decided when someone presses Play: its `recording` record (an `fm.plyr.track`, asked * of plyr.fm, or a `computer.localnetwork.dj.recording` on the DJ's PDS, served by /media/audio), then its links. - * Records are read through HappyView. Recordings on a PDS play only for accounts that manage an active project, since - * the site streams their bytes, and not at all while pauseRecordingStream is on, which leaves the set's links to play. + * Records are read through HappyView. Recordings on a PDS play only for active accounts that manage an active project, + * since the site streams their bytes, and not at all while pauseRecordingStream is on, which leaves the set's links to play. */ export class RecordingService { private readonly managers: Recent; @@ -74,7 +74,7 @@ export class RecordingService { constructor( private readonly repos: IndexedRepo, private readonly plyr: PlyrClient, - /** Whether the account manages an active project. */ + /** Whether the account is active and manages an active project. */ private readonly manages: (did: string) => Promise, private readonly logger: Logger, now: () => number = Date.now @@ -187,7 +187,10 @@ export class RecordingService { return { kind: 'audio', src: `/media/audio/${did}/${parsed.data.audio.ref.$link}`, from: 'pds' }; } - /** Whether `did` manages an active project. A directory that can't say reads as no, and isn't remembered. */ + /** + * Whether `did` is active and manages an active project. A directory that can't say reads as no, and isn't + * remembered. + */ private async isManager(did: string): Promise { try { return await this.managers.get(did, () => this.manages(did)); diff --git a/apps/web/src/lib/server/services/sets.ts b/apps/web/src/lib/server/services/sets.ts index c06e2d837..57bf4be78 100644 --- a/apps/web/src/lib/server/services/sets.ts +++ b/apps/web/src/lib/server/services/sets.ts @@ -60,12 +60,15 @@ export class SetService { } } - /** The linked sets HappyView has, by URI. A profile has at most 12 mixes, so one lookup takes them all. */ + /** + * The linked sets HappyView has, by URI, without those by accounts that aren't active. A profile has at most 12 mixes, + * so one lookup takes them all. + */ async byUri(refs: StrongRef[]): Promise> { const uris = [...new Set(refs.map((ref) => ref.uri))]; if (uris.length === 0) return new Map(); - const { sets } = await this.directory.query('getSets', { uris }); + const { sets } = await this.directory.query('getSets', { uris, inactive: this.core.accountStatuses.inactive() }); return new Map(sets.map((set) => [set.uri, set])); } diff --git a/apps/web/src/lib/server/services/shows.ts b/apps/web/src/lib/server/services/shows.ts index b97cbe784..a4254fb60 100644 --- a/apps/web/src/lib/server/services/shows.ts +++ b/apps/web/src/lib/server/services/shows.ts @@ -225,11 +225,12 @@ export class ShowService { private readonly indexWaitMs = INDEX_WAIT_MS ) {} - /** Upcoming shows, a page at a time. */ + /** Upcoming shows, a page at a time, without those by accounts that aren't active. */ async upcoming(query: ShowQuery): Promise<{ items: ShowView[]; cursor?: string }> { const { near } = query; const output = await this.directory.query('listShows', { + inactive: this.core.accountStatuses.inactive(), project: query.project, follower: query.follower, latE6: near && toE6(near.lat), diff --git a/apps/web/src/lib/server/services/supports.test.ts b/apps/web/src/lib/server/services/supports.test.ts index 0b603d340..71b147982 100644 --- a/apps/web/src/lib/server/services/supports.test.ts +++ b/apps/web/src/lib/server/services/supports.test.ts @@ -135,7 +135,7 @@ describe('SupportService', () => { } }); - const supports = new SupportService(directory, t.accounts, silentLogger, () => now); + const supports = new SupportService(directory, t.core, silentLogger, () => now); await supports.search('ferr'); await supports.search('ferr'); await supports.search('kest'); @@ -161,7 +161,7 @@ describe('SupportService', () => { } }); - const supports = new SupportService(directory, t.accounts, silentLogger, () => 0); + const supports = new SupportService(directory, t.core, silentLogger, () => 0); for (let i = 0; i <= 200; i++) await supports.search(`artist ${i}`); expect(asked).toBe(201); @@ -181,7 +181,7 @@ describe('SupportService', () => { fetch: () => new Promise((resolve) => answers.push(resolve)) }); - const supports = new SupportService(directory, t.accounts, silentLogger, () => now); + const supports = new SupportService(directory, t.core, silentLogger, () => now); const stale = supports.search('ferr'); now = 60_000; const fresh = supports.search('ferr'); diff --git a/apps/web/src/lib/server/services/supports.ts b/apps/web/src/lib/server/services/supports.ts index 365488ada..51df9a962 100644 --- a/apps/web/src/lib/server/services/supports.ts +++ b/apps/web/src/lib/server/services/supports.ts @@ -1,9 +1,9 @@ import type { ChartFilters } from '#lib/supports.ts'; import type { ArtistSupports, Charts, SupportedArtist } from '#lib/types.ts'; +import type { Core } from '../core'; import { type DirectoryOutputs, type HappyViewClient, QUERY_BYTES } from '../happyview/client'; import type { Logger } from '../logger'; import { truncateUtf8 } from '../utf8'; -import type { AccountService } from './accounts'; /** Tracks and artists the charts show. */ const CHART_SIZE = 50; @@ -25,15 +25,15 @@ type Query = 'getCharts' | 'getArtist' | 'searchArtists'; /** * Who played whose tracks, from the sets the directory keeps (lua/computer/localnetwork/directory/getCharts.lua, - * getArtist.lua and searchArtists.lua count them). Reads only; a HappyViewError means the directory is down, which - * pages show as such. + * getArtist.lua and searchArtists.lua count them), leaving out the sets of accounts that aren't active. Reads only; a + * HappyViewError means the directory is down, which pages show as such. */ export class SupportService { private readonly memo = new Map }>(); constructor( private readonly directory: HappyViewClient, - private readonly accounts: AccountService, + private readonly core: Pick, private readonly logger: Logger, private readonly now: () => number = Date.now ) {} @@ -62,7 +62,7 @@ export class SupportService { async artist(artist: { mbid: string } | { name: string }): Promise { const params = 'mbid' in artist ? artist : { name: truncateUtf8(artist.name, ARTIST_BYTES) }; const { djs, ...supports } = await this.query('getArtist', params); - const handles = await this.accounts.views(djs.map((dj) => dj.did)); + const handles = await this.core.accounts.views(djs.map((dj) => dj.did)); this.logger.debug('artist supports', { artist, tracks: supports.tracks.length, djs: djs.length }); return { @@ -71,11 +71,15 @@ export class SupportService { }; } - /** A directory query, or the same one's answer from the last minute. A failed one isn't kept. */ + /** + * A directory query, or the same one's answer from the last minute while the same accounts are inactive. A failed one + * isn't kept. + */ private query( name: K, - params: Record + asked: Record ): Promise { + const params = { ...asked, inactive: this.core.accountStatuses.inactive() }; const key = JSON.stringify([name, params]); const kept = this.memo.get(key); diff --git a/apps/web/src/lib/server/testing/core.ts b/apps/web/src/lib/server/testing/core.ts index 9374e6ec6..0d59db6fe 100644 --- a/apps/web/src/lib/server/testing/core.ts +++ b/apps/web/src/lib/server/testing/core.ts @@ -1,3 +1,4 @@ +import { type AccountStatus, AccountStatuses } from '../atproto/account-status'; import { rootSpaces } from '../atproto/spaces'; import { AuditLog } from '../audit/log'; import { ensureRootSpaces } from '../bootstrap'; @@ -86,6 +87,19 @@ export async function createTestServices( const notifications = new Notifier({ db, logger: silentLogger }); + /** + * Each account's status as its PDS would answer: active unless a test sets another. Statuses are never fresh, so + * `accountStatuses.refresh()` asks again and the directory's queries then leave the inactive ones out. + */ + const accountStatus = new Map(); + + const accountStatuses = new AccountStatuses({ + lookup: async (did) => accountStatus.get(did) ?? 'active', + accounts: async () => [...accountStatus.keys()], + logger: silentLogger, + freshMs: 0 + }); + const core: Core = { db, logger: silentLogger, @@ -96,6 +110,7 @@ export async function createTestServices( userClient: async (did) => (capable.has(did) ? net.client(did) : null), audit, accounts, + accountStatuses, notify: notifications.notify.bind(notifications), watchSpace: async () => {}, fetchSpaceBlob: async (_space, _repo, cid) => { @@ -129,7 +144,7 @@ export async function createTestServices( const planner = new PlannerService(core); const projectAdmin = new ProjectAdmin(core, projects); const tracklists = new TracklistService(core); - const supports = new SupportService(directory, accounts, silentLogger); + const supports = new SupportService(directory, core, silentLogger); // Writes are indexed in-process here, so a write that isn't served at once never will be. const indexedRepo = new IndexedRepo(directory, silentLogger, 0); @@ -208,6 +223,8 @@ export async function createTestServices( core, audit, accounts, + accountStatus, + accountStatuses, notifications, projects, requests, diff --git a/apps/web/src/routes/+error.svelte b/apps/web/src/routes/+error.svelte index 824a7cbad..e7267cd41 100644 --- a/apps/web/src/routes/+error.svelte +++ b/apps/web/src/routes/+error.svelte @@ -3,16 +3,19 @@ import Button from '#lib/ui/Button.svelte'; import SectionHeader from '#lib/ui/SectionHeader.svelte'; - const title = $derived(page.status === 404 ? "We couldn't find that page" : page.status === 403 ? 'Not allowed' : page.status === 503 ? 'Directory offline' : 'Something went wrong'); + const title = $derived(page.error?.title ?? (page.status === 404 ? "We couldn't find that page" : page.status === 403 ? 'Not allowed' : page.status === 503 ? 'Directory offline' : 'Something went wrong')); + + // An error with its own heading, like an account that isn't active, isn't a fault, so no status code heads it. + const eyebrow = $derived(page.error?.title ? undefined : `Error ${page.status}`); // SvelteKit's own 404 message is just "Not Found", which the title already says. const lede = $derived(page.status === 404 && page.error?.message === 'Not Found' ? 'The link may be out of date, or the page has moved.' : page.error?.message); -{page.status} · Local Network +{page.error?.title ?? page.status} · Local Network
- + {#snippet actions()}{/snippet} diff --git a/apps/web/src/routes/@[handle]/page.server.test.ts b/apps/web/src/routes/@[handle]/page.server.test.ts index 0be53af2e..872333a9d 100644 --- a/apps/web/src/routes/@[handle]/page.server.test.ts +++ b/apps/web/src/routes/@[handle]/page.server.test.ts @@ -192,6 +192,39 @@ it('is a 404 for an address that names no account, and a 429 once a visitor has ).rejects.toMatchObject({ status: 429 }); }); +it("says an account isn't active, the same way whatever the reason, and that a deleted one was deleted", async () => { + const loadMara = () => callRoute(load, { app: app(), params: { handle: 'mara.test' }, url: '/@mara.test' }); + const inactive = { status: 404, body: { title: "This account isn't active" } }; + + t.accountStatus.set(MARA, 'deactivated'); + await expect(loadMara()).rejects.toMatchObject(inactive); + await t.accountStatuses.refresh(); + + t.accountStatus.set(MARA, 'takendown'); + await t.accountStatuses.refresh(); + await expect(loadMara()).rejects.toMatchObject(inactive); + + t.accountStatus.set(MARA, 'deleted'); + await t.accountStatuses.refresh(); + await expect(loadMara()).rejects.toMatchObject({ status: 410, body: { title: 'This account was deleted' } }); +}); + +it("shows the profile again once its account is active again, and refuses to follow it while it isn't", async () => { + t.accountStatus.set(MARA, 'deactivated'); + await expect(post('follow', await t.viewer(FAN))).rejects.toMatchObject({ status: 404 }); + + t.accountStatus.set(MARA, 'active'); + await t.accountStatuses.refresh(); + + const data = await routeEvent({ + app: app(), + params: { handle: 'mara.test' }, + url: '/@mara.test' + }).loadData(load); + + expect(data).toMatchObject({ name: 'Mara Lind' }); +}); + /** The action `name` on `handle`'s page, as `viewer` posts it. */ const post = (name: keyof typeof actions, viewer: Viewer | null, handle = 'mara.test') => callRoute(actions[name], { app: app(), viewer, params: { handle }, url: `/@${handle}?/${name}`, form: {} }); diff --git a/apps/web/src/routes/artists/[id]/page.server.test.ts b/apps/web/src/routes/artists/[id]/page.server.test.ts index 7933dcd12..67c28fe7f 100644 --- a/apps/web/src/routes/artists/[id]/page.server.test.ts +++ b/apps/web/src/routes/artists/[id]/page.server.test.ts @@ -85,7 +85,7 @@ it("renders without the artist's supports while the directory is offline", async fetch: async () => new Response('Service Unavailable', { status: 503 }) }); - const supports = new SupportService(directory, f.t.accounts, silentLogger); + const supports = new SupportService(directory, f.t.core, silentLogger); const data = await loadRoute(load, { app: { ...app(), supports }, diff --git a/apps/web/src/routes/artists/name/[[name]]/page.server.test.ts b/apps/web/src/routes/artists/name/[[name]]/page.server.test.ts index b2bfc8f0f..3b7b764f7 100644 --- a/apps/web/src/routes/artists/name/[[name]]/page.server.test.ts +++ b/apps/web/src/routes/artists/name/[[name]]/page.server.test.ts @@ -91,7 +91,7 @@ it('names the page after the address while the directory is offline', async () = fetch: async () => new Response('Service Unavailable', { status: 503 }) }); - const supports = new SupportService(directory, f.t.accounts, silentLogger); + const supports = new SupportService(directory, f.t.core, silentLogger); const data = await loadRoute(load, { app: { ...app(), supports }, diff --git a/apps/web/src/routes/artists/page.server.test.ts b/apps/web/src/routes/artists/page.server.test.ts index 6ba676b65..5bdaf84cc 100644 --- a/apps/web/src/routes/artists/page.server.test.ts +++ b/apps/web/src/routes/artists/page.server.test.ts @@ -59,7 +59,7 @@ it('searches with an empty query when none is given', async () => { }); it('streams null for the artists while the directory is offline, so the search box still shows', async () => { - const supports = new SupportService(offline, f.t.accounts, silentLogger); + const supports = new SupportService(offline, f.t.core, silentLogger); const data = await loadRoute(load, { app: { ...app(), supports }, url: '/artists?q=Ferrule' }); expect(await data.artists).toBeNull(); diff --git a/apps/web/src/routes/charts/page.server.test.ts b/apps/web/src/routes/charts/page.server.test.ts index 82661fd1e..8cc8be57e 100644 --- a/apps/web/src/routes/charts/page.server.test.ts +++ b/apps/web/src/routes/charts/page.server.test.ts @@ -95,7 +95,7 @@ it('streams null for the charts while the directory is offline, so the filters s fetch: async () => new Response('Service Unavailable', { status: 503 }) }); - const supports = new SupportService(directory, f.t.accounts, silentLogger); + const supports = new SupportService(directory, f.t.core, silentLogger); const data = await loadRoute(load, { app: { ...app(), supports }, url: '/charts' }); expect(await data.charts).toBeNull(); diff --git a/apps/web/src/routes/error.stories.svelte b/apps/web/src/routes/error.stories.svelte index 024a0423d..6dbd1e306 100644 --- a/apps/web/src/routes/error.stories.svelte +++ b/apps/web/src/routes/error.stories.svelte @@ -3,12 +3,15 @@ import { expect, within } from 'storybook/test'; import ErrorPage from './+error.svelte'; - /** The site's error page, for a page that isn't there and for a fault. Only a fault shows a reference to report. */ + /** + * The site's error page, for a page that isn't there, an account that isn't active, and a fault. Only a fault shows a + * reference to report. + */ const { Story } = defineMeta({ title: 'Patterns/Error page', component: ErrorPage, parameters: { layout: 'fullscreen' } }); - const at = (status: number, message: string) => ({ + const at = (status: number, message: string, title?: string) => ({ sveltekit_experimental: { - state: { page: { url: new URL('https://localnetwork.computer/projects/nobody'), status, error: { message, requestId: 'req-3f2a' } } } + state: { page: { url: new URL('https://localnetwork.computer/projects/nobody'), status, error: { message, title, requestId: 'req-3f2a' } } } } }); @@ -30,3 +33,21 @@ await expect(within(canvasElement).getByText('Reference: req-3f2a')).toBeVisible(); }} /> + + { + const canvas = within(canvasElement); + await expect(canvas.getByRole('heading', { level: 1, name: "This account isn't active" })).toBeVisible(); + await expect(canvas.queryByText('Error 404')).toBeNull(); + }} +/> + + { + await expect(within(canvasElement).getByRole('heading', { level: 1, name: 'This account was deleted' })).toBeVisible(); + }} +/> diff --git a/apps/web/tests/integration/inactive-accounts.test.ts b/apps/web/tests/integration/inactive-accounts.test.ts new file mode 100644 index 000000000..9448892e6 --- /dev/null +++ b/apps/web/tests/integration/inactive-accounts.test.ts @@ -0,0 +1,64 @@ +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { load as profilePage } from '../../src/routes/@[handle]/+page.server.ts'; +import { callRoute } from '../../src/lib/testing/route-event.ts'; +import { TestNetwork } from './network.ts'; + +const BERLIN = { city: 'Berlin', country: 'DE', latE6: 52_520_000, lngE6: 13_405_000 }; + +/** Past the half hour an account's status is kept for, so the next check asks its PDS again. */ +const LATER_MS = 31 * 60_000; + +describe('an account that stops being active, on a real PDS', () => { + let net: TestNetwork; + + beforeAll(async () => { + net = await TestNetwork.create(['ada', 'neon'], { admins: ['ada'] }); + const neon = await net.viewer('neon'); + + await net.app.profiles.save(neon, { + basics: { name: 'Neon', location: BERLIN }, + performer: { genres: ['techno'] }, + avatar: 'keep', + swap: null + }); + await net.app.djListings.list(await net.viewer('ada'), neon.did); + }); + afterAll(async () => { + await net?.close(); + }); + + /** The DJs Find DJs lists, by DID. */ + const listed = async () => + (await net.app.performers.search({})).items.flatMap((item) => (item.kind === 'dj' ? [item.dj.profile.did] : [])); + + /** Checks the directory's accounts again as if half an hour had passed, so each one's PDS is asked. */ + const checkLater = async () => { + const now = Date.now(); + vi.spyOn(Date, 'now').mockReturnValue(now + LATER_MS); + + try { + await net.app.accountStatuses.refresh(); + } finally { + vi.restoreAllMocks(); + } + }; + + it("leaves a deactivated DJ out of Find DJs and says their page isn't active, until they come back", async () => { + const neon = net.user('neon'); + + const page = () => + callRoute(profilePage, { app: net.app, params: { handle: neon.handle }, url: `/@${neon.handle}` }); + + await neon.agent.com.atproto.server.deactivateAccount({}); + await net.app.accountStatuses.refresh(); + + expect(await listed()).toEqual([]); + await expect(page()).rejects.toMatchObject({ status: 404, body: { title: "This account isn't active" } }); + + await neon.agent.com.atproto.server.activateAccount(); + await checkLater(); + + expect(await listed()).toEqual([neon.did]); + await expect(page()).resolves.toMatchObject({ name: 'Neon' }); + }); +}); diff --git a/docs/adr/0020-inactive-accounts-are-asked-of-their-pds.md b/docs/adr/0020-inactive-accounts-are-asked-of-their-pds.md new file mode 100644 index 000000000..c31168e24 --- /dev/null +++ b/docs/adr/0020-inactive-accounts-are-asked-of-their-pds.md @@ -0,0 +1,17 @@ +# Inactive accounts are asked of their PDS when a page needs to know + +An account that's deactivated, taken down, suspended or deleted shouldn't stay on the site: its profile, its listing in Find DJs, the sets the charts count, its shows. The website reads public records only through HappyView, and HappyView already follows Jetstream's `account` events: at the version production runs (3.0.0-beta.14) it removes the records of an account that's deleted, taken down or suspended and keeps a tombstone that refuses later copies ([`account_event` in src/ingest.rs](https://github.com/gamesgamesgamesgamesgames/happyview/blob/v3.0.0-beta.14/src/ingest.rs), [event logs guide](https://github.com/gamesgamesgamesgamesgames/happyview/blob/v3.0.0-beta.14/packages/docs/content/docs/guides/event-logs.md)). It keeps a deactivated account's records, though, and only logs the event, and no script or query can see an account's status. When a taken-down account comes back, its records return only with a new backfill. + +So the app asks the account's PDS, the one its DID document names, with `com.atproto.sync.getRepoStatus`. `AccountStatuses` (`src/lib/server/atproto/account-status.ts`) keeps each answer in memory for half an hour. A profile or set page asks for its one account: an inactive account's page answers 404 saying the account isn't active, whatever the reason, and a deleted one's 410. For Find DJs, the charts, artist pages, linked sets and show listings, it checks every account the directory reads (the managers of the root's projects and the DJs staff list), eight at a time, and passes the inactive ones to those queries as an `inactive` param. The queries leave out those accounts' records. Only the first check after a start is waited for. After that a page gets the last list while a fresh one is made in the background, so no page waits on someone else's PDS. + +A PDS that can't be asked leaves the account as it was last seen, or active if it was never seen, and the failure is logged: the site fails open. A deleted account stays deleted in memory, and HappyView has removed its records for good, so no table is kept. When an account that was taken down or suspended turns up active again, the app has HappyView re-read its records. + +The cost is one request per directory account every half hour, and only while people look at the pages. A deactivated account leaves the lists, and comes back, up to half an hour late. + +## Considered options + +- Jetstream's `account` events through HappyView: they already handle deletions and takedowns, but HappyView keeps a deactivated account's records and offers no hook or table that tells the app. HappyView is a hosted service we don't develop, so changing that isn't ours to do. +- A subscriber of our own to Jetstream's or the relay's account events: changes would show at once, but it's a connection to keep up, a cursor to store, and a table of statuses that's cheap to fetch again. +- Asking a relay's `getRepoStatus` instead of each PDS: one host for every account and it sees a relay's own takedowns, but it ties the site to Bluesky's relay, and the dev network and the integration tests have none. +- Filtering after each query instead of passing `inactive` in: the charts and artist pages count plays across accounts, so they can't be fixed up afterwards, and Find DJs would page wrong. +- A table of deleted accounts: HappyView's tombstone already keeps their records out, and a deleted account's PDS keeps answering `RepoNotFound`. diff --git a/lexicons/computer/localnetwork/directory/getArtist.json b/lexicons/computer/localnetwork/directory/getArtist.json index 11a161501..46f5d2516 100644 --- a/lexicons/computer/localnetwork/directory/getArtist.json +++ b/lexicons/computer/localnetwork/directory/getArtist.json @@ -17,6 +17,12 @@ "type": "string", "maxLength": 2560, "description": "The artist's name, in any case, when there's no mbid. It finds the artist sets credit under that name: the name alone when some sets give it no MBID, otherwise the MBID sets give it." + }, + "inactive": { + "type": "array", + "maxLength": 100, + "items": { "type": "string", "format": "did" }, + "description": "Accounts that aren't active (deactivated, taken down, suspended or deleted), whose sets don't count." } } }, diff --git a/lexicons/computer/localnetwork/directory/getCharts.json b/lexicons/computer/localnetwork/directory/getCharts.json index 7362e0303..024679a94 100644 --- a/lexicons/computer/localnetwork/directory/getCharts.json +++ b/lexicons/computer/localnetwork/directory/getCharts.json @@ -37,6 +37,12 @@ "maximum": 100, "default": 50, "description": "The most tracks, and the most artists." + }, + "inactive": { + "type": "array", + "maxLength": 100, + "items": { "type": "string", "format": "did" }, + "description": "Accounts that aren't active (deactivated, taken down, suspended or deleted), whose sets don't count." } } }, diff --git a/lexicons/computer/localnetwork/directory/getSets.json b/lexicons/computer/localnetwork/directory/getSets.json index 9ed76474c..6c583b52b 100644 --- a/lexicons/computer/localnetwork/directory/getSets.json +++ b/lexicons/computer/localnetwork/directory/getSets.json @@ -9,7 +9,13 @@ "type": "params", "required": ["uris"], "properties": { - "uris": { "type": "array", "maxLength": 25, "items": { "type": "string", "format": "at-uri" } } + "uris": { "type": "array", "maxLength": 25, "items": { "type": "string", "format": "at-uri" } }, + "inactive": { + "type": "array", + "maxLength": 100, + "items": { "type": "string", "format": "did" }, + "description": "Accounts that aren't active (deactivated, taken down, suspended or deleted), whose sets are left out." + } } }, "output": { diff --git a/lexicons/computer/localnetwork/directory/listShows.json b/lexicons/computer/localnetwork/directory/listShows.json index c387c4fe9..b7a791c26 100644 --- a/lexicons/computer/localnetwork/directory/listShows.json +++ b/lexicons/computer/localnetwork/directory/listShows.json @@ -34,7 +34,13 @@ "description": "distance needs latE6 and lngE6." }, "limit": { "type": "integer", "minimum": 1, "maximum": 100, "default": 30 }, - "cursor": { "type": "string", "maxLength": 512 } + "cursor": { "type": "string", "maxLength": 512 }, + "inactive": { + "type": "array", + "maxLength": 100, + "items": { "type": "string", "format": "did" }, + "description": "Accounts that aren't active (deactivated, taken down, suspended or deleted), whose shows are left out." + } } }, "output": { diff --git a/lexicons/computer/localnetwork/directory/searchArtists.json b/lexicons/computer/localnetwork/directory/searchArtists.json index c33afb69e..45d6bfd1f 100644 --- a/lexicons/computer/localnetwork/directory/searchArtists.json +++ b/lexicons/computer/localnetwork/directory/searchArtists.json @@ -13,7 +13,13 @@ "maxLength": 100, "description": "Text to find anywhere in the artist's name, in any case. Without it, every artist." }, - "limit": { "type": "integer", "minimum": 1, "maximum": 50, "default": 25 } + "limit": { "type": "integer", "minimum": 1, "maximum": 50, "default": 25 }, + "inactive": { + "type": "array", + "maxLength": 100, + "items": { "type": "string", "format": "did" }, + "description": "Accounts that aren't active (deactivated, taken down, suspended or deleted), whose sets don't count." + } } }, "output": { diff --git a/lexicons/computer/localnetwork/directory/searchPerformers.json b/lexicons/computer/localnetwork/directory/searchPerformers.json index 63d1dcd5a..76ec56d8b 100644 --- a/lexicons/computer/localnetwork/directory/searchPerformers.json +++ b/lexicons/computer/localnetwork/directory/searchPerformers.json @@ -59,7 +59,13 @@ }, "sort": { "type": "string", "maxLength": 32, "knownValues": ["relevance", "distance", "recent", "name"] }, "limit": { "type": "integer", "minimum": 1, "maximum": 60, "default": 24 }, - "cursor": { "type": "string", "maxLength": 512 } + "cursor": { "type": "string", "maxLength": 512 }, + "inactive": { + "type": "array", + "maxLength": 100, + "items": { "type": "string", "format": "did" }, + "description": "Accounts that aren't active (deactivated, taken down, suspended or deleted). A listed DJ among them is left out, and so is a solo project they alone manage." + } } }, "output": { From 5b090cdee58a23c2fb7f85859124140b879920f9 Mon Sep 17 00:00:00 2001 From: botandbang <337765928+botandbang@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:58:15 -0600 Subject: [PATCH 06/22] feat(web): set up paraglide with english and an en-xa pseudo-locale ADR 0019 records what is cheap to decide now and expensive after launch: English URLs stay unprefixed, records carry their language and no English prose, and the language preference, slugs, the sidecar's locale and CSS directions each get a rule. Paraglide JS compiles apps/web/messages into src/lib/paraglide. The locale comes from the ln_locale cookie, the page gets lang and dir, and format.ts formats in the reader's locale. en-XA is generated from en.json by scripts/pseudo-locale.ts. The skip link and footer move to the catalog. CI runs inlang check, and ast-grep's no-raw-text rule fails on words written into a component that has moved. Every test runner pins en-US and UTC. Free-text records gain an optional langs field, the shape app.bsky.feed.post uses, which the web app writes as the writer's language and keeps while the text is unchanged. Fixes LOC-814 Budget-Raise: web/initial_js +3560: this branch grows every page's JavaScript by 4,584 bytes uncompressed (181,916 to 186,500 in production builds of main and the branch), mostly Paraglide's runtime and the footer's messages --- .github/workflows/web-ci.yml | 4 + apps/web/README.md | 19 +- apps/web/docs/diagrams/press-kits.md | 3 +- apps/web/docs/diagrams/requests-and-routes.md | 5 +- apps/web/messages/en-XA.json | 13 + apps/web/messages/en.json | 13 + apps/web/package.json | 11 +- apps/web/playwright.config.ts | 9 +- apps/web/project.inlang/paraglide.config.ts | 17 + apps/web/project.inlang/settings.json | 9 + apps/web/scripts/pseudo-locale.test.ts | 60 ++ apps/web/scripts/pseudo-locale.ts | 55 ++ apps/web/src/app.html | 2 +- apps/web/src/hooks.server.test.ts | 30 + apps/web/src/hooks.server.ts | 38 +- apps/web/src/lib/epk-schema.ts | 5 +- apps/web/src/lib/format.test.ts | 32 ++ apps/web/src/lib/format.ts | 38 +- apps/web/src/lib/locale.test.ts | 20 + apps/web/src/lib/locale.ts | 11 + apps/web/src/lib/server/langs.test.ts | 20 + apps/web/src/lib/server/langs.ts | 38 ++ .../src/lib/server/services/bookings.test.ts | 17 + apps/web/src/lib/server/services/bookings.ts | 8 +- .../lib/server/services/epk-drafts.test.ts | 35 ++ .../web/src/lib/server/services/epk-drafts.ts | 27 +- .../web/src/lib/server/services/epk-fields.ts | 6 + apps/web/src/lib/server/services/epk.test.ts | 8 + apps/web/src/lib/server/services/epk.ts | 3 +- .../src/lib/server/services/events.test.ts | 19 + apps/web/src/lib/server/services/events.ts | 3 + .../web/src/lib/server/services/flags.test.ts | 15 + apps/web/src/lib/server/services/flags.ts | 22 +- .../src/lib/server/services/listings.test.ts | 1 + apps/web/src/lib/server/services/listings.ts | 7 +- .../src/lib/server/services/parties.test.ts | 2 + apps/web/src/lib/server/services/parties.ts | 8 +- .../src/lib/server/services/party-index.ts | 4 +- .../lib/server/services/performer-index.ts | 5 +- .../src/lib/server/services/planner.test.ts | 23 + apps/web/src/lib/server/services/planner.ts | 13 +- .../src/lib/server/services/profiles.test.ts | 28 + apps/web/src/lib/server/services/profiles.ts | 10 + .../src/lib/server/services/project-admin.ts | 7 +- .../src/lib/server/services/projects.test.ts | 29 + apps/web/src/lib/server/services/projects.ts | 19 +- .../src/lib/server/services/requests.test.ts | 19 + apps/web/src/lib/server/services/requests.ts | 26 +- .../lib/server/services/shared-spaces.test.ts | 25 + .../src/lib/server/services/shared-spaces.ts | 9 +- .../lib/server/services/space-joins.test.ts | 10 + .../src/lib/server/services/space-joins.ts | 5 +- .../web/src/lib/server/services/staff.test.ts | 13 + apps/web/src/lib/server/services/staff.ts | 23 +- apps/web/src/lib/test-locale.svelte.test.ts | 8 + apps/web/src/lib/test-locale.test.ts | 8 + apps/web/src/lib/testing/locale.ts | 18 + apps/web/src/lib/types.ts | 16 + apps/web/src/routes/+layout.svelte | 17 +- apps/web/src/routes/layout.svelte.test.ts | 14 +- apps/web/src/writing.test.ts | 4 + apps/web/vite.config.ts | 28 +- ...efixed-and-records-carry-their-language.md | 28 + knip.jsonc | 15 +- .../localnetwork/booking/inquiry.json | 6 + .../localnetwork/booking/message.json | 6 + .../computer/localnetwork/booking/status.json | 6 + lexicons/computer/localnetwork/epk.json | 6 + .../computer/localnetwork/epk/content.json | 6 + lexicons/computer/localnetwork/epk/draft.json | 6 + .../computer/localnetwork/epk/request.json | 6 + lexicons/computer/localnetwork/event.json | 6 + lexicons/computer/localnetwork/listing.json | 6 + .../localnetwork/moderation/decision.json | 6 + .../localnetwork/moderation/request.json | 6 + lexicons/computer/localnetwork/party.json | 6 + .../computer/localnetwork/people/invite.json | 6 + .../computer/localnetwork/people/request.json | 6 + lexicons/computer/localnetwork/performer.json | 6 + .../localnetwork/performer/details.json | 6 + .../computer/localnetwork/planner/save.json | 6 + .../computer/localnetwork/planner/show.json | 6 + lexicons/computer/localnetwork/profile.json | 6 + lexicons/computer/localnetwork/project.json | 6 + .../localnetwork/project/details.json | 6 + .../computer/localnetwork/staff/group.json | 6 + .../computer/localnetwork/staff/role.json | 6 + pnpm-lock.yaml | 526 ++++++++++++++++++ tools/ast-grep/rules/no-raw-text.yml | 28 + tools/ast-grep/tests/no-raw-text-test.yml | 28 + 90 files changed, 1693 insertions(+), 84 deletions(-) create mode 100644 apps/web/messages/en-XA.json create mode 100644 apps/web/messages/en.json create mode 100644 apps/web/project.inlang/paraglide.config.ts create mode 100644 apps/web/project.inlang/settings.json create mode 100644 apps/web/scripts/pseudo-locale.test.ts create mode 100644 apps/web/scripts/pseudo-locale.ts create mode 100644 apps/web/src/lib/locale.test.ts create mode 100644 apps/web/src/lib/locale.ts create mode 100644 apps/web/src/lib/server/langs.test.ts create mode 100644 apps/web/src/lib/server/langs.ts create mode 100644 apps/web/src/lib/test-locale.svelte.test.ts create mode 100644 apps/web/src/lib/test-locale.test.ts create mode 100644 apps/web/src/lib/testing/locale.ts create mode 100644 docs/adr/0019-english-stays-unprefixed-and-records-carry-their-language.md create mode 100644 tools/ast-grep/rules/no-raw-text.yml create mode 100644 tools/ast-grep/tests/no-raw-text-test.yml diff --git a/.github/workflows/web-ci.yml b/.github/workflows/web-ci.yml index ff8d81cb7..4a58b84dd 100644 --- a/.github/workflows/web-ci.yml +++ b/.github/workflows/web-ci.yml @@ -96,6 +96,10 @@ jobs: working-directory: . run: pnpm lexicons:format --check - run: pnpm lint + # The message catalogs (messages/, project.inlang): every message in each locale, with the + # variables and plural forms English has. Words written into a migrated component instead of + # the catalog are ast-grep's no-raw-text, in repo-checks.yml. + - run: pnpm i18n:check - run: pnpm check - run: pnpm -w knip # No --with-deps, here or below: the runner has the libraries Chromium needs, and the fonts it diff --git a/apps/web/README.md b/apps/web/README.md index d744c93d2..ee05ceb9c 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -222,7 +222,7 @@ A mix whose link is a plyr.fm track (`https://plyr.fm/track/`) also gets a ` ### Sync -The app is a space syncer. For each watched space it asks the space host (the authority's PDS) for a space credential with `authorizeSpaceSync`, sending a fresh delegation token from the root's PDS and the `did:key` of a new P-256 key the credential is bound to, and signs every request with that key (RFC 9421). It enumerates writers with `listWriters`, pulls each repo's oplog with `listRepoOps`, and checks the result against the repo's LtHash commit, falling back to a full download (`getRepo`, a STAR archive) when needed. A repo the listing says left the writer set (a member removed, or no longer allowed to write) keeps the records already synced from it. Commits and records aren't signed: the repo host MACs the commit or record header of each response (an HTTP message signature) with a secret shared for that one request, derived from the author's `#atproto_kem` key. When a MAC fails, the app refetches the author's DID document once, in case the key rotated. Accounts whose DID document has no KEM key can't be synced, and the system page says so. A deleted space is dropped with everything derived from it, however often the authority says so, and a space recreated under the same URI syncs from scratch. A repo that fails doesn't hold back the others: the pass carries on through the space's later pages, and the repo is retried on its own, after a minute at first and at most an hour once it keeps failing. A writer whose account is taken down, suspended, or deactivated is skipped the same way without failing the pass, and the system page shows why. A space whose authority is taken down or deactivated is only suspended, so its local copy stays. A record whose projection into the app's tables fails, such as an inquiry read while the directory is down, waits on the same schedule and shows on the system page until it goes through ([ADR 0009](../../docs/adr/0009-synced-records-queue-for-projection.md)). It also registers for each watched space's updates, and polls. Each credential request names the app's `PUBLIC_URL` and a random token the app keeps for that space; the host checks both with `confirmRegistration` before registering, and the registration lasts as long as the credential, so polling keeps it up. The host posts each update to `notifySpaceUpdate` with that token, and the app syncs the space. A notice that the space was deleted or the registration lapsed makes the app ask for a fresh credential first, and only the authority refusing it with `SpaceDeleted` drops the space. A host that can't confirm the endpoint leaves the space on polling. Records are validated against the lexicons, and authority rules are enforced: only root-authored decisions, roles, and details count, a press kit's grants count only from their space's authority (in a project's request space, only for a press kit of that project) and drafts only from the project's current managers, a booking thread's project comes from the root's opening record (or the root's audit copy of its creation) rather than the inquiry, the show announced from it only from the root's status records, booking records from non-participants are ignored, and a booking status record counts only when the thread's rules allow its author that move ([ADR 0008](../../docs/adr/0008-booking-status-follows-the-rules-not-record-dates.md)). +The app is a space syncer. For each watched space it asks the space host (the authority's PDS) for a space credential with `authorizeSpaceSync`, sending a fresh delegation token from the root's PDS and the `did:key` of a new P-256 key the credential is bound to, and signs every request with that key (RFC 9421). It enumerates writers with `listWriters`, pulls each repo's oplog with `listRepoOps`, and checks the result against the repo's LtHash commit, falling back to a full download (`getRepo`, a STAR archive, read up to 256 MiB) when needed. A record nested deeper than 32 levels is left out of the local copy, whichever way it arrives. A repo the listing says left the writer set (a member removed, or no longer allowed to write) keeps the records already synced from it. Commits and records aren't signed: the repo host MACs the commit or record header of each response (an HTTP message signature) with a secret shared for that one request, derived from the author's `#atproto_kem` key. When a MAC fails, the app refetches the author's DID document once, in case the key rotated. Accounts whose DID document has no KEM key can't be synced, and the system page says so. A deleted space is dropped with everything derived from it, however often the authority says so, and a space recreated under the same URI syncs from scratch. A repo that fails doesn't hold back the others: the pass carries on through the space's later pages, and the repo is retried on its own, after a minute at first and at most an hour once it keeps failing. A writer whose account is taken down, suspended, or deactivated is skipped the same way without failing the pass, and the system page shows why. A space whose authority is taken down or deactivated is only suspended, so its local copy stays. A record whose projection into the app's tables fails, such as an inquiry read while the directory is down, waits on the same schedule and shows on the system page until it goes through ([ADR 0009](../../docs/adr/0009-synced-records-queue-for-projection.md)). It also registers for each watched space's updates, and polls. Each credential request names the app's `PUBLIC_URL` and a random token the app keeps for that space; the host checks both with `confirmRegistration` before registering, and the registration lasts as long as the credential, so polling keeps it up. The host posts each update to `notifySpaceUpdate` with that token, and the app syncs the space. A notice that the space was deleted or the registration lapsed makes the app ask for a fresh credential first, and only the authority refusing it with `SpaceDeleted` drops the space. A host that can't confirm the endpoint leaves the space on polling. Records are validated against the lexicons, and authority rules are enforced: only root-authored decisions, roles, and details count, a press kit's grants count only from their space's authority (in a project's request space, only for a press kit of that project) and drafts only from the project's current managers, a booking thread's project comes from the root's opening record (or the root's audit copy of its creation) rather than the inquiry, the show announced from it only from the root's status records, booking records from non-participants are ignored, and a booking status record counts only when the thread's rules allow its author that move ([ADR 0008](../../docs/adr/0008-booking-status-follows-the-rules-not-record-dates.md)). ### Directory @@ -293,6 +293,7 @@ The network is temporary; Ctrl-C stops it, and restarting resets everything (and | `pnpm build` / `pnpm start` | Production build (adapter-node) / run it | | `pnpm check` | `svelte-check` with TypeScript 6, after `pnpm lexicons:types` | | `pnpm lint` | Oxlint with type-aware rules (tsgolint) and the anti-slop plugin, then the story check | +| `pnpm i18n:check` | `inlang check` on the message catalogs ([Translation](#translation)) | | `pnpm format` / `pnpm format:check` | Oxfmt | | `pnpm test` | Unit tests (Node) + component tests (Vitest browser mode, Chromium) | | `pnpm test:integration` | Full flows against an in-process spaces PDS and a HappyView container | @@ -442,10 +443,22 @@ The services are in [`src/lib/server/token-exchange/services.json`](src/lib/serv - The [token exchange](#token-exchange) only sends requests to the token endpoints `services.json` lists, and never logs what it relays. - Spaces are access control, not end-to-end encryption: the hosting PDSes and this app can read the data they handle. +## Translation + +The site is in English, and ready for a second language ([ADR 0019](../../docs/adr/0019-english-stays-unprefixed-and-records-carry-their-language.md)). Its words live in `messages/en.json`, and a component shows one by calling its message: `import { m } from '#lib/paraglide/messages.js'`, then `{m.footer_privacy()}`. [Paraglide JS](https://paraglidejs.com) compiles the catalogs (`project.inlang/`) into `src/lib/paraglide/`, which git ignores, in the dev server, builds and tests, and in `pnpm check` and `pnpm install`. So far only the root layout's footer and skip link come from the catalog. The dates and numbers `src/lib/format.ts` writes follow the same locale. + +To add a string, put it in `messages/en.json`, run `node scripts/pseudo-locale.ts` to regenerate `messages/en-XA.json`, and call `m.()`. A test fails while en-XA is out of date, `pnpm i18n:check` fails on a message a locale lacks or a variable it gets wrong, and ast-grep's `no-raw-text` rule fails on words written into the markup of a component that has moved to the catalog. Add a component to that rule's `files` once its text has moved. + +To see the pseudo-locale, run `document.cookie = 'ln_locale=en-XA; path=/'` in the browser's console and reload (`ln_locale=en` goes back). en-XA accents every letter, makes each line about a third longer and brackets each message, so plain English on the page is text that hasn't moved to the catalog, and a clipped or missing bracket is a layout that can't stretch or a message cut short. + +Tests run in en-US and UTC whatever the machine's settings: `vite.config.ts` pins Vitest's and `playwright.config.ts` the end-to-end tests'. + ## Project layout ``` lua/ HappyView scripts: the record gates and the directory queries, one file per NSID +messages/ The message catalogs: en.json, and en-XA.json generated from it (Translation) +project.inlang/ The inlang project Paraglide compiles the catalogs from, and Paraglide's config scripts/ dev-network (local atproto network), publish-lexicons, seed data, mix-fixture, db-backup scripts/lib/ Local HappyView container and Jetstream stand-in src/lib/ Shared code: matching, genre taxonomy, geo, formatting, components @@ -613,7 +626,7 @@ flowchart TD Bucket[("Bucket: database backups")] end subgraph Client["In the browser"] - Cookies["Cookies: ln_session, ln_signed_out,
ln_flag_preview, the city picked last for shows"] + Cookies["Cookies: ln_session, ln_signed_out,
ln_flag_preview, ln_locale,
the city picked last for shows"] Local["localStorage: unsent form drafts,
the hotkeys preference"] end Repos -- "Jetstream, re-reads" --> HV @@ -624,7 +637,7 @@ flowchart TD Outbox -- "daily" --> Bucket ``` -Source: [`src/lib/server/db/schema.ts`](src/lib/server/db/schema.ts), [`src/lib/server/sync/engine.ts`](src/lib/server/sync/engine.ts), [`src/lib/server/config.ts`](src/lib/server/config.ts), [`src/lib/form-draft.svelte.ts`](src/lib/form-draft.svelte.ts), [`src/lib/server/shows-place.ts`](src/lib/server/shows-place.ts), [`src/lib/server/flags/preview.ts`](src/lib/server/flags/preview.ts) +Source: [`src/lib/server/db/schema.ts`](src/lib/server/db/schema.ts), [`src/lib/server/sync/engine.ts`](src/lib/server/sync/engine.ts), [`src/lib/server/config.ts`](src/lib/server/config.ts), [`src/lib/form-draft.svelte.ts`](src/lib/form-draft.svelte.ts), [`src/lib/server/shows-place.ts`](src/lib/server/shows-place.ts), [`src/lib/server/flags/preview.ts`](src/lib/server/flags/preview.ts), [`project.inlang/paraglide.config.ts`](project.inlang/paraglide.config.ts) ### Local tables: bookings and press kits diff --git a/apps/web/docs/diagrams/press-kits.md b/apps/web/docs/diagrams/press-kits.md index c9aedccbe..83bd2d97b 100644 --- a/apps/web/docs/diagrams/press-kits.md +++ b/apps/web/docs/diagrams/press-kits.md @@ -21,12 +21,13 @@ sequenceDiagram participant R as Root's repo participant K as Press kit's space M->>A: Save, over the version
the form opened on - A->>B: epk.draft: changed fields
and what they replace + A->>B: epk.draft: changed fields, what they
replace, and the writer's languages
when it changes words M->>A: Publish A->>A: Compare each field
with what's published now alt Another manager changed the field A-->>M: Conflict, pick a
side per field else + Note over A,K: epk and epk.content each take the draft's
languages only when it changes their words A->>R: Copy new photos,
put epk over the live CID A->>A: Wait up to 5 s
for HappyView A->>K: Root writes epk.content diff --git a/apps/web/docs/diagrams/requests-and-routes.md b/apps/web/docs/diagrams/requests-and-routes.md index b68553831..2392adb96 100644 --- a/apps/web/docs/diagrams/requests-and-routes.md +++ b/apps/web/docs/diagrams/requests-and-routes.md @@ -35,11 +35,12 @@ flowchart TD Flags --> Guard["guardArea by route"] Guard -- "/dashboard or /admin,
signed out" --> Login["303 to /login?next="] Guard -- "/admin, not staff" --> Refused["403"] - Guard --> Route["Load, action or endpoint,
page CSP with a nonce"] + Guard --> Locale["Locale from ln_locale,
English without it"] + Locale --> Route["Load, action or endpoint,
page CSP with a nonce,
the page's lang and dir"] Route --> Out["gzip, security headers,
noindex on unlisted areas,
the one log line for the request"] ``` -Source: [`src/hooks.server.ts`](../../src/hooks.server.ts), [`src/lib/server/moved-pages.ts`](../../src/lib/server/moved-pages.ts), [`src/lib/server/http.ts`](../../src/lib/server/http.ts), [`src/lib/server/services/flags.ts`](../../src/lib/server/services/flags.ts), [`src/lib/server/compress.ts`](../../src/lib/server/compress.ts), [`src/lib/server/logger.ts`](../../src/lib/server/logger.ts), [`vite.config.ts`](../../vite.config.ts) +Source: [`src/hooks.server.ts`](../../src/hooks.server.ts), [`src/lib/server/moved-pages.ts`](../../src/lib/server/moved-pages.ts), [`src/lib/server/http.ts`](../../src/lib/server/http.ts), [`src/lib/server/services/flags.ts`](../../src/lib/server/services/flags.ts), [`src/lib/server/compress.ts`](../../src/lib/server/compress.ts), [`src/lib/server/logger.ts`](../../src/lib/server/logger.ts), [`vite.config.ts`](../../vite.config.ts), [`project.inlang/paraglide.config.ts`](../../project.inlang/paraglide.config.ts) ## Page loads and form actions diff --git a/apps/web/messages/en-XA.json b/apps/web/messages/en-XA.json new file mode 100644 index 000000000..18d7b5fb4 --- /dev/null +++ b/apps/web/messages/en-XA.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://inlang.com/schema/inlang-message-format", + "skip_to_content": "[Şķīƥ ŧǿǿ ƈǿǿƞŧḗḗƞŧ]", + "footer_how_it_works": "[Ħǿǿẇ īŧ ẇǿǿřķş]", + "footer_who_its_for": "[Ẇħǿǿ īŧ'ş ƒǿǿř]", + "footer_privacy": "[Ƥřīṽȧȧƈẏ]", + "footer_tools": "[Ŧǿǿǿǿŀş]", + "footer_report_bug": "[Řḗḗƥǿǿřŧ ȧȧ ƀŭŭɠ]", + "footer_report_bug_github": "[Řḗḗƥǿǿřŧ ȧȧ ƀŭŭɠ ǿǿƞ ƓīŧĦŭŭƀ]", + "footer_shortcuts_on": "[Ķḗḗẏƀǿǿȧȧřḓ şħǿǿřŧƈŭŭŧş: ǿǿƞ]", + "footer_shortcuts_off": "[Ķḗḗẏƀǿǿȧȧřḓ şħǿǿřŧƈŭŭŧş: ǿǿƒƒ]", + "footer_tagline": "[Řḗḗƈǿǿřḓş ǿǿƞ ŧħḗḗ ȦȦŦ Ƥřǿǿŧǿǿƈǿǿŀ · ƥřīṽȧȧŧḗḗ ḓȧȧŧȧȧ īƞ şƥȧȧƈḗḗş ǿǿƞŀẏ ŧħḗḗīř ḿḗḗḿƀḗḗřş ƈȧȧƞ řḗḗȧȧḓ]" +} diff --git a/apps/web/messages/en.json b/apps/web/messages/en.json new file mode 100644 index 000000000..d61a1d270 --- /dev/null +++ b/apps/web/messages/en.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://inlang.com/schema/inlang-message-format", + "skip_to_content": "Skip to content", + "footer_how_it_works": "How it works", + "footer_who_its_for": "Who it's for", + "footer_privacy": "Privacy", + "footer_tools": "Tools", + "footer_report_bug": "Report a bug", + "footer_report_bug_github": "Report a bug on GitHub", + "footer_shortcuts_on": "Keyboard shortcuts: on", + "footer_shortcuts_off": "Keyboard shortcuts: off", + "footer_tagline": "Records on the AT Protocol · private data in spaces only their members can read" +} diff --git a/apps/web/package.json b/apps/web/package.json index 2e3a4e5bf..c7e7f6957 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -18,11 +18,12 @@ "build": "vite build", "preview": "vite preview", "start": "node build", - "prepare": "(svelte-kit sync && node scripts/flag-keys.ts && node scripts/notification-kinds.ts && pnpm lexicons:types) || echo ''", - "check": "svelte-kit sync && node scripts/flag-keys.ts && node scripts/notification-kinds.ts && pnpm lexicons:types && svelte-check --tsconfig ./tsconfig.json", - "check:watch": "svelte-kit sync && node scripts/flag-keys.ts && node scripts/notification-kinds.ts && pnpm lexicons:types && svelte-check --tsconfig ./tsconfig.json --watch", + "prepare": "(svelte-kit sync && paraglide-js compile --silent && node scripts/flag-keys.ts && node scripts/notification-kinds.ts && pnpm lexicons:types) || echo ''", + "check": "svelte-kit sync && paraglide-js compile --silent && node scripts/flag-keys.ts && node scripts/notification-kinds.ts && pnpm lexicons:types && svelte-check --tsconfig ./tsconfig.json", + "check:watch": "svelte-kit sync && paraglide-js compile --silent && node scripts/flag-keys.ts && node scripts/notification-kinds.ts && pnpm lexicons:types && svelte-check --tsconfig ./tsconfig.json --watch", "lint": "oxlint --type-aware && node scripts/story-coverage.ts", "lint:fix": "oxlint --type-aware --fix", + "i18n:check": "inlang check --project ./project.inlang", "format": "oxfmt", "format:check": "oxfmt --check", "test": "vitest run --project server --project client", @@ -92,6 +93,9 @@ "@atproto/sync": "0.0.0-spaces-alpha-20261113224550", "@axe-core/playwright": "^4.13.0", "@electric-sql/pglite": "^0.5.16", + "@inlang/cli": "^3.6.0", + "@inlang/paraglide-js": "^3.2.2", + "@inlang/plugin-message-format": "^4.6.0", "@jazzer.js/core": "^4.0.0", "@lhci/cli": "^0.16.0", "@playwright/test": "^1.63.0", @@ -126,6 +130,7 @@ "oxlint": "1.86.0", "oxlint-tsgolint": "^7.0.2003", "playwright": "^1.63.0", + "pseudo-localization": "^3.1.3", "storybook": "10.6.2", "svelte": "^5.57.1", "svelte-check": "^4.6.0", diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.ts index 453a26646..4c62d15e0 100644 --- a/apps/web/playwright.config.ts +++ b/apps/web/playwright.config.ts @@ -17,7 +17,10 @@ export default defineConfig({ use: { baseURL: `http://127.0.0.1:${APP_PORT}`, trace: 'retain-on-failure', - screenshot: 'only-on-failure' + screenshot: 'only-on-failure', + // One locale and time zone, whatever the machine's, as vite.config.ts pins for Vitest. The server below too. + locale: 'en-US', + timezoneId: 'UTC' }, // Pull requests run Chromium alone (`--project chromium`); the rest run weekly (web-scheduled.yml). projects: [ @@ -46,7 +49,9 @@ export default defineConfig({ ACTOR_SEARCH: 'none', // The bug report tests post to the stand-in userinput.app space, which is rolled out behind this flag. FLAG_OVERRIDES: 'userinputReports=on', - LOG_LEVEL: 'warn' + LOG_LEVEL: 'warn', + LC_ALL: 'en_US.UTF-8', + TZ: 'UTC' } } }); diff --git a/apps/web/project.inlang/paraglide.config.ts b/apps/web/project.inlang/paraglide.config.ts new file mode 100644 index 000000000..ee60dbb9d --- /dev/null +++ b/apps/web/project.inlang/paraglide.config.ts @@ -0,0 +1,17 @@ +import { defineConfig } from '@inlang/paraglide-js'; + +// Read by both the Vite plugin (dev, build, tests) and `paraglide-js compile` (`pnpm check` and `pnpm install`), so +// both write the same files. +export default defineConfig({ + outdir: './src/lib/paraglide', + // English stays at unprefixed URLs (docs/adr/0019), so the locale comes from a cookie until a second language + // brings the url strategy for its prefix. + strategy: ['cookie', 'baseLocale'], + cookieName: 'ln_locale', + cookieSameSite: 'lax', + // Files on disk rather than Vite's virtual modules: svelte-check and the tsx scripts read them without Vite. + outputStructure: 'message-modules', + emitTsDeclarations: true, + emitReadme: false, + emitPrettierIgnore: false +}); diff --git a/apps/web/project.inlang/settings.json b/apps/web/project.inlang/settings.json new file mode 100644 index 000000000..a3497e3d4 --- /dev/null +++ b/apps/web/project.inlang/settings.json @@ -0,0 +1,9 @@ +{ + "$schema": "https://inlang.com/schema/project-settings", + "baseLocale": "en", + "locales": ["en", "en-XA"], + "modules": ["./node_modules/@inlang/plugin-message-format/dist/index.js"], + "plugin.inlang.messageFormat": { + "pathPattern": "./messages/{locale}.json" + } +} diff --git a/apps/web/scripts/pseudo-locale.test.ts b/apps/web/scripts/pseudo-locale.test.ts new file mode 100644 index 000000000..2d3721e63 --- /dev/null +++ b/apps/web/scripts/pseudo-locale.test.ts @@ -0,0 +1,60 @@ +import { readFileSync } from 'node:fs'; +import * as fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import { type Messages, pseudoFile, pseudoLocalize, SOURCE, TARGET } from './pseudo-locale.ts'; + +describe('pseudoLocalize', () => { + it('accents every letter and brackets the message', () => { + expect(pseudoLocalize({ privacy: 'Privacy' })).toEqual({ privacy: '[Ƥřīṽȧȧƈẏ]' }); + }); + + it('keeps placeholders, markup and escaped braces as written', () => { + const { greeting } = pseudoLocalize({ greeting: 'Hi {name}, see {#link}the guide{/link} \\{not a variable\\}' }); + + expect(greeting).toMatch(/^\[Ħī \{name\}, şḗḗḗḗ \{#link\}ŧħḗḗ ɠŭŭīḓḗḗ\{\/link\} \\\{.+\\\}\]$/); + }); + + it("pseudo-localizes each variant's pattern and keeps its selectors", () => { + const shows: Messages = { + shows: [ + { + declarations: ['input count', 'local n = count: plural'], + selectors: ['n'], + match: { 'n=one': '{count} show', 'n=other': '{count} shows' } + } + ] + }; + + expect(pseudoLocalize(shows)).toEqual({ + shows: [ + { + declarations: ['input count', 'local n = count: plural'], + selectors: ['n'], + match: { 'n=one': '[{count} şħǿǿẇ]', 'n=other': '[{count} şħǿǿẇş]' } + } + ] + }); + }); + + it('leaves no Latin letter outside a placeholder, so English that skipped the catalog stands out', () => { + fc.assert( + fc.property(fc.string(), fc.stringMatching(/^[a-z]\w*$/), fc.string(), (before, name, after) => { + const pattern = `${before.replace(/[{}\\]/g, '')}{${name}}${after.replace(/[{}\\]/g, '')}`; + + // SAFETY: a message given as a pattern comes back as a pattern. + const message = pseudoLocalize({ message: pattern }).message as string; + + expect(message.replace(`{${name}}`, '')).not.toMatch(/[A-Za-z]/); + }) + ); + }); +}); + +describe('messages/en-XA.json', () => { + it('is messages/en.json pseudo-localized', () => { + expect( + readFileSync(TARGET, 'utf8'), + 'messages/en-XA.json is out of date. Regenerate it with `node scripts/pseudo-locale.ts`' + ).toBe(pseudoFile(readFileSync(SOURCE, 'utf8'))); + }); +}); diff --git a/apps/web/scripts/pseudo-locale.ts b/apps/web/scripts/pseudo-locale.ts new file mode 100644 index 000000000..636d65bbf --- /dev/null +++ b/apps/web/scripts/pseudo-locale.ts @@ -0,0 +1,55 @@ +/** + * Writes messages/en-XA.json, the pseudo-locale, from messages/en.json: every letter accented, vowels doubled so lines + * run about a third longer, and each message in brackets. Viewed in en-XA, text that skipped the catalog stays plain + * English, a layout that can't stretch clips, and a message cut short or glued to another loses a bracket. + * + * node scripts/pseudo-locale.ts + * + * scripts/pseudo-locale.test.ts fails while the file is out of date. + */ +import { readFileSync, writeFileSync } from 'node:fs'; +import { pseudoLocalizeString } from 'pseudo-localization'; + +/** A message in inlang's message format: a pattern, or variants that each match a pattern. */ +type Message = string | { declarations?: string[]; selectors?: string[]; match: Record }[]; + +export type Messages = Record; + +// A pattern's `{name}` placeholders, `{#b}` markup and `\{` escapes, which the message format reads, so they stay as +// written. +const SYNTAX = /(\\.|\{[^{}]*\})/; + +const pseudoPattern = (pattern: string) => + `[${pattern + .split(SYNTAX) + .map((part, index) => (index % 2 === 1 ? part : pseudoLocalizeString(part))) + .join('')}]`; + +/** `messages` in en-XA. `$schema` and the variants' selectors stay as they are. */ +export const pseudoLocalize = (messages: Messages): Messages => + Object.fromEntries( + Object.entries(messages).map(([key, message]) => [ + key, + key === '$schema' + ? message + : Array.isArray(message) + ? message.map((variant) => ({ + ...variant, + match: Object.fromEntries( + Object.entries(variant.match).map(([when, pattern]) => [when, pseudoPattern(pattern)]) + ) + })) + : pseudoPattern(message) + ]) + ); + +export const SOURCE = new URL('../messages/en.json', import.meta.url); + +export const TARGET = new URL('../messages/en-XA.json', import.meta.url); + +/** en-XA.json's contents for en.json's. */ +export const pseudoFile = (source: string) => + // SAFETY: en.json is in inlang's message format, which `pnpm i18n:check` loads and checks. + `${JSON.stringify(pseudoLocalize(JSON.parse(source) as Messages), null, '\t')}\n`; + +if (import.meta.main) writeFileSync(TARGET, pseudoFile(readFileSync(SOURCE, 'utf8'))); diff --git a/apps/web/src/app.html b/apps/web/src/app.html index d40052f03..ed217e7f2 100644 --- a/apps/web/src/app.html +++ b/apps/web/src/app.html @@ -1,5 +1,5 @@ - + diff --git a/apps/web/src/hooks.server.test.ts b/apps/web/src/hooks.server.test.ts index 3a7f6bc03..b42c09761 100644 --- a/apps/web/src/hooks.server.test.ts +++ b/apps/web/src/hooks.server.test.ts @@ -11,6 +11,7 @@ import { CRAWLER_HEAD } from '#lib/server/crawler-head.ts'; import { PREVIEW_COOKIE, PREVIEW_MS, sealPreview } from '#lib/server/flags/preview.ts'; import { VISITOR_COOKIE } from '#lib/server/flags/visitor.ts'; import { HappyViewError } from '#lib/server/happyview/client.ts'; +import { m } from '#lib/paraglide/messages.js'; import { requireFlag } from '#lib/server/http.ts'; import { RateLimiter } from '#lib/server/rate-limit.ts'; import { createTestServices } from '#lib/server/testing/core.ts'; @@ -552,6 +553,35 @@ it("writes the page's crawler tags into the head, once, and gzips the page", asy ); }); +it("renders the page in the locale its cookie names, with the page's lang and dir to match", async () => { + const s = await services(); + const { handle } = hooksWith(async () => s.app); + + const resolve = async (_event: RequestEvent, options?: ResolveOptions) => { + const head = `${CRAWLER_HEAD}`; + const html = (await options!.transformPageChunk!({ html: head, done: false })) ?? ''; + + return new Response(`${html}${m.footer_privacy()}`); + }; + + const page = async (headers: Record) => { + const { event } = routeEvent({ url: '/', headers }); + // SAFETY: as above. + const response = await handle({ event: event as never, resolve }); + + return { html: await response.text(), vary: response.headers.get('vary') }; + }; + + expect(await page({ cookie: 'ln_locale=en-XA' })).toEqual({ + html: '[Ƥřīṽȧȧƈẏ]', + vary: 'Cookie' + }); + expect((await page({})).html).toBe('Privacy'); + expect((await page({ cookie: 'ln_locale=xx' })).html).toBe( + 'Privacy' + ); +}); + it("preloads the scripts, styles and the two typefaces' Latin files, and nothing else", async () => { const s = await services(); const { handle } = hooksWith(async () => s.app); diff --git a/apps/web/src/hooks.server.ts b/apps/web/src/hooks.server.ts index 051adada0..97f4a869f 100644 --- a/apps/web/src/hooks.server.ts +++ b/apps/web/src/hooks.server.ts @@ -12,6 +12,8 @@ import { clientIp, guardArea, isUnlisted } from '#lib/server/http.ts'; import { createLogger, type Logger } from '#lib/server/logger.ts'; import { movedTo } from '#lib/server/moved-pages.ts'; import { toolSite } from '#lib/server/tools/site.ts'; +import { getTextDirection } from '#lib/paraglide/runtime.js'; +import { paraglideMiddleware } from '#lib/paraglide/server.js'; const fallbackLogger = createLogger({ level: process.env.LOG_LEVEL ?? 'info', @@ -136,24 +138,34 @@ export function serverHooks({ let headWritten = false; + // Paraglide's middleware runs the page under the locale its cookie names, so messages and getLocale() read + // it. It's handed the request without its body, which it would otherwise clone, keeping a copy of every + // upload: the locale only comes from the headers. + const localeRequest = new Request(event.request.url, { headers: event.request.headers }); + // The two typefaces set every line and differ in width from the system fallbacks, so arriving after // the first paint they moved the whole page (Lighthouse's CLS). Their Latin files are preloaded with // the CSS; the other subsets load only for pages that need them. const response = gzipped( event.request, - await resolve(event, { - preload: ({ type, path }) => - type === 'js' || - type === 'css' || - (type === 'font' && /(instrument-sans|jetbrains-mono)-latin-wght-normal\.[\w-]+\.woff2$/.test(path)), - // The marker is in the first chunk, app.html's head. Later chunks are left alone, whatever they hold. - transformPageChunk: ({ html }) => { - if (headWritten || !html.includes(CRAWLER_HEAD)) return html; - headWritten = true; - - return withCrawlerHead(html, event.locals.crawlerHead); - } - }) + await paraglideMiddleware(localeRequest, ({ locale }) => + resolve(event, { + preload: ({ type, path }) => + type === 'js' || + type === 'css' || + (type === 'font' && /(instrument-sans|jetbrains-mono)-latin-wght-normal\.[\w-]+\.woff2$/.test(path)), + // The marker is in the first chunk, app.html's head, after the html tag's lang and dir. Later chunks are + // left alone, whatever they hold. + transformPageChunk: ({ html }) => { + if (headWritten || !html.includes(CRAWLER_HEAD)) return html; + headWritten = true; + + return withCrawlerHead(html, event.locals.crawlerHead) + .replace('%lang%', locale) + .replace('%dir%', getTextDirection(locale)); + } + }) + ) ); response.headers.set('x-request-id', requestId); diff --git a/apps/web/src/lib/epk-schema.ts b/apps/web/src/lib/epk-schema.ts index c32ad81a5..82ad8ffd3 100644 --- a/apps/web/src/lib/epk-schema.ts +++ b/apps/web/src/lib/epk-schema.ts @@ -36,6 +36,7 @@ export const epkRecordSchema = z.object({ bio: z.string().optional(), mixes: z.array(mix).optional(), photos: z.array(photo).optional(), + langs: z.array(z.string()).optional(), access: z.object({ anyone: rule, promoters: rule, following: rule, bookedWith: rule }), createdAt: z.string(), updatedAt: z.string().optional() @@ -50,6 +51,7 @@ export const epkContentSchema = z.object({ .object({ email: z.string().optional(), phone: z.string().optional(), note: z.string().optional() }) .optional(), techRider: z.string().optional(), + langs: z.array(z.string()).optional(), updatedAt: z.string() }); @@ -57,12 +59,13 @@ export const epkContentSchema = z.object({ export const epkFieldsSchema = epkRecordSchema .pick({ title: true, headline: true, bio: true, mixes: true, photos: true, access: true }) .partial() - .extend({ content: epkContentSchema.omit({ updatedAt: true }).optional() }); + .extend({ content: epkContentSchema.omit({ updatedAt: true, langs: true }).optional() }); export const epkDraftSchema = z.object({ base: z.object({ uri: z.string(), cid: z.string() }).optional(), changes: epkFieldsSchema, previous: epkFieldsSchema.optional(), + langs: z.array(z.string()).optional(), onBehalfOf: z.string().optional(), createdAt: z.string(), updatedAt: z.string() diff --git a/apps/web/src/lib/format.test.ts b/apps/web/src/lib/format.test.ts index 21d8ce549..27938e216 100644 --- a/apps/web/src/lib/format.test.ts +++ b/apps/web/src/lib/format.test.ts @@ -10,12 +10,14 @@ import { hueFor, initials, kindLabel, + nightLabel, placeLabel, pluralize, requestTitle, shortDid, timeAgo } from './format'; +import { inLocale } from './testing/locale.ts'; import { request } from './testing/requests'; import type { ProjectProfile } from './types'; @@ -114,3 +116,33 @@ describe('requestTitle', () => { expect(requestTitle(request('list', { project: null }))).toBe('Listing: @neon.test'); }); }); + +describe("formatting in the reader's locale", () => { + const now = Date.parse('2026-10-04T12:00:00Z'); + + const formatted = () => [ + formatDate('2026-11-14T20:00:00Z', { dateStyle: 'medium', timeZone: 'UTC' }), + formatShowDate('2026-11-14T22:00:00.000Z', true), + nightLabel('2026-11-14T22:00:00.000Z'), + timeAgo('2026-10-04T10:00:00Z', now), + timeAgo('2026-10-04T10:00:00Z', now, 'narrow'), + feeLabel({ tier: 'established', currency: 'EUR', minAmount: 1500, maxAmount: 2500 }), + pluralize(1200, 'show') + ]; + + it('formats as English by default', () => { + expect(formatted()).toEqual([ + 'Nov 14, 2026', + expect.stringMatching(/^Nov 14, 2026, 10:00\sPM$/), + 'Sat 14 Nov', + '2 hours ago', + '2h ago', + 'Established · €1,500–€2,500', + '1,200 shows' + ]); + }); + + it('formats en-XA exactly as English, so the pseudo-locale only changes the words', async () => { + expect(await inLocale('en-XA', formatted)).toEqual(formatted()); + }); +}); diff --git a/apps/web/src/lib/format.ts b/apps/web/src/lib/format.ts index de55fa6c9..9d6dede7b 100644 --- a/apps/web/src/lib/format.ts +++ b/apps/web/src/lib/format.ts @@ -1,3 +1,4 @@ +import { languageOf } from './locale.ts'; import { FEE_TIERS, labelFor, PROJECT_KINDS } from './taxonomy/options'; import type { AccountView, DjSetView, Location, ProjectFee, ProjectProfile, RequestKind, RequestView } from './types'; @@ -52,10 +53,12 @@ export function setHref(uri: string, handle: string | null = null): string { return `${profileHref({ did, handle })}/sets/${rkey}`; } -const RELATIVE = { - long: new Intl.RelativeTimeFormat('en', { numeric: 'auto' }), +// Dates, times and numbers below are in the reader's language (languageOf). + +const RELATIVE: Record<'long' | 'narrow', Intl.RelativeTimeFormatOptions> = { + long: { numeric: 'auto' }, /** "2h ago", for a stamp at the end of a row. */ - narrow: new Intl.RelativeTimeFormat('en', { numeric: 'auto', style: 'narrow' }) + narrow: { numeric: 'auto', style: 'narrow' } }; const UNITS: [Intl.RelativeTimeFormatUnit, number][] = [ @@ -76,7 +79,8 @@ export function timeAgo( const seconds = (Date.parse(iso) - now) / 1000; for (const [unit, size] of UNITS) { - if (Math.abs(seconds) >= size) return RELATIVE[style].format(Math.round(seconds / size), unit); + if (Math.abs(seconds) >= size) + return new Intl.RelativeTimeFormat(languageOf(), RELATIVE[style]).format(Math.round(seconds / size), unit); } return 'just now'; @@ -89,7 +93,7 @@ export function formatDate( if (!iso) return ''; const date = new Date(iso); - return Number.isNaN(date.getTime()) ? '' : new Intl.DateTimeFormat('en', options).format(date); + return Number.isNaN(date.getTime()) ? '' : new Intl.DateTimeFormat(languageOf(), options).format(date); } export function formatDateTime(iso: string | null | undefined): string { @@ -108,9 +112,17 @@ export function formatShowDate(iso: string | null | undefined, withTime = false) /** A datetime written with its venue's UTC offset as a show date: the venue's clock, kept as UTC. */ export const asShowDate = (iso: string): string => `${iso.slice(0, 19)}Z`; -/** A night the way lists lead with it, like "Sat 14 Nov", from a show date, which is in UTC. */ +/** + * A night the way lists lead with it, like "Sat 14 Nov", from a show date, which is in UTC. In English the day comes + * first, as British English writes it; another language takes its own order. + */ export const nightLabel = (iso: string): string => - new Intl.DateTimeFormat('en-GB', { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }) + new Intl.DateTimeFormat(languageOf() === 'en' ? 'en-GB' : languageOf(), { + weekday: 'short', + day: 'numeric', + month: 'short', + timeZone: 'UTC' + }) .format(new Date(iso)) .replace(',', ''); @@ -127,10 +139,12 @@ export function feeLabel(fee: ProjectFee): string { const money = (amount: number) => fee.currency - ? new Intl.NumberFormat('en', { style: 'currency', currency: fee.currency, maximumFractionDigits: 0 }).format( - amount - ) - : amount.toLocaleString('en'); + ? new Intl.NumberFormat(languageOf(), { + style: 'currency', + currency: fee.currency, + maximumFractionDigits: 0 + }).format(amount) + : amount.toLocaleString(languageOf()); const range = fee.minAmount !== undefined && fee.maxAmount !== undefined @@ -184,7 +198,7 @@ export function hueFor(value: string): number { } export function pluralize(count: number, singular: string, plural = `${singular}s`): string { - return `${count.toLocaleString('en')} ${count === 1 ? singular : plural}`; + return `${count.toLocaleString(languageOf())} ${count === 1 ? singular : plural}`; } /** A DJ set in one line: its title (or venue), and the day it was played. */ diff --git a/apps/web/src/lib/locale.test.ts b/apps/web/src/lib/locale.test.ts new file mode 100644 index 000000000..615e80464 --- /dev/null +++ b/apps/web/src/lib/locale.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest'; +import { languageOf, writerLangs } from './locale.ts'; +import { inLocale } from './testing/locale.ts'; + +describe('languageOf', () => { + it("is the request's locale, English when nothing asks for another", async () => { + expect(languageOf()).toBe('en'); + expect(await inLocale('en', () => languageOf())).toBe('en'); + }); + + it('reads the en-XA pseudo-locale as English', async () => { + expect(await inLocale('en-XA', () => languageOf())).toBe('en'); + }); +}); + +describe('writerLangs', () => { + it("tags what someone writes under en-XA as English, since only the pages' words were dressed up", async () => { + expect(await inLocale('en-XA', () => writerLangs())).toEqual(['en']); + }); +}); diff --git a/apps/web/src/lib/locale.ts b/apps/web/src/lib/locale.ts new file mode 100644 index 000000000..a1f28a458 --- /dev/null +++ b/apps/web/src/lib/locale.ts @@ -0,0 +1,11 @@ +import { getLocale, type Locale } from '#lib/paraglide/runtime.js'; + +/** + * The language a locale reads in, for dates, numbers and a record's `langs`: the request's on the server, the cookie's + * in the browser. en-XA only dresses English up to test the pages, so it formats as English, and what someone types + * under it is still English. + */ +export const languageOf = (locale: Locale = getLocale()): string => (locale === 'en-XA' ? 'en' : locale); + +/** The languages of what someone writes, for a record's `langs`: their locale's language. */ +export const writerLangs = (locale?: Locale): string[] => [languageOf(locale)]; diff --git a/apps/web/src/lib/server/langs.test.ts b/apps/web/src/lib/server/langs.test.ts new file mode 100644 index 000000000..77d18933b --- /dev/null +++ b/apps/web/src/lib/server/langs.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest'; +import { editedLangs, withLangs } from './langs'; + +describe('withLangs', () => { + it('names the languages of a record with prose, and none of one whose text is blank or missing', () => { + expect(withLangs(['Doors at eleven', undefined], ['en'])).toEqual({ langs: ['en'] }); + expect(withLangs([' \n', undefined], ['en'])).toEqual({}); + expect(withLangs(['Doors at eleven'], undefined)).toEqual({}); + }); +}); + +describe('editedLangs', () => { + it("keeps the languages prose had while it's the same, and takes the writer's once it changes", () => { + const before = { text: ['Techno am Sonntag'], langs: ['de'] }; + + expect(editedLangs(['Techno am Sonntag'], before, ['en'])).toEqual({ langs: ['de'] }); + expect(editedLangs(['Techno on Sundays'], before, ['en'])).toEqual({ langs: ['en'] }); + expect(editedLangs(['Techno on Sundays'], null, ['en'])).toEqual({ langs: ['en'] }); + }); +}); diff --git a/apps/web/src/lib/server/langs.ts b/apps/web/src/lib/server/langs.ts new file mode 100644 index 000000000..b70f4138f --- /dev/null +++ b/apps/web/src/lib/server/langs.ts @@ -0,0 +1,38 @@ +import type { BasicsSection, PerformerSection, ProjectDetails } from '#lib/types.ts'; + +/** + * A record's prose, the fields its `langs` is about: what someone wrote in sentences, like a bio or a message, and not + * names or titles. + */ +type Text = (string | undefined)[]; + +/** + * `langs` to spread into a record whose prose is `text`, written in `langs` (the writer's, `writerLangs()`, or for a + * copy, its source's): none without any prose. + */ +export function withLangs(text: Text, langs: string[] | undefined): { langs?: string[] } { + return langs && text.some((value) => value?.trim()) ? { langs } : {}; +} + +/** + * `langs` for a record saved with the prose `text`, written in `langs`, over the version that had `before`'s: its + * languages stay while the prose is the same, since nobody wrote it again. + */ +export const editedLangs = ( + text: Text, + before: { text: Text; langs?: string[] } | null | undefined, + langs: string[] | undefined +) => withLangs(text, before && JSON.stringify(text) === JSON.stringify(before.text) ? before.langs : langs); + +/** The prose of a profile's, act's or party's sections, or a project profile's, which has the same fields. */ +export const sectionsText = ( + basics: Pick | undefined, + performer?: Pick +): Text => [basics?.bio, performer?.lookingFor, performer?.travel?.notes]; + +/** The prose of a project's or performer's private booking details. */ +export const detailsText = (details: ProjectDetails | null | undefined): Text => [ + details?.rateNotes, + details?.techRider, + details?.hospitality +]; diff --git a/apps/web/src/lib/server/services/bookings.test.ts b/apps/web/src/lib/server/services/bookings.test.ts index dc82d5a0f..15a780d00 100644 --- a/apps/web/src/lib/server/services/bookings.test.ts +++ b/apps/web/src/lib/server/services/bookings.test.ts @@ -123,6 +123,23 @@ describe('BookingService', () => { ]); }); + it('names the language of what each side wrote, and none on records nobody wrote words in', async () => { + const space = await open(); + const promoter = await t.viewer(PROMOTER); + await t.bookings.message({ actor: await t.viewer(DJ), space, text: 'Free that night' }); + await t.bookings.setStatus({ actor: promoter, space, status: 'cancelled' }); + + const langs = (repo: string) => t.net.spaceRecordsIn(space, repo).map(({ value }) => [value.$type, value.langs]); + + expect(langs(PROMOTER)).toEqual([ + [COLLECTION.bookingInquiry, ['en']], + [COLLECTION.bookingStatus, undefined] + ]); + expect(langs(DJ)).toEqual([[COLLECTION.bookingMessage, ['en']]]); + // The root's record opening the thread says "Thread opened" itself. + expect(langs(ROOT)).toEqual([[COLLECTION.bookingStatus, undefined]]); + }); + it('opens a thread on the second read of an inquiry the directory failed on the first', async () => { const space = await syncedSpace([PROMOTER, DJ]); const project = await bookable(); diff --git a/apps/web/src/lib/server/services/bookings.ts b/apps/web/src/lib/server/services/bookings.ts index aef695a65..1f249ad18 100644 --- a/apps/web/src/lib/server/services/bookings.ts +++ b/apps/web/src/lib/server/services/bookings.ts @@ -2,6 +2,7 @@ import { XRPCError } from '@atproto/api'; import { TID } from '@atproto/common-web'; import { sql } from 'kysely'; import { bookingActions, bookingGroup, type BookingRole } from '#lib/bookings.ts'; +import { writerLangs } from '#lib/locale.ts'; import { COLLECTION, SPACE_TYPE } from '#lib/nsid.ts'; import { BOOKING_STATUSES, isOneOf, labelFor } from '#lib/taxonomy/options.ts'; import type { @@ -54,6 +55,8 @@ export type BookingRecord = { promoter?: string; plannerShow?: string; announcedShow?: string; + /** The languages of what its writer wrote in it: the message, text or note. */ + langs?: string[]; onBehalfOf?: string; createdAt: string; }; @@ -173,6 +176,7 @@ export class BookingService { project: performer.uri, show: JSON.parse(JSON.stringify(input.show)), message, + langs: writerLangs(), createdAt: nowIso() }; @@ -342,7 +346,7 @@ export class BookingService { await this.requireParticipant(input.actor, input.space); const { client, onBehalf } = await spaceWriter(this.core, input.actor); - const draft: BookingRecord = { text, createdAt: nowIso() }; + const draft: BookingRecord = { text, langs: writerLangs(), createdAt: nowIso() }; if (onBehalf) draft.onBehalfOf = input.actor.did; const record = validateRecord(COLLECTION.bookingMessage, draft); @@ -381,7 +385,7 @@ export class BookingService { const draft: BookingRecord = { status: input.status, createdAt: nowIso() }; const note = input.note?.trim(); - if (note) draft.note = note; + if (note) Object.assign(draft, { note, langs: writerLangs() }); if (onBehalf) draft.onBehalfOf = input.actor.did; const record = validateRecord(COLLECTION.bookingStatus, draft); diff --git a/apps/web/src/lib/server/services/epk-drafts.test.ts b/apps/web/src/lib/server/services/epk-drafts.test.ts index 9b163b5cd..f5a223f79 100644 --- a/apps/web/src/lib/server/services/epk-drafts.test.ts +++ b/apps/web/src/lib/server/services/epk-drafts.test.ts @@ -94,6 +94,41 @@ describe('EpkDrafts', () => { expect((await f.t.epks.dashboard(f.project)).kits[0].drafts).toEqual([]); }); + it('names the language of the words a draft changes, on just the records whose words it changes', async () => { + const wordless = { headline: undefined, bio: undefined, content: { mixes: values().content?.mixes } }; + const epk = await f.publish(DJ, wordless); + const backstage = f.t.epks.drafts.space(f.project); + const draft = () => f.t.net.spaceRecordsIn(backstage, DJ)[0]?.value; + expect(published(epk.rkey).value.langs).toBeUndefined(); + expect(content(epk.space).langs).toBeUndefined(); + + await save(DJ, epk.rkey, { ...wordless, title: 'Clubs 2027' }); + expect(draft().langs).toBeUndefined(); + await publish(DJ, epk.rkey); + expect(published(epk.rkey).value.langs).toBeUndefined(); + + await save(DJ, epk.rkey, { + ...wordless, + title: 'Clubs 2027', + content: { ...wordless.content, bio: 'The long bio' } + }); + expect(draft().langs).toEqual(['en']); + await publish(DJ, epk.rkey); + expect(content(epk.space).langs).toEqual(['en']); + expect(published(epk.rkey).value.langs).toBeUndefined(); + // As if the long bio had been written in German. + content(epk.space).langs = ['de']; + + await save(DJ, epk.rkey, { + title: 'Clubs 2027', + bio: 'Rolling techno, all night', + content: { ...wordless.content, bio: 'The long bio' } + }); + await publish(DJ, epk.rkey); + expect(published(epk.rkey).value.langs).toEqual(['en']); + expect(content(epk.space).langs).toEqual(['de']); + }); + it('stops at a field someone else published since the draft changed it, and overwrites it only when told to', async () => { const epk = await f.publish(DJ); diff --git a/apps/web/src/lib/server/services/epk-drafts.ts b/apps/web/src/lib/server/services/epk-drafts.ts index 6638bcfb8..5c66860b4 100644 --- a/apps/web/src/lib/server/services/epk-drafts.ts +++ b/apps/web/src/lib/server/services/epk-drafts.ts @@ -14,6 +14,7 @@ import { LEGACY_KIT, MAX_EPKS_PER_PROJECT } from '#lib/epk.ts'; +import { writerLangs } from '#lib/locale.ts'; import { COLLECTION, EPK_CONTENT_KEY, SPACE_TYPE } from '#lib/nsid.ts'; import type { AccountView, ProjectView, Viewer } from '#lib/types.ts'; import { validateRecord } from '../atproto/lexicons'; @@ -28,6 +29,7 @@ import { backstageSpace, parsePublicRecordUri, parseSpaceUri } from '../atproto/ import { type Core, NotFoundError, ReauthError, UserError } from '../core'; import { nowIso, parseJson } from '../db'; import type { EpkDraftTable } from '../db/schema'; +import { withLangs } from '../langs'; import type { EpkService } from './epk'; import { applyChanges, @@ -35,6 +37,7 @@ import { cidOf, cleared, EPK_FIELDS, + EPK_TEXT_FIELDS, fieldsFrom, fieldsOf, photosOf, @@ -139,6 +142,9 @@ export class EpkDrafts { updatedAt: now }; + if (changed.some((field) => EPK_TEXT_FIELDS.includes(field) && valueOf(values, field))) + record.langs = writerLangs(); + if (kit) { record.base = before?.base ?? { uri: kit.epk.uri, cid: kit.epk.cid }; record.previous = fieldsFrom( @@ -218,7 +224,8 @@ export class EpkDrafts { if (!live && kits.length >= MAX_EPKS_PER_PROJECT) throw new UserError(`A project can have at most ${MAX_EPKS_PER_PROJECT} press kits`); - const published = live ? fieldsOf(live.record, await this.epks.content(live)) : {}; + const liveContent = live && (await this.epks.content(live)); + const published = live ? fieldsOf(live.record, liveContent) : {}; const keep = new Set(options.keep ?? []); const fields = changedFields(draft.changes).filter((field) => !keep.has(field)); @@ -244,6 +251,14 @@ export class EpkDrafts { } const { content, ...visible } = applyChanges(published, changes); + const inContent = (field: EpkField) => field.startsWith('content.'); + + // Each record's words are in the draft's languages once it changes them, and in the ones they had until then. + const rewrote = (part: (field: EpkField) => boolean) => + fields.some((field) => part(field) && EPK_TEXT_FIELDS.includes(field)); + + const publicLangs = rewrote((field) => !inContent(field)) ? draft.langs : live?.record.langs; + const contentLangs = rewrote(inContent) ? draft.langs : liveContent?.langs; if (!visible.title || !visible.access) throw new UserError('Give the press kit a name and say who can ask to see the rest'); @@ -267,6 +282,7 @@ export class EpkDrafts { COLLECTION.epk, toJson({ ...visible, + ...withLangs([visible.headline, visible.bio], publicLangs), title: visible.title, access: visible.access, project: current.uri, @@ -295,7 +311,14 @@ export class EpkDrafts { space: kitSpace, collection: COLLECTION.epkContent, rkey: EPK_CONTENT_KEY, - record: validateRecord(COLLECTION.epkContent, toJson({ ...content, updatedAt: now })) + record: validateRecord( + COLLECTION.epkContent, + toJson({ + ...content, + ...withLangs([content?.bio, content?.techRider, content?.contact?.note], contentLangs), + updatedAt: now + }) + ) }); this.epks.forget(); diff --git a/apps/web/src/lib/server/services/epk-fields.ts b/apps/web/src/lib/server/services/epk-fields.ts index 1887d73a7..8e4cd918b 100644 --- a/apps/web/src/lib/server/services/epk-fields.ts +++ b/apps/web/src/lib/server/services/epk-fields.ts @@ -45,6 +45,12 @@ export const EPK_FIELDS: EpkField[] = [ ...EPK_CONTENT_FIELDS.map((name) => `${CONTENT}${name}` as const) ]; +/** + * The fields that hold a press kit's prose, the words its records' `langs` name. Quotes are left out: they're other + * people's words, in whatever language those wrote them. + */ +export const EPK_TEXT_FIELDS: EpkField[] = ['headline', 'bio', 'content.bio', 'content.techRider', 'content.contact']; + /** The lists among the fields; a draft clears one with an empty list, and the rest with an empty string or object. */ const LISTS = new Set(['mixes', 'photos', 'content.mixes', 'content.photos', 'content.quotes']); diff --git a/apps/web/src/lib/server/services/epk.test.ts b/apps/web/src/lib/server/services/epk.test.ts index 46ecdea2d..6d64a89f5 100644 --- a/apps/web/src/lib/server/services/epk.test.ts +++ b/apps/web/src/lib/server/services/epk.test.ts @@ -162,6 +162,14 @@ describe('EpkService', () => { expect(await f.t.epks.forProject(f.project)).toHaveLength(MAX_EPKS_PER_PROJECT); }); + it('names the language of the message a request to see the private part comes with', async () => { + const epk = await f.publish(DJ); + + await f.t.epks.request(await f.t.viewer(STRANGER), f.kit(epk), { message: 'For a feature' }); + + expect(f.t.net.spaceRecordsIn(requestSpace(), STRANGER).map(({ value }) => value.langs)).toEqual([['en']]); + }); + it('keeps the private part from people until any manager approves them, and the root writes the grant', async () => { const epk = await f.publish(DJ); const kit = f.kit(epk); diff --git a/apps/web/src/lib/server/services/epk.ts b/apps/web/src/lib/server/services/epk.ts index 1d3a0e6e8..d7131b04e 100644 --- a/apps/web/src/lib/server/services/epk.ts +++ b/apps/web/src/lib/server/services/epk.ts @@ -27,6 +27,7 @@ import { readRule, ruleFor } from '#lib/epk.ts'; +import { writerLangs } from '#lib/locale.ts'; import { BSKY_FOLLOW, COLLECTION, EPK_CONTENT_KEY, SPACE_TYPE } from '#lib/nsid.ts'; import type { ProjectView, Viewer } from '#lib/types.ts'; import { RecordValidationError, validateRecord } from '../atproto/lexicons'; @@ -372,7 +373,7 @@ export class EpkService { const createdAt = nowIso(); const draft: JsonObject = { epk: epk.uri, createdAt }; - if (message) draft.message = message; + if (message) Object.assign(draft, { message, langs: writerLangs() }); const space = await this.ensureRequestSpace(kit.project); const { client, onBehalf } = await spaceWriter(this.core, actor); diff --git a/apps/web/src/lib/server/services/events.test.ts b/apps/web/src/lib/server/services/events.test.ts index 45e5ebb07..7df29ccb9 100644 --- a/apps/web/src/lib/server/services/events.test.ts +++ b/apps/web/src/lib/server/services/events.test.ts @@ -427,6 +427,25 @@ describe('EventService', () => { ); }); + it("names the description's language, keeping the one it had through saves that leave it as it was", async () => { + const uri = await t.events.create(host, party, input({ description: 'Doors at eleven.' })); + expect(stored(uri).value.langs).toEqual(['en']); + // As if someone had written it in German. + stored(uri).value.langs = ['de']; + + await t.events.update(host, uri, { + ...input({ name: 'Winter Opening II', description: 'Doors at eleven.' }), + swap: stored(uri).cid + }); + expect(stored(uri).value.langs).toEqual(['de']); + + await t.events.update(host, uri, { ...input({ description: 'Doors at ten.' }), swap: stored(uri).cid }); + expect(stored(uri).value.langs).toEqual(['en']); + + await t.events.update(host, uri, { ...input(), swap: stored(uri).cid }); + expect(stored(uri).value.langs).toBeUndefined(); + }); + it("logs a staff save with each field's before and after, but never the link token", async () => { const uri = await t.events.create(host, party, input()); diff --git a/apps/web/src/lib/server/services/events.ts b/apps/web/src/lib/server/services/events.ts index 50d1c83a1..7a9a7c206 100644 --- a/apps/web/src/lib/server/services/events.ts +++ b/apps/web/src/lib/server/services/events.ts @@ -1,6 +1,7 @@ import { timingSafeEqual } from 'node:crypto'; import { TID } from '@atproto/common-web'; import type { Selectable } from 'kysely'; +import { writerLangs } from '#lib/locale.ts'; import { CALENDAR_EVENT, COLLECTION } from '#lib/nsid.ts'; import { EVENT_STATUS } from '#lib/shows.ts'; import { eventPagePath, spacePagePath } from '#lib/space-paths.ts'; @@ -10,6 +11,7 @@ import { isValidRecord, validateRecord } from '../atproto/lexicons'; import { recordCid } from '../atproto/repo-client'; import { parseSpaceRecordUri, parseSpaceUri, sharedSpace, sharedSpaceKind, spaceRecordUri } from '../atproto/spaces'; import { newToken } from '../auth/session'; +import { editedLangs } from '../langs'; import { parsePerformerUri } from '../performer-uri'; import { type Core, NotFoundError, UserError } from '../core'; import { nowIso } from '../db'; @@ -609,6 +611,7 @@ export class EventService { return { name, ...(description && { description }), + ...editedLangs([description], current && { text: [current.description], langs: current.langs }, writerLangs()), ...when, ...(venue && { venue: venue.space }), ...(draftZone && { timeZone: draftZone }), diff --git a/apps/web/src/lib/server/services/flags.test.ts b/apps/web/src/lib/server/services/flags.test.ts index 844322d93..f679a0fab 100644 --- a/apps/web/src/lib/server/services/flags.test.ts +++ b/apps/web/src/lib/server/services/flags.test.ts @@ -244,6 +244,21 @@ describe('FlagService', () => { expect(JSON.parse(entry.changes ?? '')).toEqual([{ field: 'description', before: 'Early', after: 'Testers' }]); }); + it("names the description's language, keeping it through saves that leave the description alone", async () => { + const admin = await t.viewer(ADMIN); + const rkey = await t.flags.createGroup(admin, { name: 'Beta', description: 'Early', members: [DJ] }); + expect(stored(COLLECTION.staffGroup, rkey)?.value.langs).toEqual(['en']); + // As if the description had been written in German. + stored(COLLECTION.staffGroup, rkey)!.value.langs = ['de']; + + await t.flags.updateGroup(admin, rkey, { name: 'Beta', description: 'Early', members: [DJ, OTHER] }); + expect(stored(COLLECTION.staffGroup, rkey)?.value.langs).toEqual(['de']); + await t.flags.updateGroup(admin, rkey, { name: 'Beta', description: 'Testers', members: [DJ, OTHER] }); + expect(stored(COLLECTION.staffGroup, rkey)?.value.langs).toEqual(['en']); + await t.flags.updateGroup(admin, rkey, { name: 'Beta', members: [DJ, OTHER] }); + expect(stored(COLLECTION.staffGroup, rkey)?.value.langs).toBeUndefined(); + }); + it('refuses an unknown flag, a bad percentage and a group that is gone', async () => { const admin = await t.viewer(ADMIN); diff --git a/apps/web/src/lib/server/services/flags.ts b/apps/web/src/lib/server/services/flags.ts index da9d6043c..4451d7e10 100644 --- a/apps/web/src/lib/server/services/flags.ts +++ b/apps/web/src/lib/server/services/flags.ts @@ -1,6 +1,7 @@ import { TID } from '@atproto/common-web'; import { z } from 'zod'; import type { FlagKey } from '#lib/flags/keys.generated.ts'; +import { writerLangs } from '#lib/locale.ts'; import { COLLECTION } from '#lib/nsid.ts'; import type { FlagGroupView, FlagPreview, Flags, FlagView, StaffGrant, Viewer } from '#lib/types.ts'; import { validateRecord } from '../atproto/lexicons'; @@ -8,6 +9,7 @@ import { rkeyOf } from '../atproto/spaces'; import type { AuditChange, AuditEvent } from '../audit/log'; import { type Core, ForbiddenError, UserError } from '../core'; import { nowIso, parseJson } from '../db'; +import { editedLangs } from '../langs'; import { FLAGS } from '../flags/catalog'; import { type FlagGates, isOn } from '../flags/evaluate'; import { openPreview } from '../flags/preview'; @@ -28,6 +30,7 @@ export const flagRecord = z.object({ export const flagGroupRecord = z.object({ name: z.string(), description: z.string().optional(), + langs: z.array(z.string()).optional(), members: z.array(z.string()), createdAt: z.string(), updatedBy: z.string(), @@ -390,12 +393,27 @@ export class FlagService { }); } + /** + * Writes a group as staff just saved it: a description they changed is in their language, and one they left as it + * was stays in the languages it had. + */ private async writeGroup(rkey: string, value: FlagGroupRecord): Promise { const root = await this.core.root(); - const record = validateRecord(COLLECTION.staffGroup, value); + const staff = this.core.spaces.staff; + const stored = await root.getSpaceRecord({ space: staff, repo: root.did, collection: COLLECTION.staffGroup, rkey }); + const current = flagGroupRecord.safeParse(stored?.value).data; + + const record = validateRecord(COLLECTION.staffGroup, { + ...value, + ...editedLangs( + [value.description], + current && { text: [current.description], langs: current.langs }, + writerLangs() + ) + }); const ref = await root.putSpaceRecord({ - space: this.core.spaces.staff, + space: staff, collection: COLLECTION.staffGroup, rkey, record diff --git a/apps/web/src/lib/server/services/listings.test.ts b/apps/web/src/lib/server/services/listings.test.ts index e01d39329..c1b1d4b65 100644 --- a/apps/web/src/lib/server/services/listings.test.ts +++ b/apps/web/src/lib/server/services/listings.test.ts @@ -373,6 +373,7 @@ describe("an act's listing", () => { name: 'Crew', slug: 'crew', fields: { form: 'duo', basics: { ...basics, avatar: blob }, performer }, + langs: ['en'], people: [{ did: ADA, role: 'member' }], managers: [CY], updatedAt: expect.any(String) diff --git a/apps/web/src/lib/server/services/listings.ts b/apps/web/src/lib/server/services/listings.ts index 7457a1e1e..73ed5b955 100644 --- a/apps/web/src/lib/server/services/listings.ts +++ b/apps/web/src/lib/server/services/listings.ts @@ -10,8 +10,11 @@ import type { Core } from '../core'; import { nowIso } from '../db'; import type { FlagService } from './flags'; -/** What a listing shows of its space beyond its people, from the kind's {@link ListingSource}. */ -export type ListingFields = { name: string; slug?: string; fields?: JsonObject }; +/** + * What a listing shows of its space beyond its people, from the kind's {@link ListingSource}, with the languages its + * fields' text is in, as the space's record names them. + */ +export type ListingFields = { name: string; slug?: string; fields?: JsonObject; langs?: string[] }; /** Reads what a kind's public page shows, or null when there's nothing to list yet. */ export type ListingSource = { publicFields(space: string): Promise }; diff --git a/apps/web/src/lib/server/services/parties.test.ts b/apps/web/src/lib/server/services/parties.test.ts index fe2b0d564..17fd619b6 100644 --- a/apps/web/src/lib/server/services/parties.test.ts +++ b/apps/web/src/lib/server/services/parties.test.ts @@ -55,6 +55,7 @@ describe('PartyService', () => { expect(page(space)?.value).toEqual({ $type: COLLECTION.party, basics, + langs: ['en'], publishedAt: expect.any(String), createdAt: expect.any(String), updatedAt: expect.any(String) @@ -196,6 +197,7 @@ describe('PartyService', () => { kind: 'party', name: 'Night Shift', fields: { basics }, + langs: ['en'], people: [ { did: ADA, role: 'host' }, { did: BO, role: 'cohost' } diff --git a/apps/web/src/lib/server/services/parties.ts b/apps/web/src/lib/server/services/parties.ts index 600829e72..fad501cb8 100644 --- a/apps/web/src/lib/server/services/parties.ts +++ b/apps/web/src/lib/server/services/parties.ts @@ -1,9 +1,11 @@ import type { Selectable } from 'kysely'; +import { writerLangs } from '#lib/locale.ts'; import { COLLECTION } from '#lib/nsid.ts'; import type { BasicsSection, PartyRecord, Viewer } from '#lib/types.ts'; import { validateRecord } from '../atproto/lexicons'; import { type Core, NotFoundError, UserError } from '../core'; import { nowIso } from '../db'; +import { editedLangs, sectionsText, withLangs } from '../langs'; import type { PartyTable } from '../db/schema'; import { savedChanges } from './diff'; import { PARTY_KEY, partyRecord } from './party-index'; @@ -47,6 +49,7 @@ export class PartyService { const record = validateRecord(COLLECTION.party, { basics: avatar ? { ...input.basics, avatar } : input.basics, + ...withLangs(sectionsText(input.basics), writerLangs()), ...(input.publish && { publishedAt: now }), createdAt: now, updatedAt: now @@ -77,9 +80,12 @@ export class PartyService { const now = nowIso(); const publishes = input.publish && !current.publishedAt; + const { langs, ...kept } = current; + const record = validateRecord(COLLECTION.party, { - ...current, + ...kept, basics: avatar ? { ...input.basics, avatar } : input.basics, + ...editedLangs(sectionsText(input.basics), { text: sectionsText(current.basics), langs }, writerLangs()), ...(publishes && { publishedAt: now }), updatedAt: now }); diff --git a/apps/web/src/lib/server/services/party-index.ts b/apps/web/src/lib/server/services/party-index.ts index 34bf1eb94..66317467e 100644 --- a/apps/web/src/lib/server/services/party-index.ts +++ b/apps/web/src/lib/server/services/party-index.ts @@ -55,10 +55,10 @@ export function partyListingSource(db: Db): ListingSource { const record = parseJson(row?.record, null); if (!record?.publishedAt) return null; - const { basics } = record; + const { basics, langs } = record; const fields: JsonObject = JSON.parse(JSON.stringify({ basics })); - return { name: basics.name, fields }; + return { name: basics.name, fields, langs }; } }; } diff --git a/apps/web/src/lib/server/services/performer-index.ts b/apps/web/src/lib/server/services/performer-index.ts index ea6d8f33c..964576f7e 100644 --- a/apps/web/src/lib/server/services/performer-index.ts +++ b/apps/web/src/lib/server/services/performer-index.ts @@ -69,13 +69,14 @@ export function performerListingSource(db: Db): ListingSource { return { async publicFields(space) { const row = await db.selectFrom('performer').select('record').where('spaceUri', '=', space).executeTakeFirst(); - const subject = parseJson(row?.record, null)?.subject; + const record = parseJson(row?.record, null); + const subject = record?.subject; if (subject?.$type !== ACT_TYPE) return null; const { slug, form, basics, performer } = subject; const fields: JsonObject = JSON.parse(JSON.stringify({ form, basics, performer })); - return { name: basics.name, slug, fields }; + return { name: basics.name, slug, fields, langs: record?.langs }; } }; } diff --git a/apps/web/src/lib/server/services/planner.test.ts b/apps/web/src/lib/server/services/planner.test.ts index 584f9fb1e..c013d740b 100644 --- a/apps/web/src/lib/server/services/planner.test.ts +++ b/apps/web/src/lib/server/services/planner.test.ts @@ -72,6 +72,29 @@ describe('PlannerService', () => { ]); }); + it("names the language of a save's note and a show's notes, keeping it through saves that leave the notes alone", async () => { + await t.planner.save(promoter, project('3quiet')); + await t.planner.save(promoter, project('3noted'), 'Ask about May'); + const saves = t.net.spaceRecordsIn(plannerSpace(PROMOTER), PROMOTER).map(({ value }) => [value.note, value.langs]); + expect(saves).toEqual( + expect.arrayContaining([ + [undefined, undefined], + ['Ask about May', ['en']] + ]) + ); + + const rkey = await t.planner.saveShow(promoter, { details: { title: 'Opening', notes: 'Two rooms' }, lineup: [] }); + expect((await t.planner.show(promoter, rkey))?.langs).toEqual(['en']); + // As if the notes had been written in German. + const stored = t.net.spaceRecordsIn(plannerSpace(PROMOTER), PROMOTER).find(({ value }) => value.lineup); + stored!.value.langs = ['de']; + + await t.planner.saveShow(promoter, { rkey, details: { title: 'Opening II', notes: 'Two rooms' }, lineup: [] }); + expect((await t.planner.show(promoter, rkey))?.langs).toEqual(['de']); + await t.planner.saveShow(promoter, { rkey, details: { title: 'Opening II' }, lineup: [] }); + expect((await t.planner.show(promoter, rkey))?.langs).toBeUndefined(); + }); + it('lists planned shows by date, using when it was planned for a show without one', async () => { const plan = (title: string, date?: string) => t.planner.saveShow(promoter, { details: { title, date }, lineup: [] }); diff --git a/apps/web/src/lib/server/services/planner.ts b/apps/web/src/lib/server/services/planner.ts index c4b166172..f8efddfcd 100644 --- a/apps/web/src/lib/server/services/planner.ts +++ b/apps/web/src/lib/server/services/planner.ts @@ -1,5 +1,6 @@ import { createHash } from 'node:crypto'; import { TID } from '@atproto/common-web'; +import { writerLangs } from '#lib/locale.ts'; import { COLLECTION, SELF_SPACE_KEY, SPACE_TYPE } from '#lib/nsid.ts'; import type { PlannerSaveView, PlannerShowView, ShowDetails, Viewer } from '#lib/types.ts'; import { isValidRecord, validateRecord } from '../atproto/lexicons'; @@ -7,16 +8,18 @@ import { createSpaceIfMissing, memberSpacePolicy, type RepoClient } from '../atp import { plannerSpace } from '../atproto/spaces'; import { type Core, UserError } from '../core'; import { nowIso } from '../db'; +import { editedLangs } from '../langs'; import { actorRole } from './requests'; export type Slot = { project: string; slot?: string; status?: 'considering' | 'contacted' | 'confirmed' }; /** Record values by collection, mirroring lexicons/computer/localnetwork/planner. */ type PlannerRecords = { - [COLLECTION.plannerSave]: { project: string; note?: string; createdAt: string }; + [COLLECTION.plannerSave]: { project: string; note?: string; langs?: string[]; createdAt: string }; [COLLECTION.plannerShow]: { details: ShowDetails; lineup: PlannerShowView['lineup']; + langs?: string[]; createdAt: string; updatedAt?: string; }; @@ -123,7 +126,7 @@ export class PlannerService { const entry: PlannerRecords[typeof COLLECTION.plannerSave] = { project: projectUri, createdAt: nowIso() }; - if (note) entry.note = note; + if (note) Object.assign(entry, { note, langs: writerLangs() }); const record = validateRecord(COLLECTION.plannerSave, entry); const ref = await client.putSpaceRecord({ @@ -179,6 +182,7 @@ export class PlannerService { rkey, details: value.details, lineup: value.lineup, + ...(value.langs && { langs: value.langs }), createdAt: value.createdAt, updatedAt: value.updatedAt })) @@ -202,6 +206,11 @@ export class PlannerService { JSON.stringify({ details: input.details, lineup: input.lineup, + ...editedLangs( + [input.details.notes], + existing && { text: [existing.details.notes], langs: existing.langs }, + writerLangs() + ), createdAt: existing?.createdAt ?? now, updatedAt: now }) diff --git a/apps/web/src/lib/server/services/profiles.test.ts b/apps/web/src/lib/server/services/profiles.test.ts index 9aa47193e..900a26d23 100644 --- a/apps/web/src/lib/server/services/profiles.test.ts +++ b/apps/web/src/lib/server/services/profiles.test.ts @@ -152,6 +152,34 @@ describe('ProfileService.save and blueskyPrefill', () => { expect((await t.profiles.get(DJ))?.record.basics.avatar).toBeUndefined(); }); + it('names the language its words are in, keeping the one they had through saves that leave them alone', async () => { + const viewer = await t.viewer(DJ); + + const save = async (basics: { name: string; bio?: string }) => + t.profiles.save(viewer, { basics, avatar: 'keep', swap: (await t.profiles.get(DJ))?.cid ?? null }); + + const langs = async () => (await t.profiles.get(DJ))?.record.langs; + // Written in German, somewhere else. + await t.net.client(DJ).putRecord({ + collection: COLLECTION.profile, + rkey: 'self', + record: { + $type: COLLECTION.profile, + basics: { name: 'Neon', bio: 'Techno am Sonntag' }, + langs: ['de'], + createdAt: '2026-10-30T00:00:00.000Z', + updatedAt: '2026-10-30T00:00:00.000Z' + } + }); + + await save({ name: 'Neon Tide', bio: 'Techno am Sonntag' }); + expect(await langs()).toEqual(['de']); + await save({ name: 'Neon Tide', bio: 'Techno on Sundays' }); + expect(await langs()).toEqual(['en']); + await save({ name: 'Neon Tide' }); + expect(await langs()).toBeUndefined(); + }); + it("has the directory read any account's Bluesky profile for its pronouns, before they have a profile here", async () => { await t.net.client(DJ).putRecord({ collection: BSKY_PROFILE, diff --git a/apps/web/src/lib/server/services/profiles.ts b/apps/web/src/lib/server/services/profiles.ts index 8c0c69e06..6db52e442 100644 --- a/apps/web/src/lib/server/services/profiles.ts +++ b/apps/web/src/lib/server/services/profiles.ts @@ -1,6 +1,7 @@ import { XRPCError } from '@atproto/api'; import type { JsonObject } from '@atproto/lex-json'; import { z } from 'zod'; +import { writerLangs } from '#lib/locale.ts'; import { BSKY_PROFILE, COLLECTION } from '#lib/nsid.ts'; import type { BasicsSection, @@ -14,6 +15,7 @@ import type { import { RecordValidationError, validateRecord } from '../atproto/lexicons'; import { type Core, UserError } from '../core'; import { nowIso } from '../db'; +import { editedLangs, sectionsText } from '../langs'; import type { Upload } from '../forms/project'; import type { IndexedRepo } from '../happyview/indexed'; import { AVATAR_TYPES } from '../images'; @@ -194,6 +196,14 @@ export class ProfileService { ...(performer && { performer }), ...(input.promoter && { promoter: input.promoter }), ...(performer && input.takesInquiries && { takesInquiries: true }), + ...editedLangs( + sectionsText(input.basics, performer), + existing && { + text: sectionsText(existing.record.basics, existing.record.performer), + langs: existing.record.langs + }, + writerLangs() + ), createdAt: existing?.record.createdAt ?? now, updatedAt: now }); diff --git a/apps/web/src/lib/server/services/project-admin.ts b/apps/web/src/lib/server/services/project-admin.ts index 59302ad03..cb9303ccc 100644 --- a/apps/web/src/lib/server/services/project-admin.ts +++ b/apps/web/src/lib/server/services/project-admin.ts @@ -1,3 +1,4 @@ +import { writerLangs } from '#lib/locale.ts'; import type { ProjectDetails, ProjectProfile, ProjectStatus, ProjectView, Viewer } from '#lib/types.ts'; import { type Core, ForbiddenError, UserError } from '../core'; import type { ProjectService } from './projects'; @@ -70,7 +71,8 @@ export class ProjectAdmin { managers: input.managers ?? [], status: 'active', createdBy: input.actor.did, - details: input.details && Object.keys(input.details).length ? input.details : undefined + details: input.details && Object.keys(input.details).length ? input.details : undefined, + langs: writerLangs() }); await this.core.audit.record({ @@ -107,7 +109,8 @@ export class ProjectAdmin { managers: input.project.managers, status: input.project.status, createdBy: input.project.createdBy, - details: input.details + details: input.details, + langs: writerLangs() }); await this.core.audit.record({ diff --git a/apps/web/src/lib/server/services/projects.test.ts b/apps/web/src/lib/server/services/projects.test.ts index ff41cbd8c..db2182716 100644 --- a/apps/web/src/lib/server/services/projects.test.ts +++ b/apps/web/src/lib/server/services/projects.test.ts @@ -85,6 +85,35 @@ describe('ProjectService', () => { expect((await t.projects.managers()).toSorted()).toEqual(managers.toSorted()); }); + it("names the language of the words in a project's profile and private details, and none once they have none", async () => { + const admin = await t.viewer(ADMIN); + + const details = () => + t.net + .spaceRecordsIn(t.spaces.industry, ROOT) + .filter(({ uri }) => uri.includes(COLLECTION.projectDetails)) + .map(({ value }) => value.langs); + + const created = await t.projectAdmin.create({ + actor: admin, + profile: { ...profile('Worded'), bio: 'Deep house on Sundays' }, + details: { rateNotes: 'Flexible for small rooms' } + }); + + expect(created.langs).toEqual(['en']); + expect(details()).toEqual([['en']]); + + const cleared = await t.projectAdmin.update({ + actor: admin, + project: created, + profile: profile('Worded'), + details: {} + }); + + expect(cleared.langs).toBeUndefined(); + expect(details()).toEqual([undefined]); + }); + it('saves empty private details when told to clear them, and has none for a project never given any', async () => { const { project } = await publish('Cleared', null); const { project: plain } = await publish('Plain'); diff --git a/apps/web/src/lib/server/services/projects.ts b/apps/web/src/lib/server/services/projects.ts index 312d3df9e..644a20c00 100644 --- a/apps/web/src/lib/server/services/projects.ts +++ b/apps/web/src/lib/server/services/projects.ts @@ -24,6 +24,7 @@ import type { Backfills } from '../happyview/backfills'; import { type DirectoryProject, type DirectoryStats, type HappyViewClient, QUERY_BYTES } from '../happyview/client'; import { awaitIndexed, INDEX_WAIT_MS, IndexedRepo, reindex } from '../happyview/indexed'; import { MANAGER_COLLECTIONS } from '../happyview/refresh'; +import { detailsText, editedLangs, sectionsText, withLangs } from '../langs'; import type { PlyrClient } from '../plyr'; import { truncateUtf8 } from '../utf8'; import { diff } from './diff'; @@ -125,6 +126,7 @@ function projectView(rootDid: string, ref: RecordRef & { rkey: string }, record: status: record.status, revision: record.revision, createdBy: record.createdBy, + ...(record.langs && { langs: record.langs }), createdAt: record.createdAt, updatedAt: record.updatedAt, avatarUrl: avatar ? `/media/${rootDid}/${avatar}` : null @@ -345,7 +347,8 @@ export class ProjectService { * plyr.fm mixes point at their tracks' records (see withRecordings), moves its * spaces' members along when its managers change, optionally updates its * private details in the industry space, and waits for the directory to - * serve it. Returns field-level changes. + * serve it. Returns field-level changes. `langs` are the languages the profile's and details' text is in where it's + * new: the writer's, or the request's it comes from. The profile's text keeps the ones it had while it's the same. */ async publish(input: { existing?: ProjectView | null; @@ -355,6 +358,7 @@ export class ProjectService { createdBy: string; details?: ProjectDetails | null; lastRequest?: string; + langs?: string[]; }): Promise<{ project: ProjectView; changes: FieldChange[] }> { const { existing } = input; const root = await this.core.root(); @@ -371,6 +375,11 @@ export class ProjectService { status: input.status, revision: (existing?.revision ?? 0) + 1, createdBy: existing?.createdBy ?? input.createdBy, + ...editedLangs( + sectionsText(profile, profile), + existing && { text: sectionsText(existing.profile, existing.profile), langs: existing.langs }, + input.langs + ), createdAt: existing?.createdAt ?? now, updatedAt: now }; @@ -405,7 +414,13 @@ export class ProjectService { if (input.details !== undefined) { const before = existing ? await this.details(existing.uri) : null; const details = input.details ?? {}; - const detailRecord = validateRecord(COLLECTION.projectDetails, { project: ref.uri, details, updatedAt: now }); + + const detailRecord = validateRecord(COLLECTION.projectDetails, { + project: ref.uri, + details, + ...withLangs(detailsText(details), input.langs), + updatedAt: now + }); const written = await root.putSpaceRecord({ space: this.core.spaces.industry, diff --git a/apps/web/src/lib/server/services/requests.test.ts b/apps/web/src/lib/server/services/requests.test.ts index 57e8178a3..b49b7e8c8 100644 --- a/apps/web/src/lib/server/services/requests.test.ts +++ b/apps/web/src/lib/server/services/requests.test.ts @@ -295,6 +295,25 @@ describe('RequestService', () => { expect((await t.requests.get(theirs.uri))?.status).toBe('pending'); }); + it("publishes a project in the language the requester wrote its bio in, and the decision's reason in the moderator's", async () => { + const submitted = await t.requests.submit({ + actor: await t.viewer(DJ), + kind: 'create', + profile: profile('Worded', { bio: 'Deep house on Sundays' }) + }); + + expect(submitted.record.langs).toEqual(['en']); + // As if the requester had written it in German. + const uri = await synced('3worded', { ...submitted.record, langs: ['de'] }); + + await t.requests.decide({ actor: await t.viewer(MOD), uri, outcome: 'approved', reason: 'Welcome' }); + + const projects = t.net.listed(ROOT, COLLECTION.project).map(({ record }) => record?.langs); + expect(projects).toEqual([['de']]); + const decisions = t.net.spaceRecordsIn(t.spaces.moderation, ROOT).map(({ value }) => value); + expect(decisions).toEqual([expect.objectContaining({ reason: 'Welcome', langs: ['en'] })]); + }); + it("won't approve a listing request once the requester's profile is gone", async () => { const uri = await synced('3list', { kind: 'list', diff --git a/apps/web/src/lib/server/services/requests.ts b/apps/web/src/lib/server/services/requests.ts index e13f6bbd3..1bc66f8d8 100644 --- a/apps/web/src/lib/server/services/requests.ts +++ b/apps/web/src/lib/server/services/requests.ts @@ -1,6 +1,7 @@ import type { JsonObject, JsonValue } from '@atproto/lex-json'; import { sql } from 'kysely'; import { z } from 'zod'; +import { writerLangs } from '#lib/locale.ts'; import { COLLECTION } from '#lib/nsid.ts'; import { MIX_REPORT_MAX_BYTES } from '#lib/mix/report.ts'; import { parseMixReportText } from '#lib/mix/schema.ts'; @@ -26,6 +27,7 @@ import { nowIso, parseJson } from '../db'; import { unlessOffline } from '../happyview/offline'; import type { RequestRow } from '../db/schema'; import { AVATAR_TYPES } from '../images'; +import { detailsText, editedLangs, sectionsText, withLangs } from '../langs'; import { diff, savedChanges } from './diff'; import type { DjListings } from './dj-listings'; import type { ProfileService } from './profiles'; @@ -44,6 +46,7 @@ const decisionRecord = z.object({ requester: z.string(), outcome: z.enum(DECISION_OUTCOMES), reason: z.string().optional(), + langs: z.array(z.string()).optional(), decidedBy: z.string(), project: z.string().optional(), projectRevision: z.number().optional(), @@ -189,6 +192,7 @@ export class RequestService { const message = input.message?.trim(); if (message) record.message = message; + Object.assign(record, withLangs(requestText(record), writerLangs())); if (!client) record.onBehalfOf = actor.did; const validated = validateRecord(COLLECTION.request, record); @@ -400,6 +404,12 @@ export class RequestService { else delete next.message; } + delete next.langs; + Object.assign( + next, + editedLangs(requestText(next), { text: requestText(current), langs: current.langs }, writerLangs()) + ); + const validated = validateRecord(COLLECTION.request, next); const writer = client ?? (await this.core.root()); @@ -530,7 +540,8 @@ export class RequestService { status: 'active', createdBy: row.requesterDid, details: record.details ?? undefined, - lastRequest: row.uri + lastRequest: row.uri, + langs: record.langs }); result = { uri: project.uri, revision: project.revision, name: project.profile.name, changes }; @@ -552,7 +563,8 @@ export class RequestService { status: existing.status, createdBy: existing.createdBy, details: record.kind === 'update' ? record.details : undefined, - lastRequest: row.uri + lastRequest: row.uri, + langs: record.langs }); result = { uri: project.uri, revision: project.revision, name: project.profile.name, changes }; @@ -571,7 +583,7 @@ export class RequestService { createdAt: decidedAt }; - if (reason) decision.reason = reason; + if (reason) Object.assign(decision, { reason, langs: writerLangs() }); if (result) { decision.project = result.uri; @@ -1081,6 +1093,14 @@ export class RequestService { } } +/** The prose a request's requester wrote: its message, a claim's evidence, and the profile's and details' text. */ +const requestText = ({ message, claim, profile, details }: RequestRecord) => [ + message, + claim?.evidence, + ...sectionsText(profile, profile), + ...detailsText(details) +]; + /** * The record a request row was indexed from. `index` stores it as JSON of an object, and forgetting a deleted one only * removes fields, so it always parses to one. diff --git a/apps/web/src/lib/server/services/shared-spaces.test.ts b/apps/web/src/lib/server/services/shared-spaces.test.ts index 0496539e1..0c714c685 100644 --- a/apps/web/src/lib/server/services/shared-spaces.test.ts +++ b/apps/web/src/lib/server/services/shared-spaces.test.ts @@ -549,6 +549,31 @@ describe('SharedSpaces', () => { ]); }); + it("names the language of the page's words, keeping the one they had through saves that leave them alone", async () => { + const space = await start(); + const ada = await t.viewer(ADA); + + const save = (bio?: string) => + t.sharedSpaces.updatePage(ada, space, { + form: 'duo', + basics: { name: 'Crew', bio }, + performer: {}, + avatar: 'keep', + swap: page(space)!.cid + }); + + expect(page(space)?.value.langs).toBeUndefined(); + + await save('Two decks, one night'); + expect(page(space)?.value.langs).toEqual(['en']); + // As if the bio had been written in German. + page(space)!.value.langs = ['de']; + await save('Two decks, one night'); + expect(page(space)?.value.langs).toEqual(['de']); + await save(); + expect(page(space)?.value.langs).toBeUndefined(); + }); + it('refuses to save the page for someone whose page.edit was taken away, and for a space with no act', async () => { const space = await start(); await t.sharedSpaces.addPerson(await t.viewer(ADMIN), space, { did: BO, role: 'manager' }); diff --git a/apps/web/src/lib/server/services/shared-spaces.ts b/apps/web/src/lib/server/services/shared-spaces.ts index 2b9cd256c..7008d66e6 100644 --- a/apps/web/src/lib/server/services/shared-spaces.ts +++ b/apps/web/src/lib/server/services/shared-spaces.ts @@ -10,6 +10,7 @@ import { isWriter, type SpaceKind } from '#lib/capabilities.ts'; +import { writerLangs } from '#lib/locale.ts'; import { COLLECTION } from '#lib/nsid.ts'; import type { ActForm, BasicsSection, PerformerSection, SharedSpaceSummary, SpacePerson, Viewer } from '#lib/types.ts'; import { validateRecord } from '../atproto/lexicons'; @@ -18,6 +19,7 @@ import { parseSpaceUri, SHARED_SPACE_TYPES, sharedSpace, sharedSpaceKind, spaceR import type { ActorRole, AuditAction, AuditChange } from '../audit/log'; import { type Core, ForbiddenError, NotFoundError, UserError } from '../core'; import { nowIso, parseJson } from '../db'; +import { editedLangs, sectionsText, withLangs } from '../langs'; import type { Upload } from '../forms/project'; import type { ListingWriter } from './listings'; import { ACT_TYPE, indexPerformer, PERFORMER_KEY, performerRecord } from './performer-index'; @@ -259,6 +261,7 @@ export class SharedSpaces { const record = validateRecord(COLLECTION.performer, { subject: { $type: ACT_TYPE, slug, form: input.form, basics: input.basics, performer: input.performer ?? {} }, + ...withLangs(sectionsText(input.basics, input.performer), writerLangs()), createdAt: now, updatedAt: now }); @@ -290,14 +293,18 @@ export class SharedSpaces { const avatar = await pageAvatar(live.root, input.avatar, current.subject.basics.avatar); + const { langs, ...kept } = current; + const before = { text: sectionsText(current.subject.basics, current.subject.performer), langs }; + const record = validateRecord(COLLECTION.performer, { - ...current, + ...kept, subject: { ...current.subject, form: input.form, basics: avatar ? { ...input.basics, avatar } : input.basics, performer: input.performer }, + ...editedLangs(sectionsText(input.basics, input.performer), before, writerLangs()), updatedAt: nowIso() }); diff --git a/apps/web/src/lib/server/services/space-joins.test.ts b/apps/web/src/lib/server/services/space-joins.test.ts index cddaf8ed9..c25cfb2d2 100644 --- a/apps/web/src/lib/server/services/space-joins.test.ts +++ b/apps/web/src/lib/server/services/space-joins.test.ts @@ -222,6 +222,16 @@ describe('SpaceJoins', () => { }); }); + it('names the language of the message an invite or a request to join comes with, and none without one', async () => { + await t.spaceJoins.invite(await t.viewer(ADA), space, { did: BO, role: 'cohost', message: 'Join us' }); + await t.spaceJoins.invite(await t.viewer(ADA), space, { did: CY, role: 'cohost' }); + await t.spaceJoins.requestToJoin(await t.viewer(DI), space, { message: 'Can I help?', hidden: false }); + + expect(stored(COLLECTION.invite, BO)?.value.langs).toEqual(['en']); + expect(stored(COLLECTION.invite, CY)?.value.langs).toBeUndefined(); + expect(stored(COLLECTION.joinRequest, DI)?.value.langs).toEqual(['en']); + }); + describe('requests to join', () => { it('wait for someone with people.manage, who picks the role', async () => { await t.spaceJoins.requestToJoin(await t.viewer(BO), space, { message: 'Can I help?', hidden: true }); diff --git a/apps/web/src/lib/server/services/space-joins.ts b/apps/web/src/lib/server/services/space-joins.ts index 854cc48dd..927ce5e92 100644 --- a/apps/web/src/lib/server/services/space-joins.ts +++ b/apps/web/src/lib/server/services/space-joins.ts @@ -7,6 +7,7 @@ import { LINK_FORBIDDEN, type SpaceKind } from '#lib/capabilities.ts'; +import { writerLangs } from '#lib/locale.ts'; import { COLLECTION } from '#lib/nsid.ts'; import type { JoinRequestView, PendingInvite, Viewer } from '#lib/types.ts'; import { validateRecord } from '../atproto/lexicons'; @@ -95,7 +96,7 @@ export class SpaceJoins { if (actingAs !== 'member') Object.assign(record, { staff: true }); - if (input.message) Object.assign(record, { message: input.message }); + if (input.message) Object.assign(record, { message: input.message, langs: writerLangs() }); await this.write(live, COLLECTION.invite, input.did, validateRecord(COLLECTION.invite, record)); await this.spaces.record( actor, @@ -255,7 +256,7 @@ export class SpaceJoins { if (await this.stored(live, COLLECTION.joinRequest, viewer.did)) throw new UserError("You've already asked"); const record = { subject: viewer.did, hidden: input.hidden, createdAt: nowIso() }; - if (input.message) Object.assign(record, { message: input.message }); + if (input.message) Object.assign(record, { message: input.message, langs: writerLangs() }); await this.write(live, COLLECTION.joinRequest, viewer.did, validateRecord(COLLECTION.joinRequest, record)); await this.spaces.record(viewer, 'member', 'people.request', space, 'Asked to join', { person: viewer.did, diff --git a/apps/web/src/lib/server/services/staff.test.ts b/apps/web/src/lib/server/services/staff.test.ts index 1294311b3..bb8917148 100644 --- a/apps/web/src/lib/server/services/staff.test.ts +++ b/apps/web/src/lib/server/services/staff.test.ts @@ -118,6 +118,19 @@ describe('StaffService', () => { expect(parsed.grants).toEqual(['flags']); }); + it("names the note's language, and keeps it when the moderator's grants change", async () => { + const admin = await t.viewer(ADMIN); + const role = () => t.net.spaceRecordsIn(t.spaces.staff, t.core.rootDid).find(({ value }) => value.subject === MOD); + await t.staff.grant(admin, MOD, 'moderator', 'Weekends'); + expect(role()?.value.langs).toEqual(['en']); + // As if the note had been written in German. + role()!.value.langs = ['de']; + + await t.staff.setGrants(admin, MOD, ['flags']); + + expect(role()?.value).toMatchObject({ note: 'Weekends', langs: ['de'], grants: ['flags'] }); + }); + it('names staff by handle in the audit log, with the note a grant came with', async () => { const admin = await t.viewer(ADMIN); await signIn(DJ, 'dj.test'); diff --git a/apps/web/src/lib/server/services/staff.ts b/apps/web/src/lib/server/services/staff.ts index b1ebad279..49203c493 100644 --- a/apps/web/src/lib/server/services/staff.ts +++ b/apps/web/src/lib/server/services/staff.ts @@ -1,4 +1,5 @@ import { z } from 'zod'; +import { writerLangs } from '#lib/locale.ts'; import { COLLECTION } from '#lib/nsid.ts'; import type { StaffGrant, StaffMember, StaffRole, Viewer } from '#lib/types.ts'; import { validateRecord } from '../atproto/lexicons'; @@ -6,6 +7,7 @@ import { listAllSpaceRecords } from '../atproto/repo-client'; import { reconcileMembers } from './space-members'; import { type Core, ForbiddenError, UserError } from '../core'; import { nowIso, parseJson } from '../db'; +import { withLangs } from '../langs'; const STAFF_GRANTS = ['flags', 'flagGroups'] as const satisfies readonly StaffGrant[]; @@ -25,6 +27,7 @@ export const staffRoleRecord = z.object({ .optional(), grantedBy: z.string(), note: z.string().optional(), + langs: z.array(z.string()).optional(), createdAt: z.string() }); @@ -127,7 +130,7 @@ export class StaffService { // Changing a moderator's note keeps what they were given. An admin has it all anyway. if (role === 'moderator' && grants.length > 0) grant.grants = grants; - if (note) grant.note = note; + if (note) Object.assign(grant, { note, langs: writerLangs() }); const record = validateRecord(COLLECTION.staffRole, grant); await this.oneAtATime(async () => { @@ -164,6 +167,16 @@ export class StaffService { if (row?.role !== 'moderator') throw new UserError('Only moderators take grants'); const previous = parseJson(row.grants, []); + const root = await this.core.root(); + + // The note stays in the languages it was written in, which only the record holds, not the index. + const stored = await root.getSpaceRecord({ + space: this.core.spaces.staff, + repo: root.did, + collection: COLLECTION.staffRole, + rkey: subject + }); + const value: StaffRoleRecord = { subject, role: row.role, @@ -172,9 +185,13 @@ export class StaffService { createdAt: row.createdAt }; - if (row.note) value.note = row.note; + if (row.note) + Object.assign( + value, + { note: row.note }, + withLangs([row.note], staffRoleRecord.safeParse(stored?.value).data?.langs) + ); const record = validateRecord(COLLECTION.staffRole, value); - const root = await this.core.root(); const ref = await root.putSpaceRecord({ space: this.core.spaces.staff, diff --git a/apps/web/src/lib/test-locale.svelte.test.ts b/apps/web/src/lib/test-locale.svelte.test.ts new file mode 100644 index 000000000..45039fe6a --- /dev/null +++ b/apps/web/src/lib/test-locale.svelte.test.ts @@ -0,0 +1,8 @@ +import { expect, it } from 'vitest'; + +// vite.config.ts pins every test's locale and time zone, so a date or number reads the same on any machine. +it("runs in en-US and UTC, whatever the machine's", () => { + const { locale, timeZone } = Intl.DateTimeFormat().resolvedOptions(); + + expect({ locale, timeZone }).toEqual({ locale: 'en-US', timeZone: 'UTC' }); +}); diff --git a/apps/web/src/lib/test-locale.test.ts b/apps/web/src/lib/test-locale.test.ts new file mode 100644 index 000000000..45039fe6a --- /dev/null +++ b/apps/web/src/lib/test-locale.test.ts @@ -0,0 +1,8 @@ +import { expect, it } from 'vitest'; + +// vite.config.ts pins every test's locale and time zone, so a date or number reads the same on any machine. +it("runs in en-US and UTC, whatever the machine's", () => { + const { locale, timeZone } = Intl.DateTimeFormat().resolvedOptions(); + + expect({ locale, timeZone }).toEqual({ locale: 'en-US', timeZone: 'UTC' }); +}); diff --git a/apps/web/src/lib/testing/locale.ts b/apps/web/src/lib/testing/locale.ts new file mode 100644 index 000000000..700944341 --- /dev/null +++ b/apps/web/src/lib/testing/locale.ts @@ -0,0 +1,18 @@ +import { cookieName, type Locale } from '#lib/paraglide/runtime.js'; +import { paraglideMiddleware } from '#lib/paraglide/server.js'; + +/** What `run` returns while the server answers a request whose cookie asks for `locale`, as the server hook runs pages. */ +export async function inLocale(locale: Locale, run: () => T): Promise { + const results: T[] = []; + + await paraglideMiddleware( + new Request('https://localnetwork.test/', { headers: { cookie: `${cookieName}=${locale}` } }), + () => { + results.push(run()); + + return new Response(); + } + ); + + return results[0]; +} diff --git a/apps/web/src/lib/types.ts b/apps/web/src/lib/types.ts index 1dc182373..6612661b3 100644 --- a/apps/web/src/lib/types.ts +++ b/apps/web/src/lib/types.ts @@ -184,6 +184,8 @@ export type ProfileRecord = LexiconRead< promoter?: PromoterSection; /** Whether the DJ takes booking inquiries here, which they turn on themself. */ takesInquiries?: boolean; + /** The languages its text is written in. */ + langs?: string[]; createdAt: string; updatedAt: string; }, @@ -214,6 +216,8 @@ export type PerformerRecord = { subject: | ({ $type: 'computer.localnetwork.performer#act' } & ActSubject) | { $type: 'computer.localnetwork.performer#dj'; did: string }; + /** The languages an act's text is written in. */ + langs?: string[]; formerly?: string[]; createdAt: string; updatedAt: string; @@ -222,6 +226,8 @@ export type PerformerRecord = { /** A named night or series (`computer.localnetwork.party`), as the root wrote it into the party's space. */ export type PartyRecord = { basics: BasicsSection; + /** The languages its text is written in. */ + langs?: string[]; /** Absent while it's a draft. */ publishedAt?: string; createdAt: string; @@ -235,6 +241,8 @@ export type EventCredit = { performer: string; startsAt?: string; endsAt?: strin export type EventRecord = { name: string; description?: string; + /** The languages the description is written in. */ + langs?: string[]; /** With the venue's UTC offset, or the draft's time zone's. Only a draft can be without it, or without a venue. */ startsAt?: string; endsAt?: string; @@ -363,6 +371,8 @@ export type ProjectRecord = LexiconRead< revision: number; createdBy: string; lastRequest?: string; + /** The languages the profile's text is written in. */ + langs?: string[]; createdAt: string; updatedAt: string; }, @@ -379,6 +389,8 @@ export type ProjectView = { status: ProjectStatus; revision: number; createdBy: string; + /** The languages the profile's text is written in. */ + langs?: string[]; createdAt: string; updatedAt: string; avatarUrl: string | null; @@ -448,6 +460,8 @@ export type RequestRecord = LexiconRead< /** For a list request: the profile to list, and the version it was asked for with. */ listing?: { subject: string; cid?: string }; message?: string; + /** The languages the requester wrote its text in. */ + langs?: string[]; onBehalfOf?: string; withdrawnAt?: string; createdAt: string; @@ -688,6 +702,8 @@ export type PlannerShowView = { rkey: string; details: ShowDetails; lineup: { project: string; slot?: string; status?: string }[]; + /** The languages the show's notes are written in. */ + langs?: string[]; createdAt: string; updatedAt?: string; }; diff --git a/apps/web/src/routes/+layout.svelte b/apps/web/src/routes/+layout.svelte index 9a95d42ce..919c61a55 100644 --- a/apps/web/src/routes/+layout.svelte +++ b/apps/web/src/routes/+layout.svelte @@ -10,6 +10,7 @@ import { type NavLink, siteNav } from '#lib/nav.ts'; import SiteHeader from '#lib/ui/SiteHeader.svelte'; import { hotkeys, hotkeyTarget, loadHotkeyPreference, setHotkeysEnabled } from '#lib/hotkeys.svelte.ts'; + import { m } from '#lib/paraglide/messages.js'; import type { LayoutProps } from './$types'; let { children, data }: LayoutProps = $props(); @@ -72,7 +73,7 @@ -Skip to content +{m.skip_to_content()} diff --git a/apps/web/src/routes/layout.svelte.test.ts b/apps/web/src/routes/layout.svelte.test.ts index 65cad225d..490c33d7e 100644 --- a/apps/web/src/routes/layout.svelte.test.ts +++ b/apps/web/src/routes/layout.svelte.test.ts @@ -3,6 +3,7 @@ import { afterEach, beforeEach, expect, it } from 'vitest'; import { page } from 'vitest/browser'; import { render } from 'vitest-browser-svelte'; import { draftKey } from '#lib/form-draft.svelte.ts'; +import { setLocale } from '#lib/paraglide/runtime.js'; import { SIGNED_OUT_COOKIE } from '#lib/signed-out-drafts.ts'; import type { Viewer } from '#lib/types.ts'; import Layout from './+layout.svelte'; @@ -28,9 +29,12 @@ beforeEach(() => { for (const key of [mine, theirs]) localStorage.setItem(key, JSON.stringify({ savedAt: '', base: '', values: {} })); }); -afterEach(() => { +afterEach(async () => { for (const key of [mine, theirs]) localStorage.removeItem(key); document.cookie = `${SIGNED_OUT_COOKIE}=; Max-Age=0; Path=/`; + // setLocale writes its cookie too, which the next file's tests would read. + await setLocale('en', { reload: false }); + document.cookie = 'ln_locale=; Max-Age=0; Path=/'; }); it('drops the drafts of the accounts the sign-out response names on the next page load, and only theirs', async () => { @@ -56,3 +60,11 @@ it('links /for from the footer on every page, since the header leaves it out', a .element(page.getByRole('contentinfo').getByRole('link', { name: "Who it's for" })) .toHaveAttribute('href', '/for'); }); + +it('takes every word in the footer from the message catalog, so en-XA leaves no plain English there', async () => { + await setLocale('en-XA', { reload: false }); + await render(Layout, { params: {}, data: { viewer: null, pendingRequests: 0 }, children }); + + await expect.element(page.getByRole('contentinfo').getByRole('link').first()).toBeVisible(); + expect(page.getByRole('contentinfo').element().textContent).not.toMatch(/[A-Za-z]/); +}); diff --git a/apps/web/src/writing.test.ts b/apps/web/src/writing.test.ts index 887620a88..534c63771 100644 --- a/apps/web/src/writing.test.ts +++ b/apps/web/src/writing.test.ts @@ -7,11 +7,15 @@ const root = join(import.meta.dirname, '../../..'); // The site's copy, code and the lexicons it publishes are written without long dashes. const folders = ['apps/web/src', 'lexicons/computer']; +// Paraglide's compiled runtime and messages (src/lib/paraglide, git-ignored) are its code, not ours. +const PARAGLIDE = join(root, 'apps/web/src/lib/paraglide'); + // Files only: some route folders are named like files (`oauth-client-metadata.json/`). const files = folders.flatMap((folder) => readdirSync(join(root, folder), { recursive: true, withFileTypes: true }) .filter((entry) => entry.isFile() && /\.(svelte|ts|js|css|html|json)$/.test(entry.name)) .map((entry) => join(entry.parentPath, entry.name)) + .filter((file) => !file.startsWith(PARAGLIDE)) ); // Built from its code point, so this file doesn't contain one (the formatter unescapes \u escapes). diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 6ec3fc6d7..e8a7574fe 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -1,3 +1,4 @@ +import { paraglideVitePlugin } from '@inlang/paraglide-js'; import adapter from '@sveltejs/adapter-node'; import { storybookTest } from '@storybook/addon-vitest/vitest-plugin'; import { enhancedImages } from '@sveltejs/enhanced-img'; @@ -22,9 +23,20 @@ const uncachedGlobs: Plugin = { // port (63315 and up) instead of moving on, so test runs in two checkouts at once collide. const BROWSER_TEST_SERVER = { strictPort: false }; +// Every test runs in one locale and time zone, whatever the machine's, so a date or number reads the same on a +// laptop as in CI. Node takes them from the environment it starts with, which Vitest gives each test process; the +// browser tests' Chromium takes them from its context. Playwright's e2e tests pin the same (playwright.config.ts). +const TEST_LOCALE = 'en-US'; + +const TEST_TIME_ZONE = 'UTC'; + // A media element's clock follows the audio output, and on a Mac that has stopped, a recording sitting at 0:00 while // its player says it's playing. Without audio output, Chromium keeps the time itself. -const browserTests = () => playwright({ launchOptions: { args: ['--disable-audio-output'] } }); +const browserTests = () => + playwright({ + launchOptions: { args: ['--disable-audio-output'] }, + contextOptions: { locale: TEST_LOCALE, timezoneId: TEST_TIME_ZONE } + }); const storybookProject = (name: string, options: Parameters[0] = {}) => ({ extends: './vite.config.ts', @@ -48,14 +60,18 @@ const SHARED_MODULE_SIZE = 4096; const LIB = /[\\/]src[\\/]lib[\\/]/; +const PARAGLIDE_RUNTIME = /[\\/]src[\\/]lib[\\/]paraglide[\\/]runtime\.js$/; + // The shared group brings a module's imports along with it, whatever their size, so a small // component that renders a large one puts the large one in every visitor's download (ArtistPage // brought ArtistSupport, 12 KB). So everything of ours a module imports, all the way down, has to // be small too. Lucide's index isn't counted: it re-exports every icon, and only the ones used ship. +// Nor is Paraglide's runtime, which every visitor downloads already, so a component that formats a +// date or shows a message can still be shared. const isSmall = (id: string, ctx: Rolldown.ChunkingContext, seen = new Set()): boolean => { const module = ctx.getModuleInfo(id); - if (seen.has(id) || !module || !LIB.test(id)) return true; + if (seen.has(id) || !module || !LIB.test(id) || PARAGLIDE_RUNTIME.test(id)) return true; seen.add(id); return (module.code?.length ?? 0) <= SHARED_MODULE_SIZE && module.importedIds.every((dep) => isSmall(dep, ctx, seen)); @@ -100,6 +116,8 @@ const SHARED = export default defineConfig({ plugins: [ uncachedGlobs, + // The message functions and locale runtime in src/lib/paraglide, from messages/ (project.inlang/paraglide.config.ts). + paraglideVitePlugin({ project: './project.inlang' }), tailwindcss(), // `?enhanced` images: AVIF and WebP at each width, with their size set so nothing shifts as they load. enhancedImages(), @@ -192,6 +210,7 @@ export default defineConfig({ // its 4-core runners, and locally the suites ran no slower with it. Vitest sizes one pool for projects // that run together, so the cap is set here for all of them rather than on the browser projects. maxWorkers: 3, + env: { LC_ALL: 'en_US.UTF-8', TZ: TEST_TIME_ZONE }, expect: { requireAssertions: true }, tags: [ { @@ -213,7 +232,7 @@ export default defineConfig({ 'src/hooks.server.ts' ], // The tests, their harness (fakes and request builders that only tests import), stories and types, the - // generated lexicon types included. + // generated lexicon types and Paraglide's generated messages and runtime included. exclude: [ 'src/lib/server/testing/**', 'src/lib/testing/**', @@ -221,7 +240,8 @@ export default defineConfig({ 'src/lib/**/*.svelte.{test,spec}.ts', 'src/lib/**/*.stories.svelte', 'src/lib/**/types.ts', - 'src/lib/lexicons/**' + 'src/lib/lexicons/**', + 'src/lib/paraglide/**' ], // CI's pull request comment reads the summary, and json for each changed file's uncovered lines. reporter: ['text', 'html', 'lcov', 'json-summary', 'json'], diff --git a/docs/adr/0019-english-stays-unprefixed-and-records-carry-their-language.md b/docs/adr/0019-english-stays-unprefixed-and-records-carry-their-language.md new file mode 100644 index 000000000..ba4578c50 --- /dev/null +++ b/docs/adr/0019-english-stays-unprefixed-and-records-carry-their-language.md @@ -0,0 +1,28 @@ +# English stays unprefixed, and records carry their language + +Local Network launches in English, and a second language comes when a translator commits to keeping it up. Most of what translation needs can wait until then. A few choices can't, because once people have links, records and accounts, changing them means redirects, migrations or rewriting what's in people's repos. Those are made now. + +The website's words live in message catalogs (`apps/web/messages/`) that pages reach through Paraglide JS, and locallibrary's Rust code will use Fluent when its turn comes. Besides English there's `en-XA`, a pseudo-locale generated from the English: every letter accented, each line about a third longer, each message in brackets. Viewed in en-XA, text that skipped the catalog stays plain English and a layout that can't stretch clips, long before a translator sees either. + +English pages keep their URLs, with no language prefix, for good. Each later language gets a prefix of its own (`/de/act/...`), so no URL anyone has shared ever changes, and the move to `/act//` in [0016](0016-names-repeat-keys-and-handles-identify.md) happens once. Until then the locale comes from a cookie, `ln_locale`. + +Every record that holds prose a person wrote (a bio, a description, a message, a note) has an optional `langs` field, shaped as `app.bsky.feed.post` has it: up to three BCP-47 language tags. The website fills it in from the writer's locale, which is `en` today; en-XA counts as English. With it, a reader in another language can be offered a translation and a list can filter by language. Without it, every app reading the record would have to guess the language from the text. Records hold no English the app wrote, either. The audit entry's `summary` is rendered from its action and fields when it's shown, so each reader gets it in their own language. + +The language preference lives on the account (`account.locale`) as well as in the cookie. Emails and DMs go to each recipient in their language, sent outside any request of theirs that could carry a cookie, so for someone signed in the account decides and the cookie only covers visitors. The column comes with the second language, since until then it would hold `en` for everyone. + +A page's name part is only decoration ([0016](0016-names-repeat-keys-and-handles-identify.md)), so a name written in another script keeps that script in the URL instead of being transliterated. Transliteration differs by language and loses what the name said, and the key already finds the page. Place names are stored as the place itself writes them, in its own language, with the country as an ISO 3166 code that each reader's language names. Community location objects (LOC-727) keep the same rule for their address fields, and no record stores a translated place name. + +locallibrary's sidecar takes the client's locale when it starts (`initialize`), and its schema marks each field that holds text for people to read, so a desktop app shows those as they come and never compares them. + +New CSS uses logical directions (`ms-`, `pe-`, `start-` rather than `ml-`, `pr-`, `left-`), so a right-to-left language doesn't need a pass over every layout. Every test runner pins its locale and time zone, en-US and UTC, so a date or a number reads the same on a laptop as in CI. + +## Considered options + +- A prefix for English too (`/en/...`): every link already shared would become a redirect, for the one language every page is written in. +- A subdomain per language (`de.localnetwork.computer`): another origin for the session cookie, the OAuth redirect URLs and the CSP to cover, for what a prefix already does. +- The browser's `Accept-Language` from the start: with one language there's nothing to choose. It can set a first visit's language when a second one arrives. +- Keeping the audit summary's English and translating it when shown: prose the app wrote can't be translated reliably, and the action and fields already hold everything it says. + +## Consequences + +Each message ships its en-XA text to every visitor next to the English, a few bytes a message. Once most of the site's text is in the catalog, a production build can leave en-XA out. A visitor's browser writes the locale cookie on their first page. Until the rest of the text moves to the catalog, en-XA shows it in plain English, which is what en-XA is for. diff --git a/knip.jsonc b/knip.jsonc index 82fd470a1..d31a6c740 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -25,13 +25,15 @@ // elsewhere. // The Docker image ships scripts/db-backup.ts, for restores. The default run calls that entry // redundant (package.json's db: scripts reach it), but the production run only reads `start`. - // scripts/fuzz.ts loads the fuzz targets by name. + // scripts/fuzz.ts loads the fuzz targets by name. Paraglide's CLI and Vite plugin read its config from the + // inlang project. "entry": [ "src/lib/server/atproto/lexicon-files.ts!", "src/lib/server/notifications/kind-files.ts!", "src/lib/server/happyview/lua-files.ts!", "scripts/db-backup.ts!", - "fuzz/*.fuzz.ts" + "fuzz/*.fuzz.ts", + "project.inlang/paraglide.config.ts" ], "project": [ "**/*.{js,mjs,cjs,jsx,ts,tsx,mts,cts,mdx,svelte,css}!", @@ -48,8 +50,13 @@ "!src/lib/components/edit/EditBarFrame.svelte!", "!src/lib/components/edit/EditPageHarness.svelte!" ], - // src/lib/server/og/render.ts resolves their font files by path at runtime. - "ignoreDependencies": ["@fontsource/instrument-sans", "@fontsource/jetbrains-mono"] + // src/lib/server/og/render.ts resolves their font files by path at runtime, and project.inlang/settings.json + // loads the message format plugin by path. + "ignoreDependencies": [ + "@fontsource/instrument-sans", + "@fontsource/jetbrains-mono", + "@inlang/plugin-message-format" + ] }, "apps/localtoolbox": { // The content scripts, the main-world script that feeds content.ts, the popup's classic scripts, diff --git a/lexicons/computer/localnetwork/booking/inquiry.json b/lexicons/computer/localnetwork/booking/inquiry.json index 751bdf508..6e15d80db 100644 --- a/lexicons/computer/localnetwork/booking/inquiry.json +++ b/lexicons/computer/localnetwork/booking/inquiry.json @@ -25,6 +25,12 @@ "maxLength": 20000, "maxGraphemes": 2000 }, + "langs": { + "type": "array", + "description": "The languages the promoter wrote the message and the show's notes in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "plannerShow": { "type": "string", "format": "at-uri", diff --git a/lexicons/computer/localnetwork/booking/message.json b/lexicons/computer/localnetwork/booking/message.json index 80e237b2f..f30fb4e35 100644 --- a/lexicons/computer/localnetwork/booking/message.json +++ b/lexicons/computer/localnetwork/booking/message.json @@ -16,6 +16,12 @@ "maxLength": 20000, "maxGraphemes": 2000 }, + "langs": { + "type": "array", + "description": "The languages the text is written in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "onBehalfOf": { "type": "string", "format": "did", diff --git a/lexicons/computer/localnetwork/booking/status.json b/lexicons/computer/localnetwork/booking/status.json index 490213c7d..cff2c31c1 100644 --- a/lexicons/computer/localnetwork/booking/status.json +++ b/lexicons/computer/localnetwork/booking/status.json @@ -35,6 +35,12 @@ "maxLength": 5000, "maxGraphemes": 500 }, + "langs": { + "type": "array", + "description": "The languages the note is written in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "onBehalfOf": { "type": "string", "format": "did", diff --git a/lexicons/computer/localnetwork/epk.json b/lexicons/computer/localnetwork/epk.json index 67fbaa5ae..4e34ebc37 100644 --- a/lexicons/computer/localnetwork/epk.json +++ b/lexicons/computer/localnetwork/epk.json @@ -29,6 +29,12 @@ "maxGraphemes": 1000, "description": "A short bio anyone can read." }, + "langs": { + "type": "array", + "description": "The languages the headline and bio are written in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "mixes": { "type": "array", "maxLength": 12, diff --git a/lexicons/computer/localnetwork/epk/content.json b/lexicons/computer/localnetwork/epk/content.json index 25fa2afa0..83b628f35 100644 --- a/lexicons/computer/localnetwork/epk/content.json +++ b/lexicons/computer/localnetwork/epk/content.json @@ -29,6 +29,12 @@ }, "contact": { "type": "ref", "ref": "computer.localnetwork.epk.defs#contact" }, "techRider": { "type": "string", "maxLength": 20000, "maxGraphemes": 2000 }, + "langs": { + "type": "array", + "description": "The languages its text is written in: the bio, tech rider and contact note. Quotes are in whatever language their sources wrote them.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "updatedAt": { "type": "string", "format": "datetime" } } } diff --git a/lexicons/computer/localnetwork/epk/draft.json b/lexicons/computer/localnetwork/epk/draft.json index 7263e801f..22b10e3f9 100644 --- a/lexicons/computer/localnetwork/epk/draft.json +++ b/lexicons/computer/localnetwork/epk/draft.json @@ -25,6 +25,12 @@ "ref": "#fields", "description": "What each changed field held in the published press kit when the draft changed it; a changed field missing here was empty. Publishing compares these with the current values to find fields someone else published since. Absent for a press kit that isn't published yet." }, + "langs": { + "type": "array", + "description": "The languages of the text this draft changes. Publishing gives them to whichever of the press kit's records it changes the text of.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "onBehalfOf": { "type": "string", "format": "did", diff --git a/lexicons/computer/localnetwork/epk/request.json b/lexicons/computer/localnetwork/epk/request.json index fff16eaa2..919b2627d 100644 --- a/lexicons/computer/localnetwork/epk/request.json +++ b/lexicons/computer/localnetwork/epk/request.json @@ -12,6 +12,12 @@ "properties": { "epk": { "type": "string", "format": "at-uri", "description": "The computer.localnetwork.epk record." }, "message": { "type": "string", "maxLength": 10000, "maxGraphemes": 1000 }, + "langs": { + "type": "array", + "description": "The languages the message is written in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "onBehalfOf": { "type": "string", "format": "did", diff --git a/lexicons/computer/localnetwork/event.json b/lexicons/computer/localnetwork/event.json index e64c42984..e5b8e5489 100644 --- a/lexicons/computer/localnetwork/event.json +++ b/lexicons/computer/localnetwork/event.json @@ -12,6 +12,12 @@ "properties": { "name": { "type": "string", "minLength": 1, "maxLength": 1200, "maxGraphemes": 120 }, "description": { "type": "string", "maxLength": 30000, "maxGraphemes": 3000 }, + "langs": { + "type": "array", + "description": "The languages the description is written in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "startsAt": { "type": "string", "format": "datetime", diff --git a/lexicons/computer/localnetwork/listing.json b/lexicons/computer/localnetwork/listing.json index a2920bc23..55708f804 100644 --- a/lexicons/computer/localnetwork/listing.json +++ b/lexicons/computer/localnetwork/listing.json @@ -13,6 +13,12 @@ "kind": { "type": "string", "maxLength": 32, "knownValues": ["act", "party", "venue"] }, "name": { "type": "string", "minLength": 1, "maxLength": 640, "maxGraphemes": 64 }, "slug": { "type": "string", "minLength": 2, "maxLength": 64 }, + "langs": { + "type": "array", + "description": "The languages of the text in fields, as the space's own record names them.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "people": { "type": "array", "maxLength": 50, diff --git a/lexicons/computer/localnetwork/moderation/decision.json b/lexicons/computer/localnetwork/moderation/decision.json index 956a7f866..a67ca5215 100644 --- a/lexicons/computer/localnetwork/moderation/decision.json +++ b/lexicons/computer/localnetwork/moderation/decision.json @@ -15,6 +15,12 @@ "requester": { "type": "string", "format": "did" }, "outcome": { "type": "string", "maxLength": 32, "knownValues": ["approved", "rejected", "changesRequested"] }, "reason": { "type": "string", "maxLength": 10000, "maxGraphemes": 1000 }, + "langs": { + "type": "array", + "description": "The languages the reason is written in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "decidedBy": { "type": "string", "format": "did" }, "project": { "type": "string", "format": "at-uri" }, "projectRevision": { "type": "integer", "minimum": 1 }, diff --git a/lexicons/computer/localnetwork/moderation/request.json b/lexicons/computer/localnetwork/moderation/request.json index 067b912c2..73082d89f 100644 --- a/lexicons/computer/localnetwork/moderation/request.json +++ b/lexicons/computer/localnetwork/moderation/request.json @@ -23,6 +23,12 @@ "claim": { "type": "ref", "ref": "#claim" }, "listing": { "type": "ref", "ref": "#listingSubject" }, "message": { "type": "string", "maxLength": 20000, "maxGraphemes": 2000 }, + "langs": { + "type": "array", + "description": "The languages the requester wrote in: the message, the claim's evidence, and the profile's and details' text.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "onBehalfOf": { "type": "string", "format": "did", diff --git a/lexicons/computer/localnetwork/party.json b/lexicons/computer/localnetwork/party.json index e561e5a37..d0a15df5c 100644 --- a/lexicons/computer/localnetwork/party.json +++ b/lexicons/computer/localnetwork/party.json @@ -11,6 +11,12 @@ "required": ["basics", "createdAt", "updatedAt"], "properties": { "basics": { "type": "ref", "ref": "computer.localnetwork.section.defs#basics" }, + "langs": { + "type": "array", + "description": "The languages the party's text is written in, like its bio.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "publishedAt": { "type": "string", "format": "datetime", diff --git a/lexicons/computer/localnetwork/people/invite.json b/lexicons/computer/localnetwork/people/invite.json index d5e871197..6f16ded7d 100644 --- a/lexicons/computer/localnetwork/people/invite.json +++ b/lexicons/computer/localnetwork/people/invite.json @@ -19,6 +19,12 @@ "description": "Set when staff made it. It works whoever is in the space. One made by someone in the space stops working once they can't add people." }, "message": { "type": "string", "maxLength": 3000, "maxGraphemes": 300 }, + "langs": { + "type": "array", + "description": "The languages the message is written in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "createdAt": { "type": "string", "format": "datetime" }, "expiresAt": { "type": "string", "format": "datetime" } } diff --git a/lexicons/computer/localnetwork/people/request.json b/lexicons/computer/localnetwork/people/request.json index 8c260d9f9..7dd188677 100644 --- a/lexicons/computer/localnetwork/people/request.json +++ b/lexicons/computer/localnetwork/people/request.json @@ -12,6 +12,12 @@ "properties": { "subject": { "type": "string", "format": "did" }, "message": { "type": "string", "maxLength": 3000, "maxGraphemes": 300 }, + "langs": { + "type": "array", + "description": "The languages the message is written in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "hidden": { "type": "boolean", "description": "Whether they want to be hidden from everyone outside the space once they're in." diff --git a/lexicons/computer/localnetwork/performer.json b/lexicons/computer/localnetwork/performer.json index 79d8e612b..1a34aed1c 100644 --- a/lexicons/computer/localnetwork/performer.json +++ b/lexicons/computer/localnetwork/performer.json @@ -16,6 +16,12 @@ "closed": false, "description": "An act, with what its page shows, or the DJ whose backstage and managers the space holds." }, + "langs": { + "type": "array", + "description": "The languages an act's text is written in, like its bio. A DJ's has none: their page is their profile.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "formerly": { "type": "array", "maxLength": 20, diff --git a/lexicons/computer/localnetwork/performer/details.json b/lexicons/computer/localnetwork/performer/details.json index 385a3942e..e2c3c3f37 100644 --- a/lexicons/computer/localnetwork/performer/details.json +++ b/lexicons/computer/localnetwork/performer/details.json @@ -11,6 +11,12 @@ "required": ["details", "updatedAt"], "properties": { "details": { "type": "ref", "ref": "computer.localnetwork.defs#projectDetails" }, + "langs": { + "type": "array", + "description": "The languages the rate notes, tech rider and hospitality are written in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "updatedAt": { "type": "string", "format": "datetime" } } } diff --git a/lexicons/computer/localnetwork/planner/save.json b/lexicons/computer/localnetwork/planner/save.json index a79ac4588..09b058d45 100644 --- a/lexicons/computer/localnetwork/planner/save.json +++ b/lexicons/computer/localnetwork/planner/save.json @@ -12,6 +12,12 @@ "properties": { "project": { "type": "string", "format": "at-uri" }, "note": { "type": "string", "maxLength": 5000, "maxGraphemes": 500 }, + "langs": { + "type": "array", + "description": "The languages the note is written in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "createdAt": { "type": "string", "format": "datetime" } } } diff --git a/lexicons/computer/localnetwork/planner/show.json b/lexicons/computer/localnetwork/planner/show.json index adb6fe17d..6d25fbd23 100644 --- a/lexicons/computer/localnetwork/planner/show.json +++ b/lexicons/computer/localnetwork/planner/show.json @@ -11,6 +11,12 @@ "required": ["details", "lineup", "createdAt"], "properties": { "details": { "type": "ref", "ref": "computer.localnetwork.defs#showDetails" }, + "langs": { + "type": "array", + "description": "The languages the show's notes are written in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "lineup": { "type": "array", "maxLength": 40, "items": { "type": "ref", "ref": "#slot" } }, "createdAt": { "type": "string", "format": "datetime" }, "updatedAt": { "type": "string", "format": "datetime" } diff --git a/lexicons/computer/localnetwork/profile.json b/lexicons/computer/localnetwork/profile.json index 89e35295e..07151a57b 100644 --- a/lexicons/computer/localnetwork/profile.json +++ b/lexicons/computer/localnetwork/profile.json @@ -13,6 +13,12 @@ "basics": { "type": "ref", "ref": "computer.localnetwork.section.defs#basics" }, "performer": { "type": "ref", "ref": "computer.localnetwork.section.defs#performer" }, "promoter": { "type": "ref", "ref": "computer.localnetwork.section.defs#promoter" }, + "langs": { + "type": "array", + "description": "The languages the profile's text is written in, like its bio.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "takesInquiries": { "type": "boolean", "description": "Whether promoters can send this DJ booking inquiries on Local Network. Off unless true, and only counts while the performer section is on." diff --git a/lexicons/computer/localnetwork/project.json b/lexicons/computer/localnetwork/project.json index 038f582da..203a94ca4 100644 --- a/lexicons/computer/localnetwork/project.json +++ b/lexicons/computer/localnetwork/project.json @@ -12,6 +12,12 @@ "properties": { "slug": { "type": "string", "minLength": 2, "maxLength": 64 }, "profile": { "type": "ref", "ref": "computer.localnetwork.defs#projectProfile" }, + "langs": { + "type": "array", + "description": "The languages the profile's text is written in, like its bio: the request's it was published from, or the admin's who wrote it.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "managers": { "type": "array", "maxLength": 10, diff --git a/lexicons/computer/localnetwork/project/details.json b/lexicons/computer/localnetwork/project/details.json index 7afb80f28..824301f50 100644 --- a/lexicons/computer/localnetwork/project/details.json +++ b/lexicons/computer/localnetwork/project/details.json @@ -12,6 +12,12 @@ "properties": { "project": { "type": "string", "format": "at-uri" }, "details": { "type": "ref", "ref": "computer.localnetwork.defs#projectDetails" }, + "langs": { + "type": "array", + "description": "The languages the rate notes, tech rider and hospitality are written in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "updatedAt": { "type": "string", "format": "datetime" } } } diff --git a/lexicons/computer/localnetwork/staff/group.json b/lexicons/computer/localnetwork/staff/group.json index 99d5e2345..80892756a 100644 --- a/lexicons/computer/localnetwork/staff/group.json +++ b/lexicons/computer/localnetwork/staff/group.json @@ -12,6 +12,12 @@ "properties": { "name": { "type": "string", "maxLength": 640, "maxGraphemes": 64 }, "description": { "type": "string", "maxLength": 3000, "maxGraphemes": 300 }, + "langs": { + "type": "array", + "description": "The languages the description is written in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "members": { "type": "array", "maxLength": 5000, diff --git a/lexicons/computer/localnetwork/staff/role.json b/lexicons/computer/localnetwork/staff/role.json index c654ee240..158f8de32 100644 --- a/lexicons/computer/localnetwork/staff/role.json +++ b/lexicons/computer/localnetwork/staff/role.json @@ -20,6 +20,12 @@ "items": { "type": "string", "maxLength": 32, "knownValues": ["flags", "flagGroups"] } }, "note": { "type": "string", "maxLength": 3000, "maxGraphemes": 300 }, + "langs": { + "type": "array", + "description": "The languages the note is written in.", + "maxLength": 3, + "items": { "type": "string", "format": "language" } + }, "createdAt": { "type": "string", "format": "datetime" } } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b9e2a9d7e..685371b4d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -514,6 +514,15 @@ importers: '@electric-sql/pglite': specifier: ^0.5.16 version: 0.5.16 + '@inlang/cli': + specifier: ^3.6.0 + version: 3.6.0 + '@inlang/paraglide-js': + specifier: ^3.2.2 + version: 3.2.2(eslint@10.14.0(jiti@2.7.0)(supports-color@5.5.0))(typescript@6.0.3)(vite@8.3.4(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) + '@inlang/plugin-message-format': + specifier: ^4.6.0 + version: 4.6.0 '@jazzer.js/core': specifier: ^4.0.0 version: 4.0.0(supports-color@5.5.0) @@ -616,6 +625,9 @@ importers: playwright: specifier: ^1.63.0 version: 1.64.1 + pseudo-localization: + specifier: ^3.1.3 + version: 3.1.3 storybook: specifier: 10.6.2 version: 10.6.2(@types/react@19.3.0)(prettier@3.9.9)(react@19.3.0) @@ -1359,6 +1371,74 @@ packages: '@bufbuild/protobuf@1.10.1': resolution: {integrity: sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==} + '@bytecodealliance/jco-node-fs-darwin-arm64@0.3.2': + resolution: {integrity: sha512-WXQq1tRVUWhbK+ImH0G8Kni2AR0sdokLf/KyXRw5P6n4A9ZbgMHOuPfN/PEsYgw4eosuTAonutK0xILk/hA81A==} + engines: {node: '>=20'} + cpu: [arm64] + os: [darwin] + + '@bytecodealliance/jco-node-fs-darwin-x64@0.3.2': + resolution: {integrity: sha512-Fy/OjHnto7hNE5ksewVkmAMXG/uXyj+RAKFZWQFTzFkp73UyT5vuPjKq3nvx9KolUGWBG37BudEMb4ZAoD9TbQ==} + engines: {node: '>=20'} + cpu: [x64] + os: [darwin] + + '@bytecodealliance/jco-node-fs-linux-arm64-gnu@0.3.2': + resolution: {integrity: sha512-OafRtRu3tfOFQARfkia/LDEqSo2R3yAL1xPwzf4RcRW6JqkOY7qKWsUS5+LPVo/aFaSkMX7F7bdFGpFPmcoZJg==} + engines: {node: '>=20'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@bytecodealliance/jco-node-fs-linux-arm64-musl@0.3.2': + resolution: {integrity: sha512-JblDiwD7+Y+w0d/tjaNDX4QdGvh5lyuDc+S/jDeT7sYA1caA9yiwIjLa8PC/lm2xudqSxD+Cuy4AosXvl+qI0g==} + engines: {node: '>=20'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@bytecodealliance/jco-node-fs-linux-x64-gnu@0.3.2': + resolution: {integrity: sha512-6FzmHoLOsa6b4X9AuFLsvlpNF66Dt4sRRftZHaT1I1pYzCWrJkkpgNJhRXxf67ZPmOwBZJT4dan/g752Rx4xRw==} + engines: {node: '>=20'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@bytecodealliance/jco-node-fs-linux-x64-musl@0.3.2': + resolution: {integrity: sha512-SbAJG2PDV8YAHBESHU9sVSckOitJyvlezdF4CGP5/mOp01JnijVkLVXzGK62yVSfa5TpAybbSd1rk+v36NAW/Q==} + engines: {node: '>=20'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@bytecodealliance/jco-node-fs-win32-arm64-msvc@0.3.2': + resolution: {integrity: sha512-nUWYdFysRQJGsIOCk0KAYN2smkNYiHG7rZ7m+0ZXqP+5wqWxKEjkDsORwXiBjdaWFLVww0anZ3SBxrju6P7hXQ==} + engines: {node: '>=20'} + cpu: [arm64] + os: [win32] + + '@bytecodealliance/jco-node-fs-win32-x64-msvc@0.3.2': + resolution: {integrity: sha512-RsPj2t8TvltsMWK7/Z7JcVC/IWPMi07/AJkNLiNTCuGTdT/sseqTThJJwhuz3sjFw7dJdxA+bSGT+23y/KT0fw==} + engines: {node: '>=20'} + cpu: [x64] + os: [win32] + + '@bytecodealliance/jco-node-fs@0.3.2': + resolution: {integrity: sha512-yxvqQreNcOQdMsEKZomkSqThtkxrAz3f1Cmy8BsV0UHi9saa2/D1KDB14IAXPYwDq/maS6lCzS+MuMQx6QkUgA==} + engines: {node: '>=20'} + + '@bytecodealliance/jco-transpile@0.13.0': + resolution: {integrity: sha512-9hZ2GMqOlYP1Bf7qQ8v3sCsmkFoXGbgi0HtjHipzrgyk+9GGDzvvbehTGe0oM54rcbKJacvyjpPDn7wtpgzwYA==} + + '@bytecodealliance/preview2-shim@0.24.1': + resolution: {integrity: sha512-QGZsKD5M76xBhwu3BzLWqYDEpaMX90QWrrfhkQPn2pN9t378koumtdAVH4lr25mqGCZt10YNXkWvyWkw/vJbLQ==} + + '@bytecodealliance/preview2-shim@0.25.0': + resolution: {integrity: sha512-6ZSDRJ8hJc/febZepzd68z3KzLcOXyCOKtRm8LB2rgAU88xV7ykq6dMb5I4a+sBh1cuV2Yb1159gDzI1q8UsoQ==} + + '@bytecodealliance/preview3-shim@0.6.1': + resolution: {integrity: sha512-61mEfjfgGmZhEMA0H3waawPKvYd3za9y0vJ7pmQz/9yvm4FR6Ef+cmqhnxDE7ezsM07MY1btP92ymmgsgFwxmg==} + '@cacheable/memory@2.2.0': resolution: {integrity: sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==} @@ -1536,6 +1616,9 @@ packages: '@emnapi/core@1.11.0': resolution: {integrity: sha512-l9Oo58x0HOP5znGzVhYW9U3e5wVuA4LAZU2AGezTmkhO1CgQRFDhDg4nneHsu/t3WniXg9QrG2nIXL/ZS8ln8Q==} + '@emnapi/core@1.11.1': + resolution: {integrity: sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==} + '@emnapi/core@1.11.2': resolution: {integrity: sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==} @@ -1545,6 +1628,9 @@ packages: '@emnapi/runtime@1.11.0': resolution: {integrity: sha512-55coeOFKHv1ywEcUXJtWU5f+Jr/W5tZDvZig8DLKSwUN1JpROQ4rk/SNOQiFWmaR/VKF4zuFyW1B8JduOSv6Pg==} + '@emnapi/runtime@1.11.1': + resolution: {integrity: sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==} + '@emnapi/runtime@1.11.2': resolution: {integrity: sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==} @@ -2138,6 +2224,33 @@ packages: cpu: [x64] os: [win32] + '@inlang/cli@3.6.0': + resolution: {integrity: sha512-IQdki7NAXkA//RMEndIWu2bybQl1rAmtY1O+RPI26KJdRolDPauBfCPnmn39S1pQWBFJ68+oyLaj1mqqSswxuQ==} + engines: {node: '>=18.0.0'} + hasBin: true + + '@inlang/paraglide-js@3.2.2': + resolution: {integrity: sha512-YoQ2aHmzSgC+yfUgKwcJew3F0lFfwLJsriGCbwQHiJfjKGNjhQnbRr0OXoxsy2ulY2/gK8vYpiphuTv2J0wf5Q==} + hasBin: true + peerDependencies: + eslint: ^9.0.0 || ^10.0.0 + vite: '>=5.0.0' + peerDependenciesMeta: + eslint: + optional: true + vite: + optional: true + + '@inlang/plugin-message-format@4.6.0': + resolution: {integrity: sha512-DK2GZvypDygLchnUaFK/RdCIm2baiRlQftOiesGNKDtjNqioqWHnnu0zg6NKNlo3kD42h5xlRCke7zEjBFzZrg==} + + '@inlang/recommend-sherlock@0.2.1': + resolution: {integrity: sha512-ckv8HvHy/iTqaVAEKrr+gnl+p3XFNwe5D2+6w6wJk2ORV2XkcRkKOJ/XsTUJbPSiyi4PI+p+T3bqbmNx/rDUlg==} + + '@inlang/sdk@4.2.0': + resolution: {integrity: sha512-Cmaqvn34wsxiF27318Zw2rg+017HHNJWV5MH8rfyVKVANZNpzlztxzRbFienE/gASMLD8oluYHHolIb/p6Egrw==} + engines: {node: '>=20.0.0'} + '@inquirer/ansi@2.0.9': resolution: {integrity: sha512-0Ywt3S8tqM6TWUcsRlBFQ1x+X3/o8kktX0ZiKAnByYb9GFDknnOhse1PVtfiD2BXPI8ar+BWx9PV9R0lQIcygw==} engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'} @@ -2371,6 +2484,9 @@ packages: resolution: {integrity: sha512-jTvAYsCFnRKmbs+qEyCXnXmxf85kBDAaGhvyEah7zT7AjLJc8XqPTKhALT9i31Kxm7rQAQnRx58NNRiGYjGY5Q==} engines: {node: '>=22.19.0'} + '@lix-js/sdk@0.20.1': + resolution: {integrity: sha512-oscOFP8Cr1My6Wh2KVYC9+aJ1mHs+d7vnD+7PPJaA4L+Y1FR37Sm99SrFGfvUizaj/XtRi2GlDF2IOFt9iXMNQ==} + '@lucide/svelte@1.59.0': resolution: {integrity: sha512-ga9IrEsFJBkt/34VnRFcQ2HLs8eOpOovXZ62XzwfC7f0zBfo4y116FBIDroZkD0gInYYY2hSSAcsQEm/Vm+AoA==} peerDependencies: @@ -2876,6 +2992,133 @@ packages: peerDependencies: '@opentelemetry/api': ^1.10.0 + '@oxc-minify/binding-android-arm-eabi@0.136.0': + resolution: {integrity: sha512-gk1jzky1vLeOcK7w9Ib2RT/UooZ7O21s8YSeXCsy4tzsmguKb3Cbsv/Ra2fKhMp4mKeKCzvC1Xa41OfSBWfWdQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@oxc-minify/binding-android-arm64@0.136.0': + resolution: {integrity: sha512-5GIYanqud/ohXEcg2dsdn0+eSKXqclw5qlRUkvSM1sKEa4ZQ7hqOk8XPJBNPh3LXXw+Qw85B6jkmOFLKsCHp5w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@oxc-minify/binding-darwin-arm64@0.136.0': + resolution: {integrity: sha512-QAMpHKXWOoMCTenSZjQjVT5YmMooujlCKAf1T3PHFl2LuaA6ukQFXba0bgSLgAxRrAeX/itkwi4lzVQXtYmnRg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@oxc-minify/binding-darwin-x64@0.136.0': + resolution: {integrity: sha512-rDnoPj8hztiU8C1VNKuzujh7SgTJlgiUvUCiWQjTnVSLsABsLW9ZWd1l1Ji0VN3UW39wGpptgvahIWTrHnGH/A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@oxc-minify/binding-freebsd-x64@0.136.0': + resolution: {integrity: sha512-9fGSgP7uyPLCTjMx9z3AUV4UjnfOVoGTH5JzamLegPwGLJ97Gr1jht1437CRk8ZNabGmxQR6qNn3e+Tox2lswg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@oxc-minify/binding-linux-arm-gnueabihf@0.136.0': + resolution: {integrity: sha512-k0QvZS+x6ROI4O5Ikqn9dDU2dmkEJ46Yh6baZJI/eUk/a1k1GOs9/vyXItLZrKlwYrSgdEx2BFXbKgyd1NyRPw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxc-minify/binding-linux-arm-musleabihf@0.136.0': + resolution: {integrity: sha512-iRFxUc8ubotVfuyq3e4LPGbHrjvWd1/B3499a55GueMLc1EDJ0fHzNXJiCx2eMQGfzHtHodjmvrJ2BSvSXBNhQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxc-minify/binding-linux-arm64-gnu@0.136.0': + resolution: {integrity: sha512-hbKxNCXJsULrb6EyG5SumzJKuPfP8Y0UQ/TElRgXVUhyyPf6cBPlF8HMq+MAylF98ACBzV8jBp2Mm62lJyTo+w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@oxc-minify/binding-linux-arm64-musl@0.136.0': + resolution: {integrity: sha512-T+u/CGKW0UXemJeVux4ix6rK+ug3bQCUEbu5hFlX9K61KQNd44rOcrM15mDK99L7USaXwmiwHeIkEDvmmyDMSA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@oxc-minify/binding-linux-ppc64-gnu@0.136.0': + resolution: {integrity: sha512-WNPTN2F448tb49BoqjV9IMRzZWa0WB8GHzrB+bnxKQPOyzz07T6rmDKrr4Hjl81ADGjDYSsr1fgXcjyLQFdMdw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@oxc-minify/binding-linux-riscv64-gnu@0.136.0': + resolution: {integrity: sha512-MvcCfu8OeabrmNN9wqhh8Gqizg68RQ3iOvXBJmlLMy5p1PC6az9bAwqOk98lsCmKI4I5LpULekOlfxRYh3o5Kw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@oxc-minify/binding-linux-riscv64-musl@0.136.0': + resolution: {integrity: sha512-rwJXFUFFA0egAULtOOgfW8YhhLhtWrr2qFxftvZ7/U6Xtxiev8i+eCwSNW1RpHiX74QMsJVpRE3ykoefqb1MtQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@oxc-minify/binding-linux-s390x-gnu@0.136.0': + resolution: {integrity: sha512-qizAxHmj7VHm5/D5qiIlvzxAS2tlmadDOJ5XFI7zx/wfnk/+fdk5iVaHOv+C4tDE/4wLQyMoBYVIs6R1LeN91w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@oxc-minify/binding-linux-x64-gnu@0.136.0': + resolution: {integrity: sha512-gcyLAad0UblkEhGjVfx5Mwq63OSx8r04IbcfwzpZYpHisO/vioMsrs4GkDsQZ2Ejc8cdUk6YMIrf9FwNBzh+Dw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@oxc-minify/binding-linux-x64-musl@0.136.0': + resolution: {integrity: sha512-QAK6kwBjljX6luYzeppVdRP3gTaFNFfp9iS/V0cCvU43wUZay5xFXBgmzBHYrzZV2MhzURNnXfEZRo9poAxyvA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@oxc-minify/binding-openharmony-arm64@0.136.0': + resolution: {integrity: sha512-nIGxkTOnN9GwslmooxbZ3Ti2RgbX9QLHy0X9uO0pslOT+4dsNVUawBU/6r4M5cWM+ZdRD2tOF4V+n0l8tS59nQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@oxc-minify/binding-wasm32-wasi@0.136.0': + resolution: {integrity: sha512-YB3G8AHT6PpDS8/DfjlJrQjywj+/6gCkNBcAJdYzcYbQRIZE6SaTNowiGuZPR1m1jOl1WjcjefniKSmVxzhvRA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [wasm32] + + '@oxc-minify/binding-win32-arm64-msvc@0.136.0': + resolution: {integrity: sha512-UVRH3BlNc2rmla+sbSd5xTF/u+esCqZS6VSWPolZybcBh3TlVe1Sf5MOuHQWUaFoyv5uFOvee4hOfS/14nPvZw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@oxc-minify/binding-win32-ia32-msvc@0.136.0': + resolution: {integrity: sha512-zFGkUd82jci0E+isc2O36lVmmXVUDXyEMN2RYIyez+MBNqhdjPLIGx62FCsrJtLKeuiPf/8XkFv977aUtndUng==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ia32] + os: [win32] + + '@oxc-minify/binding-win32-x64-msvc@0.136.0': + resolution: {integrity: sha512-VHgPwd5xibC9UYxBeq7nURTjY+wxhdumllij6JaCIUVfD9IRcrA66SVlJ5fPNoUXcRp8ZXhJfoIZwVz9wAEGJw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + '@oxc-parser/binding-android-arm-eabi@0.127.0': resolution: {integrity: sha512-0LC7ye4hvqbIKxAzThzvswgHLFu2AURKzYLeSVvLdu2TBOYWQDmHnTqPLeA597BcUCxiLqLsS4CJ5uoI5WYWCQ==} engines: {node: ^20.19.0 || >=22.12.0} @@ -3970,6 +4213,9 @@ packages: resolution: {integrity: sha512-fCTuZK4QBa+39Oz9l4OGfJfz+GpwCp3AqO7Zch3to99xHPgstVsRFpeQ8LNd2o1Gv8raL2mCFwiaHh7bFSp5DQ==} engines: {node: '>=22'} + '@sinclair/typebox@0.31.30': + resolution: {integrity: sha512-MGsM7bVmHg3sUKCphlu3SGQ+T+5JTbygZWYArfKQCW5anJeACHeqLhcnf+R7XlCWZ+QR3C8JTBx3kCKJTN69ow==} + '@sindresorhus/is@4.6.0': resolution: {integrity: sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==} engines: {node: '>=10'} @@ -4846,6 +5092,9 @@ packages: array-flatten@1.1.1: resolution: {integrity: sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==} + array-timsort@1.0.3: + resolution: {integrity: sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ==} + asciinema-player@3.18.0: resolution: {integrity: sha512-5gpt2ipFcy4NKmgkv+c/QXnJ9zMicxqWROCOuJqgwwtiYKM8Qe9hnDOvfqke5bW6M2DW/seO3uQYkQ0xeUUVtw==} @@ -4921,6 +5170,10 @@ packages: bignumber.js@9.3.1: resolution: {integrity: sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==} + binaryen@130.0.0: + resolution: {integrity: sha512-XDrb+zql0RbFPKgj7MuH9zOc78R3Fa/P/VSGnnpdwYsvNZPWjcMYMdAkKCOQEL2A7yqgjSMTDRFp6gfSDW+/QQ==} + hasBin: true + bindings@1.5.0: resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==} @@ -5170,6 +5423,10 @@ packages: resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} engines: {node: '>= 0.8'} + commander@11.1.0: + resolution: {integrity: sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==} + engines: {node: '>=16'} + commander@14.0.3: resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==} engines: {node: '>=20'} @@ -5182,6 +5439,10 @@ packages: resolution: {integrity: sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==} engines: {node: '>= 10'} + comment-json@4.6.2: + resolution: {integrity: sha512-R2rze/hDX30uul4NZoIZ76ImSJLFxn/1/ZxtKC1L77y2X1k+yYu1joKbAtMA2Fg3hZrTOiw0I5mwVMo0cf250w==} + engines: {node: '>= 6'} + compressible@2.0.18: resolution: {integrity: sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==} engines: {node: '>= 0.6'} @@ -5197,6 +5458,10 @@ packages: resolution: {integrity: sha512-U51WPZg+o6FDFhBCV6yYFEspGMCoHvCgJSGFw9AwsW2u75gYBPoDlYca5XfDs4TdMUu3/y0R6FFdvvgyH31mKQ==} engines: {node: '>=20'} + consola@3.4.0: + resolution: {integrity: sha512-EiPU8G6dQG0GFHNR8ljnZFki/8a+cQwEQ+7wpxdChl02Q8HXlwEZWD5lqAF8vC2sEC3Tehr8hy7vErz88LHyUA==} + engines: {node: ^14.18.0 || >=16.10.0} + consola@3.4.2: resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==} engines: {node: ^14.18.0 || >=16.10.0} @@ -5731,6 +5996,11 @@ packages: es-toolkit@1.52.0: resolution: {integrity: sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==} + esbuild-wasm@0.19.12: + resolution: {integrity: sha512-Zmc4hk6FibJZBcTx5/8K/4jT3/oG1vkGTEeKJUQFCUQKimD6Q7+adp/bdVQyYJFolMKaXkQnVZdV4O5ZaTYmyQ==} + engines: {node: '>=12'} + hasBin: true + esbuild@0.28.2: resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} engines: {node: '>=18'} @@ -6625,6 +6895,10 @@ packages: resolution: {integrity: sha512-TH+b56pVXQq0tsyooYLeNfV11j6ih7D50dyN8tkM0e7ndiUH28Nziojiog3qRFlmEj9XePYdZUrNJ2079Qjdow==} engines: {node: '>=14.0.0'} + kysely@0.28.20: + resolution: {integrity: sha512-D7rXCs0Psxq2hqjg15PGzk/k2bsWY1ohT9o/Xzl8SzgWExT6GiHCz4Z0NP1z5uOE3WBG7gJ46kYdgLYCOlaLoA==} + engines: {node: '>=20.0.0'} + kysely@0.29.9: resolution: {integrity: sha512-K48ErswC3MlIcBqR0pYIIEl+n9rIgwxgzaM1FxKHMXn7egxr1NHj7bCeF98mXl9A3/QoL5I7mo5S/mLXgeDgGA==} engines: {node: '>=22.0.0'} @@ -7256,6 +7530,10 @@ packages: resolution: {integrity: sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==} engines: {node: '>=10'} + oxc-minify@0.136.0: + resolution: {integrity: sha512-u9UvPFTYVwQ/i1kpp/c20S/SbvLaLV0Ngzyhgi0YV4B1SlxM7RgnnePl4vY9N3Z9sTRcozL1MRStI3PlUN9RFA==} + engines: {node: ^20.19.0 || >=22.12.0} + oxc-parser@0.127.0: resolution: {integrity: sha512-bkgD4qHlN7WxLdX8bLXdaU54TtQtAIg/ZBAfm0aje/mo3MRDo3P0hZSgr4U7O3xfX+fQmR5AP04JS/TGcZLcFA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -7624,6 +7902,11 @@ packages: resolution: {integrity: sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==} engines: {node: '>=10'} + pseudo-localization@3.1.3: + resolution: {integrity: sha512-CUfwat30M5OPGWitLw2egrEc+pyHqBOfsLXY/F1YxqjSYNno0Xf8GYYgYq8/uDQRykeQOi23bWK+uWIl8KUqvA==} + engines: {node: '>=22'} + hasBin: true + pump@3.0.4: resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==} @@ -8442,6 +8725,9 @@ packages: url-join@4.0.1: resolution: {integrity: sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==} + urlpattern-polyfill@10.1.0: + resolution: {integrity: sha512-IGjKp/o0NL3Bso1PymYURCJxMPNAf/ILOpendP9f5B6e1rTJgdgiOvgfoT8VxCAdY+Wisb9uhGaJJf3yZ2V9nw==} + use-sync-external-store@1.7.0: resolution: {integrity: sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==} peerDependencies: @@ -8461,6 +8747,14 @@ packages: resolution: {integrity: sha512-Sc5u1VVln93y1Xnz4R+CunOZc7R9LUcTmhj7Rc7Eg3HVcf7rVn2FOoa812fe0W8p3jD7xeoGSYbfqCGGH2B6xw==} hasBin: true + valibot@1.5.0: + resolution: {integrity: sha512-nil6AkP2TChWL43Z5uJ6GTxX01CUA+g8LWUM+N/rB9NBbkUMaUsi9PUNzlUPgoKASgmx9f7eGOYpJ04/fSa6FQ==} + peerDependencies: + typescript: '>=5' + peerDependenciesMeta: + typescript: + optional: true + varint@6.0.0: resolution: {integrity: sha512-cXEIW6cfr15lFv563k4GuVuW/fiwjknytD37jIOLSdSWuOI6WnO/oKwmP2FQTU2l01LP8/M5TSAJpzUaGe3uWg==} @@ -10042,6 +10336,61 @@ snapshots: '@bufbuild/protobuf@1.10.1': {} + '@bytecodealliance/jco-node-fs-darwin-arm64@0.3.2': + optional: true + + '@bytecodealliance/jco-node-fs-darwin-x64@0.3.2': + optional: true + + '@bytecodealliance/jco-node-fs-linux-arm64-gnu@0.3.2': + optional: true + + '@bytecodealliance/jco-node-fs-linux-arm64-musl@0.3.2': + optional: true + + '@bytecodealliance/jco-node-fs-linux-x64-gnu@0.3.2': + optional: true + + '@bytecodealliance/jco-node-fs-linux-x64-musl@0.3.2': + optional: true + + '@bytecodealliance/jco-node-fs-win32-arm64-msvc@0.3.2': + optional: true + + '@bytecodealliance/jco-node-fs-win32-x64-msvc@0.3.2': + optional: true + + '@bytecodealliance/jco-node-fs@0.3.2': + optionalDependencies: + '@bytecodealliance/jco-node-fs-darwin-arm64': 0.3.2 + '@bytecodealliance/jco-node-fs-darwin-x64': 0.3.2 + '@bytecodealliance/jco-node-fs-linux-arm64-gnu': 0.3.2 + '@bytecodealliance/jco-node-fs-linux-arm64-musl': 0.3.2 + '@bytecodealliance/jco-node-fs-linux-x64-gnu': 0.3.2 + '@bytecodealliance/jco-node-fs-linux-x64-musl': 0.3.2 + '@bytecodealliance/jco-node-fs-win32-arm64-msvc': 0.3.2 + '@bytecodealliance/jco-node-fs-win32-x64-msvc': 0.3.2 + + '@bytecodealliance/jco-transpile@0.13.0': + dependencies: + '@bytecodealliance/preview2-shim': 0.24.1 + '@bytecodealliance/preview3-shim': 0.6.1 + binaryen: 130.0.0 + oxc-minify: 0.136.0 + + '@bytecodealliance/preview2-shim@0.24.1': + dependencies: + '@bytecodealliance/jco-node-fs': 0.3.2 + + '@bytecodealliance/preview2-shim@0.25.0': + dependencies: + '@bytecodealliance/jco-node-fs': 0.3.2 + + '@bytecodealliance/preview3-shim@0.6.1': + dependencies: + '@bytecodealliance/jco-node-fs': 0.3.2 + '@bytecodealliance/preview2-shim': 0.25.0 + '@cacheable/memory@2.2.0': dependencies: '@cacheable/utils': 2.5.0 @@ -10280,6 +10629,12 @@ snapshots: tslib: 2.8.1 optional: true + '@emnapi/core@1.11.1': + dependencies: + '@emnapi/wasi-threads': 1.2.2 + tslib: 2.8.1 + optional: true + '@emnapi/core@1.11.2': dependencies: '@emnapi/wasi-threads': 1.2.2 @@ -10297,6 +10652,11 @@ snapshots: tslib: 2.8.1 optional: true + '@emnapi/runtime@1.11.1': + dependencies: + tslib: 2.8.1 + optional: true + '@emnapi/runtime@1.11.2': dependencies: tslib: 2.8.1 @@ -10732,6 +11092,45 @@ snapshots: '@img/sharp-win32-x64@0.35.5': optional: true + '@inlang/cli@3.6.0': + dependencies: + '@inlang/sdk': 4.2.0 + esbuild-wasm: 0.19.12 + + '@inlang/paraglide-js@3.2.2(eslint@10.14.0(jiti@2.7.0)(supports-color@5.5.0))(typescript@6.0.3)(vite@8.3.4(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': + dependencies: + '@inlang/recommend-sherlock': 0.2.1 + '@inlang/sdk': 4.2.0 + commander: 11.1.0 + consola: 3.4.0 + jiti: 2.7.0 + json5: 2.2.3 + magic-string: 0.30.21 + unplugin: 2.3.11 + urlpattern-polyfill: 10.1.0 + valibot: 1.5.0(typescript@6.0.3) + optionalDependencies: + eslint: 10.14.0(jiti@2.7.0)(supports-color@5.5.0) + vite: 8.3.4(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) + transitivePeerDependencies: + - typescript + + '@inlang/plugin-message-format@4.6.0': + dependencies: + '@inlang/sdk': 4.2.0 + '@sinclair/typebox': 0.31.30 + + '@inlang/recommend-sherlock@0.2.1': + dependencies: + comment-json: 4.6.2 + + '@inlang/sdk@4.2.0': + dependencies: + '@lix-js/sdk': 0.20.1 + '@sinclair/typebox': 0.31.30 + kysely: 0.28.20 + uuid: 14.0.3 + '@inquirer/ansi@2.0.9': {} '@inquirer/checkbox@5.2.6(@types/node@24.19.2)': @@ -11020,6 +11419,12 @@ snapshots: - webpack - yauzl + '@lix-js/sdk@0.20.1': + dependencies: + '@bytecodealliance/jco-transpile': 0.13.0 + binaryen: 130.0.0 + fflate: 0.8.3 + '@lucide/svelte@1.59.0(svelte@5.57.2(@typescript-eslint/types@8.72.1))': dependencies: svelte: 5.57.2(@typescript-eslint/types@8.72.1) @@ -11041,6 +11446,13 @@ snapshots: '@tybys/wasm-util': 0.10.4 optional: true + '@napi-rs/wasm-runtime@1.2.4(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)': + dependencies: + '@emnapi/core': 1.11.1 + '@emnapi/runtime': 1.11.1 + '@tybys/wasm-util': 0.10.4 + optional: true + '@napi-rs/wasm-runtime@1.2.4(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)': dependencies: '@emnapi/core': 1.11.2 @@ -11722,6 +12134,70 @@ snapshots: '@opentelemetry/api': 1.10.0 '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@oxc-minify/binding-android-arm-eabi@0.136.0': + optional: true + + '@oxc-minify/binding-android-arm64@0.136.0': + optional: true + + '@oxc-minify/binding-darwin-arm64@0.136.0': + optional: true + + '@oxc-minify/binding-darwin-x64@0.136.0': + optional: true + + '@oxc-minify/binding-freebsd-x64@0.136.0': + optional: true + + '@oxc-minify/binding-linux-arm-gnueabihf@0.136.0': + optional: true + + '@oxc-minify/binding-linux-arm-musleabihf@0.136.0': + optional: true + + '@oxc-minify/binding-linux-arm64-gnu@0.136.0': + optional: true + + '@oxc-minify/binding-linux-arm64-musl@0.136.0': + optional: true + + '@oxc-minify/binding-linux-ppc64-gnu@0.136.0': + optional: true + + '@oxc-minify/binding-linux-riscv64-gnu@0.136.0': + optional: true + + '@oxc-minify/binding-linux-riscv64-musl@0.136.0': + optional: true + + '@oxc-minify/binding-linux-s390x-gnu@0.136.0': + optional: true + + '@oxc-minify/binding-linux-x64-gnu@0.136.0': + optional: true + + '@oxc-minify/binding-linux-x64-musl@0.136.0': + optional: true + + '@oxc-minify/binding-openharmony-arm64@0.136.0': + optional: true + + '@oxc-minify/binding-wasm32-wasi@0.136.0': + dependencies: + '@emnapi/core': 1.11.1 + '@emnapi/runtime': 1.11.1 + '@napi-rs/wasm-runtime': 1.2.4(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1) + optional: true + + '@oxc-minify/binding-win32-arm64-msvc@0.136.0': + optional: true + + '@oxc-minify/binding-win32-ia32-msvc@0.136.0': + optional: true + + '@oxc-minify/binding-win32-x64-msvc@0.136.0': + optional: true + '@oxc-parser/binding-android-arm-eabi@0.127.0': optional: true @@ -12323,6 +12799,8 @@ snapshots: '@simple-libs/stream-utils@2.0.0': {} + '@sinclair/typebox@0.31.30': {} + '@sindresorhus/is@4.6.0': {} '@sindresorhus/merge-streams@4.0.0': {} @@ -13275,6 +13753,8 @@ snapshots: array-flatten@1.1.1: {} + array-timsort@1.0.3: {} + asciinema-player@3.18.0: dependencies: solid-js: 1.9.19 @@ -13343,6 +13823,8 @@ snapshots: bignumber.js@9.3.1: {} + binaryen@130.0.0: {} + bindings@1.5.0: dependencies: file-uri-to-path: 1.0.0 @@ -13631,12 +14113,19 @@ snapshots: dependencies: delayed-stream: 1.0.0 + commander@11.1.0: {} + commander@14.0.3: {} commander@15.0.0: {} commander@7.2.0: {} + comment-json@4.6.2: + dependencies: + array-timsort: 1.0.3 + esprima: 4.0.1 + compressible@2.0.18: dependencies: mime-db: 1.54.0 @@ -13664,6 +14153,8 @@ snapshots: is-safe-filename: 0.1.1 xdg-basedir: 5.1.0 + consola@3.4.0: {} + consola@3.4.2: {} content-disposition@0.5.4: @@ -14149,6 +14640,8 @@ snapshots: es-toolkit@1.52.0: {} + esbuild-wasm@0.19.12: {} + esbuild@0.28.2: optionalDependencies: '@esbuild/aix-ppc64': 0.28.2 @@ -15086,6 +15579,8 @@ snapshots: kysely@0.23.5: {} + kysely@0.28.20: {} + kysely@0.29.9: {} lande@1.0.10: @@ -15635,6 +16130,29 @@ snapshots: strip-ansi: 6.0.1 wcwidth: 1.0.1 + oxc-minify@0.136.0: + optionalDependencies: + '@oxc-minify/binding-android-arm-eabi': 0.136.0 + '@oxc-minify/binding-android-arm64': 0.136.0 + '@oxc-minify/binding-darwin-arm64': 0.136.0 + '@oxc-minify/binding-darwin-x64': 0.136.0 + '@oxc-minify/binding-freebsd-x64': 0.136.0 + '@oxc-minify/binding-linux-arm-gnueabihf': 0.136.0 + '@oxc-minify/binding-linux-arm-musleabihf': 0.136.0 + '@oxc-minify/binding-linux-arm64-gnu': 0.136.0 + '@oxc-minify/binding-linux-arm64-musl': 0.136.0 + '@oxc-minify/binding-linux-ppc64-gnu': 0.136.0 + '@oxc-minify/binding-linux-riscv64-gnu': 0.136.0 + '@oxc-minify/binding-linux-riscv64-musl': 0.136.0 + '@oxc-minify/binding-linux-s390x-gnu': 0.136.0 + '@oxc-minify/binding-linux-x64-gnu': 0.136.0 + '@oxc-minify/binding-linux-x64-musl': 0.136.0 + '@oxc-minify/binding-openharmony-arm64': 0.136.0 + '@oxc-minify/binding-wasm32-wasi': 0.136.0 + '@oxc-minify/binding-win32-arm64-msvc': 0.136.0 + '@oxc-minify/binding-win32-ia32-msvc': 0.136.0 + '@oxc-minify/binding-win32-x64-msvc': 0.136.0 + oxc-parser@0.127.0: dependencies: '@oxc-project/types': 0.127.0 @@ -16152,6 +16670,8 @@ snapshots: proxy-from-env@2.1.0: {} + pseudo-localization@3.1.3: {} + pump@3.0.4: dependencies: end-of-stream: 1.4.5 @@ -17050,6 +17570,8 @@ snapshots: url-join@4.0.1: {} + urlpattern-polyfill@10.1.0: {} + use-sync-external-store@1.7.0(react@19.3.0): dependencies: react: 19.3.0 @@ -17062,6 +17584,10 @@ snapshots: uuid@14.0.3: {} + valibot@1.5.0(typescript@6.0.3): + optionalDependencies: + typescript: 6.0.3 + varint@6.0.0: {} vary@1.1.2: {} diff --git a/tools/ast-grep/rules/no-raw-text.yml b/tools/ast-grep/rules/no-raw-text.yml new file mode 100644 index 000000000..d47011eba --- /dev/null +++ b/tools/ast-grep/rules/no-raw-text.yml @@ -0,0 +1,28 @@ +# Text a page shows comes from the message catalog (apps/web/messages/en.json, through `m`), so a +# translation can replace it and the en-XA pseudo-locale shows what's left. This finds words written +# straight into a component's markup: its text, and the attributes a screen reader or a tooltip reads +# out. It can't see a string literal inside `{...}`, which en-XA still shows. `files` lists the +# components whose text has moved to the catalog; add each one as it moves. +id: no-raw-text +language: Html +severity: error +message: This writes words into the page instead of taking them from the message catalog. +note: Add the words to apps/web/messages/en.json, run `node scripts/pseudo-locale.ts` in apps/web, and use the message, like `{m.footer_privacy()}`. +files: + - 'apps/web/src/routes/+layout.svelte' +rule: + any: + # A letter outside any `{...}`. An HTML entity like ` ` doesn't count. The HTML parser ends a + # tag at an arrow function's `>`, which puts the rest of the expression in the text (and can lose + # the element's own text), so a run of text that reaches a `}` is code. + - kind: text + regex: '(?:^|\})[^{}&]*\p{L}[^{}]*(?:\{|$)' + - kind: attribute_value + regex: '^[^{]*\p{L}' + inside: + kind: quoted_attribute_value + inside: + kind: attribute + has: + kind: attribute_name + regex: '^(aria-label|aria-description|title|alt|placeholder)$' diff --git a/tools/ast-grep/tests/no-raw-text-test.yml b/tools/ast-grep/tests/no-raw-text-test.yml new file mode 100644 index 000000000..8a85bb4d9 --- /dev/null +++ b/tools/ast-grep/tests/no-raw-text-test.yml @@ -0,0 +1,28 @@ +id: no-raw-text +valid: + - | + {m.footer_privacy()} + - | + + - | + {count} · {m.shows()} + - | + + {m.report()} + - | + + - | + +invalid: + - | + Privacy + - | + Records on {protocol} · private data + - | + + - | + + - | + Mixer From db7f32d9d394d993261309ce02799e3995957c8a Mon Sep 17 00:00:00 2001 From: botandbang <337765928+botandbang@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:58:20 -0600 Subject: [PATCH 07/22] fix(web): cap how much of a repo export the syncer reads, skip records too deep to decode, and property-test sync recover() read getRepo's archive with nothing capping it, so a hostile repo host could stream until the server ran out of memory. It now stops at REPO_EXPORT_MAX_BYTES with the cap serviceApiFetch uses, logs the repo and leaves it to its retry. A record nested a few thousand levels deep overflowed the CBOR decoder and failed the whole repo; repo-archive.ts now logs and skips that record and still counts it toward the commit. readOpsPage takes the page's text and rejects anything it can't read as the host failing listRepoOps. fast-check properties fed by the lexicon arbitraries show it reads or rejects any page body and never passes on a value too deep for validateRecord, and that projecting any record applies or skips it without throwing, changes nothing when validation or the authority rules refuse it, and settles the same on replay. Fixes LOC-254 Fixes LOC-522 --- apps/web/docs/diagrams/spaces.md | 4 +- apps/web/package.json | 2 + .../web/src/lib/server/atproto/credentials.ts | 2 +- apps/web/src/lib/server/sync/engine.test.ts | 450 +++++++++++++++++- apps/web/src/lib/server/sync/engine.ts | 95 ++-- .../src/lib/server/sync/projections.test.ts | 280 ++++++++++- apps/web/src/lib/server/sync/repo-archive.ts | 96 ++++ apps/web/src/lib/server/testing/space-host.ts | 19 +- pnpm-lock.yaml | 6 + 9 files changed, 902 insertions(+), 52 deletions(-) create mode 100644 apps/web/src/lib/server/sync/repo-archive.ts diff --git a/apps/web/docs/diagrams/spaces.md b/apps/web/docs/diagrams/spaces.md index 617858a56..7817c033c 100644 --- a/apps/web/docs/diagrams/spaces.md +++ b/apps/web/docs/diagrams/spaces.md @@ -93,7 +93,7 @@ flowchart TD List -- "a repo left
the writer set" --> Keep["Read past it, keep
its synced records"] List -- "authority says
it's gone" --> Drop["Drop the local copy
and what came from it"] List --> Ops["Each repo that's behind, 4 at a time
across all spaces: listRepoOps since local rev"] - List -- "never synced" --> Star["getRepo: verified STAR archive"] + List -- "never synced" --> Star["getRepo: verified STAR archive,
256 MiB at most"] Ops -- "fails, not on a MAC or credential,
or runs past 100 pages" --> Star Ops -- "writer taken down,
suspended or deactivated" --> Skip["Skip, retry on backoff"] Star -- "same errors" --> Skip @@ -103,7 +103,7 @@ flowchart TD Project --> Due["Repos and projections whose retry
is due, then save spaceRev"] ``` -Source: [`src/lib/server/sync/engine.ts`](../../src/lib/server/sync/engine.ts) +Source: [`src/lib/server/sync/engine.ts`](../../src/lib/server/sync/engine.ts), [`src/lib/server/sync/repo-archive.ts`](../../src/lib/server/sync/repo-archive.ts) ## Repo sync lifecycle diff --git a/apps/web/package.json b/apps/web/package.json index c7e7f6957..7fd345b2b 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -53,6 +53,7 @@ }, "dependencies": { "@atproto-labs/did-resolver": "0.0.0-spaces-alpha-20261113224550", + "@atproto-labs/fetch": "0.4.2", "@atproto-labs/fetch-node": "0.0.0-spaces-alpha-20261113224550", "@atproto-labs/handle-resolver-node": "0.0.0-spaces-alpha-20261113224550", "@atproto/api": "0.0.0-spaces-alpha-20261113224550", @@ -66,6 +67,7 @@ "@atproto/oauth-client-node": "0.0.0-spaces-alpha-20261113224550", "@atproto/oauth-scopes": "0.0.0-spaces-alpha-20261113224550", "@atproto/space": "0.0.0-spaces-alpha-20261113224550", + "@atproto/star": "0.0.0-spaces-alpha-20261113224550", "@atproto/syntax": "0.0.0-spaces-alpha-20261113224550", "@atproto/xrpc-server": "0.0.0-spaces-alpha-20261113224550", "@aws-sdk/client-s3": "^3.1159.0", diff --git a/apps/web/src/lib/server/atproto/credentials.ts b/apps/web/src/lib/server/atproto/credentials.ts index cf7016d06..580223d22 100644 --- a/apps/web/src/lib/server/atproto/credentials.ts +++ b/apps/web/src/lib/server/atproto/credentials.ts @@ -398,7 +398,7 @@ const xrpcErrorBody = z * recursion goes, a key lex JSON refuses, the wrong shape, a credential that isn't a space token) is the host's * failure, so it rejects as one, naming the method. */ -function readAnswer(nsid: string, read: () => T): T { +export function readAnswer(nsid: string, read: () => T): T { try { return read(); } catch (error) { diff --git a/apps/web/src/lib/server/sync/engine.test.ts b/apps/web/src/lib/server/sync/engine.test.ts index e40678183..1c9a545cd 100644 --- a/apps/web/src/lib/server/sync/engine.test.ts +++ b/apps/web/src/lib/server/sync/engine.test.ts @@ -1,17 +1,94 @@ +import { encode } from '@atproto/lex-cbor'; +import type { LexMap } from '@atproto/lex-data'; +import { type JsonObject, type JsonValue, jsonToLex, lexToJson } from '@atproto/lex-json'; import { RepoCommit } from '@atproto/space'; +import * as fc from 'fast-check'; import { SPACE_TYPE } from '#lib/nsid.ts'; import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'; import { SpaceCredentialManager, XrpcResponseError } from '../atproto/credentials'; import { IdentityResolver } from '../atproto/identity'; +import { RecordValidationError, TOO_DEEP, validateRecord } from '../atproto/lexicons'; import { bookingSpace } from '../atproto/spaces'; import { type Db, nowIso, openDatabase } from '../db'; import { type Logger, silentLogger } from '../logger'; +import { anyRecord, RECORD_COLLECTIONS, recordKey, validRecord } from '../testing/lexicon-arbitraries'; import { FakeSpaceHost } from '../testing/space-host'; import { writtenLog } from '../testing/written-log'; -import { type ChangeHandler, type SyncedChange, SpaceSyncer } from './engine'; +import { type ChangeHandler, readOpsPage, type SyncedChange, SpaceSyncer } from './engine'; const SPACE = bookingSpace('did:plc:root', 'gig'); +// Stands in for arrays nested this deep, written into a listRepoOps page's text: JSON.stringify overflows the stack on +// them long before JSON.parse does. +const nested = (levels: number) => `\u0000nested:${levels}`; + +const NESTED = /"\\u0000nested:(\d+)"/g; + +/** A listRepoOps page as its text, with the arrays `nested` stands in for written out. */ +const write = (page: JsonValue) => + JSON.stringify(page).replace( + NESTED, + (_, levels: string) => `${'['.repeat(Number(levels))}0${']'.repeat(Number(levels))}` + ); + +/** Anything a repo could hold, or a valid record with arrays nested around the depth limit or far past the stack. */ +const opValue = (collection: string) => + fc.oneof( + anyRecord(collection), + fc + .tuple( + validRecord(collection), + fc.oneof(fc.integer({ min: 28, max: 36 }), fc.integer({ min: 1_000, max: 30_000 })) + ) + .map(([record, levels]): JsonObject => ({ ...record, nested: nested(levels) })) + ); + +/** Whether validateRecord refuses `value` as too deep. It throws nothing but RecordValidationError, which this rethrows. */ +function isTooDeepFor(collection: string, value: JsonObject): boolean { + try { + validateRecord(collection, value); + + return false; + } catch (error) { + if (!(error instanceof RecordValidationError)) throw error; + + return error.message === `Invalid ${collection} record: ${TOO_DEEP}`; + } +} + +/** A listRepoOps page as JSON. */ +type OpsPageJson = JsonObject & { ops: JsonObject[]; commit: JsonObject }; + +/** The fields of a listRepoOps page, each with what holds it: the page, its commit, or its first op. */ +const FIELDS = [ + ['page', 'ops'], + ['page', 'commit'], + ['page', 'cursor'], + ['commit', 'rev'], + ['commit', 'data'], + ['op', 'collection'], + ['op', 'rkey'], + ['op', 'cid'], + ['op', 'prev'], + ['op', 'value'] +] as const; + +// SAFETY: lexToJson only rewrites the CIDs and bytes inside a map, so a LexMap always comes back as a JSON object. +const asJson = (value: LexMap) => lexToJson(value) as JsonObject; + +/** A copy of `page` with `field` set to `value`, or taken out without one, where the page has it. */ +function withFieldSet(page: OpsPageJson, [holder, key]: (typeof FIELDS)[number], value: JsonValue | undefined) { + const copy: OpsPageJson = JSON.parse(JSON.stringify(page)); + const fields = holder === 'page' ? copy : holder === 'commit' ? copy.commit : copy.ops.at(0); + + if (!fields) return copy; + + if (value === undefined) delete fields[key]; + else fields[key] = value; + + return copy; +} + describe('SpaceSyncer', () => { let db: Db; let passes: number; @@ -207,7 +284,7 @@ describe('SpaceSyncer against a repo host', () => { const syncer = async ( onChange: ChangeHandler = async (change) => void changes.push(change), notifyEndpoint: string | null = null, - maxPages?: number + options: { maxPages?: number; maxRepoBytes?: number; logger?: Logger } = {} ) => { const credentials = new SpaceCredentialManager({ source: async () => ({ getDelegationToken: async () => 'token' }), @@ -218,13 +295,14 @@ describe('SpaceSyncer against a repo host', () => { const s: SpaceSyncer = new SpaceSyncer({ db, - logger: silentLogger, + logger: options.logger ?? silentLogger, notifyEndpoint, onChange, onSpaceDropped: async (space) => void dropped.push(space), identity: host.identity, credentials, - maxPages + maxPages: options.maxPages, + maxRepoBytes: options.maxRepoBytes }); await s.watch(SPACE); @@ -281,6 +359,36 @@ describe('SpaceSyncer against a repo host', () => { expect((await repoRow())?.lastError).toBeNull(); }); + it.each([32, 4_000])( + 'downloads a repo holding a record nested in %i arrays, logging and leaving out that one', + async (levels) => { + const { logger, notes } = writtenLog(); + const s = await syncer(undefined, null, { logger }); + await host.put(DJ, NOTE, 'a', note('one')); + // Written as DRISL by hand, since the encoder overflows its stack on a record this deep: { deep: [[...0...]] }. + const deep = Uint8Array.of(0xa1, 0x64, ...Buffer.from('deep'), ...Array(levels).fill(0x81), 0x00); + await host.putEncoded(DJ, NOTE, 'b', deep); + await host.put(DJ, NOTE, 'c', note('three')); + + await s.sync(SPACE); + expect(await records()).toEqual([ + ['a', 'one'], + ['c', 'three'] + ]); + expect((await repoRow())?.lastError).toBeNull(); + const warnings = notes().filter(({ level }) => level === 'warn'); + expect(warnings.map(({ message, uri }) => [message, uri])).toEqual([ + ['dropping a synced record nested deeper than 32 levels', `${SPACE}/${DJ}/${NOTE}/b`] + ]); + + // The record still counts toward the repo's commit, so the oplog picks up from there. + await host.put(DJ, NOTE, 'd', note('four')); + await s.sync(SPACE); + expect((await records()).at(-1)).toEqual(['d', 'four']); + expect(calls('getRepo')).toHaveLength(1); + } + ); + describe('with one failing repo among good ones', () => { const BAD = 'did:plc:bad'; const NOON = new Date('2026-11-04T12:00:00.000Z').getTime(); @@ -566,14 +674,14 @@ describe('SpaceSyncer against a repo host', () => { }); /** Has the host answer the methods in `nsids` with `edit(response)` instead, as a broken or hostile host could. */ - const tamper = (nsids: string[], edit: (response: Response) => Promise) => { + const tamper = (nsids: string[], edit: (response: Response, url: URL) => Promise) => { const real = host.fetch; vi.spyOn(host, 'fetch').mockImplementation(async (input, init) => { const url = new URL(input instanceof Request ? input.url : input); const nsid = url.pathname.replace('/xrpc/com.atproto.space.', ''); const response = await real(input, init); - return nsids.includes(nsid) ? edit(response) : response; + return nsids.includes(nsid) ? edit(response, url) : response; }); }; @@ -586,6 +694,126 @@ describe('SpaceSyncer against a repo host', () => { return new Response(JSON.stringify(page), { headers: response.headers }); }); + describe('a listRepoOps page from a broken or hostile host', () => { + /** What the oplog's first page is swapped for: any text, other values for its ops, one field changed, or cut off. */ + type PageEdit = + | { kind: 'text'; text: string } + | { kind: 'values'; values: JsonValue[] } + | { kind: 'field'; field: (typeof FIELDS)[number]; value: JsonValue | undefined } + | { kind: 'cut'; at: number }; + + const pageEdit = (collection: string): fc.Arbitrary => + fc.oneof( + fc.record({ kind: fc.constant('text' as const), text: fc.oneof(fc.string(), fc.json()) }), + fc.record({ kind: fc.constant('values' as const), values: fc.array(opValue(collection), { minLength: 1 }) }), + fc.record({ + kind: fc.constant('field' as const), + field: fc.constantFrom(...FIELDS), + value: fc.option(fc.jsonValue(), { nil: undefined }) + }), + fc.record({ kind: fc.constant('cut' as const), at: fc.nat() }) + ); + + function serve(edit: PageEdit, text: string): string { + switch (edit.kind) { + case 'text': + return edit.text; + case 'cut': + return text.slice(0, edit.at % text.length); + case 'field': + return write(withFieldSet(JSON.parse(text), edit.field, edit.value)); + case 'values': { + const page: { ops: { value?: JsonValue }[] } = JSON.parse(text); + page.ops.forEach((op, index) => { + if (index < edit.values.length) op.value = edit.values[index]; + }); + + return write(page); + } + } + } + + const stored = async () => + Object.fromEntries( + (await db.selectFrom('spaceRecord').select(['rkey', 'value']).execute()).map(({ rkey, value }) => [ + rkey, + JSON.parse(value) + ]) + ); + + it('stores the ops of a page it reads, falls back to a full download otherwise, and keeps nothing too deep to validate', async () => { + await fc.assert( + fc.asyncProperty( + fc + .constantFrom(...RECORD_COLLECTIONS) + .chain((collection) => fc.tuple(fc.constant(collection), pageEdit(collection))), + async ([collection, edit]) => { + await db.destroy(); + db = await openDatabase(':memory:'); + host = await FakeSpaceHost.create(SPACE); + changes = []; + const record = (text: string) => ({ $type: collection, text }); + + const s = await syncer(); + await host.put(DJ, collection, 'a', record('one')); + await s.sync(SPACE); + await host.put(DJ, collection, 'b', record('two')); + await host.put(DJ, collection, 'a', record('three')); + + // The pages of the last read of the oplog. Only its first page is swapped, every time it's read, so a cursor + // the swap makes up reaches the real host and ends there. + let served: string[] = []; + tamper(['listRepoOps'], async (response, url) => { + const text = await response.text(); + + if (url.searchParams.has('cursor')) served.push(text); + else served = [serve(edit, text)]; + + return new Response(served.at(-1), { headers: response.headers }); + }); + + const failed = await s.syncRepo(SPACE, DJ).then( + () => null, + (error: Error) => error + ); + + // Whatever went in, nothing comes out too deep for validateRecord to read. + const deep = changes.filter( + (change) => change.kind === 'upsert' && isTooDeepFor(change.collection, change.value) + ); + + expect(deep).toEqual([]); + + // Only a MAC that fails twice fails the repo, which keeps what it had and waits for its retry. Any other page + // it can't use, it downloads in full instead. A page it reads is the local copy's ops, with a value too deep + // to validate dropped. + const read = () => { + const copy = new Map([['a', record('one')]]); + + for (const page of served) { + const { ops }: { ops: { collection: string; rkey: string; cid: string | null; value?: JsonObject }[] } = + JSON.parse(page); + + for (const op of ops) { + if (op.cid === null || (op.value && isTooDeepFor(op.collection, op.value))) copy.delete(op.rkey); + else copy.set(op.rkey, op.value && lexToJson(jsonToLex(op.value))); + } + } + + return Object.fromEntries(copy); + }; + + const downloaded = calls('getRepo').length > 1; + const kept = failed ? { a: record('one') } : downloaded && { a: record('three'), b: record('two') }; + expect(await stored()).toEqual(kept || read()); + expect((await repoRow())?.lastError).toBe(failed?.message ?? null); + } + ), + { numRuns: 50 } + ); + }, 60_000); + }); + it('reports each watched space with its repos, and skips repos already up to date when listing from the start', async () => { const s = await syncer(); await host.put(DJ, NOTE, 'a', note('one')); @@ -676,7 +904,7 @@ describe('SpaceSyncer against a repo host', () => { // A cap of 3 keeps these to a few round trips to the host; 'reads 100 pages of a repo list a pass' pins the default. it('downloads the repo in full once its oplog runs past the page cap', async () => { - const s = await syncer(undefined, null, 3); + const s = await syncer(undefined, null, { maxPages: 3 }); await host.put(DJ, NOTE, 'a', note('one')); await s.sync(SPACE); await host.put(DJ, NOTE, 'b', note('two')); @@ -693,7 +921,7 @@ describe('SpaceSyncer against a repo host', () => { }); it('reads its repo list up to the page cap a pass, keeping its place for the next', async () => { - const s = await syncer(undefined, null, 3); + const s = await syncer(undefined, null, { maxPages: 3 }); await host.put(DJ, NOTE, 'a', note('one')); await s.sync(SPACE); endless('listWriters'); @@ -741,6 +969,10 @@ describe('SpaceSyncer against a repo host', () => { return new Response(new Uint8Array(archive), { headers: response.headers }); }); + /** `archive` with the first `text` in it replaced, byte for byte. */ + const replaced = (archive: Buffer, text: string, by: string) => + Buffer.from(archive.toString('latin1').replace(text, by), 'latin1'); + it('reads a repo archive framed with control bytes, as the alpha host has sent since Nov 5', async () => { const s = await syncer(); await host.put(DJ, NOTE, 'a', note('one')); @@ -764,6 +996,16 @@ describe('SpaceSyncer against a repo host', () => { 'has a record path that is not one', (archive: Buffer) => archive.fill('&', archive.indexOf(PATH), archive.indexOf(PATH) + 1), `invalid NSID in record path: &${PATH.slice(1)}` + ], + [ + 'has a record that does not fold into its commit', + (archive: Buffer) => replaced(archive, 'text\x63one', 'text\x63onf'), + 'records do not match the commit data' + ], + [ + 'is another kind of archive', + (archive: Buffer) => replaced(archive, 'atproto-space-repo', 'atproto-space-rapo'), + 'invalid atproto-space-repo metadata' ] ])("fails the repo when it %s, with the reader's error, and keeps the KEM key", async (_, edit, message) => { const s = await syncer(); @@ -775,6 +1017,103 @@ describe('SpaceSyncer against a repo host', () => { expect(calls('getRepo')).toHaveLength(1); expect(await db.selectFrom('syncRepoRetry').select('lastError').execute()).toEqual([{ lastError: message }]); }); + + it('fails the repo when it lists its records out of order', async () => { + const s = await syncer(); + await host.put(DJ, NOTE, 'a', note('one')); + await host.put(DJ, NOTE, 'b', note('two')); + // Each record's path swapped for the other's, by way of a third, so b's comes first. + const [OTHER, SWAP] = [`${NOTE}/b`, `${NOTE}/x`]; + editArchive((archive) => replaced(replaced(replaced(archive, PATH, SWAP), OTHER, PATH), SWAP, OTHER)); + + await expect(s.sync(SPACE)).rejects.toThrow(`records out of order at ${PATH}`); + expect(await records()).toEqual([]); + }); + + it.each([ + ['is not a map', encode(['one']), `invalid record at ${PATH}`], + ['is not DRISL', Uint8Array.of(0xa1, 0x64), `invalid record cbor at ${PATH}`] + ])('fails the repo when a record %s', async (_, bytes, message) => { + const s = await syncer(); + await host.putEncoded(DJ, NOTE, 'a', bytes); + + await expect(s.sync(SPACE)).rejects.toThrow(message); + expect(await records()).toEqual([]); + }); + }); + + describe('a repo export that runs past the size cap', () => { + const MAX_BYTES = 64 * 1024; + + /** Has the host's getRepo archive go on past its last record with records forever, counting the bytes sent. */ + const endless = () => { + let sent = 0; + tamper(['getRepo'], async (response) => { + const archive = new Uint8Array(await response.arrayBuffer()); + const value = encode(note('more')); + let count = 0; + + const body = new ReadableStream({ + pull(controller) { + // The archive without its end byte, then one record after another, in path order. Each length fits + // a one-byte varint. + const key = Buffer.from(`${NOTE}/z${String(count).padStart(12, '0')}`); + + const chunk = + count++ === 0 ? archive.subarray(0, -1) : Uint8Array.of(1, key.length, ...key, value.length, ...value); + + sent += chunk.length; + controller.enqueue(chunk); + } + }); + + return new Response(body, { headers: response.headers }); + }); + + return () => sent; + }; + + it('stops reading it, logs the repo, and keeps the local copy and its place until a retry works', async () => { + const NOON = new Date('2026-11-04T12:00:00.000Z').getTime(); + vi.useFakeTimers({ toFake: ['Date'], now: NOON }); + onTestFinished(() => void vi.useRealTimers()); + const { logger, notes } = writtenLog(); + const s = await syncer(undefined, null, { logger, maxRepoBytes: MAX_BYTES }); + await host.put(DJ, NOTE, 'a', note('one')); + await s.sync(SPACE); + // A local set hash that has drifted from the records, so the next pass downloads the repo in full. + const drifted = RepoCommit.fromState(null).setHash.state(); + await db.updateTable('syncedRepo').set({ ltHash: drifted }).execute(); + const synced = await repoRow(); + await host.put(DJ, NOTE, 'b', note('two')); + const sent = endless(); + + await expect(s.sync(SPACE)).rejects.toThrow('Response too large'); + expect(sent()).toBeLessThan(2 * MAX_BYTES); + expect(notes()).toContainEqual( + expect.objectContaining({ + level: 'warn', + message: 'repo export ran past the size cap; giving up on it', + repoDid: DJ, + maxBytes: MAX_BYTES + }) + ); + expect(await records()).toEqual([['a', 'one']]); + expect(await repoRow()).toEqual({ ...synced, lastError: 'Response too large' }); + expect(await db.selectFrom('syncRepoRetry').select(['repoDid', 'attempts']).execute()).toEqual([ + { repoDid: DJ, attempts: 1 } + ]); + + vi.mocked(host.fetch).mockRestore(); + vi.setSystemTime(NOON + 60_000); + await s.sync(SPACE); + expect(await records()).toEqual([ + ['a', 'one'], + ['b', 'two'] + ]); + expect(await db.selectFrom('syncRepoRetry').selectAll().execute()).toEqual([]); + expect((await db.selectFrom('spaceWatch').select('lastError').executeTakeFirstOrThrow()).lastError).toBeNull(); + }); }); it('refreshes the KEM key once when a full download fails its MAC', async () => { @@ -1010,3 +1349,98 @@ describe('SpaceSyncer against a repo host', () => { }); }); }); + +describe('readOpsPage', () => { + const NSID = 'com.atproto.space.listRepoOps'; + const CID = 'bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm'; + const commit = { ver: 1, repo: 'did:plc:dj', space: SPACE, rev: '3m5qbpbz4ws2c', data: { $bytes: 'AAAA' } }; + + const op = fc.constantFrom(...RECORD_COLLECTIONS).chain((collection) => + fc.record({ + collection: fc.constant(collection), + rkey: recordKey(collection), + cid: fc.constant(CID), + prev: fc.constant(null), + value: opValue(collection) + }) + ); + + const page = fc.record({ + ops: fc.array(op), + commit: fc.constant(commit), + cursor: fc.option(fc.string(), { nil: undefined }) + }); + + const withField = fc + .tuple(page, fc.constantFrom(...FIELDS), fc.option(fc.jsonValue(), { nil: undefined })) + .map(([body, field, value]) => withFieldSet(body, field, value)); + + it('reads any text as a page, or rejects it as the host failing listRepoOps', () => { + const text = fc.oneof( + fc.string(), + fc.json(), + page.map(write), + withField.map(write), + // Cut off anywhere. + fc.tuple(page.map(write), fc.nat()).map(([whole, at]) => whole.slice(0, at % whole.length)), + // Nested past the stack somewhere other than a record. + fc + .tuple(page, fc.integer({ min: 1_000, max: 30_000 })) + .map(([body, levels]) => write({ ...body, extra: nested(levels) })) + ); + + /** What readOpsPage makes of `body`: how many ops it read and how many values among them are too deep, or how it failed. */ + function outcome(body: string) { + try { + const { ops } = readOpsPage(body).page; + + return { + ops: ops.length, + deep: ops.filter(({ collection, value }) => value && isTooDeepFor(collection, asJson(value))).length + }; + } catch (error) { + return { + rejected: + error instanceof XrpcResponseError ? { status: error.status, error: error.error, nsid: error.nsid } : error + }; + } + } + + fc.assert( + fc.property(text, (body) => { + const read = outcome(body); + + expect(read).toEqual( + 'rejected' in read + ? { rejected: { status: 502, error: 'InvalidResponse', nsid: NSID } } + : { ops: JSON.parse(body).ops.length, deep: 0 } + ); + }) + ); + }); + + it('keeps every op of a page that reads, holding back only the values validateRecord refuses as too deep', () => { + fc.assert( + fc.property(page.map(write), (text) => { + const sent: { collection: string; value: JsonObject }[] = JSON.parse(text).ops; + + const { page: read, tooDeep } = readOpsPage(text); + + // Each op as it went out, with its value held back exactly when it was too deep, and every value kept readable. + expect( + read.ops.map(({ collection, value }, index) => ({ + index, + held: tooDeep.has(index), + kept: value === undefined ? null : isTooDeepFor(collection, asJson(value)) + })) + ).toEqual( + sent.map(({ collection, value }, index) => { + const deep = isTooDeepFor(collection, value); + + return { index, held: deep, kept: deep ? null : false }; + }) + ); + }) + ); + }); +}); diff --git a/apps/web/src/lib/server/sync/engine.ts b/apps/web/src/lib/server/sync/engine.ts index a3ec2abc2..4bfb552dc 100644 --- a/apps/web/src/lib/server/sync/engine.ts +++ b/apps/web/src/lib/server/sync/engine.ts @@ -1,15 +1,8 @@ -import { ComAtprotoSpaceDefs } from '@atproto/api'; +import { fetchResponseMaxSizeChecker } from '@atproto-labs/fetch'; import { type Cid, isLexMap, isObject, type LexMap, parseCid } from '@atproto/lex-data'; import { type JsonObject, type JsonValue, jsonToLex, lexToJson } from '@atproto/lex-json'; import { isDidString, isNsidString, isSpaceKeyString } from '@atproto/oauth-scopes'; -import { - COMMIT_MAC_PROFILE, - type RecordPathParts, - RepoCommit, - type SpaceCommit, - verifyCommit, - verifyRepoStarFull -} from '@atproto/space'; +import { COMMIT_MAC_PROFILE, type RecordPathParts, RepoCommit, type SpaceCommit, verifyCommit } from '@atproto/space'; import { isSpaceRefString } from '@atproto/syntax'; import { timingSafeEqual } from 'node:crypto'; import PQueue from 'p-queue'; @@ -19,6 +12,7 @@ import { type SpaceCredentialManager, isCredentialRejected, isMacFailure, + readAnswer, XrpcResponseError } from '../atproto/credentials'; import type { IdentityResolver } from '../atproto/identity'; @@ -27,6 +21,7 @@ import { isTooDeep, TOO_DEEP } from '../atproto/lexicons'; import { parseSpaceUri, spaceRecordUri } from '../atproto/spaces'; import { type Db, nowIso, parseJson } from '../db'; import type { Logger } from '../logger'; +import { isSpaceCommit, readRepoArchive } from './repo-archive'; export type SyncedChange = | { @@ -70,7 +65,7 @@ const listRepoOpsOutput = z.object({ value: z.custom(isLexMap).optional() }) ), - commit: z.custom((value) => ComAtprotoSpaceDefs.validateCommit(value).success), + commit: z.custom(isSpaceCommit), cursor: z.string().optional() }); @@ -96,10 +91,14 @@ export type SyncStatus = { }; /** - * A listRepoOps page decoded from its JSON, with the indexes of the ops whose values are nested deeper than - * validateRecord allows. jsonToLex recurses, so those values are taken out before it decodes the rest. + * A listRepoOps page read from its text, with the indexes of the ops whose values are nested deeper than + * validateRecord allows. jsonToLex recurses, so those values are taken out before it decodes the rest. A page that + * doesn't read (not JSON, the wrong shape, or nested too deep anywhere else) is the host's failure, so it rejects as + * one, and syncRepo downloads the repo in full instead. @internal */ -function readOpsPage(json: JsonValue) { +export function readOpsPage(text: string) { + const nsid = 'com.atproto.space.listRepoOps'; + const json: JsonValue = readAnswer(nsid, () => JSON.parse(text)); const tooDeep = new Set(); const ops = isObject(json) && !Array.isArray(json) && Array.isArray(json.ops) ? json.ops : []; @@ -109,7 +108,7 @@ function readOpsPage(json: JsonValue) { delete op.value; } - return { page: listRepoOpsOutput.parse(jsonToLex(json)), tooDeep }; + return { page: readAnswer(nsid, () => listRepoOpsOutput.parse(jsonToLex(json))), tooDeep }; } // SAFETY: lexToJson only rewrites the CIDs and bytes inside a map, so a LexMap always comes back as a JSON object. @@ -159,6 +158,19 @@ const isRepoUnavailable = (cause: unknown) => */ const MAX_PAGES = 100; +/** + * The most of a repo export (`getRepo`) one download reads, in bytes. Every record in it is held in memory until the + * download is applied, and a hostile repo host could send one that never ends. A record is at most 1 MiB + * (@atproto/space's MAX_RECORD_SIZE), but the records this app writes are a few KiB at most. The largest repo is the + * root's in the audit space, which gains an entry for every audited action, most well under 1 KiB, so this holds a + * few hundred thousand of them, many times what any repo here is expected to hold. A repo past it fails and waits + * for its retry like any other, and the system page shows it. + */ +const REPO_EXPORT_MAX_BYTES = 256 * 1024 * 1024; + +/** What the response cap @atproto-labs/fetch applies (serviceApiFetch's too) fails a body past it with. */ +const TOO_LARGE = 'Response too large'; + /** How long a repo waits after its `attempts`th failure in a row: 1 minute, doubling up to an hour. */ const retryDelayMs = (attempts: number) => Math.min(60_000 * 2 ** (attempts - 1), 3_600_000); @@ -200,6 +212,8 @@ export class SpaceSyncer { notifyEndpoint: string | null; /** The most pages of a listing one pass reads, MAX_PAGES unless a test needs a host's endless listing short. */ maxPages?: number; + /** The most bytes of a repo export one download reads, REPO_EXPORT_MAX_BYTES unless a test needs it small. */ + maxRepoBytes?: number; } ) {} @@ -550,8 +564,7 @@ export class SpaceSyncer { mac: { profile: COMMIT_MAC_PROFILE, kemKey } }); - const json: JsonValue = JSON.parse(await response.text()); - const { page, tooDeep } = readOpsPage(json); + const { page, tooDeep } = readOpsPage(await response.text()); for (const [index, op] of page.ops.entries()) { state.applyOp({ collection: op.collection, rkey: op.rkey, cid: asCid(op.cid), prev: asCid(op.prev) }); @@ -616,6 +629,9 @@ export class SpaceSyncer { } private async recover(space: string, repoDid: string, pds: string, kemKey: string) { + const { logger } = this.deps; + const maxBytes = this.deps.maxRepoBytes ?? REPO_EXPORT_MAX_BYTES; + const { response, mac } = await this.deps.credentials.macRequest({ space, service: pds, @@ -625,10 +641,23 @@ export class SpaceSyncer { mac: { profile: COMMIT_MAC_PROFILE, kemKey } }); - if (!response.body) throw new Error('Empty repo response'); + let archive: Awaited>; + + try { + // Capped the way serviceApiFetch caps an answer read whole, at what a repo export can reach. + const { body } = fetchResponseMaxSizeChecker(response, maxBytes); + + if (!body) throw new Error('Empty repo response'); + + // A STAR archive: the commit, checked against its MAC, then every record, which must fold into its data. + archive = await readRepoArchive(body, { ...commitScope(space, repoDid), ...mac }); + } catch (error) { + if (error instanceof Error && error.message === TOO_LARGE) { + logger.warn('repo export ran past the size cap; giving up on it', { space, repoDid, maxBytes }); + } - // A STAR archive: the commit, checked against its MAC, then every record, which must fold into its data. - const { commit, records } = await verifyRepoStarFull(response.body, { ...commitScope(space, repoDid), ...mac }); + throw error; + } const existing = await this.deps.db .selectFrom('spaceRecord') @@ -641,22 +670,20 @@ export class SpaceSyncer { const changes: SyncedChange[] = []; const known = new Map(existing.map((row) => [`${row.collection}/${row.rkey}`, row.cid])); - for (const record of records) { - const path = `${record.collection}/${record.rkey}`; + for (const { collection, rkey, cid, value } of archive.records) { + const uri = spaceRecordUri(space, repoDid, collection, rkey); + + // A record too deep to read is dropped from the local copy, as the oplog drops one. + if (value === null) { + logger.warn(`dropping a synced record ${TOO_DEEP}`, { uri }); + continue; + } + + const path = `${collection}/${rkey}`; present.add(path); - const cid = record.cid.toString(); - if (known.get(path) === cid) continue; - changes.push({ - kind: 'upsert', - space, - repoDid, - collection: record.collection, - rkey: record.rkey, - uri: spaceRecordUri(space, repoDid, record.collection, record.rkey), - cid, - value: toJson(record.record) - }); + if (known.get(path) === cid.toString()) continue; + changes.push({ kind: 'upsert', space, repoDid, collection, rkey, uri, cid: cid.toString(), value }); } for (const row of existing) { @@ -672,7 +699,7 @@ export class SpaceSyncer { } } - await this.apply(space, repoDid, pds, commit, RepoCommit.fromRecords(records), changes); + await this.apply(space, repoDid, pds, archive.commit, archive.state, changes); } private async apply( diff --git a/apps/web/src/lib/server/sync/projections.test.ts b/apps/web/src/lib/server/sync/projections.test.ts index 2002fc67e..97aa7e100 100644 --- a/apps/web/src/lib/server/sync/projections.test.ts +++ b/apps/web/src/lib/server/sync/projections.test.ts @@ -1,5 +1,7 @@ import type { JsonObject } from '@atproto/lex-json'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fc from 'fast-check'; +import { sql } from 'kysely'; +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'; import { COLLECTION } from '#lib/nsid.ts'; import { backstageSpace, @@ -11,7 +13,15 @@ import { } from '../atproto/spaces'; import { grantKey } from '../services/epk'; import { createTestServices, ROOT } from '../testing/core'; -import { CODJ, DJ, FRIEND, NO_SPACES, pressKitServices, STRANGER } from '../testing/press-kits'; +import { + anyRecord, + nearlyValidRecord, + RECORD_COLLECTIONS, + recordKey, + validRecord +} from '../testing/lexicon-arbitraries'; +import { CODJ, DJ, FRIEND, NO_SPACES, pressKitServices, PROMOTER, STRANGER } from '../testing/press-kits'; +import type { SyncedChange } from './engine'; import { createProjections } from './projections'; import { flagsOff } from '#lib/testing/flags.ts'; @@ -724,4 +734,270 @@ describe('createProjections', () => { expect(await t.db.selectFrom(table).selectAll().execute()).toEqual([]); }); }); + + describe('any synced record', () => { + /** The record collections this app has lexicons for, which a space member can write whatever the space. */ + const COLLECTIONS = Object.values(COLLECTION).filter((collection) => RECORD_COLLECTIONS.includes(collection)); + + /** What only the root writes in a performer's, party's or venue's space. */ + const SHARED = [ + COLLECTION.person, + COLLECTION.invite, + COLLECTION.inviteLink, + COLLECTION.joinRequest, + COLLECTION.listingStatus, + COLLECTION.performer, + COLLECTION.venue, + COLLECTION.venueApproval, + COLLECTION.event, + COLLECTION.party + ]; + + const BOOKING = [COLLECTION.bookingInquiry, COLLECTION.bookingMessage, COLLECTION.bookingStatus]; + + /** Every table's rows, in a stable order, to see what projecting changed. */ + const tables = async () => { + await t.audit.idle(); + const names = (await t.db.introspection.getTables()).map(({ name }) => name); + + return Object.fromEntries( + await Promise.all( + names.map(async (name) => { + const { rows } = await sql`select * from ${sql.table(name)}`.execute(t.db); + + return [name, rows.map((row) => JSON.stringify(row)).toSorted()]; + }) + ) + ); + }; + + /** The collections whose records the app keys by the DID they're about, and only reads at that key. */ + const KEYED_BY_SUBJECT = new Set([ + COLLECTION.person, + COLLECTION.invite, + COLLECTION.joinRequest, + COLLECTION.staffRole + ]); + + /** `record` about the DID it's keyed by, when `keyed`, so it can apply. */ + const keyedBy = (collection: string, record: JsonObject, rkey: string, keyed: boolean): JsonObject => + keyed && KEYED_BY_SUBJECT.has(collection) ? { ...record, subject: rkey } : record; + + /** A change to `collection` in `space` by `repoDid`: an upsert of `value`, or a delete without one. */ + const change = ( + space: string, + repoDid: string, + collection: string, + rkey: string, + value?: JsonObject + ): SyncedChange => { + const uri = `${space}/${repoDid}/${collection}/${rkey}`; + + return value + ? { kind: 'upsert', space, repoDid, collection, rkey, uri, cid: 'bafyreiabc', value } + : { kind: 'delete', space, repoDid, collection, rkey, uri }; + }; + + /** Changes by `authors` to `collections` in `space`, with content from `content`, and deletes when `deletes`. */ + const changes = ( + space: string, + authors: string[], + collections: string[], + content: (collection: string) => fc.Arbitrary, + deletes: boolean + ) => + fc.tuple(fc.constantFrom(...authors), fc.constantFrom(...collections)).chain(([repoDid, collection]) => + fc + .record({ + rkey: fc.oneof(recordKey(collection), fc.constantFrom(ALICE, BOB, 'self')), + value: deletes ? fc.option(content(collection), { nil: undefined }) : content(collection), + keyed: fc.boolean() + }) + .map(({ rkey, value, keyed }) => + change(space, repoDid, collection, rkey, value && keyedBy(collection, value, rkey, keyed)) + ) + ); + + /** A space of each type, under the root and under someone else. */ + const spaces = () => [ + t.spaces.staff, + t.spaces.moderation, + t.spaces.audit, + t.spaces.industry, + bookingSpace(ROOT, '3gig'), + backstageSpace(ROOT, '3proj'), + epkSpace(ALICE, '3kit'), + epkRequestSpace(ROOT, '3proj'), + sharedSpace(ROOT, 'party', '3party'), + sharedSpace(ROOT, 'performer', '3perf'), + sharedSpace(ALICE, 'venue', '3venue') + ]; + + /** + * Records validateRecord refuses. Not broken at `subject`, which `keyedBy` would mend. Most go where the root's + * records land as they are (a request, an audit copy, project details, a booking event), so a record that got past + * validation would show in the tables. + */ + const refused = (space: string) => { + const content = (collection: string) => + nearlyValidRecord(collection) + .filter(({ path }) => path !== '/subject') + .map(({ record }) => record); + + return fc.oneof( + changes(t.spaces.moderation, [ROOT, ALICE], [COLLECTION.request], content, false), + changes(t.spaces.audit, [ROOT, ALICE], [COLLECTION.auditEntry], content, false), + changes(t.spaces.industry, [ROOT], [COLLECTION.projectDetails], content, false), + changes(bookingSpace(ROOT, '3gig'), [ROOT], BOOKING, content, false), + changes(space, [ROOT, ALICE, BOB], COLLECTIONS, content, false) + ); + }; + + it('applies or skips any change without throwing, refused records change nothing, and a replay changes nothing', async () => { + // Rows carry the time they were written, which a replay would otherwise move on. + vi.useFakeTimers({ toFake: ['Date'], now: new Date('2026-11-13T12:00:00.000Z') }); + onTestFinished(() => void vi.useRealTimers()); + + const anyChange = fc + .constantFrom(...spaces()) + .chain((space) => changes(space, [ROOT, ALICE, BOB], COLLECTIONS, anyRecord, true)); + + const anyRefused = fc.constantFrom(...spaces()).chain(refused); + + await fc.assert( + fc.asyncProperty( + fc.array(anyChange, { minLength: 1 }), + fc.array(anyRefused, { minLength: 1 }), + async (synced, invalid) => { + // With every service up, a throw would only leave the record to fail again on every retry (ADR 0009). + for (const each of synced) await project(each); + const once = await tables(); + + for (const each of invalid) await project(each); + expect(await tables()).toEqual(once); + + for (const each of synced) await project(each); + expect(await tables()).toEqual(once); + } + ), + { numRuns: 50 } + ); + }, 60_000); + + it('changes nothing for a record its author has no say over, whatever it holds', async () => { + const request = `${t.spaces.moderation}/${ALICE}/${COLLECTION.request}/3req`; + await upsert(t.spaces.moderation, ALICE, COLLECTION.request, '3req', { + kind: 'create', + profile: { name: 'A', kind: 'solo', genres: ['x'], location: { city: 'c', country: 'DE' } }, + createdAt: new Date().toISOString() + }); + + // Valid records most of the time, so only the author check stands between them and the tables. A decision names + // the open request, which it would decide. + const content = (collection: string) => + fc + .oneof({ weight: 3, arbitrary: validRecord(collection) }, anyRecord(collection)) + .map((record) => (collection === COLLECTION.decision ? { ...record, request } : record)); + + const staff = [COLLECTION.staffRole, COLLECTION.staffFlag, COLLECTION.staffGroup]; + + const notTheirs = fc.oneof( + changes(t.spaces.moderation, [ALICE, BOB], [COLLECTION.decision], content, false), + changes(t.spaces.staff, [ALICE, BOB], staff, content, true), + changes(t.spaces.industry, [ALICE, BOB], [COLLECTION.projectDetails], content, false), + // A press kit's space is its authority's to grant in, and no other kind of space holds grants. + changes(epkSpace(ALICE, '3kit'), [ROOT, BOB], [COLLECTION.epkGrant], content, false), + changes(backstageSpace(ROOT, '3proj'), [ROOT], [COLLECTION.epkGrant], content, false), + // Who's in a performer's, party's or venue's space is the root's to write, in a space under the root. + changes(sharedSpace(ROOT, 'party', '3party'), [ALICE, BOB], SHARED, content, true), + changes(sharedSpace(ALICE, 'party', '3party'), [ROOT, ALICE], SHARED, content, true), + // Nobody has joined this booking thread. + changes(bookingSpace(ROOT, '3gig'), [ALICE, BOB], BOOKING, content, false) + ); + + await fc.assert( + fc.asyncProperty(fc.array(notTheirs, { minLength: 1 }), async (synced) => { + const before = await tables(); + + for (const each of synced) await project(each); + expect(await tables()).toEqual(before); + }), + { numRuns: 50 } + ); + }, 60_000); + + it('never answers a press kit request from a decision anyone but the root wrote, whatever it holds', async () => { + const f = await pressKitServices(); + onTestFinished(async () => { + await f.t.audit.idle(); + await f.t.db.destroy(); + }); + const kit = f.kit(await f.publish(DJ)); + await f.t.epks.request(await f.t.viewer(STRANGER), kit, {}); + const [request] = await f.t.epks.requests(kit.epk); + const sync = createProjections(f.t); + const space = epkRequestSpace(ROOT, f.project.rkey); + const rows = () => f.t.db.selectFrom('epkRequest').selectAll().execute(); + const before = await rows(); + + // Valid most of the time and naming the open request and its press kit, so only the author check stands between + // a decision and the answer it would give. + const decision = fc + .oneof({ weight: 3, arbitrary: validRecord(COLLECTION.epkDecision) }, anyRecord(COLLECTION.epkDecision)) + .map((record) => ({ ...record, request: request.uri, requester: STRANGER, epk: kit.epk.uri })); + + await fc.assert( + fc.asyncProperty( + fc.constantFrom(DJ, CODJ, STRANGER, ALICE), + recordKey(COLLECTION.epkDecision), + decision, + async (repoDid, rkey, value) => { + await sync(change(space, repoDid, COLLECTION.epkDecision, rkey, value)); + expect(await rows()).toEqual(before); + } + ), + { numRuns: 50 } + ); + }, 60_000); + + it("never lists a draft by someone who doesn't manage the project, whatever it holds", async () => { + const f = await pressKitServices(); + onTestFinished(async () => { + await f.t.audit.idle(); + await f.t.db.destroy(); + }); + const epk = await f.publish(DJ); + const sync = createProjections(f.t); + const space = backstageSpace(ROOT, f.project.rkey); + + // Drafts of press kits that aren't published, which most of these are, list apart from the kits. + const listed = async () => { + const { kits, drafts } = await f.t.epks.dashboard(f.project); + + return [...kits.flatMap((kit) => kit.drafts), ...drafts]; + }; + + const before = await listed(); + + // Keyed by the published press kit, and often without a base naming another, as a manager's own draft would be. + const draft = fc + .tuple( + fc.oneof({ weight: 3, arbitrary: validRecord(COLLECTION.epkDraft) }, anyRecord(COLLECTION.epkDraft)), + fc.boolean() + ) + .map(([record, based]) => { + const { base: _, ...unbased } = record; + + return based ? record : unbased; + }); + + await fc.assert( + fc.asyncProperty(fc.constantFrom(PROMOTER, STRANGER), draft, async (repoDid, value) => { + await sync(change(space, repoDid, COLLECTION.epkDraft, epk.rkey, value)); + expect(await listed()).toEqual(before); + }), + { numRuns: 50 } + ); + }, 60_000); + }); }); diff --git a/apps/web/src/lib/server/sync/repo-archive.ts b/apps/web/src/lib/server/sync/repo-archive.ts new file mode 100644 index 000000000..ecb155931 --- /dev/null +++ b/apps/web/src/lib/server/sync/repo-archive.ts @@ -0,0 +1,96 @@ +import { ComAtprotoSpaceDefs } from '@atproto/api'; +import { decode } from '@atproto/lex-cbor'; +import { type Cid, cidForCbor, isPlainObject } from '@atproto/lex-data'; +import { type JsonObject, lexToJson } from '@atproto/lex-json'; +import { + MAX_RECORD_SIZE, + parseRecordPath, + type RecordPathParts, + RepoCommit, + type SpaceCommit, + SpaceRepoVerificationError, + verifyCommit +} from '@atproto/space'; +import { readStar } from '@atproto/star'; +import { isTooDeep } from '../atproto/lexicons'; + +/** Whether `value` is a `com.atproto.space.defs#commit` in its lex form, as a commit is checked against its MAC. */ +export const isSpaceCommit = (value: unknown): value is SpaceCommit => + ComAtprotoSpaceDefs.validateCommit(value).success; + +/** What a repo archive's metadata names its profile with. */ +const REPO_STAR_TYPE = 'atproto-space-repo'; + +/** The frame limits @atproto/space reads a repo archive with (its REPO_STAR_LIMITS, which it doesn't export). */ +const LIMITS = { maxMetaLength: 64 * 1024, maxKeyLength: 4 * 1024, maxValueLength: MAX_RECORD_SIZE }; + +/** A record from a repo archive: its value as JSON, or null when it's nested deeper than validateRecord reads. */ +export type ArchivedRecord = RecordPathParts & { cid: Cid; value: JsonObject | null }; + +/** + * Reads a `getRepo` archive as @atproto/space's verifyRepoStarFull does: the commit checked against its MAC, then + * every record, which must fold into the commit's data. The difference is a record nested too deep to read. The + * CBOR decoder and lexToJson recurse, so one a few thousand levels deep overflows the stack, and verifyRepoStarFull + * fails the whole repo for it. Here it comes back with a null value instead, and still counts toward the commit's + * data, since its CID is the hash of its bytes, which needs no decoding. + */ +export async function readRepoArchive( + body: AsyncIterable, + params: Parameters[1] +): Promise<{ commit: SpaceCommit; records: ArchivedRecord[]; state: RepoCommit }> { + const archive = await readStar(body, LIMITS); + + try { + const { $type, ...commit } = archive.meta; + + if ($type !== REPO_STAR_TYPE || !isSpaceCommit(commit)) { + throw new SpaceRepoVerificationError(`invalid ${REPO_STAR_TYPE} metadata`); + } + + verifyCommit(commit, params); + + const records: ArchivedRecord[] = []; + const decoder = new TextDecoder(); + let previous: Uint8Array | undefined; + + for await (const { key, value } of archive.pairs) { + const path = decoder.decode(key); + const { collection, rkey } = parseRecordPath(path); + + if (previous && Buffer.compare(key, previous) <= 0) { + throw new SpaceRepoVerificationError(`records out of order at ${path}`); + } + + previous = key; + records.push({ collection, rkey, cid: await cidForCbor(value), value: readValue(value, path) }); + } + + const state = RepoCommit.fromRecords(records); + + if (!state.matches(commit)) throw new SpaceRepoVerificationError('records do not match the commit data'); + + return { commit, records, state }; + } finally { + await archive[Symbol.asyncDispose](); + } +} + +/** A record's DRISL bytes as JSON, or null when it's nested deeper than validateRecord reads. */ +function readValue(bytes: Uint8Array, path: string): JsonObject | null { + try { + const value = decode(bytes); + + if (!isPlainObject(value)) throw new SpaceRepoVerificationError(`invalid record at ${path}`); + + // SAFETY: lexToJson only rewrites the CIDs and bytes inside a map, so a map always comes back as a JSON object. + const json = lexToJson(value) as JsonObject; + + return isTooDeep(json) ? null : json; + } catch (cause) { + // The decoder reports malformed bytes with a plain Error, so a RangeError is the stack running out. + if (cause instanceof RangeError) return null; + + if (cause instanceof SpaceRepoVerificationError) throw cause; + throw new SpaceRepoVerificationError(`invalid record cbor at ${path}`, { cause }); + } +} diff --git a/apps/web/src/lib/server/testing/space-host.ts b/apps/web/src/lib/server/testing/space-host.ts index d469a4b47..e50cb9af9 100644 --- a/apps/web/src/lib/server/testing/space-host.ts +++ b/apps/web/src/lib/server/testing/space-host.ts @@ -1,6 +1,7 @@ import { TID } from '@atproto/common-web'; import { P256Keypair } from '@atproto/crypto'; -import type { Cid, LexMap } from '@atproto/lex-data'; +import { encode } from '@atproto/lex-cbor'; +import { type Cid, cidForCbor, type LexMap } from '@atproto/lex-data'; import { lexStringify } from '@atproto/lex-json'; import { isDidString, isNsidString, isSpaceKeyString } from '@atproto/oauth-scopes'; import { isSpaceAtUriString } from '@atproto/syntax'; @@ -17,7 +18,6 @@ import { RECORD_MAC_PROFILE, type RecordPathParts, RepoCommit, - serializeRecord, type SpaceCommit, verifyCredentialSig, writeRepoStar @@ -27,7 +27,8 @@ import { IdentityResolver, type ResolvedIdentity } from '../atproto/identity'; import { parseSpaceUri, spaceRecordUri } from '../atproto/spaces'; import { silentLogger } from '../logger'; -type HostedRecord = RecordPathParts & { cid: Cid; bytes: Uint8Array; value: LexMap }; +/** A record, and its value unless it was put as bytes only, which listRepoOps then serves without one. */ +type HostedRecord = RecordPathParts & { cid: Cid; bytes: Uint8Array; value?: LexMap }; type HostedOp = RecordPathParts & { cid: string | null; prev: string | null }; @@ -146,9 +147,17 @@ export class FakeSpaceHost { /** Creates or updates a record in `did`'s repo in the space. */ async put(did: string, collection: string, rkey: string, value: LexMap): Promise { + await this.putEncoded(did, collection, rkey, encode(value), value); + } + + /** + * Creates or updates a record from its DRISL bytes, as a writer can store bytes the encoder here won't make, such + * as a record nested deep enough to overflow its stack. + */ + async putEncoded(did: string, collection: string, rkey: string, bytes: Uint8Array, value?: LexMap): Promise { if (!isNsidString(collection) || !isSpaceKeyString(rkey)) throw new Error(`Bad record path ${collection}/${rkey}`); const repo = await this.repo(did); - const { cid, bytes } = await serializeRecord(collection, rkey, value); + const cid = await cidForCbor(bytes); const prev = repo.records.get(`${collection}/${rkey}`)?.cid.toString() ?? null; repo.records.set(`${collection}/${rkey}`, { collection, rkey, cid, bytes, value }); this.write(repo, { collection, rkey, cid: cid.toString(), prev }); @@ -257,7 +266,7 @@ export class FakeSpaceHost { const ops = repo.ops.slice(from, next).map((op) => { const current = repo.records.get(`${op.collection}/${op.rkey}`); - return current?.cid.toString() === op.cid ? { ...op, value: current.value } : op; + return current?.value && current.cid.toString() === op.cid ? { ...op, value: current.value } : op; }); const cursor = next < repo.ops.length ? String(next) : undefined; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 685371b4d..91be859c0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -399,6 +399,9 @@ importers: '@atproto-labs/did-resolver': specifier: 0.0.0-spaces-alpha-20261113224550 version: 0.0.0-spaces-alpha-20261113224550 + '@atproto-labs/fetch': + specifier: 0.4.2 + version: 0.4.2 '@atproto-labs/fetch-node': specifier: 0.0.0-spaces-alpha-20261113224550 version: 0.0.0-spaces-alpha-20261113224550 @@ -438,6 +441,9 @@ importers: '@atproto/space': specifier: 0.0.0-spaces-alpha-20261113224550 version: 0.0.0-spaces-alpha-20261113224550 + '@atproto/star': + specifier: 0.0.0-spaces-alpha-20261113224550 + version: 0.0.0-spaces-alpha-20261113224550 '@atproto/syntax': specifier: 0.0.0-spaces-alpha-20261113224550 version: 0.0.0-spaces-alpha-20261113224550 From 26426ae33a5759bf97b484dc7be393e6b7fd7aed Mon Sep 17 00:00:00 2001 From: botandbang <337765928+botandbang@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:58:25 -0600 Subject: [PATCH 08/22] fix(web): close the gaps review found in the flag, account and press kit work Only flags with showsOn give signed-out visitors a rollout id, so a percentage on an account-only flag no longer makes every public page private, and parityCanary and userinputReports drop their showsOn. Paraglide's Vary: Cookie is dropped from public immutable answers, and the privacy page mentions the language cookie (LOC-321, LOC-655, LOC-814). pauseReconcilers leaves venue blocks running, since that round only reads the root's blocks and an empty index after a restore would show blocked promoters as confirmed. pauseBackfills also stops the re-reads after a write. The kill switches' flags are required wherever they're read, including the token exchange (LOC-313, LOC-323). An inactive answer from a PDS is checked against a fresh DID document before an account counts as gone, deleted accounts are asked again like the rest and stay out of the directory's list, and ADR 0020 says what the first check after a restart does (LOC-455). A press kit decision is written before its grant, so a refused write leaves nobody let in (LOC-728). The footer and /report agree on when a report goes to GitHub, the notification settings say "Not on for your account yet." when a channel isn't rolled out to someone, and the account overview shows such a channel as paused (LOC-314, LOC-315). An inactive account's page names the handle (LOC-455). The flag page shows its remove-by date, a link to its audit entries and the ready-to-remove note, only release flags are marked ready to remove, and the audit log's flag filter no longer takes in flag groups (LOC-655). The lexicon arbitraries learn the language format, and a property checks press kit decisions only count from the root (LOC-522). The inlang cache stays out of the repo. The privacy page gets a table of every cookie the site sets, heading anchors and links to the notification settings. Headings wrap a long handle instead of pushing a phone's page sideways. The account status cache reads the clock when it checks, so fake timers reach it, and the integration tests give the routes the flags the server hook always sets. New app tests cover the outbox's flag wiring and the re-read of a reinstated account. --- apps/web/.gitignore | 3 + apps/web/README.md | 12 +- apps/web/docs/diagrams/flags.md | 4 +- apps/web/docs/diagrams/jobs-and-directory.md | 6 +- apps/web/docs/diagrams/mixes-and-sets.md | 2 +- apps/web/docs/diagrams/requests-and-routes.md | 4 +- apps/web/src/hooks.server.test.ts | 68 ++++++-- apps/web/src/hooks.server.ts | 14 +- .../lib/components/DmSettings.stories.svelte | 3 + apps/web/src/lib/components/DmSettings.svelte | 10 +- .../components/EmailSettings.stories.svelte | 3 + .../src/lib/components/EmailSettings.svelte | 14 +- .../lib/components/dm-settings.svelte.test.ts | 7 + .../components/email-settings.svelte.test.ts | 7 + apps/web/src/lib/server/app.test.ts | 158 ++++++++++++++++-- apps/web/src/lib/server/app.ts | 40 +++-- .../lib/server/atproto/account-status.test.ts | 76 ++++++++- .../src/lib/server/atproto/account-status.ts | 43 +++-- apps/web/src/lib/server/audit/log.test.ts | 9 + apps/web/src/lib/server/audit/log.ts | 6 +- apps/web/src/lib/server/db/schema.ts | 11 +- .../web/src/lib/server/happyview/backfills.ts | 29 +++- .../src/lib/server/happyview/indexed.test.ts | 31 +++- apps/web/src/lib/server/happyview/indexed.ts | 14 +- apps/web/src/lib/server/media/audio.test.ts | 2 + apps/web/src/lib/server/media/audio.ts | 6 +- apps/web/src/lib/server/meta.test.ts | 13 +- apps/web/src/lib/server/meta.ts | 8 +- apps/web/src/lib/server/profile-page.test.ts | 11 +- apps/web/src/lib/server/profile-page.ts | 5 +- .../src/lib/server/services/bug-reports.ts | 7 + apps/web/src/lib/server/services/epk.test.ts | 58 +++++++ apps/web/src/lib/server/services/epk.ts | 12 +- .../web/src/lib/server/services/flags.test.ts | 64 ++++--- apps/web/src/lib/server/services/flags.ts | 22 ++- apps/web/src/lib/server/services/follows.ts | 7 +- .../lib/server/services/performers.test.ts | 4 +- apps/web/src/lib/server/services/projects.ts | 10 +- .../lib/server/services/recordings.test.ts | 86 ++++++---- .../web/src/lib/server/services/recordings.ts | 16 +- .../src/lib/server/services/requests.test.ts | 17 ++ apps/web/src/lib/server/services/rsvps.ts | 7 +- apps/web/src/lib/server/services/shows.ts | 9 +- .../lib/server/testing/lexicon-arbitraries.ts | 10 ++ .../server/token-exchange/exchange.test.ts | 78 ++++++--- .../src/lib/server/token-exchange/exchange.ts | 6 +- apps/web/src/lib/types.ts | 4 +- apps/web/src/lib/ui/SectionHeader.svelte | 4 +- apps/web/src/routes/+error.svelte | 2 +- apps/web/src/routes/+layout.server.ts | 22 ++- apps/web/src/routes/+layout.svelte | 4 +- .../src/routes/@[handle]/page.server.test.ts | 4 +- .../routes/admin/audit/page.server.test.ts | 17 ++ .../src/routes/admin/flags/[key]/+page.svelte | 13 +- .../admin/flags/[key]/page.stories.svelte | 53 ++++-- .../admin/flags/[key]/page.svelte.test.ts | 58 ++++++- apps/web/src/routes/admin/system/+page.svelte | 2 + .../routes/dashboard/account/+page.server.ts | 17 +- .../src/routes/dashboard/account/+page.svelte | 5 +- .../account/notifications/+page.server.ts | 2 + .../account/notifications/+page.svelte | 6 +- .../account/notifications/page.server.test.ts | 18 ++ .../account/notifications/page.stories.svelte | 4 +- .../account/notifications/page.svelte.test.ts | 20 ++- .../dashboard/account/page.server.test.ts | 35 +++- .../dashboard/account/page.stories.svelte | 7 +- .../dashboard/account/page.svelte.test.ts | 10 +- apps/web/src/routes/error.stories.svelte | 33 +++- apps/web/src/routes/layout.server.test.ts | 41 ++++- .../media/audio/[did]/[cid]/server.test.ts | 6 +- apps/web/src/routes/page.stories.svelte | 4 +- apps/web/src/routes/privacy/+page.server.ts | 1 + apps/web/src/routes/privacy/+page.svelte | 37 ++-- .../src/routes/privacy/page.server.test.ts | 8 +- apps/web/src/routes/report/+page.server.ts | 8 +- apps/web/tests/integration/flows.test.ts | 16 +- .../tests/integration/held-records.test.ts | 3 +- .../integration/inactive-accounts.test.ts | 11 +- apps/web/tests/integration/press-kits.test.ts | 3 +- .../tests/integration/shared-spaces.test.ts | 3 +- .../web/tests/integration/sync-notify.test.ts | 3 +- ...18-signed-out-visitors-get-a-rollout-id.md | 7 +- ...efixed-and-records-carry-their-language.md | 2 +- ...nactive-accounts-are-asked-of-their-pds.md | 6 +- docs/research/feature-flag-platforms.md | 4 +- flags/README.md | 6 +- flags/catalog/parityCanary.json | 3 +- flags/catalog/pauseBackfills.json | 2 +- flags/catalog/pauseOgCards.json | 3 +- flags/catalog/pauseReconcilers.json | 2 +- flags/catalog/pauseRecordingStream.json | 3 +- 91 files changed, 1216 insertions(+), 338 deletions(-) diff --git a/apps/web/.gitignore b/apps/web/.gitignore index 855def8aa..d73b74824 100644 --- a/apps/web/.gitignore +++ b/apps/web/.gitignore @@ -28,3 +28,6 @@ test-results *storybook.log storybook-static + +# inlang writes its compile cache next to the project settings. +project.inlang/cache/ diff --git a/apps/web/README.md b/apps/web/README.md index ee05ceb9c..e45c8186f 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -40,7 +40,7 @@ All data lives on the AT Protocol. Public profiles are ordinary atproto records; - `/for/djs` makes the case for joining: a real listing from the directory, what promoters search on, the profile being the DJ's own, press kits, locallibrary with its captures, the month's most played tracks, the next shows, and how listing works. The listing, the shows and the charts stream in, so the page paints first. - List a new project, or claim one an admin added. Several managers per project (crews, agents). - When a project's managers change, a new manager joins its booking threads that are still being worked out or confirmed for an upcoming show, and a manager who leaves is taken out of all of them. The promoter always stays. The same step keeps the project's backstage, its press kit request space and its press kit spaces to the current managers, leaving the people granted a press kit. The app repeats this at startup, every hour, and on the System page's bootstrap, so a change that failed part way still finishes. A thread follows the project named in the root's opening record, which the promoter can't rewrite, or for a thread opened before that record named one, in its `booking.create` audit entry (written by the app, and rebuilt only from the root's copy). A thread with neither, or where the two disagree, is left as it is. -- Acts, parties and venues each get a space under the root. Their pages ship dark behind two release flags: `spacePages` for the public act, party, venue and event pages, and `peopleSpaces` for the member pages (inviting people, invite links, asking to join, people lists). A route behind one calls `requireFlag` (`src/lib/server/http.ts`), which answers 404 while the flag is off for the viewer. A performer's space also holds the root's `computer.localnetwork.performer` record, which says whether it's an act (with what its page shows) or a DJ's own space for their backstage and managers. A venue's space holds the root's `computer.localnetwork.venue` record: its name, address and coordinates, its Foursquare place once known, and whether events naming it show at once (Anyone can list) or only once confirmed (Venue approves). Names repeat ([ADR 0016](../../docs/adr/0016-names-repeat-keys-and-handles-identify.md)): an act, party or venue goes by its space key, and its page is `///` (`spacePagePath` in `src/lib/space-paths.ts`), where the name part is only there to read: any other name, or none, redirects to the current one. Anyone signed in can add a venue, which puts nobody in its space (owning one takes a confirmed claim). Adding a place that's already a venue gives back that venue, and so does adding the same name in the same city and country unless the two are different Foursquare places. Forms pick one with the venue picker (`src/lib/components/VenuePicker.svelte`): an existing venue by name, with its city on a second line to tell same-named ones apart, or a new one by its name and its city from the city search, both through `/api/venues`, which answers 404 while `spacePages` is off. A new venue's Foursquare place stays empty until staff add it. A party's space holds the root's `computer.localnetwork.party` record: its basics (name, picture, bio, area and links) and, once it's published, when. Without that it's a draft, which only its people and staff can open; everyone else gets a 404. Its page, `/party//`, is the first built in place ([docs/edit-mode.md](docs/edit-mode.md)): its people with page.edit, or staff with Edit as staff, edit its name, picture, bio, area and links where they're shown, and Publish a draft. It also shows its hosts and cohosts who haven't hidden. `/party/new` (signed in) opens the same page empty in edit mode: Save draft starts the party as a draft with its creator as host and goes on editing it at its own address, and Publish starts it published. The dashboard's sidebar offers it while `spacePages` is on. A party's events have their pages under it at `/party///`, the event's record key and then its name to read, built in place the same way (`src/lib/server/event-page.ts`): its people with events.manage edit the name, the venue, the date and times (on the venue's clock, or until there's a venue, a time zone picked with them, which a new draft takes from its party's area, else its creator's, else UTC), the lineup (each performer by handle or act page link), the ticket link, what it's about and who can see it, and outside edit mode copy or reset a private event's link and cancel a published one. Its people and staff open any of its events; anyone else opens a published public one, or a private one from its link's `?t=` token, and gets a 404 for the rest. The page says whether the venue has confirmed it or it's waiting for the venue, and never more (ADR 0014), and links the venue's page. A listed event (published, public, not Never confirmed, and under Venue approves only once confirmed) has a public copy, a `community.lexicon.calendar.event` the root keeps in its own repo under the event's record key with its name, what it's about, its times, its status, the venue's address, coordinates and page, and its ticket link and page here (`calendarCopy` in `src/lib/server/services/events.ts`), so other calendar apps can show it. Each save and the venue confirming it rewrite it, and it's deleted once the event isn't listed. What changes listing without either (the night ending while it waits for the venue, the venue's mode or blocks) is caught by `reconcileCalendarCopies`, which runs at startup, every hour, and for the venue after its settings change, and writes only where a copy differs. While it's listed, until its night is over, and unless it's cancelled, the page has Going and Interested beside its tickets, with how many said each (`src/lib/server/services/rsvps.ts`): each writes a `community.lexicon.calendar.rsvp`, the record other AT Protocol calendar apps write, to the guest's own repo, answering the public copy, and pressing the pressed one takes the answer back. They're forms, so they work without scripts; signed out, they link to sign-in and back. A private event has neither, since an RSVP in a guest's public repo would show anyone who's going. An RSVP to a copy that's since been taken down stays in the guest's repo, counted nowhere. A night ends at 6:00 the next morning on the venue's clock (`nightEnd` in `src/lib/server/venue-time.ts`), and an event still waiting for the venue then is Never confirmed: it leaves every list, and only its party's people and staff can open it, marked so. A confirmed one just becomes a past event. The party's page lists its events until their night ends, its drafts, private ones and ones never confirmed marked for its people, and `/party//new` opens an empty event page in edit mode for its people with events.manage: Save draft makes the event as a draft and Publish makes it published. A save that would move the times onto another clock (picking a venue in another time zone, another venue, or another zone for the draft) comes back asking whether to keep them as entered or at the same moments, and each answer saves again. A venue's page, `/venue//`, shows its address, an OpenStreetMap link when its coordinates are known, and the events listed there until their night ends, each with its party and marked waiting for the venue or Confirmed. It links the venue's dashboard pages for the people who can use them (claiming it for anyone else signed in) while `peopleSpaces` is on, and leaves its owners off until they can choose to show. A performer's booking details go in a separate booking details space with the same key, which only the root is in, so members can't read them from another client ([ADR 0011](../../docs/adr/0011-booking-details-stay-out-of-the-performer-space.md)). Each space's people records say who's in it, in what role, with which capabilities, and whether they're hidden from everyone outside it. The root writes every record there, for someone who holds the capability the change needs or for staff, whose changes the audit log marks with their role. Someone always has to be left who can manage its people, unless staff decide otherwise. The space's members follow its people: everyone reads, and those with a capability that writes also write. The app repeats that at startup and every hour, so a member update that failed part way still finishes. The `pauseReconcilers` flag stops that, and every other round that fixes drift in the root's repo, without a deploy. +- Acts, parties and venues each get a space under the root. Their pages ship dark behind two release flags: `spacePages` for the public act, party, venue and event pages, and `peopleSpaces` for the member pages (inviting people, invite links, asking to join, people lists). A route behind one calls `requireFlag` (`src/lib/server/http.ts`), which answers 404 while the flag is off for the viewer. A performer's space also holds the root's `computer.localnetwork.performer` record, which says whether it's an act (with what its page shows) or a DJ's own space for their backstage and managers. A venue's space holds the root's `computer.localnetwork.venue` record: its name, address and coordinates, its Foursquare place once known, and whether events naming it show at once (Anyone can list) or only once confirmed (Venue approves). Names repeat ([ADR 0016](../../docs/adr/0016-names-repeat-keys-and-handles-identify.md)): an act, party or venue goes by its space key, and its page is `///` (`spacePagePath` in `src/lib/space-paths.ts`), where the name part is only there to read: any other name, or none, redirects to the current one. Anyone signed in can add a venue, which puts nobody in its space (owning one takes a confirmed claim). Adding a place that's already a venue gives back that venue, and so does adding the same name in the same city and country unless the two are different Foursquare places. Forms pick one with the venue picker (`src/lib/components/VenuePicker.svelte`): an existing venue by name, with its city on a second line to tell same-named ones apart, or a new one by its name and its city from the city search, both through `/api/venues`, which answers 404 while `spacePages` is off. A new venue's Foursquare place stays empty until staff add it. A party's space holds the root's `computer.localnetwork.party` record: its basics (name, picture, bio, area and links) and, once it's published, when. Without that it's a draft, which only its people and staff can open; everyone else gets a 404. Its page, `/party//`, is the first built in place ([docs/edit-mode.md](docs/edit-mode.md)): its people with page.edit, or staff with Edit as staff, edit its name, picture, bio, area and links where they're shown, and Publish a draft. It also shows its hosts and cohosts who haven't hidden. `/party/new` (signed in) opens the same page empty in edit mode: Save draft starts the party as a draft with its creator as host and goes on editing it at its own address, and Publish starts it published. The dashboard's sidebar offers it while `spacePages` is on. A party's events have their pages under it at `/party///`, the event's record key and then its name to read, built in place the same way (`src/lib/server/event-page.ts`): its people with events.manage edit the name, the venue, the date and times (on the venue's clock, or until there's a venue, a time zone picked with them, which a new draft takes from its party's area, else its creator's, else UTC), the lineup (each performer by handle or act page link), the ticket link, what it's about and who can see it, and outside edit mode copy or reset a private event's link and cancel a published one. Its people and staff open any of its events; anyone else opens a published public one, or a private one from its link's `?t=` token, and gets a 404 for the rest. The page says whether the venue has confirmed it or it's waiting for the venue, and never more (ADR 0014), and links the venue's page. A listed event (published, public, not Never confirmed, and under Venue approves only once confirmed) has a public copy, a `community.lexicon.calendar.event` the root keeps in its own repo under the event's record key with its name, what it's about, its times, its status, the venue's address, coordinates and page, and its ticket link and page here (`calendarCopy` in `src/lib/server/services/events.ts`), so other calendar apps can show it. Each save and the venue confirming it rewrite it, and it's deleted once the event isn't listed. What changes listing without either (the night ending while it waits for the venue, the venue's mode or blocks) is caught by `reconcileCalendarCopies`, which runs at startup, every hour, and for the venue after its settings change, and writes only where a copy differs. While it's listed, until its night is over, and unless it's cancelled, the page has Going and Interested beside its tickets, with how many said each (`src/lib/server/services/rsvps.ts`): each writes a `community.lexicon.calendar.rsvp`, the record other AT Protocol calendar apps write, to the guest's own repo, answering the public copy, and pressing the pressed one takes the answer back. They're forms, so they work without scripts; signed out, they link to sign-in and back. A private event has neither, since an RSVP in a guest's public repo would show anyone who's going. An RSVP to a copy that's since been taken down stays in the guest's repo, counted nowhere. A night ends at 6:00 the next morning on the venue's clock (`nightEnd` in `src/lib/server/venue-time.ts`), and an event still waiting for the venue then is Never confirmed: it leaves every list, and only its party's people and staff can open it, marked so. A confirmed one just becomes a past event. The party's page lists its events until their night ends, its drafts, private ones and ones never confirmed marked for its people, and `/party//new` opens an empty event page in edit mode for its people with events.manage: Save draft makes the event as a draft and Publish makes it published. A save that would move the times onto another clock (picking a venue in another time zone, another venue, or another zone for the draft) comes back asking whether to keep them as entered or at the same moments, and each answer saves again. A venue's page, `/venue//`, shows its address, an OpenStreetMap link when its coordinates are known, and the events listed there until their night ends, each with its party and marked waiting for the venue or Confirmed. It links the venue's dashboard pages for the people who can use them (claiming it for anyone else signed in) while `peopleSpaces` is on, and leaves its owners off until they can choose to show. A performer's booking details go in a separate booking details space with the same key, which only the root is in, so members can't read them from another client ([ADR 0011](../../docs/adr/0011-booking-details-stay-out-of-the-performer-space.md)). Each space's people records say who's in it, in what role, with which capabilities, and whether they're hidden from everyone outside it. The root writes every record there, for someone who holds the capability the change needs or for staff, whose changes the audit log marks with their role. Someone always has to be left who can manage its people, unless staff decide otherwise. The space's members follow its people: everyone reads, and those with a capability that writes also write. The app repeats that at startup and every hour, so a member update that failed part way still finishes. The `pauseReconcilers` flag stops that, and every other round that writes to the root's repo to fix drift, without a deploy. The venue blocks round keeps running, since it only reads the root's blocks into the index. - People come into one by an invite to their account, an invite link, or a request to join that someone with people.manage approves, and choose then whether to be hidden. A link's token is shown once and only its hash is kept, and a link never lets anyone manage people. Invites last 30 days and links 7 unless their maker picks up to 90, someone can have 50 open in a space at once, and both go when their maker can no longer add people, unless staff made them. - When staff list one, the root writes a `computer.localnetwork.listing` record to its public repo with what its public page shows, the people in a listed role (an act's members, a party's hosts and cohosts) who haven't hidden, and an act's managers who haven't. It's rewritten only when that changes, and checked every hour. A listing points at a public page, so none is written until `spacePages` is on for everyone, and turning it off takes them down at the next hourly check. Acts, parties and venues have something to list: an act's form, basics and performer sections, a published party's basics (each avatar is a blob the root uploaded), and a venue's name, address and coordinates. A published party is public at its address before it's listed; a draft is never listed. A venue is listed as soon as it's added, since it's a public place, and a DJ's own space is never listed. HappyView keeps only the root's listings (`lua/computer/localnetwork/listing.lua`). Staff see every space and its people, hidden ones marked, at `/admin/spaces`, where they add and remove people, change roles, and list or unlist it. - Profiles cover genres, city and travel radius, set types and lengths, formats, room sizes, any number of fee levels (each a tier, with an optional label and range), links, playable SoundCloud/Mixcloud/YouTube mixes, highlights, photo. @@ -82,11 +82,11 @@ All data lives on the AT Protocol. Public profiles are ordinary atproto records; ### Flags -A flag turns a feature on for some people before everyone. The flags themselves are files in [`flags/catalog/`](../../flags/README.md), which locallibrary reads too. Staff set who each is on for at `/admin/flags`: everyone, a percentage of people, [flag groups](../../GLOSSARY.md) at `/admin/flags/groups`, or single accounts. "Off for everyone" turns a flag off and keeps all of that for when it's back on. Admins manage all of it, and on the Staff page they can give a moderator either part: flags, or flag groups. Every change is in the audit log. The list marks a flag "Ready to remove" once it's been on for everyone, or every account, for 30 days. +A flag turns a feature on for some people before everyone. The flags themselves are files in [`flags/catalog/`](../../flags/README.md), which locallibrary reads too. Staff set who each is on for at `/admin/flags`: everyone, a percentage of people, [flag groups](../../GLOSSARY.md) at `/admin/flags/groups`, or single accounts. "Off for everyone" turns a flag off and keeps all of that for when it's back on. Admins manage all of it, and on the Staff page they can give a moderator either part: flags, or flag groups. Every change is in the audit log. The list marks a release flag "Ready to remove" once it's been on for everyone, or every account, for 30 days. To see a flag without changing it for anyone, staff with the flags grant can turn it on or off for their own browser from its page. The preview is a cookie signed with their session, lasts an hour, shows a banner on every page until it's cleared, and is audited. In development and tests, `FLAG_OVERRIDES=key=on,other=off` forces flags for every request instead; the app won't start with it in production ([ADR 0010](../../docs/adr/0010-flags-turn-off-and-preview-without-touching-targeting.md)). -What's set is kept as `staff.flag` and `staff.group` records in the staff space, indexed into SQLite and held in memory, so reading one on a request costs nothing. Pages read `data.flags?.key` and server code `locals.flags.key`, worked out once per request. A signed-out visitor counts in a percentage by a random id in the `ln_flag_visitor` cookie, set only while a flag is on for one ([ADR 0018](../../docs/adr/0018-signed-out-visitors-get-a-rollout-id.md)). locallibrary can't read the staff space, so `computer.localnetwork.flags.getFlags` tells it the public gates and whether it's targeted ([ADR 0006](../../docs/adr/0006-locallibrary-asks-the-website-for-flags.md)). +What's set is kept as `staff.flag` and `staff.group` records in the staff space, indexed into SQLite and held in memory, so reading one on a request costs nothing. Pages read `data.flags?.key` and server code `locals.flags.key`, worked out once per request. A signed-out visitor counts in a percentage by a random id in the `ln_flag_visitor` cookie, set only while a flag that changes a public page (one with `showsOn`) is on for one ([ADR 0018](../../docs/adr/0018-signed-out-visitors-get-a-rollout-id.md)). locallibrary can't read the staff space, so `computer.localnetwork.flags.getFlags` tells it the public gates and whether it's targeted ([ADR 0006](../../docs/adr/0006-locallibrary-asks-the-website-for-flags.md)). ### Staff @@ -233,7 +233,7 @@ Published projects, the DJ stats, sets, press kits, shows, calendar events, foll - `dj/recording.lua` keeps every account's set recordings, which locallibrary uploads and a set's `recording` points at: the audio blob as written, how long it plays and `createdAt`, and nothing else. A recording without an audio blob isn't kept. - `profile.lua` keeps every account's Local Network profile at the key `self`, as written, when each field the site reads has the type it expects. `listing/profile.lua` keeps only the root's DJ listings, each keyed by the DID it names. - `dj/profile.lua` and `locallibrary/settings.lua` keep every account's DJ stats and rekordbox settings as written, at the key `self`. `epk.lua` keeps press kits of the root's projects: the root's own, and legacy ones by an account that manages the project they name. -- Jetstream only brings records written after HappyView started keeping them, so the app has HappyView re-read the root's and the managers' sets, recordings, stats, press kits, calendar events, profiles and Bluesky profiles from their PDS: for each of them once per version of each one's record script (one job per 500 accounts per collection, retried until all start, the version kept in the app database), and when a project gains a manager and HappyView serves it (their follows too). The same goes, once per script version, for the follows of the managers of projects whose press kits read follows, the root's verifications and DJ listings, and the bug report space. The edit form's set picker also re-reads its accounts' sets when it opens (one backfill for all of them, each account at most every ten minutes); publishing a project's first press kit that reads follows re-reads its managers' follows; and a profile or the space HappyView doesn't have yet is re-read, and waited for, when it's needed. The `pauseBackfills` flag stops the re-reads for a new script version, the boot's re-read of every manager's shows, and the set picker's and requestIndex's without a deploy; the re-reads that follow one change still run. +- Jetstream only brings records written after HappyView started keeping them, so the app has HappyView re-read the root's and the managers' sets, recordings, stats, press kits, calendar events, profiles and Bluesky profiles from their PDS: for each of them once per version of each one's record script (one job per 500 accounts per collection, retried until all start, the version kept in the app database), and when a project gains a manager and HappyView serves it (their follows too). The same goes, once per script version, for the follows of the managers of projects whose press kits read follows, the root's verifications and DJ listings, and the bug report space. The edit form's set picker also re-reads its accounts' sets when it opens (one backfill for all of them, each account at most every ten minutes); publishing a project's first press kit that reads follows re-reads its managers' follows; and a profile or the space HappyView doesn't have yet is re-read, and waited for, when it's needed. The `pauseBackfills` flag stops all of these without a deploy, including the ones that follow one change (a new manager, a late write, a first press kit, a DJ listing). Only the root's own performers are still re-read at boot, since the directory lists nothing without them. - locallibrary reads its account's sets, recordings, stats and settings back from HappyView before replacing them, so it first calls `computer.localnetwork.directory.requestIndex`, a procedure this app answers itself (`src/routes/xrpc/`) with inter-service auth from the account's PDS. It has HappyView re-read those four collections from the caller's repo, and only theirs, under the picker's limit (each account and collection at most every ten minutes; a call in between answers from the last re-read), and waits up to 5 seconds: `indexed` says whether it finished. While the `pauseRequestIndex` flag is on, it answers `indexed: false` without re-reading anything. - `show.lua` keeps only shows with coordinates and an RFC 3339 start time by an account that manages the project they name, and only http(s) ticket links; `follow.lua` keeps only follows of the root's projects and of the profiles HappyView keeps, leaving out an account following its own. Jetstream sends every account's calendar events, from every calendar app, so `community/lexicon/calendar/event.lua` keeps only the root's (party events' public copies) and events by an account that manages one of the root's projects, as written. It checks the author rather than a show naming the event, so it doesn't matter which of the two HappyView hears of first. Listings read each show's own copy; the event is for the announce form, and the show's strongRef to it says when it changed since. `community/lexicon/calendar/rsvp.lua` keeps RSVPs from any calendar app to the root's calendar events, by the subject's URI, with just the event and the answer. - Other apps' records get gates too, since Jetstream sends every account's. `app/bsky/graph/verification.lua` keeps only the root's verifications. `app/bsky/actor/profile.lua` keeps every account's Bluesky profile (at the key `self`) as written: the hosted instance backfills all of them and keeps them current, so an account that becomes a manager, gets verified or makes a profile here later already has one. The site reads only the display names and pronouns: profile pages show the pronouns and verification statuses compare the names. Saving a profile has HappyView re-read that account's Bluesky profile. The profile form shows the pronouns but can't change them yet. `app/bsky/graph/follow.lua` keeps only the subject and date of follows by the managers of a project with a press kit that treats people they follow differently from anyone, since any of them following someone counts. `app/userinput/space.lua` keeps only `USERINPUT_SPACE`, whose version each bug report pins (record scripts get it beside `ROOT_DID`). Follows and profiles are busy: on 2026-10-24 Bluesky carried about 42 follow events and 1.3 profile changes a second. HappyView runs a script for each, which cost about 1.3 ms of CPU on a laptop under HappyView 2, nearly all of it HappyView's own cost per script run; the profile script now only checks the record key. The follow gate first looks up the root projects the follower manages, which ends it for nearly every follow. On the shared store a gate only hides records it has run over, so an account's raw follows show up in `listRecords` until it has; the site only reads follows by manager, for press kits that read them. HappyView 3 writes an event log row for each run only with verbose event logging on, so keep that off. @@ -241,7 +241,7 @@ Published projects, the DJ stats, sets, press kits, shows, calendar events, foll - `searchProjects`, `matchProjects`, `getProject`, `getProjects`, and `getStats` do the search, ranking, and lookups. `searchPerformers` searches active projects and listed DJs together: a DJ counts when the root lists them and their profile has the performer section on, as a solo act, by the genres their DJ stats say they play most when the section names none. Both searches share their filters and ranking (`lua/lib/directory.lua`). Match results carry reason codes, which the app turns into text. `getProject` with `counts` also counts the project's press kits and upcoming shows, so the project's pages hold that much room for them while they stream in. `getSets` and `listSets` look up sets by URI and by account, without their tracks. - `getRecords` (up to 25 URIs) and `listRecords` (one account's records of one collection, last record key first, with a cursor) read any record HappyView keeps, as its record script stored it, the way `com.atproto.repo.getRecord` and `listRecords` read a PDS. For calendar events, the bug report space and DJ stats, a record HappyView lacks is read from the account's own PDS instead (`lua/lib/pds.lua`, through the `happyview-http` library plugin), without being stored or gated, so those don't wait for a backfill. The app's `IndexedRepo` (`src/lib/server/happyview/indexed.ts`) wraps them for the DJ stats and sets on project pages, press kits and their managers' follows, shows and their calendar events, verifications and display names, and the bug report space. A HappyView that's down reads as nothing for pages that list them, and fails a read that a change or an access decision depends on (opening one press kit, counting a project's press kits, moving legacy ones, syncing their spaces' members, a press kit's "people you follow" rule, editing a show, verifying, posting a bug report). A press kit draft and a show edit save only over the versions their form was opened on, and publishing a press kit or re-issuing a verification swaps on the version HappyView serves, so none overwrites a change the person hasn't seen: they're asked to reload. - `getCharts`, `getArtist`, and `searchArtists` count supports. They group every stored play by track and artist in SQL on each request (about a third of a second for 2,000 sets of 25 tracks on a laptop, measured on SQLite), so no counts are kept anywhere; the app reuses an answer for a minute, and the pages may be cached for as long. -- HappyView also follows Jetstream's account events. It removes the records of an account that's deleted, taken down or suspended, but keeps a deactivated account's, and a taken-down account's records come back only with a re-read. So the app asks an account's PDS whether it's active (`com.atproto.sync.getRepoStatus`) and keeps each answer in memory for half an hour (`src/lib/server/atproto/account-status.ts`, [ADR 0020](../../docs/adr/0020-inactive-accounts-are-asked-of-their-pds.md)). `searchPerformers`, `getCharts`, `getArtist`, `searchArtists`, `getSets` and `listShows` take an `inactive` list of DIDs and leave out those accounts' sets, shows and listed profiles, along with a solo project that gives way to such a profile. The app sends the inactive ones among the managers and listed DJs, checked eight at a time in the background once the list is half an hour old, so pages never wait on it. A PDS that can't be asked leaves the account as last seen, or active. When a taken-down or suspended account is active again, the app has HappyView re-read its records. +- HappyView also follows Jetstream's account events. It removes the records of an account that's deleted, taken down or suspended, but keeps a deactivated account's, and a taken-down account's records come back only with a re-read. So the app asks an account's PDS whether it's active (`com.atproto.sync.getRepoStatus`) and keeps each answer in memory for half an hour (`src/lib/server/atproto/account-status.ts`, [ADR 0020](../../docs/adr/0020-inactive-accounts-are-asked-of-their-pds.md)). `searchPerformers`, `getCharts`, `getArtist`, `searchArtists`, `getSets` and `listShows` take an `inactive` list of up to 100 DIDs and leave out those accounts' sets, shows and listed profiles, along with a solo project that gives way to such a profile. The app sends the deactivated, taken-down and suspended ones among the managers and listed DJs (HappyView already dropped a deleted account's records), checked eight at a time in the background once the list is half an hour old, so pages never wait on it. After a restart, inactive accounts can show until the first check finishes, usually within seconds. An inactive answer is checked against a freshly fetched DID document, so an account that just moved PDS isn't taken for deleted or deactivated. A PDS that can't be asked leaves the account as last seen, or active. When a taken-down or suspended account is active again, the app has HappyView re-read its records. - The genre taxonomy and fee tiers are generated into the scripts from `src/lib/taxonomy/`, so TypeScript stays the source of truth. With `HAPPYVIEW_API_KEY` set, the app uploads whichever of its scripts and lexicons changed when it boots (scripts first, so the record gate is in place before ingestion starts), has HappyView track the other authorities' lexicons it needs that it doesn't yet (`POST /admin/network-lexicons`, which resolves them from the network and replaces a copy uploaded by hand), then has HappyView re-read the root's repo and waits for that to finish, and then every manager's shows in one batch. After publishing a project, a show, a follow, an RSVP, or a press kit it waits (up to 5 seconds) for HappyView to index it, so the next page shows it; when a show or its calendar event, a follow, an RSVP, or a press kit doesn't show up in time, HappyView re-reads that collection from that one account's repo. The directory queries are lexicons too, so `pnpm lexicons:publish` publishes a new one with the rest (see [Deploying](#deploying)). @@ -405,7 +405,7 @@ railway ssh --service localnetwork -- node scripts/db-backup.ts restore latest railway service restart --service localnetwork --yes ``` -A restore downloads the backup, checks its integrity, keeps the database it replaces as `localnetwork.db.before-restore` beside it, and writes the backup in with the same online backup, so it's safe while the app has the database open. `pnpm db:restore data/copy.db` restores to another path instead, to look at a backup locally. +A restore downloads the backup, checks its integrity, keeps the database it replaces as `localnetwork.db.before-restore` beside it, and writes the backup in with the same online backup, so it's safe while the app has the database open. Flags come back as the backup had them until the first sync reads the staff space again, and the member rounds at boot run before it. So `pauseReconcilers` holds through a restore only if it was on when the backup was taken; turn it on again from its page once the app is up. `pnpm db:restore data/copy.db` restores to another path instead, to look at a backup locally. ### Tools' pages and hosts diff --git a/apps/web/docs/diagrams/flags.md b/apps/web/docs/diagrams/flags.md index 5fc96d1aa..df3f0e4d5 100644 --- a/apps/web/docs/diagrams/flags.md +++ b/apps/web/docs/diagrams/flags.md @@ -34,13 +34,13 @@ Source: [`src/lib/server/flags/evaluate.ts`](../../src/lib/server/flags/evaluate ## Flags on a page request -Every request gets every flag decided once, held in memory between record changes. An `/xrpc` call never reads a cookie, so it only gets flags on for everyone. A signed-out visitor gets an id of their own while a flag is on for a percentage, and their response stays out of shared caches. A staff member's preview changes only their own browser. +Every request gets every flag decided once, held in memory between record changes. An `/xrpc` call never reads a cookie, so it only gets flags on for everyone. A signed-out visitor gets an id of their own while a flag that changes a public page (one with `showsOn`) is on for a percentage, and their response stays out of shared caches. A staff member's preview changes only their own browser. ```mermaid flowchart TD Request["A request"] -- "/xrpc" --> Route["Every flag with no id,
locals.flags for the route, no preview"] Request -- "signed in" --> Decide["Decide every flag for the viewer"] - Request -- "signed out" --> Share{"A flag on for
a percentage?"} + Request -- "signed out" --> Share{"A flag with showsOn
on for a percentage?"} Share -- "no" --> Nobody["Decide every flag with no id"] Share -- "yes" --> Visitor["ln_flag_visitor, set if missing:
decide for its visitor id,
no public caching"] Decide --> Cookie{"ln_flag_preview set?"} diff --git a/apps/web/docs/diagrams/jobs-and-directory.md b/apps/web/docs/diagrams/jobs-and-directory.md index e4f0447a1..c337d3983 100644 --- a/apps/web/docs/diagrams/jobs-and-directory.md +++ b/apps/web/docs/diagrams/jobs-and-directory.md @@ -12,7 +12,7 @@ Startup, scheduled jobs and HappyView. The rest are listed in the [README](../.. ## Startup -What happens when the process starts. A failed start leaves the setup page up, and the next request tries again. While the `pauseReconcilers` flag is on for everyone, bootstrap skips the reconcile steps and `moveKitSpaces`, logging each one it skips. +What happens when the process starts. A failed start leaves the setup page up, and the next request tries again. While the `pauseReconcilers` flag is on for everyone, bootstrap skips the reconcile steps that write to the root's repo and `moveKitSpaces`, logging each one it skips. `reconcileBlocks` still runs: it only reads the root's blocks into the index. On a new or restored database the member steps run before `syncAll` has read the flag's record, so they read it as the database had it: off on a fresh one, as the backup had it after a restore. ```mermaid flowchart TD @@ -35,7 +35,7 @@ Source: [`src/hooks.server.ts`](../../src/hooks.server.ts), [`src/lib/server/app ## Scheduled jobs -The jobs the app schedules, all in one process. A job still running skips its next turn. While the `pauseReconcilers` flag is on for everyone, the rounds that write to the root's repo (staff-spaces, manager-spaces, shared-spaces, listings, venue-blocks and calendar-copies) skip their turn and log that they did. +The jobs the app schedules, all in one process. A job still running skips its next turn. While the `pauseReconcilers` flag is on for everyone, the rounds that write to the root's repo (staff-spaces, manager-spaces, shared-spaces, listings and calendar-copies) skip their turn and log that they did. venue-blocks only reads the root's blocks into the index, so it keeps running: a block index left empty would show blocked promoters as confirmed. ```mermaid flowchart LR @@ -76,7 +76,7 @@ Source: [`src/lib/server/happyview/sync.ts`](../../src/lib/server/happyview/sync ## HappyView re-reads -What makes the app ask HappyView to read repos again through `/admin/backfill`, up to 500 accounts a job. Jetstream only brings new writes, so these fill the gaps; on the hosted instance's shared Network store, they run the record script over what the store holds. The `pauseBackfills` flag stops the ones for a new record script, the managers' shows at boot, the set picker's and requestIndex's; the ones that follow one change (a new manager, a late write, a first press kit, a DJ listing) still run. +What makes the app ask HappyView to read repos again through `/admin/backfill`, up to 500 accounts a job. Jetstream only brings new writes, so these fill the gaps; on the hosted instance's shared Network store, they run the record script over what the store holds. The `pauseBackfills` flag stops all of them but the root's performers at boot, which the directory needs to list anything. ```mermaid flowchart LR diff --git a/apps/web/docs/diagrams/mixes-and-sets.md b/apps/web/docs/diagrams/mixes-and-sets.md index e4450dab3..d64d62fd6 100644 --- a/apps/web/docs/diagrams/mixes-and-sets.md +++ b/apps/web/docs/diagrams/mixes-and-sets.md @@ -118,7 +118,7 @@ Support counts come straight from the sets HappyView keeps, and nothing stores t ```mermaid flowchart TD Sets["dj.set records of active performers' managers,
each named track kept by the gate"] --> Sql - Inactive["The app's list of inactive accounts"] -- "inactive param" --> Sql["Lua queries group plays in SQL"] + Inactive["The app's list of deactivated,
taken-down and suspended accounts"] -- "inactive param" --> Sql["Lua queries group plays in SQL"] Sql --> Charts["getCharts"] Sql --> Artist["getArtist"] Sql --> Search["searchArtists"] diff --git a/apps/web/docs/diagrams/requests-and-routes.md b/apps/web/docs/diagrams/requests-and-routes.md index 2392adb96..c57c8700e 100644 --- a/apps/web/docs/diagrams/requests-and-routes.md +++ b/apps/web/docs/diagrams/requests-and-routes.md @@ -31,7 +31,7 @@ flowchart TD Load --> Limit["Write limit for this address"] Limit -- "over it" --> Slow["429"] Limit --> Session["ln_session to a viewer,
skipped on /xrpc/"] - Session --> Flags["Flags for the viewer, a signed-out visitor's
ln_flag_visitor id while a flag is on for a
percentage, no id on /xrpc/, and a staff
preview from ln_flag_preview off it"] + Session --> Flags["Flags for the viewer, a signed-out visitor's
ln_flag_visitor id while a flag with showsOn
is on for a percentage, no id on /xrpc/, and a staff
preview from ln_flag_preview off it"] Flags --> Guard["guardArea by route"] Guard -- "/dashboard or /admin,
signed out" --> Login["303 to /login?next="] Guard -- "/admin, not staff" --> Refused["403"] @@ -68,7 +68,7 @@ Source: [`src/routes/+layout.server.ts`](../../src/routes/+layout.server.ts), [` ## Response caching -What each response lets a browser or a shared cache keep. Pages that show the same thing to everyone use `cacheBriefly`. While a flag is on for a percentage, the server hook turns `public` into `private` on every response to a signed-out visitor outside `/xrpc/`, since their flags come from their own `ln_flag_visitor` cookie. +What each response lets a browser or a shared cache keep. Pages that show the same thing to everyone use `cacheBriefly`. While a flag that changes a public page is on for a percentage, the server hook turns `public` into `private` on every response to a signed-out visitor outside `/xrpc/`, since their flags come from their own `ln_flag_visitor` cookie. ```mermaid flowchart LR diff --git a/apps/web/src/hooks.server.test.ts b/apps/web/src/hooks.server.test.ts index b42c09761..33cd2aac2 100644 --- a/apps/web/src/hooks.server.test.ts +++ b/apps/web/src/hooks.server.test.ts @@ -17,6 +17,7 @@ import { RateLimiter } from '#lib/server/rate-limit.ts'; import { createTestServices } from '#lib/server/testing/core.ts'; import { type WrittenLine, writtenLog } from '#lib/server/testing/written-log.ts'; import type { Logger } from '#lib/server/logger.ts'; +import type { FlagKey } from '#lib/flags/keys.generated.ts'; import type { Viewer } from '#lib/types.ts'; import { flagsOff } from '#lib/testing/flags.ts'; import { routeEvent, type RouteEventInit } from '#lib/testing/route-event.ts'; @@ -298,8 +299,8 @@ it('counts a signed-out visitor in a percentage by their own cookie, the same wa const inside = await handledWithLocals(handle, { url: '/', cookies: { [VISITOR_COOKIE]: INSIDE_HALF } }); const outside = await handledWithLocals(handle, { url: '/', cookies: { [VISITOR_COOKIE]: OUTSIDE_HALF } }); - expect(inside.locals.flags?.parityCanary).toBe(true); - expect(outside.locals.flags?.parityCanary).toBe(false); + expect(inside.locals.flags?.[PAGE_FLAG]).toBe(true); + expect(outside.locals.flags?.[PAGE_FLAG]).toBe(false); expect(inside.cookies.options.has(VISITOR_COOKIE)).toBe(false); } }); @@ -309,7 +310,9 @@ it('gives a signed-out visitor a first-party id on their first request, and keep const { handle } = hooksWith(async () => s.app); await atPercentage(s, 50); - for (const cookies of [{}, { [VISITOR_COOKIE]: 'not-a-uuid' }]) { + const visits: Record[] = [{}, { [VISITOR_COOKIE]: 'not-a-uuid' }]; + + for (const cookies of visits) { const first = await handledWithLocals(handle, { url: '/', cookies }); const id = first.cookies.get(VISITOR_COOKIE); @@ -324,7 +327,7 @@ it('gives a signed-out visitor a first-party id on their first request, and keep const again = await handledWithLocals(handle, { url: '/', cookies: { [VISITOR_COOKIE]: id! } }); - expect(again.locals.flags?.parityCanary).toBe(first.locals.flags?.parityCanary); + expect(again.locals.flags?.[PAGE_FLAG]).toBe(first.locals.flags?.[PAGE_FLAG]); } }); @@ -356,7 +359,7 @@ it('gives a visitor no id while no flag is on for a percentage, nor when signed cookies: { [VISITOR_COOKIE]: INSIDE_HALF } }); - expect(xrpc.locals.flags?.parityCanary).toBe(false); + expect(xrpc.locals.flags?.[PAGE_FLAG]).toBe(false); expect(xrpc.cookies.options.has(VISITOR_COOKIE)).toBe(false); }); @@ -378,6 +381,20 @@ it("keeps a signed-out page out of shared caches while it depends on the visitor expect(await cacheControl({ [VISITOR_COOKIE]: OUTSIDE_HALF })).toBe('private, max-age=60'); }); +it('gives a visitor no id, and keeps pages shared-cacheable, while only a flag for accounts is on for a percentage', async () => { + const s = await services({ admins: [ADMIN] }); + const { handle } = hooksWith(async () => s.app); + await atPercentage(s, 50, {}, ACCOUNT_FLAG); + + const { cookies, response } = await handledWithLocals(handle, { url: '/artists' }, 200, { + 'cache-control': 'public, max-age=60', + vary: 'Cookie' + }); + + expect(cookies.options.has(VISITOR_COOKIE)).toBe(false); + expect(response.headers.get('cache-control')).toBe('public, max-age=60'); +}); + it('limits writes by address, and counts an unknown address as one', async () => { const s = await services({ writes: 1 }); const { handle } = hooksWith(async () => s.app); @@ -582,6 +599,30 @@ it("renders the page in the locale its cookie names, with the page's lang and di ); }); +it("keeps the locale cookie out of a public immutable answer's Vary, so caches share an OG card or avatar", async () => { + // Arrange + const s = await services(); + const { handle } = hooksWith(async () => s.app); + const image = { 'content-type': 'image/png', 'cache-control': 'public, max-age=31536000, immutable' }; + const request = { url: '/og/project/3proj.png', cookies: { ln_locale: 'en' } }; + + // Act + const { response } = await handledWithLocals(handle, request, 200, image); + const page = await handledWithLocals(handle, { url: '/artists' }, 200, { 'cache-control': 'public, max-age=60' }); + + const gzipped = await handledWithLocals(handle, { ...request, headers: { 'accept-encoding': 'gzip' } }, 200, { + ...image, + 'content-type': 'application/json' + }); + + // Assert + expect({ + image: response.headers.get('vary'), + page: page.response.headers.get('vary'), + gzipped: gzipped.response.headers.get('vary') + }).toEqual({ image: null, page: 'Cookie', gzipped: 'accept-encoding' }); +}); + it("preloads the scripts, styles and the two typefaces' Latin files, and nothing else", async () => { const s = await services(); const { handle } = hooksWith(async () => s.app); @@ -647,19 +688,26 @@ const DJ = 'did:plc:dj'; const ADMIN = 'did:plc:admin'; -/** Visitor cookies whose ids sit in parityCanary's buckets 16 and 55: inside a 50% rollout, and outside it. */ +/** A flag that changes a public page (its catalog file has `showsOn`), so signed-out visitors are counted in it. */ +const PAGE_FLAG = 'pauseRecordingStream' satisfies FlagKey; + +/** A flag with no `showsOn`, which changes only what accounts see. */ +const ACCOUNT_FLAG = 'inboxEmail' satisfies FlagKey; + +/** Visitor cookies whose ids sit in PAGE_FLAG's buckets 36 and 59: inside a 50% rollout, and outside it. */ const INSIDE_HALF = '00000000-0000-4000-8000-000000000000'; const OUTSIDE_HALF = '00000001-0000-4000-8000-000000000000'; -/** Puts parityCanary on for `percentage` of everyone, with `gates` on top, as an admin of `s`. */ +/** Puts `key` on for `percentage` of everyone, with `gates` on top, as an admin of `s`. */ async function atPercentage( s: Awaited>, percentage: number, - gates: { enabled?: boolean; everyone?: boolean } = {} + gates: { enabled?: boolean; everyone?: boolean } = {}, + key: FlagKey = PAGE_FLAG ) { const input = { enabled: true, everyone: false, percentage, groups: [], dids: [], ...gates }; - await s.flags.updateFlag(await s.viewer(ADMIN), 'parityCanary', input); + await s.flags.updateFlag(await s.viewer(ADMIN), key, input); } /** An account whose OAuth grant lacks scopes the app now asks for, so the app has no viewer for it. */ @@ -672,7 +720,7 @@ type HookApp = { logger?: Logger; sessions?: WebSessions; limits?: { write: RateLimiter }; - flags?: Pick; + flags?: Pick; viewer?: (did: string) => Promise; config?: { publicUrl: string }; }; diff --git a/apps/web/src/hooks.server.ts b/apps/web/src/hooks.server.ts index 97f4a869f..0cf365240 100644 --- a/apps/web/src/hooks.server.ts +++ b/apps/web/src/hooks.server.ts @@ -113,9 +113,9 @@ export function serverHooks({ // An xrpc call never reads a cookie, so it only gets flags on for everyone. A route that has checked a service // token can evaluate flags for that token's DID itself. A signed-out visitor gets an id of their own while a flag - // is on for a percentage, so they're in or out of it the same way on every request. + // that changes a public page is on for a percentage, so they're in or out of it the same way on every request. const { viewer } = event.locals; - const needsVisitorId = !viewer && !isXrpc && (await app.flags.hasPercentage()); + const needsVisitorId = !viewer && !isXrpc && (await app.flags.hasPublicPercentage()); const visitor = needsVisitorId ? flagVisitor(event.cookies, isHttps) : null; event.locals.flags = await app.flags.evaluate(viewer?.did ?? visitor?.id ?? null); @@ -176,6 +176,16 @@ export function serverHooks({ if (isUnlisted(event.route.id)) response.headers.set('x-robots-tag', 'noindex'); const cacheControl = response.headers.get('cache-control'); + // Paraglide varies every answer on Cookie, for the locale cookie. A public immutable one (an OG card, an avatar, a + // recording) is the same in every language, and varying it would have caches keep a copy per cookie, or none. + if (cacheControl?.includes('public') && cacheControl.includes('immutable')) { + const fields = (response.headers.get('vary') ?? '').split(',').map((field) => field.trim()); + const kept = fields.filter((field) => field && field.toLowerCase() !== 'cookie'); + + if (kept.length) response.headers.set('vary', kept.join(', ')); + else response.headers.delete('vary'); + } + // The answer now depends on this browser's own cookie, so a shared cache mustn't keep it for the next visitor, // or hand them the cookie it set. The browser's own cache still can. if (visitor && cacheControl?.includes('public')) { diff --git a/apps/web/src/lib/components/DmSettings.stories.svelte b/apps/web/src/lib/components/DmSettings.stories.svelte index 880eb926d..9874022b9 100644 --- a/apps/web/src/lib/components/DmSettings.stories.svelte +++ b/apps/web/src/lib/components/DmSettings.stories.svelte @@ -45,6 +45,9 @@ + + + diff --git a/apps/web/src/lib/components/DmSettings.svelte b/apps/web/src/lib/components/DmSettings.svelte index 2961f49f2..811ea61ff 100644 --- a/apps/web/src/lib/components/DmSettings.svelte +++ b/apps/web/src/lib/components/DmSettings.svelte @@ -18,17 +18,19 @@ /** * Someone's Bluesky DM setting for their inbox. DMs come from the root account (`root`, its handle), so whether they * can arrive depends on the person's chat settings, which `availability` reports once Bluesky chat answers. `available` - * is false when the site doesn't send DMs, or hasn't rolled them out to this person; DMs they turned on before that can - * still be turned off. + * is false when the site doesn't send DMs, or hasn't rolled them out to this person (`notYet` says it's the second); + * DMs they turned on before that can still be turned off. */ let { available, + notYet = false, channel, availability, root, form }: { available: boolean; + notYet?: boolean; channel: ChannelView | null; availability: Promise | null; root: string; @@ -38,7 +40,7 @@ const id = $props.id(); const status = $derived( - !available ? (channel ? 'Paused on this site for now.' : 'Not set up on this site.') : !channel ? `Get your inbox as DMs from @${root} too.` : channel.status === 'paused' ? 'Paused.' : `On, from @${root}.` + !available ? (channel ? 'Paused on this site for now.' : notYet ? 'Not on for your account yet.' : 'Not set up on this site.') : !channel ? `Get your inbox as DMs from @${root} too.` : channel.status === 'paused' ? 'Paused.' : `On, from @${root}.` ); @@ -78,7 +80,7 @@ {/if} {#if !available} - {#if channel}{/if} + {#if channel}
{/if} {:else if !channel}
{:else if channel.status === 'paused'} diff --git a/apps/web/src/lib/components/EmailSettings.stories.svelte b/apps/web/src/lib/components/EmailSettings.stories.svelte index 3526083aa..93a590172 100644 --- a/apps/web/src/lib/components/EmailSettings.stories.svelte +++ b/apps/web/src/lib/components/EmailSettings.stories.svelte @@ -38,6 +38,9 @@ + + + diff --git a/apps/web/src/lib/components/EmailSettings.svelte b/apps/web/src/lib/components/EmailSettings.svelte index 51a674d5b..d7e7bbd3b 100644 --- a/apps/web/src/lib/components/EmailSettings.svelte +++ b/apps/web/src/lib/components/EmailSettings.svelte @@ -16,17 +16,19 @@ /** * Someone's email setting for their inbox. `available` is false when the site can't send email, or hasn't rolled it - * out to them; email they turned on before that can still be turned off. `returned` says how asking their account's - * host for the address just went, when it didn't go through. Turning email on (or checking again) is a full page - * POST: it goes on to their account's host, which client-side navigation can't follow. + * out to them (`notYet` says it's the second); email they turned on before that can still be turned off. `returned` + * says how asking their account's host for the address just went, when it didn't go through. Turning email on (or + * checking again) is a full page POST: it goes on to their account's host, which client-side navigation can't follow. */ let { available, + notYet = false, channel, returned, form }: { available: boolean; + notYet?: boolean; channel: ChannelView | null; returned?: 'declined' | 'limited' | null; form?: { error?: string; success?: string } | null; @@ -42,7 +44,9 @@ !available ? channel ? 'Paused on this site for now.' - : 'Not set up on this site.' + : notYet + ? 'Not on for your account yet.' + : 'Not set up on this site.' : !channel ? 'Get your inbox by email too.' : channel.pausedReason === 'email_unverified' @@ -65,7 +69,7 @@ {#if returned === 'limited' && !form}

We can't send a confirmation link to that address right now. Try again tomorrow.

{/if} {#if !available} - {#if channel}
{/if} + {#if channel}
{/if} {:else if !channel} {#if returned === 'declined'}

You didn't allow sharing your email address, so email is still off.

{/if}
diff --git a/apps/web/src/lib/components/dm-settings.svelte.test.ts b/apps/web/src/lib/components/dm-settings.svelte.test.ts index fb686358e..34eae0769 100644 --- a/apps/web/src/lib/components/dm-settings.svelte.test.ts +++ b/apps/web/src/lib/components/dm-settings.svelte.test.ts @@ -72,4 +72,11 @@ describe('DmSettings', () => { await expect.element(page.getByText('Not set up on this site.')).toBeVisible(); expect(page.getByRole('button').elements()).toHaveLength(0); }); + + it("says when the site sends DMs but they aren't on for this account yet", async () => { + await render(DmSettings, { available: false, notYet: true, channel: null, availability: null, root }); + + await expect.element(page.getByText('Not on for your account yet.')).toBeVisible(); + expect(page.getByRole('button').elements()).toHaveLength(0); + }); }); diff --git a/apps/web/src/lib/components/email-settings.svelte.test.ts b/apps/web/src/lib/components/email-settings.svelte.test.ts index 76fa25250..6579d3876 100644 --- a/apps/web/src/lib/components/email-settings.svelte.test.ts +++ b/apps/web/src/lib/components/email-settings.svelte.test.ts @@ -65,4 +65,11 @@ describe('EmailSettings', () => { await expect.element(page.getByText('Not set up on this site.')).toBeVisible(); expect(page.getByRole('button').elements()).toHaveLength(0); }); + + it("says when the site sends email but it isn't on for this account yet", async () => { + await render(EmailSettings, { available: false, notYet: true, channel: null }); + + await expect.element(page.getByText('Not on for your account yet.')).toBeVisible(); + expect(page.getByRole('button').elements()).toHaveLength(0); + }); }); diff --git a/apps/web/src/lib/server/app.test.ts b/apps/web/src/lib/server/app.test.ts index 44e331307..3b6d16719 100644 --- a/apps/web/src/lib/server/app.test.ts +++ b/apps/web/src/lib/server/app.test.ts @@ -10,6 +10,7 @@ import { z } from 'zod'; import { COLLECTION, DIRECTORY, VERIFICATION } from '#lib/nsid.ts'; import { type App, createApp, getApp } from './app'; import { rootSpacePolicies } from './bootstrap'; +import { MANAGER_COLLECTIONS } from './happyview/refresh'; import { loadConfig } from './config'; import { nowIso } from './db'; import { type Logger, silentLogger } from './logger'; @@ -637,7 +638,7 @@ describe('start', () => { await vi.waitFor(() => expect(deletes()).toBe(1)); }); - it('skip every round while pauseReconcilers is on, saying so, and write nothing', async () => { + it('skip every round that writes while pauseReconcilers is on, saying so, and write nothing', async () => { const { logger, notes } = writtenLog('info'); const app = await start({ ...HOURLY, FLAG_OVERRIDES: 'pauseReconcilers=on' }, logger); app.start(); @@ -647,13 +648,17 @@ describe('start', () => { await vi.waitFor(() => expect(new Set(skipped().map((note) => note.round))).toEqual( - new Set(['manager-spaces', 'staff-spaces', 'shared-spaces', 'listings', 'venue-blocks', 'calendar-copies']) + new Set(['manager-spaces', 'staff-spaces', 'shared-spaces', 'listings', 'calendar-copies']) ) ); expect(deletes()).toBe(0); + // Only the venue-blocks round, which reads the root's blocks into the index and writes nothing there. expect( - net.seen.some((call) => call.host === 'pds.test' && call.path !== '/xrpc/com.atproto.server.createSession') - ).toBe(false); + net.seen + .filter((call) => call.host === 'pds.test' && call.path !== '/xrpc/com.atproto.server.createSession') + .map((call) => [call.path.split('.').at(-1), call.url.searchParams.get('collection')]) + ).toEqual([['listRecords', COLLECTION.venueBlock]]); + expect(notes().some((note) => note.message === 'reconciled venue blocks')).toBe(true); }); it('skip the rounds a bootstrap runs while pauseReconcilers is on', async () => { @@ -679,17 +684,10 @@ describe('start', () => { .map((note) => note.round) ) ).toEqual( - new Set([ - 'staff-spaces', - 'manager-spaces', - 'shared-spaces', - 'listings', - 'venue-blocks', - 'calendar-copies', - 'press-kit-spaces' - ]) + new Set(['staff-spaces', 'manager-spaces', 'shared-spaces', 'listings', 'calendar-copies', 'press-kit-spaces']) ); expect(deletes()).toBe(0); + expect(notes().some((note) => note.message === 'reconciled venue blocks')).toBe(true); }); }); @@ -765,6 +763,140 @@ describe('backups', () => { }); }); +describe('notification delivery', () => { + it.each([ + ['on', 'sent', 1], + ['off', 'skipped', 0] + ])("goes by the app's flags: with inboxEmail %s, a due email is %s", async (flag, status, sent) => { + vi.useFakeTimers({ toFake: ['Date'] }); + const emails: string[] = []; + + net.routes.set('POST /emails', async (request) => { + emails.push(z.object({ text: z.string() }).parse(await request.json()).text); + + return Response.json({ id: `email-${emails.length}` }); + }); + + const app = await start({ + ...NO_KEY, + EMAIL_PROVIDER: 'resend', + RESEND_API_KEY: 're_key', + FLAG_OVERRIDES: `inboxEmail=${flag}` + }); + + await app.notificationChannels.onSignIn({ + did: NEON, + scope: 'atproto account:email', + optIn: true, + session: async () => ({ email: 'neon@example.test', emailConfirmed: true }) + }); + const link = new URL(z.string().parse(emails[0].match(/https:\S+/)?.[0])); + expect(await app.notificationChannels.confirmEmail(link.searchParams.get('t') ?? '')).toBe('confirmed'); + + await app.notifications.notify({ + kind: 'booking.message', + to: [NEON], + key: 'first', + subject: `at://${ROOT}/space/computer.localnetwork.booking/3mabc`, + data: { skey: '3mabc', title: 'first', projectName: 'Neon Tide', from: 'promoter' }, + href: '/dashboard/bookings/3mabc', + at: new Date().toISOString() + }); + vi.setSystemTime(Date.now() + 2 * 60_000); + await app.outbox.processDue(); + + const deliveries = await app.db.selectFrom('notificationDelivery').select('status').execute(); + expect(deliveries.map((row) => row.status)).toEqual([status]); + expect(emails.length - 1).toBe(sent); + }); +}); + +describe('a reinstated account', () => { + /** What NEON's PDS answers getRepoStatus with. */ + let status: string; + /** The collections HappyView was asked to re-read NEON's records of. */ + let reread: string[]; + /** A collection whose re-read HappyView fails. */ + let failing: string | undefined; + + beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }); + status = 'takendown'; + reread = []; + failing = undefined; + + net.routes.set('GET /xrpc/com.atproto.sync.getRepoStatus', () => + Response.json(status === 'active' ? { active: true } : { active: false, status }) + ); + net.routes.set('POST /admin/backfill', async (request) => { + const body = z.object({ collection: z.string(), dids: z.array(z.string()) }).parse(await request.json()); + + if (body.dids.includes(NEON)) reread.push(body.collection); + + if (body.collection === failing) return new Response('down', { status: 500 }); + + return Response.json({ id: 'job', status: 'running' }, { status: 201 }); + }); + }); + + /** Sees NEON taken down, then has the status asked again once it's stale and finds NEON active. */ + const reinstate = async (app: App) => { + expect(await app.accountStatuses.status(NEON)).toBe('takendown'); + status = 'active'; + vi.setSystemTime(Date.now() + 31 * 60_000); + await app.accountStatuses.status(NEON); + }; + + const sorted = (collections: readonly string[]) => collections.toSorted((a, b) => a.localeCompare(b)); + + const warnings = (notes: () => { message: string }[]) => + notes().filter((note) => note.message === "a reinstated account's records may not all be back"); + + it("has HappyView re-read the account's records of every manager collection", async () => { + const { logger, notes } = capture(); + const app = await start({}, logger); + + await reinstate(app); + await vi.waitFor(() => expect(sorted(reread)).toEqual(sorted(MANAGER_COLLECTIONS))); + + // Joining the re-reads under way waits for them, and a turn of the event loop lets the reinstatement finish. + const done = await Promise.all(MANAGER_COLLECTIONS.map((collection) => app.backfills.backfill(collection, [NEON]))); + expect(done.every(Boolean)).toBe(true); + await new Promise((resolve) => setImmediate(resolve)); + expect(warnings(notes)).toEqual([]); + }); + + it.each<[string, Record, (app: App) => Promise, readonly string[]]>([ + [ + "HappyView can't re-read one collection", + {}, + async () => { + failing = COLLECTION.djSet; + }, + [COLLECTION.djSet] + ], + ['pauseBackfills is on', { FLAG_OVERRIDES: 'pauseBackfills=on' }, async () => undefined, MANAGER_COLLECTIONS], + [ + "the flags can't be read", + {}, + async (app) => { + await app.db.schema.dropTable('flagGroup').execute(); + // Forgets the flags read so far, so the next check reads them again. + await app.flags.removeFlagByUri(`at://${ROOT}/space/gone`); + }, + MANAGER_COLLECTIONS + ] + ])('logs the collections that may not be back when %s', async (_when, env, setup, unread) => { + const { logger, notes } = capture(); + const app = await start(env, logger); + await setup(app); + + await reinstate(app); + await vi.waitFor(() => expect(warnings(notes)).toHaveLength(1)); + expect(warnings(notes)[0]).toMatchObject({ did: NEON, collections: [...unread] }); + }); +}); + describe('getApp', () => { it('starts one app for the process, and tries again after a failed start', async () => { for (const [name, value] of Object.entries({ ...ENV, ...NO_KEY })) vi.stubEnv(name, value); diff --git a/apps/web/src/lib/server/app.ts b/apps/web/src/lib/server/app.ts index 5f1ae889f..668407ad8 100644 --- a/apps/web/src/lib/server/app.ts +++ b/apps/web/src/lib/server/app.ts @@ -186,15 +186,26 @@ export async function createApp(options: CreateAppOptions) { notify: (space) => syncer.registration(space) }); + /** + * Has HappyView re-read a reinstated account's records, which it dropped at the takedown. Nothing tries again later, + * so a re-read that's paused, failed or still going after its wait is logged for staff to run by hand. + */ + const rereadReinstated = async (did: string) => { + const done = await Promise.all( + MANAGER_COLLECTIONS.map((collection) => backfills.backfill(collection, [did]).catch(() => false)) + ); + + const unread = MANAGER_COLLECTIONS.filter((_, index) => !done[index]); + + if (unread.length) logger.warn("a reinstated account's records may not all be back", { did, collections: unread }); + }; + // Services built after `core` list the directory's accounts, and only from their methods. const accountStatuses = new AccountStatuses({ lookup: repoStatusLookup(identity), accounts: async () => [...(await projects.managers()), ...(await djListings.listed())], logger: logger.child({ component: 'account-status' }), - // HappyView drops a taken-down account's records, so a reinstated one's are read again. - reinstated: (did) => { - for (const collection of MANAGER_COLLECTIONS) void backfills.backfill(collection, [did]); - } + reinstated: (did) => void rereadReinstated(did) }); const core: Core = { @@ -262,11 +273,11 @@ export async function createApp(options: CreateAppOptions) { logger.warn('flags forced by FLAG_OVERRIDES', { flags: config.flagOverrides }); const backfills = new Backfills(happyView, logger.child({ component: 'backfills' }), flags); const plyr = new PlyrClient(logger.child({ component: 'plyr' })); - const projects = new ProjectService(core, happyView, INDEX_WAIT_MS, backfills, plyr); + const projects = new ProjectService(core, happyView, INDEX_WAIT_MS, backfills, plyr, flags); const planner = new PlannerService(core); const projectAdmin = new ProjectAdmin(core, projects); const tracklists = new TracklistService(core); - const indexedRepo = new IndexedRepo(happyView, logger.child({ component: 'indexed-repo' })); + const indexedRepo = new IndexedRepo(happyView, logger.child({ component: 'indexed-repo' }), INDEX_WAIT_MS, flags); const dj = new DjService(indexedRepo, logger.child({ component: 'dj' })); const profiles = new ProfileService(core, indexedRepo); const djListings = new DjListings(core, indexedRepo); @@ -287,8 +298,8 @@ export async function createApp(options: CreateAppOptions) { const epks = new EpkService(core, projects, indexedRepo, (identifier) => identity.resolveIdentifier(identifier)); const epkViews = new EpkViews(core, epks, config.epkViewRetentionDays); - const shows = new ShowService(core, projects, happyView, indexedRepo); - const follows = new FollowService(core, happyView); + const shows = new ShowService(core, projects, happyView, indexedRepo, INDEX_WAIT_MS, flags); + const follows = new FollowService(core, happyView, INDEX_WAIT_MS, flags); const verifications = new VerificationService(core, indexedRepo, projects, identity); const listings = new ListingWriter(core, flags, { @@ -330,7 +341,7 @@ export async function createApp(options: CreateAppOptions) { config.publicUrl ); - const rsvps = new RsvpService(core, happyView, config.publicUrl); + const rsvps = new RsvpService(core, happyView, config.publicUrl, INDEX_WAIT_MS, flags); const requests = new RequestService(core, projects, profiles, djListings, venues, sharedSpaces); const heldRecords = new HeldRecords(core, requests, projects, limits.write); @@ -424,7 +435,7 @@ export async function createApp(options: CreateAppOptions) { }; /** Runs one of the rounds that fix drift in the root's repo, unless pauseReconcilers is on. */ - const reconcile = async (round: string, work: () => Promise) => { + const reconcile = async (round: string, work: () => Promise) => { if (!(await paused('pauseReconcilers', round))) await work(); }; @@ -584,7 +595,9 @@ export async function createApp(options: CreateAppOptions) { await syncer.syncAll(); // After the sync, so the index has every space's people, and the requests and grants left in press kit spaces. await reconcile('listings', () => listings.reconcile()); - await reconcile('venue-blocks', () => venues.reconcileBlocks()); + // Not paused by pauseReconcilers: it only reads the root's blocks into the index, and an index left empty + // after a restore would show blocked promoters as confirmed (ADR 0014). + await venues.reconcileBlocks(); // After the blocks, which decide which events are listed. await reconcile('calendar-copies', () => events.reconcileCalendarCopies()); await reconcile('press-kit-spaces', () => moveKitSpaces(core, epks)); @@ -624,11 +637,12 @@ export async function createApp(options: CreateAppOptions) { // Rewrites listings that drifted from their spaces: one listRecords of the root's listings, and writes only // where one differs. every(60 * 60_000, () => reconcile('listings', () => listings.reconcile()), 'listings'); - // Indexes the root's venue blocks and drops ones that are gone: one listRecords of the root's own repo. - every(60 * 60_000, () => reconcile('venue-blocks', () => venues.reconcileBlocks()), 'venue-blocks'); // Takes down the calendar copies of events whose night ended while they waited for the venue, and fixes any that // drifted: one listRecords of the root's own repo, and writes only where a copy differs. every(60 * 60_000, () => reconcile('calendar-copies', () => events.reconcileCalendarCopies()), 'calendar-copies'); + // Indexes the root's venue blocks and drops ones that are gone: one listRecords of the root's own repo. It writes + // nothing there, so pauseReconcilers leaves it running. + every(60 * 60_000, () => venues.reconcileBlocks(), 'venue-blocks'); every(60 * 60_000, () => epkViews.expire(), 'epk-view-expiry'); every(60 * 60_000, () => Promise.all([notifications.prune(), outbox.prune()]), 'inbox-retention'); every(15_000, () => outbox.processDue(), 'notification-delivery'); diff --git a/apps/web/src/lib/server/atproto/account-status.test.ts b/apps/web/src/lib/server/atproto/account-status.test.ts index 20d29e73c..7852e2f7e 100644 --- a/apps/web/src/lib/server/atproto/account-status.test.ts +++ b/apps/web/src/lib/server/atproto/account-status.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'; import { silentLogger } from '../logger'; import { type AccountStatus, AccountStatuses, repoStatusLookup } from './account-status'; import type { ResolvedIdentity } from './identity'; +import { writtenLog } from '../testing/written-log'; const MARA = 'did:plc:mara'; @@ -9,6 +10,8 @@ const OSKAR = 'did:plc:oskar'; const PDS = 'https://pds.test'; +const NEW_PDS = 'https://new-pds.test'; + const HALF_HOUR = 30 * 60_000; describe('repoStatusLookup', () => { @@ -41,6 +44,23 @@ describe('repoStatusLookup', () => { expect(await repoStatusLookup(pdsAnswering(MARA, answer))(MARA)).toBe('active'); }); + it.each([ + ['RepoNotFound', Response.json({ error: 'RepoNotFound', message: 'Could not find repo' }, { status: 400 })], + ['deactivated', Response.json({ did: MARA, active: false, status: 'deactivated' })] + ])( + 'should ask the PDS an account moved to when the one its cached DID document names answers %s', + async (_, answer) => { + // Arrange + const lookup = repoStatusLookup(movedAccount(MARA, answer)); + + // Act + const status = await lookup(MARA); + + // Assert + expect(status).toBe('active'); + } + ); + it("should throw when the PDS can't say", async () => { const lookup = repoStatusLookup(pdsAnswering(MARA, new Response('down', { status: 502 }))); @@ -95,7 +115,7 @@ describe('AccountStatuses', () => { expect(await statuses.status(MARA)).toBe('deactivated'); }); - it('should keep a deleted account deleted', async () => { + it('should ask about a deleted account again once its answer is old, as an account that just moved can look deleted', async () => { const pds = new Map([[MARA, 'deleted']]); const { statuses, clock } = tracked(pds); await statuses.status(MARA); @@ -104,7 +124,7 @@ describe('AccountStatuses', () => { await statuses.refresh(); - expect(await statuses.status(MARA)).toBe('deleted'); + expect(await statuses.status(MARA)).toBe('active'); }); it.each(['takendown', 'suspended'] as const)('should say when a %s account is active again', async (inactive) => { @@ -156,6 +176,35 @@ describe('AccountStatuses', () => { expect({ before, after: statuses.inactive() }).toEqual({ before: [MARA], after: [] }); }); + it("should leave deleted accounts out of the directory's inactive list, since HappyView dropped their records", async () => { + const pds = new Map([ + [MARA, 'deleted'], + [OSKAR, 'deactivated'] + ]); + + const { statuses } = tracked(pds); + + await statuses.refresh(); + + expect(statuses.inactive()).toEqual([OSKAR]); + }); + + it('should send the directory queries at most 100 inactive accounts, saying how many there were', async () => { + const pds = new Map( + Array.from({ length: 101 }, (_, index) => [`did:plc:inactive${index}`, 'deactivated'] as const) + ); + + const { logger, notes } = writtenLog('warn'); + const { statuses } = tracked(pds, { logger }); + + await statuses.refresh(); + + expect(statuses.inactive()).toHaveLength(100); + expect(notes()).toContainEqual( + expect.objectContaining({ message: 'more inactive accounts than the directory queries take', inactive: 101 }) + ); + }); + it("should keep the last list when the directory can't list its accounts", async () => { const pds = new Map([[MARA, 'deactivated']]); let down = false; @@ -199,6 +248,29 @@ function pdsAnswering(did: string, answer: Response) { }; } +/** + * An account that moved from PDS to NEW_PDS, which has it active, while the resolver's cached DID document still names + * PDS, which answers `before`. Only a forced refresh reads the current document. + */ +function movedAccount(did: string, before: Response) { + return { + resolve: async (asked: string, forceRefresh = false): Promise => ({ + did: asked, + handle: null, + pds: forceRefresh ? NEW_PDS : PDS, + signingKey: 'did:key:z', + kemKey: null + }), + serviceApiFetch: async (input: string | URL | Request) => { + const url = new URL(input instanceof Request ? input.url : input); + + if (url.searchParams.get('did') !== did) return new Response('not found', { status: 404 }); + + return url.origin === PDS ? before : Response.json({ did, active: true }); + } + }; +} + /** * AccountStatuses over `pds` (an account it lacks can't be asked), with the directory's accounts being the ones in it * unless `options` says otherwise, and a clock that only moves when a test moves it. diff --git a/apps/web/src/lib/server/atproto/account-status.ts b/apps/web/src/lib/server/atproto/account-status.ts index 2fcc6db0b..fba75d469 100644 --- a/apps/web/src/lib/server/atproto/account-status.ts +++ b/apps/web/src/lib/server/atproto/account-status.ts @@ -39,11 +39,13 @@ const INACTIVE_PARAM_MAX = 100; /** * `com.atproto.sync.getRepoStatus` from the PDS the account's DID document names, through the guarded fetch. A PDS - * answers `RepoNotFound` for an account it deleted. + * answers `RepoNotFound` for an account it deleted. The resolver caches DID documents, and the PDS an account just + * moved away from answers `RepoNotFound` or deactivated, so an inactive answer is checked against a fresh document and, + * when that names another PDS, asked of that one. */ export function repoStatusLookup(identity: Pick): StatusLookup { - return async (did) => { - const url = new URL('/xrpc/com.atproto.sync.getRepoStatus', (await identity.resolve(did)).pds); + const statusAt = async (pds: string, did: string): Promise => { + const url = new URL('/xrpc/com.atproto.sync.getRepoStatus', pds); url.searchParams.set('did', did); const response = await identity.serviceApiFetch(url, { @@ -62,6 +64,16 @@ export function repoStatusLookup(identity: Pick { + const { pds } = await identity.resolve(did); + const status = await statusAt(pds, did); + + if (status === 'active') return status; + const current = (await identity.resolve(did, true)).pds; + + return current === pds ? status : statusAt(current, did); + }; } type AccountStatusOptions = { @@ -79,7 +91,8 @@ type AccountStatusOptions = { * Which accounts are inactive, asked of their PDS when a page needs to know and kept for half an hour (ADR 0020). * HappyView keeps a deactivated account's records, so the directory queries are told which accounts to leave out, and * the account's own pages say it isn't active. A PDS that can't be asked leaves the account as it was last seen, or - * active when it never was: the site fails open. A deleted account stays deleted, since deletion can't be undone. + * active when it never was: the site fails open. A deleted account is asked again like any other, since one whose + * PDS changed can look deleted for a moment, and HappyView's tombstone keeps a really deleted one's records out anyway. */ export class AccountStatuses { private readonly known = new Map(); @@ -91,7 +104,7 @@ export class AccountStatuses { constructor(private readonly options: AccountStatusOptions) { this.freshMs = options.freshMs ?? FRESH_MS; - this.now = options.now ?? Date.now; + this.now = options.now ?? (() => Date.now()); } /** @@ -109,7 +122,8 @@ export class AccountStatuses { } /** - * The directory's accounts last found inactive, for the queries to leave out: none until the first check is done. + * The directory's accounts last found deactivated, taken down or suspended, for the queries to leave out: none until + * the first check is done. * When the answer is older than half an hour, refresh() starts in the background, so no page waits on a PDS. */ inactive(): string[] { @@ -159,7 +173,8 @@ export class AccountStatuses { ) ); - let dids = accounts.filter((_, index) => statuses[index] !== 'active'); + // HappyView already dropped a deleted account's records, so it isn't sent to take one of the param's places. + let dids = accounts.filter((_, index) => statuses[index] !== 'active' && statuses[index] !== 'deleted'); if (dids.length > INACTIVE_PARAM_MAX) { this.options.logger.warn('more inactive accounts than the directory queries take', { inactive: dids.length }); @@ -188,15 +203,11 @@ export class AccountStatuses { const before = this.known.get(did)?.status; let status: AccountStatus; - if (before === 'deleted') { - status = before; - } else { - try { - status = await this.options.lookup(did); - } catch (error) { - status = before ?? 'active'; - this.options.logger.warn("could not check an account's status", { err: error, did, assumed: status }); - } + try { + status = await this.options.lookup(did); + } catch (error) { + status = before ?? 'active'; + this.options.logger.warn("could not check an account's status", { err: error, did, assumed: status }); } this.known.delete(did); diff --git a/apps/web/src/lib/server/audit/log.test.ts b/apps/web/src/lib/server/audit/log.test.ts index 903d41341..e13f6345a 100644 --- a/apps/web/src/lib/server/audit/log.test.ts +++ b/apps/web/src/lib/server/audit/log.test.ts @@ -202,6 +202,15 @@ describe('AuditLog', () => { expect(await log.verifyChain()).toEqual({ ok: true, checked: 1 }); }); + it('filters by an action, or by its group without taking in a group that starts the same', async () => { + await log.record({ actor: ALICE, action: 'flag.update', summary: 'on' }); + await log.record({ actor: ALICE, action: 'flagGroup.create', summary: 'group' }); + + expect((await log.list({ action: 'flag' })).map((entry) => entry.action)).toEqual(['flag.update']); + expect((await log.list({ action: 'flag.update' })).map((entry) => entry.action)).toEqual(['flag.update']); + expect((await log.list({ action: 'flagGroup' })).map((entry) => entry.action)).toEqual(['flagGroup.create']); + }); + it('reports orphan copies that have no root entry', async () => { await log.onSyncedCopy({ uri: 'at://x', repoDid: BOB, rkey: 'zzz', cid: 'c', value: { actor: BOB } }); expect((await log.orphans()).map((o) => o.repoDid)).toEqual([BOB]); diff --git a/apps/web/src/lib/server/audit/log.ts b/apps/web/src/lib/server/audit/log.ts index 10cbb0257..ae6ffc41a 100644 --- a/apps/web/src/lib/server/audit/log.ts +++ b/apps/web/src/lib/server/audit/log.ts @@ -445,7 +445,11 @@ export class AuditLog { if (filter.actor) query = query.where('actorDid', '=', filter.actor); - if (filter.action) query = query.where('action', 'like', `${filter.action.replace(/[%_]/g, '')}%`); + if (filter.action) { + // An action or its group: `flag` is flag.update but not flagGroup.update. + const action = filter.action.replace(/[%_]/g, ''); + query = query.where((eb) => eb.or([eb('action', '=', action), eb('action', 'like', `${action}.%`)])); + } if (filter.subject) query = query.where('subject', '=', filter.subject); diff --git a/apps/web/src/lib/server/db/schema.ts b/apps/web/src/lib/server/db/schema.ts index a6a16fffc..6cc4cab3b 100644 --- a/apps/web/src/lib/server/db/schema.ts +++ b/apps/web/src/lib/server/db/schema.ts @@ -55,7 +55,7 @@ export interface Database { /** * Where each table's rows come from. `rebuilt` ones come back from records on the network: the space sync, or for venue * blocks, the root's repo at startup. `server-only` ones live only here, so a restore needs them from a backup. A new - * table has to pick one to type-check. + * table has to pick one to type-check, and db.test.ts holds the migrated database to it. @internal */ export const TABLE_SOURCE = { /** The root's session, when the app first started, HappyView script uploads and listing digests. */ @@ -106,7 +106,9 @@ export const TABLE_SOURCE = { notificationDelivery: 'server-only' } as const satisfies Record; -/** The columns of rebuilt tables that only the server knows, which a re-sync loses or works out differently. */ +/** + * The columns of rebuilt tables that only the server knows, which a re-sync loses or works out differently. @internal + */ export const SERVER_ONLY_COLUMNS = { /** * A request whose record is gone keeps its row only here: marked deleted after it was decided, or withdrawn. The @@ -365,7 +367,10 @@ export interface EpkRequestTable { status: 'pending' | 'approved' | 'declined' | 'withdrawn'; createdAt: string; decidedAt: string | null; - /** When its asker deleted the root's record of it, after it was answered. The row stays, without its message. */ + /** + * Set while the request's record isn't there to read: its decision synced first (cleared once the request syncs), + * or its asker deleted the root's copy after it was answered (the row stays, without its message). + */ deletedAt: string | null; } diff --git a/apps/web/src/lib/server/happyview/backfills.ts b/apps/web/src/lib/server/happyview/backfills.ts index 6ac54c4cc..840becd45 100644 --- a/apps/web/src/lib/server/happyview/backfills.ts +++ b/apps/web/src/lib/server/happyview/backfills.ts @@ -8,6 +8,26 @@ const WAIT_MS = 5_000; /** How often one account's records of one collection are re-read at most. Jetstream keeps them current in between. */ const EVERY_MS = 10 * 60_000; +/** The app's flags, for pauseBackfills. A caller without them never pauses its re-reads. */ +export type BackfillFlags = Pick | undefined; + +/** + * Whether the pauseBackfills flag, on for everyone, stops a re-read of `collection` for `dids` now. It notes the skip, + * so staff can see the switch working. + */ +export async function backfillsPaused( + flags: BackfillFlags, + logger: Logger, + collection: string, + dids: string[] +): Promise { + const paused = !!(await flags?.evaluate(null))?.pauseBackfills; + + if (paused) logger.info('HappyView re-reads paused', { collection, accounts: dids.length, flag: 'pauseBackfills' }); + + return paused; +} + /** * Has HappyView re-read accounts' records of a collection from their PDS, for records Jetstream never brought (ones * written before HappyView kept that collection, or while it was down). Only with an API key, and at most every ten @@ -21,8 +41,7 @@ export class Backfills { constructor( private readonly directory: HappyViewClient, private readonly logger: Logger, - /** The app's, for pauseBackfills. Without it, re-reads are never paused. */ - private readonly flags?: Pick + private readonly flags?: BackfillFlags ) {} /** @@ -32,11 +51,7 @@ export class Backfills { async backfill(collection: string, dids: string[]): Promise { if (!this.directory.admin) return false; - if ((await this.flags?.evaluate(null))?.pauseBackfills) { - this.logger.info('HappyView re-reads paused', { collection, accounts: dids.length, flag: 'pauseBackfills' }); - - return false; - } + if (await backfillsPaused(this.flags, this.logger, collection, dids)) return false; const reads: Promise[] = []; const due: string[] = []; diff --git a/apps/web/src/lib/server/happyview/indexed.test.ts b/apps/web/src/lib/server/happyview/indexed.test.ts index a2900b8e6..65d9c3e6d 100644 --- a/apps/web/src/lib/server/happyview/indexed.test.ts +++ b/apps/web/src/lib/server/happyview/indexed.test.ts @@ -3,10 +3,12 @@ import { jsonToLex } from '@atproto/lex-json'; import { describe, expect, it } from 'vitest'; import { z } from 'zod'; import { COLLECTION, DIRECTORY } from '#lib/nsid.ts'; +import { flagsOff } from '#lib/testing/flags.ts'; import { silentLogger } from '../logger'; +import { writtenLog } from '../testing/written-log'; import { FakeHappyView } from '../testing/happyview'; import { HappyViewClient } from './client'; -import { IndexedRepo } from './indexed'; +import { IndexedRepo, reindex } from './indexed'; const DJ = 'did:plc:dj'; @@ -95,4 +97,31 @@ describe('IndexedRepo', () => { `backfill ${COLLECTION.djSet} ${DJ}` ]); }); + + it("starts no re-read for a write while pauseBackfills is on, saying so, and does once it's off", async () => { + const hv = new FakeHappyView('did:plc:root'); + const { client, calls } = admin(hv); + let paused = true; + const flags = { evaluate: async () => ({ ...flagsOff, pauseBackfills: paused }) }; + const { logger, notes } = writtenLog('info'); + const repo = new IndexedRepo(client, logger, 0, flags); + const backfills = () => calls.filter((call) => call.startsWith('backfill')); + + await repo.awaitWrite(DJ, COLLECTION.djSet, '3set', 'bafynewer'); + await repo.getRecordOrReindex(DJ, COLLECTION.djSet, 'missing'); + await reindex(client, logger, flags, COLLECTION.follow, [DJ]); + + expect(backfills()).toEqual([]); + expect( + notes() + .filter((note) => note.flag === 'pauseBackfills') + .map((note) => note.collection) + ).toEqual([COLLECTION.djSet, COLLECTION.djSet, COLLECTION.follow]); + + paused = false; + await repo.awaitWrite(DJ, COLLECTION.djSet, '3set', 'bafynewer'); + await reindex(client, logger, flags, COLLECTION.follow, [DJ]); + + expect(backfills()).toEqual([`backfill ${COLLECTION.djSet} ${DJ}`, `backfill ${COLLECTION.follow} ${DJ}`]); + }); }); diff --git a/apps/web/src/lib/server/happyview/indexed.ts b/apps/web/src/lib/server/happyview/indexed.ts index a06c18ecc..3e90b6eb0 100644 --- a/apps/web/src/lib/server/happyview/indexed.ts +++ b/apps/web/src/lib/server/happyview/indexed.ts @@ -1,5 +1,6 @@ import { setTimeout as sleep } from 'node:timers/promises'; import type { Logger } from '../logger'; +import { type BackfillFlags, backfillsPaused } from './backfills'; import type { DirectoryRecord, HappyViewClient } from './client'; import { unlessOffline } from './offline'; @@ -35,17 +36,19 @@ export async function awaitIndexed(served: () => Promise, waitMs: numbe /** * Has HappyView re-read the accounts' records of `collection` from their PDS, in one job per 500 accounts, for a write - * it didn't serve in time, in case Jetstream never brought it. Only with an API key. It waits up to `waitMs` for the - * jobs to finish, which then run on in HappyView; a failure is only logged. + * it didn't serve in time, in case Jetstream never brought it. Only with an API key, and not while `flags` has + * pauseBackfills on. It waits up to `waitMs` for the jobs to finish, which then run on in HappyView; a failure is only + * logged. */ export async function reindex( directory: HappyViewClient, logger: Logger, + flags: BackfillFlags, collection: string, dids: string[], waitMs = 0 ) { - if (!directory.admin) return; + if (!directory.admin || (await backfillsPaused(flags, logger, collection, dids))) return; try { const jobs = await directory.backfill(collection, dids); @@ -66,7 +69,8 @@ export class IndexedRepo { constructor( private readonly directory: HappyViewClient, private readonly logger: Logger, - private readonly indexWaitMs = INDEX_WAIT_MS + private readonly indexWaitMs = INDEX_WAIT_MS, + private readonly flags?: BackfillFlags ) {} async getRecord( @@ -162,7 +166,7 @@ export class IndexedRepo { /** Has HappyView re-read one account's records of `collection` from its PDS, waiting up to `waitMs` (see reindex). */ reindex(did: string, collection: string, waitMs = 0): Promise { - return reindex(this.directory, this.logger, collection, [did], waitMs); + return reindex(this.directory, this.logger, this.flags, collection, [did], waitMs); } private read({ strict }: ReadOptions, query: () => Promise): Promise { diff --git a/apps/web/src/lib/server/media/audio.test.ts b/apps/web/src/lib/server/media/audio.test.ts index 379bd2e36..d105ed12b 100644 --- a/apps/web/src/lib/server/media/audio.test.ts +++ b/apps/web/src/lib/server/media/audio.test.ts @@ -2,6 +2,7 @@ import { createServer } from 'node:http'; import type { AddressInfo } from 'node:net'; import * as fc from 'fast-check'; import { describe, expect, it, onTestFinished, vi } from 'vitest'; +import { flagsOff } from '#lib/testing/flags.ts'; import { IdentityResolver } from '../atproto/identity'; import { silentLogger } from '../logger'; import { rebindToLoopback } from '../testing/rebind'; @@ -92,6 +93,7 @@ function ask(range: string | null, overrides: Overrides = {}) { audio: async (did, cid) => (did === DJ && cid === CID ? declared : null), identity: identityOf(endpoint, fetch, allowPrivateNetwork), log: silentLogger, + flags: flagsOff, ...request }); } diff --git a/apps/web/src/lib/server/media/audio.ts b/apps/web/src/lib/server/media/audio.ts index b58b1b1e9..01f6cb4ae 100644 --- a/apps/web/src/lib/server/media/audio.ts +++ b/apps/web/src/lib/server/media/audio.ts @@ -87,8 +87,8 @@ export type AudioRequest = { */ identity: Pick; log: Logger; - /** The request's flags, where pauseRecordingStream stops the streaming. Nothing is paused without them. */ - flags?: Partial; + /** The request's flags, where pauseRecordingStream stops the streaming. */ + flags: Flags; }; /** @@ -102,7 +102,7 @@ export async function recordingAudio(request: AudioRequest): Promise { const { log } = request; log.set({ recording: { did, cid, range: request.range } }); - if (request.flags?.pauseRecordingStream) { + if (request.flags.pauseRecordingStream) { log.info('recording stream paused', { flag: 'pauseRecordingStream' }); // Not kept, so the recording plays again as soon as the flag goes off. diff --git a/apps/web/src/lib/server/meta.test.ts b/apps/web/src/lib/server/meta.test.ts index dcae4c7be..eeb44ebe3 100644 --- a/apps/web/src/lib/server/meta.test.ts +++ b/apps/web/src/lib/server/meta.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest'; +import { flagsOff } from '#lib/testing/flags.ts'; import type { ProjectView } from '#lib/types.ts'; import { artistMeta, listed, mixMeta, pageMeta, performerMeta, pressKitMeta, pressKitsMeta, profileMeta } from './meta'; @@ -216,7 +217,7 @@ describe('listed', () => { const thing = () => ({ '@type': 'Thing', name: 'x' }); it("sets a listed page's at-tags and structured data aside for the head, and leaves its metadata as it was", async () => { - const locals: Pick = {}; + const locals: Pick = { flags: flagsOff }; const meta = performerMeta(SITE, project); expect(await listed(locals, meta, { records: () => records, jsonLd: thing })).toBe(meta); @@ -226,13 +227,13 @@ describe('listed', () => { ); // A page with nothing to say gets nothing. - const plain: Pick = {}; + const plain: Pick = { flags: flagsOff }; await listed(plain, meta, { jsonLd: null }); expect(plain.crawlerHead ?? '').toBe(''); }); it('leaves a page kept out of search as it was, without even looking its records up', async () => { - const locals: Pick = {}; + const locals: Pick = { flags: flagsOff }; const hidden = performerMeta(SITE, { ...project, status: 'hidden' }); const lookUp = () => { @@ -244,7 +245,7 @@ describe('listed', () => { }); it("shows the site's card in place of a drawn one while pauseOgCards is on, and keeps a page's own picture", async () => { - const paused = { pauseOgCards: true }; + const paused = { ...flagsOff, pauseOgCards: true }; const avatar = profileMeta( SITE, @@ -258,8 +259,6 @@ describe('listed', () => { SITE_CARD ); expect(await listed({ flags: paused }, avatar, {})).toEqual(avatar); - expect((await listed({ flags: { pauseOgCards: false } }, performerMeta(SITE, project), {})).image?.url).toMatch( - /\/og\/project\// - ); + expect((await listed({ flags: flagsOff }, performerMeta(SITE, project), {})).image?.url).toMatch(/\/og\/project\//); }); }); diff --git a/apps/web/src/lib/server/meta.ts b/apps/web/src/lib/server/meta.ts index f1a35753a..ea0b644c6 100644 --- a/apps/web/src/lib/server/meta.ts +++ b/apps/web/src/lib/server/meta.ts @@ -4,7 +4,7 @@ import { formatShowDate, kindLabel, placeLabel, pluralize, profileHref, setHref import { type PageImage, type PageMeta, SITE_NAME } from '#lib/meta.ts'; import { CARD } from '#lib/og/style.ts'; import { bareMbid } from '#lib/supports.ts'; -import type { AccountView, Flags, ProfileRecord, ProfileView, ProjectView } from '#lib/types.ts'; +import type { AccountView, ProfileRecord, ProfileView, ProjectView } from '#lib/types.ts'; import { type PageRecords, recordTags } from './meta-records'; import { isDrawable } from './og/drawable'; import { cardPaths } from './og/paths'; @@ -231,15 +231,15 @@ export const mixMeta = ( * `meta`, with what only a page search engines may list carries set aside for the server hook to write into its head: * the records behind it as at-tags, and its structured data (see crawler-head.ts). A page kept out of search gets * neither, and its records aren't even looked up. While pauseOgCards is on, a card drawn for the page gives way to the - * site's, since the card routes don't draw then; nothing is paused without `locals.flags`. + * site's, since the card routes don't draw then. */ export async function listed( - locals: Pick & { flags?: Partial }, + locals: Pick, meta: PageMeta, { records, jsonLd }: { records?: () => PageRecords | Promise; jsonLd?: JsonLdBuilder | null } ): Promise { const shown = - locals.flags?.pauseOgCards && isDrawnCard(meta.image) ? { ...meta, image: absolute(SITE_CARD, meta.url) } : meta; + locals.flags.pauseOgCards && isDrawnCard(meta.image) ? { ...meta, image: absolute(SITE_CARD, meta.url) } : meta; if (shown.noindex) return shown; const head = [records && recordTags(await records()), jsonLd && jsonLdScript(jsonLdFor(shown, jsonLd))]; diff --git a/apps/web/src/lib/server/profile-page.test.ts b/apps/web/src/lib/server/profile-page.test.ts index 7ebb27d45..236ec6567 100644 --- a/apps/web/src/lib/server/profile-page.test.ts +++ b/apps/web/src/lib/server/profile-page.test.ts @@ -107,7 +107,7 @@ describe('loadProfilePage', () => { } catch (cause) { if (isRedirect(cause)) return { redirect: cause.location, status: cause.status }; - if (isHttpError(cause)) return { status: cause.status }; + if (isHttpError(cause)) return { status: cause.status, ...(cause.body.title && { title: cause.body.title }) }; throw cause; } }; @@ -143,6 +143,15 @@ describe('loadProfilePage', () => { expect(await open('cy.test')).toEqual({ status: 404 }); }); + it("names an account that isn't active by its handle, and one without a verified handle as this account", async () => { + t.accountStatus.set(ADA, 'deactivated'); + t.accountStatus.set(CY, 'deleted'); + await t.accountStatuses.refresh(); + + expect(await open('ada.test')).toEqual({ status: 404, title: "@ada.test isn't active" }); + expect(await open(CY)).toEqual({ status: 410, title: 'This account was deleted' }); + }); + it('gives an account without a profile a page with its Bluesky name, or else its handle', async () => { const profile = { name: 'Bea Crew', kind: 'duo', genres: ['house'], location: { city: 'Leipzig', country: 'DE' } }; await t.projects.publish({ profile, managers: [BEA], status: 'active', createdBy: ROOT }); diff --git a/apps/web/src/lib/server/profile-page.ts b/apps/web/src/lib/server/profile-page.ts index 8ea412ea5..d4fcf8ae1 100644 --- a/apps/web/src/lib/server/profile-page.ts +++ b/apps/web/src/lib/server/profile-page.ts @@ -64,15 +64,16 @@ export async function pageAccount(locals: App.Locals, param: string, rest: strin misses.refund(ip); const status = await locals.app.core.accountStatuses.status(account.did); + const who = account.handle ? `@${account.handle}` : 'This account'; if (status === 'deleted') { - error(410, { status: 410, title: 'This account was deleted', message: 'Their profile and sets are gone.' }); + error(410, { status: 410, title: `${who} was deleted`, message: 'Their profile and sets are gone.' }); } if (status !== 'active') { error(404, { status: 404, - title: "This account isn't active", + title: `${who} isn't active`, message: 'Their profile and sets come back when the account does.' }); } diff --git a/apps/web/src/lib/server/services/bug-reports.ts b/apps/web/src/lib/server/services/bug-reports.ts index 5698d4e95..b01674450 100644 --- a/apps/web/src/lib/server/services/bug-reports.ts +++ b/apps/web/src/lib/server/services/bug-reports.ts @@ -81,3 +81,10 @@ export class BugReportService { return discussionUrl(uri); } } + +/** + * Whether a signed-in viewer's report goes to userinput.app: the site has a space to post to, and it's rolled out to + * them. Off, it goes to GitHub, which is also how staff send everyone there while userinput.app is down. + */ +export const postsToUserinput = ({ app, flags }: Pick): boolean => + app.bugReports.enabled && flags.userinputReports; diff --git a/apps/web/src/lib/server/services/epk.test.ts b/apps/web/src/lib/server/services/epk.test.ts index 6d64a89f5..1b2655795 100644 --- a/apps/web/src/lib/server/services/epk.test.ts +++ b/apps/web/src/lib/server/services/epk.test.ts @@ -1,3 +1,4 @@ +import { XRPCError } from '@atproto/api'; import { TID } from '@atproto/common-web'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { type EpkAccess, type EpkView, MAX_EPKS_PER_PROJECT } from '#lib/epk.ts'; @@ -46,6 +47,29 @@ describe('EpkService', () => { const requestSpace = () => epkRequestSpace(ROOT, f.project.rkey); + /** Has the space host refuse decision records, as it does before their lexicon is published. Returns the undo. */ + const refuseDecisions = () => { + const { root } = f.t.core; + + f.t.core.root = async () => { + const client = await root(); + const create = client.createSpaceRecord.bind(client); + + client.createSpaceRecord = async (input) => { + if (input.collection === COLLECTION.epkDecision) + throw new XRPCError(400, 'InvalidRequest', `Unknown collection: ${input.collection}`); + + return create(input); + }; + + return client; + }; + + return () => { + f.t.core.root = root; + }; + }; + /** The grant the root wrote for `did` to see `epk`, in the project's request space. */ const grantOf = (epk: EpkView, did: string) => f.t.net.spaceRecords.get(`${requestSpace()}|${ROOT}|${COLLECTION.epkGrant}|${grantKey(epk.rkey, did)}`)?.value; @@ -229,6 +253,40 @@ describe('EpkService', () => { expect(await f.t.epks.requests(epk)).toEqual([]); }); + it("lets nobody in when the space host refuses the decision, so approving again works once it doesn't", async () => { + // Arrange + const epk = await f.publish(DJ); + const kit = f.kit(epk); + const stranger = await f.t.viewer(STRANGER); + await f.t.epks.request(stranger, kit, {}); + const [request] = await f.t.epks.requests(epk); + const accept = refuseDecisions(); + + // Act + const refused = f.t.epks.decide(await f.t.viewer(DJ), kit, request.uri, 'approve'); + + // Assert + await expect(refused).rejects.toThrow(/Unknown collection/); + expect({ + state: (await f.t.epks.accessState(kit, stranger)).kind, + grant: grantOf(epk, STRANGER), + member: f.t.net.spaces.get(epk.space)?.members.has(STRANGER) + }).toEqual({ state: 'pending', grant: undefined, member: false }); + accept(); + await f.t.epks.decide(await f.t.viewer(DJ), kit, request.uri, 'approve'); + expect((await f.t.epks.accessState(kit, stranger)).kind).toBe('granted'); + }); + + it("leaves a request for the managers when the space host refuses its automatic approval's decision", async () => { + const epk = await f.publish(DJ, { access: preset('open') }); + refuseDecisions(); + + await expect(f.t.epks.request(await f.t.viewer(STRANGER), f.kit(epk), {})).rejects.toThrow(/Unknown collection/); + + expect(grantOf(epk, STRANGER)).toBeUndefined(); + expect((await f.t.epks.requests(epk)).map(({ status }) => status)).toEqual(['pending']); + }); + it("leaves an automatic approval of a legacy press kit waiting, since only its maker's space holds it", async () => { const epk = await f.legacy(DJ, { access: preset('open') }); const kit = f.kit(epk); diff --git a/apps/web/src/lib/server/services/epk.ts b/apps/web/src/lib/server/services/epk.ts index d7131b04e..4bb4552fc 100644 --- a/apps/web/src/lib/server/services/epk.ts +++ b/apps/web/src/lib/server/services/epk.ts @@ -850,9 +850,8 @@ export class EpkService { } private async grant(kit: PressKit, grant: Omit, actor: Viewer | null): Promise { - await this.writeGrant(kit.project, kit.epk, { ...grant, createdAt: nowIso() }); - - // Revoking deletes the grant, so the request's answer needs a record of its own. + // Revoking deletes the grant, so the request's answer needs a record of its own. It goes first: a space host that + // refuses it (before the decision lexicon is published there) leaves nobody let in and the request open to approve again. if (grant.request) await this.writeDecision( kit, @@ -860,6 +859,7 @@ export class EpkService { 'approved', actor?.did ?? this.core.rootDid ); + await this.writeGrant(kit.project, kit.epk, { ...grant, createdAt: nowIso() }); await this.core.audit.record({ actor: actor?.did ?? this.core.rootDid, actorRole: actor ? actorRole(actor) : 'system', @@ -900,9 +900,9 @@ export class EpkService { } /** - * Sets a request's answer. A decision synced before its request, or one that outlived it, makes the row: marked - * deleted, as an answered request whose record is gone is, until the request syncs. So a re-sync keeps a decline, - * and with it the rule that the asker can't ask again, even when the asker deleted their request. + * Sets a request's answer. A decision synced before its request, or one that outlived it, makes the row, with + * `deletedAt` saying the request's record hasn't been seen until it syncs (saveRequest). So a re-sync keeps a + * decline, and with it the rule that the asker can't ask again, even when the asker deleted their request. */ private async saveDecision(space: string, decision: EpkDecision): Promise { const answer = { status: decision.outcome, decidedAt: decision.createdAt }; diff --git a/apps/web/src/lib/server/services/flags.test.ts b/apps/web/src/lib/server/services/flags.test.ts index f679a0fab..a7c2de6aa 100644 --- a/apps/web/src/lib/server/services/flags.test.ts +++ b/apps/web/src/lib/server/services/flags.test.ts @@ -16,8 +16,15 @@ const DJ = 'did:plc:dj'; const OTHER = 'did:plc:other'; +/** An ops flag. */ const FLAG = 'parityCanary'; +/** An ops flag that changes public pages, which its catalog file lists in `showsOn`. */ +const PAGE_FLAG = 'pauseRecordingStream'; + +/** A release flag, which goes once it's rolled out. */ +const RELEASE = 'dashboardCalendar'; + const off = { enabled: true, everyone: false, percentage: 0, groups: [], dids: [] }; describe('FlagService', () => { @@ -117,24 +124,34 @@ describe('FlagService', () => { expect(await t.flags.evaluate(null)).toEqual({ ...flagsOff, [FLAG]: true }); }); - it('says whether a flag is on for a percentage, which signed-out visitors need an id for', async () => { + it('says whether a flag on public pages is on for a percentage, which signed-out visitors need an id for', async () => { const admin = await t.viewer(ADMIN); - expect(await t.flags.hasPercentage()).toBe(false); + expect(await t.flags.hasPublicPercentage()).toBe(false); - await t.flags.updateFlag(admin, FLAG, { ...off, percentage: 5 }); + await t.flags.updateFlag(admin, PAGE_FLAG, { ...off, percentage: 5 }); - expect(await t.flags.hasPercentage()).toBe(true); - expect(await new FlagService(t.core, t.staff, { [FLAG]: true }).hasPercentage()).toBe(false); - expect(await new FlagService(t.core, t.staff, { [FLAG]: false }).hasPercentage()).toBe(false); + expect(await t.flags.hasPublicPercentage()).toBe(true); + expect(await new FlagService(t.core, t.staff, { [PAGE_FLAG]: true }).hasPublicPercentage()).toBe(false); + expect(await new FlagService(t.core, t.staff, { [PAGE_FLAG]: false }).hasPublicPercentage()).toBe(false); - await t.flags.updateFlag(admin, FLAG, { ...off, percentage: 5, enabled: false }); + await t.flags.updateFlag(admin, PAGE_FLAG, { ...off, percentage: 5, enabled: false }); - expect(await t.flags.hasPercentage()).toBe(false); + expect(await t.flags.hasPublicPercentage()).toBe(false); - await t.flags.updateFlag(admin, FLAG, { ...off, percentage: 5, everyone: true }); + await t.flags.updateFlag(admin, PAGE_FLAG, { ...off, percentage: 5, everyone: true }); - expect(await t.flags.hasPercentage()).toBe(false); + expect(await t.flags.hasPublicPercentage()).toBe(false); + }); + + it('needs no visitor id for a flag that changes only what accounts see, whatever its percentage', async () => { + const admin = await t.viewer(ADMIN); + + for (const key of [FLAG, 'inboxEmail', 'inboxDm', 'userinputReports'] as const) { + await t.flags.updateFlag(admin, key, { ...off, percentage: 50 }); + } + + expect(await t.flags.hasPublicPercentage()).toBe(false); }); it('tells a caller its own targeting and never who else', async () => { @@ -298,19 +315,24 @@ describe('FlagService', () => { }); it('lists the kinds of page a flag shows on from its catalog file, and none when it names none', async () => { - expect((await t.flags.flag(FLAG))?.showsOn).toEqual(['profile']); - expect((await t.flags.flag('pauseGoogleTokenExchange'))?.showsOn).toEqual([]); + expect((await t.flags.flag(PAGE_FLAG))?.showsOn).toEqual(['set', 'mix']); + expect((await t.flags.flag(FLAG))?.showsOn).toEqual([]); }); - it('says a flag is ready to remove once it has been on for everyone or every account for 30 days', async () => { - const uri = spaceRecordUri(t.spaces.staff, t.core.rootDid, COLLECTION.staffFlag, FLAG); + it('gives a release flag the date its catalog file says to remove it by, and an ops flag none', async () => { + expect((await t.flags.flag(RELEASE))?.removeBy).toMatch(/^\d{4}-\d{2}-\d{2}$/); + expect((await t.flags.flag(FLAG))?.removeBy).toBeUndefined(); + }); + + it('says a release flag is ready to remove once it has been on for everyone or every account for 30 days', async () => { + const uri = (key: string) => spaceRecordUri(t.spaces.staff, t.core.rootDid, COLLECTION.staffFlag, key); const dids: string[] = []; - const record = { key: FLAG, everyone: false, percentage: 0, groups: [], dids, updatedBy: ADMIN }; + const record = { everyone: false, percentage: 0, groups: [], dids, updatedBy: ADMIN }; - const ready = async (gates: Partial, updatedAt: string) => { - await t.flags.indexFlag(uri, { ...record, ...gates, updatedAt }); + const ready = async (gates: Partial, updatedAt: string, key = RELEASE) => { + await t.flags.indexFlag(uri(key), { ...record, key, ...gates, updatedAt }); - return (await t.flags.flag(FLAG))?.readyToRemove; + return (await t.flags.flag(key))?.readyToRemove; }; vi.useFakeTimers({ now: new Date('2026-12-01T12:00:00.000Z'), toFake: ['Date'] }); @@ -321,13 +343,15 @@ describe('FlagService', () => { expect(await ready({ everyone: true }, '2026-11-01T12:00:00.001Z')).toBe(false); expect(await ready({ percentage: 99, dids: [DJ] }, '2026-01-01T00:00:00.000Z')).toBe(false); expect(await ready({ everyone: true, enabled: false }, '2026-01-01T00:00:00.000Z')).toBe(false); + // An ops flag stays, however long it's been on. + expect(await ready({ everyone: true }, '2026-01-01T00:00:00.000Z', FLAG)).toBe(false); } finally { vi.useRealTimers(); } - await t.flags.removeFlagByUri(uri); + await t.flags.removeFlagByUri(uri(RELEASE)); - expect((await t.flags.flag(FLAG))?.readyToRemove).toBe(false); + expect((await t.flags.flag(RELEASE))?.readyToRemove).toBe(false); }); it('shows a group that has gone by its key, so a flag still naming it can be fixed', async () => { diff --git a/apps/web/src/lib/server/services/flags.ts b/apps/web/src/lib/server/services/flags.ts index 4451d7e10..83e636887 100644 --- a/apps/web/src/lib/server/services/flags.ts +++ b/apps/web/src/lib/server/services/flags.ts @@ -57,7 +57,12 @@ const list = (items: string[]) => items.toSorted().join(', '); const inCatalog = (key: string) => FLAGS.some((flag) => flag.key === key); -/** How long a flag has to be fully on, untouched, before the console says to remove it. PostHog uses the same. */ +/** The flags that change a public page, which signed-out visitors see too. */ +const SHOWN = new Set(FLAGS.filter((flag) => flag.showsOn).map((flag) => flag.key)); + +/** + * How long a release flag has to be fully on, untouched, before the console says to remove it. PostHog uses the same. + */ const READY_TO_REMOVE_MS = 30 * 86_400_000; /** The audit changes among `[field, before, after]` values. Empty when saving changes nothing. */ @@ -187,10 +192,13 @@ export class FlagService { return Object.fromEntries(answers.map((answer) => [answer.key, isOn(answer, answer.key, id)])) as Flags; } - /** Whether a flag is on for a percentage now, which a signed-out visitor needs an id of their own to be counted in. */ - async hasPercentage(): Promise { + /** + * Whether a flag that changes a public page is on for a percentage now, which a signed-out visitor needs an id of + * their own to be counted in. A flag with no `showsOn` changes only what accounts see, so it never needs one. + */ + async hasPublicPercentage(): Promise { return (await this.answers(null)).some( - ({ enabled, everyone, percentage }) => enabled && !everyone && percentage > 0 + ({ key, enabled, everyone, percentage }) => SHOWN.has(key) && enabled && !everyone && percentage > 0 ); } @@ -200,7 +208,7 @@ export class FlagService { const accounts = await this.core.accounts.views([...flags.values()].flatMap((flag) => flag.dids)); const settled = new Date(Date.now() - READY_TO_REMOVE_MS).toISOString(); - return FLAGS.map(({ key, description, showsOn = [] }) => { + return FLAGS.map(({ key, description, showsOn = [], type, removeBy }) => { const flag = flags.get(key); const fullyOn = !!flag?.enabled && (flag.everyone || flag.percentage === 100); @@ -208,13 +216,15 @@ export class FlagService { key, description, showsOn, + removeBy, enabled: flag?.enabled ?? true, everyone: flag?.everyone ?? false, percentage: flag?.percentage ?? 0, groups: (flag?.groups ?? []).map((rkey) => ({ rkey, name: groups.get(rkey)?.name ?? rkey })), accounts: (flag?.dids ?? []).map((did) => ({ did, handle: accounts.get(did).handle })), updatedAt: flag?.updatedAt ?? null, - readyToRemove: fullyOn && flag.updatedAt <= settled + // An ops flag stays in the code however long it's been on. + readyToRemove: type === 'release' && fullyOn && flag.updatedAt <= settled }; }); } diff --git a/apps/web/src/lib/server/services/follows.ts b/apps/web/src/lib/server/services/follows.ts index 75575bc68..1dafa78de 100644 --- a/apps/web/src/lib/server/services/follows.ts +++ b/apps/web/src/lib/server/services/follows.ts @@ -5,6 +5,7 @@ import { parsePublicRecordUri } from '../atproto/spaces'; import { type Core, NotFoundError, UserError } from '../core'; import { nowIso } from '../db'; import { type HappyViewClient, HappyViewError } from '../happyview/client'; +import type { BackfillFlags } from '../happyview/backfills'; import { awaitIndexed, INDEX_WAIT_MS, reindex } from '../happyview/indexed'; import { writeOwn } from './own-repo'; import { actorRole } from './requests'; @@ -34,7 +35,9 @@ export class FollowService { constructor( private readonly core: Core, private readonly directory: HappyViewClient, - private readonly indexWaitMs = INDEX_WAIT_MS + private readonly indexWaitMs = INDEX_WAIT_MS, + /** The app's, for pauseBackfills. */ + private readonly flags?: BackfillFlags ) {} async state(subject: Followable, viewer: string | undefined): Promise { @@ -118,6 +121,6 @@ export class FollowService { if (await awaitIndexed(served, this.indexWaitMs)) return; this.core.logger.warn('the directory has not caught up with a follow yet', { subject: subject.uri, actor }); - await reindex(this.directory, this.core.logger, COLLECTION.follow, [actor]); + await reindex(this.directory, this.core.logger, this.flags, COLLECTION.follow, [actor]); } } diff --git a/apps/web/src/lib/server/services/performers.test.ts b/apps/web/src/lib/server/services/performers.test.ts index b8ecb6166..fb7c8487a 100644 --- a/apps/web/src/lib/server/services/performers.test.ts +++ b/apps/web/src/lib/server/services/performers.test.ts @@ -111,7 +111,7 @@ describe('PerformerSearch', () => { expect(await found()).toEqual(['project', 'dj']); }); - it('leaves out a deleted DJ for good, even once their PDS says otherwise', async () => { + it("shows a DJ found deleted once their PDS says they're active, as after moving PDS", async () => { const found = async () => (await t.performers.search({ sort: 'name' })).items.map((item) => item.kind); t.accountStatus.set(DJ, 'deleted'); @@ -119,6 +119,6 @@ describe('PerformerSearch', () => { t.accountStatus.set(DJ, 'active'); await t.accountStatuses.refresh(); - expect(await found()).toEqual(['project']); + expect(await found()).toEqual(['project', 'dj']); }); }); diff --git a/apps/web/src/lib/server/services/projects.ts b/apps/web/src/lib/server/services/projects.ts index 644a20c00..bff35dfa9 100644 --- a/apps/web/src/lib/server/services/projects.ts +++ b/apps/web/src/lib/server/services/projects.ts @@ -20,7 +20,7 @@ import { type JsonRecord, type RecordRef, xrpcErrorName } from '../atproto/repo- import { parsePublicRecordUri } from '../atproto/spaces'; import { type Core, UserError } from '../core'; import { nowIso, parseJson } from '../db'; -import type { Backfills } from '../happyview/backfills'; +import type { BackfillFlags, Backfills } from '../happyview/backfills'; import { type DirectoryProject, type DirectoryStats, type HappyViewClient, QUERY_BYTES } from '../happyview/client'; import { awaitIndexed, INDEX_WAIT_MS, IndexedRepo, reindex } from '../happyview/indexed'; import { MANAGER_COLLECTIONS } from '../happyview/refresh'; @@ -146,16 +146,18 @@ export class ProjectService { /** * `backfills` is the app's, which other re-reads of the same accounts share (SetService makes one without it). * `plyr` finds the records of plyr.fm tracks that mixes link; without it, only recordings already published stay. + * `flags` are the app's, for pauseBackfills. */ constructor( private readonly core: Core, private readonly directory: HappyViewClient, private readonly indexWaitMs = INDEX_WAIT_MS, backfills?: Backfills, - private readonly plyr?: PlyrClient + private readonly plyr?: PlyrClient, + private readonly flags?: BackfillFlags ) { this.sets = new SetService(core, directory, backfills); - this.managerSpaces = new ManagerSpaces(core, new IndexedRepo(directory, core.logger, indexWaitMs)); + this.managerSpaces = new ManagerSpaces(core, new IndexedRepo(directory, core.logger, indexWaitMs, flags)); } /** @@ -450,7 +452,7 @@ export class ProjectService { void this.sets.refresh(added); for (const collection of [...MANAGER_COLLECTIONS.filter((nsid) => nsid !== COLLECTION.djSet), BSKY_FOLLOW]) - void reindex(this.directory, this.core.logger, collection, added); + void reindex(this.directory, this.core.logger, this.flags, collection, added); } return { project: projectView(this.core.rootDid, { ...ref, rkey }, record), changes }; diff --git a/apps/web/src/lib/server/services/recordings.test.ts b/apps/web/src/lib/server/services/recordings.test.ts index 1b1ecaddd..fcd0d3611 100644 --- a/apps/web/src/lib/server/services/recordings.test.ts +++ b/apps/web/src/lib/server/services/recordings.test.ts @@ -2,6 +2,7 @@ import { cidForLex } from '@atproto/lex-cbor'; import { jsonToLex } from '@atproto/lex-json'; import { describe, expect, it } from 'vitest'; import { COLLECTION } from '#lib/nsid.ts'; +import { flagsOff } from '#lib/testing/flags.ts'; import type { JsonRecord } from '../atproto/repo-client'; import { HappyViewClient } from '../happyview/client'; import { IndexedRepo } from '../happyview/indexed'; @@ -112,7 +113,7 @@ describe('RecordingService.source', () => { it("plays a plyr.fm recording from plyr's CDN, ahead of the set's links", async () => { const { recordings } = await service([], { plyrTrack: {} }); - expect(await recordings.source({ recording: ref(PLYR_URI), links: [{ uri: ARCHIVE }] })).toEqual({ + expect(await recordings.source({ recording: ref(PLYR_URI), links: [{ uri: ARCHIVE }] }, flagsOff)).toEqual({ kind: 'audio', src: 'https://audio.plyr.fm/audio/f1.mp3', from: 'plyr.fm', @@ -124,13 +125,13 @@ describe('RecordingService.source', () => { it("falls back to plyr's own player for a gated track, but takes audio from a link over it", async () => { const { recordings } = await service([], { plyrTrack: { gated: true } }); - expect(await recordings.source({ recording: ref(PLYR_URI), links: [{ uri: SOUNDCLOUD }] })).toEqual({ + expect(await recordings.source({ recording: ref(PLYR_URI), links: [{ uri: SOUNDCLOUD }] }, flagsOff)).toEqual({ kind: 'embed', src: 'https://plyr.fm/embed/track/1567', platform: 'plyr.fm', link: 'https://plyr.fm/track/1567' }); - expect(await recordings.source({ recording: ref(PLYR_URI), links: [{ uri: ARCHIVE }] })).toMatchObject({ + expect(await recordings.source({ recording: ref(PLYR_URI), links: [{ uri: ARCHIVE }] }, flagsOff)).toMatchObject({ from: 'archive.org' }); }); @@ -138,17 +139,19 @@ describe('RecordingService.source', () => { it("uses the links when plyr.fm doesn't have the track", async () => { const { recordings } = await service([]); - expect(await recordings.source({ recording: ref(PLYR_URI), links: [{ uri: SOUNDCLOUD }] })).toMatchObject({ - kind: 'embed', - platform: 'SoundCloud' - }); - expect(await recordings.source({ recording: ref(PLYR_URI) })).toBeNull(); + expect(await recordings.source({ recording: ref(PLYR_URI), links: [{ uri: SOUNDCLOUD }] }, flagsOff)).toMatchObject( + { + kind: 'embed', + platform: 'SoundCloud' + } + ); + expect(await recordings.source({ recording: ref(PLYR_URI) }, flagsOff)).toBeNull(); }); it("plays a recording on a manager's PDS through the site's audio route", async () => { const { recordings } = await service([{ collection: COLLECTION.djRecording, rkey: '3rec', record: recording() }]); - expect(await recordings.source({ recording: ref(`at://${DJ}/${COLLECTION.djRecording}/3rec`) })).toEqual({ + expect(await recordings.source({ recording: ref(`at://${DJ}/${COLLECTION.djRecording}/3rec`) }, flagsOff)).toEqual({ kind: 'audio', src: `/media/audio/${DJ}/${AUDIO_CID}`, from: 'pds' @@ -160,7 +163,7 @@ describe('RecordingService.source', () => { plyrTrack: {} }); - const paused = { pauseRecordingStream: true }; + const paused = { ...flagsOff, pauseRecordingStream: true }; const pds = ref(`at://${DJ}/${COLLECTION.djRecording}/3rec`); expect(await recordings.source({ recording: pds, links: [{ uri: SOUNDCLOUD }] }, paused)).toMatchObject({ @@ -176,7 +179,9 @@ describe('RecordingService.source', () => { { collection: COLLECTION.djRecording, rkey: '3rec', record: recording({}, {}) } ]); - expect(await recordings.source({ recording: ref(`at://${DJ}/${COLLECTION.djRecording}/3rec`) })).toMatchObject({ + expect( + await recordings.source({ recording: ref(`at://${DJ}/${COLLECTION.djRecording}/3rec`) }, flagsOff) + ).toMatchObject({ src: `/media/audio/${DJ}/${AUDIO_CID}` }); expect(await recordings.audio(DJ, AUDIO_CID)).toEqual({ mimeType: 'audio/mpeg', size: 1234 }); @@ -187,7 +192,9 @@ describe('RecordingService.source', () => { { collection: COLLECTION.djRecording, rkey: '3rec', record: recording({ mimeType: 'video/mp4' }) } ]); - expect(await recordings.source({ recording: ref(`at://${DJ}/${COLLECTION.djRecording}/3rec`) })).toMatchObject({ + expect( + await recordings.source({ recording: ref(`at://${DJ}/${COLLECTION.djRecording}/3rec`) }, flagsOff) + ).toMatchObject({ src: `/media/audio/${DJ}/${AUDIO_CID}` }); expect(await recordings.audio(DJ, AUDIO_CID)).toEqual({ mimeType: 'video/mp4', size: 1234 }); @@ -199,11 +206,15 @@ describe('RecordingService.source', () => { { collection: COLLECTION.djRecording, rkey: 'over', record: recording({ cid: 'bafyover', size: MAX_SIZE + 1 }) } ]); - expect(await recordings.source({ recording: ref(`at://${DJ}/${COLLECTION.djRecording}/cap`) })).toMatchObject({ + expect( + await recordings.source({ recording: ref(`at://${DJ}/${COLLECTION.djRecording}/cap`) }, flagsOff) + ).toMatchObject({ src: `/media/audio/${DJ}/bafycap` }); expect(await recordings.audio(DJ, 'bafycap')).toEqual({ mimeType: 'audio/mpeg', size: MAX_SIZE }); - expect(await recordings.source({ recording: ref(`at://${DJ}/${COLLECTION.djRecording}/over`) })).toBeNull(); + expect( + await recordings.source({ recording: ref(`at://${DJ}/${COLLECTION.djRecording}/over`) }, flagsOff) + ).toBeNull(); expect(await recordings.audio(DJ, 'bafyover')).toBeNull(); }); @@ -221,7 +232,7 @@ describe('RecordingService.source', () => { `at://${STRANGER}/${COLLECTION.djRecording}/3rec`, `at://${DJ}/app.bsky.feed.post/3rec` ]) - expect(await recordings.source({ recording: ref(uri) })).toBeNull(); + expect(await recordings.source({ recording: ref(uri) }, flagsOff)).toBeNull(); }); }); @@ -256,7 +267,10 @@ describe('RecordingService.set and forMix', () => { ); expect( - await recordings.forMix({ url: SOUNDCLOUD, set: { uri: `at://${DJ}/${COLLECTION.djSet}/3set`, cid: 'bafyx' } }) + await recordings.forMix( + { url: SOUNDCLOUD, set: { uri: `at://${DJ}/${COLLECTION.djSet}/3set`, cid: 'bafyx' } }, + flagsOff + ) ).toMatchObject({ platform: 'SoundCloud' }); }); @@ -268,30 +282,40 @@ describe('RecordingService.set and forMix', () => { const setUri = (rkey: string) => ({ uri: `at://${DJ}/${COLLECTION.djSet}/${rkey}`, cid: 'bafyx' }); - expect(await recordings.forMix({ url: SOUNDCLOUD, set: setUri('3set') })).toMatchObject({ from: 'plyr.fm' }); - expect(await recordings.forMix({ url: ARCHIVE, set: setUri('3embed') })).toMatchObject({ from: 'archive.org' }); - expect(await recordings.forMix({ url: 'https://www.mixcloud.com/neon/x/', set: setUri('3embed') })).toMatchObject({ + expect(await recordings.forMix({ url: SOUNDCLOUD, set: setUri('3set') }, flagsOff)).toMatchObject({ + from: 'plyr.fm' + }); + expect(await recordings.forMix({ url: ARCHIVE, set: setUri('3embed') }, flagsOff)).toMatchObject({ + from: 'archive.org' + }); + expect( + await recordings.forMix({ url: 'https://www.mixcloud.com/neon/x/', set: setUri('3embed') }, flagsOff) + ).toMatchObject({ platform: 'SoundCloud' }); - expect(await recordings.forMix({ url: SOUNDCLOUD, set: setUri('gone') })).toMatchObject({ platform: 'SoundCloud' }); - expect(await recordings.forMix({ url: 'https://neon.example/mix' })).toBeNull(); + expect(await recordings.forMix({ url: SOUNDCLOUD, set: setUri('gone') }, flagsOff)).toMatchObject({ + platform: 'SoundCloud' + }); + expect(await recordings.forMix({ url: 'https://neon.example/mix' }, flagsOff)).toBeNull(); }); it("plays a mix's own recording before its linked set, and its link when the recording can't play", async () => { const { recordings } = await service([set({ links: [{ uri: SOUNDCLOUD }] })], { plyrTrack: {} }); const linked = { uri: `at://${DJ}/${COLLECTION.djSet}/3set`, cid: 'bafyx' }; - expect(await recordings.forMix({ url: SOUNDCLOUD, set: linked, recording: ref(PLYR_URI) })).toMatchObject({ - from: 'plyr.fm', - src: 'https://audio.plyr.fm/audio/f1.mp3' - }); + expect(await recordings.forMix({ url: SOUNDCLOUD, set: linked, recording: ref(PLYR_URI) }, flagsOff)).toMatchObject( + { + from: 'plyr.fm', + src: 'https://audio.plyr.fm/audio/f1.mp3' + } + ); expect( - await recordings.forMix({ url: SOUNDCLOUD, recording: ref(`at://${DJ}/app.bsky.feed.post/3rec`) }) + await recordings.forMix({ url: SOUNDCLOUD, recording: ref(`at://${DJ}/app.bsky.feed.post/3rec`) }, flagsOff) ).toMatchObject({ platform: 'SoundCloud' }); const { recordings: offline } = await service([]); - expect(await offline.forMix({ url: SOUNDCLOUD, recording: ref(PLYR_URI) })).toMatchObject({ + expect(await offline.forMix({ url: SOUNDCLOUD, recording: ref(PLYR_URI) }, flagsOff)).toMatchObject({ platform: 'SoundCloud' }); }); @@ -304,7 +328,7 @@ describe('RecordingService.set and forMix', () => { set({ recording: pds }) ]); - const paused = { pauseRecordingStream: true }; + const paused = { ...flagsOff, pauseRecordingStream: true }; const linked = { uri: `at://${DJ}/${COLLECTION.djSet}/3set`, cid: 'bafyx' }; expect(await recordings.forMix({ url: SOUNDCLOUD, recording: pds }, paused)).toMatchObject({ @@ -384,9 +408,11 @@ describe('RecordingService.audio', () => { } }); - expect(await recordings.source({ recording: ref(`at://${DJ}/${COLLECTION.djRecording}/a`) })).toBeNull(); + expect(await recordings.source({ recording: ref(`at://${DJ}/${COLLECTION.djRecording}/a`) }, flagsOff)).toBeNull(); fail = false; - expect(await recordings.source({ recording: ref(`at://${DJ}/${COLLECTION.djRecording}/a`) })).toMatchObject({ + expect( + await recordings.source({ recording: ref(`at://${DJ}/${COLLECTION.djRecording}/a`) }, flagsOff) + ).toMatchObject({ from: 'pds' }); }); diff --git a/apps/web/src/lib/server/services/recordings.ts b/apps/web/src/lib/server/services/recordings.ts index 2c5c9fd70..38b7009d5 100644 --- a/apps/web/src/lib/server/services/recordings.ts +++ b/apps/web/src/lib/server/services/recordings.ts @@ -95,8 +95,11 @@ export class RecordingService { return parsed.success ? { ...parsed.data, uri: record.uri } : null; } - /** What a set plays: its recording record, then its links, audio first. Nothing is paused without `flags`. */ - async source(set: Pick, flags: Partial = {}): Promise { + /** + * What a set plays: its recording record, then its links, audio first. `flags` is the request's, for + * pauseRecordingStream. + */ + async source(set: Pick, flags: Flags): Promise { const recording = set.recording ? await this.recording(set.recording.uri, flags) : null; return preferred([recording, ...linkSources(set.links)]); @@ -104,12 +107,9 @@ export class RecordingService { /** * What a mix on a profile plays: its own recording record, then its linked set's recording or links, else the mix's - * own link. Never rejects, since the mix's page streams it. Nothing is paused without `flags`. + * own link. Never rejects, since the mix's page streams it. `flags` is the request's, for pauseRecordingStream. */ - async forMix( - mix: Pick, - flags: Partial = {} - ): Promise { + async forMix(mix: Pick, flags: Flags): Promise { const own = linkSources([{ uri: mix.url }]); try { @@ -146,7 +146,7 @@ export class RecordingService { }); } - private async recording(uri: string, flags: Partial): Promise { + private async recording(uri: string, flags: Flags): Promise { const ref = parsePublicRecordUri(uri); if (ref?.collection === PLYR_TRACK) return this.plyrTrack(uri); diff --git a/apps/web/src/lib/server/services/requests.test.ts b/apps/web/src/lib/server/services/requests.test.ts index b49b7e8c8..4cb170833 100644 --- a/apps/web/src/lib/server/services/requests.test.ts +++ b/apps/web/src/lib/server/services/requests.test.ts @@ -314,6 +314,23 @@ describe('RequestService', () => { expect(decisions).toEqual([expect.objectContaining({ reason: 'Welcome', langs: ['en'] })]); }); + it("doesn't give a project the languages of a request whose only prose is its message", async () => { + // Arrange + const uri = await synced('3unworded', { + kind: 'create', + profile: profile('Unworded'), + message: 'Wir spielen sonntags', + langs: ['de'] + }); + + // Act + await t.requests.decide({ actor: await t.viewer(MOD), uri, outcome: 'approved' }); + + // Assert + const [project] = t.net.listed(ROOT, COLLECTION.project).map(({ record }) => record); + expect(project).not.toHaveProperty('langs'); + }); + it("won't approve a listing request once the requester's profile is gone", async () => { const uri = await synced('3list', { kind: 'list', diff --git a/apps/web/src/lib/server/services/rsvps.ts b/apps/web/src/lib/server/services/rsvps.ts index 33a475712..98adee612 100644 --- a/apps/web/src/lib/server/services/rsvps.ts +++ b/apps/web/src/lib/server/services/rsvps.ts @@ -8,6 +8,7 @@ import { recordCid, type RepoWrite } from '../atproto/repo-client'; import { parsePublicRecordUri } from '../atproto/spaces'; import { type Core, UserError } from '../core'; import { type HappyViewClient, HappyViewError } from '../happyview/client'; +import type { BackfillFlags } from '../happyview/backfills'; import { awaitIndexed, INDEX_WAIT_MS, reindex } from '../happyview/indexed'; import { calendarCopy, type EventView } from './events'; import { writeOwn } from './own-repo'; @@ -38,7 +39,9 @@ export class RsvpService { private readonly directory: HappyViewClient, /** The site's address, which the calendar copy links pages by, so its CID depends on it. */ private readonly publicUrl: string, - private readonly indexWaitMs = INDEX_WAIT_MS + private readonly indexWaitMs = INDEX_WAIT_MS, + /** The app's, for pauseBackfills. */ + private readonly flags?: BackfillFlags ) {} /** @@ -131,6 +134,6 @@ export class RsvpService { if (await awaitIndexed(served, this.indexWaitMs)) return; this.core.logger.warn('the directory has not caught up with an RSVP yet', { subject, actor }); - await reindex(this.directory, this.core.logger, CALENDAR_RSVP, [actor]); + await reindex(this.directory, this.core.logger, this.flags, CALENDAR_RSVP, [actor]); } } diff --git a/apps/web/src/lib/server/services/shows.ts b/apps/web/src/lib/server/services/shows.ts index a4254fb60..c4e71373a 100644 --- a/apps/web/src/lib/server/services/shows.ts +++ b/apps/web/src/lib/server/services/shows.ts @@ -10,6 +10,7 @@ import { recordCid, xrpcErrorName } from '../atproto/repo-client'; import { parsePublicRecordUri } from '../atproto/spaces'; import { type Core, ForbiddenError, NotFoundError, UserError } from '../core'; import { nowIso } from '../db'; +import type { BackfillFlags } from '../happyview/backfills'; import type { DirectoryShow, HappyViewClient } from '../happyview/client'; import { awaitIndexed, INDEX_WAIT_MS, type IndexedRepo, reindex } from '../happyview/indexed'; import { atVenue, venueEnd, venueTime, zoneOf } from '../venue-time'; @@ -222,7 +223,9 @@ export class ShowService { private readonly projects: ProjectService, private readonly directory: HappyViewClient, private readonly indexed: IndexedRepo, - private readonly indexWaitMs = INDEX_WAIT_MS + private readonly indexWaitMs = INDEX_WAIT_MS, + /** The app's, for pauseBackfills. */ + private readonly flags?: BackfillFlags ) {} /** Upcoming shows, a page at a time, without those by accounts that aren't active. */ @@ -392,7 +395,7 @@ export class ShowService { * never brought (while HappyView was down, say). Runs when the app boots. */ async reindexManagers(): Promise { - await reindex(this.directory, this.core.logger, COLLECTION.show, await this.projects.managers()); + await reindex(this.directory, this.core.logger, this.flags, COLLECTION.show, await this.projects.managers()); } /** @@ -425,7 +428,7 @@ export class ShowService { private async awaitServed(did: string, served: () => Promise): Promise { if (await awaitIndexed(served, this.indexWaitMs)) return; this.core.logger.warn('the directory has not caught up with a show write yet', { did }); - await reindex(this.directory, this.core.logger, COLLECTION.show, [did]); + await reindex(this.directory, this.core.logger, this.flags, COLLECTION.show, [did]); } /** The app's view of a directory show, or null (logged) when it or its project doesn't validate. */ diff --git a/apps/web/src/lib/server/testing/lexicon-arbitraries.ts b/apps/web/src/lib/server/testing/lexicon-arbitraries.ts index 53b9ff434..ef1145c6a 100644 --- a/apps/web/src/lib/server/testing/lexicon-arbitraries.ts +++ b/apps/web/src/lib/server/testing/lexicon-arbitraries.ts @@ -6,6 +6,7 @@ import { isDatetimeStringLenient, isValidDid, isValidHandle, + isValidLanguage, isValidNsid, isValidRecordKey, isValidTid, @@ -127,6 +128,14 @@ const datetime = fc .date({ min: new Date('1970-01-01T00:00:00Z'), max: new Date('2100-01-01T00:00:00Z'), noInvalidDate: true }) .map((date) => date.toISOString()); +/** BCP 47 tags as records carry them: a primary language, sometimes with a script or region. */ +const language = fc + .oneof( + fc.constantFrom('en', 'de', 'pt-BR', 'ja', 'zh-Hant-TW', 'en-XA'), + fc.stringMatching(/^[a-z]{2,3}(-[A-Z]{2})?$/) + ) + .filter(isValidLanguage); + /** Each format the record lexicons use: how to make a value, and the check the validator makes of it. */ const FORMATS = new Map; check: (value: string) => boolean }>([ ['did', { valid: did, check: isValidDid }], @@ -134,6 +143,7 @@ const FORMATS = new Map; check: (value: st ['at-uri', { valid: atUri, check: isAtUriString }], ['cid', { valid: cid, check: isCid }], ['datetime', { valid: datetime, check: isDatetimeStringLenient }], + ['language', { valid: language, check: isValidLanguage }], ['uri', { valid: fc.oneof(fc.webUrl(), atUri, did).filter(isValidUri), check: isValidUri }] ]); diff --git a/apps/web/src/lib/server/token-exchange/exchange.test.ts b/apps/web/src/lib/server/token-exchange/exchange.test.ts index d42eaff86..3dbb1dadd 100644 --- a/apps/web/src/lib/server/token-exchange/exchange.test.ts +++ b/apps/web/src/lib/server/token-exchange/exchange.test.ts @@ -1,5 +1,6 @@ import * as fc from 'fast-check'; import { describe, expect, it } from 'vitest'; +import { flagsOff } from '#lib/testing/flags.ts'; import { silentLogger } from '../logger'; import { remoteObject } from '../testing/remote-bodies'; import { writtenLog } from '../testing/written-log'; @@ -93,7 +94,12 @@ describe('exchangeToken', () => { const { sent, fetch } = services(); const { lines, log } = capture(); - const answer = await exchangeToken('soundcloud', post({ ...code, client_id: 'the-plugins' }), { log, env, fetch }); + const answer = await exchangeToken('soundcloud', post({ ...code, client_id: 'the-plugins' }), { + log, + env, + fetch, + flags: flagsOff + }); expect(answer.status).toBe(200); expect(answer.headers.get('cache-control')).toBe('no-store'); @@ -115,7 +121,7 @@ describe('exchangeToken', () => { const { lines, log } = capture(); const refresh = (token: string) => post({ grant_type: 'refresh_token', refresh_token: token }); - const fresh = await exchangeToken('soundcloud', refresh('rt-1'), { log, env, fetch }); + const fresh = await exchangeToken('soundcloud', refresh('rt-1'), { log, env, fetch, flags: flagsOff }); expect(await fresh.json()).toMatchObject({ access_token: 'at-2', refresh_token: 'rt-2' }); expect(Object.fromEntries(sent[0].form)).toEqual({ grant_type: 'refresh_token', @@ -124,13 +130,14 @@ describe('exchangeToken', () => { client_secret: 'sc-secret' }); - const spent = await exchangeToken('soundcloud', refresh('rt-0'), { log, env, fetch }); + const spent = await exchangeToken('soundcloud', refresh('rt-0'), { log, env, fetch, flags: flagsOff }); expect([spent.status, await spent.json()]).toEqual([400, { error: 'invalid_grant', error_description: 'spent' }]); const wrong = await exchangeToken('soundcloud', refresh('rt-1'), { log, env: { ...env, SOUNDCLOUD_CLIENT_SECRET: 'stale' }, - fetch + fetch, + flags: flagsOff }); expect([wrong.status, await wrong.json()]).toEqual([401, { error: 'invalid_client' }]); @@ -141,7 +148,7 @@ describe('exchangeToken', () => { const { sent, fetch } = services(); const { log } = capture(); - const answer = await exchangeToken('mixcloud', post(code), { log, env, fetch }); + const answer = await exchangeToken('mixcloud', post(code), { log, env, fetch, flags: flagsOff }); expect(await answer.json()).toEqual({ access_token: 'at-1', token_type: 'bearer' }); expect(sent.map((s) => [s.method, s.url.origin + s.url.pathname, Object.fromEntries(s.form)])).toEqual([ @@ -155,7 +162,8 @@ describe('exchangeToken', () => { const refused = await exchangeToken('mixcloud', post({ grant_type: 'refresh_token', refresh_token: 'rt-1' }), { log, env, - fetch + fetch, + flags: flagsOff }); expect([refused.status, await refused.json()]).toEqual([ @@ -166,7 +174,8 @@ describe('exchangeToken', () => { const unknown = await exchangeToken('mixcloud', post(code), { log, env: { ...env, MIXCLOUD_CLIENT_ID: 'x' }, - fetch + fetch, + flags: flagsOff }); expect([unknown.status, await unknown.json()]).toEqual([400, { error: 'incorrect_client_credentials' }]); @@ -178,7 +187,7 @@ describe('exchangeToken', () => { async (id) => { const { sent, fetch } = services(); - const answer = await exchangeToken(id, post(code), { log: capture().log, env, fetch }); + const answer = await exchangeToken(id, post(code), { log: capture().log, env, fetch, flags: flagsOff }); expect([answer.status, await answer.json()]).toEqual([ 404, @@ -193,7 +202,7 @@ describe('exchangeToken', () => { const { lines, log } = capture(); for (const missing of [{}, { GOOGLE_CLIENT_ID: 'g-client' }, { GOOGLE_CLIENT_ID: 'g', GOOGLE_CLIENT_SECRET: '' }]) { - const answer = await exchangeToken('google', post(code), { log, env: missing, fetch }); + const answer = await exchangeToken('google', post(code), { log, env: missing, fetch, flags: flagsOff }); expect([answer.status, await answer.json()]).toEqual([ 503, @@ -209,7 +218,7 @@ describe('exchangeToken', () => { it('answers 503 for a service whose pause flag is on, sending it nothing, while the others still trade', async () => { const { sent, fetch } = services(); const { lines, log } = capture(); - const flags = { pauseMixcloudTokenExchange: true }; + const flags = { ...flagsOff, pauseMixcloudTokenExchange: true }; const paused = await exchangeToken('mixcloud', post(code), { log, env, fetch, flags }); @@ -235,7 +244,7 @@ describe('exchangeToken', () => { ])('refuses %s', async (_, body) => { const { sent, fetch } = services(); - const answer = await exchangeToken('soundcloud', posted(body), { log: capture().log, env, fetch }); + const answer = await exchangeToken('soundcloud', posted(body), { log: capture().log, env, fetch, flags: flagsOff }); expect([answer.status, (await answer.json()).error]).toEqual([400, 'invalid_request']); expect(sent).toEqual([]); @@ -249,7 +258,8 @@ describe('exchangeToken', () => { const answer = await exchangeToken('mixcloud', post({ ...code, redirect_uri: redirect }), { log: capture().log, env, - fetch + fetch, + flags: flagsOff }); expect(answer.status).toBe(200); @@ -275,7 +285,12 @@ describe('exchangeToken', () => { const { lines, log } = capture(); for (const service of ['mixcloud', 'soundcloud']) { - const answer = await exchangeToken(service, post({ ...code, redirect_uri: redirect }), { log, env, fetch }); + const answer = await exchangeToken(service, post({ ...code, redirect_uri: redirect }), { + log, + env, + fetch, + flags: flagsOff + }); expect([answer.status, await answer.json()]).toEqual([ 400, @@ -297,11 +312,23 @@ describe('exchangeToken', () => { const refresh = (redirect: string) => post({ grant_type: 'refresh_token', refresh_token: 'rt-1', redirect_uri: redirect }); - const elsewhere = await exchangeToken('soundcloud', refresh('https://attacker.example/cb'), { log, env, fetch }); + const elsewhere = await exchangeToken('soundcloud', refresh('https://attacker.example/cb'), { + log, + env, + fetch, + flags: flagsOff + }); + expect(elsewhere.status).toBe(400); expect(sent).toEqual([]); - const home = await exchangeToken('soundcloud', refresh('http://127.0.0.1:47110/callback'), { log, env, fetch }); + const home = await exchangeToken('soundcloud', refresh('http://127.0.0.1:47110/callback'), { + log, + env, + fetch, + flags: flagsOff + }); + expect(await home.json()).toMatchObject({ access_token: 'at-2' }); }); @@ -309,7 +336,7 @@ describe('exchangeToken', () => { const { sent, fetch } = services(); const huge = post({ ...code, code: 'c'.repeat(70_000) }); - const answer = await exchangeToken('soundcloud', huge, { log: capture().log, env, fetch }); + const answer = await exchangeToken('soundcloud', huge, { log: capture().log, env, fetch, flags: flagsOff }); expect([answer.status, (await answer.json()).error_description]).toEqual([413, 'The token request is too large']); expect(sent).toEqual([]); @@ -324,7 +351,7 @@ describe('exchangeToken', () => { throw Object.assign(new TypeError('fetch failed', { cause }), { request: new Request(input).url }); }; - const unreachable = await exchangeToken('mixcloud', post(code), { log, env, fetch: down }); + const unreachable = await exchangeToken('mixcloud', post(code), { log, env, fetch: down, flags: flagsOff }); expect([unreachable.status, await unreachable.json()]).toEqual([ 502, { error: 'temporarily_unavailable', error_description: "Mixcloud isn't answering" } @@ -335,7 +362,7 @@ describe('exchangeToken', () => { throw new DOMException('The operation was aborted due to timeout', 'TimeoutError'); }; - const late = await exchangeToken('soundcloud', post(code), { log, env, fetch: slow }); + const late = await exchangeToken('soundcloud', post(code), { log, env, fetch: slow, flags: flagsOff }); expect(late.status).toBe(502); expect(JSON.stringify(lines)).toContain('"reason":"The operation was aborted due to timeout"'); @@ -344,7 +371,9 @@ describe('exchangeToken', () => { throw 'mc-secret'; }; - expect((await exchangeToken('mixcloud', post(code), { log, env, fetch: thrown })).status).toBe(502); + expect((await exchangeToken('mixcloud', post(code), { log, env, fetch: thrown, flags: flagsOff })).status).toBe( + 502 + ); expect(JSON.stringify(lines)).toContain('"reason":"unknown"'); // The last is nested deeper than answering it could stringify, though it's well under the size cap. @@ -358,7 +387,7 @@ describe('exchangeToken', () => { deep ]) { const odd = async () => new Response(body, { status: body === null ? 502 : 200 }); - const answer = await exchangeToken('soundcloud', post(code), { log, env, fetch: odd }); + const answer = await exchangeToken('soundcloud', post(code), { log, env, fetch: odd, flags: flagsOff }); expect([answer.status, (await answer.json()).error_description]).toEqual([ 502, @@ -430,7 +459,12 @@ describe('exchangeToken, for anything sent to it', () => { return Response.json({ access_token: 'at-1', token_type: 'bearer' }); }; - const answer = await exchangeToken(id, posted(body), { log: silentLogger, env: everywhere, fetch }); + const answer = await exchangeToken(id, posted(body), { + log: silentLogger, + env: everywhere, + fetch, + flags: flagsOff + }); expect([200, 400, 404, 413]).toContain(answer.status); // Only an id no service is registered under, "constructor" and "__proto__" among them, is a 404. @@ -478,7 +512,7 @@ describe('exchangeToken, for anything sent to it', () => { const body = BODILESS.has(status) ? null : text; const fetch = async () => new Response(body, { status, headers: { 'content-type': type } }); - const answer = await exchangeToken(id, post(code), { log: silentLogger, env, fetch }); + const answer = await exchangeToken(id, post(code), { log: silentLogger, env, fetch, flags: flagsOff }); const answered: unknown = await answer.json(); expect(answered).toBeTypeOf('object'); diff --git a/apps/web/src/lib/server/token-exchange/exchange.ts b/apps/web/src/lib/server/token-exchange/exchange.ts index 31a9c17f9..690d0948a 100644 --- a/apps/web/src/lib/server/token-exchange/exchange.ts +++ b/apps/web/src/lib/server/token-exchange/exchange.ts @@ -106,13 +106,13 @@ export type ExchangeOptions = { /** Where the services' client ids and secrets are read from. */ env?: Record; fetch?: typeof fetch; - /** The request's flags, where a service's pauseFlag stops its exchange. Nothing is paused without them. */ - flags?: Partial; + /** The request's flags, where a service's pauseFlag stops its exchange. */ + flags: Flags; }; /** Trades a code or refresh token for tokens at the service `id` names, with Local Network's client there. */ export async function exchangeToken(id: string, request: Request, options: ExchangeOptions): Promise { - const { log, env = process.env, fetch: send = fetch, flags = {} } = options; + const { log, env = process.env, fetch: send = fetch, flags } = options; const service = Object.hasOwn(services, id) ? services[id] : undefined; if (!service) return refuse(404, 'invalid_request', `Local Network doesn't sign in to "${id.slice(0, 64)}"`); diff --git a/apps/web/src/lib/types.ts b/apps/web/src/lib/types.ts index 6612661b3..956b593e7 100644 --- a/apps/web/src/lib/types.ts +++ b/apps/web/src/lib/types.ts @@ -522,6 +522,8 @@ export type FlagView = { description: string; /** The kinds of page it changes, from its catalog file. Empty when the file names none. */ showsOn: ShowsOn[]; + /** When a release flag should be gone from the code, as YYYY-MM-DD. Ops flags stay, so they have none. */ + removeBy?: string; /** False when it's turned off for everyone. The gates below are kept for when it's back on. */ enabled: boolean; everyone: boolean; @@ -529,7 +531,7 @@ export type FlagView = { groups: { rkey: string; name: string }[]; accounts: FlagAccount[]; updatedAt: string | null; - /** On for everyone, or every account, and unchanged for 30 days: time to take it out of the code. */ + /** A release flag on for everyone, or every account, and unchanged for 30 days: time to take it out of the code. */ readyToRemove: boolean; }; diff --git a/apps/web/src/lib/ui/SectionHeader.svelte b/apps/web/src/lib/ui/SectionHeader.svelte index f97b83daa..cfc10bcf2 100644 --- a/apps/web/src/lib/ui/SectionHeader.svelte +++ b/apps/web/src/lib/ui/SectionHeader.svelte @@ -32,10 +32,10 @@ const display = $derived(size === 'display'); -
+
{#if eyebrow}{eyebrow}{/if} - {#if typeof title === 'string'}{title}{:else}{@render title()}{/if} + {#if typeof title === 'string'}{title}{:else}{@render title()}{/if}
{#if lede}

{lede}

diff --git a/apps/web/src/routes/+error.svelte b/apps/web/src/routes/+error.svelte index e7267cd41..e6a0e197e 100644 --- a/apps/web/src/routes/+error.svelte +++ b/apps/web/src/routes/+error.svelte @@ -14,7 +14,7 @@ {page.error?.title ?? page.status} · Local Network -
+
{#snippet actions()}{/snippet} diff --git a/apps/web/src/routes/+layout.server.ts b/apps/web/src/routes/+layout.server.ts index cc991eaa7..0595d9911 100644 --- a/apps/web/src/routes/+layout.server.ts +++ b/apps/web/src/routes/+layout.server.ts @@ -1,9 +1,19 @@ import { requireViewer } from '#lib/server/http.ts'; +import { postsToUserinput } from '#lib/server/services/bug-reports.ts'; import type { FlagPreview, Flags, Viewer } from '#lib/types.ts'; import type { LayoutServerLoad } from './$types'; -/** `flags` is optional so a page rendered on its own, in a test or a story, reads every flag as off. */ -type RootData = { viewer: Viewer | null; pendingRequests: number; flags?: Flags; flagPreview?: FlagPreview }; +/** + * `flags` is optional so a page rendered on its own, in a test or a story, reads every flag as off. `reportsToUserinput` + * says whether /report would post this viewer's report to userinput.app rather than send them to GitHub. + */ +type RootData = { + viewer: Viewer | null; + pendingRequests: number; + flags?: Flags; + flagPreview?: FlagPreview; + reportsToUserinput?: boolean; +}; export const load: LayoutServerLoad = async ({ locals, url }): Promise => { // Send a session that has to sign in again to the login page before anything tries to write with it. @@ -13,5 +23,11 @@ export const load: LayoutServerLoad = async ({ locals, url }): Promise if (viewer?.isStaff) pendingRequests = (await locals.app.requests.counts()).pending; - return { viewer, pendingRequests, flags: locals.flags, flagPreview: locals.flagPreview }; + return { + viewer, + pendingRequests, + flags: locals.flags, + flagPreview: locals.flagPreview, + reportsToUserinput: postsToUserinput(locals) + }; }; diff --git a/apps/web/src/routes/+layout.svelte b/apps/web/src/routes/+layout.svelte index 919c61a55..37898a3f9 100644 --- a/apps/web/src/routes/+layout.svelte +++ b/apps/web/src/routes/+layout.svelte @@ -97,8 +97,8 @@ {m.footer_who_its_for()} {m.footer_privacy()} {m.footer_tools()} - - {data.viewer ? m.footer_report_bug() : m.footer_report_bug_github()} + + {data.viewer && data.reportsToUserinput ? m.footer_report_bug() : m.footer_report_bug_github()} {m.footer_tagline()}
diff --git a/apps/web/src/routes/@[handle]/page.server.test.ts b/apps/web/src/routes/@[handle]/page.server.test.ts index 872333a9d..b05780537 100644 --- a/apps/web/src/routes/@[handle]/page.server.test.ts +++ b/apps/web/src/routes/@[handle]/page.server.test.ts @@ -194,7 +194,7 @@ it('is a 404 for an address that names no account, and a 429 once a visitor has it("says an account isn't active, the same way whatever the reason, and that a deleted one was deleted", async () => { const loadMara = () => callRoute(load, { app: app(), params: { handle: 'mara.test' }, url: '/@mara.test' }); - const inactive = { status: 404, body: { title: "This account isn't active" } }; + const inactive = { status: 404, body: { title: "@mara.test isn't active" } }; t.accountStatus.set(MARA, 'deactivated'); await expect(loadMara()).rejects.toMatchObject(inactive); @@ -206,7 +206,7 @@ it("says an account isn't active, the same way whatever the reason, and that a d t.accountStatus.set(MARA, 'deleted'); await t.accountStatuses.refresh(); - await expect(loadMara()).rejects.toMatchObject({ status: 410, body: { title: 'This account was deleted' } }); + await expect(loadMara()).rejects.toMatchObject({ status: 410, body: { title: '@mara.test was deleted' } }); }); it("shows the profile again once its account is active again, and refuses to follow it while it isn't", async () => { diff --git a/apps/web/src/routes/admin/audit/page.server.test.ts b/apps/web/src/routes/admin/audit/page.server.test.ts index 6aafe8583..95d0ad76b 100644 --- a/apps/web/src/routes/admin/audit/page.server.test.ts +++ b/apps/web/src/routes/admin/audit/page.server.test.ts @@ -63,6 +63,23 @@ it("filters by an actor's handle, action, outcome, and text, and echoes the filt expect(data.filters).toEqual({ actor: 'admin.test', action: 'role', outcome: 'success', q: 'mod' }); }); +it("finds a flag's changes, and only that flag's, where the flag's page links to", async () => { + const admin = await t.viewer(ADMIN); + const gates = { enabled: true, everyone: true, percentage: 0, groups: [], dids: [] }; + await t.flags.updateFlag(admin, 'dashboardCalendar', gates); + await t.flags.recordPreview(admin, 'dashboardCalendar', true); + await t.flags.updateFlag(admin, 'parityCanary', gates); + await t.flags.createGroup(admin, { name: 'dashboardCalendar testers', members: [MOD] }); + await t.audit.idle(); + + const data = await audit('/admin/audit?action=flag&q=dashboardCalendar'); + + expect(data.entries.map((entry) => [entry.action, entry.subject])).toEqual([ + ['flag.preview', 'dashboardCalendar'], + ['flag.update', 'dashboardCalendar'] + ]); +}); + it("filters by the actor as typed when it isn't a handle it can resolve", async () => { expect((await audit(`/admin/audit?actor=${ADMIN}`)).entries).toHaveLength(1); expect((await audit('/admin/audit?actor=nobody.example')).entries).toEqual([]); diff --git a/apps/web/src/routes/admin/flags/[key]/+page.svelte b/apps/web/src/routes/admin/flags/[key]/+page.svelte index 2569259a4..5de4e70e3 100644 --- a/apps/web/src/routes/admin/flags/[key]/+page.svelte +++ b/apps/web/src/routes/admin/flags/[key]/+page.svelte @@ -4,6 +4,7 @@ import FormMessage from '#lib/components/FormMessage.svelte'; import { SHOWS_ON } from '#lib/flags/shows-on.ts'; import { formFields } from '#lib/form-fields.svelte.ts'; + import { formatShowDate } from '#lib/format.ts'; import SectionHeader from '#lib/ui/SectionHeader.svelte'; import type { PageProps } from './$types'; @@ -34,7 +35,15 @@ Flags
-

Shows on: {showsOn}

+ {#if flag.readyToRemove} +

Ready to removeDelete flags/catalog/{flag.key}.json and the code it gates.

+ {/if} +
+

Shows on: {showsOn}

+ + {#if flag.removeBy}

Remove by: {formatShowDate(flag.removeBy)}

{/if} + Changes in the audit log +
({ update }) => update({ reset: false })}> @@ -52,7 +61,7 @@
-

Signed-out visitors count once per browser. Everyone in stays in as it grows.

+

Counts signed-out browsers too; anyone in stays in.{#if flag.showsOn.length > 0}{' '}Crawlers see it about this share of the time.{/if}

Groups diff --git a/apps/web/src/routes/admin/flags/[key]/page.stories.svelte b/apps/web/src/routes/admin/flags/[key]/page.stories.svelte index 18b38cae3..7440fabfe 100644 --- a/apps/web/src/routes/admin/flags/[key]/page.stories.svelte +++ b/apps/web/src/routes/admin/flags/[key]/page.stories.svelte @@ -10,9 +10,10 @@ const { Story } = defineMeta({ title: 'Staff/Flag' }); const flag: FlagView = { - key: 'parityCanary', - description: 'Gates nothing. Turn it on for an account to check that the website and locallibrary give it the same answer.', - showsOn: ['profile'], + key: 'spacePages', + description: "The public act, party, venue and event pages. Off, they answer 404, and no listing is written until it's on for everyone, since a listing points at a public page.", + showsOn: ['act', 'party', 'venue', 'event'], + removeBy: '2027-02-12', enabled: true, everyone: false, percentage: 25, @@ -22,7 +23,17 @@ readyToRemove: false }; - const groups: FlagGroupView[] = [{ rkey: '3lzy2ji4nms2z', name: 'Beta DJs', description: null, members: [{ did: 'did:plc:milo', handle: 'milo.test' }], flags: ['parityCanary'] }]; + const groups: FlagGroupView[] = [{ rkey: '3lzy2ji4nms2z', name: 'Beta DJs', description: null, members: [{ did: 'did:plc:milo', handle: 'milo.test' }], flags: ['spacePages'] }]; + + /** A release flag on for everyone past its time: what the page asks staff to delete. */ + const calendar: Partial = { + key: 'dashboardCalendar', + description: 'Shows Calendar in the dashboard sidebar and serves /dashboard/calendar, every night for the year ahead.', + showsOn: [], + removeBy: '2027-02-15', + everyone: true, + readyToRemove: true + }; const data = (fields: Partial = {}, flagPreview?: Record) => ({ viewer: ada, @@ -34,7 +45,7 @@ }); - + - + - + - + - + + + - + - + - + + + + { + const canvas = within(canvasElement); + + await expect(canvas.getByText('Ready to remove')).toBeVisible(); + await expect(canvas.getByText('Feb 15, 2027')).toBeVisible(); + }} +> + + - + diff --git a/apps/web/src/routes/admin/flags/[key]/page.svelte.test.ts b/apps/web/src/routes/admin/flags/[key]/page.svelte.test.ts index af31527e9..ab907d004 100644 --- a/apps/web/src/routes/admin/flags/[key]/page.svelte.test.ts +++ b/apps/web/src/routes/admin/flags/[key]/page.svelte.test.ts @@ -6,9 +6,9 @@ import type { FlagView } from '#lib/types.ts'; import Page from './+page.svelte'; it('lists the kinds of page the flag shows on', async () => { - await renderFlag({ showsOn: ['profile'] }); + await renderFlag({ key: 'pauseRecordingStream', showsOn: ['set', 'mix'] }); - await expect.element(page.getByText('Shows on: Profile', { exact: true })).toBeVisible(); + await expect.element(page.getByText('Shows on: Set, Mix', { exact: true })).toBeVisible(); }); it('names each kind as the staff console does, and every page for global', async () => { @@ -27,9 +27,61 @@ it('says so when the flag lists no kind of page', async () => { await expect.element(page.getByText('Shows on: None listed', { exact: true })).toBeVisible(); }); +const CRAWLERS = 'Crawlers see it about this share of the time.'; + +it('warns that crawlers see a flag that shows on public pages about as often as its percentage', async () => { + await renderFlag({ key: 'spacePages', showsOn: ['act', 'party', 'venue', 'event'] }); + + await expect.element(page.getByText(CRAWLERS, { exact: false })).toBeVisible(); +}); + +it('leaves crawlers out of the percentage hint for a flag that shows on no public page', async () => { + await renderFlag({ showsOn: [] }); + + await expect.element(page.getByText('anyone in stays in.', { exact: false })).toBeVisible(); + await expect.element(page.getByText(CRAWLERS, { exact: false })).not.toBeInTheDocument(); +}); + +it("gives a release flag's remove-by date as its catalog file writes it", async () => { + await renderFlag({ key: 'dashboardCalendar', removeBy: '2027-02-15' }); + + await expect.element(page.getByText('Remove by: Feb 15, 2027', { exact: true })).toBeVisible(); +}); + +it('gives no remove-by date for a flag without one', async () => { + await renderFlag({}); + + await expect.element(page.getByText('Shows on:', { exact: false })).toBeVisible(); + await expect.element(page.getByText('Remove by', { exact: false })).not.toBeInTheDocument(); +}); + +it("links to the flag's changes in the audit log", async () => { + await renderFlag({ key: 'dashboardCalendar' }); + + await expect + .element(page.getByRole('link', { name: 'Changes in the audit log' })) + .toHaveAttribute('href', '/admin/audit?action=flag&q=dashboardCalendar'); +}); + +it('says what to delete once the flag is ready to remove', async () => { + await renderFlag({ key: 'dashboardCalendar', readyToRemove: true }); + + await expect.element(page.getByText('Ready to remove', { exact: true })).toBeVisible(); + await expect + .element(page.getByText('Delete flags/catalog/dashboardCalendar.json and the code it gates.')) + .toBeVisible(); +}); + +it("doesn't say to remove a flag that isn't ready", async () => { + await renderFlag({ key: 'dashboardCalendar' }); + + await expect.element(page.getByRole('heading', { name: 'dashboardCalendar', level: 1 })).toBeVisible(); + await expect.element(page.getByText('Ready to remove')).not.toBeInTheDocument(); +}); + // Helpers -/** The flag page for parityCanary, with `fields` on top of a flag nobody has set. */ +/** The flag page for parityCanary, or the flag `fields` names, on top of a flag nobody has set. */ function renderFlag(fields: Partial) { const flag: FlagView = { key: 'parityCanary', diff --git a/apps/web/src/routes/admin/system/+page.svelte b/apps/web/src/routes/admin/system/+page.svelte index c0b5f10b9..fcf340aa6 100644 --- a/apps/web/src/routes/admin/system/+page.svelte +++ b/apps/web/src/routes/admin/system/+page.svelte @@ -104,6 +104,8 @@

Root spaces

+ +
diff --git a/apps/web/src/routes/dashboard/account/+page.server.ts b/apps/web/src/routes/dashboard/account/+page.server.ts index c46b04de6..6357acc60 100644 --- a/apps/web/src/routes/dashboard/account/+page.server.ts +++ b/apps/web/src/routes/dashboard/account/+page.server.ts @@ -1,5 +1,7 @@ import { soon } from '#lib/server/home.ts'; import { requireViewer } from '#lib/server/http.ts'; +import { offeredChannels } from '#lib/server/notifications/outbox.ts'; +import type { NotificationChannel } from '#lib/types.ts'; import type { PageServerLoad } from './$types'; export const load: PageServerLoad = async ({ locals, url }) => { @@ -16,10 +18,19 @@ export const load: PageServerLoad = async ({ locals, url }) => { }) ); + const offered = offeredChannels(locals); + + /** On, off, or paused: by the channel itself, or, as the notifications page says, while this site doesn't offer it. */ + const state = async (channel: NotificationChannel, isOffered: boolean): Promise<'on' | 'paused' | 'off'> => { + const view = await app.notificationChannels.view(viewer.did, channel); + + if (!view) return 'off'; + + return view.status === 'active' && isOffered ? 'on' : 'paused'; + }; + const [channels, latest, requests, held] = await Promise.all([ - quietly( - Promise.all([app.notificationChannels.view(viewer.did, 'email'), app.notificationChannels.view(viewer.did, 'dm')]) - ), + quietly(Promise.all([state('email', offered.email), state('dm', Boolean(offered.dm))])), quietly(app.audit.list({ actor: viewer.did, limit: 1 })), quietly(app.requests.list({ requester: viewer.did, limit: 50 })), quietly(app.heldRecords.list(viewer)) diff --git a/apps/web/src/routes/dashboard/account/+page.svelte b/apps/web/src/routes/dashboard/account/+page.svelte index 81df3f9b5..ea68ac9d3 100644 --- a/apps/web/src/routes/dashboard/account/+page.svelte +++ b/apps/web/src/routes/dashboard/account/+page.svelte @@ -4,7 +4,6 @@ import LinkRows from '#lib/components/LinkRows.svelte'; import { accountLabel, pluralize, timeAgo } from '#lib/format.ts'; import { resolved } from '#lib/resolved.svelte.ts'; - import type { ChannelView } from '#lib/types.ts'; import Button from '#lib/ui/Button.svelte'; import type { PageProps } from './$types'; @@ -18,8 +17,6 @@ const held = resolved(() => data.held, undefined); - const onOrOff = (channel: ChannelView | null) => (channel ? (channel.status === 'active' ? 'on' : 'paused') : 'off'); - /** A row's line: nothing yet while its source is out, and what the page holds in general if that source failed. */ const line = (value: T | null | undefined, about: string, say: (value: T) => string) => { if (value === undefined) return null; @@ -28,7 +25,7 @@ }; const lines = $derived<(string | null)[]>([ - line(channels.value, ACCOUNT_PAGES[0].about, ([email, dm]) => `Email ${onOrOff(email)} · Bluesky DMs ${onOrOff(dm)}`), + line(channels.value, ACCOUNT_PAGES[0].about, ([email, dm]) => `Email ${email} · Bluesky DMs ${dm}`), line(latest.value, ACCOUNT_PAGES[1].about, ([entry]) => (entry ? `${auditSentence(entry)} · ${timeAgo(entry.createdAt)}` : 'Nothing yet')), line(held.value, ACCOUNT_PAGES[2].about, (records) => (records.length ? `${pluralize(records.length, 'record')} held for you` : 'Nothing held for you')), line(requests.value, ACCOUNT_PAGES[3].about, (list) => { diff --git a/apps/web/src/routes/dashboard/account/notifications/+page.server.ts b/apps/web/src/routes/dashboard/account/notifications/+page.server.ts index d04ae104d..e622f194e 100644 --- a/apps/web/src/routes/dashboard/account/notifications/+page.server.ts +++ b/apps/web/src/routes/dashboard/account/notifications/+page.server.ts @@ -101,11 +101,13 @@ export const load: PageServerLoad = async ({ locals, url }) => { topics: KIND_TOPICS, email: { available: offered.email, + notYet: !offered.email && app.outbox.configured.includes('email'), channel: await app.notificationChannels.view(viewer.did, 'email'), returned: returned(url.searchParams.get('email')) }, dm: { available: Boolean(offered.dm), + notYet: !offered.dm && app.outbox.configured.includes('dm'), channel: dm, // Streamed: Bluesky chat can be slow, and the rest of the page doesn't wait on it. availability: offered.dm ? offered.dm.availability(viewer.did) : null, diff --git a/apps/web/src/routes/dashboard/account/notifications/+page.svelte b/apps/web/src/routes/dashboard/account/notifications/+page.svelte index b10a21c33..7d0c2ee66 100644 --- a/apps/web/src/routes/dashboard/account/notifications/+page.svelte +++ b/apps/web/src/routes/dashboard/account/notifications/+page.svelte @@ -18,11 +18,11 @@

Notifications

-

Your inbox here gets everything. Pick what else goes by email or Bluesky DM.

+

Your inbox here gets everything. {#if channels.length}Pick what else goes by email or Bluesky DM.{/if}

{#if channels.length}{/if}
- - + +
diff --git a/apps/web/src/routes/dashboard/account/notifications/page.server.test.ts b/apps/web/src/routes/dashboard/account/notifications/page.server.test.ts index 2bd10f525..233719494 100644 --- a/apps/web/src/routes/dashboard/account/notifications/page.server.test.ts +++ b/apps/web/src/routes/dashboard/account/notifications/page.server.test.ts @@ -242,6 +242,24 @@ it("doesn't offer email or DMs to someone they aren't rolled out to, on a site t expect(neither.dm).toMatchObject({ available: false, availability: null }); }); +it("says a channel isn't on for them yet only when the site sends by it", async () => { + const viewer = await t.viewer(DJ); + const url = '/dashboard/account/notifications'; + + const bare = app({ + outbox: new Outbox({ db: t.db, logger: silentLogger, channels, flags: t.flags, senders: {} }), + dm: null + }); + + const notRolledOut = await loadRoute(load, { app: app(), viewer, url }); + const rolledOut = await loadRoute(load, { app: app(), viewer, url, flags: ROLLED_OUT }); + const notSetUp = await loadRoute(load, { app: bare, viewer, url }); + + expect([notRolledOut.email.notYet, notRolledOut.dm.notYet]).toEqual([true, true]); + expect([rolledOut.email.notYet, rolledOut.dm.notYet]).toEqual([false, false]); + expect([notSetUp.email.notYet, notSetUp.dm.notYet]).toEqual([false, false]); +}); + it("won't turn on, save or test a channel for a post while it isn't rolled out to them, but turns it off", async () => { await signedIn(WITH_EMAIL); await run('emailOn'); diff --git a/apps/web/src/routes/dashboard/account/notifications/page.stories.svelte b/apps/web/src/routes/dashboard/account/notifications/page.stories.svelte index 2085848dd..817b225dc 100644 --- a/apps/web/src/routes/dashboard/account/notifications/page.stories.svelte +++ b/apps/web/src/routes/dashboard/account/notifications/page.stories.svelte @@ -14,8 +14,8 @@ const data = (email: ChannelView | null, dm: ChannelView | null, availability: DmAvailability = 'ok', available = true): PageProps['data'] => ({ ...accountLayout, topics: ['bookings'], - email: { available, channel: email, returned: null }, - dm: { available, channel: dm, availability: Promise.resolve(availability), root: 'localnetwork.computer' } + email: { available, notYet: false, channel: email, returned: null }, + dm: { available, notYet: false, channel: dm, availability: Promise.resolve(availability), root: 'localnetwork.computer' } }); diff --git a/apps/web/src/routes/dashboard/account/notifications/page.svelte.test.ts b/apps/web/src/routes/dashboard/account/notifications/page.svelte.test.ts index fd2a45e3e..3358cd5de 100644 --- a/apps/web/src/routes/dashboard/account/notifications/page.svelte.test.ts +++ b/apps/web/src/routes/dashboard/account/notifications/page.svelte.test.ts @@ -9,14 +9,15 @@ import Page from './+page.svelte'; const data = (available: boolean, channel: ChannelView | null = null): PageProps['data'] => ({ ...accountLayout, topics: ['bookings'], - email: { available, channel, returned: null }, - dm: { available, channel, availability: Promise.resolve('ok'), root: 'localnetwork.computer' } + email: { available, notYet: false, channel, returned: null }, + dm: { available, notYet: false, channel, availability: Promise.resolve('ok'), root: 'localnetwork.computer' } }); it('offers the grid while email or Bluesky DM can be set up', async () => { await render(Page, { params: {}, form: null, data: data(true) }); await expect.element(page.getByRole('heading', { name: 'What goes where' })).toBeVisible(); + await expect.element(page.getByText('Pick what else goes by email or Bluesky DM.', { exact: false })).toBeVisible(); }); it('leaves the grid out when neither can be set up here', async () => { @@ -24,6 +25,21 @@ it('leaves the grid out when neither can be set up here', async () => { await expect.element(page.getByRole('heading', { name: 'Notifications', level: 1 })).toBeVisible(); await expect.element(page.getByRole('heading', { name: 'What goes where' })).not.toBeInTheDocument(); + await expect.element(page.getByText('Your inbox here gets everything.')).toBeVisible(); + await expect.element(page.getByText('Pick what else', { exact: false })).not.toBeInTheDocument(); +}); + +it("says when email and DMs aren't on for their account yet", async () => { + const off = data(false); + + await render(Page, { + params: {}, + form: null, + data: { ...off, email: { ...off.email, notYet: true }, dm: { ...off.dm, notYet: true } } + }); + + await expect.element(page.getByText('Not on for your account yet.').first()).toBeVisible(); + expect(page.getByText('Not on for your account yet.').elements()).toHaveLength(2); }); it('lets someone turn off a channel they turned on before it stopped being offered to them', async () => { diff --git a/apps/web/src/routes/dashboard/account/page.server.test.ts b/apps/web/src/routes/dashboard/account/page.server.test.ts index 78d91e5ef..883d3c7cf 100644 --- a/apps/web/src/routes/dashboard/account/page.server.test.ts +++ b/apps/web/src/routes/dashboard/account/page.server.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, expect, it } from 'vitest'; import { createTestServices } from '#lib/server/testing/core.ts'; import { writtenLog } from '#lib/server/testing/written-log.ts'; +import type { ChannelView } from '#lib/types.ts'; import { callRoute, loadRoute } from '#lib/testing/route-event.ts'; import type { PageServerData } from './$types'; import { load } from './+page.server.ts'; @@ -35,12 +36,44 @@ it("says where each page stands from the viewer's own records", async () => { url: '/dashboard/account' }); - expect(await data.channels).toEqual([null, null]); + expect(await data.channels).toEqual(['off', 'off']); expect((await data.latest)?.map((entry) => entry.action)).toEqual(['request.submit']); expect((await data.requests)?.map((request) => request.status)).toEqual(['pending']); expect(await data.held).toEqual([]); }); +it("says a channel they have is paused while it's paused, or while this site doesn't offer it to them", async () => { + // Arrange + const email: ChannelView = { + status: 'active', + pausedReason: null, + address: 'dj@neontide.test', + topics: ['bookings'] + }; + + const dm: ChannelView = { status: 'paused', pausedReason: 'dm_not_allowed', address: null, topics: ['bookings'] }; + const views = { view: async (_did: string, channel: string) => (channel === 'email' ? email : dm) }; + const app = { ...t, notificationChannels: views, outbox: { configured: ['email', 'dm'] }, dm: {} }; + const viewer = await t.viewer(DJ); + const url = '/dashboard/account'; + + // Act + const offered = await loadRoute(load, { + app, + viewer, + url, + flags: { inboxEmail: true, inboxDm: true } + }); + + const notOffered = await loadRoute(load, { app, viewer, url }); + + // Assert + expect([await offered.channels, await notOffered.channels]).toEqual([ + ['on', 'paused'], + ['paused', 'paused'] + ]); +}); + it('loses only the line of a source that fails, and logs it', async () => { const { logger: log, notes } = writtenLog('info'); diff --git a/apps/web/src/routes/dashboard/account/page.stories.svelte b/apps/web/src/routes/dashboard/account/page.stories.svelte index 901e60f7e..34351808f 100644 --- a/apps/web/src/routes/dashboard/account/page.stories.svelte +++ b/apps/web/src/routes/dashboard/account/page.stories.svelte @@ -4,7 +4,7 @@ import AccountNav from '#lib/components/AccountNav.svelte'; import { accountLayout, auditEntry } from '#lib/testing/account.ts'; import { request } from '#lib/testing/requests.ts'; - import type { ChannelView, HeldRecordView } from '#lib/types.ts'; + import type { HeldRecordView } from '#lib/types.ts'; import { phone } from '#lib/testing/viewports.ts'; import Activity from './activity/+page.svelte'; import Data from './data/+page.svelte'; @@ -46,9 +46,7 @@ const held = (kind: HeldRecordView['kind'], uri: string): HeldRecordView => ({ uri, kind, title: 'A record', excerpt: null, createdAt: hoursAgo(4) }); - const email: ChannelView = { status: 'active', pausedReason: null, address: null, topics: [] }; - - const landing: ComponentProps['data'] = { ...accountLayout, channels: [email, null], latest: [entries[1]], requests, held: [held('booking', 'a'), held('booking', 'b')] }; + const landing: ComponentProps['data'] = { ...accountLayout, channels: ['on', 'off'], latest: [entries[1]], requests, held: [held('booking', 'a'), held('booking', 'b')] }; const activity = (value: ComponentProps['data']['activity']) => ({ ...accountLayout, activity: value }); @@ -58,6 +56,7 @@ + diff --git a/apps/web/src/routes/dashboard/account/page.svelte.test.ts b/apps/web/src/routes/dashboard/account/page.svelte.test.ts index 9a5340f9c..e55d54555 100644 --- a/apps/web/src/routes/dashboard/account/page.svelte.test.ts +++ b/apps/web/src/routes/dashboard/account/page.svelte.test.ts @@ -6,14 +6,14 @@ import { request } from '#lib/testing/requests.ts'; import type { PageProps } from './$types'; import Page from './+page.svelte'; -const data: PageProps['data'] = { ...accountLayout, channels: [null, null], latest: [], requests: [], held: [] }; +const data: PageProps['data'] = { ...accountLayout, channels: ['off', 'off'], latest: [], requests: [], held: [] }; const open = (changes: Partial = {}) => render(Page, { params: {}, form: null, data: { ...data, ...changes } }); it('links each page with where things stand there', async () => { await open({ - channels: [{ status: 'paused', pausedReason: 'email_unverified', address: null, topics: [] }, null], + channels: ['paused', 'off'], requests: [request('create'), request('claim', { status: 'changes_requested' })], held: [{ uri: 'a', kind: 'booking', title: 'Inquiry', excerpt: null, createdAt: '2026-10-30T20:00:00Z' }] }); @@ -36,6 +36,12 @@ it('links each page with where things stand there', async () => { await expect.element(page.getByText('1 needs you · 1 with staff')).toBeVisible(); }); +it('says which channels are on', async () => { + await open({ channels: ['on', 'paused'] }); + + await expect.element(page.getByText('Email on · Bluesky DMs paused')).toBeVisible(); +}); + it('puts the latest entry in a plain sentence', async () => { await open({ latest: [ diff --git a/apps/web/src/routes/error.stories.svelte b/apps/web/src/routes/error.stories.svelte index 6dbd1e306..322cbea4f 100644 --- a/apps/web/src/routes/error.stories.svelte +++ b/apps/web/src/routes/error.stories.svelte @@ -2,6 +2,7 @@ import { defineMeta } from '@storybook/addon-svelte-csf'; import { expect, within } from 'storybook/test'; import ErrorPage from './+error.svelte'; + import { phone } from '#lib/testing/viewports.ts'; /** * The site's error page, for a page that isn't there, an account that isn't active, and a fault. Only a fault shows a @@ -36,18 +37,42 @@ { const canvas = within(canvasElement); - await expect(canvas.getByRole('heading', { level: 1, name: "This account isn't active" })).toBeVisible(); + await expect(canvas.getByRole('heading', { level: 1, name: "@mara.test isn't active" })).toBeVisible(); await expect(canvas.queryByText('Error 404')).toBeNull(); }} /> { - await expect(within(canvasElement).getByRole('heading', { level: 1, name: 'This account was deleted' })).toBeVisible(); + await expect(within(canvasElement).getByRole('heading', { level: 1, name: '@mara.test was deleted' })).toBeVisible(); + }} +/> + + + { + await expect(canvasElement.ownerDocument.documentElement.scrollWidth).toBeLessThanOrEqual(canvasElement.ownerDocument.documentElement.clientWidth); + }} +/> + + + { + const page = canvasElement.querySelector('.container-page'); + const home = within(canvasElement).getByRole('link', { name: 'Back to home' }); + const gutters = page ? Number.parseFloat(getComputedStyle(page).paddingLeft) * 2 : 0; + + await expect(home.getBoundingClientRect().width).toBe((page?.clientWidth ?? 0) - gutters); }} /> diff --git a/apps/web/src/routes/layout.server.test.ts b/apps/web/src/routes/layout.server.test.ts index 1372bfabc..b34de447c 100644 --- a/apps/web/src/routes/layout.server.test.ts +++ b/apps/web/src/routes/layout.server.test.ts @@ -24,14 +24,18 @@ afterEach(async () => { * Calls the layout's load at `url` for a session whose grant now lacks scopes the app asks for, which the server hook * gives no viewer. */ +/** The site with no userinput.app space, so reports go to GitHub. */ +const site = () => ({ ...t, bugReports: { enabled: false } }); + const loadNeedingReauth = (url: string) => - loadRoute(load, { app: t, sessionToken: 'session-token', reauth: true, url }); + loadRoute(load, { app: site(), sessionToken: 'session-token', reauth: true, url }); it('gives someone signed out no viewer and no requests to review', async () => { - expect(await loadRoute(load, { app: t, url: '/' })).toEqual({ + expect(await loadRoute(load, { app: site(), url: '/' })).toEqual({ viewer: null, pendingRequests: 0, - flags: flagsOff + flags: flagsOff, + reportsToUserinput: false }); }); @@ -45,15 +49,17 @@ it('counts the pending requests for staff only', async () => { const admin = await t.viewer(ADMIN); const dj = await t.viewer(DJ); - expect(await loadRoute(load, { app: t, viewer: admin, url: '/' })).toEqual({ + expect(await loadRoute(load, { app: site(), viewer: admin, url: '/' })).toEqual({ viewer: admin, pendingRequests: 1, - flags: flagsOff + flags: flagsOff, + reportsToUserinput: false }); - expect(await loadRoute(load, { app: t, viewer: dj, url: '/' })).toEqual({ + expect(await loadRoute(load, { app: site(), viewer: dj, url: '/' })).toEqual({ viewer: dj, pendingRequests: 0, - flags: flagsOff + flags: flagsOff, + reportsToUserinput: false }); }); @@ -68,12 +74,29 @@ it('lets a session that has to sign in again load the login page itself', async expect(await loadNeedingReauth('/login')).toEqual({ viewer: null, pendingRequests: 0, - flags: flagsOff + flags: flagsOff, + reportsToUserinput: false }); }); it('hands pages the flags the server hook worked out', async () => { - const data = await loadRoute(load, { app: t, url: '/', flags: { parityCanary: true } }); + const data = await loadRoute(load, { app: site(), url: '/', flags: { parityCanary: true } }); expect(data.flags).toEqual({ ...flagsOff, parityCanary: true }); }); + +it('says reports go to userinput.app only when the site has a space and the flag is on for the viewer', async () => { + const viewer = await t.viewer(DJ); + + const reports = (enabled: boolean, userinputReports: boolean) => + loadRoute(load, { + app: { ...t, bugReports: { enabled } }, + viewer, + url: '/', + flags: { userinputReports } + }).then((data) => data.reportsToUserinput); + + expect(await reports(true, true)).toBe(true); + expect(await reports(true, false)).toBe(false); + expect(await reports(false, true)).toBe(false); +}); diff --git a/apps/web/src/routes/media/audio/[did]/[cid]/server.test.ts b/apps/web/src/routes/media/audio/[did]/[cid]/server.test.ts index c4b1b02f3..91f283ee9 100644 --- a/apps/web/src/routes/media/audio/[did]/[cid]/server.test.ts +++ b/apps/web/src/routes/media/audio/[did]/[cid]/server.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import { IdentityResolver } from '#lib/server/atproto/identity.ts'; import { silentLogger } from '#lib/server/logger.ts'; import { type Loopback, rebindToLoopback } from '#lib/server/testing/rebind.ts'; +import { flagsOff } from '#lib/testing/flags.ts'; import { callRoute } from '#lib/testing/route-event.ts'; import { GET } from './+server.ts'; @@ -38,11 +39,12 @@ it("won't stream a recording from a PDS whose name points at loopback when it co }); const recordings = { audio: async () => ({ mimeType: 'audio/mpeg', size: 100 }) }; - const locals = { app: { identity, recordings }, log: silentLogger }; + const locals = { app: { identity, recordings }, log: silentLogger, flags: flagsOff }; const request = new Request('https://x.test/'); const event = { params: { did: DJ, cid: CID }, request, locals, fetch: globalThis.fetch }; - // SAFETY: the route reads only its params, the request's headers, the app's identity and recordings, and the log. + // SAFETY: the route reads only its params, the request's headers, the app's identity and recordings, the log and the + // flags. const response = await GET(event as never); expect(response.status).toBe(502); diff --git a/apps/web/src/routes/page.stories.svelte b/apps/web/src/routes/page.stories.svelte index 2f75ce21c..75ed69014 100644 --- a/apps/web/src/routes/page.stories.svelte +++ b/apps/web/src/routes/page.stories.svelte @@ -152,14 +152,14 @@ {#snippet home(viewer: Viewer | null, data: typeof directory | typeof empty | typeof offline | typeof loading)} - {@const layout = { viewer, pendingRequests: 0, meta: PAGE_META }} + {@const layout = { viewer, pendingRequests: 0, meta: PAGE_META, reportsToUserinput: viewer !== null }} {/snippet} {#snippet social(viewer: Viewer | null, data: Social)} - {@const layout = { viewer, pendingRequests: 0, meta: PAGE_META }} + {@const layout = { viewer, pendingRequests: 0, meta: PAGE_META, reportsToUserinput: viewer !== null }} diff --git a/apps/web/src/routes/privacy/+page.server.ts b/apps/web/src/routes/privacy/+page.server.ts index a076bddbe..300376406 100644 --- a/apps/web/src/routes/privacy/+page.server.ts +++ b/apps/web/src/routes/privacy/+page.server.ts @@ -3,6 +3,7 @@ import type { PageServerLoad } from './$types'; export const load: PageServerLoad = ({ locals }) => ({ retentionDays: locals.app.epkViews.retentionDays, + sessionDays: locals.app.config.sessionDays, meta: pageMeta(locals.app.config.publicUrl, { title: 'Privacy', description: 'What Local Network stores, where each kind of data lives, and who can read it.', diff --git a/apps/web/src/routes/privacy/+page.svelte b/apps/web/src/routes/privacy/+page.svelte index 19c975dea..87bc339d2 100644 --- a/apps/web/src/routes/privacy/+page.svelte +++ b/apps/web/src/routes/privacy/+page.svelte @@ -8,26 +8,43 @@
-

Public

+

Public

Published project profiles (name, genres, city, links, mixes, fee tier, managers' DIDs) are public atproto records anyone can read.

A bug report you send while signed in is a public post on userinput.app, kept in your own repo, with the page you sent it from and your browser.

-

Booking details

+

Booking details

Private booking details (email, phone, rates, tech rider) are stored in a space only Local Network and its staff can read. The project's managers see them, and so does anyone they let into one of their press kits, inside that press kit.

-

Staff only

+

Staff only

Requests, claim evidence, decisions, staff roles, and the audit log live in spaces only staff can read. Audit entries record what happened (who, what, when, and which fields changed); booking message contents are never copied into the audit log.

-

Press kits

+

Press kits

A press kit's public part is a record in Local Network's repo that anyone can read. The rest sits in a space under Local Network's account that only the project's managers, Local Network, and the people they let in can read. Asking to see it shares your handle, and any role and message you give, with the project's managers only: requests sit in a separate space that only they and Local Network can read. Each person let in gets a record saying so in that same space, which any of the managers can have deleted to take access away. Drafts of a press kit sit in each manager's repo in a space only the project's current managers can read.

When someone let in opens a press kit on this site, its project's managers see who and when. Local Network keeps that receipt for {data.retentionDays} days, and any of the managers can delete it sooner. The audit log keeps a record that the press kit was viewed, but not by whom.

-

Acts, parties and venues

+

Acts, parties and venues

Each act, party and venue has a space under Local Network's account with who's in it, their roles, invites and requests to join, and whether it's listed in the directory. Only its people are members of the space, and staff see it through this site.

-

Booking threads and your planner

+

Booking threads and your planner

Each booking thread is a space under Local Network's account whose only members are the promoter and the project's managers. Local Network indexes the thread so the site can show it to them. Your planner is readable only by you.

-

On our server

+

On our server

We keep a search index derived from the records above, OAuth tokens needed to act on your behalf (encrypted at rest by your host's disk encryption), hashed browser session tokens, and an outbox of audit entries waiting to be written. Signing out revokes our OAuth session.

Your inbox lives only on our server. Each item says what happened and where (a new inquiry or message in one of your booking threads, say) but not what anyone wrote. Read items are deleted after 90 days and unread ones after 180.

-

If you turn on email for your inbox, we keep the email address your account's host shares with us, to send it to, and delete it as soon as you turn email off. We send one email with a link to confirm the address is yours, and nothing else until you open it. Each email goes through our email provider, Resend, and has a link that turns email off without signing in.

-

If you turn on Bluesky DMs for your inbox, they come from Local Network's own Bluesky account. Bluesky's chat service carries and keeps them like any other DM, and all we keep is that you turned them on.

-

Deleting data

+

If you turn on email for your inbox, we keep the email address your account's host shares with us, to send it to, and delete it as soon as you turn email off. We send one email with a link to confirm the address is yours, and nothing else until you open it. Each email goes through our email provider, Resend, and has a link that turns email off without signing in.

+

If you turn on Bluesky DMs for your inbox, they come from Local Network's own Bluesky account. Bluesky's chat service carries and keeps them like any other DM, and all we keep is that you turned them on.

+

Cookies

+ + +
+
SpaceReadWriteURI
+ + + + + + + + + +
NameWhat it's forKept for
ln_sessionKeeps you signed in. We store only a hash of it, with the browser you signed in from.{data.sessionDays} days, or until you sign out
ln_localeThe language you see the site in.400 days
ln_flag_visitorOnly while you're signed out and we're trying something new on a share of visitors: a random id, so you get the same version on every visit. It isn't linked to an account and we don't log it.1 year
ln_shows_placeThe city you last picked on Shows or the home page, so both open on it.1 year
ln_signed_outSet when you sign out, naming the account, so the next page clears its form drafts from this browser.Until the next page reads it
ln_flag_previewStaff only: the features they're previewing in this browser.1 hour
+
+

Your browser also keeps drafts of long forms, and whether keyboard shortcuts are on, in its local storage. Signing out clears that account's drafts.

+

Deleting data

Anything you wrote with your own account is in your own repo, where any atproto tool can delete it. What Local Network wrote for you when your account's server couldn't, you can delete from Your data; audit log entries and booking status changes stay, and so do the decisions on requests you delete. Ask an admin to archive a project you manage.

diff --git a/apps/web/src/routes/privacy/page.server.test.ts b/apps/web/src/routes/privacy/page.server.test.ts index 1dfdd2b00..b59377830 100644 --- a/apps/web/src/routes/privacy/page.server.test.ts +++ b/apps/web/src/routes/privacy/page.server.test.ts @@ -3,11 +3,15 @@ import { loadRoute } from '#lib/testing/route-event.ts'; import type { PageServerData } from './$types'; import { load } from './+page.server.ts'; -it('says how long press kit views are kept, under the canonical /privacy address', async () => { - const app = { epkViews: { retentionDays: 90 }, config: { publicUrl: 'https://localnetwork.computer' } }; +it('says how long press kit views and sign-ins are kept, under the canonical /privacy address', async () => { + const app = { + epkViews: { retentionDays: 90 }, + config: { publicUrl: 'https://localnetwork.computer', sessionDays: 30 } + }; const data = await loadRoute(load, { app, url: '/privacy' }); expect(data.retentionDays).toBe(90); + expect(data.sessionDays).toBe(30); expect(data.meta).toMatchObject({ title: 'Privacy', url: 'https://localnetwork.computer/privacy' }); }); diff --git a/apps/web/src/routes/report/+page.server.ts b/apps/web/src/routes/report/+page.server.ts index e84c62bb8..6be20d619 100644 --- a/apps/web/src/routes/report/+page.server.ts +++ b/apps/web/src/routes/report/+page.server.ts @@ -1,7 +1,7 @@ import { fail, redirect } from '@sveltejs/kit'; import { githubIssueUrl, REPORT_LIMITS, type ReportFacts, reportBody } from '#lib/bug-report.ts'; import { OptionalScopeUnsupported } from '#lib/server/atproto/oauth.ts'; -import { browserLabel } from '#lib/server/services/bug-reports.ts'; +import { browserLabel, postsToUserinput } from '#lib/server/services/bug-reports.ts'; import { requireViewer, safeNext, text } from '#lib/server/http.ts'; import type { Actions, PageServerLoad } from './$types'; @@ -11,12 +11,6 @@ const factsOf = (request: Request, from: string | null): ReportFacts => ({ browser: browserLabel(request.headers.get('user-agent')) }); -/** - * Whether a signed-in viewer's report goes to userinput.app: the site has a space to post to, and it's rolled out to - * them. Off, it goes to GitHub, which is also how staff send everyone there while userinput.app is down. - */ -const postsToUserinput = ({ app, flags }: App.Locals) => app.bugReports.enabled && flags.userinputReports; - export const load: PageServerLoad = async ({ locals, request, url }) => { const facts = factsOf(request, url.searchParams.get('from')); const github = githubIssueUrl(facts); diff --git a/apps/web/tests/integration/flows.test.ts b/apps/web/tests/integration/flows.test.ts index 517607162..6def83f4e 100644 --- a/apps/web/tests/integration/flows.test.ts +++ b/apps/web/tests/integration/flows.test.ts @@ -154,7 +154,7 @@ describe('Local Network on a real atproto spaces network', () => { const event = { params: { id: '1', slug: 'x', rkey: 'x' }, url, - locals: { app: net.app, viewer: pat, log: silentLogger } + locals: { app: net.app, viewer: pat, log: silentLogger, flags: flagsOff } }; for (const load of [ @@ -288,7 +288,7 @@ describe('Local Network on a real atproto spaces network', () => { params: { slug }, url, request: new Request(url, { method: 'POST', body: form }), - locals: { app: net.app, viewer: lee, log: silentLogger } + locals: { app: net.app, viewer: lee, log: silentLogger, flags: flagsOff } }) ).rejects.toMatchObject({ status: 403 }); expect(await net.app.requests.list({ requester: lee.did })).toEqual([]); @@ -366,7 +366,7 @@ describe('Local Network on a real atproto spaces network', () => { const review = await adminRequest({ params: { rkey: request.rkey }, url: new URL(`http://localhost/admin/requests/${request.rkey}`), - locals: { app: net.app, viewer: await net.viewer('ada'), log: silentLogger } + locals: { app: net.app, viewer: await net.viewer('ada'), log: silentLogger, flags: flagsOff } }); expect(review.avatar).toEqual({ type: 'image/svg+xml', shown: false }); @@ -448,7 +448,11 @@ describe('Local Network on a real atproto spaces network', () => { expect(stored?.value).toMatchObject({ profile: { mixes: [{ title: 'Closing', set: { uri, cid } }] } }); const page = async () => { - const event = { params: { slug: project.slug }, locals: { app: net.app, viewer: null, log: silentLogger } }; + const event = { + params: { slug: project.slug }, + locals: { app: net.app, viewer: null, log: silentLogger, flags: flagsOff } + }; + const data = await projectPage(event); return data && 'sets' in data ? (await data.sets)?.get(uri) : undefined; @@ -648,7 +652,7 @@ describe('Local Network on a real atproto spaces network', () => { headers: { authorization: `Bearer ${token}` } }); - const response = await requestIndex({ request, locals: { app: net.app, log: silentLogger } }); + const response = await requestIndex({ request, locals: { app: net.app, log: silentLogger, flags: flagsOff } }); return { status: response.status, body: await response.json() }; }; @@ -1015,7 +1019,7 @@ describe('Local Network on a real atproto spaces network', () => { it('brings someone who turns down sharing their email back to the settings, and anyone else to sign-in', async () => { const callback = async (url: URL) => { try { - await oauthCallback({ url, locals: { app: net.app, log: silentLogger } }); + await oauthCallback({ url, locals: { app: net.app, log: silentLogger, flags: flagsOff } }); } catch (thrown) { return isRedirect(thrown) ? thrown.location : thrown; } diff --git a/apps/web/tests/integration/held-records.test.ts b/apps/web/tests/integration/held-records.test.ts index 9c71fbc5c..b10e77f83 100644 --- a/apps/web/tests/integration/held-records.test.ts +++ b/apps/web/tests/integration/held-records.test.ts @@ -5,6 +5,7 @@ import type { HeldRecordView, Viewer } from '../../src/lib/types.ts'; import { load } from '../../src/routes/dashboard/account/data/+page.server.ts'; import { actions } from '../../src/routes/dashboard/account/data/[kind]/+page.server.ts'; import { TestNetwork } from './network.ts'; +import { flagsOff } from '../../src/lib/testing/flags.ts'; describe('deleting what the root wrote on your behalf, on a real atproto spaces network', () => { let net: TestNetwork; @@ -32,7 +33,7 @@ describe('deleting what the root wrote on your behalf, on a real atproto spaces const event = (viewer: Viewer, form?: Record) => ({ url, - locals: { app: net.app, viewer, log: silentLogger }, + locals: { app: net.app, viewer, log: silentLogger, flags: flagsOff }, request: new Request(url, { method: 'POST', body: new URLSearchParams(form) }) }); diff --git a/apps/web/tests/integration/inactive-accounts.test.ts b/apps/web/tests/integration/inactive-accounts.test.ts index 9448892e6..f25101e24 100644 --- a/apps/web/tests/integration/inactive-accounts.test.ts +++ b/apps/web/tests/integration/inactive-accounts.test.ts @@ -46,14 +46,19 @@ describe('an account that stops being active, on a real PDS', () => { it("leaves a deactivated DJ out of Find DJs and says their page isn't active, until they come back", async () => { const neon = net.user('neon'); - const page = () => - callRoute(profilePage, { app: net.app, params: { handle: neon.handle }, url: `/@${neon.handle}` }); + const page = (address = neon.handle) => + callRoute(profilePage, { app: net.app, params: { handle: address }, url: `/@${address}` }); await neon.agent.com.atproto.server.deactivateAccount({}); await net.app.accountStatuses.refresh(); expect(await listed()).toEqual([]); - await expect(page()).rejects.toMatchObject({ status: 404, body: { title: "This account isn't active" } }); + // A deactivated account's PDS stops answering for its handle, so that address finds nobody; its DID still says why. + await expect(page()).rejects.toMatchObject({ status: 404 }); + await expect(page(neon.did)).rejects.toMatchObject({ + status: 404, + body: { title: expect.stringMatching(/isn't active$/) } + }); await neon.agent.com.atproto.server.activateAccount(); await checkLater(); diff --git a/apps/web/tests/integration/press-kits.test.ts b/apps/web/tests/integration/press-kits.test.ts index b06e64b61..96e379776 100644 --- a/apps/web/tests/integration/press-kits.test.ts +++ b/apps/web/tests/integration/press-kits.test.ts @@ -33,6 +33,7 @@ import { load as publicKit } from '../../src/routes/projects/[slug]/press-kits/[ import { grantKey, type PressKit } from '../../src/lib/server/services/epk.ts'; import type { ProjectView } from '../../src/lib/types.ts'; import { TestNetwork } from './network.ts'; +import { flagsOff } from '../../src/lib/testing/flags.ts'; /** A 1x1 PNG. */ const PNG = Uint8Array.from( @@ -460,7 +461,7 @@ describe('shared press kits on a real atproto spaces network', () => { const [neon, remy, pat] = [await net.viewer('neon'), await net.viewer('remy'), await net.viewer('pat')]; const night = await project('Night Shift', ['neon', 'remy']); const slug = night.slug; - const locals = (viewer: typeof neon | null) => ({ app: net.app, viewer, log: silentLogger }); + const locals = (viewer: typeof neon | null) => ({ app: net.app, viewer, log: silentLogger, flags: flagsOff }); /** A handler's result as a promise, so a redirect it throws, even synchronously, rejects it. */ const handled = async (run: () => T | Promise): Promise => run(); diff --git a/apps/web/tests/integration/shared-spaces.test.ts b/apps/web/tests/integration/shared-spaces.test.ts index fd0d966c1..695ddf399 100644 --- a/apps/web/tests/integration/shared-spaces.test.ts +++ b/apps/web/tests/integration/shared-spaces.test.ts @@ -11,6 +11,7 @@ import { } from '../../src/routes/admin/spaces/[kind]/[skey]/+page.server.ts'; import { load as spacesLoad } from '../../src/routes/admin/spaces/+page.server.ts'; import { TestNetwork } from './network.ts'; +import { flagsOff } from '../../src/lib/testing/flags.ts'; const listRecordsOutput = z.object({ records: z.array(z.object({ value: z.object({ subject: z.string() }) })) @@ -92,7 +93,7 @@ describe('shared spaces on a real atproto spaces network', () => { const staff = await net.viewer('mira'); const { kind, skey } = { kind: 'performer', skey: parseSpaceUri(space)!.skey }; const url = new URL(`http://127.0.0.1/admin/spaces/${kind}/${skey}`); - const locals = { app: net.app, viewer: staff, log: silentLogger }; + const locals = { app: net.app, viewer: staff, log: silentLogger, flags: flagsOff }; const list = await spacesLoad({ url, locals, params: {} }); expect(await list.spaces).toMatchObject([{ uri: space, kind, people: 2, listed: true }]); diff --git a/apps/web/tests/integration/sync-notify.test.ts b/apps/web/tests/integration/sync-notify.test.ts index 3a8fa07c1..d3ed1cd69 100644 --- a/apps/web/tests/integration/sync-notify.test.ts +++ b/apps/web/tests/integration/sync-notify.test.ts @@ -8,6 +8,7 @@ import { silentLogger } from '../../src/lib/server/logger.ts'; import { POST as confirmRegistration } from '../../src/routes/xrpc/com.atproto.space.confirmRegistration/+server.ts'; import { POST as notifySpaceUpdate } from '../../src/routes/xrpc/com.atproto.space.notifySpaceUpdate/+server.ts'; import { TestNetwork } from './network.ts'; +import { flagsOff } from '../../src/lib/testing/flags.ts'; const NOTE = 'computer.localnetwork.test.note'; @@ -34,7 +35,7 @@ describe("space updates from a real atproto spaces host, sent to the app's own r const response = route && net - ? await route({ request, locals: { app: net.app, log: silentLogger } }) + ? await route({ request, locals: { app: net.app, log: silentLogger, flags: flagsOff } }) : new Response(null, { status: 503 }); calls.push({ nsid, body: JSON.parse(body), status: response.status }); diff --git a/docs/adr/0018-signed-out-visitors-get-a-rollout-id.md b/docs/adr/0018-signed-out-visitors-get-a-rollout-id.md index 86f7b8e59..604ffefa6 100644 --- a/docs/adr/0018-signed-out-visitors-get-a-rollout-id.md +++ b/docs/adr/0018-signed-out-visitors-get-a-rollout-id.md @@ -2,9 +2,9 @@ The rule that decides a flag buckets a DID, and a signed-out visitor has none, so a percentage only ever counted accounts. That was fine while new features were for signed-in DJs. Public pages are different: most people who see an act, party, venue or event page aren't signed in, so a flag like `spacePages` could only go from a staff preview straight to everyone. -So while any flag is on for a percentage, the website gives a signed-out browser an id of its own: a random version 4 UUID in a first-party cookie, `ln_flag_visitor`, for the site's whole path, `HttpOnly`, `SameSite=Lax`, `Secure` over https, kept for a year. The rule buckets `visitor:` followed by that UUID with the same sum it uses for a DID, so a browser gets the same answer on every request and stays in as the percentage grows. A DID starts `did:`, so a visitor's id is never an account's and is never targeted. `flags/vectors.json` has cases for visitor ids, which locallibrary's test reads as it reads any other id. +So while a flag that changes a public page is on for a percentage, the website gives a signed-out browser an id of its own: a random version 4 UUID in a first-party cookie, `ln_flag_visitor`, for the site's whole path, `HttpOnly`, `SameSite=Lax`, `Secure` over https, kept for a year. The rule buckets `visitor:` followed by that UUID with the same sum it uses for a DID, so a browser gets the same answer on every request and stays in as the percentage grows. A DID starts `did:`, so a visitor's id is never an account's and is never targeted. `flags/vectors.json` has cases for visitor ids, which locallibrary's test reads as it reads any other id. -Nothing else asks differently. `getFlags` and locallibrary ask with a DID or with nothing, and an xrpc call never reads a cookie, so a caller with neither still only gets flags on for everyone. The cookie is only set for a signed-out visitor outside `/xrpc/`, and only while a flag is enabled, not on for everyone, and above 0%. The server uses the id for flags alone and never stores or logs it; a request's log line only says whether the visitor's id was new. +Nothing else asks differently. `getFlags` and locallibrary ask with a DID or with nothing, and an xrpc call never reads a cookie, so a caller with neither still only gets flags on for everyone. The cookie is only set for a signed-out visitor outside `/xrpc/`, and only while a flag with `showsOn` in its catalog file is enabled, not on for everyone, and above 0%. A flag without `showsOn`, like `inboxEmail` or `userinputReports`, changes only what accounts see, so rolling it out to a percentage sets no cookie and keeps signed-out pages shared-cacheable. A flag that does change a public page has to list it in `showsOn`, or signed-out visitors stay out of its percentage. The server uses the id for flags alone and never stores or logs it; a request's log line only says whether the visitor's id was new. A signed-out page that depends on the id can't go in a shared cache. `cacheBriefly` marks signed-out pages `public`, and a visitor's first response sets the cookie, so a cache in front of the site could serve one visitor's answer and their cookie to the next. Nothing caches in front of the site today, but while a visitor id is in use the server hook turns `public` into `private` on the response. Browsers still cache their own copy. @@ -15,6 +15,7 @@ A signed-out page that depends on the id can't go in a shared cache. `cacheBrief - An id in local storage, as LaunchDarkly's browser SDK keeps one: pages are rendered on the server, which can't read it on any request. - Bucketing on the flag key alone, as Statsig does for an empty id: every visitor gets the same answer, so a percentage becomes a switch. - Setting the cookie on every signed-out request: most of the time no flag needs it, and signed-out pages would never be shared-cacheable. +- Setting it while any flag is on for a percentage: a rollout of something only accounts see, like inbox email, would give every signed-out browser a cookie and make every public page private for as long as it ran. - Relying on `Vary: Cookie`, which `cacheBriefly` already sends: a cached first response has no cookie to vary on, and carries its `Set-Cookie` to everyone after. ## Consequences @@ -22,4 +23,4 @@ A signed-out page that depends on the id can't go in a shared cache. `cacheBrief - Signing in moves someone from their browser's bucket to their account's, so a feature can appear or disappear for them at that moment. PostHog documents the same problem. - Crawlers and anything else that drops cookies get a new id on every request, so during a percentage rollout they see the flag on at about that rate. A page that 404s while its flag is off will 404 to a crawler some of the time. `spacePages` writes no directory listing until it's on for everyone, which keeps those pages out of the directory meanwhile. - A visitor can clear or edit the cookie to land somewhere else. Flags are for rolling something out, not for keeping anyone out, so that's allowed. -- While any flag is on for a percentage, no signed-out response outside `/xrpc/` is shared-cacheable. +- While a flag with `showsOn` is on for a percentage, no signed-out response outside `/xrpc/` is shared-cacheable. diff --git a/docs/adr/0019-english-stays-unprefixed-and-records-carry-their-language.md b/docs/adr/0019-english-stays-unprefixed-and-records-carry-their-language.md index ba4578c50..e4413ffe4 100644 --- a/docs/adr/0019-english-stays-unprefixed-and-records-carry-their-language.md +++ b/docs/adr/0019-english-stays-unprefixed-and-records-carry-their-language.md @@ -25,4 +25,4 @@ New CSS uses logical directions (`ms-`, `pe-`, `start-` rather than `ml-`, `pr-` ## Consequences -Each message ships its en-XA text to every visitor next to the English, a few bytes a message. Once most of the site's text is in the catalog, a production build can leave en-XA out. A visitor's browser writes the locale cookie on their first page. Until the rest of the text moves to the catalog, en-XA shows it in plain English, which is what en-XA is for. +Each message ships its en-XA text to every visitor next to the English, a few bytes a message. Once most of the site's text is in the catalog, a production build can leave en-XA out. A visitor's browser writes the locale cookie on their first page, and every answer varies on Cookie for it, except public immutable ones (OG cards, avatars, recordings), which `src/hooks.server.ts` keeps shareable by caches. Until the rest of the text moves to the catalog, en-XA shows it in plain English, which is what en-XA is for. diff --git a/docs/adr/0020-inactive-accounts-are-asked-of-their-pds.md b/docs/adr/0020-inactive-accounts-are-asked-of-their-pds.md index c31168e24..f25b0b56f 100644 --- a/docs/adr/0020-inactive-accounts-are-asked-of-their-pds.md +++ b/docs/adr/0020-inactive-accounts-are-asked-of-their-pds.md @@ -2,11 +2,11 @@ An account that's deactivated, taken down, suspended or deleted shouldn't stay on the site: its profile, its listing in Find DJs, the sets the charts count, its shows. The website reads public records only through HappyView, and HappyView already follows Jetstream's `account` events: at the version production runs (3.0.0-beta.14) it removes the records of an account that's deleted, taken down or suspended and keeps a tombstone that refuses later copies ([`account_event` in src/ingest.rs](https://github.com/gamesgamesgamesgamesgames/happyview/blob/v3.0.0-beta.14/src/ingest.rs), [event logs guide](https://github.com/gamesgamesgamesgamesgames/happyview/blob/v3.0.0-beta.14/packages/docs/content/docs/guides/event-logs.md)). It keeps a deactivated account's records, though, and only logs the event, and no script or query can see an account's status. When a taken-down account comes back, its records return only with a new backfill. -So the app asks the account's PDS, the one its DID document names, with `com.atproto.sync.getRepoStatus`. `AccountStatuses` (`src/lib/server/atproto/account-status.ts`) keeps each answer in memory for half an hour. A profile or set page asks for its one account: an inactive account's page answers 404 saying the account isn't active, whatever the reason, and a deleted one's 410. For Find DJs, the charts, artist pages, linked sets and show listings, it checks every account the directory reads (the managers of the root's projects and the DJs staff list), eight at a time, and passes the inactive ones to those queries as an `inactive` param. The queries leave out those accounts' records. Only the first check after a start is waited for. After that a page gets the last list while a fresh one is made in the background, so no page waits on someone else's PDS. +So the app asks the account's PDS, the one its DID document names, with `com.atproto.sync.getRepoStatus`. The DID resolver caches documents, and the PDS an account just moved away from answers `RepoNotFound` or deactivated, so an inactive answer is checked against a freshly fetched document and, when that names another PDS, asked again of that one. `AccountStatuses` (`src/lib/server/atproto/account-status.ts`) keeps each answer in memory for half an hour. A profile or set page asks for its one account: an inactive account's page answers 404 saying the account isn't active, whatever the reason, and a deleted one's 410. For Find DJs, the charts, artist pages, linked sets and show listings, it checks every account the directory reads (the managers of the root's projects and the DJs staff list), eight at a time, and passes the deactivated, taken-down and suspended ones to those queries as an `inactive` param, which takes at most 100. The queries leave out those accounts' records. Deleted accounts aren't sent, since HappyView already dropped their records. No page waits for that check: a page gets the last list while a fresh one is made in the background, so after a restart inactive accounts can show until the first check finishes, usually within seconds. -A PDS that can't be asked leaves the account as it was last seen, or active if it was never seen, and the failure is logged: the site fails open. A deleted account stays deleted in memory, and HappyView has removed its records for good, so no table is kept. When an account that was taken down or suspended turns up active again, the app has HappyView re-read its records. +A PDS that can't be asked leaves the account as it was last seen, or active if it was never seen, and the failure is logged: the site fails open. A deleted account is asked again every half hour like any other, since right after a move between PDSes an account can look deleted. HappyView's tombstone keeps a really deleted account's records out, so no table is kept. When an account that was taken down or suspended turns up active again, the app has HappyView re-read its records. -The cost is one request per directory account every half hour, and only while people look at the pages. A deactivated account leaves the lists, and comes back, up to half an hour late. +The cost is one request per directory account every half hour, and only while people look at the pages, plus a fresh DID document for each account found inactive. Opening a profile or set page asks that account's PDS too, and the answer is kept for 30 minutes. A deactivated account leaves the lists, and comes back, up to half an hour late. ## Considered options diff --git a/docs/research/feature-flag-platforms.md b/docs/research/feature-flag-platforms.md index 19c728779..f620fa0fe 100644 --- a/docs/research/feature-flag-platforms.md +++ b/docs/research/feature-flag-platforms.md @@ -16,7 +16,7 @@ Every platform in the set evaluates a flag the same way: it checks for a kill or | Reusable audiences | Segments, cohorts, saved groups, often rule-based | Named groups of up to 5000 DIDs | No rule-based membership | No | | Exclusions | Segment `excluded` lists (LD), "none of" (Statsig), `NONE` rules (Flagsmith) | None: any matching gate turns a flag on | Can't pull one account out of a rollout | Low | | Percentage rollout | Hash of salt plus stable id into 100 to 100,000 buckets | `sha256(key + did)`, first 4 bytes, mod 100, which ADR 0006 has locallibrary apply too | Coarse 1% steps, no re-salt | No | -| Signed-out visitors | Random device keys (LD, PostHog), random fallback (Unleash), bucket on salt alone (Statsig) | A random id in a first-party cookie while a flag is on for a percentage, bucketed like a DID | None | None | +| Signed-out visitors | Random device keys (LD, PostHog), random fallback (Unleash), bucket on salt alone (Statsig) | A random id in a first-party cookie while a public-page flag is on for a percentage, bucketed like a DID | None | None | | Prerequisites | Flag-on-flag dependencies in LD, Statsig, FME, ConfigCat, PostHog, GrowthBook, Unleash | None | None | No | | Kill switch | A dedicated off state that keeps targeting (LD off variation, FME kill, flagd `DISABLED`, GOFF `disable`) | `enabled: false` on the record, which keeps groups, accounts and percentage | None | Done | | Server evaluation | Full ruleset in memory, no network per check | Snapshot from SQLite, reloaded after each write or sync | None | No | @@ -123,7 +123,7 @@ Local Network had the hard half from the start. Deleting a catalog file breaks t Each `flags/catalog/.json` has a `type`: `release`, `experiment`, `ops` or `permission`. Release and experiment flags must have a `removeBy` date (YYYY-MM-DD), and the other types can't have one. A unit test fails once a flag is past its `removeBy`, naming the flag. `parityCanary` is `ops`. -The `/admin/flags` list marks a flag "Ready to remove" when it's enabled and either on for everyone or at 100%, and its record's `updatedAt` is 30 or more days old. That's PostHog's definition, worked out from fields already stored. Any saved change resets `updatedAt`, so editing a fully rolled-out flag starts its 30 days again. +The `/admin/flags` list marks a release flag "Ready to remove" when it's enabled and either on for everyone or at 100%, and its record's `updatedAt` is 30 or more days old. That's PostHog's definition, worked out from fields already stored. Any saved change resets `updatedAt`, so editing a fully rolled-out flag starts its 30 days again. Evaluation counts, the signal Unleash and LaunchDarkly lean on, would be useless here: the server hook evaluates every catalog flag on every request ([hooks.server.ts](https://github.com/cutenode/localnetwork/blob/2f9d6c93a3b8dbb68fae3b9806ab85af26398ea5/apps/web/src/hooks.server.ts#L103)), so every flag would always look in use. Exposure events and experiments, which LaunchDarkly, Statsig, FME, PostHog and GrowthBook build on top of evaluation logs ([PostHog exposures](https://posthog.com/docs/experiments/exposures); [GrowthBook results](https://docs.growthbook.io/app/experiment-results)), have no use here without an analytics pipeline, and the glossary's rollout-only scope rules them out anyway. diff --git a/flags/README.md b/flags/README.md index 2a7636785..6427fbeee 100644 --- a/flags/README.md +++ b/flags/README.md @@ -6,9 +6,9 @@ Every flag has a `type`, `release` or `ops`. A `release` flag is meant to go, so A flag nobody has saved reads as off, so name a flag for the state you can switch it to. A kill switch, for something that already works, is named for the paused state, like `pauseRecordingStream`, and is `ops`: the deploy that adds it changes nothing, and turning it on stops the feature. Something that's dark today and should stay switchable after it ships, like inbox email, is named for the on state and is `ops` too, so it has no `removeBy`. Use `release` only for flags that go once the rollout is done. -A flag can list the kinds of page it changes in `showsOn`: `profile`, `act`, `party`, `venue`, `event`, `set`, `mix` or `pressKit`, or `global` for every page. An act's page is still `/projects/` until acts move. The flag's page in the staff console lists them under Shows on. Leave it out when the flag changes no public page, like a kill switch for the token exchange or something in the dashboard. +A flag can list the kinds of page it changes in `showsOn`: `profile`, `act`, `party`, `venue`, `event`, `set`, `mix` or `pressKit`, or `global` for every page. An act's page is still `/projects/` until acts move. The flag's page in the staff console lists them under Shows on. Leave it out when the flag changes no public page, like a kill switch for the token exchange, something in the dashboard, or anything only signed-in accounts see. It also decides whether signed-out visitors are counted in a percentage: only a flag with `showsOn` gives them a rollout id. -Who a flag is on for lives in the staff space and is set at `/admin/flags`, not here. Every flag starts off. The list there marks a flag "Ready to remove" once it's been on for everyone, or every account, for 30 days. +Who a flag is on for lives in the staff space and is set at `/admin/flags`, not here. Every flag starts off. The list there marks a release flag "Ready to remove" once it's been on for everyone, or every account, for 30 days, and its page shows when it should be gone by. ```jsonc { @@ -32,7 +32,7 @@ bucket(key, id) = the first 4 bytes of sha256(key + id), big-endian, mod 100 on = enabled && (everyone || targeted || (id is known && bucket(key, id) < percentage)) ``` -`enabled` is false once someone turns the flag off for everyone, which keeps the other gates for when it's back on. A record that doesn't say is enabled. `targeted` means the account is one of the flag's accounts or in one of its groups. Only the website can know that, since those lists are private; it says so through `computer.localnetwork.flags.getFlags`. `id` is the caller's DID. A signed-out visitor has none, so while any flag is on for a percentage the website gives their browser a random id in a first-party cookie, `ln_flag_visitor`, and buckets `visitor:` followed by it. They get the same answer on every request until they clear it or sign in, when their account's bucket takes over. A caller with neither, like an xrpc call, only gets flags on for everyone. Raising a percentage only adds accounts and browsers. [ADR 0018](../docs/adr/0018-signed-out-visitors-get-a-rollout-id.md) covers why, and what it means for caching and crawlers. +`enabled` is false once someone turns the flag off for everyone, which keeps the other gates for when it's back on. A record that doesn't say is enabled. `targeted` means the account is one of the flag's accounts or in one of its groups. Only the website can know that, since those lists are private; it says so through `computer.localnetwork.flags.getFlags`. `id` is the caller's DID. A signed-out visitor has none, so while a flag with `showsOn` is on for a percentage the website gives their browser a random id in a first-party cookie, `ln_flag_visitor`, and buckets `visitor:` followed by it. They get the same answer on every request until they clear it or sign in, when their account's bucket takes over. A caller with neither, like an xrpc call, only gets flags on for everyone. Raising a percentage only adds accounts and browsers. [ADR 0018](../docs/adr/0018-signed-out-visitors-get-a-rollout-id.md) covers why, and what it means for caching and crawlers. `vectors.json` holds computed answers, for DIDs, visitor ids and callers with neither. The website's and locallibrary's tests both run them, so the two can't come to disagree. A case without `enabled` is enabled. If a case has to change, the rule changed, and accounts will move in or out of every rollout. diff --git a/flags/catalog/parityCanary.json b/flags/catalog/parityCanary.json index 730778e2c..369332f90 100644 --- a/flags/catalog/parityCanary.json +++ b/flags/catalog/parityCanary.json @@ -2,6 +2,5 @@ "$schema": "../flag.schema.json", "key": "parityCanary", "description": "Gates nothing. Turn it on for an account to check that the website and locallibrary give it the same answer.", - "type": "ops", - "showsOn": ["profile"] + "type": "ops" } diff --git a/flags/catalog/pauseBackfills.json b/flags/catalog/pauseBackfills.json index 8a6f48470..4c2bec1ef 100644 --- a/flags/catalog/pauseBackfills.json +++ b/flags/catalog/pauseBackfills.json @@ -1,6 +1,6 @@ { "$schema": "../flag.schema.json", "key": "pauseBackfills", - "description": "Stops the site asking HappyView to re-read repos: the refresh at start and on the directory sync round, and the set picker, carry on with what HappyView already has. Turn it on for everyone: the refreshes have no account to check.", + "description": "Stops the site asking HappyView to re-read repos: refreshes, the set picker, requestIndex and re-reads after a write carry on with what HappyView has. The root's performers are still re-read at start. Turn it on for everyone.", "type": "ops" } diff --git a/flags/catalog/pauseOgCards.json b/flags/catalog/pauseOgCards.json index 0293af785..8feefe53f 100644 --- a/flags/catalog/pauseOgCards.json +++ b/flags/catalog/pauseOgCards.json @@ -2,5 +2,6 @@ "$schema": "../flag.schema.json", "key": "pauseOgCards", "description": "Stops drawing link-preview cards for performers, mixes, press kits and artists: pages point their preview at the site's card, and a card not already kept in memory redirects there. Turn it on for everyone: crawlers are signed out.", - "type": "ops" + "type": "ops", + "showsOn": ["profile", "act", "mix", "pressKit"] } diff --git a/flags/catalog/pauseReconcilers.json b/flags/catalog/pauseReconcilers.json index a8374ed35..ee295bcac 100644 --- a/flags/catalog/pauseReconcilers.json +++ b/flags/catalog/pauseReconcilers.json @@ -1,6 +1,6 @@ { "$schema": "../flag.schema.json", "key": "pauseReconcilers", - "description": "Stops the rounds that fix drift in the root's repo (manager, staff and shared spaces, listings, venue blocks and calendar copies), at start and every round after. Turn it on for everyone: the rounds have no account to check.", + "description": "Stops the rounds that write to the root's repo to fix drift (manager, staff and shared spaces, listings and calendar copies), at start and every round after. Turn it on for everyone. On a fresh database, the first rounds at start run before this is read.", "type": "ops" } diff --git a/flags/catalog/pauseRecordingStream.json b/flags/catalog/pauseRecordingStream.json index acde9ddcc..3589f6ea5 100644 --- a/flags/catalog/pauseRecordingStream.json +++ b/flags/catalog/pauseRecordingStream.json @@ -2,5 +2,6 @@ "$schema": "../flag.schema.json", "key": "pauseRecordingStream", "description": "Stops the site streaming recordings from DJs' servers: the audio route answers 503 without reading anything, and set and mix players play the links instead. plyr.fm recordings still play. Turn it on for everyone: most listeners are signed out.", - "type": "ops" + "type": "ops", + "showsOn": ["set", "mix"] } From eec0cdc834d63240a6187c2aee01e345f431db2e Mon Sep 17 00:00:00 2001 From: botandbang <337765928+botandbang@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:58:27 -0600 Subject: [PATCH 09/22] feat(web): add the home page to the kinds of page a flag shows on socialHome changes the public home page, which had no kind to list, so its flag page said "None listed". The list in lib/flags/shows-on.ts gains home, the generated schema follows, and socialHome lists it. Fixes LOC-655 --- apps/web/src/lib/flags/shows-on.ts | 4 +++- flags/catalog/socialHome.json | 3 ++- flags/flag.schema.json | 4 ++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/apps/web/src/lib/flags/shows-on.ts b/apps/web/src/lib/flags/shows-on.ts index 61be73ef7..b22e29f0a 100644 --- a/apps/web/src/lib/flags/shows-on.ts +++ b/apps/web/src/lib/flags/shows-on.ts @@ -1,9 +1,11 @@ /** * The kinds of page a flag can show on (its `showsOn` in flags/catalog), with what the staff console calls each: - * `global` for every page, or one of the glossary's page types. `act` is `/projects/` until acts move. + * `global` for every page, `home` for the home page, or one of the glossary's page types. `act` is `/projects/` + * until acts move. */ export const SHOWS_ON = { global: 'Every page', + home: 'Home page', profile: 'Profile', act: 'Act', party: 'Party', diff --git a/flags/catalog/socialHome.json b/flags/catalog/socialHome.json index ffb2d2c60..e0b27d23f 100644 --- a/flags/catalog/socialHome.json +++ b/flags/catalog/socialHome.json @@ -3,5 +3,6 @@ "key": "socialHome", "description": "The home page built around events near you and your network, in place of the one for booking DJs. Turn it on with event pages and RSVPs.", "type": "release", - "removeBy": "2027-02-12" + "removeBy": "2027-02-12", + "showsOn": ["home"] } diff --git a/flags/flag.schema.json b/flags/flag.schema.json index 0bb902162..d078b6388 100644 --- a/flags/flag.schema.json +++ b/flags/flag.schema.json @@ -26,7 +26,7 @@ "type": "array", "items": { "type": "string", - "enum": ["global", "profile", "act", "party", "venue", "event", "set", "mix", "pressKit"] + "enum": ["global", "home", "profile", "act", "party", "venue", "event", "set", "mix", "pressKit"] } }, "type": { @@ -68,7 +68,7 @@ "type": "array", "items": { "type": "string", - "enum": ["global", "profile", "act", "party", "venue", "event", "set", "mix", "pressKit"] + "enum": ["global", "home", "profile", "act", "party", "venue", "event", "set", "mix", "pressKit"] } }, "type": { From 27a1681d495b5ab2ff9042a02bb6e777fc074adb Mon Sep 17 00:00:00 2001 From: botandbang <337765928+botandbang@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:58:28 -0600 Subject: [PATCH 10/22] docs(web): show how the repo export cap was sized from production Production's largest repo before launch was the root's in the audit space: 60 entries in 40,548 bytes, 676 a piece. At that size the 256 MiB cap holds about 397,000 entries, a year at 1,000 audited actions a day, and a single entry can reach about 820 KiB under the lexicon's limits. The comment beside REPO_EXPORT_MAX_BYTES now gives that arithmetic. Fixes LOC-254 --- apps/web/src/lib/server/sync/engine.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/apps/web/src/lib/server/sync/engine.ts b/apps/web/src/lib/server/sync/engine.ts index 4bfb552dc..1d19fc775 100644 --- a/apps/web/src/lib/server/sync/engine.ts +++ b/apps/web/src/lib/server/sync/engine.ts @@ -160,11 +160,13 @@ const MAX_PAGES = 100; /** * The most of a repo export (`getRepo`) one download reads, in bytes. Every record in it is held in memory until the - * download is applied, and a hostile repo host could send one that never ends. A record is at most 1 MiB - * (@atproto/space's MAX_RECORD_SIZE), but the records this app writes are a few KiB at most. The largest repo is the - * root's in the audit space, which gains an entry for every audited action, most well under 1 KiB, so this holds a - * few hundred thousand of them, many times what any repo here is expected to hold. A repo past it fails and waits - * for its retry like any other, and the system page shows it. + * download is applied, and a hostile repo host could send one that never ends. The largest repo is the root's in the + * audit space, which gains an entry for every audited action and never shrinks. On production before launch its 60 + * entries came to 40,548 bytes, 676 a piece, so this holds about 397,000 of them: a year at 1,000 audited actions a + * day. A single entry can reach about 820 KiB under the lexicon's limits (100 changes of two 4,000-byte values, and a + * 10,000-byte reason), and any record is at most 1 MiB (@atproto/space's MAX_RECORD_SIZE), so a repo of rare large + * entries still fits a few hundred. Members' repos in shared spaces hold a few KiB each. A repo past it fails and + * waits for its retry like any other, and the system page shows it. */ const REPO_EXPORT_MAX_BYTES = 256 * 1024 * 1024; From 359538380f555ae1e0e8a2f0279ad7c79cf8a85d Mon Sep 17 00:00:00 2001 From: botandbang <337765928+botandbang@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:58:29 -0600 Subject: [PATCH 11/22] feat(web): turn a flag on for signed-out visitors last, as its own setting A percentage of signed-out visitors, with a random id in a cookie, gave way to a setting of its own: signed-out visitors get a flag only once staff tick Signed-out visitors on its page, which they can do only after it's on for every signed-in account. A save that takes it below every account turns it off again. With no DID a flag is on when it's enabled, signedOut is on and it's on for everyone or at 100%; with a DID nothing changes. An ops flag's signedOut follows everyone, so kill switches still reach xrpc routes, background rounds and signed-out locallibrary. The staff flag record and getFlags carry the gate, migration 023 stores it, flags/vectors.json and locallibrary's rule follow, and "Ready to remove" waits for signed-out visitors too. The visitor cookie, its private caching, the crawler hint and its row on the privacy page are gone, and ADR 0018 records the choice. The flag list shows a release flag's remove-by date and "Signed-out visitors next" once every account has it, and links its recent changes in the audit log. The glossary and flags README also list the home page kind. Fixes LOC-321 --- GLOSSARY.md | 6 +- apps/locallibrary/docs/account.md | 4 +- apps/web/README.md | 4 +- apps/web/docs/diagrams/flags.md | 36 +++-- apps/web/docs/diagrams/requests-and-routes.md | 6 +- apps/web/docs/diagrams/staff-and-upkeep.md | 2 +- apps/web/src/app.d.ts | 2 +- apps/web/src/hooks.server.test.ts | 146 +----------------- apps/web/src/hooks.server.ts | 21 +-- .../lib/components/FlagTable.stories.svelte | 7 +- apps/web/src/lib/components/FlagTable.svelte | 19 ++- .../lib/components/flag-tables.svelte.test.ts | 36 ++++- apps/web/src/lib/server/db/migrations.ts | 6 + apps/web/src/lib/server/db/schema.ts | 2 + .../web/src/lib/server/flags/evaluate.test.ts | 69 ++++++--- apps/web/src/lib/server/flags/evaluate.ts | 40 +++-- .../src/lib/server/flags/get-flags.test.ts | 9 +- apps/web/src/lib/server/flags/visitor.ts | 30 ---- apps/web/src/lib/server/forms/flags.ts | 1 + .../web/src/lib/server/services/flags.test.ts | 136 ++++++++++++---- apps/web/src/lib/server/services/flags.ts | 91 +++++++---- .../src/lib/server/services/listings.test.ts | 8 +- apps/web/src/lib/server/services/listings.ts | 5 +- apps/web/src/lib/testing/flags.ts | 2 +- apps/web/src/lib/types.ts | 7 +- apps/web/src/routes/admin/flags/+page.svelte | 6 +- .../src/routes/admin/flags/[key]/+page.svelte | 27 +++- .../admin/flags/[key]/page.stories.svelte | 47 +++++- .../admin/flags/[key]/page.svelte.test.ts | 57 ++++++- .../routes/admin/flags/page.server.test.ts | 23 +++ .../routes/admin/flags/page.svelte.test.ts | 17 ++ apps/web/src/routes/privacy/+page.svelte | 1 - .../server.test.ts | 24 ++- .../src/atmosphere/flags/tests.rs | 14 +- crates/locallibrary/src/flags.rs | 16 +- crates/locallibrary/src/flags/tests.rs | 60 +++++-- crates/locallibrary/tests/support/mock_pds.rs | 11 +- .../adr/0018-signed-out-visitors-come-last.md | 24 +++ ...18-signed-out-visitors-get-a-rollout-id.md | 26 ---- docs/research/feature-flag-platforms.md | 34 ++-- flags/README.md | 17 +- flags/catalog/spacePages.json | 2 +- flags/vectors.json | 84 +++++++--- .../computer/localnetwork/flags/getFlags.json | 8 +- .../computer/localnetwork/staff/flag.json | 6 +- 45 files changed, 763 insertions(+), 436 deletions(-) delete mode 100644 apps/web/src/lib/server/flags/visitor.ts create mode 100644 apps/web/src/routes/admin/flags/page.svelte.test.ts create mode 100644 docs/adr/0018-signed-out-visitors-come-last.md delete mode 100644 docs/adr/0018-signed-out-visitors-get-a-rollout-id.md diff --git a/GLOSSARY.md b/GLOSSARY.md index 5d13a604b..c804f8e15 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -53,11 +53,11 @@ The separate area where staff moderate and run the site. Only staff can see it. _Avoid_: admin dashboard, admin panel **Flag**: -A switch that turns a feature on for some people before everyone. The website and locallibrary share its key and give an account the same answer. Staff set who it's on for in the staff console. Flags are for rolling something out, not for keeping anyone out. Turning one off for everyone keeps who it was on for, ready for when it's back on. A flag can say which kinds of page it shows on, so staff can switch it from there. +A switch that turns a feature on for some people before everyone. The website and locallibrary share its key and give an account the same answer. Staff set who it's on for in the staff console. Flags are for rolling something out, not for keeping anyone out. Turning one off for everyone keeps who it was on for, ready for when it's back on. Signed-out visitors come last, through a switch of their own that waits until every account has the flag; a kill switch reaches them whenever it's on for everyone. A flag can say which kinds of page it shows on, so staff can switch it from there. _Avoid_: feature toggle, experiment, setting **Shows on**: -The kinds of page a flag changes: profiles, acts, parties, venues, events, sets, mixes or press kits, or every page. Each flag lists its own in the catalog, and its page in the staff console shows them. +The kinds of page a flag changes: the home page, profiles, acts, parties, venues, events, sets, mixes or press kits, or every page. Each flag lists its own in the catalog, and its page in the staff console shows them. _Avoid_: contexts, placement, scope **Flag group**: @@ -73,7 +73,7 @@ A flag that stops something that already works while it's on. It's named for the _Avoid_: circuit breaker, pause flag **Rollout**: -The share of people a flag is on for: accounts, and signed-out visitors once per browser. Anyone in stays in as the share grows, and has the same chance of being in on every flag. A visitor who signs in counts as their account from then on. +The share of signed-in accounts a flag is on for. An account stays in as the share grows, and has the same chance of being in on every flag. Signed-out visitors are never counted: they get a flag all at once, and only after every account has it. _Avoid_: percentage (in copy), canary, staged release ## People and acts diff --git a/apps/locallibrary/docs/account.md b/apps/locallibrary/docs/account.md index fedafa7a6..b0339ce2a 100644 --- a/apps/locallibrary/docs/account.md +++ b/apps/locallibrary/docs/account.md @@ -188,7 +188,9 @@ locallibrary account flags --refresh # ask now Local Network turns new things on for some accounts first, with the same flags on the website and here. A flag is on when it's on for everyone, when it names your account or a group you're in, or when your DID falls inside its percentage, the sum the website does (`flags/README.md` in the repo). -Signed out, only flags on for everyone are on. A flag staff turned off is off for everyone. +Signed out, a flag is on only once it's on for signed-out visitors: staff turn that on last, after +every account has it, and a kill switch has it whenever it's on for everyone. A flag staff turned +off is off for everyone. Only a command that depends on a flag asks, and nothing else goes to the network because of them. The website's answer is kept in `flags.json` in the store folder for an hour, or until the next diff --git a/apps/web/README.md b/apps/web/README.md index e45c8186f..5b99fdd64 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -82,11 +82,11 @@ All data lives on the AT Protocol. Public profiles are ordinary atproto records; ### Flags -A flag turns a feature on for some people before everyone. The flags themselves are files in [`flags/catalog/`](../../flags/README.md), which locallibrary reads too. Staff set who each is on for at `/admin/flags`: everyone, a percentage of people, [flag groups](../../GLOSSARY.md) at `/admin/flags/groups`, or single accounts. "Off for everyone" turns a flag off and keeps all of that for when it's back on. Admins manage all of it, and on the Staff page they can give a moderator either part: flags, or flag groups. Every change is in the audit log. The list marks a release flag "Ready to remove" once it's been on for everyone, or every account, for 30 days. +A flag turns a feature on for some people before everyone. The flags themselves are files in [`flags/catalog/`](../../flags/README.md), which locallibrary reads too. Staff set who each is on for at `/admin/flags`: every account, a percentage of accounts, [flag groups](../../GLOSSARY.md) at `/admin/flags/groups`, or single accounts, and then signed-out visitors. "Off for everyone" turns a flag off and keeps all of that for when it's back on. Admins manage all of it, and on the Staff page they can give a moderator either part: flags, or flag groups. Every change is in the audit log. The list marks a release flag "Ready to remove" once every account and signed-out visitors have had it for 30 days. To see a flag without changing it for anyone, staff with the flags grant can turn it on or off for their own browser from its page. The preview is a cookie signed with their session, lasts an hour, shows a banner on every page until it's cleared, and is audited. In development and tests, `FLAG_OVERRIDES=key=on,other=off` forces flags for every request instead; the app won't start with it in production ([ADR 0010](../../docs/adr/0010-flags-turn-off-and-preview-without-touching-targeting.md)). -What's set is kept as `staff.flag` and `staff.group` records in the staff space, indexed into SQLite and held in memory, so reading one on a request costs nothing. Pages read `data.flags?.key` and server code `locals.flags.key`, worked out once per request. A signed-out visitor counts in a percentage by a random id in the `ln_flag_visitor` cookie, set only while a flag that changes a public page (one with `showsOn`) is on for one ([ADR 0018](../../docs/adr/0018-signed-out-visitors-get-a-rollout-id.md)). locallibrary can't read the staff space, so `computer.localnetwork.flags.getFlags` tells it the public gates and whether it's targeted ([ADR 0006](../../docs/adr/0006-locallibrary-asks-the-website-for-flags.md)). +What's set is kept as `staff.flag` and `staff.group` records in the staff space, indexed into SQLite and held in memory, so reading one on a request costs nothing. Pages read `data.flags?.key` and server code `locals.flags.key`, worked out once per request. A signed-out visitor gets a release flag only once staff turn it on for them, which waits until every account has it; an ops flag reaches them whenever it's on for everyone ([ADR 0018](../../docs/adr/0018-signed-out-visitors-come-last.md)). locallibrary can't read the staff space, so `computer.localnetwork.flags.getFlags` tells it the public gates and whether it's targeted ([ADR 0006](../../docs/adr/0006-locallibrary-asks-the-website-for-flags.md)). ### Staff diff --git a/apps/web/docs/diagrams/flags.md b/apps/web/docs/diagrams/flags.md index df3f0e4d5..f5d44364f 100644 --- a/apps/web/docs/diagrams/flags.md +++ b/apps/web/docs/diagrams/flags.md @@ -10,42 +10,41 @@ Deciding a flag, flags on each request, getFlags, the staff console and the flag ## Deciding a flag -Whether one flag is on for one caller. Only flags in `flags/catalog/` exist: a record for a flag that's gone from it is ignored. +Whether one flag is on for one caller. Only flags in `flags/catalog/` exist: a record for a flag that's gone from it is ignored. A caller with no DID comes last. `signedOut` is worked out as the record is read: an ops flag's is its `everyone`, and a release flag's only holds while every account has it. ```mermaid flowchart TD - Ask["A catalog flag, for a DID, a signed-out
visitor's id, or no id"] --> Forced{"In FLAG_OVERRIDES?"} + Ask["A catalog flag, for a DID
or a signed-out visitor"] --> Forced{"In FLAG_OVERRIDES?"} Forced -- "forced on" --> On["On"] Forced -- "forced off" --> Off["Off"] Forced -- "no" --> Record{"A staff.flag record?"} Record -- "no" --> Off Record -- "yes" --> Enabled{"enabled?"} Enabled -- "no" --> Off - Enabled -- "yes" --> Everyone{"everyone?"} + Enabled -- "yes" --> Caller{"A DID?"} + Caller -- "no" --> SignedOut{"signedOut, and everyone
or 100%?"} + SignedOut -- "yes" --> On + SignedOut -- "no" --> Off + Caller -- "yes" --> Everyone{"everyone?"} Everyone -- "yes" --> On Everyone -- "no" --> Targeted{"The DID is in its accounts
or one of its groups?"} Targeted -- "yes" --> On - Targeted -- "no" --> Bucket{"An id, and SHA-256 of key + id,
mod 100, under percentage?"} + Targeted -- "no" --> Bucket{"SHA-256 of key + DID,
mod 100, under percentage?"} Bucket -- "yes" --> On Bucket -- "no" --> Off ``` -Source: [`src/lib/server/flags/evaluate.ts`](../../src/lib/server/flags/evaluate.ts), [`src/lib/server/flags/visitor.ts`](../../src/lib/server/flags/visitor.ts), [`src/lib/server/services/flags.ts`](../../src/lib/server/services/flags.ts), [`src/lib/server/flags/catalog.ts`](../../src/lib/server/flags/catalog.ts), [`src/lib/server/config.ts`](../../src/lib/server/config.ts) +Source: [`src/lib/server/flags/evaluate.ts`](../../src/lib/server/flags/evaluate.ts), [`src/lib/server/services/flags.ts`](../../src/lib/server/services/flags.ts), [`src/lib/server/flags/catalog.ts`](../../src/lib/server/flags/catalog.ts), [`src/lib/server/config.ts`](../../src/lib/server/config.ts) ## Flags on a page request -Every request gets every flag decided once, held in memory between record changes. An `/xrpc` call never reads a cookie, so it only gets flags on for everyone. A signed-out visitor gets an id of their own while a flag that changes a public page (one with `showsOn`) is on for a percentage, and their response stays out of shared caches. A staff member's preview changes only their own browser. +Every request gets every flag decided once, held in memory between record changes. An `/xrpc` call never reads the sign-in cookie, so it gets a signed-out visitor's flags. A staff member's preview changes only their own browser. ```mermaid flowchart TD - Request["A request"] -- "/xrpc" --> Route["Every flag with no id,
locals.flags for the route, no preview"] - Request -- "signed in" --> Decide["Decide every flag for the viewer"] - Request -- "signed out" --> Share{"A flag with showsOn
on for a percentage?"} - Share -- "no" --> Nobody["Decide every flag with no id"] - Share -- "yes" --> Visitor["ln_flag_visitor, set if missing:
decide for its visitor id,
no public caching"] - Decide --> Cookie{"ln_flag_preview set?"} - Nobody --> Cookie - Visitor --> Cookie + Request["A request"] --> Decide["Decide every flag for the viewer,
or for a signed-out visitor"] + Decide -- "/xrpc, always signed out" --> Route["locals.flags for the route,
no preview"] + Decide -- "not /xrpc" --> Cookie{"ln_flag_preview set?"} Cookie -- "no" --> Locals["locals.flags, passed to
every page by the root layout"] Cookie -- "yes" --> Valid{"Signed with this session, for this viewer,
under an hour old, and they hold flags?"} Valid -- "yes" --> Merge["Previewed flags replace theirs,
with a banner on every page"] @@ -54,7 +53,7 @@ flowchart TD Drop --> Locals ``` -Source: [`src/hooks.server.ts`](../../src/hooks.server.ts), [`src/lib/server/flags/visitor.ts`](../../src/lib/server/flags/visitor.ts), [`src/lib/server/flags/preview.ts`](../../src/lib/server/flags/preview.ts), [`src/lib/server/services/flags.ts`](../../src/lib/server/services/flags.ts), [`src/routes/+layout.server.ts`](../../src/routes/+layout.server.ts), [`src/routes/+layout.svelte`](../../src/routes/+layout.svelte) +Source: [`src/hooks.server.ts`](../../src/hooks.server.ts), [`src/lib/server/flags/preview.ts`](../../src/lib/server/flags/preview.ts), [`src/lib/server/services/flags.ts`](../../src/lib/server/services/flags.ts), [`src/routes/+layout.server.ts`](../../src/routes/+layout.server.ts), [`src/routes/+layout.svelte`](../../src/routes/+layout.svelte) ## getFlags @@ -80,11 +79,13 @@ Source: [`src/routes/xrpc/computer.localnetwork.flags.getFlags/+server.ts`](../. ## Changing flags -What `/admin/flags` writes. Admins hold both grants; a moderator holds what an admin gives them on `/admin/staff`. Each write is audited, and saving a flag or a group unchanged writes nothing. +What `/admin/flags` writes. Admins hold both grants; a moderator holds what an admin gives them on `/admin/staff`. Each write is audited, and saving a flag or a group unchanged writes nothing. A save writes an ops flag's `signedOut` as its `everyone`, and a release flag's as off while it's below every account. ```mermaid flowchart TD - Flag["/admin/flags/[key]"] -- "save, needs flags" --> PutFlag["Put staff.flag in the staff space,
keyed by the flag"] + Flag["/admin/flags/[key]"] -- "save, needs flags" --> Last{"Signed-out visitors ticked for a
release flag that had them off,
below every account?"} + Last -- "yes" --> TooSoon["Refused: turn it on
for every account first"] + Last -- "no" --> PutFlag["Put staff.flag in the staff space,
keyed by the flag"] Flag -- "preview on, off or clear,
needs flags" --> Preview["ln_flag_preview for an hour,
audited as flag.preview"] Groups["/admin/flags/groups"] -- "create or edit,
needs flagGroups" --> PutGroup["Put staff.group in the staff space"] Groups -- "delete, needs flagGroups" --> InUse{"A flag targets it?"} @@ -113,6 +114,7 @@ erDiagram feature_flag { text key PK integer enabled + integer signed_out integer everyone integer percentage text group_rkeys diff --git a/apps/web/docs/diagrams/requests-and-routes.md b/apps/web/docs/diagrams/requests-and-routes.md index c57c8700e..0caa766f0 100644 --- a/apps/web/docs/diagrams/requests-and-routes.md +++ b/apps/web/docs/diagrams/requests-and-routes.md @@ -31,7 +31,7 @@ flowchart TD Load --> Limit["Write limit for this address"] Limit -- "over it" --> Slow["429"] Limit --> Session["ln_session to a viewer,
skipped on /xrpc/"] - Session --> Flags["Flags for the viewer, a signed-out visitor's
ln_flag_visitor id while a flag with showsOn
is on for a percentage, no id on /xrpc/, and a staff
preview from ln_flag_preview off it"] + Session --> Flags["Flags for the viewer, a signed-out
visitor's on /xrpc/, and a staff preview
from ln_flag_preview off it"] Flags --> Guard["guardArea by route"] Guard -- "/dashboard or /admin,
signed out" --> Login["303 to /login?next="] Guard -- "/admin, not staff" --> Refused["403"] @@ -68,7 +68,7 @@ Source: [`src/routes/+layout.server.ts`](../../src/routes/+layout.server.ts), [` ## Response caching -What each response lets a browser or a shared cache keep. Pages that show the same thing to everyone use `cacheBriefly`. While a flag that changes a public page is on for a percentage, the server hook turns `public` into `private` on every response to a signed-out visitor outside `/xrpc/`, since their flags come from their own `ln_flag_visitor` cookie. +What each response lets a browser or a shared cache keep. Pages that show the same thing to everyone use `cacheBriefly`. ```mermaid flowchart LR @@ -87,7 +87,7 @@ flowchart LR Responses -- "/healthz, token exchange, audit export,
getFlags with a token, paused cards
and recordings" --> Never["no-store"] ``` -Source: [`src/lib/server/http.ts`](../../src/lib/server/http.ts), [`src/hooks.server.ts`](../../src/hooks.server.ts), [`src/routes/charts/+page.server.ts`](../../src/routes/charts/+page.server.ts), [`src/routes/venue/[key]/[[name]]/+page.server.ts`](../../src/routes/venue/[key]/[[name]]/+page.server.ts), [`src/routes/projects/[slug]/mixes/[n]/+page.server.ts`](../../src/routes/projects/[slug]/mixes/[n]/+page.server.ts), [`src/routes/media/[did]/[cid]/+server.ts`](../../src/routes/media/[did]/[cid]/+server.ts), [`src/lib/server/og/serve.ts`](../../src/lib/server/og/serve.ts), [`src/routes/projects/[slug]/press-kits/[rkey]/photos/[cid]/+server.ts`](../../src/routes/projects/[slug]/press-kits/[rkey]/photos/[cid]/+server.ts), [`src/routes/api/places/+server.ts`](../../src/routes/api/places/+server.ts), [`src/routes/sets/[did]/[rkey]/player.json/+server.ts`](../../src/routes/sets/[did]/[rkey]/player.json/+server.ts), [`src/lib/server/flags/get-flags.ts`](../../src/lib/server/flags/get-flags.ts) +Source: [`src/lib/server/http.ts`](../../src/lib/server/http.ts), [`src/routes/charts/+page.server.ts`](../../src/routes/charts/+page.server.ts), [`src/routes/venue/[key]/[[name]]/+page.server.ts`](../../src/routes/venue/[key]/[[name]]/+page.server.ts), [`src/routes/projects/[slug]/mixes/[n]/+page.server.ts`](../../src/routes/projects/[slug]/mixes/[n]/+page.server.ts), [`src/routes/media/[did]/[cid]/+server.ts`](../../src/routes/media/[did]/[cid]/+server.ts), [`src/lib/server/og/serve.ts`](../../src/lib/server/og/serve.ts), [`src/routes/projects/[slug]/press-kits/[rkey]/photos/[cid]/+server.ts`](../../src/routes/projects/[slug]/press-kits/[rkey]/photos/[cid]/+server.ts), [`src/routes/api/places/+server.ts`](../../src/routes/api/places/+server.ts), [`src/routes/sets/[did]/[rkey]/player.json/+server.ts`](../../src/routes/sets/[did]/[rkey]/player.json/+server.ts), [`src/lib/server/flags/get-flags.ts`](../../src/lib/server/flags/get-flags.ts) ## Error paths diff --git a/apps/web/docs/diagrams/staff-and-upkeep.md b/apps/web/docs/diagrams/staff-and-upkeep.md index 390e1c2ea..ddae6dabf 100644 --- a/apps/web/docs/diagrams/staff-and-upkeep.md +++ b/apps/web/docs/diagrams/staff-and-upkeep.md @@ -160,7 +160,7 @@ Source: [`src/lib/server/services/shared-spaces.ts`](../../src/lib/server/servic ## Public listings -How a listed act, party or venue reaches the directory. Acts, published parties and venues have something to list, from the root's performer, party or venue record in their space, and a venue is listed from the moment it's added; a DJ's own space and a draft party have nothing to show, so they're never listed. A listing points at a public page, so none is written until the `spacePages` flag is on for everyone. HappyView keeps only the root's listings. +How a listed act, party or venue reaches the directory. Acts, published parties and venues have something to list, from the root's performer, party or venue record in their space, and a venue is listed from the moment it's added; a DJ's own space and a draft party have nothing to show, so they're never listed. A listing points at a public page, so none is written until the `spacePages` flag is on for signed-out visitors. HappyView keeps only the root's listings. ```mermaid flowchart TD diff --git a/apps/web/src/app.d.ts b/apps/web/src/app.d.ts index 43f820e2a..83d2786d3 100644 --- a/apps/web/src/app.d.ts +++ b/apps/web/src/app.d.ts @@ -17,7 +17,7 @@ declare global { interface Locals { app: ServerApp; viewer: Viewer | null; - /** Every feature flag for this viewer or signed-out visitor. On XRPC requests, only those on for everyone. */ + /** Every feature flag for this viewer, or as a signed-out visitor gets them, which XRPC requests do too. */ flags: Flags; /** The flags a staff member is previewing in this browser, already in `flags`. */ flagPreview?: FlagPreview; diff --git a/apps/web/src/hooks.server.test.ts b/apps/web/src/hooks.server.test.ts index 33cd2aac2..d7170db61 100644 --- a/apps/web/src/hooks.server.test.ts +++ b/apps/web/src/hooks.server.test.ts @@ -9,7 +9,6 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import { SESSION_COOKIE, WebSessions } from '#lib/server/auth/session.ts'; import { CRAWLER_HEAD } from '#lib/server/crawler-head.ts'; import { PREVIEW_COOKIE, PREVIEW_MS, sealPreview } from '#lib/server/flags/preview.ts'; -import { VISITOR_COOKIE } from '#lib/server/flags/visitor.ts'; import { HappyViewError } from '#lib/server/happyview/client.ts'; import { m } from '#lib/paraglide/messages.js'; import { requireFlag } from '#lib/server/http.ts'; @@ -17,7 +16,6 @@ import { RateLimiter } from '#lib/server/rate-limit.ts'; import { createTestServices } from '#lib/server/testing/core.ts'; import { type WrittenLine, writtenLog } from '#lib/server/testing/written-log.ts'; import type { Logger } from '#lib/server/logger.ts'; -import type { FlagKey } from '#lib/flags/keys.generated.ts'; import type { Viewer } from '#lib/types.ts'; import { flagsOff } from '#lib/testing/flags.ts'; import { routeEvent, type RouteEventInit } from '#lib/testing/route-event.ts'; @@ -197,7 +195,7 @@ it("applies a staff member's flag preview to their own requests only", async () expect(signedOut.cookies.deleted).toContain(PREVIEW_COOKIE); }); -it('lets a page behind a flag 404 until the flag is on for the viewer, a staff preview included', async () => { +it('lets a page behind a flag 404 until the flag is on for the viewer, signed-out visitors last', async () => { const s = await services({ admins: [ADMIN] }); const { handle } = hooksWith(async () => s.app); const adminToken = await s.sessions.create(ADMIN, null); @@ -228,15 +226,14 @@ it('lets a page behind a flag 404 until the flag is on for the viewer, a staff p expect(await page({ [SESSION_COOKIE]: djToken })).toBe(404); expect(await page({})).toBe(404); - await s.flags.updateFlag(await s.viewer(ADMIN), 'spacePages', { - enabled: true, - everyone: true, - percentage: 0, - groups: [], - dids: [] - }); + const everyAccount = { enabled: true, everyone: true, percentage: 0, groups: [], dids: [] }; + await s.flags.updateFlag(await s.viewer(ADMIN), 'spacePages', everyAccount); expect(await page({ [SESSION_COOKIE]: djToken })).toBe(200); + expect(await page({})).toBe(404); + + await s.flags.updateFlag(await s.viewer(ADMIN), 'spacePages', { ...everyAccount, signedOut: true }); + expect(await page({})).toBe(200); }); @@ -290,111 +287,6 @@ it("gives an xrpc call a signed-out visitor's flags, and ignores a staff preview expect(resolve).not.toHaveBeenCalled(); }); -it('counts a signed-out visitor in a percentage by their own cookie, the same way on every request', async () => { - const s = await services({ admins: [ADMIN] }); - const { handle } = hooksWith(async () => s.app); - await atPercentage(s, 50); - - for (let request = 0; request < 3; request++) { - const inside = await handledWithLocals(handle, { url: '/', cookies: { [VISITOR_COOKIE]: INSIDE_HALF } }); - const outside = await handledWithLocals(handle, { url: '/', cookies: { [VISITOR_COOKIE]: OUTSIDE_HALF } }); - - expect(inside.locals.flags?.[PAGE_FLAG]).toBe(true); - expect(outside.locals.flags?.[PAGE_FLAG]).toBe(false); - expect(inside.cookies.options.has(VISITOR_COOKIE)).toBe(false); - } -}); - -it('gives a signed-out visitor a first-party id on their first request, and keeps their answer with it', async () => { - const s = await services({ admins: [ADMIN], publicUrl: 'https://localnetwork.test' }); - const { handle } = hooksWith(async () => s.app); - await atPercentage(s, 50); - - const visits: Record[] = [{}, { [VISITOR_COOKIE]: 'not-a-uuid' }]; - - for (const cookies of visits) { - const first = await handledWithLocals(handle, { url: '/', cookies }); - const id = first.cookies.get(VISITOR_COOKIE); - - expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); - expect(first.cookies.options.get(VISITOR_COOKIE)).toEqual({ - path: '/', - httpOnly: true, - sameSite: 'lax', - secure: true, - maxAge: 365 * 86_400 - }); - - const again = await handledWithLocals(handle, { url: '/', cookies: { [VISITOR_COOKIE]: id! } }); - - expect(again.locals.flags?.[PAGE_FLAG]).toBe(first.locals.flags?.[PAGE_FLAG]); - } -}); - -it('gives a visitor no id while no flag is on for a percentage, nor when signed in or over xrpc', async () => { - const s = await services({ admins: [ADMIN] }); - const { handle } = hooksWith(async () => s.app); - const token = await s.sessions.create(DJ, null); - - const setsId = async (request: RouteEventInit) => - (await handledWithLocals(handle, request)).cookies.options.has(VISITOR_COOKIE); - - expect(await setsId({ url: '/' })).toBe(false); - - await atPercentage(s, 50, { enabled: false }); - - expect(await setsId({ url: '/' })).toBe(false); - - await atPercentage(s, 50, { everyone: true }); - - expect(await setsId({ url: '/' })).toBe(false); - - await atPercentage(s, 50); - - expect(await setsId({ url: '/' })).toBe(true); - expect(await setsId({ url: '/', cookies: { [SESSION_COOKIE]: token } })).toBe(false); - - const xrpc = await handledWithLocals(handle, { - url: '/xrpc/computer.localnetwork.flags.getFlags', - cookies: { [VISITOR_COOKIE]: INSIDE_HALF } - }); - - expect(xrpc.locals.flags?.[PAGE_FLAG]).toBe(false); - expect(xrpc.cookies.options.has(VISITOR_COOKIE)).toBe(false); -}); - -it("keeps a signed-out page out of shared caches while it depends on the visitor's own bucket", async () => { - const s = await services({ admins: [ADMIN] }); - const { handle } = hooksWith(async () => s.app); - const cachedBriefly = { 'cache-control': 'public, max-age=60', vary: 'Cookie' }; - - const cacheControl = async (cookies: Record) => - (await handledWithLocals(handle, { url: '/artists', cookies }, 200, cachedBriefly)).response.headers.get( - 'cache-control' - ); - - expect(await cacheControl({})).toBe('public, max-age=60'); - - await atPercentage(s, 50); - - expect(await cacheControl({})).toBe('private, max-age=60'); - expect(await cacheControl({ [VISITOR_COOKIE]: OUTSIDE_HALF })).toBe('private, max-age=60'); -}); - -it('gives a visitor no id, and keeps pages shared-cacheable, while only a flag for accounts is on for a percentage', async () => { - const s = await services({ admins: [ADMIN] }); - const { handle } = hooksWith(async () => s.app); - await atPercentage(s, 50, {}, ACCOUNT_FLAG); - - const { cookies, response } = await handledWithLocals(handle, { url: '/artists' }, 200, { - 'cache-control': 'public, max-age=60', - vary: 'Cookie' - }); - - expect(cookies.options.has(VISITOR_COOKIE)).toBe(false); - expect(response.headers.get('cache-control')).toBe('public, max-age=60'); -}); - it('limits writes by address, and counts an unknown address as one', async () => { const s = await services({ writes: 1 }); const { handle } = hooksWith(async () => s.app); @@ -688,28 +580,6 @@ const DJ = 'did:plc:dj'; const ADMIN = 'did:plc:admin'; -/** A flag that changes a public page (its catalog file has `showsOn`), so signed-out visitors are counted in it. */ -const PAGE_FLAG = 'pauseRecordingStream' satisfies FlagKey; - -/** A flag with no `showsOn`, which changes only what accounts see. */ -const ACCOUNT_FLAG = 'inboxEmail' satisfies FlagKey; - -/** Visitor cookies whose ids sit in PAGE_FLAG's buckets 36 and 59: inside a 50% rollout, and outside it. */ -const INSIDE_HALF = '00000000-0000-4000-8000-000000000000'; - -const OUTSIDE_HALF = '00000001-0000-4000-8000-000000000000'; - -/** Puts `key` on for `percentage` of everyone, with `gates` on top, as an admin of `s`. */ -async function atPercentage( - s: Awaited>, - percentage: number, - gates: { enabled?: boolean; everyone?: boolean } = {}, - key: FlagKey = PAGE_FLAG -) { - const input = { enabled: true, everyone: false, percentage, groups: [], dids: [], ...gates }; - await s.flags.updateFlag(await s.viewer(ADMIN), key, input); -} - /** An account whose OAuth grant lacks scopes the app now asks for, so the app has no viewer for it. */ const STALE = 'did:plc:stale'; @@ -720,7 +590,7 @@ type HookApp = { logger?: Logger; sessions?: WebSessions; limits?: { write: RateLimiter }; - flags?: Pick; + flags?: Pick; viewer?: (did: string) => Promise; config?: { publicUrl: string }; }; diff --git a/apps/web/src/hooks.server.ts b/apps/web/src/hooks.server.ts index 0cf365240..bf4a1b937 100644 --- a/apps/web/src/hooks.server.ts +++ b/apps/web/src/hooks.server.ts @@ -6,7 +6,6 @@ import { HappyViewError } from '#lib/server/happyview/client.ts'; import { SESSION_COOKIE } from '#lib/server/auth/session.ts'; import { gzipped } from '#lib/server/compress.ts'; import { PREVIEW_COOKIE } from '#lib/server/flags/preview.ts'; -import { flagVisitor } from '#lib/server/flags/visitor.ts'; import { CRAWLER_HEAD, withCrawlerHead } from '#lib/server/crawler-head.ts'; import { clientIp, guardArea, isUnlisted } from '#lib/server/http.ts'; import { createLogger, type Logger } from '#lib/server/logger.ts'; @@ -89,7 +88,6 @@ export function serverHooks({ const { requestId } = event.locals; const isXrpc = event.url.pathname.startsWith('/xrpc/'); - const isHttps = app.config.publicUrl.startsWith('https:'); if (MUTATING.has(event.request.method) && !isXrpc && !app.limits.write.take(`ip:${clientIp(event)}`)) { return new Response('Too many requests. Slow down a little.', { status: 429, headers: { 'retry-after': '30' } }); @@ -111,15 +109,10 @@ export function serverHooks({ } } - // An xrpc call never reads a cookie, so it only gets flags on for everyone. A route that has checked a service - // token can evaluate flags for that token's DID itself. A signed-out visitor gets an id of their own while a flag - // that changes a public page is on for a percentage, so they're in or out of it the same way on every request. + // An xrpc call never reads the sign-in cookie, so it gets the flags a signed-out visitor does. A route that has + // checked a service token can evaluate flags for that token's DID itself. const { viewer } = event.locals; - const needsVisitorId = !viewer && !isXrpc && (await app.flags.hasPublicPercentage()); - const visitor = needsVisitorId ? flagVisitor(event.cookies, isHttps) : null; - event.locals.flags = await app.flags.evaluate(viewer?.did ?? visitor?.id ?? null); - - if (visitor) log.set({ flagVisitor: visitor.isNew ? 'new' : 'returning' }); + event.locals.flags = await app.flags.evaluate(viewer?.did ?? null); if (!isXrpc) { const cookie = event.cookies.get(PREVIEW_COOKIE); @@ -186,13 +179,7 @@ export function serverHooks({ else response.headers.delete('vary'); } - // The answer now depends on this browser's own cookie, so a shared cache mustn't keep it for the next visitor, - // or hand them the cookie it set. The browser's own cache still can. - if (visitor && cacheControl?.includes('public')) { - response.headers.set('cache-control', cacheControl.replace('public', 'private')); - } - - if (isHttps) { + if (app.config.publicUrl.startsWith('https:')) { response.headers.set('strict-transport-security', 'max-age=31536000; includeSubDomains'); } diff --git a/apps/web/src/lib/components/FlagTable.stories.svelte b/apps/web/src/lib/components/FlagTable.stories.svelte index fdb9d58ef..7375bdb09 100644 --- a/apps/web/src/lib/components/FlagTable.stories.svelte +++ b/apps/web/src/lib/components/FlagTable.stories.svelte @@ -10,8 +10,10 @@ const flag = (key: string, description: string, gates: Partial): FlagView => ({ key: key as FlagView['key'], description, + type: 'release', showsOn: [], enabled: true, + signedOut: false, everyone: false, percentage: 0, groups: [], @@ -23,8 +25,9 @@ const flags = [ flag('newPlanner', 'The planner with booking notes.', { percentage: 25, groups: [{ rkey: '3lzy2ji4nms2z', name: 'Beta DJs' }], updatedAt: '2026-11-02T10:00:00Z' }), - flag('parityCanary', 'Gates nothing.', { accounts: [{ did: 'did:plc:milo', handle: 'milo.test' }], updatedAt: '2026-11-01T09:00:00Z' }), - flag('quietInbox', 'Fewer inbox emails.', { everyone: true, updatedAt: '2026-09-30T09:00:00Z', readyToRemove: true }), + flag('parityCanary', 'Gates nothing.', { type: 'ops', accounts: [{ did: 'did:plc:milo', handle: 'milo.test' }], updatedAt: '2026-11-01T09:00:00Z' }), + flag('quietInbox', 'Fewer inbox emails.', { everyone: true, signedOut: true, updatedAt: '2026-09-30T09:00:00Z', readyToRemove: true }), + flag('socialHome', 'The home page built around events near you.', { everyone: true, removeBy: '2027-02-12', updatedAt: '2026-11-10T12:00:00Z' }), flag('slowCharts', 'Charts from the new index.', { enabled: false, percentage: 40, accounts: [{ did: 'did:plc:milo', handle: 'milo.test' }], updatedAt: '2026-11-08T21:00:00Z' }), flag('tapeDecks', 'Not turned on yet.', {}) ]; diff --git a/apps/web/src/lib/components/FlagTable.svelte b/apps/web/src/lib/components/FlagTable.svelte index 464509f6c..c4f204549 100644 --- a/apps/web/src/lib/components/FlagTable.svelte +++ b/apps/web/src/lib/components/FlagTable.svelte @@ -1,5 +1,5 @@ {flag.key} · Flags · Local Network @@ -56,13 +69,21 @@ {#if fields.off}

Kept for when it's back on. None of it applies while it's off.

{/if}
- + -

Counts signed-out browsers too; anyone in stays in.{#if flag.showsOn.length > 0}{' '}Crawlers see it about this share of the time.{/if}

+

Accounts stay in as this grows.

+ {#if flag.type === 'release'} + + + {/if}
Groups {#if data.groups.length === 0} diff --git a/apps/web/src/routes/admin/flags/[key]/page.stories.svelte b/apps/web/src/routes/admin/flags/[key]/page.stories.svelte index 7440fabfe..4947b2c0b 100644 --- a/apps/web/src/routes/admin/flags/[key]/page.stories.svelte +++ b/apps/web/src/routes/admin/flags/[key]/page.stories.svelte @@ -11,10 +11,12 @@ const flag: FlagView = { key: 'spacePages', - description: "The public act, party, venue and event pages. Off, they answer 404, and no listing is written until it's on for everyone, since a listing points at a public page.", + description: "The public act, party, venue and event pages. Off, they answer 404, and no listing is written until it's on for signed-out visitors, since a listing points at a public page.", + type: 'release', showsOn: ['act', 'party', 'venue', 'event'], removeBy: '2027-02-12', enabled: true, + signedOut: false, everyone: false, percentage: 25, groups: [{ rkey: '3lzy2ji4nms2z', name: 'Beta DJs' }], @@ -25,16 +27,28 @@ const groups: FlagGroupView[] = [{ rkey: '3lzy2ji4nms2z', name: 'Beta DJs', description: null, members: [{ did: 'did:plc:milo', handle: 'milo.test' }], flags: ['spacePages'] }]; - /** A release flag on for everyone past its time: what the page asks staff to delete. */ + /** A release flag on for every caller past its time: what the page asks staff to delete. */ const calendar: Partial = { key: 'dashboardCalendar', description: 'Shows Calendar in the dashboard sidebar and serves /dashboard/calendar, every night for the year ahead.', showsOn: [], removeBy: '2027-02-15', everyone: true, + signedOut: true, readyToRemove: true }; + /** A kill switch, which has no signed-out switch of its own. */ + const killSwitch: Partial = { + key: 'pauseRecordingStream', + description: "Stops the site streaming recordings from DJs' servers.", + type: 'ops', + showsOn: ['set', 'mix'], + removeBy: undefined, + percentage: 0, + groups: [] + }; + const data = (fields: Partial = {}, flagPreview?: Record) => ({ viewer: ada, pendingRequests: 0, @@ -52,7 +66,7 @@ asChild play={async ({ canvasElement }) => { await expect(within(canvasElement).getByRole('switch', { name: /^Off for everyone/ })).toBeChecked(); - await expect(within(canvasElement).getByLabelText('Percentage of people')).toHaveValue(25); + await expect(within(canvasElement).getByLabelText('Percentage of accounts')).toHaveValue(25); }} > @@ -96,3 +110,30 @@ + + + { + await expect(within(canvasElement).getByRole('checkbox', { name: /^Signed-out visitors/ })).toBeEnabled(); + }} +> + + + + + + + + + + { + await expect(within(canvasElement).queryByRole('checkbox', { name: /^Signed-out visitors/ })).toBeNull(); + }} +> + + diff --git a/apps/web/src/routes/admin/flags/[key]/page.svelte.test.ts b/apps/web/src/routes/admin/flags/[key]/page.svelte.test.ts index ab907d004..a93b49c43 100644 --- a/apps/web/src/routes/admin/flags/[key]/page.svelte.test.ts +++ b/apps/web/src/routes/admin/flags/[key]/page.svelte.test.ts @@ -27,19 +27,47 @@ it('says so when the flag lists no kind of page', async () => { await expect.element(page.getByText('Shows on: None listed', { exact: true })).toBeVisible(); }); -const CRAWLERS = 'Crawlers see it about this share of the time.'; +/** The signed-out switch, whose label also holds its hint. */ +const SIGNED_OUT = /^Signed-out visitors/; -it('warns that crawlers see a flag that shows on public pages about as often as its percentage', async () => { - await renderFlag({ key: 'spacePages', showsOn: ['act', 'party', 'venue', 'event'] }); +it('counts the percentage in accounts', async () => { + await renderFlag({ percentage: 25 }); - await expect.element(page.getByText(CRAWLERS, { exact: false })).toBeVisible(); + await expect.element(page.getByLabelText('Percentage of accounts')).toHaveValue(25); }); -it('leaves crawlers out of the percentage hint for a flag that shows on no public page', async () => { - await renderFlag({ showsOn: [] }); +it('starts signed-out visitors off for a release flag, and holds the switch until every account has it', async () => { + await renderFlag({ key: 'socialHome', type: 'release', percentage: 99 }); + + const signedOut = page.getByRole('checkbox', { name: SIGNED_OUT }); + + await expect.element(signedOut).not.toBeChecked(); + await expect.element(signedOut).toBeDisabled(); + await expect.element(signedOut).toHaveAccessibleDescription("Only once it's on for every account."); +}); + +it('lets staff turn signed-out visitors on once every account has the flag', async () => { + await renderFlag({ key: 'socialHome', type: 'release', percentage: 100 }); + + await expect.element(page.getByRole('checkbox', { name: SIGNED_OUT })).toBeEnabled(); +}); + +it('says signed-out visitors go when the flag drops below every account', async () => { + await renderFlag({ key: 'socialHome', type: 'release', everyone: true, signedOut: true }); + + const signedOut = page.getByRole('checkbox', { name: SIGNED_OUT }); - await expect.element(page.getByText('anyone in stays in.', { exact: false })).toBeVisible(); - await expect.element(page.getByText(CRAWLERS, { exact: false })).not.toBeInTheDocument(); + await expect.element(signedOut).toBeChecked(); + await expect.element(signedOut).toHaveAccessibleDescription('Turns off if it drops below every account.'); +}); + +it('gives an ops flag no signed-out switch, since everyone takes them in', async () => { + await renderFlag({ key: 'pauseRecordingStream', type: 'ops' }); + + await expect + .element(page.getByRole('checkbox', { name: /^On for everyone/ })) + .toHaveAccessibleDescription('Signed-out visitors too.'); + await expect.element(page.getByRole('checkbox', { name: SIGNED_OUT })).not.toBeInTheDocument(); }); it("gives a release flag's remove-by date as its catalog file writes it", async () => { @@ -79,6 +107,17 @@ it("doesn't say to remove a flag that isn't ready", async () => { await expect.element(page.getByText('Ready to remove')).not.toBeInTheDocument(); }); +it('says to save first when the form reaches every account but the saved flag does not', async () => { + await renderFlag({ key: 'socialHome', type: 'release', percentage: 60 }); + + await page.getByRole('checkbox', { name: /^On for everyone/ }).click(); + + await expect.element(page.getByRole('checkbox', { name: SIGNED_OUT })).toBeDisabled(); + await expect + .element(page.getByRole('checkbox', { name: SIGNED_OUT })) + .toHaveAccessibleDescription('Save first, then this opens.'); +}); + // Helpers /** The flag page for parityCanary, or the flag `fields` names, on top of a flag nobody has set. */ @@ -86,8 +125,10 @@ function renderFlag(fields: Partial) { const flag: FlagView = { key: 'parityCanary', description: 'Gates nothing.', + type: 'ops', showsOn: [], enabled: true, + signedOut: false, everyone: false, percentage: 0, groups: [], diff --git a/apps/web/src/routes/admin/flags/page.server.test.ts b/apps/web/src/routes/admin/flags/page.server.test.ts index 3e7fc4010..205796473 100644 --- a/apps/web/src/routes/admin/flags/page.server.test.ts +++ b/apps/web/src/routes/admin/flags/page.server.test.ts @@ -130,6 +130,29 @@ it('turns a flag off for everyone and keeps who it was for', async () => { expect(await t.flags.flag(FLAG)).toMatchObject({ enabled: true, percentage: 30 }); }); +it('turns signed-out visitors on only once every account has the flag', async () => { + // Arrange + const key = 'dashboardCalendar'; + + const save = async (form: Record) => + callRoute(flagActions.save, { + app: app(), + viewer: await t.viewer(ADMIN), + url: `/admin/flags/${key}`, + params: { key }, + form + }); + + // Act + const early = await save({ percentage: '50', signedOut: 'on' }); + const last = await save({ percentage: '100', signedOut: 'on' }); + + // Assert + expect(early).toMatchObject({ status: 400, data: { error: 'Turn it on for every account first' } }); + expect(last).toEqual({ success: 'Flag saved' }); + expect(await t.flags.flag(key)).toMatchObject({ percentage: 100, signedOut: true }); +}); + it('says which account it could not find, and saves nothing', async () => { const viewer = await t.viewer(ADMIN); diff --git a/apps/web/src/routes/admin/flags/page.svelte.test.ts b/apps/web/src/routes/admin/flags/page.svelte.test.ts new file mode 100644 index 000000000..87c510413 --- /dev/null +++ b/apps/web/src/routes/admin/flags/page.svelte.test.ts @@ -0,0 +1,17 @@ +import { page } from 'vitest/browser'; +import { expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; +import { ada } from '#lib/testing/requests.ts'; +import Page from './+page.svelte'; + +it('links to the saves in the audit log, newest first', async () => { + await render(Page, { + params: {}, + form: null, + data: { viewer: ada, pendingRequests: 0, grants: ['flags'], flags: [] } + }); + + await expect + .element(page.getByRole('link', { name: 'Recent changes' })) + .toHaveAttribute('href', '/admin/audit?action=flag.update'); +}); diff --git a/apps/web/src/routes/privacy/+page.svelte b/apps/web/src/routes/privacy/+page.svelte index 87bc339d2..039e7d3aa 100644 --- a/apps/web/src/routes/privacy/+page.svelte +++ b/apps/web/src/routes/privacy/+page.svelte @@ -36,7 +36,6 @@ ln_sessionKeeps you signed in. We store only a hash of it, with the browser you signed in from.{data.sessionDays} days, or until you sign out ln_localeThe language you see the site in.400 days - ln_flag_visitorOnly while you're signed out and we're trying something new on a share of visitors: a random id, so you get the same version on every visit. It isn't linked to an account and we don't log it.1 year ln_shows_placeThe city you last picked on Shows or the home page, so both open on it.1 year ln_signed_outSet when you sign out, naming the account, so the next page clears its form drafts from this browser.Until the next page reads it ln_flag_previewStaff only: the features they're previewing in this browser.1 hour diff --git a/apps/web/src/routes/xrpc/computer.localnetwork.flags.getFlags/server.test.ts b/apps/web/src/routes/xrpc/computer.localnetwork.flags.getFlags/server.test.ts index eadabf21a..a1a7bb296 100644 --- a/apps/web/src/routes/xrpc/computer.localnetwork.flags.getFlags/server.test.ts +++ b/apps/web/src/routes/xrpc/computer.localnetwork.flags.getFlags/server.test.ts @@ -54,7 +54,13 @@ async function ask(authorization?: string) { it('tells anyone the public gates, and targets nobody', async () => { expect(await ask()).toEqual({ - flags: answersWith('parityCanary', { enabled: true, everyone: false, percentage: 10, targeted: false }) + flags: answersWith('parityCanary', { + enabled: true, + signedOut: false, + everyone: false, + percentage: 10, + targeted: false + }) }); }); @@ -67,7 +73,13 @@ it('tells an account its own targeting, with a token from its server', async () }); expect(await ask(token)).toEqual({ - flags: answersWith('parityCanary', { enabled: true, everyone: false, percentage: 10, targeted: true }) + flags: answersWith('parityCanary', { + enabled: true, + signedOut: false, + everyone: false, + percentage: 10, + targeted: true + }) }); }); @@ -81,6 +93,12 @@ it('says a flag is off for everyone, with the gates it keeps for when it is back }); expect(await ask()).toEqual({ - flags: answersWith('parityCanary', { enabled: false, everyone: false, percentage: 10, targeted: false }) + flags: answersWith('parityCanary', { + enabled: false, + signedOut: false, + everyone: false, + percentage: 10, + targeted: false + }) }); }); diff --git a/crates/locallibrary/src/atmosphere/flags/tests.rs b/crates/locallibrary/src/atmosphere/flags/tests.rs index 6e12fa535..91ed9797a 100644 --- a/crates/locallibrary/src/atmosphere/flags/tests.rs +++ b/crates/locallibrary/src/atmosphere/flags/tests.rs @@ -17,7 +17,7 @@ const OTHER: &str = "did:plc:other"; const FLAG: &str = keys::PARITY_CANARY; const GET_SERVICE_AUTH: &str = "com.atproto.server.getServiceAuth"; -const NOTHING_ON: Gates = Gates { enabled: true, everyone: false, percentage: 0, targeted: false }; +const NOTHING_ON: Gates = Gates { enabled: true, signed_out: false, everyone: false, percentage: 0, targeted: false }; /// A store, and a pretend data server that's Local Network's website too. struct World { @@ -140,7 +140,7 @@ fn a_flag_turned_off_is_off_for_the_account_it_targets() { let now = Utc::now(); assert!(!check_at(w.root(), FLAG, now)); assert_eq!(w.asked(), [false, true]); - let gates = Gates { enabled: false, everyone: true, percentage: 100, targeted: true }; + let gates = Gates { enabled: false, signed_out: false, everyone: true, percentage: 100, targeted: true }; assert_eq!(Cache::load(w.root()).flags, [Flag { key: FLAG.into(), gates }]); assert!(!shown(&all_at(w.root(), false, now + TimeDelta::minutes(1)))); } @@ -152,12 +152,13 @@ fn a_check_now_reads_a_fresh_answer(tc: TestCase) { let w = world(); let gates = Gates { enabled: tc.draw(gs::booleans()), + signed_out: tc.draw(gs::booleans()), everyone: tc.draw(gs::booleans()), percentage: tc.draw(gs::sampled_from(vec![0u32, 100])), targeted: tc.draw(gs::booleans()), }; save(w.root(), &cached(None, TimeDelta::zero(), gates, Utc::now())); - let expected = gates.enabled && gates.everyone; + let expected = gates.enabled && gates.signed_out && (gates.everyone || gates.percentage == 100); assert_eq!(crate::flags::check(w.root(), FLAG), expected); let report = crate::flags::all(w.root(), false); assert_eq!((shown(&report), report.freshness), (expected, Freshness::Fresh)); @@ -169,7 +170,7 @@ fn a_check_now_reads_a_fresh_answer(tc: TestCase) { fn a_website_thats_down_leaves_the_last_answer_and_waits() { let w = world(); let now = Utc::now(); - save(w.root(), &cached(None, TimeDelta::hours(2), Gates { everyone: true, ..NOTHING_ON }, now)); + save(w.root(), &cached(None, TimeDelta::hours(2), Gates { everyone: true, signed_out: true, ..NOTHING_ON }, now)); w.pds.set_flags_answers(Some((503, json!({ "error": "Down" }))), None); assert!(check_at(w.root(), FLAG, now)); assert!(check_at(w.root(), FLAG, now + RETRY_AFTER_FAILURE - TimeDelta::seconds(1))); @@ -194,7 +195,7 @@ fn a_website_thats_down_leaves_the_last_answer_and_waits() { fn an_answer_over_two_weeks_old_is_off() { let w = world(); let now = Utc::now(); - let gates = Gates { everyone: true, ..NOTHING_ON }; + let gates = Gates { everyone: true, signed_out: true, ..NOTHING_ON }; let mut cache = cached(None, LAST_KNOWN_GOOD, gates, now); cache.last_attempt_at = Some(now); save(w.root(), &cache); @@ -525,7 +526,8 @@ fn a_check_ends_as_the_cache_and_the_servers_say(tc: TestCase) { Session::Ended => sign_in_ended(root, &pds.url), } let last = age.map(|age| { - let gates = Gates { enabled: true, everyone: was.0, percentage: was.1, targeted: was.2 }; + // Signed-out callers follow everyone, as the website answers for an ops flag like this one. + let gates = Gates { enabled: true, signed_out: was.0, everyone: was.0, percentage: was.1, targeted: was.2 }; let mut cache = cached(said_of, TimeDelta::minutes(age), gates, now); cache.last_attempt_at = Some(now - TimeDelta::minutes(attempted)); cache diff --git a/crates/locallibrary/src/flags.rs b/crates/locallibrary/src/flags.rs index c0708a54b..61fea9ca8 100644 --- a/crates/locallibrary/src/flags.rs +++ b/crates/locallibrary/src/flags.rs @@ -46,6 +46,11 @@ pub struct Gates { /// flag off is on, and so is an answer from a website that predates it. #[serde(default = "enabled_by_default")] pub enabled: bool, + /// Signed out, it's on only with this, and only once it's on for every account: `everyone` or + /// 100%. A website from before it doesn't send it, which is off. + #[serde(default, rename = "signedOut")] + pub signed_out: bool, + /// Every signed-in account. pub everyone: bool, /// How much of the accounts it's on for, 0 to 100. pub percentage: u32, @@ -72,9 +77,16 @@ pub fn bucket(key: &str, did: &str) -> u32 { u32::from_be_bytes([hash[0], hash[1], hash[2], hash[3]]) % 100 } -/// Whether `key` is on for `did`, given its gates. Signed out, there's no DID to bucket. +/// Whether `key` is on for `did`, given its gates. Signed out, there's no DID to bucket, and the +/// flag comes last: only with `signed_out`, once every account has it. pub fn decide(gates: &Gates, key: &str, did: Option<&str>) -> bool { - gates.enabled && (gates.everyone || gates.targeted || did.is_some_and(|did| bucket(key, did) < gates.percentage)) + if !gates.enabled { + return false; + } + match did { + Some(did) => gates.everyone || gates.targeted || bucket(key, did) < gates.percentage, + None => gates.signed_out && (gates.everyone || gates.percentage >= 100), + } } /// How much an answer can be gone by. diff --git a/crates/locallibrary/src/flags/tests.rs b/crates/locallibrary/src/flags/tests.rs index 9fbba0f5e..cac2cbcf4 100644 --- a/crates/locallibrary/src/flags/tests.rs +++ b/crates/locallibrary/src/flags/tests.rs @@ -16,7 +16,7 @@ fn answered(did: Option<&str>, age: TimeDelta, gates: Gates, now: DateTime) } } -const NOTHING_ON: Gates = Gates { enabled: true, everyone: false, percentage: 0, targeted: false }; +const NOTHING_ON: Gates = Gates { enabled: true, signed_out: false, everyone: false, percentage: 0, targeted: false }; /// Both the website and this code read these, so the two can't come to disagree. #[test] @@ -74,7 +74,7 @@ fn a_damaged_cache_is_no_cache() { #[test] fn an_unknown_key_is_off() { let now = Utc::now(); - let gates = Gates { enabled: true, everyone: true, percentage: 100, targeted: true }; + let gates = Gates { enabled: true, signed_out: true, everyone: true, percentage: 100, targeted: true }; let cache = answered(Some("did:plc:abc"), TimeDelta::zero(), gates, now); assert!(cache.on(FLAG, Some("did:plc:abc"), now)); assert!(!cache.on("notAFlag", Some("did:plc:abc"), now)); @@ -96,7 +96,7 @@ fn a_build_without_the_account_has_every_flag_off() { off(dir.path()); assert!(!dir.path().join(CACHE_FILE).exists()); - let gates = Gates { enabled: true, everyone: true, percentage: 100, targeted: true }; + let gates = Gates { enabled: true, signed_out: true, everyone: true, percentage: 100, targeted: true }; let left = answered(None, TimeDelta::zero(), gates, Utc::now()); crate::fsutil::write_json_atomic(&dir.path().join(CACHE_FILE), &left).unwrap(); off(dir.path()); @@ -123,21 +123,40 @@ fn raising_a_percentage_only_adds_accounts(tc: TestCase) { assert!(!at(0) && at(100)); } -/// Signed out there's no DID: a percentage can't apply and nothing cached can target anyone, so -/// only a flag on for everyone is on, as on the website. +/// Signed out there's no DID: a percentage can't pick anyone and nothing cached can target +/// anyone, so a flag is on only for signed-out callers and once every account has it, as on the +/// website. #[hegel::test(test_cases = 100)] -fn signed_out_only_flags_on_for_everyone_are_on(tc: TestCase) { +fn signed_out_only_flags_on_for_them_and_every_account_are_on(tc: TestCase) { let now = Utc::now(); let gates = Gates { enabled: tc.draw(gs::booleans()), + signed_out: tc.draw(gs::booleans()), everyone: tc.draw(gs::booleans()), percentage: tc.draw(gs::integers::().max_value(100)), targeted: tc.draw(gs::booleans()), }; let did = tc.draw(gs::optional(gs::just("did:plc:abc"))); - let on_for_everyone = gates.enabled && gates.everyone; - assert_eq!(answered(did, TimeDelta::zero(), gates, now).on(FLAG, None, now), on_for_everyone); - assert_eq!(decide(&Gates { targeted: false, ..gates }, FLAG, None), on_for_everyone); + let on = gates.enabled && gates.signed_out && (gates.everyone || gates.percentage == 100); + assert_eq!(answered(did, TimeDelta::zero(), gates, now).on(FLAG, None, now), on); + assert_eq!(decide(&Gates { targeted: false, ..gates }, FLAG, None), on); +} + +/// Signed in, the signed-out setting changes nothing. +#[hegel::test(test_cases = 100)] +fn signed_out_changes_nothing_for_an_account(tc: TestCase) { + let gates = Gates { + enabled: tc.draw(gs::booleans()), + signed_out: tc.draw(gs::booleans()), + everyone: tc.draw(gs::booleans()), + percentage: tc.draw(gs::integers::().max_value(100)), + targeted: tc.draw(gs::booleans()), + }; + let did = tc.draw(gs::text()); + assert_eq!( + decide(&gates, FLAG, Some(&did)), + decide(&Gates { signed_out: !gates.signed_out, ..gates }, FLAG, Some(&did)) + ); } /// A flag staff turned off is off for everyone, whoever it targets or however far it's rolled out, @@ -147,6 +166,7 @@ fn a_flag_turned_off_is_off_for_everyone(tc: TestCase) { let now = Utc::now(); let on = Gates { enabled: true, + signed_out: tc.draw(gs::booleans()), everyone: tc.draw(gs::booleans()), percentage: tc.draw(gs::integers::().max_value(100)), targeted: tc.draw(gs::booleans()), @@ -156,7 +176,10 @@ fn a_flag_turned_off_is_off_for_everyone(tc: TestCase) { let said_of = tc.draw(gs::optional(gs::just("did:plc:abc"))); assert!(!decide(&off, FLAG, did)); assert!(!answered(said_of, TimeDelta::zero(), off, now).on(FLAG, did, now)); - let expected = on.everyone || on.targeted || did.is_some_and(|did| bucket(FLAG, did) < on.percentage); + let expected = match did { + Some(did) => on.everyone || on.targeted || bucket(FLAG, did) < on.percentage, + None => on.signed_out && (on.everyone || on.percentage == 100), + }; assert_eq!(decide(&on, FLAG, did), expected); } @@ -168,6 +191,20 @@ fn no_word_on_enabled_is_enabled() { assert!(!enabled(json!({ "key": FLAG, "enabled": false, "everyone": true, "percentage": 0, "targeted": false }))); } +/// A website or a cache from before signed-out visitors had their own setting says nothing about +/// it: signed out, the flag is off, and the cache keeps the field's name as the website sends it. +#[test] +fn no_word_on_signed_out_is_off() { + let signed_out = |flag: Value| serde_json::from_value::(flag).unwrap().gates.signed_out; + assert!(!signed_out(json!({ "key": FLAG, "everyone": true, "percentage": 100, "targeted": false }))); + assert!(signed_out( + json!({ "key": FLAG, "signedOut": true, "everyone": true, "percentage": 0, "targeted": false }) + )); + let gates = Gates { signed_out: true, ..NOTHING_ON }; + let kept = serde_json::to_value(Flag { key: FLAG.into(), gates }).unwrap(); + assert_eq!(kept["signedOut"], json!(true)); +} + /// An answer is fresh for an hour, stale up to 14 days and then no answer; it's asked for again /// once it isn't fresh and the last attempt is 15 minutes old. #[cfg(feature = "account")] @@ -181,7 +218,8 @@ fn an_answer_ages_as_the_design_says(tc: TestCase) { let now = Utc::now(); let minutes = tc.draw(gs::integers::().min_value(0).max_value(40_000)); let attempted = tc.draw(gs::integers::().min_value(0).max_value(40)); - let mut cache = answered(None, TimeDelta::minutes(minutes), Gates { everyone: true, ..NOTHING_ON }, now); + let gates = Gates { everyone: true, signed_out: true, ..NOTHING_ON }; + let mut cache = answered(None, TimeDelta::minutes(minutes), gates, now); cache.last_attempt_at = Some(now - TimeDelta::minutes(attempted)); let expected = match minutes { diff --git a/crates/locallibrary/tests/support/mock_pds.rs b/crates/locallibrary/tests/support/mock_pds.rs index e7a2550b3..4da8475eb 100644 --- a/crates/locallibrary/tests/support/mock_pds.rs +++ b/crates/locallibrary/tests/support/mock_pds.rs @@ -250,7 +250,8 @@ impl MockPds { } /// What `getFlags` lists from now on: each flag's key, `everyone` and `percentage`, those - /// named in `targeted` targeting a caller with a token. + /// named in `targeted` targeting a caller with a token. Signed-out callers get a flag with + /// `everyone`, as the website answers for an ops flag. pub fn set_flags(&self, flags: &[(&str, bool, u32)], targeted: &[&str]) { let mut s = self.state.lock().unwrap(); s.flags = flags.iter().map(|(key, everyone, percentage)| (key.to_string(), *everyone, *percentage)).collect(); @@ -725,7 +726,13 @@ fn answer(req: &Request, state: &Mutex, base: &str) -> Answer { } let flag = |(key, everyone, percentage): &(String, bool, u32)| { let targeted = token && s.targeted.contains(key); - json!({ "key": key, "everyone": everyone, "percentage": percentage, "targeted": targeted }) + json!({ + "key": key, + "signedOut": everyone, + "everyone": everyone, + "percentage": percentage, + "targeted": targeted + }) }; (200, vec![], json!({ "flags": s.flags.iter().map(flag).collect::>() })) } diff --git a/docs/adr/0018-signed-out-visitors-come-last.md b/docs/adr/0018-signed-out-visitors-come-last.md new file mode 100644 index 000000000..98b61bc85 --- /dev/null +++ b/docs/adr/0018-signed-out-visitors-come-last.md @@ -0,0 +1,24 @@ +# Signed-out visitors come last + +The rule that decides a flag buckets a DID, and a signed-out visitor has none. So a percentage only ever counted accounts, and turning a flag on for everyone showed it to every signed-out visitor in the same save that gave it to the last accounts. Public pages are where that matters. Most people who see an act, party, venue or event page aren't signed in, and crawlers and directory listings see what they see. + +So signed-out visitors are a switch of their own on each flag, and the last one to turn on. `computer.localnetwork.staff.flag` has an optional `signedOut` boolean, off unless staff tick Signed-out visitors on the flag's page. The website refuses it until what's saved has the flag on for every signed-in account (`everyone`, or 100%), and a save that takes the flag below that turns it off again, so the order can't be skipped or left half undone. `everyone` now means every signed-in account. A caller with no DID gets a flag when `enabled && signedOut && (everyone || percentage >= 100)`, and a caller with one is decided as before, whatever `signedOut` says. `getFlags` sends `signedOut` with the other gates, locallibrary applies the same rule when it's signed out, and `flags/vectors.json` has cases for it. + +Ops flags have no setting of their own. A kill switch has to work where there's no account: xrpc routes, the server's background rounds, crawlers and locallibrary signed out all ask with no DID. An ops flag's `signedOut` is always its `everyone`. Saving one writes it that way, and a record without the field reads that way. A release flag's record without it reads as off. + +Nothing about a signed-out visitor is kept in their browser, so every signed-out visitor gets the same page, and those pages stay shared-cacheable. + +## Considered options + +- A random id in a first-party cookie, bucketed like a DID, so a share of signed-out browsers could get a flag. The maintainer turned it down: signed-out visitors should only get a feature when it's switched on for them, after everyone signed in has it. It also added a cookie to the privacy page, made signed-out pages private while a percentage ran, and showed crawlers a page some of the time. +- Keeping `everyone` as signed in or not: no new field, but a release flag couldn't reach every account without reaching every visitor in the same save. +- Letting a flag's `showsOn` decide whether signed-out visitors are counted: it's a list for the staff console, and a flag that changes something signed-out visitors meet without naming a kind of page would slip past it. +- The same setting on ops flags: a kill switch turned on for everyone and not for signed-out visitors would leave everything with no account running. + +## Consequences + +- A release flag that was on for everyone before this is off for signed-out visitors until staff tick the setting. +- `spacePages` writes directory listings only once signed-out visitors have it, since a listing sends them to the page. +- The console marks a release flag "Ready to remove" only once signed-out visitors have had it for 30 days too, since deleting a flag gives it to every caller. +- `FLAG_OVERRIDES` forcing a flag on turns it on for signed-out visitors as well. +- A feature can't be tried on a share of signed-out visitors. One that needs that would need a new decision. diff --git a/docs/adr/0018-signed-out-visitors-get-a-rollout-id.md b/docs/adr/0018-signed-out-visitors-get-a-rollout-id.md deleted file mode 100644 index 604ffefa6..000000000 --- a/docs/adr/0018-signed-out-visitors-get-a-rollout-id.md +++ /dev/null @@ -1,26 +0,0 @@ -# Signed-out visitors get a rollout id - -The rule that decides a flag buckets a DID, and a signed-out visitor has none, so a percentage only ever counted accounts. That was fine while new features were for signed-in DJs. Public pages are different: most people who see an act, party, venue or event page aren't signed in, so a flag like `spacePages` could only go from a staff preview straight to everyone. - -So while a flag that changes a public page is on for a percentage, the website gives a signed-out browser an id of its own: a random version 4 UUID in a first-party cookie, `ln_flag_visitor`, for the site's whole path, `HttpOnly`, `SameSite=Lax`, `Secure` over https, kept for a year. The rule buckets `visitor:` followed by that UUID with the same sum it uses for a DID, so a browser gets the same answer on every request and stays in as the percentage grows. A DID starts `did:`, so a visitor's id is never an account's and is never targeted. `flags/vectors.json` has cases for visitor ids, which locallibrary's test reads as it reads any other id. - -Nothing else asks differently. `getFlags` and locallibrary ask with a DID or with nothing, and an xrpc call never reads a cookie, so a caller with neither still only gets flags on for everyone. The cookie is only set for a signed-out visitor outside `/xrpc/`, and only while a flag with `showsOn` in its catalog file is enabled, not on for everyone, and above 0%. A flag without `showsOn`, like `inboxEmail` or `userinputReports`, changes only what accounts see, so rolling it out to a percentage sets no cookie and keeps signed-out pages shared-cacheable. A flag that does change a public page has to list it in `showsOn`, or signed-out visitors stay out of its percentage. The server uses the id for flags alone and never stores or logs it; a request's log line only says whether the visitor's id was new. - -A signed-out page that depends on the id can't go in a shared cache. `cacheBriefly` marks signed-out pages `public`, and a visitor's first response sets the cookie, so a cache in front of the site could serve one visitor's answer and their cookie to the next. Nothing caches in front of the site today, but while a visitor id is in use the server hook turns `public` into `private` on the response. Browsers still cache their own copy. - -## Considered options - -- Leaving signed-out visitors out of percentages, as before: no cookie, and no gradual rollout of a public page. -- Bucketing by IP address or user agent: many people share an address, one person's changes between networks, and the hash would be built from personal data. -- An id in local storage, as LaunchDarkly's browser SDK keeps one: pages are rendered on the server, which can't read it on any request. -- Bucketing on the flag key alone, as Statsig does for an empty id: every visitor gets the same answer, so a percentage becomes a switch. -- Setting the cookie on every signed-out request: most of the time no flag needs it, and signed-out pages would never be shared-cacheable. -- Setting it while any flag is on for a percentage: a rollout of something only accounts see, like inbox email, would give every signed-out browser a cookie and make every public page private for as long as it ran. -- Relying on `Vary: Cookie`, which `cacheBriefly` already sends: a cached first response has no cookie to vary on, and carries its `Set-Cookie` to everyone after. - -## Consequences - -- Signing in moves someone from their browser's bucket to their account's, so a feature can appear or disappear for them at that moment. PostHog documents the same problem. -- Crawlers and anything else that drops cookies get a new id on every request, so during a percentage rollout they see the flag on at about that rate. A page that 404s while its flag is off will 404 to a crawler some of the time. `spacePages` writes no directory listing until it's on for everyone, which keeps those pages out of the directory meanwhile. -- A visitor can clear or edit the cookie to land somewhere else. Flags are for rolling something out, not for keeping anyone out, so that's allowed. -- While a flag with `showsOn` is on for a percentage, no signed-out response outside `/xrpc/` is shared-cacheable. diff --git a/docs/research/feature-flag-platforms.md b/docs/research/feature-flag-platforms.md index f620fa0fe..2ca7e97c2 100644 --- a/docs/research/feature-flag-platforms.md +++ b/docs/research/feature-flag-platforms.md @@ -16,7 +16,7 @@ Every platform in the set evaluates a flag the same way: it checks for a kill or | Reusable audiences | Segments, cohorts, saved groups, often rule-based | Named groups of up to 5000 DIDs | No rule-based membership | No | | Exclusions | Segment `excluded` lists (LD), "none of" (Statsig), `NONE` rules (Flagsmith) | None: any matching gate turns a flag on | Can't pull one account out of a rollout | Low | | Percentage rollout | Hash of salt plus stable id into 100 to 100,000 buckets | `sha256(key + did)`, first 4 bytes, mod 100, which ADR 0006 has locallibrary apply too | Coarse 1% steps, no re-salt | No | -| Signed-out visitors | Random device keys (LD, PostHog), random fallback (Unleash), bucket on salt alone (Statsig) | A random id in a first-party cookie while a public-page flag is on for a percentage, bucketed like a DID | None | None | +| Signed-out visitors | Random device keys (LD, PostHog), random fallback (Unleash), bucket on salt alone (Statsig) | A separate switch per flag, on only once every account has it | No partial rollout to signed-out visitors | Low, by design | | Prerequisites | Flag-on-flag dependencies in LD, Statsig, FME, ConfigCat, PostHog, GrowthBook, Unleash | None | None | No | | Kill switch | A dedicated off state that keeps targeting (LD off variation, FME kill, flagd `DISABLED`, GOFF `disable`) | `enabled: false` on the record, which keeps groups, accounts and percentage | None | Done | | Server evaluation | Full ruleset in memory, no network per check | Snapshot from SQLite, reloaded after each write or sync | None | No | @@ -73,7 +73,7 @@ The properties that matter are all there. The flag key acts as a per-flag salt, Shared vectors guard against a failure the platforms have run into, where SDKs in different languages drift apart. flagd changed its hashing in v0.18.0 and now requires flagd and every provider to upgrade together ([flagd fractional](https://flagd.dev/reference/custom-operations/fractional-operation/)). GrowthBook had to ship a second hash version after v1 "had a flaw that caused bias when running experiments in parallel" and pins UTF-16 code units to keep SDKs consistent ([GrowthBook SDK spec](https://docs.growthbook.io/lib/build-your-own)). Flipt's own docs describe its hash input differently from what its v2.14.1 code does ([Flipt concepts](https://docs.flipt.io/v2/concepts) vs [evaluation.go](https://github.com/flipt-io/flipt/blob/v2.14.1/internal/server/evaluation/evaluation.go#L240-L280)). One vectors file that every evaluator must pass is the cheap version of OpenFeature's provider conformance kit. -Two hashing features are missing, and neither matters yet. LaunchDarkly, Statsig and Flagsmith keep a salt separate from the flag key, so a flag can be renamed without reshuffling anyone, and an operator can re-salt on purpose to reshuffle: "To reshuffle all users, you must resalt the gate" ([Statsig FAQ](https://docs.statsig.com/faq/); [LD salt support article](https://support.launchdarkly.com/hc/en-us/articles/36961986486811-How-to-update-the-flag-salt); [Flagsmith models.py](https://github.com/Flagsmith/flagsmith/blob/v2.290.0/api/features/models.py#L774-L781)). In Local Network, renaming a key means a new catalog file and a fresh rollout anyway, so a separate salt would buy nothing. The second is signed-out visitors. LaunchDarkly gives them a random key kept in local storage, PostHog buckets by `$device_id`, Unleash falls back to a random number with no stickiness, and Statsig buckets empty IDs on the salt alone, so every anonymous visitor gets the same answer ([LD anonymous contexts](https://launchdarkly.com/docs/home/flags/anonymous-contexts); [PostHog device bucketing](https://posthog.com/docs/feature-flags/device-bucketing); [Unleash stickiness](https://docs.getunleash.io/reference/stickiness); [Statsig evaluation](https://docs.statsig.com/sdks/how-evaluation-works)). Local Network leaves signed-out visitors out of percentages ([flags/README.md](https://github.com/cutenode/localnetwork/blob/2f9d6c93a3b8dbb68fae3b9806ab85af26398ea5/flags/README.md#L17-L24)), which avoids PostHog's documented problem of a user's bucket changing after sign-in ([PostHog creating flags](https://posthog.com/docs/feature-flags/creating-feature-flags)). That's the right default for a site where new features are aimed at signed-in DJs. Public pages changed that: [ADR 0018](../adr/0018-signed-out-visitors-get-a-rollout-id.md) gives a signed-out browser a random id in a cookie while a flag is on for a percentage, and buckets it like a DID. Signing in still moves a visitor to their account's bucket. +Two hashing features are missing, and neither matters yet. LaunchDarkly, Statsig and Flagsmith keep a salt separate from the flag key, so a flag can be renamed without reshuffling anyone, and an operator can re-salt on purpose to reshuffle: "To reshuffle all users, you must resalt the gate" ([Statsig FAQ](https://docs.statsig.com/faq/); [LD salt support article](https://support.launchdarkly.com/hc/en-us/articles/36961986486811-How-to-update-the-flag-salt); [Flagsmith models.py](https://github.com/Flagsmith/flagsmith/blob/v2.290.0/api/features/models.py#L774-L781)). In Local Network, renaming a key means a new catalog file and a fresh rollout anyway, so a separate salt would buy nothing. The second is signed-out visitors. LaunchDarkly gives them a random key kept in local storage, PostHog buckets by `$device_id`, Unleash falls back to a random number with no stickiness, and Statsig buckets empty IDs on the salt alone, so every anonymous visitor gets the same answer ([LD anonymous contexts](https://launchdarkly.com/docs/home/flags/anonymous-contexts); [PostHog device bucketing](https://posthog.com/docs/feature-flags/device-bucketing); [Unleash stickiness](https://docs.getunleash.io/reference/stickiness); [Statsig evaluation](https://docs.statsig.com/sdks/how-evaluation-works)). Local Network leaves signed-out visitors out of percentages ([flags/README.md](https://github.com/cutenode/localnetwork/blob/2f9d6c93a3b8dbb68fae3b9806ab85af26398ea5/flags/README.md#L17-L24)), which avoids PostHog's documented problem of a user's bucket changing after sign-in ([PostHog creating flags](https://posthog.com/docs/feature-flags/creating-feature-flags)). That's the right default for a site where new features are aimed at signed-in DJs. Public pages kept it that way on purpose: [ADR 0018](../adr/0018-signed-out-visitors-come-last.md) gives each flag a separate switch for signed-out visitors, which can only go on once every account has the flag. The time-based rollout tools are where the paid tiers live. LaunchDarkly's progressive rollouts ramp a percentage on a schedule, and its guarded rollouts watch metrics and roll back automatically on a significant regression, which needs Enterprise plus the Guardian add-on ([LD progressive](https://launchdarkly.com/docs/home/releases/progressive-rollouts); [LD guarded](https://launchdarkly.com/docs/home/releases/guarded-rollouts)). Statsig has release pipelines and rollout alerts ([Statsig release pipeline](https://docs.statsig.com/release-pipeline); [rollout alerts](https://docs.statsig.com/metrics/rollout-alerts)). PostHog schedules changes on cron ([PostHog scheduled changes](https://posthog.com/docs/feature-flags/scheduled-flag-changes)), and GO Feature Flag offers `scheduledRollout` and `progressiveRollout` for free ([GOFF internal_flag.go](https://github.com/thomaspoignant/go-feature-flag/blob/v1.58.1/modules/core/flag/internal_flag.go#L209-L262)). Guarded rollouts need a metrics pipeline Local Network doesn't have, and scheduled ramps save a few clicks spread over a week. Neither is worth building. @@ -123,7 +123,7 @@ Local Network had the hard half from the start. Deleting a catalog file breaks t Each `flags/catalog/.json` has a `type`: `release`, `experiment`, `ops` or `permission`. Release and experiment flags must have a `removeBy` date (YYYY-MM-DD), and the other types can't have one. A unit test fails once a flag is past its `removeBy`, naming the flag. `parityCanary` is `ops`. -The `/admin/flags` list marks a release flag "Ready to remove" when it's enabled and either on for everyone or at 100%, and its record's `updatedAt` is 30 or more days old. That's PostHog's definition, worked out from fields already stored. Any saved change resets `updatedAt`, so editing a fully rolled-out flag starts its 30 days again. +The `/admin/flags` list marks a release flag "Ready to remove" when it's enabled, on for every account (everyone or 100%) and for signed-out visitors, and its record's `updatedAt` is 30 or more days old. That's PostHog's definition with signed-out visitors added, since deleting the flag gives it to them too, worked out from fields already stored. Any saved change resets `updatedAt`, so editing a fully rolled-out flag starts its 30 days again. Evaluation counts, the signal Unleash and LaunchDarkly lean on, would be useless here: the server hook evaluates every catalog flag on every request ([hooks.server.ts](https://github.com/cutenode/localnetwork/blob/2f9d6c93a3b8dbb68fae3b9806ab85af26398ea5/apps/web/src/hooks.server.ts#L103)), so every flag would always look in use. Exposure events and experiments, which LaunchDarkly, Statsig, FME, PostHog and GrowthBook build on top of evaluation logs ([PostHog exposures](https://posthog.com/docs/experiments/exposures); [GrowthBook results](https://docs.growthbook.io/app/experiment-results)), have no use here without an analytics pipeline, and the glossary's rollout-only scope rules them out anyway. @@ -139,20 +139,20 @@ Staff holding the `flags` grant can preview a flag from `/admin/flags/`, tu ## Gaps ranked for a project this size -The ranking weighs how likely each gap is to bite against what it costs to close. Rows 1, 3 to 6 and 9 are done. Row 2 is open. Rows 7, 8 and 10 are left as designed. - -| # | Gap | Status | When it matters | Fix | -| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -| 1 | `flags/**` was in neither the `web` nor the `locallibrary` CI path filter, so a PR that only touched the catalog or `vectors.json` ran no checks ([ci.yml web](https://github.com/cutenode/localnetwork/blob/2f9d6c93a3b8dbb68fae3b9806ab85af26398ea5/.github/workflows/ci.yml#L177-L199); [ci.yml locallibrary](https://github.com/cutenode/localnetwork/blob/2f9d6c93a3b8dbb68fae3b9806ab85af26398ea5/.github/workflows/ci.yml#L107-L124)). PR #456 promised this as a follow-up | Done | Now | `flags/**` is in both filters of `.github/workflows/ci.yml` | -| 2 | The locallibrary client isn't merged; main has ADR 0006 and the website endpoint, but no Rust code reads flags | Open | Before any locallibrary feature uses a flag | Deploy the website side, pass one live sign-in with a dev build, merge the client | -| 3 | Turning a flag off meant clearing all its targeting | Done | Before the first real rollout | Optional `enabled` on `staff.flag`, checked first, with new vectors and an "Off for everyone" switch | -| 4 | No developer or tester override | Done | Before the first real rollout | `FLAG_OVERRIDES` for development and tests; a signed preview cookie for staff | -| 5 | No type or removal date in the catalog, so nothing failed when a flag outlived its purpose | Done | Past about five flags | `type` and `removeBy` in the schema, plus a time-bomb test | -| 6 | No "fully rolled out" signal in the admin list | Done | Past about five flags | "Ready to remove" for enabled flags at `everyone` or 100% for 30+ days | -| 7 | Every catalog key reaches every browser; public gates are readable through `getFlags` | Left as designed | Only if a key name spoils a launch | Pick neutral key names | -| 8 | No per-account exclusion inside a rollout | Left as designed | If one account in a partial rollout hits a bug | A `notDids` list, only if it comes up | -| 9 | Signed-out visitors can't be in a percentage | Done | Before a public page rolls out to a share of visitors | A random id in a first-party cookie, bucketed like a DID ([ADR 0018](../adr/0018-signed-out-visitors-get-a-rollout-id.md)) | -| 10 | 1% steps, flag key as salt, no re-salt | Left as designed | Not at this scale | None | +The ranking weighs how likely each gap is to bite against what it costs to close. Rows 1 and 3 to 6 are done. Row 2 is open. Rows 7 to 10 are left as designed. + +| # | Gap | Status | When it matters | Fix | +| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| 1 | `flags/**` was in neither the `web` nor the `locallibrary` CI path filter, so a PR that only touched the catalog or `vectors.json` ran no checks ([ci.yml web](https://github.com/cutenode/localnetwork/blob/2f9d6c93a3b8dbb68fae3b9806ab85af26398ea5/.github/workflows/ci.yml#L177-L199); [ci.yml locallibrary](https://github.com/cutenode/localnetwork/blob/2f9d6c93a3b8dbb68fae3b9806ab85af26398ea5/.github/workflows/ci.yml#L107-L124)). PR #456 promised this as a follow-up | Done | Now | `flags/**` is in both filters of `.github/workflows/ci.yml` | +| 2 | The locallibrary client isn't merged; main has ADR 0006 and the website endpoint, but no Rust code reads flags | Open | Before any locallibrary feature uses a flag | Deploy the website side, pass one live sign-in with a dev build, merge the client | +| 3 | Turning a flag off meant clearing all its targeting | Done | Before the first real rollout | Optional `enabled` on `staff.flag`, checked first, with new vectors and an "Off for everyone" switch | +| 4 | No developer or tester override | Done | Before the first real rollout | `FLAG_OVERRIDES` for development and tests; a signed preview cookie for staff | +| 5 | No type or removal date in the catalog, so nothing failed when a flag outlived its purpose | Done | Past about five flags | `type` and `removeBy` in the schema, plus a time-bomb test | +| 6 | No "fully rolled out" signal in the admin list | Done | Past about five flags | "Ready to remove" for enabled release flags at `everyone` or 100%, signed-out visitors included, for 30+ days | +| 7 | Every catalog key reaches every browser; public gates are readable through `getFlags` | Left as designed | Only if a key name spoils a launch | Pick neutral key names | +| 8 | No per-account exclusion inside a rollout | Left as designed | If one account in a partial rollout hits a bug | A `notDids` list, only if it comes up | +| 9 | Signed-out visitors can't be in a percentage | Left as designed | Only for a rollout aimed at a share of anonymous visitors | None: signed-out visitors get a flag last, all at once ([ADR 0018](../adr/0018-signed-out-visitors-come-last.md)) | +| 10 | 1% steps, flag key as salt, no re-salt | Left as designed | Not at this scale | None | One smaller problem is also open. PR #456 notes that the pinned PDS doesn't enforce a space type's `collections`, so whether the production PDS accepts the staff collections hasn't been tested. If it refused them, saving a flag would fail and every flag would stay off ([PR #456](https://github.com/cutenode/localnetwork/pull/456)). That one belongs with row 2's live check, since the website deploy is a precondition anyway. diff --git a/flags/README.md b/flags/README.md index 6427fbeee..cdcd8dff9 100644 --- a/flags/README.md +++ b/flags/README.md @@ -6,9 +6,9 @@ Every flag has a `type`, `release` or `ops`. A `release` flag is meant to go, so A flag nobody has saved reads as off, so name a flag for the state you can switch it to. A kill switch, for something that already works, is named for the paused state, like `pauseRecordingStream`, and is `ops`: the deploy that adds it changes nothing, and turning it on stops the feature. Something that's dark today and should stay switchable after it ships, like inbox email, is named for the on state and is `ops` too, so it has no `removeBy`. Use `release` only for flags that go once the rollout is done. -A flag can list the kinds of page it changes in `showsOn`: `profile`, `act`, `party`, `venue`, `event`, `set`, `mix` or `pressKit`, or `global` for every page. An act's page is still `/projects/` until acts move. The flag's page in the staff console lists them under Shows on. Leave it out when the flag changes no public page, like a kill switch for the token exchange, something in the dashboard, or anything only signed-in accounts see. It also decides whether signed-out visitors are counted in a percentage: only a flag with `showsOn` gives them a rollout id. +A flag can list the kinds of page it changes in `showsOn`: `home`, `profile`, `act`, `party`, `venue`, `event`, `set`, `mix` or `pressKit`, or `global` for every page. An act's page is still `/projects/` until acts move. The flag's page in the staff console lists them under Shows on. Leave it out when the flag changes no public page, like a kill switch for the token exchange, something in the dashboard, or anything only signed-in accounts see. -Who a flag is on for lives in the staff space and is set at `/admin/flags`, not here. Every flag starts off. The list there marks a release flag "Ready to remove" once it's been on for everyone, or every account, for 30 days, and its page shows when it should be gone by. +Who a flag is on for lives in the staff space and is set at `/admin/flags`, not here. Every flag starts off. The list there marks a release flag "Ready to remove" once every account and signed-out visitors have had it for 30 days, and its page shows when it should be gone by. ```jsonc { @@ -21,20 +21,23 @@ Who a flag is on for lives in the staff space and is set at `/admin/flags`, not } ``` -Check a flag on the website with `locals.flags.newPlanner` on the server or `data.flags?.newPlanner` in a page. An xrpc route never reads a cookie, so it only gets flags on for everyone: targeting and percentages don't reach it. A route that has checked a service token can call `app.flags.evaluate(did)` with that token's DID to get them. +Check a flag on the website with `locals.flags.newPlanner` on the server or `data.flags?.newPlanner` in a page. An xrpc route gets the flags a signed-out visitor does, since the website never reads the sign-in cookie there: targeting and percentages don't reach it. A route that has checked a service token can call `app.flags.evaluate(did)` with that token's DID to get them. In locallibrary, use `locallibrary::flags::check(root, flags::keys::NEW_PLANNER)`. A flag in locallibrary is for rolling something out. Anything that has to be enforced belongs on the server, since anyone can change what's on their own computer. ## How a flag is decided ```text -bucket(key, id) = the first 4 bytes of sha256(key + id), big-endian, mod 100 -on = enabled && (everyone || targeted || (id is known && bucket(key, id) < percentage)) +bucket(key, did) = the first 4 bytes of sha256(key + did), big-endian, mod 100 +with a DID: on = enabled && (everyone || targeted || bucket(key, did) < percentage) +with no DID: on = enabled && signedOut && (everyone || percentage >= 100) ``` -`enabled` is false once someone turns the flag off for everyone, which keeps the other gates for when it's back on. A record that doesn't say is enabled. `targeted` means the account is one of the flag's accounts or in one of its groups. Only the website can know that, since those lists are private; it says so through `computer.localnetwork.flags.getFlags`. `id` is the caller's DID. A signed-out visitor has none, so while a flag with `showsOn` is on for a percentage the website gives their browser a random id in a first-party cookie, `ln_flag_visitor`, and buckets `visitor:` followed by it. They get the same answer on every request until they clear it or sign in, when their account's bucket takes over. A caller with neither, like an xrpc call, only gets flags on for everyone. Raising a percentage only adds accounts and browsers. [ADR 0018](../docs/adr/0018-signed-out-visitors-get-a-rollout-id.md) covers why, and what it means for caching and crawlers. +`enabled` is false once someone turns the flag off for everyone, which keeps the other gates for when it's back on. A record that doesn't say is enabled. `everyone` means every signed-in account. `targeted` means the account is one of the flag's accounts or in one of its groups. Only the website can know that, since those lists are private; it says so through `computer.localnetwork.flags.getFlags`. Raising a percentage only adds accounts. -`vectors.json` holds computed answers, for DIDs, visitor ids and callers with neither. The website's and locallibrary's tests both run them, so the two can't come to disagree. A case without `enabled` is enabled. If a case has to change, the rule changed, and accounts will move in or out of every rollout. +A caller with no DID comes last: a signed-out visitor, an xrpc call, background work on the server, or locallibrary signed out. A release flag is on for them only once staff tick Signed-out visitors on its page, which sets `signedOut`, and only while every account has the flag. The console refuses it before then, and a save that takes the flag below every account turns it off again. A record that doesn't say has it off. An ops flag has no setting of its own: its `signedOut` is always the same as `everyone`, so a kill switch turned on for everyone also stops what runs with no account. There's no percentage of signed-out visitors and no cookie for them, so signed-out pages stay shared-cacheable. [ADR 0018](../docs/adr/0018-signed-out-visitors-come-last.md) covers why. + +`vectors.json` holds computed answers. The website's and locallibrary's tests both run them, so the two can't come to disagree. A case without `enabled` is enabled, and one without `signedOut` is a flag signed-out visitors don't have. If a case has to change, the rule changed, and accounts will move in or out of every rollout. ## Trying a flag diff --git a/flags/catalog/spacePages.json b/flags/catalog/spacePages.json index 287cc1a13..40ba1f309 100644 --- a/flags/catalog/spacePages.json +++ b/flags/catalog/spacePages.json @@ -1,7 +1,7 @@ { "$schema": "../flag.schema.json", "key": "spacePages", - "description": "The public act, party, venue and event pages. Off, they answer 404, and no listing is written until it's on for everyone, since a listing points at a public page.", + "description": "The public act, party, venue and event pages. Off, they answer 404, and no listing is written until it's on for signed-out visitors, since a listing points at a public page.", "type": "release", "removeBy": "2027-02-12", "showsOn": ["act", "party", "venue", "event"] diff --git a/flags/vectors.json b/flags/vectors.json index ff356d1e1..a18495d64 100644 --- a/flags/vectors.json +++ b/flags/vectors.json @@ -1,5 +1,5 @@ { - "$comment": "Computed answers both the website and locallibrary test themselves against. `did` is the id the rule buckets: an account's DID, a signed-out visitor's `visitor:` id from the website's cookie, or null for a caller with neither. A case without `enabled` is a record that doesn't say, which counts as true. Add cases freely; changing one means the rule changed, and every account can move.", + "$comment": "Computed answers both the website and locallibrary test themselves against. `did` is null for a caller with no account, like a signed-out visitor. A case without `enabled` is a record that doesn't say, which counts as true. A case without `signedOut` is a flag signed-out visitors don't have. Add cases freely; changing one means the rule changed, and every account can move.", "cases": [ { "key": "parityCanary", @@ -139,6 +139,7 @@ { "key": "parityCanary", "did": null, + "signedOut": true, "everyone": true, "targeted": false, "percentage": 0, @@ -292,6 +293,7 @@ { "key": "newPlanner", "did": null, + "signedOut": true, "everyone": true, "targeted": false, "percentage": 0, @@ -445,6 +447,7 @@ { "key": "a", "did": null, + "signedOut": true, "everyone": true, "targeted": false, "percentage": 0, @@ -598,6 +601,7 @@ { "key": "mixUploads2", "did": null, + "signedOut": true, "everyone": true, "targeted": false, "percentage": 0, @@ -697,6 +701,7 @@ "key": "parityCanary", "did": null, "enabled": true, + "signedOut": true, "everyone": true, "targeted": false, "percentage": 0, @@ -745,56 +750,93 @@ }, { "key": "parityCanary", - "did": "visitor:00000000-0000-4000-8000-000000000000", - "everyone": false, + "did": null, + "signedOut": false, + "everyone": true, "targeted": false, - "percentage": 16, - "bucket": 16, + "percentage": 0, + "bucket": null, "on": false }, { "key": "parityCanary", - "did": "visitor:00000000-0000-4000-8000-000000000000", + "did": null, + "signedOut": true, "everyone": false, "targeted": false, - "percentage": 17, - "bucket": 16, + "percentage": 100, + "bucket": null, "on": true }, { "key": "parityCanary", - "did": "visitor:00000008-0000-4000-8000-000000000000", + "did": null, + "signedOut": true, "everyone": false, "targeted": false, "percentage": 99, - "bucket": 99, + "bucket": null, "on": false }, { "key": "parityCanary", - "did": "visitor:00000008-0000-4000-8000-000000000000", + "did": null, + "signedOut": true, "everyone": false, + "targeted": true, + "percentage": 0, + "bucket": null, + "on": false + }, + { + "key": "parityCanary", + "did": null, + "enabled": false, + "signedOut": true, + "everyone": true, "targeted": false, "percentage": 100, - "bucket": 99, - "on": true + "bucket": null, + "on": false }, { - "key": "spacePages", - "did": "visitor:00000000-0000-4000-8000-000000000000", + "key": "parityCanary", + "did": "did:plc:z72i7hdynmk6r22z27h6tvur", + "signedOut": true, "everyone": false, "targeted": false, - "percentage": 57, - "bucket": 57, + "percentage": 48, + "bucket": 48, "on": false }, { - "key": "spacePages", - "did": "visitor:00000000-0000-4000-8000-000000000000", + "key": "parityCanary", + "did": "did:plc:z72i7hdynmk6r22z27h6tvur", + "signedOut": true, "everyone": false, "targeted": false, - "percentage": 58, - "bucket": 57, + "percentage": 49, + "bucket": 48, + "on": true + }, + { + "key": "parityCanary", + "did": "did:plc:z72i7hdynmk6r22z27h6tvur", + "signedOut": true, + "everyone": false, + "targeted": false, + "percentage": 0, + "bucket": 48, + "on": false + }, + { + "key": "parityCanary", + "did": "did:plc:z72i7hdynmk6r22z27h6tvur", + "signedOut": false, + "everyone": true, + "targeted": false, + "percentage": 0, + "bucket": 48, "on": true } ] diff --git a/lexicons/computer/localnetwork/flags/getFlags.json b/lexicons/computer/localnetwork/flags/getFlags.json index cf4f7bddf..24bc44910 100644 --- a/lexicons/computer/localnetwork/flags/getFlags.json +++ b/lexicons/computer/localnetwork/flags/getFlags.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "query", - "description": "Every feature flag's public gates, and whether the caller is targeted by account or group. Inter-service auth is optional: without it, nothing is targeted. A flag is on for a caller when it's enabled and it's on for everyone, targets them, or their DID falls inside the percentage. Group names and member lists aren't exposed.", + "description": "Every feature flag's public gates, and whether the caller is targeted by account or group. Inter-service auth is optional: without it, nothing is targeted. A flag is on for a signed-in caller when it's enabled and it's on for everyone, targets them, or their DID falls inside the percentage. With no account, it's on when it's enabled, signedOut is true, and it's on for everyone or 100%. Group names and member lists aren't exposed.", "output": { "encoding": "application/json", "schema": { @@ -32,7 +32,11 @@ "type": "boolean", "description": "False means off for every caller, whatever the other gates say." }, - "everyone": { "type": "boolean" }, + "signedOut": { + "type": "boolean", + "description": "Callers with no account have it too, once it's on for everyone or 100%. Missing means false." + }, + "everyone": { "type": "boolean", "description": "On for every signed-in account." }, "percentage": { "type": "integer", "minimum": 0, "maximum": 100 }, "targeted": { "type": "boolean", diff --git a/lexicons/computer/localnetwork/staff/flag.json b/lexicons/computer/localnetwork/staff/flag.json index ac2b1df6c..a742ee56f 100644 --- a/lexicons/computer/localnetwork/staff/flag.json +++ b/lexicons/computer/localnetwork/staff/flag.json @@ -15,7 +15,11 @@ "type": "boolean", "description": "False turns it off for everyone and keeps the gates below for when it's back on. Missing means true." }, - "everyone": { "type": "boolean", "description": "On for every visitor, signed in or not." }, + "signedOut": { + "type": "boolean", + "description": "Signed-out visitors have it too. Only counts while it's on for every account, so it's turned on last. Missing means false for a release flag and the same as everyone for an ops flag." + }, + "everyone": { "type": "boolean", "description": "On for every signed-in account." }, "percentage": { "type": "integer", "minimum": 0, From 0501fa92a1485863ae47ad132c7a4da9d3b7cc9a Mon Sep 17 00:00:00 2001 From: botandbang <337765928+botandbang@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:12:38 -0600 Subject: [PATCH 12/22] test(web): expect signedOut in getFlags' answers getFlags now sends each flag's signedOut gate, and its tests still expected answers without it. Fixes LOC-321 --- apps/web/src/lib/server/flags/get-flags.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/web/src/lib/server/flags/get-flags.test.ts b/apps/web/src/lib/server/flags/get-flags.test.ts index 9d333afcc..e7c41a663 100644 --- a/apps/web/src/lib/server/flags/get-flags.test.ts +++ b/apps/web/src/lib/server/flags/get-flags.test.ts @@ -55,7 +55,9 @@ describe('getFlags', () => { expect(response.status).toBe(200); expect(await response.json()).toEqual({ - flags: [{ key: 'parityCanary', enabled: true, everyone: false, percentage: 25, targeted: false }] + flags: [ + { key: 'parityCanary', enabled: true, everyone: false, percentage: 25, signedOut: false, targeted: false } + ] }); expect(response.headers.get('cache-control')).toBe('public, max-age=60'); expect(response.headers.get('vary')).toBe('authorization'); @@ -65,7 +67,7 @@ describe('getFlags', () => { const response = await ask(await token()); expect(await response.json()).toEqual({ - flags: [{ key: 'parityCanary', enabled: true, everyone: false, percentage: 25, targeted: true }] + flags: [{ key: 'parityCanary', enabled: true, everyone: false, percentage: 25, signedOut: false, targeted: true }] }); expect(response.headers.get('cache-control')).toBe('private, no-store'); expect(response.headers.get('vary')).toBe('authorization'); From a149f5fe91ef11dc658d086ea98be70e56e3df45 Mon Sep 17 00:00:00 2001 From: botandbang <337765928+botandbang@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:32:58 -0600 Subject: [PATCH 13/22] ci(labels): label the flags, locale and langs files Fixes the policy check on #754. --- .github/labeler.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/labeler.yml b/.github/labeler.yml index 10a451195..5dd081773 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -141,7 +141,7 @@ atstore: - "apps/web/src/lib/{audit-sentences,requests,request-standing,capabilities,bug-report,verification}.*" - "apps/web/src/lib/server/services/{staff,flags,project-admin,requests,diff,bug-reports,verifications}.*" - "apps/web/src/lib/server/forms/flags.*" - - "apps/web/src/lib/server/flags/**" + - "apps/web/src/lib/{,server/}flags/**" - "flags/**" - "apps/web/src/lib/server/audit/**" - "apps/web/src/lib/components/DiffTable.svelte" @@ -173,7 +173,7 @@ atstore: - "apps/web/src/{hooks.server,app.d}.*" - "apps/web/src/lib/{nsid,types,space-paths}.*" - "apps/web/src/lib/server/{atproto,db,happyview,sync,testing,backup}/**" - - "apps/web/src/lib/server/{app,bootstrap,compress,config,core,edit-mode,http,logger,rate-limit}.*" + - "apps/web/src/lib/server/{app,bootstrap,compress,config,core,edit-mode,http,langs,logger,rate-limit}.*" - "apps/web/src/lib/server/{env-files,crawler-head,images,utf8,moved-pages,meta,meta-records,structured-data}.*" - "apps/web/src/lib/server/services/{shared-spaces,space-joins,space-members,manager-spaces,own-repo,held-records,services}.*" - "apps/web/src/routes/{xrpc,.well-known,media,healthz}/**" @@ -193,7 +193,7 @@ atstore: - "!apps/web/src/lib/components/profile.svelte.test.ts" - any-glob-to-any-file: - "apps/web/src/lib/{ui,assets,og}/**" - - "apps/web/src/lib/{format,nav,combobox,form-*,hotkeys,headline,hosts,meta,structured-data,home,resolved,web-url}.*" + - "apps/web/src/lib/{format,nav,combobox,form-*,hotkeys,headline,hosts,locale,test-locale,meta,structured-data,home,resolved,web-url}.*" - "apps/web/src/lib/server/og/**" - "apps/web/src/lib/server/{home,landing,social-home}.*" - "apps/web/src/routes/{+layout,+error,layout,error,heads,link-matrix,listings,stored-images,social-home}.*" From a33a1ec737317c08e3843d7094332aa914fc3f0b Mon Sep 17 00:00:00 2001 From: botandbang <337765928+botandbang@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:21:48 -0600 Subject: [PATCH 14/22] fix(web): give signed-out callers an ops flag saved at 100% A kill switch saved at 100% without "everyone" never reached callers with no DID, so background rounds kept running with pauseReconcilers on. An ops flag's signedOut now follows every account having it, everyone or 100%. --- apps/web/src/lib/server/app.test.ts | 21 +++++++++++++++++++ .../web/src/lib/server/services/flags.test.ts | 12 +++++++---- apps/web/src/lib/server/services/flags.ts | 8 ++++--- .../src/routes/admin/flags/[key]/+page.svelte | 2 +- .../src/atmosphere/flags/tests.rs | 10 +++++++-- crates/locallibrary/tests/support/mock_pds.rs | 4 ++-- .../adr/0018-signed-out-visitors-come-last.md | 2 +- flags/README.md | 2 +- .../computer/localnetwork/staff/flag.json | 2 +- 9 files changed, 48 insertions(+), 15 deletions(-) diff --git a/apps/web/src/lib/server/app.test.ts b/apps/web/src/lib/server/app.test.ts index 3b6d16719..254d53fee 100644 --- a/apps/web/src/lib/server/app.test.ts +++ b/apps/web/src/lib/server/app.test.ts @@ -661,6 +661,27 @@ describe('start', () => { expect(notes().some((note) => note.message === 'reconciled venue blocks')).toBe(true); }); + it('skip the rounds that write once pauseReconcilers is saved at 100%, with no account to ask for', async () => { + const { logger, notes } = writtenLog('info'); + const app = await start(HOURLY, logger); + await app.flags.indexFlag(`at://${ROOT}/${COLLECTION.staffFlag}/pauseReconcilers`, { + key: 'pauseReconcilers', + everyone: false, + percentage: 100, + groups: [], + dids: [], + updatedBy: ROOT, + updatedAt: nowIso() + }); + app.start(); + + await vi.advanceTimersByTimeAsync(60 * 60_000); + await vi.waitFor(() => + expect(notes().filter((note) => note.flag === 'pauseReconcilers' && note.round === 'listings')).toHaveLength(1) + ); + expect(deletes()).toBe(0); + }); + it('skip the rounds a bootstrap runs while pauseReconcilers is on', async () => { const { logger, notes } = writtenLog('info'); const app = await start({ ...NO_KEY, FLAG_OVERRIDES: 'pauseReconcilers=on' }, logger); diff --git a/apps/web/src/lib/server/services/flags.test.ts b/apps/web/src/lib/server/services/flags.test.ts index 1096daa89..f722f8b65 100644 --- a/apps/web/src/lib/server/services/flags.test.ts +++ b/apps/web/src/lib/server/services/flags.test.ts @@ -112,13 +112,17 @@ describe('FlagService', () => { expect(await t.flags.evaluate(OTHER)).toEqual({ ...flagsOff, [FLAG]: true }); }); - it('gives a signed-out visitor an ops flag only while it is on for everyone', async () => { + it('gives a signed-out visitor an ops flag only while every account has it', async () => { const admin = await t.viewer(ADMIN); - await t.flags.updateFlag(admin, FLAG, { ...off, percentage: 100, dids: [DJ] }); + await t.flags.updateFlag(admin, FLAG, { ...off, percentage: 99, dids: [DJ] }); expect(await t.flags.evaluate(DJ)).toEqual({ ...flagsOff, [FLAG]: true }); expect(await t.flags.evaluate(null)).toEqual({ ...flagsOff, [FLAG]: false }); + await t.flags.updateFlag(admin, FLAG, { ...off, percentage: 100 }); + + expect(await t.flags.evaluate(null)).toEqual({ ...flagsOff, [FLAG]: true }); + await t.flags.updateFlag(admin, FLAG, { ...off, everyone: true }); expect(await t.flags.evaluate(null)).toEqual({ ...flagsOff, [FLAG]: true }); @@ -178,14 +182,14 @@ describe('FlagService', () => { expect(await t.flags.evaluate(null)).toMatchObject({ [RELEASE]: false }); }); - it('follow everyone for an ops flag, whatever a save asks, so a kill switch works with no account', async () => { + it('follow every account for an ops flag, whatever a save asks, so a kill switch works with no account', async () => { const admin = await t.viewer(ADMIN); await t.flags.updateFlag(admin, PAGE_FLAG, { ...off, everyone: true }); expect(await t.flags.evaluate(null)).toMatchObject({ [PAGE_FLAG]: true }); expect(stored(COLLECTION.staffFlag, PAGE_FLAG)?.value).toMatchObject({ signedOut: true }); - await t.flags.updateFlag(admin, PAGE_FLAG, { ...off, percentage: 100, signedOut: true }); + await t.flags.updateFlag(admin, PAGE_FLAG, { ...off, percentage: 99, signedOut: true }); expect(await t.flags.evaluate(null)).toMatchObject({ [PAGE_FLAG]: false }); expect(await t.flags.flag(PAGE_FLAG)).toMatchObject({ signedOut: false }); diff --git a/apps/web/src/lib/server/services/flags.ts b/apps/web/src/lib/server/services/flags.ts index b4d143775..f61b8f5fe 100644 --- a/apps/web/src/lib/server/services/flags.ts +++ b/apps/web/src/lib/server/services/flags.ts @@ -69,13 +69,15 @@ const isOps = (key: string) => FLAGS.some((flag) => flag.key === key && flag.typ /** * Whether signed-out visitors have `key`, from what a record says or a save asks for. A kill switch has to work where * there's no account (xrpc routes, background rounds, signed-out locallibrary), so an ops flag has no setting of its - * own: it follows `everyone`. A release flag's is off unless staff turn it on, and only holds while every account has + * own: it's on for them once it's on for every account, `everyone` or 100%. A release flag's is off unless staff turn it on, and only holds while every account has * the flag, so lowering it for accounts turns it off for signed-out visitors too. */ function signedOutFor(key: string, gates: Pick, asked: boolean | undefined) { - if (isOps(key)) return gates.everyone; + const everyAccount = gates.everyone || gates.percentage === 100; - return !!asked && (gates.everyone || gates.percentage === 100); + if (isOps(key)) return everyAccount; + + return !!asked && everyAccount; } /** diff --git a/apps/web/src/routes/admin/flags/[key]/+page.svelte b/apps/web/src/routes/admin/flags/[key]/+page.svelte index 07e5f0783..d18ae1c74 100644 --- a/apps/web/src/routes/admin/flags/[key]/+page.svelte +++ b/apps/web/src/routes/admin/flags/[key]/+page.svelte @@ -77,7 +77,7 @@

Accounts stay in as this grows.

{#if flag.type === 'release'} -