@cubicecho/server-kit 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.
- package/LICENSE +21 -0
- package/README.md +43 -2
- package/_agents/docs/01-database.md +31 -0
- package/_agents/docs/02-columns.md +25 -0
- package/_agents/docs/03-testing.md +18 -0
- package/_agents/docs/04-auth.md +41 -0
- package/_agents/docs/common-mistakes.md +23 -0
- package/dist/auth/defaults.d.ts +20 -0
- package/dist/auth/defaults.js +12 -0
- package/dist/auth/index.d.ts +3 -0
- package/dist/auth/index.js +3 -0
- package/dist/auth/plugins.d.ts +1270 -0
- package/dist/auth/plugins.js +39 -0
- package/dist/auth/preset.d.ts +53 -0
- package/dist/auth/preset.js +21 -0
- package/dist/columns/index.d.ts +38 -0
- package/dist/columns/index.js +53 -0
- package/dist/consts.d.ts +4 -0
- package/dist/consts.js +4 -0
- package/dist/db/connection.d.ts +18 -0
- package/dist/db/connection.js +15 -0
- package/dist/db/create.d.ts +40 -0
- package/dist/db/create.js +91 -0
- package/dist/db/defaults.d.ts +13 -0
- package/dist/db/defaults.js +8 -0
- package/dist/db/errors.d.ts +11 -0
- package/dist/db/errors.js +19 -0
- package/dist/db/index.d.ts +9 -0
- package/dist/db/index.js +8 -0
- package/dist/db/prepare.d.ts +32 -0
- package/dist/db/prepare.js +75 -0
- package/dist/db/ssl.d.ts +21 -0
- package/dist/db/ssl.js +91 -0
- package/dist/db/version.d.ts +22 -0
- package/dist/db/version.js +57 -0
- package/dist/db/wait.d.ts +23 -0
- package/dist/db/wait.js +52 -0
- package/dist/testing/index.d.ts +17 -0
- package/dist/testing/index.js +51 -0
- package/dist/testing/postgres-problems.d.ts +38 -0
- package/dist/testing/postgres-problems.js +57 -0
- package/dist/testing/schema-problems.d.ts +18 -0
- package/dist/testing/schema-problems.js +153 -0
- package/llms.txt +68 -0
- package/package.json +99 -4
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { oidcPairingPlugins } from '@cubicecho/better-auth-oidc-pairing';
|
|
2
|
+
import { bearer, magicLink } from 'better-auth/plugins';
|
|
3
|
+
import { AUTH_DEFAULTS, AUTH_PATHS } from './defaults.js';
|
|
4
|
+
const SECONDS_PER_MINUTE = 60;
|
|
5
|
+
/** better-auth's id for the magic-link plugin. */
|
|
6
|
+
const MAGIC_LINK_PLUGIN_ID = 'magic-link';
|
|
7
|
+
/**
|
|
8
|
+
* How people sign in: bearer sessions, OIDC with pairing, and emailed links. Never a password.
|
|
9
|
+
*
|
|
10
|
+
* @param options - The app's links and provider.
|
|
11
|
+
* @returns The plugins, to spread into `plugins`.
|
|
12
|
+
*/
|
|
13
|
+
export function signInPlugins({ appUrl, deliver, oidc, paths, magicLinkTtlMinutes = AUTH_DEFAULTS.magicLinkTtlMinutes, }) {
|
|
14
|
+
const { login, verify, signedIn } = { ...AUTH_PATHS, ...paths };
|
|
15
|
+
const links = deliver === undefined
|
|
16
|
+
? []
|
|
17
|
+
: [
|
|
18
|
+
magicLink({
|
|
19
|
+
expiresIn: magicLinkTtlMinutes * SECONDS_PER_MINUTE,
|
|
20
|
+
storeToken: 'hashed',
|
|
21
|
+
// Links go to the app, which spends the token over GraphQL. The REST verify route is not mounted.
|
|
22
|
+
sendMagicLink: ({ email, token }) => deliver({ email, token, url: `${appUrl}${verify}?token=${encodeURIComponent(token)}` }),
|
|
23
|
+
}),
|
|
24
|
+
];
|
|
25
|
+
return [
|
|
26
|
+
bearer(),
|
|
27
|
+
...oidcPairingPlugins({ ...oidc, signedInURL: `${appUrl}${signedIn}`, errorURL: `${appUrl}${login}` }),
|
|
28
|
+
...links,
|
|
29
|
+
];
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Whether an instance emails sign-in links.
|
|
33
|
+
*
|
|
34
|
+
* @param auth - The auth instance.
|
|
35
|
+
* @returns true when it was built with a way to deliver them.
|
|
36
|
+
*/
|
|
37
|
+
export function sendsMagicLinks(auth) {
|
|
38
|
+
return (auth.options.plugins ?? []).some((plugin) => plugin.id === MAGIC_LINK_PLUGIN_ID);
|
|
39
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
|
|
2
|
+
import { type AuthPaths, type AuthSettings } from './defaults.ts';
|
|
3
|
+
/** The tables better-auth keeps, by its own model names. */
|
|
4
|
+
export interface AuthTables {
|
|
5
|
+
user: unknown;
|
|
6
|
+
session: unknown;
|
|
7
|
+
account: unknown;
|
|
8
|
+
verification: unknown;
|
|
9
|
+
/** Tables plugins add, such as `apikey` and `ssoProvider`. */
|
|
10
|
+
[model: string]: unknown;
|
|
11
|
+
}
|
|
12
|
+
/** What an app gives the preset. */
|
|
13
|
+
export interface AuthPresetOptions extends Partial<Pick<AuthSettings, 'sessionTtlDays'>> {
|
|
14
|
+
/** The Drizzle client. */
|
|
15
|
+
db: Parameters<typeof drizzleAdapter>[0];
|
|
16
|
+
/** The tables, passed explicitly: the rc Drizzle client is keyed by relations, so they cannot be discovered. */
|
|
17
|
+
tables: AuthTables;
|
|
18
|
+
/** What better-auth signs with. */
|
|
19
|
+
secret: string;
|
|
20
|
+
/** Where a browser reaches this server. */
|
|
21
|
+
serverUrl: string;
|
|
22
|
+
/** Where users reach the app. A sign-in may finish there. */
|
|
23
|
+
appUrl: string;
|
|
24
|
+
/**
|
|
25
|
+
* Pages that are somewhere else in this app.
|
|
26
|
+
*
|
|
27
|
+
* @defaultValue `AUTH_PATHS`
|
|
28
|
+
*/
|
|
29
|
+
paths?: Partial<AuthPaths>;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The better-auth options every server shares. Spread it into `betterAuth`, then add plugins and hooks.
|
|
33
|
+
*
|
|
34
|
+
* @param options - What differs per app.
|
|
35
|
+
* @returns Sessions in Postgres, ids from the columns' own defaults, and the app's origin trusted.
|
|
36
|
+
*/
|
|
37
|
+
export declare function authPreset({ db, tables, secret, serverUrl, appUrl, paths, sessionTtlDays, }: AuthPresetOptions): {
|
|
38
|
+
database: (options: import("@better-auth/core").BetterAuthOptions) => import("@better-auth/core/db/adapter").DBAdapter<import("@better-auth/core").BetterAuthOptions>;
|
|
39
|
+
secret: string;
|
|
40
|
+
baseURL: string;
|
|
41
|
+
trustedOrigins: string[];
|
|
42
|
+
advanced: {
|
|
43
|
+
database: {
|
|
44
|
+
generateId: 'uuid';
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
session: {
|
|
48
|
+
expiresIn: number;
|
|
49
|
+
};
|
|
50
|
+
onAPIError: {
|
|
51
|
+
errorURL: string;
|
|
52
|
+
};
|
|
53
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
|
|
2
|
+
import { AUTH_DEFAULTS, AUTH_PATHS } from './defaults.js';
|
|
3
|
+
const SECONDS_PER_DAY = 86_400;
|
|
4
|
+
/**
|
|
5
|
+
* The better-auth options every server shares. Spread it into `betterAuth`, then add plugins and hooks.
|
|
6
|
+
*
|
|
7
|
+
* @param options - What differs per app.
|
|
8
|
+
* @returns Sessions in Postgres, ids from the columns' own defaults, and the app's origin trusted.
|
|
9
|
+
*/
|
|
10
|
+
export function authPreset({ db, tables, secret, serverUrl, appUrl, paths, sessionTtlDays = AUTH_DEFAULTS.sessionTtlDays, }) {
|
|
11
|
+
return {
|
|
12
|
+
database: drizzleAdapter(db, { provider: 'pg', schema: tables }),
|
|
13
|
+
secret,
|
|
14
|
+
baseURL: serverUrl,
|
|
15
|
+
trustedOrigins: [new URL(appUrl).origin],
|
|
16
|
+
// On Postgres this leaves the id out of the insert, so the column's uuidv7() fills it.
|
|
17
|
+
advanced: { database: { generateId: 'uuid' } },
|
|
18
|
+
session: { expiresIn: sessionTtlDays * SECONDS_PER_DAY },
|
|
19
|
+
onAPIError: { errorURL: `${appUrl}${{ ...AUTH_PATHS, ...paths }.login}` },
|
|
20
|
+
};
|
|
21
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type PgColumn } from 'drizzle-orm/pg-core';
|
|
2
|
+
/**
|
|
3
|
+
* The primary key of an entity: a UUIDv7, made by the database.
|
|
4
|
+
*
|
|
5
|
+
* @returns The `id` column.
|
|
6
|
+
*/
|
|
7
|
+
export declare function id(): import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetIsPrimaryKey<import("drizzle-orm/pg-core").PgUUIDBuilder>>;
|
|
8
|
+
/**
|
|
9
|
+
* A moment, with its time zone.
|
|
10
|
+
*
|
|
11
|
+
* @typeParam Name - The column's SQL name.
|
|
12
|
+
* @param name - The column's SQL name.
|
|
13
|
+
* @returns The column.
|
|
14
|
+
*/
|
|
15
|
+
export declare function moment<Name extends string>(name: Name): import("drizzle-orm/pg-core").PgTimestampBuilder;
|
|
16
|
+
/**
|
|
17
|
+
* When a row was made, and when it last changed. Spread into a mutable table's columns.
|
|
18
|
+
*
|
|
19
|
+
* @returns `createdAt` and `updatedAt`.
|
|
20
|
+
*/
|
|
21
|
+
export declare function timestamps(): {
|
|
22
|
+
createdAt: import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>>;
|
|
23
|
+
updatedAt: import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>>>;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* The column that keeps a table to one row. It is always true and unique, and an upsert targets it.
|
|
27
|
+
*
|
|
28
|
+
* @returns The `singleton` column. The table also needs `singletonRules`.
|
|
29
|
+
*/
|
|
30
|
+
export declare function singleton(): import("drizzle-orm/pg-core").SetHasDefault<import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgBooleanBuilder>>;
|
|
31
|
+
/**
|
|
32
|
+
* The unique index and the check that make `singleton` work.
|
|
33
|
+
*
|
|
34
|
+
* @param table - The table's SQL name.
|
|
35
|
+
* @param column - Its `singleton` column.
|
|
36
|
+
* @returns Both, to spread into the table's extras.
|
|
37
|
+
*/
|
|
38
|
+
export declare function singletonRules(table: string, column: PgColumn): (import("drizzle-orm/pg-core").CheckBuilder | import("drizzle-orm/pg-core").IndexBuilder)[];
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { sql } from 'drizzle-orm';
|
|
2
|
+
import { boolean, check, timestamp, uniqueIndex, uuid } from 'drizzle-orm/pg-core';
|
|
3
|
+
/**
|
|
4
|
+
* The primary key of an entity: a UUIDv7, made by the database.
|
|
5
|
+
*
|
|
6
|
+
* @returns The `id` column.
|
|
7
|
+
*/
|
|
8
|
+
export function id() {
|
|
9
|
+
return uuid('id').primaryKey().default(sql `uuidv7()`);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* A moment, with its time zone.
|
|
13
|
+
*
|
|
14
|
+
* @typeParam Name - The column's SQL name.
|
|
15
|
+
* @param name - The column's SQL name.
|
|
16
|
+
* @returns The column.
|
|
17
|
+
*/
|
|
18
|
+
export function moment(name) {
|
|
19
|
+
return timestamp(name, { withTimezone: true });
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* When a row was made, and when it last changed. Spread into a mutable table's columns.
|
|
23
|
+
*
|
|
24
|
+
* @returns `createdAt` and `updatedAt`.
|
|
25
|
+
*/
|
|
26
|
+
export function timestamps() {
|
|
27
|
+
return {
|
|
28
|
+
createdAt: moment('created_at').notNull().defaultNow(),
|
|
29
|
+
updatedAt: moment('updated_at')
|
|
30
|
+
.notNull()
|
|
31
|
+
.defaultNow()
|
|
32
|
+
.$onUpdate(() => new Date()),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The column that keeps a table to one row. It is always true and unique, and an upsert targets it.
|
|
37
|
+
*
|
|
38
|
+
* @returns The `singleton` column. The table also needs `singletonRules`.
|
|
39
|
+
*/
|
|
40
|
+
export function singleton() {
|
|
41
|
+
return boolean('singleton').notNull().default(true);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The unique index and the check that make `singleton` work.
|
|
45
|
+
*
|
|
46
|
+
* @param table - The table's SQL name.
|
|
47
|
+
* @param column - Its `singleton` column.
|
|
48
|
+
* @returns Both, to spread into the table's extras.
|
|
49
|
+
*/
|
|
50
|
+
export function singletonRules(table, column) {
|
|
51
|
+
const isTrue = sql `${column}`;
|
|
52
|
+
return [uniqueIndex(`uq_${table}_singleton`).on(column), check(`ck_${table}_singleton`, isTrue)];
|
|
53
|
+
}
|
package/dist/consts.d.ts
ADDED
package/dist/consts.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** What a postgres-js client is given besides its URL. */
|
|
2
|
+
export interface ConnectionOptions {
|
|
3
|
+
/** Present when TLS has to be forced on. */
|
|
4
|
+
ssl?: 'require';
|
|
5
|
+
/** Drops notices. */
|
|
6
|
+
onnotice: () => void;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The postgres-js options a server connects with.
|
|
10
|
+
*
|
|
11
|
+
* @param url - The connection string.
|
|
12
|
+
* @param isProduction - Whether to force TLS to a host that is not private.
|
|
13
|
+
* @returns The options, to spread beside `url`.
|
|
14
|
+
*
|
|
15
|
+
* @remarks
|
|
16
|
+
* Idempotent migrations emit a NOTICE on every boot, and printing it makes a healthy restart look like a failure.
|
|
17
|
+
*/
|
|
18
|
+
export declare function connectionOptions(url: string, isProduction: boolean): ConnectionOptions;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { requiresSsl } from './ssl.js';
|
|
2
|
+
/**
|
|
3
|
+
* The postgres-js options a server connects with.
|
|
4
|
+
*
|
|
5
|
+
* @param url - The connection string.
|
|
6
|
+
* @param isProduction - Whether to force TLS to a host that is not private.
|
|
7
|
+
* @returns The options, to spread beside `url`.
|
|
8
|
+
*
|
|
9
|
+
* @remarks
|
|
10
|
+
* Idempotent migrations emit a NOTICE on every boot, and printing it makes a healthy restart look like a failure.
|
|
11
|
+
*/
|
|
12
|
+
export function connectionOptions(url, isProduction) {
|
|
13
|
+
const mustForceSsl = isProduction && requiresSsl(url);
|
|
14
|
+
return { onnotice: () => { }, ...(mustForceSsl ? { ssl: 'require' } : {}) };
|
|
15
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Queryable } from './wait.ts';
|
|
2
|
+
/** The least boot needs of a connection to the maintenance database. */
|
|
3
|
+
export interface AdminClient {
|
|
4
|
+
unsafe: (query: string, parameters?: string[]) => PromiseLike<unknown>;
|
|
5
|
+
end: () => Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
/** Opens a connection to the maintenance database. */
|
|
8
|
+
export type OpenAdmin = (url: string) => AdminClient;
|
|
9
|
+
/** A connection string's database, and where to create it from. */
|
|
10
|
+
export interface MaintenanceTarget {
|
|
11
|
+
/** The database the connection string names. */
|
|
12
|
+
database: string;
|
|
13
|
+
/** The same server and credentials, on the maintenance database. */
|
|
14
|
+
maintenanceUrl: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Opens one connection, with TLS decided as the app's own pool decides it.
|
|
18
|
+
*
|
|
19
|
+
* @param isProduction - Whether to force TLS to a host that is not private.
|
|
20
|
+
* @returns A function that opens a client the caller must end.
|
|
21
|
+
*/
|
|
22
|
+
export declare function openAdmin(isProduction: boolean): OpenAdmin;
|
|
23
|
+
/**
|
|
24
|
+
* Splits a connection string into its database and the server's maintenance database.
|
|
25
|
+
*
|
|
26
|
+
* @param url - The connection string.
|
|
27
|
+
* @returns Both.
|
|
28
|
+
* @throws {@link DatabaseBootError} If it names no database.
|
|
29
|
+
*/
|
|
30
|
+
export declare function maintenanceTarget(url: string): MaintenanceTarget;
|
|
31
|
+
/**
|
|
32
|
+
* Creates the database a connection string names.
|
|
33
|
+
*
|
|
34
|
+
* @param url - The connection string whose database is missing.
|
|
35
|
+
* @param open - Opens the maintenance connection.
|
|
36
|
+
* @param check - Throws when the app cannot run on the server. Called before anything is created.
|
|
37
|
+
* @returns true when this call created it, false when another instance got there first.
|
|
38
|
+
* @throws {@link DatabaseBootError} If the role may not create databases.
|
|
39
|
+
*/
|
|
40
|
+
export declare function createDatabase(url: string, open: OpenAdmin, check: (server: Queryable) => Promise<void>): Promise<boolean>;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { PgDialect } from 'drizzle-orm/pg-core';
|
|
2
|
+
import postgres from 'postgres';
|
|
3
|
+
import { connectionOptions } from './connection.js';
|
|
4
|
+
import { DatabaseBootError, errorCode } from './errors.js';
|
|
5
|
+
/** CREATE DATABASE lost a race with another instance doing the same. */
|
|
6
|
+
const ALREADY_EXISTS = '42P04';
|
|
7
|
+
/** The role may not create databases. */
|
|
8
|
+
const NOT_ALLOWED = '42501';
|
|
9
|
+
/** The database every server has, to connect to while the app's is missing. */
|
|
10
|
+
const MAINTENANCE_DATABASE = 'postgres';
|
|
11
|
+
const dialect = new PgDialect();
|
|
12
|
+
/**
|
|
13
|
+
* Opens one connection, with TLS decided as the app's own pool decides it.
|
|
14
|
+
*
|
|
15
|
+
* @param isProduction - Whether to force TLS to a host that is not private.
|
|
16
|
+
* @returns A function that opens a client the caller must end.
|
|
17
|
+
*/
|
|
18
|
+
export function openAdmin(isProduction) {
|
|
19
|
+
return (url) => postgres(url, { max: 1, ...connectionOptions(url, isProduction) });
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Splits a connection string into its database and the server's maintenance database.
|
|
23
|
+
*
|
|
24
|
+
* @param url - The connection string.
|
|
25
|
+
* @returns Both.
|
|
26
|
+
* @throws {@link DatabaseBootError} If it names no database.
|
|
27
|
+
*/
|
|
28
|
+
export function maintenanceTarget(url) {
|
|
29
|
+
const parsed = new URL(url);
|
|
30
|
+
// Undecoded, as postgres-js reads it. Without one it falls back to the environment, which is not read here.
|
|
31
|
+
const database = parsed.pathname.slice(1);
|
|
32
|
+
if (database === '') {
|
|
33
|
+
throw new DatabaseBootError('DATABASE_URL names no database, so there is nothing to create.');
|
|
34
|
+
}
|
|
35
|
+
parsed.pathname = `/${MAINTENANCE_DATABASE}`;
|
|
36
|
+
return { database, maintenanceUrl: parsed.toString() };
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Quotes a name as a SQL identifier.
|
|
40
|
+
*
|
|
41
|
+
* @param name - The raw identifier.
|
|
42
|
+
* @returns The identifier, safe in a statement.
|
|
43
|
+
*/
|
|
44
|
+
function quoteIdentifier(name) {
|
|
45
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Lets a maintenance connection run Drizzle's queries.
|
|
49
|
+
*
|
|
50
|
+
* @param client - The connection.
|
|
51
|
+
* @returns It, as something `requirePostgres` can ask.
|
|
52
|
+
*/
|
|
53
|
+
function queryable(client) {
|
|
54
|
+
return {
|
|
55
|
+
execute: (query) => {
|
|
56
|
+
const { sql, params } = dialect.sqlToQuery(query);
|
|
57
|
+
return client.unsafe(sql, params.map(String));
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Creates the database a connection string names.
|
|
63
|
+
*
|
|
64
|
+
* @param url - The connection string whose database is missing.
|
|
65
|
+
* @param open - Opens the maintenance connection.
|
|
66
|
+
* @param check - Throws when the app cannot run on the server. Called before anything is created.
|
|
67
|
+
* @returns true when this call created it, false when another instance got there first.
|
|
68
|
+
* @throws {@link DatabaseBootError} If the role may not create databases.
|
|
69
|
+
*/
|
|
70
|
+
export async function createDatabase(url, open, check) {
|
|
71
|
+
const { database, maintenanceUrl } = maintenanceTarget(url);
|
|
72
|
+
const client = open(maintenanceUrl);
|
|
73
|
+
try {
|
|
74
|
+
await check(queryable(client));
|
|
75
|
+
await client.unsafe(`create database ${quoteIdentifier(database)}`);
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
const code = errorCode(error);
|
|
80
|
+
if (code === ALREADY_EXISTS) {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
if (code === NOT_ALLOWED) {
|
|
84
|
+
throw new DatabaseBootError(`Database "${database}" does not exist, and this role may not create it. Create it, or grant the role CREATEDB.`, { cause: error });
|
|
85
|
+
}
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
await client.end();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Settings for reaching Postgres at boot. */
|
|
2
|
+
export interface DatabaseSettings {
|
|
3
|
+
/** How long boot waits for Postgres before giving up. */
|
|
4
|
+
connectTimeoutMs: number;
|
|
5
|
+
/** The wait before the first retry. */
|
|
6
|
+
firstRetryDelayMs: number;
|
|
7
|
+
/** The longest wait between two retries. */
|
|
8
|
+
maxRetryDelayMs: number;
|
|
9
|
+
/** How much the wait grows after each failed attempt. */
|
|
10
|
+
retryBackoffFactor: number;
|
|
11
|
+
}
|
|
12
|
+
/** What boot uses when the app overrides nothing. */
|
|
13
|
+
export declare const DATABASE_DEFAULTS: Readonly<DatabaseSettings>;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Every value someone might tune, as plain data. Nothing here computes, reads the environment or imports.
|
|
2
|
+
/** What boot uses when the app overrides nothing. */
|
|
3
|
+
export const DATABASE_DEFAULTS = Object.freeze({
|
|
4
|
+
connectTimeoutMs: 60_000,
|
|
5
|
+
firstRetryDelayMs: 500,
|
|
6
|
+
maxRetryDelayMs: 5_000,
|
|
7
|
+
retryBackoffFactor: 2,
|
|
8
|
+
});
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Thrown when boot cannot use the database. Its message is written for whoever runs the server. */
|
|
2
|
+
export declare class DatabaseBootError extends Error {
|
|
3
|
+
name: string;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Reads the driver or errno code of an error, or of whatever caused it.
|
|
7
|
+
*
|
|
8
|
+
* @param error - Whatever was thrown. Drizzle wraps the driver's error.
|
|
9
|
+
* @returns The code, or undefined when there is none.
|
|
10
|
+
*/
|
|
11
|
+
export declare function errorCode(error: unknown): string | undefined;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Thrown when boot cannot use the database. Its message is written for whoever runs the server. */
|
|
2
|
+
export class DatabaseBootError extends Error {
|
|
3
|
+
name = 'DatabaseBootError';
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Reads the driver or errno code of an error, or of whatever caused it.
|
|
7
|
+
*
|
|
8
|
+
* @param error - Whatever was thrown. Drizzle wraps the driver's error.
|
|
9
|
+
* @returns The code, or undefined when there is none.
|
|
10
|
+
*/
|
|
11
|
+
export function errorCode(error) {
|
|
12
|
+
if (typeof error !== 'object' || error === null) {
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
if ('code' in error && typeof error.code === 'string') {
|
|
16
|
+
return error.code;
|
|
17
|
+
}
|
|
18
|
+
return 'cause' in error ? errorCode(error.cause) : undefined;
|
|
19
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { MIN_POSTGRES_MAJOR, TESTED_POSTGRES_MAJOR } from '../consts.ts';
|
|
2
|
+
export { type ConnectionOptions, connectionOptions } from './connection.ts';
|
|
3
|
+
export type { AdminClient, OpenAdmin } from './create.ts';
|
|
4
|
+
export { DATABASE_DEFAULTS, type DatabaseSettings } from './defaults.ts';
|
|
5
|
+
export { DatabaseBootError, errorCode } from './errors.ts';
|
|
6
|
+
export { type PrepareOptions, prepareDatabase } from './prepare.ts';
|
|
7
|
+
export { isPrivateHost, requiresSsl } from './ssl.ts';
|
|
8
|
+
export { type PostgresNeeds, requirePostgres } from './version.ts';
|
|
9
|
+
export { type Queryable, waitForDatabase } from './wait.ts';
|
package/dist/db/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { MIN_POSTGRES_MAJOR, TESTED_POSTGRES_MAJOR } from '../consts.js';
|
|
2
|
+
export { connectionOptions } from './connection.js';
|
|
3
|
+
export { DATABASE_DEFAULTS } from './defaults.js';
|
|
4
|
+
export { DatabaseBootError, errorCode } from './errors.js';
|
|
5
|
+
export { prepareDatabase } from './prepare.js';
|
|
6
|
+
export { isPrivateHost, requiresSsl } from './ssl.js';
|
|
7
|
+
export { requirePostgres } from './version.js';
|
|
8
|
+
export { waitForDatabase } from './wait.js';
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type OpenAdmin } from './create.ts';
|
|
2
|
+
import type { DatabaseSettings } from './defaults.ts';
|
|
3
|
+
import { type PostgresNeeds } from './version.ts';
|
|
4
|
+
import { type Queryable } from './wait.ts';
|
|
5
|
+
/** How a database is made ready. */
|
|
6
|
+
export interface PrepareOptions extends PostgresNeeds, Partial<DatabaseSettings> {
|
|
7
|
+
/** The connection string the client was built from. */
|
|
8
|
+
url: string;
|
|
9
|
+
/** Whether to force TLS to a host that is not private. */
|
|
10
|
+
isProduction: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Where retries, the creation and warnings are reported.
|
|
13
|
+
*
|
|
14
|
+
* @defaultValue `console.warn`
|
|
15
|
+
*/
|
|
16
|
+
log?: (message: string) => void;
|
|
17
|
+
/**
|
|
18
|
+
* Opens the maintenance connection. Tests replace it.
|
|
19
|
+
*
|
|
20
|
+
* @defaultValue a postgres-js client
|
|
21
|
+
*/
|
|
22
|
+
open?: OpenAdmin;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Makes the database ready to migrate: waits for it, creates it when it is missing, and checks its version.
|
|
26
|
+
*
|
|
27
|
+
* @param db - The app's Drizzle client.
|
|
28
|
+
* @param options - Where the database is, and what the app needs of it.
|
|
29
|
+
* @returns Resolves once the app may migrate.
|
|
30
|
+
* @throws {@link DatabaseBootError} If the app cannot run on it. The message says why, and what to do.
|
|
31
|
+
*/
|
|
32
|
+
export declare function prepareDatabase(db: Queryable, options: PrepareOptions): Promise<void>;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { createDatabase, maintenanceTarget, openAdmin } from './create.js';
|
|
2
|
+
import { DatabaseBootError, errorCode } from './errors.js';
|
|
3
|
+
import { requirePostgres } from './version.js';
|
|
4
|
+
import { isStillStarting, waitForDatabase } from './wait.js';
|
|
5
|
+
/** Postgres's answer when the database a connection names does not exist. */
|
|
6
|
+
const MISSING_DATABASE = '3D000';
|
|
7
|
+
/** Postgres's port, shown when a connection string names none. */
|
|
8
|
+
const DEFAULT_POSTGRES_PORT = '5432';
|
|
9
|
+
/**
|
|
10
|
+
* Makes the database ready to migrate: waits for it, creates it when it is missing, and checks its version.
|
|
11
|
+
*
|
|
12
|
+
* @param db - The app's Drizzle client.
|
|
13
|
+
* @param options - Where the database is, and what the app needs of it.
|
|
14
|
+
* @returns Resolves once the app may migrate.
|
|
15
|
+
* @throws {@link DatabaseBootError} If the app cannot run on it. The message says why, and what to do.
|
|
16
|
+
*/
|
|
17
|
+
export async function prepareDatabase(db, options) {
|
|
18
|
+
const { url, isProduction, log = console.warn, open = openAdmin(isProduction), extensions, testedMajor } = options;
|
|
19
|
+
const { connectTimeoutMs, firstRetryDelayMs, maxRetryDelayMs, retryBackoffFactor } = options;
|
|
20
|
+
const settings = withoutUnset({ connectTimeoutMs, firstRetryDelayMs, maxRetryDelayMs, retryBackoffFactor });
|
|
21
|
+
const needs = { extensions, testedMajor };
|
|
22
|
+
try {
|
|
23
|
+
await waitOrCreate(db, { url, settings, needs, log, open });
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (isStillStarting(error)) {
|
|
27
|
+
throw new DatabaseBootError(unreachable(url, errorCode(error)), { cause: error });
|
|
28
|
+
}
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
await requirePostgres(db, needs, log);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Drops the settings a caller left out, so a spread does not copy `undefined` over a default.
|
|
35
|
+
*
|
|
36
|
+
* @param settings - Settings, some unset.
|
|
37
|
+
* @returns The ones that are set.
|
|
38
|
+
*/
|
|
39
|
+
function withoutUnset(settings) {
|
|
40
|
+
return Object.fromEntries(Object.entries(settings).filter(([, value]) => value !== undefined));
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Waits for the database, creating it first when the server is up without it.
|
|
44
|
+
*
|
|
45
|
+
* @param db - The app's Drizzle client.
|
|
46
|
+
* @param options - Where the database is, and how long to wait.
|
|
47
|
+
*/
|
|
48
|
+
async function waitOrCreate(db, { url, settings, needs, log, open }) {
|
|
49
|
+
try {
|
|
50
|
+
await waitForDatabase(db, settings, log);
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (errorCode(error) !== MISSING_DATABASE) {
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
const created = await createDatabase(url, open, (server) => requirePostgres(server, needs, () => { }));
|
|
57
|
+
if (created) {
|
|
58
|
+
log(`[db] created database "${maintenanceTarget(url).database}"`);
|
|
59
|
+
}
|
|
60
|
+
await waitForDatabase(db, settings, log);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Says that a server cannot be reached, without its credentials.
|
|
65
|
+
*
|
|
66
|
+
* @param url - The connection string.
|
|
67
|
+
* @param code - Why, as the driver put it.
|
|
68
|
+
* @returns The message.
|
|
69
|
+
*/
|
|
70
|
+
function unreachable(url, code) {
|
|
71
|
+
const { hostname, port } = new URL(url);
|
|
72
|
+
return (`Cannot reach Postgres at ${hostname}:${port || DEFAULT_POSTGRES_PORT} (${code}). ` +
|
|
73
|
+
'Check DATABASE_URL, and that the database is up and reachable from here. With a remote Docker daemon, a port ' +
|
|
74
|
+
"published on 127.0.0.1 is on the daemon host's loopback.");
|
|
75
|
+
}
|
package/dist/db/ssl.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a host is this machine or on a private network.
|
|
3
|
+
*
|
|
4
|
+
* "Private" is wider than loopback, because self-hosting is: a compose service
|
|
5
|
+
* and a box on the LAN are both names nothing outside can reach.
|
|
6
|
+
*
|
|
7
|
+
* @param hostname - The host from a URL, lowercased and without IPv6 brackets.
|
|
8
|
+
* @returns true for localhost, a dotless name, a private-use suffix or a private address.
|
|
9
|
+
*/
|
|
10
|
+
export declare function isPrivateHost(hostname: string): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Whether to insist on TLS for a connection string.
|
|
13
|
+
*
|
|
14
|
+
* Read from the parsed hostname, never the raw string: a URL carrying
|
|
15
|
+
* credentials puts the userinfo where a prefix match looks for the host. A
|
|
16
|
+
* private host speaks no TLS by default, and demanding it breaks the connection.
|
|
17
|
+
*
|
|
18
|
+
* @param url - The connection string.
|
|
19
|
+
* @returns false for a private host, and when the URL sets its own `sslmode`.
|
|
20
|
+
*/
|
|
21
|
+
export declare function requiresSsl(url: string): boolean;
|