@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/dist/route.js ADDED
@@ -0,0 +1,212 @@
1
+ import { createDbAdmin, openDriver, } from '@otwdesign/db-core';
2
+ import { appConnections } from "./connections.js";
3
+ import { cookieOf, samePassword, SESSION_COOKIE, sessionCookie, signSession, usable, verifySession, } from "./session.js";
4
+ import { redirect, signedInPage, signInPage } from "./sign-in.js";
5
+ import { supabaseUser } from "./supabase.js";
6
+ import { listedAs, listedUsers } from "./users.js";
7
+ /**
8
+ * pg and pg-cursor from this package's own dependencies. db-core imports its drivers where the
9
+ * app runs, hidden from bundlers so an app builds without the ones it doesn't install; but what
10
+ * a bundler can't see, Next's file tracing doesn't copy into a Vercel function either, and there
11
+ * the first query would find no pg-cursor. Imported here in plain sight, they're traced.
12
+ */
13
+ const postgres = {
14
+ modules: () => Promise.all([import('pg'), import('pg-cursor')]),
15
+ };
16
+ /**
17
+ * How long a wrong password waits for its answer, and how many may be waiting. They're answered
18
+ * one after another, not all at once: a guesser gets two tries a second from a server, however
19
+ * many connections it opens. Past the few that wait, a sign-in is turned away unread, the right
20
+ * password too: answered by whether it was right, it would be a guess with no wait at all.
21
+ */
22
+ const WRONG_PASSWORD_MS = 500;
23
+ const WRONG_PASSWORDS_WAITING = 8;
24
+ /** How long a sign-in's form has to arrive, and how much of one is read. */
25
+ const FORM_MS = 2_000;
26
+ const FORM_BYTES = 4_096;
27
+ /**
28
+ * OTW DB as a Next.js route: `export const { GET, POST } = createDbRoute()` in
29
+ * `app/db/[[...path]]/route.ts`. It signs people in itself: anyone with DB_ADMIN_PASSWORD, and
30
+ * the app's signed-in users listed in DB_ADMIN_USERS with no password at all.
31
+ *
32
+ * Nothing is read or opened until the first request: Next imports a route when it builds, where
33
+ * the app's environment isn't there yet.
34
+ */
35
+ export function createDbRoute(options = {}) {
36
+ const { basePath: givenBase, connections, password: givenPassword, users: givenUsers, user: appUser, authorize: appAuthorize, env: givenEnv, ...rest } = options;
37
+ const basePath = (givenBase ?? '/db').replace(/\/+$/, '');
38
+ const env = () => givenEnv ?? process.env;
39
+ const password = () => givenPassword ?? env().DB_ADMIN_PASSWORD;
40
+ const listed = () => listedUsers(givenUsers ?? env().DB_ADMIN_USERS);
41
+ /** The app's signed-in user who is on the list: who, or that their sign-in has run out. */
42
+ async function listedUser(request) {
43
+ const list = listed();
44
+ if (!list.size)
45
+ return {};
46
+ if (appUser)
47
+ return { who: listedAs(list, [await appUser(request)]) };
48
+ const user = await supabaseUser(request, env());
49
+ if (user === 'expired')
50
+ return { expired: true };
51
+ return { who: user ? listedAs(list, [user.email, user.id]) : undefined };
52
+ }
53
+ async function hasSession(request) {
54
+ const set = password();
55
+ return usable(set) && (await verifySession(cookieOf(request, SESSION_COOKIE), set, basePath));
56
+ }
57
+ /** Listed users first, so the audit log has who it was, not only that they knew the password. */
58
+ async function authorize(request) {
59
+ const { who } = await listedUser(request);
60
+ if (who)
61
+ return { id: who };
62
+ return (await hasSession(request)) ? { id: 'password' } : null;
63
+ }
64
+ let admin;
65
+ const tool = () => (admin ??= createDbAdmin({
66
+ driver: (connection) => openDriver(connection, { postgres }),
67
+ ...(appAuthorize ? {} : { signInUrl: `${basePath}/sign-in` }),
68
+ ...rest,
69
+ basePath,
70
+ connections: connections ?? appConnections(env()),
71
+ authorize: appAuthorize ?? authorize,
72
+ }));
73
+ /** The sign-ins being looked at or waiting for their answer, and the wait of the last wrong one. */
74
+ let waiting = 0;
75
+ let lastRefusal = Promise.resolve();
76
+ async function signIn(request) {
77
+ const set = password();
78
+ const state = {
79
+ basePath,
80
+ password: usable(set) ? 'ready' : set ? 'short' : 'unset',
81
+ listed: listed().size > 0,
82
+ };
83
+ const { who, expired } = await listedUser(request);
84
+ if (request.method === 'GET') {
85
+ if (who)
86
+ return signedInPage(basePath, who);
87
+ if (await hasSession(request))
88
+ return signedInPage(basePath, null);
89
+ return signInPage({ ...state, ...(expired ? { expired } : {}) });
90
+ }
91
+ if (!sameOrigin(request))
92
+ return new Response('Sign in from this site.', { status: 403 });
93
+ // Counted at the door, before the form is read: every one of a crowd arrives before the
94
+ // first of them has been found wrong.
95
+ if (waiting >= WRONG_PASSWORDS_WAITING) {
96
+ return signInPage({ ...state, busy: true }, 429, { 'retry-after': '5' });
97
+ }
98
+ waiting += 1;
99
+ try {
100
+ const given = await passwordOf(request);
101
+ // No password came (a form that never arrived, or had none): nothing was guessed, so
102
+ // nothing waits, and its place is free again.
103
+ if (given === null)
104
+ return signInPage(state, 400);
105
+ if (!usable(set) || !samePassword(given, set)) {
106
+ const turn = lastRefusal.then(() => new Promise((resolve) => setTimeout(resolve, WRONG_PASSWORD_MS)));
107
+ lastRefusal = turn;
108
+ await turn;
109
+ console.warn(`otw-db: a sign-in at ${basePath} was refused`);
110
+ return signInPage({ ...state, wrong: usable(set) }, 401);
111
+ }
112
+ return redirect(basePath || '/', sessionCookie(await signSession(set, basePath), { basePath, secure: secure(request) }));
113
+ }
114
+ finally {
115
+ waiting -= 1;
116
+ }
117
+ }
118
+ async function handle(request) {
119
+ const url = new URL(request.url);
120
+ // Next's trailingSlash sends /db/api/rows to /db/api/rows/, which is the same place.
121
+ if (url.pathname.length > 1 && url.pathname.endsWith('/')) {
122
+ // Counted from the end: a pattern for "slashes at the end" is tried from every slash of
123
+ // a long run of them that doesn't reach it.
124
+ let end = url.pathname.length;
125
+ while (end > 1 && url.pathname.charCodeAt(end - 1) === 47)
126
+ end -= 1;
127
+ url.pathname = url.pathname.slice(0, end);
128
+ request = new Request(url, request);
129
+ }
130
+ if (!appAuthorize) {
131
+ if (url.pathname === `${basePath}/sign-in`)
132
+ return signIn(request);
133
+ if (url.pathname === `${basePath}/sign-out` && request.method === 'POST') {
134
+ if (!sameOrigin(request))
135
+ return new Response('Sign out from this site.', { status: 403 });
136
+ return redirect(`${basePath}/sign-in`, sessionCookie(null, { basePath, secure: secure(request) }));
137
+ }
138
+ }
139
+ return tool().fetch(request);
140
+ }
141
+ return { GET: handle, POST: handle };
142
+ }
143
+ /** The password a sign-in form posted, or null where there is none to read. */
144
+ async function passwordOf(request) {
145
+ // A form that never finishes arriving would keep its place among the sign-ins being looked
146
+ // at for as long as it liked; one of megabytes would be read whole and hashed. Two seconds,
147
+ // and a few kilobytes: a password and nothing else.
148
+ if (Number(request.headers.get('content-length') ?? 0) > FORM_BYTES)
149
+ return null;
150
+ const reader = request.body?.getReader();
151
+ if (!reader)
152
+ return null;
153
+ let timer;
154
+ const late = new Promise((resolve) => {
155
+ timer = setTimeout(() => resolve(null), FORM_MS);
156
+ });
157
+ const chunks = [];
158
+ let read = 0;
159
+ try {
160
+ for (;;) {
161
+ const next = await Promise.race([reader.read(), late]);
162
+ if (!next)
163
+ return null;
164
+ if (next.done)
165
+ break;
166
+ read += next.value.byteLength;
167
+ if (read > FORM_BYTES)
168
+ return null;
169
+ chunks.push(next.value);
170
+ }
171
+ const given = new URLSearchParams(Buffer.concat(chunks).toString('utf8')).get('password');
172
+ return given ? given : null;
173
+ }
174
+ catch {
175
+ return null;
176
+ }
177
+ finally {
178
+ clearTimeout(timer);
179
+ void reader.cancel().catch(() => { });
180
+ }
181
+ }
182
+ /** Whether the site is served over https, behind a proxy or not. */
183
+ function secure(request) {
184
+ const forwarded = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim();
185
+ return (forwarded ?? new URL(request.url).protocol.replace(':', '')) === 'https';
186
+ }
187
+ /**
188
+ * Whether a form's post comes from this site: another site could otherwise sign a browser in, or
189
+ * out, behind its owner's back. Browsers say where a post comes from; one that says nothing at
190
+ * all isn't a browser's cross-site form.
191
+ */
192
+ function sameOrigin(request) {
193
+ const site = request.headers.get('sec-fetch-site');
194
+ if (site && site !== 'same-origin' && site !== 'none')
195
+ return false;
196
+ const origin = request.headers.get('origin');
197
+ if (!origin)
198
+ return true;
199
+ let host;
200
+ try {
201
+ host = new URL(origin).host;
202
+ }
203
+ catch {
204
+ return false;
205
+ }
206
+ return [
207
+ request.headers.get('x-forwarded-host')?.split(',')[0]?.trim(),
208
+ request.headers.get('host'),
209
+ new URL(request.url).host,
210
+ ].includes(host);
211
+ }
212
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route.js","sourceRoot":"","sources":["../src/route.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,UAAU,GAMX,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAA;AACjD,OAAO,EACL,QAAQ,EACR,YAAY,EACZ,cAAc,EACd,aAAa,EACb,WAAW,EACX,MAAM,EACN,aAAa,GACd,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAC5C,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AA2ClD;;;;;GAKG;AACH,MAAM,QAAQ,GAAoB;IAChC,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC;CAChE,CAAA;AAED;;;;;GAKG;AACH,MAAM,iBAAiB,GAAG,GAAG,CAAA;AAC7B,MAAM,uBAAuB,GAAG,CAAC,CAAA;AACjC,4EAA4E;AAC5E,MAAM,OAAO,GAAG,KAAK,CAAA;AACrB,MAAM,UAAU,GAAG,KAAK,CAAA;AAExB;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CAAC,UAA0B,EAAE;IACxD,MAAM,EACJ,QAAQ,EAAE,SAAS,EACnB,WAAW,EACX,QAAQ,EAAE,aAAa,EACvB,KAAK,EAAE,UAAU,EACjB,IAAI,EAAE,OAAO,EACb,SAAS,EAAE,YAAY,EACvB,GAAG,EAAE,QAAQ,EACb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E,CAAA;IACjF,OAAO,CAAC,SAAS,IAAI,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,KAAK,OAAO,CAAA;AAClF,CAAC;AAED;;;;GAIG;AACH,SAAS,UAAU,CAAC,OAAgB;IAClC,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAA;IAClD,IAAI,IAAI,IAAI,IAAI,KAAK,aAAa,IAAI,IAAI,KAAK,MAAM;QAAE,OAAO,KAAK,CAAA;IACnE,MAAM,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAA;IAC5C,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAA;IACxB,IAAI,IAAY,CAAA;IAChB,IAAI,CAAC;QACH,IAAI,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,CAAA;IAC7B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAA;IACd,CAAC;IACD,OAAO;QACL,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE;QAC9D,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC;QAC3B,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI;KAC1B,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAA;AAClB,CAAC"}
@@ -0,0 +1,27 @@
1
+ export declare const SESSION_COOKIE = "otw_db_session";
2
+ /** How long a sign-in lasts. */
3
+ export declare const SESSION_MS: number;
4
+ /**
5
+ * The shortest password taken. Nothing a server with no shared memory can count stops someone
6
+ * guessing, so the password must be too long to guess: `init` makes one of 32 characters.
7
+ */
8
+ export declare const MIN_PASSWORD = 16;
9
+ /** A cookie's value by name, as the browser sent it. */
10
+ export declare function cookieOf(request: Request, name: string): string | undefined;
11
+ /** Whether `password` is one the sign-in takes at all. */
12
+ export declare function usable(password: string | undefined): password is string;
13
+ /** Whether `given` is the password, compared so the time taken says nothing of either. */
14
+ export declare function samePassword(given: string, password: string): boolean;
15
+ /** A session's cookie value: when it ends, and the signature that says this server set it. */
16
+ export declare function signSession(password: string, basePath: string, now?: number): Promise<string>;
17
+ /** Whether `value` is a session this password signed for this base path, not yet over. */
18
+ export declare function verifySession(value: string | undefined, password: string, basePath: string, now?: number): Promise<boolean>;
19
+ /**
20
+ * The Set-Cookie that starts a session, or ends it (`value` null). Only this tool's own paths
21
+ * get it, never scripts (HttpOnly), never another site's requests (SameSite=Strict), and over
22
+ * https only where the site is served so.
23
+ */
24
+ export declare function sessionCookie(value: string | null, { basePath, secure }: {
25
+ basePath: string;
26
+ secure: boolean;
27
+ }): string;
@@ -0,0 +1,90 @@
1
+ import { createHash, createHmac, scrypt, timingSafeEqual } from 'node:crypto';
2
+ /*
3
+ * The password sign-in's session: a cookie the server can check with nothing kept on its side,
4
+ * since a host's instances (Vercel's functions) share no memory. It holds when it ends, signed
5
+ * with a key made from the password, so changing the password ends every session.
6
+ */
7
+ export const SESSION_COOKIE = 'otw_db_session';
8
+ /** How long a sign-in lasts. */
9
+ export const SESSION_MS = 12 * 60 * 60 * 1000;
10
+ /**
11
+ * The shortest password taken. Nothing a server with no shared memory can count stops someone
12
+ * guessing, so the password must be too long to guess: `init` makes one of 32 characters.
13
+ */
14
+ export const MIN_PASSWORD = 16;
15
+ /** A cookie's value by name, as the browser sent it. */
16
+ export function cookieOf(request, name) {
17
+ for (const part of (request.headers.get('cookie') ?? '').split(';')) {
18
+ const at = part.indexOf('=');
19
+ if (at !== -1 && part.slice(0, at).trim() === name)
20
+ return part.slice(at + 1).trim();
21
+ }
22
+ return undefined;
23
+ }
24
+ /** Whether `password` is one the sign-in takes at all. */
25
+ export function usable(password) {
26
+ return typeof password === 'string' && password.length >= MIN_PASSWORD;
27
+ }
28
+ /** Whether `given` is the password, compared so the time taken says nothing of either. */
29
+ export function samePassword(given, password) {
30
+ const digest = (text) => createHash('sha256').update(text).digest();
31
+ return timingSafeEqual(digest(given), digest(password));
32
+ }
33
+ /**
34
+ * The key sessions are signed with, made from the password the slow way (scrypt: 65 ms and 32 MB
35
+ * a time). A cookie is checked with nothing but that key, so a cookie made from a guess at the
36
+ * password and sent with any request says whether the guess was right, with none of the sign-in
37
+ * page's waiting. Made slowly, each guess costs whoever makes it what a sign-in costs here; the
38
+ * server makes its own once and keeps it.
39
+ */
40
+ const keys = new Map();
41
+ function keyOf(password, basePath) {
42
+ const id = `${basePath}\n${password}`;
43
+ let key = keys.get(id);
44
+ if (!key) {
45
+ key = new Promise((resolve, reject) => scrypt(password, `otw-db-session:${basePath}`, 32, { N: 32_768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }, (error, derived) => (error ? reject(error) : resolve(derived))));
46
+ // The password in use, and the one before it while a deploy rolls out: no more are kept.
47
+ if (keys.size >= 4)
48
+ keys.delete(keys.keys().next().value);
49
+ keys.set(id, key);
50
+ key.catch(() => keys.delete(id));
51
+ }
52
+ return key;
53
+ }
54
+ async function signature(expires, password, basePath) {
55
+ return createHmac('sha256', await keyOf(password, basePath))
56
+ .update(String(expires))
57
+ .digest('base64url');
58
+ }
59
+ /** A session's cookie value: when it ends, and the signature that says this server set it. */
60
+ export async function signSession(password, basePath, now = Date.now()) {
61
+ const expires = now + SESSION_MS;
62
+ return `${expires}.${await signature(expires, password, basePath)}`;
63
+ }
64
+ /** Whether `value` is a session this password signed for this base path, not yet over. */
65
+ export async function verifySession(value, password, basePath, now = Date.now()) {
66
+ const [expires, signed, ...rest] = (value ?? '').split('.');
67
+ if (!expires || !signed || rest.length || !/^\d{1,16}$/.test(expires))
68
+ return false;
69
+ if (Number(expires) <= now)
70
+ return false;
71
+ const expected = Buffer.from(await signature(Number(expires), password, basePath));
72
+ const given = Buffer.from(signed);
73
+ return given.length === expected.length && timingSafeEqual(given, expected);
74
+ }
75
+ /**
76
+ * The Set-Cookie that starts a session, or ends it (`value` null). Only this tool's own paths
77
+ * get it, never scripts (HttpOnly), never another site's requests (SameSite=Strict), and over
78
+ * https only where the site is served so.
79
+ */
80
+ export function sessionCookie(value, { basePath, secure }) {
81
+ return [
82
+ `${SESSION_COOKIE}=${value ?? ''}`,
83
+ `Path=${basePath || '/'}`,
84
+ `Max-Age=${value === null ? 0 : Math.floor(SESSION_MS / 1000)}`,
85
+ 'HttpOnly',
86
+ 'SameSite=Strict',
87
+ ...(secure ? ['Secure'] : []),
88
+ ].join('; ');
89
+ }
90
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAE7E;;;;GAIG;AAEH,MAAM,CAAC,MAAM,cAAc,GAAG,gBAAgB,CAAA;AAC9C,gCAAgC;AAChC,MAAM,CAAC,MAAM,UAAU,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAA;AAC7C;;;GAGG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,CAAA;AAE9B,wDAAwD;AACxD,MAAM,UAAU,QAAQ,CAAC,OAAgB,EAAE,IAAY;IACrD,KAAK,MAAM,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACpE,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;QAC5B,IAAI,EAAE,KAAK,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,KAAK,IAAI;YAAE,OAAO,IAAI,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AM,IAAI,IAAI,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC;QAAE,OAAO,KAAK,CAAA;IACnF,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,GAAG;QAAE,OAAO,KAAK,CAAA;IACxC,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,SAAS,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAA;IAClF,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IACjC,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM,IAAI,eAAe,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;AAC7E,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAC3B,KAAoB,EACpB,EAAE,QAAQ,EAAE,MAAM,EAAyC;IAE3D,OAAO;QACL,GAAG,cAAc,IAAI,KAAK,IAAI,EAAE,EAAE;QAClC,QAAQ,QAAQ,IAAI,GAAG,EAAE;QACzB,WAAW,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,GAAG,IAAI,CAAC,EAAE;QAC/D,UAAU;QACV,iBAAiB;QACjB,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;KAC9B,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AACd,CAAC"}
@@ -0,0 +1,20 @@
1
+ /** What the sign-in page has to say, besides its form. */
2
+ export interface SignInState {
3
+ basePath: string;
4
+ /** A password is set, and long enough to be taken. */
5
+ password: 'ready' | 'unset' | 'short';
6
+ /** The app has listed users (DB_ADMIN_USERS), who need no password. */
7
+ listed: boolean;
8
+ /** The visitor's sign-in to the app has run out: the app renews it, not this page. */
9
+ expired?: boolean;
10
+ /** The password just tried was wrong. */
11
+ wrong?: boolean;
12
+ /** Too many wrong passwords are waiting for their answer: this one wasn't looked at. */
13
+ busy?: boolean;
14
+ }
15
+ /** The page that asks for the password, or says why there is none to ask for. */
16
+ export declare function signInPage(state: SignInState, status?: number, headers?: Record<string, string>): Response;
17
+ /** The page for someone already in: on to the database, or out again. */
18
+ export declare function signedInPage(basePath: string, who: string | null): Response;
19
+ /** Sends the browser on, with a cookie set or cleared on the way. */
20
+ export declare function redirect(location: string, cookie?: string): Response;
@@ -0,0 +1,93 @@
1
+ import { MIN_PASSWORD } from "./session.js";
2
+ /*
3
+ * The sign-in page: one small page of this package's own, with no script, so the browser app
4
+ * needs no change to offer it. Its Content-Security-Policy lets it do nothing but post its form
5
+ * back to where it came from.
6
+ */
7
+ const CSP = [
8
+ "default-src 'none'",
9
+ "style-src 'unsafe-inline'",
10
+ "form-action 'self'",
11
+ "frame-ancestors 'none'",
12
+ "base-uri 'none'",
13
+ ].join('; ');
14
+ const STYLE = `
15
+ :root { color-scheme: light dark; }
16
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center;
17
+ font: 14px/1.5 system-ui, -apple-system, 'Segoe UI', sans-serif; background: Canvas; color: CanvasText; }
18
+ main { width: min(360px, calc(100vw - 48px)); }
19
+ h1 { font-size: 18px; margin: 0 0 16px; }
20
+ p { margin: 0 0 12px; }
21
+ label { display: block; font-weight: 600; margin-bottom: 6px; }
22
+ input { width: 100%; box-sizing: border-box; padding: 8px 10px; font: inherit;
23
+ border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); border-radius: 6px;
24
+ background: Field; color: FieldText; }
25
+ button, a.button { display: inline-block; margin-top: 12px; padding: 8px 14px; font: inherit; font-weight: 600;
26
+ border: 0; border-radius: 6px; background: #2f6fed; color: #fff; cursor: pointer; text-decoration: none; }
27
+ button.plain { background: transparent; color: inherit;
28
+ border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); }
29
+ .notice { padding: 8px 10px; border-radius: 6px; background: color-mix(in srgb, #d92d20 14%, transparent); }
30
+ .muted { opacity: 0.75; }
31
+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; }
32
+ form.row { display: inline; }
33
+ `;
34
+ const escape = (text) => text
35
+ .replaceAll('&', '&amp;')
36
+ .replaceAll('<', '&lt;')
37
+ .replaceAll('>', '&gt;')
38
+ .replaceAll('"', '&quot;')
39
+ .replaceAll("'", '&#39;');
40
+ function page(status, body, headers = {}) {
41
+ return new Response(`<!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>`, {
42
+ status,
43
+ headers: {
44
+ 'content-type': 'text/html; charset=utf-8',
45
+ 'cache-control': 'no-store',
46
+ 'content-security-policy': CSP,
47
+ 'x-content-type-options': 'nosniff',
48
+ 'referrer-policy': 'same-origin',
49
+ ...headers,
50
+ },
51
+ });
52
+ }
53
+ /** The page that asks for the password, or says why there is none to ask for. */
54
+ export function signInPage(state, status = 200, headers = {}) {
55
+ const action = escape(`${state.basePath}/sign-in`);
56
+ const parts = ['<h1>Sign in to the database</h1>'];
57
+ if (state.busy) {
58
+ parts.push('<p class="notice" role="alert">Too many wrong passwords have just been tried here. Wait a moment, then try again.</p>');
59
+ }
60
+ else if (state.wrong) {
61
+ parts.push('<p class="notice" role="alert">That isn’t the password.</p>');
62
+ }
63
+ if (state.password === 'ready') {
64
+ parts.push(`<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>`);
65
+ }
66
+ else if (!state.listed) {
67
+ parts.push(state.password === 'unset'
68
+ ? '<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>'
69
+ : `<p class="notice" role="alert"><code>DB_ADMIN_PASSWORD</code> is too short to be safe: it needs ${MIN_PASSWORD} characters or more.</p>`);
70
+ }
71
+ if (state.listed) {
72
+ parts.push(state.expired
73
+ ? '<p class="notice" role="alert">Your sign-in to the app has run out. Open the app, then come back to this page.</p>'
74
+ : `<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>`);
75
+ }
76
+ return page(status, parts.join(''), headers);
77
+ }
78
+ /** The page for someone already in: on to the database, or out again. */
79
+ export function signedInPage(basePath, who) {
80
+ const home = escape(basePath || '/');
81
+ const out = escape(`${basePath}/sign-out`);
82
+ return page(200, who
83
+ ? `<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>`
84
+ : `<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>`);
85
+ }
86
+ /** Sends the browser on, with a cookie set or cleared on the way. */
87
+ export function redirect(location, cookie) {
88
+ return new Response(null, {
89
+ status: 303,
90
+ headers: { location, 'cache-control': 'no-store', ...(cookie ? { 'set-cookie': cookie } : {}) },
91
+ });
92
+ }
93
+ //# sourceMappingURL=sign-in.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sign-in.js","sourceRoot":"","sources":["../src/sign-in.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAE3C;;;;GAIG;AAEH,MAAM,GAAG,GAAG;IACV,oBAAoB;IACpB,2BAA2B;IAC3B,oBAAoB;IACpB,wBAAwB;IACxB,iBAAiB;CAClB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AAEZ,MAAM,KAAK,GAAG;;;;;;;;;;;;;;;;;;;CAmBb,CAAA;AAED,MAAM,MAAM,GAAG,CAAC,IAAY,EAAE,EAAE,CAC9B,IAAI;KACD,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC;KACxB,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC;KACvB,UAAU,CAAC,G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ACD,IAAI,KAAK,CAAC,MAAM,EAAE,CAAC;QACjB,KAAK,CAAC,IAAI,CACR,KAAK,CAAC,OAAO;YACX,CAAC,CAAC,oHAAoH;YACtH,CAAC,CAAC,oBAAoB,KAAK,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,2GAA2G,CACnL,CAAA;IACH,CAAC;IACD,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC,CAAA;AAC9C,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,YAAY,CAAC,QAAgB,EAAE,GAAkB;IAC/D,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,IAAI,GAAG,CAAC,CAAA;IACpC,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,QAAQ,WAAW,CAAC,CAAA;IAC1C,OAAO,IAAI,CACT,GAAG,EACH,GAAG;QACD,CAAC,CAAC,kCAAkC,MAAM,CAAC,GAAG,CAAC,sGAAsG,IAAI,yBAAyB;QAClL,CAAC,CAAC,oDAAoD,IAAI,mEAAmE,GAAG,gEAAgE,CACnM,CAAA;AACH,CAAC;AAED,qEAAqE;AACrE,MAAM,UAAU,QAAQ,CAAC,QAAgB,EAAE,MAAe;IACxD,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE;QACxB,MAAM,EAAE,GAAG;QACX,OAAO,EAAE,EAAE,QAAQ,EAAE,eAAe,EAAE,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE;KAChG,CAAC,CAAA;AACJ,CAAC"}
@@ -0,0 +1,30 @@
1
+ type Env = Readonly<Record<string, string | undefined>>;
2
+ /** A signed-in user, as far as this tool needs: who, and their email once they've confirmed it. */
3
+ export interface SignedIn {
4
+ id: string;
5
+ /** Only a confirmed address: an unconfirmed one is whatever someone typed when signing up. */
6
+ email?: string;
7
+ }
8
+ /** `expired`: there is a session, but its token has run out and the app must renew it. */
9
+ export type SupabaseUser = SignedIn | 'expired' | null;
10
+ /** The project's address and the public key its browser clients use, from the app's env. */
11
+ export declare function supabaseProject(env: Env): {
12
+ url: string;
13
+ key: string;
14
+ } | null;
15
+ /** The session cookie's name, as supabase-js derives it from the project's address. */
16
+ export declare function sessionCookieName(url: string): string;
17
+ /**
18
+ * The access token in the session cookie: whole, or in numbered pieces when it's long
19
+ * (`name.0`, `name.1`…), as JSON, plain or base64url after `base64-`.
20
+ */
21
+ export declare function accessToken(request: Request, name: string): string | null;
22
+ /**
23
+ * Who the request's Supabase session belongs to, as Supabase says: null without a session, or
24
+ * with one it doesn't know. `fetch` is the app's own, for tests to stand in for.
25
+ */
26
+ export declare function supabaseUser(request: Request, env?: Env, options?: {
27
+ fetch?: typeof fetch;
28
+ now?: number;
29
+ }): Promise<SupabaseUser>;
30
+ export {};
@@ -0,0 +1,108 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { cookieOf } from "./session.js";
3
+ /** The project's address and the public key its browser clients use, from the app's env. */
4
+ export function supabaseProject(env) {
5
+ const url = (env.NEXT_PUBLIC_SUPABASE_URL ?? env.SUPABASE_URL)?.trim().replace(/\/+$/, '');
6
+ const key = (env.NEXT_PUBLIC_SUPABASE_ANON_KEY ??
7
+ env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY ??
8
+ env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_DEFAULT_KEY ??
9
+ env.SUPABASE_ANON_KEY)?.trim();
10
+ return url && key ? { url, key } : null;
11
+ }
12
+ /** The session cookie's name, as supabase-js derives it from the project's address. */
13
+ export function sessionCookieName(url) {
14
+ return `sb-${new URL(url).hostname.split('.')[0]}-auth-token`;
15
+ }
16
+ /**
17
+ * The access token in the session cookie: whole, or in numbered pieces when it's long
18
+ * (`name.0`, `name.1`…), as JSON, plain or base64url after `base64-`.
19
+ */
20
+ export function accessToken(request, name) {
21
+ let value = cookieOf(request, name);
22
+ if (value === undefined) {
23
+ const pieces = [];
24
+ for (let i = 0;; i++) {
25
+ const piece = cookieOf(request, `${name}.${i}`);
26
+ if (piece === undefined)
27
+ break;
28
+ pieces.push(piece);
29
+ }
30
+ if (!pieces.length)
31
+ return null;
32
+ value = pieces.join('');
33
+ }
34
+ try {
35
+ const text = decodeURIComponent(value);
36
+ const json = text.startsWith('base64-')
37
+ ? Buffer.from(text.slice('base64-'.length), 'base64url').toString('utf8')
38
+ : text;
39
+ const session = JSON.parse(json);
40
+ // The older helpers kept a list, the token first.
41
+ const token = Array.isArray(session) ? session[0] : session?.access_token;
42
+ return typeof token === 'string' && token ? token : null;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ /** Whether a JWT says of itself that it has run out. Not trusted for anything else. */
49
+ function ranOut(token, now) {
50
+ try {
51
+ const claims = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString());
52
+ return typeof claims.exp === 'number' && claims.exp * 1000 <= now;
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ }
58
+ /** Answers kept a minute per token, so a page's burst of requests asks Supabase once. */
59
+ const KEPT_MS = 60_000;
60
+ const KEPT_MOST = 500;
61
+ const kept = new Map();
62
+ /**
63
+ * Who the request's Supabase session belongs to, as Supabase says: null without a session, or
64
+ * with one it doesn't know. `fetch` is the app's own, for tests to stand in for.
65
+ */
66
+ export async function supabaseUser(request, env = process.env, options = {}) {
67
+ const project = supabaseProject(env);
68
+ if (!project)
69
+ return null;
70
+ const token = accessToken(request, sessionCookieName(project.url));
71
+ if (!token)
72
+ return null;
73
+ const now = options.now ?? Date.now();
74
+ if (ranOut(token, now))
75
+ return 'expired';
76
+ const key = createHash('sha256').update(`${project.url}\n${token}`).digest('hex');
77
+ const known = kept.get(key);
78
+ if (known && now - known.at < KEPT_MS)
79
+ return known.user;
80
+ let user = null;
81
+ try {
82
+ const response = await (options.fetch ?? fetch)(`${project.url}/auth/v1/user`, {
83
+ headers: { apikey: project.key, authorization: `Bearer ${token}` },
84
+ signal: AbortSignal.timeout(5_000),
85
+ });
86
+ if (response.ok) {
87
+ const body = (await response.json());
88
+ if (typeof body.id === 'string' && body.id) {
89
+ user = {
90
+ id: body.id,
91
+ ...(typeof body.email === 'string' && body.email && body.email_confirmed_at
92
+ ? { email: body.email }
93
+ : {}),
94
+ };
95
+ }
96
+ }
97
+ }
98
+ catch (error) {
99
+ // Unreachable, not refused: nobody is let in on it, and the next request asks again.
100
+ console.warn('otw-db: could not ask Supabase who is signed in', error);
101
+ return null;
102
+ }
103
+ if (kept.size >= KEPT_MOST)
104
+ kept.delete(kept.keys().next().value);
105
+ kept.set(key, { at: now, user });
106
+ return user;
107
+ }
108
+ //# sourceMappingURL=supabase.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"supabase.js","sourceRoot":"","sources":["../src/supabase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAoBvC,4FAA4F;AAC5F,MAAM,UAAU,eAAe,CAAC,GAAQ;IACtC,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,wBAAwB,IAAI,GAAG,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAA;IAC1F,MAAM,GAAG,GAAG,CACV,GAAG,CAAC,6BAA6B;QACjC,GAAG,CAAC,oCAAoC;QACxC,GAAG,CAAC,4CAA4C;QAChD,GAAG,CAAC,iBAAiB,CACtB,EAAE,IAAI,EAAE,CAAA;IACT,OAAO,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAA;AACzC,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,iBAAiB,CAAC,GAAW;IAC3C,OAAO,MAAM,IAAI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AC;QACf,qFAAqF;QACrF,OAAO,CAAC,IAAI,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAA;QACtE,OAAO,IAAI,CAAA;IACb,CAAC;IACD,IAAI,IAAI,CAAC,IAAI,IAAI,SAAS;QAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAM,CAAC,CAAA;IAClE,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAA;IAChC,OAAO,IAAI,CAAA;AACb,CAAC"}
@@ -0,0 +1,4 @@
1
+ /** The list, from `DB_ADMIN_USERS`'s value: trimmed, lower-cased, empty entries dropped. */
2
+ export declare function listedUsers(value: string | undefined): ReadonlySet<string>;
3
+ /** Which of `names` (an email, an id) is on the list, as the list has it; undefined for none. */
4
+ export declare function listedAs(listed: ReadonlySet<string>, names: readonly (string | null | undefined)[]): string | undefined;