-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsettings.ts
More file actions
623 lines (593 loc) · 27.4 KB
/
Copy pathsettings.ts
File metadata and controls
623 lines (593 loc) · 27.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
import { eq, inArray } from 'drizzle-orm';
import { siteSettings } from './db/schema';
import { APP_NAME } from '$lib/config';
import { DEFAULT_GALLERY_SORT, isValidGallerySort, type GallerySort } from '$lib/gallery';
import {
supporterKeyStatusFromResult,
verifySupporterKey,
type SupporterKeyResult,
type SupporterKeyStatus
} from './supporter-key';
import type { Database } from './db';
export type StorageProviderId = 'uploadthing' | 'r2';
export interface SiteSettings {
siteName: string;
/** The site owner's / persona's display name (e.g. shown on the About page).
* Empty falls back to `siteName` at the point of use. */
ownerName: string;
/** The owner's pronouns, exactly as they typed them (e.g. "they/them",
* "彼/かれ"). ONE free-text field, rendered verbatim everywhere it appears:
* never parsed into parts, never localized, never matched against a list.
* Pronoun sets are personal and open-ended, and a picker or a translation
* would be the software deciding which ones exist. Empty → nothing renders,
* with no space held for it. */
pronouns: string;
aboutText: string;
/** Contact email shown on /share for larger photo batches. */
contactEmail: string;
/** Canonical https origin (no trailing slash) used to build links in outgoing
* emails (e.g. the password-reset link), so an alias/preview host hitting the
* form doesn't mail a link to itself. Empty → the request origin is used. */
siteUrl: string;
/** Locale for automated emails (e.g. password resets). One of the site's
* available locales; empty/invalid → the base locale. */
emailLanguage: string;
/** Owner-editable override for the /privacy page body (plain text). Empty →
* the code-accurate default policy from `$lib/legal` is shown instead. */
privacyPolicy: string;
/** Owner-editable override for the /terms page body (plain text). Empty →
* the default terms from `$lib/legal` are shown instead. */
termsOfService: string;
/** Date (YYYY-MM-DD) the /privacy override text was last changed, stamped when
* that page's override is saved. Drives its "Last updated" line when an
* override is set. Empty → the page shows the built-in defaults' date instead. */
privacyUpdatedAt: string;
/** Date (YYYY-MM-DD) the /terms override text was last changed, stamped when
* that page's override is saved. Drives its "Last updated" line when an
* override is set. Empty → the page shows the built-in defaults' date instead. */
termsUpdatedAt: string;
/** Whether the /ai disclosure page (and its footer link) is served. Stored
* as 'true'/'false'; ABSENT MEANS ON (SONA-167).
*
* The polarity is a deliberate operator decision, not an oversight. Every
* site that is already live keeps the page on, and the Settings toggle is
* how an owner turns it off; the marketing site carries a platform-level
* version of the same disclosure (SONA-178), so the software's use of AI is
* explained for every fork whether or not that fork publishes its own page.
*
* New installs do not rely on the default: the setup wizard writes the row
* explicitly from its affirmation checkbox, so the first-person claims in
* the default copy are owner-affirmed there. One path skips that — a fork
* bootstrapped with the ADMIN_PASSWORD env var counts as setup-complete
* (see getSetupState) and never runs the wizard, so it lands on the
* absent default like a pre-existing install. Both cases are covered by the
* SONA-167 section in UPDATING.md, which names the claims the page makes in
* the owner's voice and where to turn it off. */
aiPageEnabled: boolean;
/** Owner-editable override for the /ai page body (plain text). Empty → the
* default disclosure copy from `$lib/ai-disclosure` is shown instead.
* Server-only beyond /ai itself: it is absent from the public allowlist
* below, so no public payload carries it, and /ai's own load returns it. */
aiPageText: string;
/** Date (YYYY-MM-DD) the /ai override text was last changed, stamped when
* that page's override is saved. Drives its "Last updated" line when an
* override is set. Empty → no line (the default copy shows none). */
aiPageUpdatedAt: string;
/** Whether /feed.xml (and its footer link and head autodiscovery) is served.
* Stored as 'true'/'false'; ABSENT MEANS ON (SONA-172) — the same polarity,
* for the same reason, as aiPageEnabled above.
*
* A feed of already-public pages publishes nothing a visitor could not
* already read, so defaulting it on costs an existing fork nothing, and the
* Settings toggle is how an owner who does not want their uploads
* syndicated turns it off. Turning it off also removes the feed paragraph
* from the default privacy policy, since that paragraph describes a feed
* the site no longer publishes. */
rssFeedEnabled: boolean;
/** Whether the feed will serve NSFW work AT ALL, to anyone. Default OFF, and
* off is a hard gate: with this off there is no address that returns adult
* items, whatever key is presented.
*
* Server-only, like the key below. The public feed never reveals whether an
* adult variant exists — a wrong or absent key returns the ordinary SFW
* document rather than an error, so nothing distinguishes "no NSFW feed" from
* "an NSFW feed you do not have the key for". */
rssNsfwEnabled: boolean;
/** The unguessable token that unlocks the adult feed: /feed.xml?key=<this>.
* 128 bits of hex, minted server-side (see mintFeedKey) when the owner first
* turns rssNsfwEnabled on, and replaced by the Regenerate control — which
* kills the old address. Empty means no key has been minted yet.
*
* NEVER allowlisted for public payloads: it is a bearer credential, and the
* (public) layout load rides every page on the site. */
rssNsfwKey: string;
// --- Sona / reference profile (shown on /art, part of the threePath landing) ---
// The reference sheet itself is the most recent published gallery image
// tagged "reference" — not stored here (see /art load).
sonaSpecies: string;
sonaBuild: string;
sonaKeyFeatures: string;
/** JSON array of { name, hex } color swatches. */
sonaColors: string;
/** Newline-separated "do" items (what artists are encouraged to do). */
sonaDos: string;
/** Newline-separated "don't" items. */
sonaDonts: string;
twitterUrl: string;
blueskyUrl: string;
telegramUrl: string;
furAffinityUrl: string;
instagramUrl: string;
furtrackUrl: string;
adminAvatarUrl: string;
/** The site's main character / FurTrack tag — who the site is for. Used to
* default the fursuit import and the gallery's fursuit view. */
primaryCharacter: string;
/** Active image store for the whole site (gallery + fursuit photos). */
storageProvider: StorageProviderId;
/** Public base URL for R2-served images (the bucket's custom domain). */
r2PublicUrl: string;
/** When on, the daily cron pulls new stickers into Telegram-sourced packs.
* Opt-in — defaults off so the scheduled job does nothing until enabled. */
autoResyncEnabled: boolean;
/** Active visual theme (palette family) id — see src/lib/themes. Applied at
* SSR via a data-theme-id attribute; orthogonal to the dark/light mode. */
themeId: string;
/** Landing-page layout id — see src/lib/landing (e.g. 'mosaic' | 'threePath'). */
landingLayout: string;
/** Subtitle under the wordmark on the threePath splash. Empty falls back to
* the localized default (m.splash_subtitle) at the point of use. */
splashSubtitle: string;
/** When on, the registry sync overwrites locally-edited artist fields (name,
* avatar, socials) for registry-linked artists. Off (default) keeps local
* edits and only fills empty fields. */
registryOverridesLocal: boolean;
/** Default gallery sort when a request carries no ?sort= param. One of the
* four gallery sort keys; an explicit param still wins. */
galleryDefaultSort: GallerySort;
}
export interface SonaColor {
name: string;
hex: string;
}
/** Parse the stored sonaColors JSON into a typed array, tolerating bad data. */
export function parseSonaColors(raw: string): SonaColor[] {
try {
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
return parsed
.filter((c) => c && typeof c.hex === 'string')
.map((c) => ({ name: String(c.name ?? ''), hex: String(c.hex) }));
} catch {
return [];
}
}
/** Split a newline-separated list setting into trimmed, non-empty lines. */
export function parseLines(raw: string): string[] {
return raw
.split('\n')
.map((l) => l.trim())
.filter(Boolean);
}
/**
* The settings that may ride a public page's client payload.
*
* An allowlist, not a denylist: a field added to `SiteSettings` stays
* server-only until it is named here, so nothing reaches every visitor by
* default. settings.classification.test.ts fails when a key is in neither this
* list nor SERVER_ONLY_SETTINGS_KEYS, which forces the call at review time.
*/
export const PUBLIC_SETTINGS_KEYS = [
'siteName',
'ownerName',
'pronouns',
'aboutText',
'contactEmail',
'siteUrl',
'emailLanguage',
'privacyPolicy',
'termsOfService',
'privacyUpdatedAt',
'termsUpdatedAt',
'aiPageEnabled',
'aiPageUpdatedAt',
// The footer link and the head autodiscovery tag are rendered from this, so
// it has to reach the client. It says nothing the feed itself does not.
'rssFeedEnabled',
'sonaSpecies',
'sonaBuild',
'sonaKeyFeatures',
'sonaColors',
'sonaDos',
'sonaDonts',
'twitterUrl',
'blueskyUrl',
'telegramUrl',
'furAffinityUrl',
'instagramUrl',
'furtrackUrl',
'adminAvatarUrl',
'primaryCharacter',
'storageProvider',
'r2PublicUrl',
'autoResyncEnabled',
'themeId',
'landingLayout',
'splashSubtitle',
'registryOverridesLocal',
'galleryDefaultSort'
] as const satisfies readonly (keyof SiteSettings)[];
/**
* Settings deliberately withheld from public payloads. Naming a key here is
* what lets the classification test pass without publishing it.
*
* `aiPageText`: the (public) layout load rides every public page, so shipping
* the override there would keep publishing a fork's /ai copy after the owner
* turned the page off. /ai's own load returns it, behind that route's 404 gate.
*/
export const SERVER_ONLY_SETTINGS_KEYS = [
'aiPageText',
// A bearer credential. Publishing it in the layout payload would hand the
// adult feed's address to every visitor of every page, which is the whole
// thing the key exists to prevent.
'rssNsfwKey',
// Withheld so the public surface cannot answer "does an adult feed exist
// here?" — the same reason a wrong key returns the SFW document rather than
// an error.
'rssNsfwEnabled'
] as const satisfies readonly (keyof SiteSettings)[];
/** The settings shape public pages receive — exactly PUBLIC_SETTINGS_KEYS. */
export type PublicSiteSettings = Pick<SiteSettings, (typeof PUBLIC_SETTINGS_KEYS)[number]>;
/**
* Narrow full settings to the public allowlist. Every public load returns
* settings through this helper, so a new one cannot forget the narrowing.
*
* The input is a fully-populated `SiteSettings` (what getSettings and
* settingsFallback return): every allowlisted key is emitted, so a partial
* object would yield those keys with undefined values rather than absent.
*/
export function toPublicSettings(settings: SiteSettings): PublicSiteSettings {
return Object.fromEntries(
PUBLIC_SETTINGS_KEYS.map((key) => [key, settings[key]])
) as PublicSiteSettings;
}
// Neutral, brand-agnostic defaults. A real deployment overrides these via the
// first-run setup wizard / admin Settings (stored as site_settings rows); the
// example sparky.ink config seeds its own values. Keep these generic so a fresh
// fork starts unbranded rather than impersonating another site.
//
// Exported because the compiler forces this literal to carry every
// `SiteSettings` key, which makes it the runtime inventory of the interface —
// what the classification test checks the public/server-only lists against.
export const DEFAULTS: SiteSettings = {
siteName: APP_NAME,
ownerName: '',
pronouns: '',
aboutText: 'A personal gallery for collecting and showcasing furry artwork from talented artists.',
// The three-path pages (/art, /connect, /share) render gracefully with these
// empty — sections that have no data simply don't show.
contactEmail: '',
// Empty → outgoing-email links use the request origin; emails render in baseLocale.
siteUrl: '',
emailLanguage: '',
// Empty → /privacy and /terms render the code-accurate defaults from $lib/legal.
privacyPolicy: '',
termsOfService: '',
// Empty → the legal pages show the built-in defaults' date (LEGAL_DEFAULTS_UPDATED).
privacyUpdatedAt: '',
termsUpdatedAt: '',
// The /ai disclosure page defaults ON fleet-wide; '' override → the default
// copy from $lib/ai-disclosure.
aiPageEnabled: true,
aiPageText: '',
aiPageUpdatedAt: '',
// The feed defaults ON fleet-wide (it syndicates only already-public pages);
// serving NSFW work through it is strictly opt-in, and has no key until the
// owner opts in.
rssFeedEnabled: true,
rssNsfwEnabled: false,
rssNsfwKey: '',
sonaSpecies: '',
sonaBuild: '',
sonaKeyFeatures: '',
sonaColors: '[]',
sonaDos: '',
sonaDonts: '',
twitterUrl: '',
blueskyUrl: '',
telegramUrl: '',
furAffinityUrl: '',
instagramUrl: '',
furtrackUrl: '',
adminAvatarUrl: '',
primaryCharacter: '',
// Default to UploadThing so existing sites behave exactly as before until an
// admin explicitly switches/migrates to R2.
storageProvider: 'uploadthing',
r2PublicUrl: '',
// Opt-in: the daily Telegram re-sync cron is a no-op until an admin enables it.
autoResyncEnabled: false,
themeId: 'default',
landingLayout: 'mosaic',
// Empty → the splash renders the localized default subtitle.
splashSubtitle: '',
registryOverridesLocal: false,
galleryDefaultSort: DEFAULT_GALLERY_SORT
};
// Short-TTL in-memory cache. siteSettings is global (not per-user) and changes
// rarely, so caching it per-isolate removes a D1 round-trip from the hot path of
// every request. The cache is cleared immediately on save within the writing
// isolate; other isolates converge within SETTINGS_TTL_MS. Pass { fresh: true }
// to bypass it (e.g. the admin settings editor, which must show current values).
const SETTINGS_TTL_MS = 60_000;
let settingsCache: { value: SiteSettings; expires: number } | null = null;
export function clearSettingsCache() {
settingsCache = null;
}
/**
* Best-effort settings to fall back to when a live read is too slow (see
* withTimeout). Prefers the last cached value so a brief D1 stall still renders
* the real site name/links; only drops to hard defaults on a cold isolate.
*/
export function settingsFallback(): SiteSettings {
return settingsCache ? settingsCache.value : { ...DEFAULTS };
}
export async function getSettings(
db: Database,
{ fresh = false }: { fresh?: boolean } = {}
): Promise<SiteSettings> {
if (!fresh && settingsCache && settingsCache.expires > Date.now()) {
return settingsCache.value;
}
try {
const rows = await db.select().from(siteSettings);
const map = Object.fromEntries(rows.map((r) => [r.key, r.value]));
const value: SiteSettings = {
siteName: map.siteName ?? DEFAULTS.siteName,
ownerName: map.ownerName ?? DEFAULTS.ownerName,
pronouns: map.pronouns ?? DEFAULTS.pronouns,
aboutText: map.aboutText ?? DEFAULTS.aboutText,
contactEmail: map.contactEmail ?? DEFAULTS.contactEmail,
siteUrl: map.siteUrl ?? DEFAULTS.siteUrl,
emailLanguage: map.emailLanguage ?? DEFAULTS.emailLanguage,
privacyPolicy: map.privacyPolicy ?? DEFAULTS.privacyPolicy,
termsOfService: map.termsOfService ?? DEFAULTS.termsOfService,
privacyUpdatedAt: map.privacyUpdatedAt ?? DEFAULTS.privacyUpdatedAt,
termsUpdatedAt: map.termsUpdatedAt ?? DEFAULTS.termsUpdatedAt,
// Default-ON boolean: only an explicit stored 'false' turns the /ai
// page off (unlike the default-off toggles below, which require 'true').
aiPageEnabled: map.aiPageEnabled !== 'false',
aiPageText: map.aiPageText ?? DEFAULTS.aiPageText,
aiPageUpdatedAt: map.aiPageUpdatedAt ?? DEFAULTS.aiPageUpdatedAt,
// The second default-ON boolean, same polarity as aiPageEnabled: only an
// explicit stored 'false' turns the feed off.
rssFeedEnabled: map.rssFeedEnabled !== 'false',
rssNsfwEnabled: map.rssNsfwEnabled === 'true',
rssNsfwKey: map.rssNsfwKey ?? DEFAULTS.rssNsfwKey,
sonaSpecies: map.sonaSpecies ?? DEFAULTS.sonaSpecies,
sonaBuild: map.sonaBuild ?? DEFAULTS.sonaBuild,
sonaKeyFeatures: map.sonaKeyFeatures ?? DEFAULTS.sonaKeyFeatures,
sonaColors: map.sonaColors ?? DEFAULTS.sonaColors,
sonaDos: map.sonaDos ?? DEFAULTS.sonaDos,
sonaDonts: map.sonaDonts ?? DEFAULTS.sonaDonts,
twitterUrl: map.twitterUrl ?? DEFAULTS.twitterUrl,
blueskyUrl: map.blueskyUrl ?? DEFAULTS.blueskyUrl,
telegramUrl: map.telegramUrl ?? DEFAULTS.telegramUrl,
furAffinityUrl: map.furAffinityUrl ?? DEFAULTS.furAffinityUrl,
instagramUrl: map.instagramUrl ?? DEFAULTS.instagramUrl,
furtrackUrl: map.furtrackUrl ?? DEFAULTS.furtrackUrl,
adminAvatarUrl: map.adminAvatarUrl ?? DEFAULTS.adminAvatarUrl,
primaryCharacter: map.primaryCharacter ?? DEFAULTS.primaryCharacter,
storageProvider:
map.storageProvider === 'r2' || map.storageProvider === 'uploadthing'
? map.storageProvider
: DEFAULTS.storageProvider,
r2PublicUrl: map.r2PublicUrl ?? DEFAULTS.r2PublicUrl,
// Booleans are persisted as the text 'true'/'false'; absent → default.
autoResyncEnabled: map.autoResyncEnabled === 'true',
themeId: map.themeId ?? DEFAULTS.themeId,
landingLayout: map.landingLayout ?? DEFAULTS.landingLayout,
splashSubtitle: map.splashSubtitle ?? DEFAULTS.splashSubtitle,
registryOverridesLocal: map.registryOverridesLocal === 'true',
galleryDefaultSort: isValidGallerySort(map.galleryDefaultSort ?? '')
? (map.galleryDefaultSort as GallerySort)
: DEFAULTS.galleryDefaultSort
};
settingsCache = { value, expires: Date.now() + SETTINGS_TTL_MS };
return value;
} catch {
// Table may not exist yet during deployment — fall back to defaults.
// Don't cache the failure so we retry on the next request.
return { ...DEFAULTS };
}
}
/** Read a single raw site_settings row (for internal keys not in SiteSettings,
* e.g. the registry sync cursor). Returns null if absent. */
export async function getRawSetting(db: Database, key: string): Promise<string | null> {
const row = await db.select().from(siteSettings).where(eq(siteSettings.key, key)).get();
return row?.value ?? null;
}
/**
* Read several raw rows in ONE query. Like getRawSetting this bypasses the
* settings cache and lets D1 errors propagate, which is what callers that must
* fail closed need — they just should not pay a round-trip per key to get it.
*/
export async function getRawSettings(
db: Database,
keys: string[]
): Promise<Record<string, string | null>> {
const rows = await db.select().from(siteSettings).where(inArray(siteSettings.key, keys));
const found = Object.fromEntries(rows.map((r) => [r.key, r.value]));
return Object.fromEntries(keys.map((k) => [k, found[k] ?? null]));
}
/** Upsert a single raw site_settings row. */
export async function setRawSetting(db: Database, key: string, value: string): Promise<void> {
const existing = await db.select().from(siteSettings).where(eq(siteSettings.key, key)).get();
if (existing) {
await db.update(siteSettings).set({ value }).where(eq(siteSettings.key, key));
} else {
await db.insert(siteSettings).values({ key, value });
}
}
// Resolved supporter-key status, memoized per isolate next to the settings cache
// above (SONA-118). The admin layout load runs this on every authenticated admin
// page request; uncached it costs a D1 read of the `supporterKey` row plus an
// Ed25519 verify each time.
//
// SETTINGS_TTL_MS bounds the same staleness it bounds for settings: the key row
// can be written by another isolate, whose clearSupporterKeyStatusCache this one
// never sees.
//
// SONA-119 made the resolved status viewer-dependent (validUntil and
// daysRemaining are rendered in the operator's zone), so the status itself is
// no longer cacheable in a shared entry — one operator's dates would be served
// to another. What IS cached are the zone-independent verified facts below
// (getVerifiedSupporterKey); the status is derived from them per call, which
// still spares the hot path the D1 read and the Ed25519 verify.
// Bumped by clearSupporterKeyStatusCache: a resolution that was already awaiting
// the read when a save/remove cleared the entry must not re-cache its pre-write
// status. Same guard as the nav probes (cachedProbe in nav-gating.ts).
let supporterKeyStatusGeneration = 0;
/**
* What verifying the stored key established about it: whether the issuer's
* signature checks out, and — when it does — the unix ms instant the key stops
* working. A union rather than two loose fields, so the two can't drift apart
* and a caller that checks the signature needs no null check after it. Frozen:
* callers share one instance.
*/
export type VerifiedSupporterKey =
| { readonly signatureValid: true; readonly expiresAt: number }
| { readonly signatureValid: false; readonly expiresAt: null };
/** The fail-closed answer: no key, or nothing that verified as one. Exported so
* callers that degrade to "no key" name the same thing the memo does. */
export const NO_SUPPORTER_KEY: VerifiedSupporterKey = Object.freeze({
signatureValid: false,
expiresAt: null
});
// The second memo of the `supporterKey` row, for enforcement paths (the next
// early-access feature's gate — the retired SONA-124 VR gate was the first
// consumer), which otherwise pay a D1 read plus an Ed25519 verify each time.
//
// THE INVARIANT, stated once for everything below: nothing cached here depends
// on `now` or on who is asking. Only the signature verdict and the expiry
// instant are stored; validity is that pair compared against the caller's own
// `now`, re-decided per call. That is why this memo needs no UTC-day key where
// the status memo above does, and why SONA-119's viewer-zone rendering of the
// STATUS fields cannot collide with it.
//
// This is the ONLY memo of the `supporterKey` row: the display status
// (getSupporterKeyStatus below) is derived from these facts plus the caller's
// `now` and zone on every call, exactly because those inputs are per-viewer
// (SONA-119) while these facts are not.
//
// Staleness: the isolate running the save/remove clears immediately, others
// converge on the TTL. A key that currently entitles is held for the full
// SETTINGS_TTL_MS, so REMOVING one leaves other isolates entitled for up to a
// minute — the same bound the settings and status caches already accept, and
// only the owner revoking their own entitlement can reach it.
//
// Everything that does NOT entitle right now — no row, nothing that verified,
// and a lapsed key — is held for seconds instead. That is the direction where
// staleness looks like a bug: the operator installs or renews a key, the
// settings page (which reads uncached) says valid, and a warm isolate would
// otherwise keep answering from the stale no-key facts (denying, when a gate
// consumes them). Renewal is the common case, since keys run ~45 days, and a
// renewal replaces a LAPSED entry — which is why the short TTL keys off
// "usable now" rather than "signature ok".
const NO_KEY_TTL_MS = 5_000;
let verifiedSupporterKeyCache: { value: VerifiedSupporterKey; expires: number } | null = null;
/**
* The single invalidation hook for EVERY memo of the `supporterKey` row — the
* display status and the verified-key facts alike. Both save/remove actions
* call it once; a new memo of that row belongs here rather than in its own
* clear function, so an action can't invalidate one and miss the other.
*/
export function clearSupporterKeyStatusCache() {
verifiedSupporterKeyCache = null;
supporterKeyStatusGeneration++;
}
/**
* The verified FACTS about the stored key — memoized under the invariant
* above. Today's only consumer is the display-status path; an early-access
* enforcement gate (the retired SONA-124 VR gate was the first) consumes the
* same facts.
*
* Fails closed on every uncertain outcome: a token that doesn't verify, a
* missing row and an empty row all resolve to NO_SUPPORTER_KEY. D1 errors
* propagate (and are not cached) so the caller decides — a gate treats them
* as "no key" and denies.
*/
export async function getVerifiedSupporterKey(db: Database): Promise<VerifiedSupporterKey> {
const cached = verifiedSupporterKeyCache;
if (cached && cached.expires > Date.now()) return cached.value;
const startedIn = supporterKeyStatusGeneration;
const token = await getRawSetting(db, 'supporterKey');
// `now` only picks which arm of the result carries the expiry, and both arms
// that carry one fold to the same facts — so nothing about WHEN this ran
// reaches the cache.
const value = token
? verifiedSupporterKeyFrom(await verifySupporterKey(token, new Date()))
: NO_SUPPORTER_KEY;
// A resolution that a save/remove overtook must not re-cache its pre-write
// answer — same guard, and the same counter, as the status memo.
if (supporterKeyStatusGeneration === startedIn) {
// Only the entry's LIFETIME is time-relative; the value it holds still is
// not, so the invariant above is intact.
const entitlesNow = value.signatureValid && value.expiresAt > Date.now();
verifiedSupporterKeyCache = {
value,
// An entitling entry is also capped at the key's OWN expiry: past that
// instant the same cached facts stop entitling, and a full-TTL entry
// would keep a warm isolate answering from them for up to a minute after
// a renewal was installed — the exact staleness NO_KEY_TTL_MS exists to
// avoid, reached from the other side.
expires:
Date.now() +
(entitlesNow ? Math.min(SETTINGS_TTL_MS, value.expiresAt - Date.now()) : NO_KEY_TTL_MS)
};
}
return value;
}
/** Keep the expiry of anything the issuer actually signed — the `expired` arm
* carries a trustworthy `expiresAt` too, and that is what lets one entry answer
* correctly on both sides of the moment a key lapses. */
function verifiedSupporterKeyFrom(res: SupporterKeyResult): VerifiedSupporterKey {
if (res.valid || res.reason === 'expired') {
return Object.freeze({ signatureValid: true, expiresAt: res.expiresAt.getTime() });
}
return NO_SUPPORTER_KEY;
}
/**
* The stored key's DISPLAY status, for the admin layout's expiry notice.
*
* D1 errors propagate and are not cached, so a transient failure doesn't stick.
* The admin layout catches them to degrade just its notice; the settings page
* deliberately does NOT use this — it reads and verifies loudly on every
* request so a D1 error there can never render as "no key".
*/
export async function getSupporterKeyStatus(
db: Database,
now: Date,
timeZone: string
): Promise<SupporterKeyStatus | null> {
const key = await getVerifiedSupporterKey(db);
if (!key.signatureValid) return null;
// Re-shape the cached facts as the verify result they came from; login/tier
// are not part of the facts and the status never renders them.
const expiresAt = new Date(key.expiresAt);
const res: SupporterKeyResult =
now.getTime() >= key.expiresAt
? { valid: false, reason: 'expired', login: '', tier: 0, expiresAt }
: { valid: true, login: '', tier: 0, expiresAt };
return supporterKeyStatusFromResult(res, now, timeZone);
}
export async function saveSettings(db: Database, settings: Partial<SiteSettings>) {
for (const [key, rawValue] of Object.entries(settings)) {
if (rawValue === undefined) continue;
// The value column is TEXT — coerce non-strings (e.g. boolean toggles) to
// their string form. No-op for the existing string settings.
await setRawSetting(db, key, String(rawValue));
}
// Invalidate so subsequent reads in this isolate see the new values.
clearSettingsCache();
}