@astralarium/repo-auth 0.0.0-stage → 0.2.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.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +59 -2
  3. package/dist/client.d.ts +2173 -0
  4. package/dist/client.js +203 -0
  5. package/dist/dev-sign-in/client.d.ts +21 -0
  6. package/dist/dev-sign-in/client.js +17 -0
  7. package/dist/dev-sign-in/endpoint.d.ts +2 -0
  8. package/dist/dev-sign-in/endpoint.js +2 -0
  9. package/dist/dev-sign-in/index.d.ts +4 -0
  10. package/dist/dev-sign-in/index.js +4 -0
  11. package/dist/dev-sign-in/provider-user.d.ts +30 -0
  12. package/dist/dev-sign-in/provider-user.js +55 -0
  13. package/dist/dev-sign-in/sign-in.d.ts +62 -0
  14. package/dist/dev-sign-in/sign-in.js +116 -0
  15. package/dist/index.server.d.ts +645 -0
  16. package/dist/index.server.js +307 -0
  17. package/dist/providers/google.d.ts +8 -0
  18. package/dist/providers/google.js +11 -0
  19. package/dist/providers/index.d.ts +3 -0
  20. package/dist/providers/index.js +3 -0
  21. package/dist/providers/provider.d.ts +135 -0
  22. package/dist/providers/provider.js +86 -0
  23. package/dist/request.d.ts +42 -0
  24. package/dist/request.js +75 -0
  25. package/dist/schema.d.ts +6 -0
  26. package/dist/schema.js +23 -0
  27. package/dist/start/index.d.ts +6 -0
  28. package/dist/start/index.js +6 -0
  29. package/dist/start/index.server.d.ts +28 -0
  30. package/dist/start/index.server.js +29 -0
  31. package/dist/start/middleware.d.ts +33 -0
  32. package/dist/start/middleware.js +70 -0
  33. package/dist/start/return-path.d.ts +16 -0
  34. package/dist/start/return-path.js +32 -0
  35. package/dist/start/viewer.d.ts +8 -0
  36. package/dist/start/viewer.js +15 -0
  37. package/dist/testkit/index.d.ts +131 -0
  38. package/dist/testkit/index.js +238 -0
  39. package/dist/testkit/json-post.d.ts +8 -0
  40. package/dist/testkit/json-post.js +12 -0
  41. package/dist/testkit/oidc.d.ts +35 -0
  42. package/dist/testkit/oidc.js +154 -0
  43. package/dist/testkit/suites.d.ts +126 -0
  44. package/dist/testkit/suites.js +255 -0
  45. package/dist/types.d.ts +7 -0
  46. package/dist/types.js +1 -0
  47. package/package.json +86 -3
  48. package/sql/jobs/schema.sql +19 -0
  49. package/sql/schema.sql +97 -0
  50. package/sql/scrub.sql +6 -0
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Server half of shell-auth: an app's better-auth identity, schema and
3
+ * providers (`defineShellAuthApp`), one auth instance per isolate over the app's
4
+ * `auth.*` tables (`shellAuth`), its `get-session` answering the app's
5
+ * projected session, and `withShellAuth`, scoping its database to a request.
6
+ */
7
+ import { AsyncLocalStorage } from "node:async_hooks";
8
+ import { ExpectedError } from "@astralarium/repo-telemetry";
9
+ import { betterAuth } from "better-auth";
10
+ import { createAuthEndpoint, getSession } from "better-auth/api";
11
+ import { genericOAuth } from "better-auth/plugins/generic-oauth";
12
+ import { PostgresAdapter, PostgresDriver, PostgresIntrospector, PostgresQueryCompiler } from "kysely";
13
+ import { Pool } from "pg";
14
+ import { z } from "zod";
15
+ /** `ShellAuthConfig` constraints the types leave open. */
16
+ const ShellAuthAppShape = z.object({
17
+ appName: z.string().min(1),
18
+ errorURL: z.string().min(1),
19
+ session: z.object({
20
+ expiresIn: z.number().int().positive().optional(),
21
+ updateAge: z.number().int().nonnegative().optional()
22
+ }).optional()
23
+ });
24
+ /** `value`, unchanged; throws `ExpectedError` naming each value
25
+ * `ShellAuthAppShape` rejects in `what`. */
26
+ function validated(what, value) {
27
+ const result = ShellAuthAppShape.safeParse(value);
28
+ if (!result.success) {
29
+ throw new ExpectedError(`Invalid shell-auth ${what}:\n${z.prettifyError(result.error)}`);
30
+ }
31
+ return value;
32
+ }
33
+ /** The app's auth declaration, validated; infers `Fields` and
34
+ * `Projected` from the literal. Throws `ExpectedError` naming each
35
+ * invalid value. */
36
+ export function defineShellAuthApp(app) {
37
+ return validated("app", app);
38
+ }
39
+ /** `auth.*` table mapping and the app's user columns. */
40
+ function schemaOptions({
41
+ appName,
42
+ additionalFields,
43
+ session,
44
+ account,
45
+ databaseHooks
46
+ }) {
47
+ return {
48
+ appName,
49
+ advanced: {
50
+ disableOriginCheck: false,
51
+ database: {
52
+ generateId: false,
53
+ // The runtime check starts at init, outside any request's database
54
+ // scope; tests check the deployed schema.
55
+ validateSchema: false
56
+ }
57
+ },
58
+ // Callers rate-limit ahead of the handler.
59
+ rateLimit: {
60
+ enabled: false
61
+ },
62
+ databaseHooks,
63
+ session: {
64
+ ...session,
65
+ // `get-session` answers from the signed cookie; reads that must see a
66
+ // fresh row pass `disableCookieCache`.
67
+ cookieCache: {
68
+ enabled: true,
69
+ maxAge: 60
70
+ },
71
+ modelName: "auth.session",
72
+ fields: {
73
+ userId: "user_id",
74
+ expiresAt: "expires_at",
75
+ ipAddress: "ip_address",
76
+ userAgent: "user_agent",
77
+ createdAt: "created_at",
78
+ updatedAt: "updated_at"
79
+ }
80
+ },
81
+ user: {
82
+ modelName: "auth.users",
83
+ fields: {
84
+ name: "name",
85
+ email: "email",
86
+ emailVerified: "email_verified",
87
+ image: "image",
88
+ createdAt: "created_at",
89
+ updatedAt: "updated_at"
90
+ },
91
+ additionalFields
92
+ },
93
+ account: {
94
+ ...account,
95
+ modelName: "auth.account",
96
+ fields: {
97
+ userId: "user_id",
98
+ providerId: "provider_id",
99
+ accountId: "provider_account_id",
100
+ accessToken: "access_token",
101
+ refreshToken: "refresh_token",
102
+ accessTokenExpiresAt: "access_token_expires_at",
103
+ refreshTokenExpiresAt: "refresh_token_expires_at",
104
+ scope: "scope",
105
+ idToken: "id_token",
106
+ password: "password",
107
+ createdAt: "created_at",
108
+ updatedAt: "updated_at"
109
+ }
110
+ },
111
+ verification: {
112
+ modelName: "auth.verification",
113
+ fields: {
114
+ identifier: "identifier",
115
+ value: "value",
116
+ expiresAt: "expires_at",
117
+ createdAt: "created_at",
118
+ updatedAt: "updated_at"
119
+ }
120
+ }
121
+ };
122
+ }
123
+ /** Plugin replacing `get-session` with the app's projection; `$Infer`
124
+ * types the client store. */
125
+ function sessionProjection(project) {
126
+ /** Native session read, including cookie refresh and database errors. */
127
+ const readSession = getSession();
128
+ /** Projected session, preserving the native read's cookies and errors. */
129
+ const projectedSession = createAuthEndpoint("/get-session", {
130
+ ...readSession.options,
131
+ metadata: {
132
+ ...readSession.options.metadata,
133
+ CUSTOM_SESSION: true
134
+ }
135
+ }, async ctx => {
136
+ const {
137
+ response,
138
+ headers
139
+ } = await readSession({
140
+ ...ctx,
141
+ asResponse: false,
142
+ returnHeaders: true,
143
+ returnStatus: false
144
+ });
145
+ for (const cookie of headers.getSetCookie()) {
146
+ ctx.responseHeaders.append("set-cookie", cookie);
147
+ }
148
+ headers.forEach((value, name) => {
149
+ if (name !== "set-cookie") ctx.setHeader(name, value);
150
+ });
151
+ if (!response) return ctx.json(null);
152
+ return ctx.json(project(response));
153
+ });
154
+ return {
155
+ id: "session-projection",
156
+ endpoints: {
157
+ getSession: projectedSession
158
+ },
159
+ $Infer: {
160
+ Session: {}
161
+ }
162
+ };
163
+ }
164
+ /** better-auth options of the providers with credentials: built-in social
165
+ * providers and one `genericOAuth` plugin. */
166
+ function providerOptions(providers, credentials = {}) {
167
+ const social = {};
168
+ const generic = [];
169
+ for (const provider of providers?.list ?? []) {
170
+ const pair = credentials[provider.id];
171
+ if (!pair) continue;
172
+ const config = provider.configure(pair);
173
+ if ("social" in config) social[provider.id] = config.social;else generic.push(config.oauth);
174
+ }
175
+ const plugins = generic.length ? [genericOAuth({
176
+ config: generic
177
+ })] : [];
178
+ return {
179
+ socialProviders: social,
180
+ plugins
181
+ };
182
+ }
183
+ /** The running `withShellAuth` scope's driver over its pool. Workers pins
184
+ * I/O objects to the request that created them, so a pool serves one
185
+ * request. */
186
+ const scope = new AsyncLocalStorage();
187
+ /** The running scope's driver; throws `ExpectedError` outside a scope. */
188
+ function scopeDriver() {
189
+ const driver = scope.getStore();
190
+ if (!driver) {
191
+ throw new ExpectedError("shell-auth queried its database outside withShellAuth: run the auth call inside withShellAuth(db, fn)");
192
+ }
193
+ return driver;
194
+ }
195
+ /** Kysely driver forwarding each call to the running scope's driver. */
196
+ class ScopedDriver {
197
+ /** Scopes open their own pools. */
198
+ init() {
199
+ return Promise.resolve();
200
+ }
201
+ acquireConnection(options) {
202
+ return scopeDriver().acquireConnection(options);
203
+ }
204
+ beginTransaction(connection, settings) {
205
+ return scopeDriver().beginTransaction(connection, settings);
206
+ }
207
+ commitTransaction(connection) {
208
+ return scopeDriver().commitTransaction(connection);
209
+ }
210
+ rollbackTransaction(connection) {
211
+ return scopeDriver().rollbackTransaction(connection);
212
+ }
213
+ savepoint(connection, name, compile) {
214
+ return scopeDriver().savepoint(connection, name, compile);
215
+ }
216
+ rollbackToSavepoint(connection, name, compile) {
217
+ return scopeDriver().rollbackToSavepoint(connection, name, compile);
218
+ }
219
+ releaseSavepoint(connection, name, compile) {
220
+ return scopeDriver().releaseSavepoint(connection, name, compile);
221
+ }
222
+ releaseConnection(connection, options) {
223
+ // `connection` came from the scope driver's `acquireConnection`; typed as
224
+ // `Driver` to pass it on.
225
+ const driver = scopeDriver();
226
+ return driver.releaseConnection(connection, options);
227
+ }
228
+ /** Scopes close their own pools. */
229
+ destroy() {
230
+ return Promise.resolve();
231
+ }
232
+ }
233
+ /** Kysely Postgres dialect over the running scope's pool. */
234
+ const scopedPostgres = {
235
+ createDriver: () => new ScopedDriver(),
236
+ createQueryCompiler: () => new PostgresQueryCompiler(),
237
+ createAdapter: () => new PostgresAdapter(),
238
+ createIntrospector: db => new PostgresIntrospector(db)
239
+ };
240
+ /** better-auth for `config` over the running scope's database: the `auth.*`
241
+ * schema, the session projection, the providers' plugins, dev sign-in,
242
+ * then `config.plugins`. */
243
+ function buildAuth(config) {
244
+ const {
245
+ baseURL,
246
+ secret,
247
+ plugins,
248
+ devSignIn,
249
+ errorURL
250
+ } = config;
251
+ const schema = schemaOptions(config);
252
+ const providers = providerOptions(config.providers, config.credentials);
253
+ return betterAuth({
254
+ ...schema,
255
+ baseURL,
256
+ secret,
257
+ database: {
258
+ dialect: scopedPostgres,
259
+ type: "postgres",
260
+ transaction: true
261
+ },
262
+ socialProviders: providers.socialProviders,
263
+ plugins: [sessionProjection(config.projectSession), ...providers.plugins, ...(devSignIn ? [devSignIn] : []), ...(plugins ?? [])],
264
+ onAPIError: {
265
+ errorURL
266
+ }
267
+ });
268
+ }
269
+ /**
270
+ * The auth instance of `configure(env)`, built once per `env` object: one per
271
+ * isolate on Workers, so plugin init runs once. Queries run inside
272
+ * `withShellAuth`. An invalid config throws `ExpectedError` naming each
273
+ * invalid value. A failed init drops the instance; the next call rebuilds
274
+ * it.
275
+ */
276
+ export function shellAuth(configure) {
277
+ const instances = new WeakMap();
278
+ return env => {
279
+ const cached = instances.get(env);
280
+ if (cached) return cached;
281
+ const auth = buildAuth(validated("config", configure(env)));
282
+ instances.set(env, auth);
283
+ auth.$context.catch(() => {
284
+ if (instances.get(env) === auth) instances.delete(env);
285
+ });
286
+ return auth;
287
+ };
288
+ }
289
+ /**
290
+ * Runs `fn` with `shellAuth` queries on a pool over `db`; the pool closes
291
+ * when `fn` settles. `fn` finishes its database reads first: a Response streaming
292
+ * lazily from the database fails.
293
+ */
294
+ export async function withShellAuth(db, fn) {
295
+ const driver = new PostgresDriver({
296
+ pool: new Pool({
297
+ connectionString: db,
298
+ max: 1
299
+ })
300
+ });
301
+ await driver.init();
302
+ try {
303
+ return await scope.run(driver, fn);
304
+ } finally {
305
+ await driver.destroy();
306
+ }
307
+ }
@@ -0,0 +1,8 @@
1
+ import { type AuthProvider, type SocialProviderOptions } from "./provider.ts";
2
+ /** Google sign-in options: better-auth's `GoogleOptions` beside the
3
+ * credentials. */
4
+ export type GoogleProviderOptions = SocialProviderOptions<"google">;
5
+ /** Google sign-in through better-auth's built-in provider; credentials
6
+ * from `AUTH_GOOGLE_ID`/`AUTH_GOOGLE_SECRET`, callback
7
+ * `/callback/google`. */
8
+ export declare function google(options?: GoogleProviderOptions): AuthProvider<"google">;
@@ -0,0 +1,11 @@
1
+ import { defineAuthProvider } from "./provider.js";
2
+ /** Google sign-in through better-auth's built-in provider; credentials
3
+ * from `AUTH_GOOGLE_ID`/`AUTH_GOOGLE_SECRET`, callback
4
+ * `/callback/google`. */
5
+ export function google(options = {}) {
6
+ return defineAuthProvider({
7
+ id: "google",
8
+ name: "Google",
9
+ social: () => options
10
+ });
11
+ }
@@ -0,0 +1,3 @@
1
+ /** OAuth sign-in providers: declarations, the app's set and built-ins. */
2
+ export * from "./google.ts";
3
+ export * from "./provider.ts";
@@ -0,0 +1,3 @@
1
+ /** OAuth sign-in providers: declarations, the app's set and built-ins. */
2
+ export * from "./google.js";
3
+ export * from "./provider.js";
@@ -0,0 +1,135 @@
1
+ /**
2
+ * OAuth sign-in providers as plugins: `defineAuthProvider` declares one,
3
+ * `defineAuthProviders` the app's set. A provider's id names its
4
+ * credential env keys (`AUTH_<ID>_ID`, `AUTH_<ID>_SECRET`), its callback
5
+ * (`/callback/<id>`) and its `auth.account.provider_id`; credentials
6
+ * enable it.
7
+ */
8
+ import { type OAuthCredentials } from "@astralarium/repo-env";
9
+ import type { BetterAuthOptions } from "better-auth";
10
+ import type { GenericOAuthConfig } from "better-auth/plugins/generic-oauth";
11
+ /** better-auth's built-in social providers by id. */
12
+ type SocialProviders = NonNullable<BetterAuthOptions["socialProviders"]>;
13
+ /** Ids of better-auth's built-in social providers. */
14
+ export type SocialProviderId = Extract<keyof SocialProviders, string>;
15
+ /** Options of built-in provider `Id` beside its credentials. */
16
+ export type SocialProviderOptions<Id extends SocialProviderId> = Omit<Exclude<NonNullable<SocialProviders[Id]>, (...args: never[]) => unknown>, "clientId" | "clientSecret">;
17
+ /** better-auth generic OAuth config beside the provider's id, name,
18
+ * credentials, endpoints and discovery. */
19
+ type GenericOAuthBase = Omit<GenericOAuthConfig, "providerId" | "name" | "clientId" | "clientSecret" | "discoveryUrl" | "discoveryHeaders" | "requireIdTokenVerification" | "disableIdTokenNonceBinding" | "authorizationUrl" | "tokenUrl" | "userInfoUrl">;
20
+ /**
21
+ * Generic OAuth with explicit endpoints. The profile is the claims of the
22
+ * ID token `tokenUrl` returns over TLS when they carry `sub` and `email`
23
+ * (signature unchecked), else `userInfoUrl`'s answer. Its `id` keys the
24
+ * account; `accountSubject` picks another claim, such as `sub`.
25
+ */
26
+ export type GenericOAuthEndpointOptions = GenericOAuthBase & {
27
+ /** Authorization endpoint the sign-in redirects to. */
28
+ authorizationUrl: string;
29
+ /** Token endpoint exchanging the authorization code. */
30
+ tokenUrl: string;
31
+ /** Userinfo endpoint read with the access token. */
32
+ userInfoUrl: string;
33
+ discoveryUrl?: never;
34
+ discoveryHeaders?: never;
35
+ requireIdTokenVerification?: never;
36
+ disableIdTokenNonceBinding?: never;
37
+ };
38
+ /**
39
+ * Generic OAuth over an OpenID Connect discovery document. A document
40
+ * with `issuer` and `jwks_uri` turns on ID token signature and nonce
41
+ * checks; a document listing `id_token_signing_alg_values_supported`
42
+ * keys accounts by `sub`.
43
+ */
44
+ export type GenericOAuthDiscoveryOptions = GenericOAuthBase & {
45
+ /** Discovery document URL, fetched at the auth instance's first init
46
+ * (inside a request on Workers). A failed fetch leaves the provider
47
+ * skipped, with a logged error, until the isolate recycles. */
48
+ discoveryUrl: string;
49
+ /** Headers of the discovery request. */
50
+ discoveryHeaders?: Record<string, string>;
51
+ /** Skips the provider when discovery lacks `issuer` or `jwks_uri`. */
52
+ requireIdTokenVerification?: boolean;
53
+ /** Accepts ID tokens missing the authorization request's `nonce`. */
54
+ disableIdTokenNonceBinding?: boolean;
55
+ /** Overrides the document's `authorization_endpoint`. */
56
+ authorizationUrl?: string;
57
+ /** Overrides the document's `token_endpoint`. */
58
+ tokenUrl?: string;
59
+ /** Overrides the document's `userinfo_endpoint`. */
60
+ userInfoUrl?: string;
61
+ };
62
+ /** better-auth generic OAuth config beside the provider's id, name and
63
+ * credentials: explicit endpoints or discovery. */
64
+ export type GenericOAuthOptions = GenericOAuthEndpointOptions | GenericOAuthDiscoveryOptions;
65
+ /** `Id` as an env key segment: upper case, `-` as `_`. */
66
+ type EnvSegment<Id extends string> = Id extends `${infer Head}-${infer Tail}` ? `${Uppercase<Head>}_${EnvSegment<Tail>}` : Uppercase<Id>;
67
+ /** Credential env keys of provider `Id`. */
68
+ export type AuthProviderKey<Id extends string> = `AUTH_${EnvSegment<Id>}_ID` | `AUTH_${EnvSegment<Id>}_SECRET`;
69
+ /** Fields every provider declaration shares. */
70
+ interface ProviderBase<Id extends string> {
71
+ /** Lower-case letters and digits, `-` between words. */
72
+ id: Id;
73
+ /** English display name: better-auth's provider name, consent screens
74
+ * and logs. Sign-in UI labels are the app's messages keyed by `id`. */
75
+ name: string;
76
+ }
77
+ /** A built-in better-auth social provider. */
78
+ export interface SocialProviderDefinition<Id extends SocialProviderId> extends ProviderBase<Id> {
79
+ /** Options for one auth instance; credentials merge over them. */
80
+ social: (credentials: OAuthCredentials) => SocialProviderOptions<Id>;
81
+ oauth?: never;
82
+ }
83
+ /** A generic OAuth 2.0 provider (better-auth `genericOAuth`). */
84
+ export interface OAuthProviderDefinition<Id extends string> extends ProviderBase<Id> {
85
+ /** Endpoints, scopes and profile mapping for one auth instance. */
86
+ oauth: (credentials: OAuthCredentials) => GenericOAuthOptions;
87
+ social?: never;
88
+ }
89
+ /** better-auth config of one provider for one auth instance. */
90
+ export type AuthProviderConfig = {
91
+ social: SocialProviderOptions<SocialProviderId> & OAuthCredentials;
92
+ } | {
93
+ oauth: GenericOAuthConfig;
94
+ };
95
+ /** A declared provider. */
96
+ export interface AuthProvider<Id extends string = string> {
97
+ id: Id;
98
+ name: string;
99
+ /** Credential env keys. */
100
+ keys: {
101
+ clientId: `AUTH_${EnvSegment<Id>}_ID`;
102
+ clientSecret: `AUTH_${EnvSegment<Id>}_SECRET`;
103
+ };
104
+ /** better-auth config over `credentials`. */
105
+ configure(credentials: OAuthCredentials): AuthProviderConfig;
106
+ }
107
+ /** Declares a built-in better-auth social provider. */
108
+ export declare function defineAuthProvider<const Id extends SocialProviderId>(definition: SocialProviderDefinition<Id>): AuthProvider<Id>;
109
+ /** Declares a generic OAuth 2.0 provider. */
110
+ export declare function defineAuthProvider<const Id extends string>(definition: OAuthProviderDefinition<Id>): AuthProvider<Id>;
111
+ /** Credentials by provider id; a provider without them stays off. */
112
+ export type AuthProviderCredentials<Id extends string = string> = Partial<Record<Id, OAuthCredentials>>;
113
+ /** Environment carrying the credential keys of providers `Id`. */
114
+ export type AuthProviderEnv<Id extends string> = Readonly<Partial<Record<AuthProviderKey<Id>, string | undefined>>>;
115
+ /** Credential bindings of providers `Id`; empty when unset. */
116
+ export type AuthProviderEnvironment<Id extends string> = Record<AuthProviderKey<Id>, string>;
117
+ /** An app's providers, in sign-in order. */
118
+ export interface AuthProviders<Id extends string = string> {
119
+ list: readonly AuthProvider<Id>[];
120
+ ids: readonly Id[];
121
+ /** Every credential env key: deploy secrets, dev overrides. */
122
+ keys: readonly AuthProviderKey<Id>[];
123
+ /** Credentials read from `env`; a half-set pair throws `ExpectedError`. */
124
+ credentials(env: AuthProviderEnv<Id>): AuthProviderCredentials<Id>;
125
+ /** Credential bindings for `credentials`, empty when unset. */
126
+ environment(credentials?: AuthProviderCredentials<Id>): AuthProviderEnvironment<Id>;
127
+ /** Ids with credentials, in sign-in order. */
128
+ enabled(credentials: AuthProviderCredentials<Id>): Id[];
129
+ }
130
+ /** Provider ids of a provider set. */
131
+ export type AuthProviderId<Providers extends AuthProviders> = Providers extends AuthProviders<infer Id> ? Id : never;
132
+ /** The app's provider set; empty leaves email and dev sign-in alone.
133
+ * Throws `ExpectedError` naming a repeated id. */
134
+ export declare function defineAuthProviders<const List extends readonly AuthProvider[]>(list: List): AuthProviders<List[number]["id"]>;
135
+ export {};
@@ -0,0 +1,86 @@
1
+ /**
2
+ * OAuth sign-in providers as plugins: `defineAuthProvider` declares one,
3
+ * `defineAuthProviders` the app's set. A provider's id names its
4
+ * credential env keys (`AUTH_<ID>_ID`, `AUTH_<ID>_SECRET`), its callback
5
+ * (`/callback/<id>`) and its `auth.account.provider_id`; credentials
6
+ * enable it.
7
+ */
8
+ import { credentialPair } from "@astralarium/repo-env";
9
+ import { ExpectedError } from "@astralarium/repo-telemetry";
10
+ import { z } from "zod";
11
+ /** Provider ids: lower-case words of letters and digits joined by `-`. */
12
+ const PROVIDER_ID = /^[a-z][a-z\d]*(?:-[a-z\d]+)*$/;
13
+ /** Id and name constraints the types leave open. */
14
+ const DefinitionShape = z.object({
15
+ id: z.string().regex(PROVIDER_ID),
16
+ name: z.string().min(1)
17
+ });
18
+ /** `id`'s env key segment. */
19
+ function envSegment(id) {
20
+ return id.toUpperCase().replaceAll("-", "_");
21
+ }
22
+ /** Validated provider; throws `ExpectedError` naming an invalid id or
23
+ * name. */
24
+ export function defineAuthProvider(definition) {
25
+ const result = DefinitionShape.safeParse(definition);
26
+ if (!result.success) {
27
+ throw new ExpectedError(`Invalid auth provider:\n${z.prettifyError(result.error)}`);
28
+ }
29
+ const {
30
+ id,
31
+ name
32
+ } = definition;
33
+ const segment = envSegment(id);
34
+ return {
35
+ id,
36
+ name,
37
+ keys: {
38
+ clientId: `AUTH_${segment}_ID`,
39
+ clientSecret: `AUTH_${segment}_SECRET`
40
+ },
41
+ configure: credentials => definition.social ? {
42
+ social: {
43
+ ...definition.social(credentials),
44
+ ...credentials
45
+ }
46
+ } : {
47
+ oauth: {
48
+ ...definition.oauth(credentials),
49
+ providerId: id,
50
+ name,
51
+ ...credentials
52
+ }
53
+ }
54
+ };
55
+ }
56
+ /** The app's provider set; empty leaves email and dev sign-in alone.
57
+ * Throws `ExpectedError` naming a repeated id. */
58
+ export function defineAuthProviders(list) {
59
+ const providers = list;
60
+ const repeated = providers.map(provider => provider.id).filter((id, index, ids) => ids.indexOf(id) !== index);
61
+ if (repeated.length) {
62
+ throw new ExpectedError(`Auth provider ids must be unique: ${[...new Set(repeated)].join(", ")}`);
63
+ }
64
+ return {
65
+ list: providers,
66
+ ids: providers.map(provider => provider.id),
67
+ keys: providers.flatMap(provider => [provider.keys.clientId, provider.keys.clientSecret]),
68
+ credentials(env) {
69
+ const credentials = {};
70
+ for (const provider of providers) {
71
+ const pair = credentialPair(env, provider.keys.clientId, provider.keys.clientSecret);
72
+ if (pair) credentials[provider.id] = pair;
73
+ }
74
+ return credentials;
75
+ },
76
+ environment(credentials = {}) {
77
+ return Object.fromEntries(providers.flatMap(provider => {
78
+ const pair = credentials[provider.id];
79
+ return [[provider.keys.clientId, pair?.clientId ?? ""], [provider.keys.clientSecret, pair?.clientSecret ?? ""]];
80
+ }));
81
+ },
82
+ enabled(credentials) {
83
+ return providers.filter(provider => credentials[provider.id]).map(provider => provider.id);
84
+ }
85
+ };
86
+ }
@@ -0,0 +1,42 @@
1
+ /** Serving Better Auth's endpoints: the paths an app answers, a per-client
2
+ * rate limit, and the base URL across dev origins. */
3
+ import type { publicWebConfig } from "@astralarium/repo-env";
4
+ import type { AdditionalFields, ShellAuthApp } from "./index.server.ts";
5
+ import type { SessionLike } from "./types.ts";
6
+ /** Better Auth's default mount path. */
7
+ export declare const AUTH_BASE_PATH = "/api/auth";
8
+ /** Endpoints starting an OAuth authorization from a JSON body. */
9
+ export declare const AUTHORIZE_PATHS: ReadonlySet<string>;
10
+ /** Endpoints `app`'s client calls: session, social sign-in, each
11
+ * provider's callback and sign-out; account linking with `linkSocial`;
12
+ * dev sign-in's endpoints with `devSignIn`. */
13
+ export declare function authPaths({ providers, linkSocial, devSignIn, }: Pick<ShellAuthApp<AdditionalFields, SessionLike>, "providers" | "linkSocial" | "devSignIn">): ReadonlySet<string>;
14
+ /** A per-key limiter: Cloudflare's rate limiting binding. */
15
+ export interface RateLimiter {
16
+ limit(options: {
17
+ key: string;
18
+ }): Promise<{
19
+ success: boolean;
20
+ }>;
21
+ }
22
+ /** What `serveAuthRequest` answers. */
23
+ export interface AuthRequestOptions {
24
+ /** Endpoints served (`authPaths`); others answer 404. */
25
+ paths: ReadonlySet<string>;
26
+ /** Limits each client IP (`cf-connecting-ip`); past it, 429. */
27
+ limiter?: RateLimiter;
28
+ /** Answers a served request: the auth instance's handler. */
29
+ handle: (request: Request) => Promise<Response>;
30
+ }
31
+ /** Answers `request` to the auth endpoints: 404 outside `paths`, 429 past
32
+ * `limiter`, 400 for an authorization start outside the redirect flow,
33
+ * else `handle`. */
34
+ export declare function serveAuthRequest(request: Request, { paths, limiter, handle }: AuthRequestOptions): Promise<Response>;
35
+ /** Better Auth `baseURL` for `config`: the request's host among its local
36
+ * origins, other hosts falling back to the site origin; the site origin
37
+ * alone without local origins. */
38
+ export declare function authBaseURL({ siteOrigin, localOrigins, }: ReturnType<typeof publicWebConfig>): string | {
39
+ allowedHosts: string[];
40
+ protocol: "https";
41
+ fallback: string;
42
+ };
@@ -0,0 +1,75 @@
1
+ /** Better Auth's default mount path. */
2
+ export const AUTH_BASE_PATH = "/api/auth";
3
+ /** Endpoints starting an OAuth authorization from a JSON body. */
4
+ export const AUTHORIZE_PATHS = new Set(["/sign-in/social", "/link-social"].map(path => `${AUTH_BASE_PATH}${path}`));
5
+ /** Endpoints `app`'s client calls: session, social sign-in, each
6
+ * provider's callback and sign-out; account linking with `linkSocial`;
7
+ * dev sign-in's endpoints with `devSignIn`. */
8
+ export function authPaths({
9
+ providers,
10
+ linkSocial,
11
+ devSignIn
12
+ }) {
13
+ return new Set(["/get-session", "/sign-in/social", ...(linkSocial ? ["/link-social"] : []), ...(providers?.ids ?? []).map(id => `/callback/${id}`), "/sign-out", ...Object.values(devSignIn?.endpoints ?? {}).map(({
14
+ path
15
+ }) => path)].map(path => `${AUTH_BASE_PATH}${path}`));
16
+ }
17
+ /** Whether `request` carries a JSON object without `idToken`. ID-token
18
+ * sign-in skips state, PKCE and nonce; authorization takes the redirect
19
+ * flow alone. */
20
+ async function redirectFlowBody(request) {
21
+ if (!request.headers.get("content-type")?.startsWith("application/json")) return false;
22
+ try {
23
+ const body = await request.clone().json();
24
+ return typeof body === "object" && body !== null && !Array.isArray(body) && !("idToken" in body);
25
+ } catch {
26
+ return false;
27
+ }
28
+ }
29
+ /** Answers `request` to the auth endpoints: 404 outside `paths`, 429 past
30
+ * `limiter`, 400 for an authorization start outside the redirect flow,
31
+ * else `handle`. */
32
+ export async function serveAuthRequest(request, {
33
+ paths,
34
+ limiter,
35
+ handle
36
+ }) {
37
+ const {
38
+ pathname
39
+ } = new URL(request.url);
40
+ if (!paths.has(pathname)) return new Response("Not Found", {
41
+ status: 404
42
+ });
43
+ if (limiter) {
44
+ const key = request.headers.get("cf-connecting-ip") ?? "local";
45
+ const {
46
+ success
47
+ } = await limiter.limit({
48
+ key
49
+ });
50
+ if (!success) return new Response("Too Many Requests", {
51
+ status: 429,
52
+ headers: {
53
+ "retry-after": "60"
54
+ }
55
+ });
56
+ }
57
+ if (AUTHORIZE_PATHS.has(pathname) && !(await redirectFlowBody(request))) return new Response("Bad Request", {
58
+ status: 400
59
+ });
60
+ return handle(request);
61
+ }
62
+ /** Better Auth `baseURL` for `config`: the request's host among its local
63
+ * origins, other hosts falling back to the site origin; the site origin
64
+ * alone without local origins. */
65
+ export function authBaseURL({
66
+ siteOrigin,
67
+ localOrigins
68
+ }) {
69
+ if (localOrigins.origins.length === 0) return siteOrigin;
70
+ return {
71
+ allowedHosts: localOrigins.hosts,
72
+ protocol: "https",
73
+ fallback: siteOrigin
74
+ };
75
+ }
@@ -0,0 +1,6 @@
1
+ /** The tables of shell-auth's Better Auth mapping and
2
+ * `auth.delete_expired()`; apps add their `additionalFields` columns in
3
+ * modules requiring it. Snapshots run `scrub.sql`. */
4
+ export declare const authSchema: import("@astralarium/repo-postgres/schema").SchemaModule;
5
+ /** pg_cron job `auth-ttl`: `auth.delete_expired()` hourly. */
6
+ export declare const authJobs: import("@astralarium/repo-postgres/schema").SchemaModule;