@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
package/dist/schema.js ADDED
@@ -0,0 +1,23 @@
1
+ /** The `auth` schema as schema modules: shell-auth's tables and their
2
+ * cleanup job. */
3
+ import { resolve } from "node:path";
4
+ import { packageRoot } from "@astralarium/repo-package-files";
5
+ import { cron, defineSchemaModule } from "@astralarium/repo-postgres/schema";
6
+ /** This package's SQL. */
7
+ const SQL_DIR = resolve(packageRoot(import.meta.filename), "sql");
8
+ /** The tables of shell-auth's Better Auth mapping and
9
+ * `auth.delete_expired()`; apps add their `additionalFields` columns in
10
+ * modules requiring it. Snapshots run `scrub.sql`. */
11
+ export const authSchema = defineSchemaModule({
12
+ name: "auth",
13
+ root: SQL_DIR,
14
+ files: ["schema.sql"],
15
+ scrub: "scrub.sql"
16
+ });
17
+ /** pg_cron job `auth-ttl`: `auth.delete_expired()` hourly. */
18
+ export const authJobs = defineSchemaModule({
19
+ name: "auth-jobs",
20
+ root: resolve(SQL_DIR, "jobs"),
21
+ files: ["schema.sql"],
22
+ requires: [cron, authSchema]
23
+ });
@@ -0,0 +1,6 @@
1
+ /** TanStack Start bindings of shell-auth, client-safe: the layout route
2
+ * context carrying the viewer's session, return paths, and server
3
+ * function middleware. */
4
+ export * from "./middleware.ts";
5
+ export * from "./return-path.ts";
6
+ export * from "./viewer.ts";
@@ -0,0 +1,6 @@
1
+ /** TanStack Start bindings of shell-auth, client-safe: the layout route
2
+ * context carrying the viewer's session, return paths, and server
3
+ * function middleware. */
4
+ export * from "./middleware.js";
5
+ export * from "./return-path.js";
6
+ export * from "./viewer.js";
@@ -0,0 +1,28 @@
1
+ import type { SessionLike } from "../types.ts";
2
+ /** Runs `fn` with the app's auth instance, its queries scoped to the
3
+ * request (`withShellAuth`). */
4
+ export type WithAuth<Auth> = <T>(fn: (auth: Auth) => Promise<T>) => Promise<T>;
5
+ /** What `viewerSession` reads of an auth instance: `shellAuth`'s
6
+ * projected `get-session`. */
7
+ export interface ViewerAuth {
8
+ api: {
9
+ getSession(context: {
10
+ headers: Headers;
11
+ returnHeaders: true;
12
+ }): Promise<{
13
+ headers: Headers;
14
+ response: unknown;
15
+ }>;
16
+ };
17
+ $Infer: {
18
+ Session: SessionLike;
19
+ };
20
+ }
21
+ /**
22
+ * Server function handler: the request's projected session, `null` signed
23
+ * out, read through `withAuth`; the response carries the read's cookies
24
+ * and is `private, no-store`. Apps declare the GET server function itself,
25
+ * as Start compiles top-level declarations alone:
26
+ * `createServerFn({ method: "GET" }).handler(viewerSession(withAuth))`.
27
+ */
28
+ export declare function viewerSession<Auth extends ViewerAuth>(withAuth: WithAuth<Auth>): () => Promise<Auth["$Infer"]["Session"] | null>;
@@ -0,0 +1,29 @@
1
+ /** Server half of shell-auth's TanStack Start bindings: the viewer's
2
+ * session read. */
3
+ import { createServerOnlyFn } from "@tanstack/react-start";
4
+ import { appendResponseHeader, getRequestHeaders, setResponseHeader } from "@tanstack/react-start/server";
5
+ /** `auth`'s session of the request, `null` signed out. The response
6
+ * carries the read's `Set-Cookie` values (cookie cache refresh, session
7
+ * extension) and depends on the request, so shared caches skip it. */
8
+ const readViewerSession = createServerOnlyFn(async auth => {
9
+ setResponseHeader("cache-control", "private, no-store");
10
+ const {
11
+ headers,
12
+ response
13
+ } = await auth.api.getSession({
14
+ headers: getRequestHeaders(),
15
+ returnHeaders: true
16
+ });
17
+ for (const cookie of headers.getSetCookie()) appendResponseHeader("set-cookie", cookie);
18
+ return response;
19
+ });
20
+ /**
21
+ * Server function handler: the request's projected session, `null` signed
22
+ * out, read through `withAuth`; the response carries the read's cookies
23
+ * and is `private, no-store`. Apps declare the GET server function itself,
24
+ * as Start compiles top-level declarations alone:
25
+ * `createServerFn({ method: "GET" }).handler(viewerSession(withAuth))`.
26
+ */
27
+ export function viewerSession(withAuth) {
28
+ return () => withAuth(auth => readViewerSession(auth));
29
+ }
@@ -0,0 +1,33 @@
1
+ /** Plain-text body of the 401 `Response` answering a signed-out call of
2
+ * an `authedMiddleware` server function. */
3
+ export declare const UNAUTHENTICATED = "unauthenticated";
4
+ /** Whether `error` is a 401 `Response`, as a signed-out call of an
5
+ * `authedMiddleware` server function rejects with. */
6
+ export declare function isUnauthenticated(error: unknown): error is Response;
7
+ /** Adds `sql`: one client over `connectionString()` per server function
8
+ * call; its one connection opens at the first query and closes when the
9
+ * handler resolves. The connection string reads per call: bindings are
10
+ * absent at static prerender. `connectionString` lands in the client
11
+ * build: a `createServerOnlyFn` drops its imports there. */
12
+ export declare function dbMiddleware(connectionString: () => string): import("@tanstack/react-start").FunctionMiddlewareAfterServer<{}, unknown, undefined, {
13
+ sql: import("postgres").Sql<{}>;
14
+ }, undefined, undefined, undefined>;
15
+ /** Adds the viewer's `session` from `readSession` (`viewerSession`'s
16
+ * server function), `null` signed out. The read opens its own
17
+ * connection (`withAuth`'s scope), closed before the handler runs; the
18
+ * cookie cache answers most reads with none. Handlers querying `sql`
19
+ * add `dbMiddleware` beside it. */
20
+ export declare function sessionMiddleware<Session>(readSession: () => Promise<Session | null>): import("@tanstack/react-start").FunctionMiddlewareAfterServer<{}, unknown, undefined, {
21
+ session: Awaited<Session> | null;
22
+ }, undefined, undefined, undefined>;
23
+ /** A `sessionMiddleware` over sessions of `Session`. */
24
+ export type SessionMiddleware<Session> = ReturnType<typeof sessionMiddleware<Session>>;
25
+ /** `session`'s context with a signed-in `session`, opening no
26
+ * connection of its own. A signed-out call throws a 401 `Response` with
27
+ * body `UNAUTHENTICATED`; Start rejects the caller's call with that
28
+ * `Response`, in the browser and during SSR (`isUnauthenticated`). */
29
+ export declare function authedMiddleware<Session>(session: SessionMiddleware<Session>): import("@tanstack/react-start").FunctionMiddlewareAfterServer<{}, readonly [import("@tanstack/react-start").FunctionMiddlewareAfterServer<{}, unknown, undefined, {
30
+ session: Awaited<Session> | null;
31
+ }, undefined, undefined, undefined>], undefined, {
32
+ session: NonNullable<Awaited<Session>>;
33
+ }, undefined, undefined, undefined>;
@@ -0,0 +1,70 @@
1
+ /** Server function middleware of shell-auth: a database client per call,
2
+ * the viewer's session, and signed-in calls alone. Client-importable:
3
+ * this package lists `@tanstack/react-start` as a peer, so Start's Vite
4
+ * plugin compiles it, and the client compile strips `.server()` bodies
5
+ * and their imports. */
6
+ import { withSql } from "@astralarium/repo-postgres/sql";
7
+ import { createMiddleware } from "@tanstack/react-start";
8
+ /** Plain-text body of the 401 `Response` answering a signed-out call of
9
+ * an `authedMiddleware` server function. */
10
+ export const UNAUTHENTICATED = "unauthenticated";
11
+ /** Whether `error` is a 401 `Response`, as a signed-out call of an
12
+ * `authedMiddleware` server function rejects with. */
13
+ export function isUnauthenticated(error) {
14
+ return error instanceof Response && error.status === 401;
15
+ }
16
+ /** Adds `sql`: one client over `connectionString()` per server function
17
+ * call; its one connection opens at the first query and closes when the
18
+ * handler resolves. The connection string reads per call: bindings are
19
+ * absent at static prerender. `connectionString` lands in the client
20
+ * build: a `createServerOnlyFn` drops its imports there. */
21
+ export function dbMiddleware(connectionString) {
22
+ return createMiddleware({
23
+ type: "function"
24
+ }).server(({
25
+ next
26
+ }) => withSql(connectionString(), sql => next({
27
+ context: {
28
+ sql
29
+ }
30
+ })));
31
+ }
32
+ /** Adds the viewer's `session` from `readSession` (`viewerSession`'s
33
+ * server function), `null` signed out. The read opens its own
34
+ * connection (`withAuth`'s scope), closed before the handler runs; the
35
+ * cookie cache answers most reads with none. Handlers querying `sql`
36
+ * add `dbMiddleware` beside it. */
37
+ export function sessionMiddleware(readSession) {
38
+ return createMiddleware({
39
+ type: "function"
40
+ }).server(async ({
41
+ next
42
+ }) => next({
43
+ context: {
44
+ session: await readSession()
45
+ }
46
+ }));
47
+ }
48
+ /** `session`'s context with a signed-in `session`, opening no
49
+ * connection of its own. A signed-out call throws a 401 `Response` with
50
+ * body `UNAUTHENTICATED`; Start rejects the caller's call with that
51
+ * `Response`, in the browser and during SSR (`isUnauthenticated`). */
52
+ export function authedMiddleware(session) {
53
+ return createMiddleware({
54
+ type: "function"
55
+ }).middleware([session]).server(({
56
+ next,
57
+ context
58
+ }) => {
59
+ if (!context.session)
60
+ // eslint-disable-next-line @typescript-eslint/only-throw-error -- Start answers a thrown `Response` as is
61
+ throw new Response(UNAUTHENTICATED, {
62
+ status: 401
63
+ });
64
+ return next({
65
+ context: {
66
+ session: context.session
67
+ }
68
+ });
69
+ });
70
+ }
@@ -0,0 +1,16 @@
1
+ /** Return paths: where a page sends the visitor once done, kept on this
2
+ * site. */
3
+ /** `url` resolved against `base`; null when it fails to parse. Stands in
4
+ * for `URL.parse`, which postdates the Vite browser baseline (Safari
5
+ * 16.4). */
6
+ export declare function parseUrl(url: string, base?: string): URL | null;
7
+ /** `url`'s normalized path, query and fragment when the browser resolves
8
+ * it as an origin-relative path; undefined when it or its normalized path
9
+ * (`//host`, from dot segments) names a host. */
10
+ export declare function ifUrlOkay(url?: string | null): string | undefined;
11
+ /** Search of a page returning to `r` once done; `validateSearch`. `r` is
12
+ * `ifUrlOkay`'s origin-relative path; an unsafe or non-string `r`
13
+ * drops. */
14
+ export declare function validateReturnSearch(search: Record<string, unknown>): {
15
+ r?: string;
16
+ };
@@ -0,0 +1,32 @@
1
+ /** Return paths: where a page sends the visitor once done, kept on this
2
+ * site. */
3
+ /** `url` resolved against `base`; null when it fails to parse. Stands in
4
+ * for `URL.parse`, which postdates the Vite browser baseline (Safari
5
+ * 16.4). */
6
+ export function parseUrl(url, base) {
7
+ try {
8
+ return new URL(url, base);
9
+ } catch {
10
+ return null;
11
+ }
12
+ }
13
+ /** Stand-in origin for resolving paths. */
14
+ const PATH_BASE = "http://path.invalid";
15
+ /** `url`'s normalized path, query and fragment when the browser resolves
16
+ * it as an origin-relative path; undefined when it or its normalized path
17
+ * (`//host`, from dot segments) names a host. */
18
+ export function ifUrlOkay(url) {
19
+ if (!url?.startsWith("/")) return;
20
+ const resolved = parseUrl(url, PATH_BASE);
21
+ if (resolved?.origin !== PATH_BASE || resolved.pathname.startsWith("//")) return;
22
+ return resolved.pathname + resolved.search + resolved.hash;
23
+ }
24
+ /** Search of a page returning to `r` once done; `validateSearch`. `r` is
25
+ * `ifUrlOkay`'s origin-relative path; an unsafe or non-string `r`
26
+ * drops. */
27
+ export function validateReturnSearch(search) {
28
+ const r = typeof search.r === "string" ? ifUrlOkay(search.r) : undefined;
29
+ return r === undefined ? {} : {
30
+ r
31
+ };
32
+ }
@@ -0,0 +1,8 @@
1
+ import type { ViewerContext } from "../client.ts";
2
+ /**
3
+ * `beforeLoad` of the layout route above every page reading the session:
4
+ * `{ session }` from `fetchViewer` (`viewerSession`'s server function) on
5
+ * the server, dehydrated with the match; `undefined` in the browser,
6
+ * whose live session store holds it (`watchViewerRouter`).
7
+ */
8
+ export declare function viewerRouteContext<Session>(fetchViewer: () => Promise<Session | null>): () => Promise<ViewerContext<Session>>;
@@ -0,0 +1,15 @@
1
+ /** The layout route context carrying the viewer's session in a TanStack
2
+ * Start app. */
3
+ import { createIsomorphicFn } from "@tanstack/react-start";
4
+ /**
5
+ * `beforeLoad` of the layout route above every page reading the session:
6
+ * `{ session }` from `fetchViewer` (`viewerSession`'s server function) on
7
+ * the server, dehydrated with the match; `undefined` in the browser,
8
+ * whose live session store holds it (`watchViewerRouter`).
9
+ */
10
+ export function viewerRouteContext(fetchViewer) {
11
+ const read = createIsomorphicFn().server(() => fetchViewer());
12
+ return async () => ({
13
+ session: await read()
14
+ });
15
+ }
@@ -0,0 +1,131 @@
1
+ /** Test support: a deployed `auth.*` schema checked against an app's auth
2
+ * instance, endpoint conformance (unserved paths, ID-token refusal,
3
+ * anonymous sessions), cookies out of auth responses, a rate-limit probe,
4
+ * social sign-in starts, session reads held on a lock, `testUtils`
5
+ * sessions, `auth.users` rows inserted directly, and a fake OpenID
6
+ * Connect provider. */
7
+ import { type Sql, type TransactionSql } from "@astralarium/repo-postgres/sql";
8
+ import { authPaths } from "../request.ts";
9
+ import { type JsonPost } from "./json-post.ts";
10
+ export * from "./oidc.ts";
11
+ /** The app fields `authPaths` reads. */
12
+ type AuthPathsApp = Parameters<typeof authPaths>[0];
13
+ /** What `unservedAuthPaths` reads of an auth instance: its endpoints. */
14
+ interface EndpointsAuth {
15
+ api: object;
16
+ }
17
+ /**
18
+ * Paths of `auth`'s HTTP endpoints outside `authPaths(app)`, sorted; each
19
+ * answers 404 through `serveAuthRequest`. A path parameter reads
20
+ * `undeclared` (`/api/auth/callback/undeclared`). Server-only endpoints
21
+ * mount no route.
22
+ */
23
+ export declare function unservedAuthPaths(auth: EndpointsAuth, app: AuthPathsApp): string[];
24
+ /** `app`'s endpoints starting an OAuth authorization from a JSON body:
25
+ * `/sign-in/social`, plus `/link-social` with `linkSocial`. An ID-token
26
+ * body there answers 400 (`idTokenAuthorization`). */
27
+ export declare function authorizePaths(app: AuthPathsApp): string[];
28
+ /** A JSON POST from `origin` authorizing `provider` with an ID token. */
29
+ export declare function idTokenAuthorization({ origin, provider, }: Pick<SocialSignIn, "origin" | "provider">): JsonPost;
30
+ /** A client of the app under test: its answer to a GET of `path`. */
31
+ export type TextRequester = (path: string) => Promise<{
32
+ status: number;
33
+ text(): Promise<string>;
34
+ }>;
35
+ /** Resolves once a cookieless `get-session` answers 200 `null`; rejects
36
+ * naming any other answer. */
37
+ export declare function expectAnonymousSession(request: TextRequester): Promise<void>;
38
+ /** `name=value` pairs of `setCookies` (or `cookie` header entries), later
39
+ * names replacing earlier. */
40
+ export declare function cookiePairs(setCookies: readonly string[]): Map<string, string>;
41
+ /** A `cookie` header of `pairs`. */
42
+ export declare function cookieHeader(pairs: Map<string, string>): string;
43
+ /** A client of the app under test: the response to a GET of `path`. */
44
+ export type AuthRequester = (path: string) => Promise<{
45
+ status: number;
46
+ body: {
47
+ cancel(): Promise<void>;
48
+ } | null;
49
+ }>;
50
+ /**
51
+ * Resolves once a GET of `path` through `request` answers 429: batches of
52
+ * 20 up to `2 * limit + 20` requests span at most two limit windows, so
53
+ * one window receives more than `limit`. Rejects when every request passes.
54
+ * Exhausts the client's budget for the window; run last.
55
+ */
56
+ export declare function expectAuthRateLimited(request: AuthRequester, path: string, limit: number): Promise<void>;
57
+ /** What the check reads of an auth instance: `shellAuth`'s, or any
58
+ * better-auth instance. */
59
+ interface SchemaCheckedAuth {
60
+ $context: Promise<{
61
+ explicitSchemaCheck?: (() => Promise<void> | undefined) | undefined;
62
+ }>;
63
+ }
64
+ /**
65
+ * Resolves once `db` holds every table and column `auth`'s configuration
66
+ * maps, plugin tables included; rejects with better-auth's
67
+ * `SchemaMismatchError` naming each missing one. Runs in its own
68
+ * `withShellAuth` scope over `db`.
69
+ */
70
+ export declare function verifyAuthSchema(db: string, auth: SchemaCheckedAuth): Promise<void>;
71
+ /** A client of the app under test: its answer to `init` at `path`. */
72
+ export type JsonRequester = (path: string, init: JsonPost) => Promise<{
73
+ status: number;
74
+ text(): Promise<string>;
75
+ }>;
76
+ /** A social sign-in `socialSignIn` starts. */
77
+ export interface SocialSignIn {
78
+ /** Page origin starting the sign-in; the `origin` header. */
79
+ origin: string;
80
+ /** Provider id. */
81
+ provider: string;
82
+ /** Page the provider returns to. Default `/`. */
83
+ callbackURL?: string;
84
+ }
85
+ /**
86
+ * Resolves to the provider authorization URL of a sign-in started at
87
+ * `${AUTH_BASE_PATH}/sign-in/social` with `disableRedirect`; rejects naming the
88
+ * status of any other answer than 200.
89
+ */
90
+ export declare function socialSignIn(request: JsonRequester, { origin, provider, callbackURL }: SocialSignIn): Promise<URL>;
91
+ /** A session read waiting on `withBlockedSessionRead`'s lock. */
92
+ export interface BlockedSessionRead<R> {
93
+ /** Postgres backend serving the read. */
94
+ pid: number;
95
+ /** Postgres role the backend runs as. */
96
+ role: string;
97
+ /** Whether `role` is a superuser. */
98
+ superuser: boolean;
99
+ /** The read's answer, settling once the lock releases. */
100
+ response: Promise<R>;
101
+ }
102
+ /** `withBlockedSessionRead` behavior. */
103
+ export interface BlockedSessionReadOptions {
104
+ /** `application_name` of the read's connection: picks its backend among
105
+ * other waiters on the lock. Default: the first read (SELECT) waiting on
106
+ * the lock. */
107
+ applicationName?: string;
108
+ /** Wait for the read to reach the lock. Default 10 s. */
109
+ timeout?: number;
110
+ }
111
+ /**
112
+ * Runs `fn` while a transaction over `db` holds `auth.session` exclusively
113
+ * (`holdTransaction`) and `readSession` (a database session read, e.g.
114
+ * `get-session` with a session cookie and `disableCookieCache`) waits on
115
+ * it. The lock releases as `fn` settles; rejects when no read reaches it
116
+ * within `timeout`.
117
+ */
118
+ export declare function withBlockedSessionRead<R, T>(db: string, readSession: () => Promise<R>, fn: (blocked: BlockedSessionRead<R>) => T | Promise<T>, { applicationName, timeout }?: BlockedSessionReadOptions): Promise<T>;
119
+ /** What `userSession` reads of an auth instance: one with better-auth's
120
+ * `testUtils` plugin. */
121
+ interface TestUtilsAuth {
122
+ $context: Promise<object>;
123
+ }
124
+ /** A `cookie` header carrying a new session of user `userId`, signed in
125
+ * through `auth`'s `testUtils` login in a `withShellAuth` scope over
126
+ * `db`. */
127
+ export declare function userSession(db: string, auth: TestUtilsAuth, userId: string): Promise<string>;
128
+ /** Inserts an `auth.users` row: a fresh verified email, created now,
129
+ * `fields` adding or overriding columns (the app's `additionalFields`).
130
+ * Resolves to the new user's id. */
131
+ export declare function insertAuthUser(sql: Sql | TransactionSql, fields?: Record<string, string | null>): Promise<string>;
@@ -0,0 +1,238 @@
1
+ /** Test support: a deployed `auth.*` schema checked against an app's auth
2
+ * instance, endpoint conformance (unserved paths, ID-token refusal,
3
+ * anonymous sessions), cookies out of auth responses, a rate-limit probe,
4
+ * social sign-in starts, session reads held on a lock, `testUtils`
5
+ * sessions, `auth.users` rows inserted directly, and a fake OpenID
6
+ * Connect provider. */
7
+ import { sql as pooledSql } from "@astralarium/repo-postgres/sql";
8
+ import { holdTransaction } from "@astralarium/repo-postgres/testkit";
9
+ import { z } from "zod";
10
+ import { withShellAuth } from "../index.server.js";
11
+ import { AUTH_BASE_PATH, AUTHORIZE_PATHS, authPaths } from "../request.js";
12
+ import { jsonPost } from "./json-post.js";
13
+ export * from "./oidc.js";
14
+ /** Fills each path parameter of a mounted endpoint: an id no app declares. */
15
+ const UNDECLARED_PARAM = "undeclared";
16
+ /**
17
+ * Paths of `auth`'s HTTP endpoints outside `authPaths(app)`, sorted; each
18
+ * answers 404 through `serveAuthRequest`. A path parameter reads
19
+ * `undeclared` (`/api/auth/callback/undeclared`). Server-only endpoints
20
+ * mount no route.
21
+ */
22
+ export function unservedAuthPaths(auth, app) {
23
+ const served = authPaths(app);
24
+ const unserved = new Set();
25
+ for (const endpoint of Object.values(auth.api)) {
26
+ const {
27
+ path,
28
+ options
29
+ } = endpoint;
30
+ if (!path || options?.metadata?.SERVER_ONLY) continue;
31
+ const route = `${AUTH_BASE_PATH}${path.replace(/:[^/]+/g, UNDECLARED_PARAM)}`;
32
+ if (!served.has(route)) unserved.add(route);
33
+ }
34
+ return [...unserved].sort();
35
+ }
36
+ /** `app`'s endpoints starting an OAuth authorization from a JSON body:
37
+ * `/sign-in/social`, plus `/link-social` with `linkSocial`. An ID-token
38
+ * body there answers 400 (`idTokenAuthorization`). */
39
+ export function authorizePaths(app) {
40
+ const served = authPaths(app);
41
+ return [...AUTHORIZE_PATHS].filter(path => served.has(path));
42
+ }
43
+ /** A JSON POST from `origin` authorizing `provider` with an ID token. */
44
+ export function idTokenAuthorization({
45
+ origin,
46
+ provider
47
+ }) {
48
+ return jsonPost(origin, {
49
+ provider,
50
+ idToken: {
51
+ token: "header.payload.signature"
52
+ }
53
+ });
54
+ }
55
+ /** Whether `text` is JSON `null`. */
56
+ function parsesToNull(text) {
57
+ try {
58
+ return JSON.parse(text) === null;
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
63
+ /** Resolves once a cookieless `get-session` answers 200 `null`; rejects
64
+ * naming any other answer. */
65
+ export async function expectAnonymousSession(request) {
66
+ const response = await request(`${AUTH_BASE_PATH}/get-session`);
67
+ const body = await response.text();
68
+ if (response.status !== 200 || !parsesToNull(body)) throw new Error(`anonymous get-session: HTTP ${response.status} ${body}, expected 200 null`);
69
+ }
70
+ /** `name=value` pairs of `setCookies` (or `cookie` header entries), later
71
+ * names replacing earlier. */
72
+ export function cookiePairs(setCookies) {
73
+ return new Map(setCookies.map(value => {
74
+ const pair = value.split(";")[0] ?? "";
75
+ const separator = pair.indexOf("=");
76
+ return [pair.slice(0, separator), pair.slice(separator + 1)];
77
+ }));
78
+ }
79
+ /** A `cookie` header of `pairs`. */
80
+ export function cookieHeader(pairs) {
81
+ return [...pairs].map(([name, value]) => `${name}=${value}`).join("; ");
82
+ }
83
+ /**
84
+ * Resolves once a GET of `path` through `request` answers 429: batches of
85
+ * 20 up to `2 * limit + 20` requests span at most two limit windows, so
86
+ * one window receives more than `limit`. Rejects when every request passes.
87
+ * Exhausts the client's budget for the window; run last.
88
+ */
89
+ export async function expectAuthRateLimited(request, path, limit) {
90
+ const batch = 20;
91
+ const total = 2 * limit + batch;
92
+ for (let sent = 0; sent < total; sent += batch) {
93
+ const statuses = await Promise.all(Array.from({
94
+ length: batch
95
+ }, async () => {
96
+ const response = await request(path);
97
+ await response.body?.cancel();
98
+ return response.status;
99
+ }));
100
+ if (statuses.includes(429)) return;
101
+ }
102
+ throw new Error(`no 429 within ${total} requests to ${path}`);
103
+ }
104
+ /**
105
+ * Resolves once `db` holds every table and column `auth`'s configuration
106
+ * maps, plugin tables included; rejects with better-auth's
107
+ * `SchemaMismatchError` naming each missing one. Runs in its own
108
+ * `withShellAuth` scope over `db`.
109
+ */
110
+ export function verifyAuthSchema(db, auth) {
111
+ return withShellAuth(db, async () => {
112
+ const check = (await auth.$context).explicitSchemaCheck;
113
+ if (!check) throw new Error("the auth adapter registers no schema check");
114
+ await check();
115
+ });
116
+ }
117
+ /**
118
+ * Resolves to the provider authorization URL of a sign-in started at
119
+ * `${AUTH_BASE_PATH}/sign-in/social` with `disableRedirect`; rejects naming the
120
+ * status of any other answer than 200.
121
+ */
122
+ export async function socialSignIn(request, {
123
+ origin,
124
+ provider,
125
+ callbackURL = "/"
126
+ }) {
127
+ const response = await request(`${AUTH_BASE_PATH}/sign-in/social`, jsonPost(origin, {
128
+ provider,
129
+ callbackURL,
130
+ disableRedirect: true
131
+ }));
132
+ const body = await response.text();
133
+ if (response.status !== 200) {
134
+ throw new Error(`${provider} sign-in from ${origin}: HTTP ${response.status} ${body}`);
135
+ }
136
+ const {
137
+ url
138
+ } = z.object({
139
+ url: z.string()
140
+ }).parse(JSON.parse(body));
141
+ return new URL(url);
142
+ }
143
+ /**
144
+ * Runs `fn` while a transaction over `db` holds `auth.session` exclusively
145
+ * (`holdTransaction`) and `readSession` (a database session read, e.g.
146
+ * `get-session` with a session cookie and `disableCookieCache`) waits on
147
+ * it. The lock releases as `fn` settles; rejects when no read reaches it
148
+ * within `timeout`.
149
+ */
150
+ export async function withBlockedSessionRead(db, readSession, fn, {
151
+ applicationName,
152
+ timeout = 10_000
153
+ } = {}) {
154
+ const client = pooledSql(db);
155
+ try {
156
+ const held = await holdTransaction(hold => client.begin(async tx => {
157
+ await tx`LOCK TABLE auth.session IN ACCESS EXCLUSIVE MODE`;
158
+ await hold(tx);
159
+ }));
160
+ try {
161
+ const response = readSession();
162
+ // Rejections surface through `fn`; a timeout leaves them unobserved.
163
+ response.catch(() => undefined);
164
+ const deadline = Date.now() + timeout;
165
+ for (;;) {
166
+ // pg_locks and pg_stat_activity.usename are visible across roles.
167
+ const [row] = await client`
168
+ SELECT a.pid, a.usename, r.rolsuper
169
+ FROM pg_locks l
170
+ JOIN pg_stat_activity a ON a.pid = l.pid
171
+ JOIN pg_roles r ON r.rolname = a.usename
172
+ WHERE l.relation = 'auth.session'::regclass AND NOT l.granted
173
+ AND l.mode = 'AccessShareLock'
174
+ AND ${held.holder}::integer = ANY(pg_blocking_pids(l.pid))
175
+ AND (${applicationName ?? null}::text IS NULL
176
+ OR a.application_name = ${applicationName ?? null})
177
+ `;
178
+ if (row) {
179
+ return await fn({
180
+ pid: row.pid,
181
+ role: row.usename,
182
+ superuser: row.rolsuper,
183
+ response
184
+ });
185
+ }
186
+ if (Date.now() > deadline) {
187
+ throw new Error(`no session read waited on auth.session in ${timeout} ms`);
188
+ }
189
+ await new Promise(resolve => setTimeout(resolve, 50));
190
+ }
191
+ } finally {
192
+ held.release();
193
+ await held.done;
194
+ }
195
+ } finally {
196
+ await client.end();
197
+ }
198
+ }
199
+ /** Whether `context` carries `testUtils`' helpers. */
200
+ function hasTestHelpers(context) {
201
+ return "test" in context;
202
+ }
203
+ /** A `cookie` header carrying a new session of user `userId`, signed in
204
+ * through `auth`'s `testUtils` login in a `withShellAuth` scope over
205
+ * `db`. */
206
+ export function userSession(db, auth, userId) {
207
+ return withShellAuth(db, async () => {
208
+ const context = await auth.$context;
209
+ if (!hasTestHelpers(context)) throw new Error("userSession: the auth instance lacks testUtils");
210
+ const {
211
+ cookies
212
+ } = await context.test.login({
213
+ userId
214
+ });
215
+ return cookies.map(({
216
+ name,
217
+ value
218
+ }) => `${name}=${value}`).join("; ");
219
+ });
220
+ }
221
+ /** Inserts an `auth.users` row: a fresh verified email, created now,
222
+ * `fields` adding or overriding columns (the app's `additionalFields`).
223
+ * Resolves to the new user's id. */
224
+ export async function insertAuthUser(sql, fields = {}) {
225
+ const now = new Date();
226
+ const user = {
227
+ name: "Test User",
228
+ email: `${crypto.randomUUID()}@test.invalid`,
229
+ email_verified: true,
230
+ created_at: now,
231
+ updated_at: now,
232
+ ...fields
233
+ };
234
+ const [row] = await sql`
235
+ INSERT INTO auth.users ${sql(user)} RETURNING id
236
+ `;
237
+ return row.id;
238
+ }
@@ -0,0 +1,8 @@
1
+ /** A JSON POST request init. */
2
+ export interface JsonPost {
3
+ method: "POST";
4
+ headers: Record<string, string>;
5
+ body: string;
6
+ }
7
+ /** A JSON POST of `body` from `origin`; `headers` add or override. */
8
+ export declare function jsonPost(origin: string, body: object, headers?: Record<string, string>): JsonPost;
@@ -0,0 +1,12 @@
1
+ /** A JSON POST of `body` from `origin`; `headers` add or override. */
2
+ export function jsonPost(origin, body, headers = {}) {
3
+ return {
4
+ method: "POST",
5
+ headers: {
6
+ origin,
7
+ "content-type": "application/json",
8
+ ...headers
9
+ },
10
+ body: JSON.stringify(body)
11
+ };
12
+ }