@otwdesign/db-next 0.0.0-stage → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/route.ts ADDED
@@ -0,0 +1,278 @@
1
+ import {
2
+ createDbAdmin,
3
+ openDriver,
4
+ type ConnectionConfig,
5
+ type DbAdmin,
6
+ type DbAdminOptions,
7
+ type PostgresOptions,
8
+ type Viewer,
9
+ } from '@otwdesign/db-core'
10
+ import { appConnections } from './connections.ts'
11
+ import {
12
+ cookieOf,
13
+ samePassword,
14
+ SESSION_COOKIE,
15
+ sessionCookie,
16
+ signSession,
17
+ usable,
18
+ verifySession,
19
+ } from './session.ts'
20
+ import { redirect, signedInPage, signInPage } from './sign-in.ts'
21
+ import { supabaseUser } from './supabase.ts'
22
+ import { listedAs, listedUsers } from './users.ts'
23
+
24
+ type Env = Readonly<Record<string, string | undefined>>
25
+
26
+ /** What `createDbRoute` takes: all of it optional, for an app that sets its env and nothing else. */
27
+ export interface DbRouteOptions extends Partial<
28
+ Omit<DbAdminOptions, 'authorize' | 'basePath' | 'connections'>
29
+ > {
30
+ /**
31
+ * Where the route is: `/db` for `app/db/[[...path]]/route.ts`. With `basePath` set in
32
+ * next.config, that comes first, as the browser has it: `/docs/db`.
33
+ */
34
+ basePath?: string
35
+ /** The databases to open. Defaults to `appConnections()`: DB_ADMIN_<NAME>_URL, or the app's own. */
36
+ connections?: readonly ConnectionConfig[]
37
+ /** The password that signs anyone in. Defaults to DB_ADMIN_PASSWORD; 16 characters at least. */
38
+ password?: string
39
+ /**
40
+ * The app's own users who get in without the password, by email (or id), separated by commas.
41
+ * Defaults to DB_ADMIN_USERS.
42
+ */
43
+ users?: string
44
+ /**
45
+ * Who is signed in to the app, as its own sign-in knows them: their email, or an id, to look up
46
+ * among `users`. Without it, an app on Supabase Auth has its session read; any other sign-in
47
+ * (Auth.js, Clerk, the app's own) is asked here.
48
+ */
49
+ user?(request: Request): string | null | undefined | Promise<string | null | undefined>
50
+ /**
51
+ * The app's own decision, instead of the password and the users list: who is asking, or null.
52
+ * With it, this package serves no sign-in page; set `signInUrl` to the app's.
53
+ */
54
+ authorize?: DbAdminOptions['authorize']
55
+ /** The environment read for the defaults. `process.env`, unless a test says otherwise. */
56
+ env?: Env
57
+ }
58
+
59
+ /** The route's handlers, as a Next.js route file exports them. */
60
+ export interface DbRoute {
61
+ GET(request: Request): Promise<Response>
62
+ POST(request: Request): Promise<Response>
63
+ }
64
+
65
+ /**
66
+ * pg and pg-cursor from this package's own dependencies. db-core imports its drivers where the
67
+ * app runs, hidden from bundlers so an app builds without the ones it doesn't install; but what
68
+ * a bundler can't see, Next's file tracing doesn't copy into a Vercel function either, and there
69
+ * the first query would find no pg-cursor. Imported here in plain sight, they're traced.
70
+ */
71
+ const postgres: PostgresOptions = {
72
+ modules: () => Promise.all([import('pg'), import('pg-cursor')]),
73
+ }
74
+
75
+ /**
76
+ * How long a wrong password waits for its answer, and how many may be waiting. They're answered
77
+ * one after another, not all at once: a guesser gets two tries a second from a server, however
78
+ * many connections it opens. Past the few that wait, a sign-in is turned away unread, the right
79
+ * password too: answered by whether it was right, it would be a guess with no wait at all.
80
+ */
81
+ const WRONG_PASSWORD_MS = 500
82
+ const WRONG_PASSWORDS_WAITING = 8
83
+ /** How long a sign-in's form has to arrive, and how much of one is read. */
84
+ const FORM_MS = 2_000
85
+ const FORM_BYTES = 4_096
86
+
87
+ /**
88
+ * OTW DB as a Next.js route: `export const { GET, POST } = createDbRoute()` in
89
+ * `app/db/[[...path]]/route.ts`. It signs people in itself: anyone with DB_ADMIN_PASSWORD, and
90
+ * the app's signed-in users listed in DB_ADMIN_USERS with no password at all.
91
+ *
92
+ * Nothing is read or opened until the first request: Next imports a route when it builds, where
93
+ * the app's environment isn't there yet.
94
+ */
95
+ export function createDbRoute(options: DbRouteOptions = {}): DbRoute {
96
+ const {
97
+ basePath: givenBase,
98
+ connections,
99
+ password: givenPassword,
100
+ users: givenUsers,
101
+ user: appUser,
102
+ authorize: appAuthorize,
103
+ env: givenEnv,
104
+ ...rest
105
+ } = options
106
+ const basePath = (givenBase ?? '/db').replace(/\/+$/, '')
107
+ const env = () => givenEnv ?? process.env
108
+ const password = () => givenPassword ?? env().DB_ADMIN_PASSWORD
109
+ const listed = () => listedUsers(givenUsers ?? env().DB_ADMIN_USERS)
110
+
111
+ /** The app's signed-in user who is on the list: who, or that their sign-in has run out. */
112
+ async function listedUser(request: Request): Promise<{ who?: string; expired?: boolean }> {
113
+ const list = listed()
114
+ if (!list.size) return {}
115
+ if (appUser) return { who: listedAs(list, [await appUser(request)]) }
116
+ const user = await supabaseUser(request, env())
117
+ if (user === 'expired') return { expired: true }
118
+ return { who: user ? listedAs(list, [user.email, user.id]) : undefined }
119
+ }
120
+
121
+ async function hasSession(request: Request): Promise<boolean> {
122
+ const set = password()
123
+ return usable(set) && (await verifySession(cookieOf(request, SESSION_COOKIE), set, basePath))
124
+ }
125
+
126
+ /** Listed users first, so the audit log has who it was, not only that they knew the password. */
127
+ async function authorize(request: Request): Promise<Viewer | null> {
128
+ const { who } = await listedUser(request)
129
+ if (who) return { id: who }
130
+ return (await hasSession(request)) ? { id: 'password' } : null
131
+ }
132
+
133
+ let admin: DbAdmin | undefined
134
+ const tool = () =>
135
+ (admin ??= createDbAdmin({
136
+ driver: (connection) => openDriver(connection, { postgres }),
137
+ ...(appAuthorize ? {} : { signInUrl: `${basePath}/sign-in` }),
138
+ ...rest,
139
+ basePath,
140
+ connections: connections ?? appConnections(env()),
141
+ authorize: appAuthorize ?? authorize,
142
+ }))
143
+
144
+ /** The sign-ins being looked at or waiting for their answer, and the wait of the last wrong one. */
145
+ let waiting = 0
146
+ let lastRefusal: Promise<void> = Promise.resolve()
147
+
148
+ async function signIn(request: Request): Promise<Response> {
149
+ const set = password()
150
+ const state = {
151
+ basePath,
152
+ password: usable(set) ? ('ready' as const) : set ? ('short' as const) : ('unset' as const),
153
+ listed: listed().size > 0,
154
+ }
155
+ const { who, expired } = await listedUser(request)
156
+ if (request.method === 'GET') {
157
+ if (who) return signedInPage(basePath, who)
158
+ if (await hasSession(request)) return signedInPage(basePath, null)
159
+ return signInPage({ ...state, ...(expired ? { expired } : {}) })
160
+ }
161
+ if (!sameOrigin(request)) return new Response('Sign in from this site.', { status: 403 })
162
+ // Counted at the door, before the form is read: every one of a crowd arrives before the
163
+ // first of them has been found wrong.
164
+ if (waiting >= WRONG_PASSWORDS_WAITING) {
165
+ return signInPage({ ...state, busy: true }, 429, { 'retry-after': '5' })
166
+ }
167
+ waiting += 1
168
+ try {
169
+ const given = await passwordOf(request)
170
+ // No password came (a form that never arrived, or had none): nothing was guessed, so
171
+ // nothing waits, and its place is free again.
172
+ if (given === null) return signInPage(state, 400)
173
+ if (!usable(set) || !samePassword(given, set)) {
174
+ const turn = lastRefusal.then(
175
+ () => new Promise<void>((resolve) => setTimeout(resolve, WRONG_PASSWORD_MS)),
176
+ )
177
+ lastRefusal = turn
178
+ await turn
179
+ console.warn(`otw-db: a sign-in at ${basePath} was refused`)
180
+ return signInPage({ ...state, wrong: usable(set) }, 401)
181
+ }
182
+ return redirect(
183
+ basePath || '/',
184
+ sessionCookie(await signSession(set, basePath), { basePath, secure: secure(request) }),
185
+ )
186
+ } finally {
187
+ waiting -= 1
188
+ }
189
+ }
190
+
191
+ async function handle(request: Request): Promise<Response> {
192
+ const url = new URL(request.url)
193
+ // Next's trailingSlash sends /db/api/rows to /db/api/rows/, which is the same place.
194
+ if (url.pathname.length > 1 && url.pathname.endsWith('/')) {
195
+ // Counted from the end: a pattern for "slashes at the end" is tried from every slash of
196
+ // a long run of them that doesn't reach it.
197
+ let end = url.pathname.length
198
+ while (end > 1 && url.pathname.charCodeAt(end - 1) === 47) end -= 1
199
+ url.pathname = url.pathname.slice(0, end)
200
+ request = new Request(url, request)
201
+ }
202
+ if (!appAuthorize) {
203
+ if (url.pathname === `${basePath}/sign-in`) return signIn(request)
204
+ if (url.pathname === `${basePath}/sign-out` && request.method === 'POST') {
205
+ if (!sameOrigin(request)) return new Response('Sign out from this site.', { status: 403 })
206
+ return redirect(
207
+ `${basePath}/sign-in`,
208
+ sessionCookie(null, { basePath, secure: secure(request) }),
209
+ )
210
+ }
211
+ }
212
+ return tool().fetch(request)
213
+ }
214
+
215
+ return { GET: handle, POST: handle }
216
+ }
217
+
218
+ /** The password a sign-in form posted, or null where there is none to read. */
219
+ async function passwordOf(request: Request): Promise<string | null> {
220
+ // A form that never finishes arriving would keep its place among the sign-ins being looked
221
+ // at for as long as it liked; one of megabytes would be read whole and hashed. Two seconds,
222
+ // and a few kilobytes: a password and nothing else.
223
+ if (Number(request.headers.get('content-length') ?? 0) > FORM_BYTES) return null
224
+ const reader = request.body?.getReader()
225
+ if (!reader) return null
226
+ let timer: ReturnType<typeof setTimeout> | undefined
227
+ const late = new Promise<null>((resolve) => {
228
+ timer = setTimeout(() => resolve(null), FORM_MS)
229
+ })
230
+ const chunks: Uint8Array[] = []
231
+ let read = 0
232
+ try {
233
+ for (;;) {
234
+ const next = await Promise.race([reader.read(), late])
235
+ if (!next) return null
236
+ if (next.done) break
237
+ read += next.value.byteLength
238
+ if (read > FORM_BYTES) return null
239
+ chunks.push(next.value)
240
+ }
241
+ const given = new URLSearchParams(Buffer.concat(chunks).toString('utf8')).get('password')
242
+ return given ? given : null
243
+ } catch {
244
+ return null
245
+ } finally {
246
+ clearTimeout(timer)
247
+ void reader.cancel().catch(() => {})
248
+ }
249
+ }
250
+
251
+ /** Whether the site is served over https, behind a proxy or not. */
252
+ function secure(request: Request): boolean {
253
+ const forwarded = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim()
254
+ return (forwarded ?? new URL(request.url).protocol.replace(':', '')) === 'https'
255
+ }
256
+
257
+ /**
258
+ * Whether a form's post comes from this site: another site could otherwise sign a browser in, or
259
+ * out, behind its owner's back. Browsers say where a post comes from; one that says nothing at
260
+ * all isn't a browser's cross-site form.
261
+ */
262
+ function sameOrigin(request: Request): boolean {
263
+ const site = request.headers.get('sec-fetch-site')
264
+ if (site && site !== 'same-origin' && site !== 'none') return false
265
+ const origin = request.headers.get('origin')
266
+ if (!origin) return true
267
+ let host: string
268
+ try {
269
+ host = new URL(origin).host
270
+ } catch {
271
+ return false
272
+ }
273
+ return [
274
+ request.headers.get('x-forwarded-host')?.split(',')[0]?.trim(),
275
+ request.headers.get('host'),
276
+ new URL(request.url).host,
277
+ ].includes(host)
278
+ }
package/src/session.ts ADDED
@@ -0,0 +1,116 @@
1
+ import { createHash, createHmac, scrypt, timingSafeEqual } from 'node:crypto'
2
+
3
+ /*
4
+ * The password sign-in's session: a cookie the server can check with nothing kept on its side,
5
+ * since a host's instances (Vercel's functions) share no memory. It holds when it ends, signed
6
+ * with a key made from the password, so changing the password ends every session.
7
+ */
8
+
9
+ export const SESSION_COOKIE = 'otw_db_session'
10
+ /** How long a sign-in lasts. */
11
+ export const SESSION_MS = 12 * 60 * 60 * 1000
12
+ /**
13
+ * The shortest password taken. Nothing a server with no shared memory can count stops someone
14
+ * guessing, so the password must be too long to guess: `init` makes one of 32 characters.
15
+ */
16
+ export const MIN_PASSWORD = 16
17
+
18
+ /** A cookie's value by name, as the browser sent it. */
19
+ export function cookieOf(request: Request, name: string): string | undefined {
20
+ for (const part of (request.headers.get('cookie') ?? '').split(';')) {
21
+ const at = part.indexOf('=')
22
+ if (at !== -1 && part.slice(0, at).trim() === name) return part.slice(at + 1).trim()
23
+ }
24
+ return undefined
25
+ }
26
+
27
+ /** Whether `password` is one the sign-in takes at all. */
28
+ export function usable(password: string | undefined): password is string {
29
+ return typeof password === 'string' && password.length >= MIN_PASSWORD
30
+ }
31
+
32
+ /** Whether `given` is the password, compared so the time taken says nothing of either. */
33
+ export function samePassword(given: string, password: string): boolean {
34
+ const digest = (text: string) => createHash('sha256').update(text).digest()
35
+ return timingSafeEqual(digest(given), digest(password))
36
+ }
37
+
38
+ /**
39
+ * The key sessions are signed with, made from the password the slow way (scrypt: 65 ms and 32 MB
40
+ * a time). A cookie is checked with nothing but that key, so a cookie made from a guess at the
41
+ * password and sent with any request says whether the guess was right, with none of the sign-in
42
+ * page's waiting. Made slowly, each guess costs whoever makes it what a sign-in costs here; the
43
+ * server makes its own once and keeps it.
44
+ */
45
+ const keys = new Map<string, Promise<Buffer>>()
46
+
47
+ function keyOf(password: string, basePath: string): Promise<Buffer> {
48
+ const id = `${basePath}\n${password}`
49
+ let key = keys.get(id)
50
+ if (!key) {
51
+ key = new Promise<Buffer>((resolve, reject) =>
52
+ scrypt(
53
+ password,
54
+ `otw-db-session:${basePath}`,
55
+ 32,
56
+ { N: 32_768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 },
57
+ (error, derived) => (error ? reject(error) : resolve(derived)),
58
+ ),
59
+ )
60
+ // The password in use, and the one before it while a deploy rolls out: no more are kept.
61
+ if (keys.size >= 4) keys.delete(keys.keys().next().value!)
62
+ keys.set(id, key)
63
+ key.catch(() => keys.delete(id))
64
+ }
65
+ return key
66
+ }
67
+
68
+ async function signature(expires: number, password: string, basePath: string): Promise<string> {
69
+ return createHmac('sha256', await keyOf(password, basePath))
70
+ .update(String(expires))
71
+ .digest('base64url')
72
+ }
73
+
74
+ /** A session's cookie value: when it ends, and the signature that says this server set it. */
75
+ export async function signSession(
76
+ password: string,
77
+ basePath: string,
78
+ now = Date.now(),
79
+ ): Promise<string> {
80
+ const expires = now + SESSION_MS
81
+ return `${expires}.${await signature(expires, password, basePath)}`
82
+ }
83
+
84
+ /** Whether `value` is a session this password signed for this base path, not yet over. */
85
+ export async function verifySession(
86
+ value: string | undefined,
87
+ password: string,
88
+ basePath: string,
89
+ now = Date.now(),
90
+ ): Promise<boolean> {
91
+ const [expires, signed, ...rest] = (value ?? '').split('.')
92
+ if (!expires || !signed || rest.length || !/^\d{1,16}$/.test(expires)) return false
93
+ if (Number(expires) <= now) return false
94
+ const expected = Buffer.from(await signature(Number(expires), password, basePath))
95
+ const given = Buffer.from(signed)
96
+ return given.length === expected.length && timingSafeEqual(given, expected)
97
+ }
98
+
99
+ /**
100
+ * The Set-Cookie that starts a session, or ends it (`value` null). Only this tool's own paths
101
+ * get it, never scripts (HttpOnly), never another site's requests (SameSite=Strict), and over
102
+ * https only where the site is served so.
103
+ */
104
+ export function sessionCookie(
105
+ value: string | null,
106
+ { basePath, secure }: { basePath: string; secure: boolean },
107
+ ): string {
108
+ return [
109
+ `${SESSION_COOKIE}=${value ?? ''}`,
110
+ `Path=${basePath || '/'}`,
111
+ `Max-Age=${value === null ? 0 : Math.floor(SESSION_MS / 1000)}`,
112
+ 'HttpOnly',
113
+ 'SameSite=Strict',
114
+ ...(secure ? ['Secure'] : []),
115
+ ].join('; ')
116
+ }
package/src/sign-in.ts ADDED
@@ -0,0 +1,132 @@
1
+ import { MIN_PASSWORD } from './session.ts'
2
+
3
+ /*
4
+ * The sign-in page: one small page of this package's own, with no script, so the browser app
5
+ * needs no change to offer it. Its Content-Security-Policy lets it do nothing but post its form
6
+ * back to where it came from.
7
+ */
8
+
9
+ const CSP = [
10
+ "default-src 'none'",
11
+ "style-src 'unsafe-inline'",
12
+ "form-action 'self'",
13
+ "frame-ancestors 'none'",
14
+ "base-uri 'none'",
15
+ ].join('; ')
16
+
17
+ const STYLE = `
18
+ :root { color-scheme: light dark; }
19
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center;
20
+ font: 14px/1.5 system-ui, -apple-system, 'Segoe UI', sans-serif; background: Canvas; color: CanvasText; }
21
+ main { width: min(360px, calc(100vw - 48px)); }
22
+ h1 { font-size: 18px; margin: 0 0 16px; }
23
+ p { margin: 0 0 12px; }
24
+ label { display: block; font-weight: 600; margin-bottom: 6px; }
25
+ input { width: 100%; box-sizing: border-box; padding: 8px 10px; font: inherit;
26
+ border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); border-radius: 6px;
27
+ background: Field; color: FieldText; }
28
+ button, a.button { display: inline-block; margin-top: 12px; padding: 8px 14px; font: inherit; font-weight: 600;
29
+ border: 0; border-radius: 6px; background: #2f6fed; color: #fff; cursor: pointer; text-decoration: none; }
30
+ button.plain { background: transparent; color: inherit;
31
+ border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); }
32
+ .notice { padding: 8px 10px; border-radius: 6px; background: color-mix(in srgb, #d92d20 14%, transparent); }
33
+ .muted { opacity: 0.75; }
34
+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; }
35
+ form.row { display: inline; }
36
+ `
37
+
38
+ const escape = (text: string) =>
39
+ text
40
+ .replaceAll('&', '&amp;')
41
+ .replaceAll('<', '&lt;')
42
+ .replaceAll('>', '&gt;')
43
+ .replaceAll('"', '&quot;')
44
+ .replaceAll("'", '&#39;')
45
+
46
+ function page(status: number, body: string, headers: Record<string, string> = {}): Response {
47
+ return new Response(
48
+ `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>Sign in · OTW DB</title><style>${STYLE}</style></head><body><main>${body}</main></body></html>`,
49
+ {
50
+ status,
51
+ headers: {
52
+ 'content-type': 'text/html; charset=utf-8',
53
+ 'cache-control': 'no-store',
54
+ 'content-security-policy': CSP,
55
+ 'x-content-type-options': 'nosniff',
56
+ 'referrer-policy': 'same-origin',
57
+ ...headers,
58
+ },
59
+ },
60
+ )
61
+ }
62
+
63
+ /** What the sign-in page has to say, besides its form. */
64
+ export interface SignInState {
65
+ basePath: string
66
+ /** A password is set, and long enough to be taken. */
67
+ password: 'ready' | 'unset' | 'short'
68
+ /** The app has listed users (DB_ADMIN_USERS), who need no password. */
69
+ listed: boolean
70
+ /** The visitor's sign-in to the app has run out: the app renews it, not this page. */
71
+ expired?: boolean
72
+ /** The password just tried was wrong. */
73
+ wrong?: boolean
74
+ /** Too many wrong passwords are waiting for their answer: this one wasn't looked at. */
75
+ busy?: boolean
76
+ }
77
+
78
+ /** The page that asks for the password, or says why there is none to ask for. */
79
+ export function signInPage(
80
+ state: SignInState,
81
+ status = 200,
82
+ headers: Record<string, string> = {},
83
+ ): Response {
84
+ const action = escape(`${state.basePath}/sign-in`)
85
+ const parts = ['<h1>Sign in to the database</h1>']
86
+ if (state.busy) {
87
+ parts.push(
88
+ '<p class="notice" role="alert">Too many wrong passwords have just been tried here. Wait a moment, then try again.</p>',
89
+ )
90
+ } else if (state.wrong) {
91
+ parts.push('<p class="notice" role="alert">That isn’t the password.</p>')
92
+ }
93
+ if (state.password === 'ready') {
94
+ parts.push(
95
+ `<form method="post" action="${action}"><label for="password">Password</label><input id="password" name="password" type="password" autocomplete="current-password" required autofocus><button type="submit">Sign in</button></form>`,
96
+ )
97
+ } else if (!state.listed) {
98
+ parts.push(
99
+ state.password === 'unset'
100
+ ? '<p class="notice" role="alert">No password is set. Set <code>DB_ADMIN_PASSWORD</code> in this app’s environment, then open this page again.</p>'
101
+ : `<p class="notice" role="alert"><code>DB_ADMIN_PASSWORD</code> is too short to be safe: it needs ${MIN_PASSWORD} characters or more.</p>`,
102
+ )
103
+ }
104
+ if (state.listed) {
105
+ parts.push(
106
+ state.expired
107
+ ? '<p class="notice" role="alert">Your sign-in to the app has run out. Open the app, then come back to this page.</p>'
108
+ : `<p class="muted">${state.password === 'ready' ? 'Or sign' : 'Sign'} in to the app as one of the users it lets in here, then open this page again: they need no password.</p>`,
109
+ )
110
+ }
111
+ return page(status, parts.join(''), headers)
112
+ }
113
+
114
+ /** The page for someone already in: on to the database, or out again. */
115
+ export function signedInPage(basePath: string, who: string | null): Response {
116
+ const home = escape(basePath || '/')
117
+ const out = escape(`${basePath}/sign-out`)
118
+ return page(
119
+ 200,
120
+ who
121
+ ? `<h1>You’re signed in</h1><p>As ${escape(who)}, one of the app’s users let in here. To sign out, sign out of the app.</p><a class="button" href="${home}">Open the database</a>`
122
+ : `<h1>You’re signed in</h1><a class="button" href="${home}">Open the database</a> <form class="row" method="post" action="${out}"><button class="plain" type="submit">Sign out</button></form>`,
123
+ )
124
+ }
125
+
126
+ /** Sends the browser on, with a cookie set or cleared on the way. */
127
+ export function redirect(location: string, cookie?: string): Response {
128
+ return new Response(null, {
129
+ status: 303,
130
+ headers: { location, 'cache-control': 'no-store', ...(cookie ? { 'set-cookie': cookie } : {}) },
131
+ })
132
+ }
@@ -0,0 +1,133 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { cookieOf } from './session.ts'
3
+
4
+ /*
5
+ * Who is signed in to an app that uses Supabase Auth, without Supabase's packages: the session
6
+ * is in a cookie `@supabase/ssr` sets, and Supabase itself says whose it is. Reading the cookie
7
+ * alone would trust whatever a browser sends; the token in it is checked where it was issued.
8
+ */
9
+
10
+ type Env = Readonly<Record<string, string | undefined>>
11
+
12
+ /** A signed-in user, as far as this tool needs: who, and their email once they've confirmed it. */
13
+ export interface SignedIn {
14
+ id: string
15
+ /** Only a confirmed address: an unconfirmed one is whatever someone typed when signing up. */
16
+ email?: string
17
+ }
18
+
19
+ /** `expired`: there is a session, but its token has run out and the app must renew it. */
20
+ export type SupabaseUser = SignedIn | 'expired' | null
21
+
22
+ /** The project's address and the public key its browser clients use, from the app's env. */
23
+ export function supabaseProject(env: Env): { url: string; key: string } | null {
24
+ const url = (env.NEXT_PUBLIC_SUPABASE_URL ?? env.SUPABASE_URL)?.trim().replace(/\/+$/, '')
25
+ const key = (
26
+ env.NEXT_PUBLIC_SUPABASE_ANON_KEY ??
27
+ env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY ??
28
+ env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_DEFAULT_KEY ??
29
+ env.SUPABASE_ANON_KEY
30
+ )?.trim()
31
+ return url && key ? { url, key } : null
32
+ }
33
+
34
+ /** The session cookie's name, as supabase-js derives it from the project's address. */
35
+ export function sessionCookieName(url: string): string {
36
+ return `sb-${new URL(url).hostname.split('.')[0]}-auth-token`
37
+ }
38
+
39
+ /**
40
+ * The access token in the session cookie: whole, or in numbered pieces when it's long
41
+ * (`name.0`, `name.1`…), as JSON, plain or base64url after `base64-`.
42
+ */
43
+ export function accessToken(request: Request, name: string): string | null {
44
+ let value = cookieOf(request, name)
45
+ if (value === undefined) {
46
+ const pieces: string[] = []
47
+ for (let i = 0; ; i++) {
48
+ const piece = cookieOf(request, `${name}.${i}`)
49
+ if (piece === undefined) break
50
+ pieces.push(piece)
51
+ }
52
+ if (!pieces.length) return null
53
+ value = pieces.join('')
54
+ }
55
+ try {
56
+ const text = decodeURIComponent(value)
57
+ const json = text.startsWith('base64-')
58
+ ? Buffer.from(text.slice('base64-'.length), 'base64url').toString('utf8')
59
+ : text
60
+ const session = JSON.parse(json) as { access_token?: unknown } | unknown[]
61
+ // The older helpers kept a list, the token first.
62
+ const token = Array.isArray(session) ? session[0] : session?.access_token
63
+ return typeof token === 'string' && token ? token : null
64
+ } catch {
65
+ return null
66
+ }
67
+ }
68
+
69
+ /** Whether a JWT says of itself that it has run out. Not trusted for anything else. */
70
+ function ranOut(token: string, now: number): boolean {
71
+ try {
72
+ const claims = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString()) as {
73
+ exp?: unknown
74
+ }
75
+ return typeof claims.exp === 'number' && claims.exp * 1000 <= now
76
+ } catch {
77
+ return false
78
+ }
79
+ }
80
+
81
+ /** Answers kept a minute per token, so a page's burst of requests asks Supabase once. */
82
+ const KEPT_MS = 60_000
83
+ const KEPT_MOST = 500
84
+ const kept = new Map<string, { at: number; user: SignedIn | null }>()
85
+
86
+ /**
87
+ * Who the request's Supabase session belongs to, as Supabase says: null without a session, or
88
+ * with one it doesn't know. `fetch` is the app's own, for tests to stand in for.
89
+ */
90
+ export async function supabaseUser(
91
+ request: Request,
92
+ env: Env = process.env,
93
+ options: { fetch?: typeof fetch; now?: number } = {},
94
+ ): Promise<SupabaseUser> {
95
+ const project = supabaseProject(env)
96
+ if (!project) return null
97
+ const token = accessToken(request, sessionCookieName(project.url))
98
+ if (!token) return null
99
+ const now = options.now ?? Date.now()
100
+ if (ranOut(token, now)) return 'expired'
101
+ const key = createHash('sha256').update(`${project.url}\n${token}`).digest('hex')
102
+ const known = kept.get(key)
103
+ if (known && now - known.at < KEPT_MS) return known.user
104
+ let user: SignedIn | null = null
105
+ try {
106
+ const response = await (options.fetch ?? fetch)(`${project.url}/auth/v1/user`, {
107
+ headers: { apikey: project.key, authorization: `Bearer ${token}` },
108
+ signal: AbortSignal.timeout(5_000),
109
+ })
110
+ if (response.ok) {
111
+ const body = (await response.json()) as {
112
+ id?: unknown
113
+ email?: unknown
114
+ email_confirmed_at?: unknown
115
+ }
116
+ if (typeof body.id === 'string' && body.id) {
117
+ user = {
118
+ id: body.id,
119
+ ...(typeof body.email === 'string' && body.email && body.email_confirmed_at
120
+ ? { email: body.email }
121
+ : {}),
122
+ }
123
+ }
124
+ }
125
+ } catch (error) {
126
+ // Unreachable, not refused: nobody is let in on it, and the next request asks again.
127
+ console.warn('otw-db: could not ask Supabase who is signed in', error)
128
+ return null
129
+ }
130
+ if (kept.size >= KEPT_MOST) kept.delete(kept.keys().next().value!)
131
+ kept.set(key, { at: now, user })
132
+ return user
133
+ }
package/src/users.ts ADDED
@@ -0,0 +1,26 @@
1
+ /*
2
+ * The app's own users who may open the database without the password: DB_ADMIN_USERS, their
3
+ * emails (or ids, as the app's sign-in names them) separated by commas.
4
+ */
5
+
6
+ /** The list, from `DB_ADMIN_USERS`'s value: trimmed, lower-cased, empty entries dropped. */
7
+ export function listedUsers(value: string | undefined): ReadonlySet<string> {
8
+ return new Set(
9
+ (value ?? '')
10
+ .split(',')
11
+ .map((entry) => entry.trim().toLowerCase())
12
+ .filter(Boolean),
13
+ )
14
+ }
15
+
16
+ /** Which of `names` (an email, an id) is on the list, as the list has it; undefined for none. */
17
+ export function listedAs(
18
+ listed: ReadonlySet<string>,
19
+ names: readonly (string | null | undefined)[],
20
+ ): string | undefined {
21
+ for (const name of names) {
22
+ const entry = name?.trim().toLowerCase()
23
+ if (entry && listed.has(entry)) return entry
24
+ }
25
+ return undefined
26
+ }