@cubicecho/server-kit 0.11.0 → 0.11.1

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.
@@ -82,7 +82,7 @@ await gate.as(code, () => auth.api.pairOidcProvider({ body: { setupUrl }, header
82
82
  ```
83
83
 
84
84
  - With `setup`, the first account comes from `claimInstance` or an OIDC provider's callback, and from nothing else. Until then no link is emailed.
85
- - One claim wins, across processes. Refusals are `FORBIDDEN` or `CONFLICT` with a `SetupRefusal` as `extensions.reason`. `asSetupRefusal` turns better-auth's own error into the same.
85
+ - One claim wins, across processes. A claim keeps others out for `SETUP_DEFAULTS.claimSeconds` (60), or `signInPlugins({ claimSeconds })`, should its process die part way. Refusals are `FORBIDDEN` or `CONFLICT` with a `SetupRefusal` as `extensions.reason`. `asSetupRefusal` turns better-auth's own error into the same.
86
86
  - A server for one person refuses the second account in its own `user.create.before`, which runs after the kit's.
87
87
  - `canPair` has to check that there is no account as well: `gate.isAdmitted()` only says the caller has the code.
88
88
  - A made-up code is the process's own, so run one process, or set `SETUP_CODE`.
@@ -25,7 +25,7 @@ stopOnSignals(server, { before: () => scheduler.stop(), after: closeDatabase });
25
25
 
26
26
  - Mount `/healthz` and `mountAuthRedirects` before the static handler, which answers every path.
27
27
  - `checkHealth` logs why Postgres did not answer and never says it: anyone may ask, and a driver's error names hosts.
28
- - `createStaticHandler` keeps `/assets/` and `/_expo/` files for a year, and answers 404 for one that is gone. Anything else that is not a file is `index.html`.
28
+ - `createStaticHandler` keeps `/assets/` and `/_expo/` files for a year (`createStaticHandler(dir, { immutableCacheSeconds })` changes that), and answers 404 for one that is gone. Anything else that is not a file is `index.html`.
29
29
  - `stopOnSignals` drains, runs `after`, and exits within `shutdownDeadlineSeconds`, under Docker's 10. A second signal exits at once.
30
30
  - `cutOff` runs at the drain deadline and is awaited before the open connections are cut: end SSE streams there, so a client reads a clean end instead of a reset.
31
31
  - `oidcSignInUrl` and `oidcRedirectUri` name the two OIDC routes for a provider.
@@ -1,5 +1,5 @@
1
1
  import { oidcPairingPlugins } from '@cubicecho/better-auth-oidc-pairing';
2
- import { type AuthPaths, type AuthSettings } from './defaults.ts';
2
+ import { type AuthPaths, type AuthSettings, type SetupSettings } from './defaults.ts';
3
3
  import { type SetupGate } from './setup.ts';
4
4
  /** What delivering one sign-in link is given. */
5
5
  export interface MagicLink {
@@ -11,7 +11,7 @@ export interface MagicLink {
11
11
  /** OIDC sign-in and pairing, without the two URLs, which follow from `appUrl`. */
12
12
  export type OidcOptions = Omit<Parameters<typeof oidcPairingPlugins>[0], 'signedInURL' | 'errorURL'>;
13
13
  /** What an app gives `signInPlugins`, besides OIDC. */
14
- export interface SignInOptions extends Partial<Pick<AuthSettings, 'magicLinkTtlMinutes'>> {
14
+ export interface SignInOptions extends Partial<Pick<AuthSettings, 'magicLinkTtlMinutes'>>, Partial<Pick<SetupSettings, 'claimSeconds'>> {
15
15
  /** Where users reach the app. */
16
16
  appUrl: string;
17
17
  /** Delivers a sign-in link, or undefined on an instance that cannot email. */
@@ -31,7 +31,7 @@ export interface SignInOptions extends Partial<Pick<AuthSettings, 'magicLinkTtlM
31
31
  * @param options - The app's links.
32
32
  * @returns The plugins.
33
33
  */
34
- declare function linkPlugins({ appUrl, deliver, paths, setup, magicLinkTtlMinutes, }: SignInOptions): ({
34
+ declare function linkPlugins({ appUrl, deliver, paths, setup, magicLinkTtlMinutes, claimSeconds, }: SignInOptions): ({
35
35
  id: "bearer";
36
36
  version: string;
37
37
  hooks: {
@@ -11,7 +11,7 @@ const MAGIC_LINK_PLUGIN_ID = 'magic-link';
11
11
  * @param options - The app's links.
12
12
  * @returns The plugins.
13
13
  */
14
- function linkPlugins({ appUrl, deliver, paths, setup, magicLinkTtlMinutes = AUTH_DEFAULTS.magicLinkTtlMinutes, }) {
14
+ function linkPlugins({ appUrl, deliver, paths, setup, magicLinkTtlMinutes = AUTH_DEFAULTS.magicLinkTtlMinutes, claimSeconds, }) {
15
15
  const { verify } = { ...AUTH_PATHS, ...paths };
16
16
  const links = deliver === undefined
17
17
  ? []
@@ -28,7 +28,7 @@ function linkPlugins({ appUrl, deliver, paths, setup, magicLinkTtlMinutes = AUTH
28
28
  },
29
29
  }),
30
30
  ];
31
- const setups = setup === undefined ? [] : [setupPlugin(setup)];
31
+ const setups = setup === undefined ? [] : [setupPlugin(setup, claimSeconds === undefined ? {} : { claimSeconds })];
32
32
  return [bearer(), ...links, ...setups];
33
33
  }
34
34
  /**
@@ -25,7 +25,7 @@ export declare function openAdmin(isProduction: boolean): OpenAdmin;
25
25
  *
26
26
  * @param url - The connection string.
27
27
  * @returns Both.
28
- * @throws {@link DatabaseBootError} If it names no database.
28
+ * @throws {@link DatabaseBootError} If it is not a URL, or names no database.
29
29
  */
30
30
  export declare function maintenanceTarget(url: string): MaintenanceTarget;
31
31
  /**
package/dist/db/create.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { PgDialect } from 'drizzle-orm/pg-core';
2
2
  import postgres from 'postgres';
3
3
  import { connectionOptions } from './connection.js';
4
- import { DatabaseBootError, errorCode } from './errors.js';
4
+ import { DatabaseBootError, errorCode, parseDatabaseUrl } from './errors.js';
5
5
  /** CREATE DATABASE lost a race with another instance doing the same. */
6
6
  const ALREADY_EXISTS = '42P04';
7
7
  /** The role may not create databases. */
@@ -23,14 +23,14 @@ export function openAdmin(isProduction) {
23
23
  *
24
24
  * @param url - The connection string.
25
25
  * @returns Both.
26
- * @throws {@link DatabaseBootError} If it names no database.
26
+ * @throws {@link DatabaseBootError} If it is not a URL, or names no database.
27
27
  */
28
28
  export function maintenanceTarget(url) {
29
- const parsed = new URL(url);
29
+ const parsed = parseDatabaseUrl(url);
30
30
  // Undecoded, as postgres-js reads it. Without one it falls back to the environment, which is not read here.
31
31
  const database = parsed.pathname.slice(1);
32
32
  if (database === '') {
33
- throw new DatabaseBootError('DATABASE_URL names no database, so there is nothing to create.');
33
+ throw new DatabaseBootError('DATABASE_URL names no database, so there is nothing to create. Add its name as the path: postgres://user:password@host:5432/<database>.');
34
34
  }
35
35
  parsed.pathname = `/${MAINTENANCE_DATABASE}`;
36
36
  return { database, maintenanceUrl: parsed.toString() };
@@ -2,6 +2,14 @@
2
2
  export declare class DatabaseBootError extends Error {
3
3
  name: string;
4
4
  }
5
+ /**
6
+ * Parses a connection string, refusing one that is not a URL without repeating it: it holds the password.
7
+ *
8
+ * @param url - The connection string.
9
+ * @returns The parsed URL.
10
+ * @throws {@link DatabaseBootError} If it does not parse. Node's own error would carry the whole string.
11
+ */
12
+ export declare function parseDatabaseUrl(url: string): URL;
5
13
  /**
6
14
  * Reads the driver or errno code of an error, or of whatever caused it.
7
15
  *
package/dist/db/errors.js CHANGED
@@ -2,6 +2,19 @@
2
2
  export class DatabaseBootError extends Error {
3
3
  name = 'DatabaseBootError';
4
4
  }
5
+ /**
6
+ * Parses a connection string, refusing one that is not a URL without repeating it: it holds the password.
7
+ *
8
+ * @param url - The connection string.
9
+ * @returns The parsed URL.
10
+ * @throws {@link DatabaseBootError} If it does not parse. Node's own error would carry the whole string.
11
+ */
12
+ export function parseDatabaseUrl(url) {
13
+ if (URL.canParse(url) === false) {
14
+ throw new DatabaseBootError('DATABASE_URL is not a valid URL. Percent-encode any character in the user or password that is not a letter, a digit or one of - . _ ~');
15
+ }
16
+ return new URL(url);
17
+ }
5
18
  /**
6
19
  * Reads the driver or errno code of an error, or of whatever caused it.
7
20
  *
@@ -1,5 +1,5 @@
1
1
  import { createDatabase, maintenanceTarget, openAdmin } from './create.js';
2
- import { DatabaseBootError, errorCode } from './errors.js';
2
+ import { DatabaseBootError, errorCode, parseDatabaseUrl } from './errors.js';
3
3
  import { requirePostgres } from './version.js';
4
4
  import { isStillStarting, waitForDatabase } from './wait.js';
5
5
  /** Postgres's answer when the database a connection names does not exist. */
@@ -66,9 +66,10 @@ async function waitOrCreate(db, { url, settings, needs, log, open }) {
66
66
  * @param url - The connection string.
67
67
  * @param code - Why, as the driver put it.
68
68
  * @returns The message.
69
+ * @throws {@link DatabaseBootError} If the connection string is not a URL.
69
70
  */
70
71
  function unreachable(url, code) {
71
- const { hostname, port } = new URL(url);
72
+ const { hostname, port } = parseDatabaseUrl(url);
72
73
  return (`Cannot reach Postgres at ${hostname}:${port || DEFAULT_POSTGRES_PORT} (${code}). ` +
73
74
  'Check DATABASE_URL, and that the database is up and reachable from here. With a remote Docker daemon, a port ' +
74
75
  "published on 127.0.0.1 is on the daemon host's loopback.");
@@ -17,6 +17,6 @@ export interface PostgresNeeds {
17
17
  * @param [needs] - What the app needs besides the minimum version.
18
18
  * @param [log] - Called with a warning when the server is newer than the app is tested on.
19
19
  * @returns Resolves once the server is known to be good enough.
20
- * @throws {@link DatabaseBootError} If it is too old, or lacks an extension.
20
+ * @throws {@link DatabaseBootError} If its version can't be read, it is too old, or it lacks an extension.
21
21
  */
22
22
  export declare function requirePostgres(db: Queryable, { extensions, testedMajor }?: PostgresNeeds, log?: (message: string) => void): Promise<void>;
@@ -23,11 +23,16 @@ async function rowsOf(db, query) {
23
23
  * @param [needs] - What the app needs besides the minimum version.
24
24
  * @param [log] - Called with a warning when the server is newer than the app is tested on.
25
25
  * @returns Resolves once the server is known to be good enough.
26
- * @throws {@link DatabaseBootError} If it is too old, or lacks an extension.
26
+ * @throws {@link DatabaseBootError} If its version can't be read, it is too old, or it lacks an extension.
27
27
  */
28
28
  export async function requirePostgres(db, { extensions = [], testedMajor = TESTED_POSTGRES_MAJOR } = {}, log = console.warn) {
29
29
  const [server] = await rowsOf(db, sql `select current_setting('server_version_num')::int as number, current_setting('server_version') as name`);
30
30
  const major = Math.floor(Number(server?.number) / VERSION_NUM_PER_MAJOR);
31
+ // An answer this can't read is refused: letting it through would skip the check it is here for.
32
+ const isKnown = Number.isFinite(major);
33
+ if (isKnown === false) {
34
+ throw new DatabaseBootError('Could not read the Postgres server version, so it cannot be checked. Nothing was changed. Check that DATABASE_URL points at Postgres.');
35
+ }
31
36
  if (major < MIN_POSTGRES_MAJOR) {
32
37
  throw new DatabaseBootError(`Postgres ${server?.name} is too old: ${MIN_POSTGRES_MAJOR} or later is needed. Nothing was changed.`);
33
38
  }
@@ -3,7 +3,8 @@ import type { Advertisement, Advertiser } from '@cubicecho/graphql-mdns-discover
3
3
  export interface Announcement {
4
4
  name: string;
5
5
  port: number;
6
- path: string;
6
+ /** Where the service is served. Each package has its own default when it is missing. */
7
+ path?: string;
7
8
  tls?: boolean;
8
9
  onError?: (error: Error) => void;
9
10
  }
@@ -1,3 +1,4 @@
1
+ import { DEFAULT_GRAPHQL_PATH } from '@cubicecho/graphql-mdns-discovery';
1
2
  import { advertiseGraphql, createGraphqlAdvertiser } from '@cubicecho/graphql-mdns-discovery/mdns';
2
3
  /** What an app installs to announce its MCP door. */
3
4
  const MCP_DISCOVERY = '@cubicecho/mcp-discovery';
@@ -23,18 +24,19 @@ const announceMcp = async (announcement) => {
23
24
  * door is kept in step the same way without loading mcp-discovery until it starts.
24
25
  *
25
26
  * @param deps - The server's switch and log.
26
- * @param label - Put before each log line, so the two types' lines can be told apart.
27
- * @param options - What to announce, or null when this type isn't.
28
- * @param start - Starts this type's announcement.
27
+ * @param type - This type: its label for the log, whether the server has it, what to announce and how.
28
+ * @param type.label - Put before each log line, so the two types' lines can be told apart.
29
+ * @param type.isServed - Whether the server serves this type at all.
30
+ * @param type.options - What to announce.
31
+ * @param type.start - Starts this type's announcement.
29
32
  * @returns The advertiser.
30
33
  */
31
- function typeAdvertiser(deps, label, options, start) {
34
+ function typeAdvertiser(deps, type) {
32
35
  return createGraphqlAdvertiser({
33
- isWanted: () => deps.isWanted() && options() !== null,
34
- // Read only when isWanted is true, so options() is not null here.
35
- options: () => options(),
36
- log: (message) => deps.log(`${label}: ${message}`),
37
- start: (announcement) => start(announcement),
36
+ isWanted: () => deps.isWanted() && type.isServed(),
37
+ options: type.options,
38
+ log: (message) => deps.log(`${type.label}: ${message}`),
39
+ start: type.start,
38
40
  });
39
41
  }
40
42
  /**
@@ -50,14 +52,24 @@ function typeAdvertiser(deps, label, options, start) {
50
52
  * share. One that fails is logged and the server carries on; the next `sync` tries again.
51
53
  */
52
54
  export function createLanAdvertiser(deps) {
53
- const graphql = typeAdvertiser(deps, 'GraphQL', () => {
54
- const { name, port, graphqlPath = '/graphql', tls } = deps.options();
55
- return { name, port, path: graphqlPath, tls };
56
- }, deps.announce?.graphql ?? advertiseGraphql);
57
- const mcp = typeAdvertiser(deps, 'MCP', () => {
58
- const { name, port, mcpPath, tls } = deps.options();
59
- return mcpPath === undefined ? null : { name, port, path: mcpPath, tls };
60
- }, deps.announce?.mcp ?? announceMcp);
55
+ const graphql = typeAdvertiser(deps, {
56
+ label: 'GraphQL',
57
+ isServed: () => true,
58
+ options: () => {
59
+ const { name, port, graphqlPath = DEFAULT_GRAPHQL_PATH, tls } = deps.options();
60
+ return { name, port, path: graphqlPath, tls };
61
+ },
62
+ start: deps.announce?.graphql ?? advertiseGraphql,
63
+ });
64
+ const mcp = typeAdvertiser(deps, {
65
+ label: 'MCP',
66
+ isServed: () => deps.options().mcpPath !== undefined,
67
+ options: () => {
68
+ const { name, port, mcpPath, tls } = deps.options();
69
+ return { name, port, path: mcpPath, tls };
70
+ },
71
+ start: deps.announce?.mcp ?? announceMcp,
72
+ });
61
73
  return {
62
74
  sync: async () => {
63
75
  await Promise.all([graphql.sync(), mcp.sync()]);
@@ -1,13 +1,15 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { type HttpSettings } from './defaults.ts';
2
3
  /** A request handler, for Express or plain `node:http`. */
3
4
  export type StaticHandler = (request: IncomingMessage, response: ServerResponse) => void;
4
5
  /**
5
6
  * Serves a built single-page app, whose `index.html` answers every path that is not a file.
6
7
  *
7
8
  * @param root - The directory holding the built app.
9
+ * @param [overrides] - How long a browser keeps a hashed file, when not `HTTP_DEFAULTS.immutableCacheSeconds`.
8
10
  * @returns The handler.
9
11
  *
10
12
  * @remarks
11
13
  * A hashed file that is missing is a 404, never the index: a browser would keep that page under the bundle's name.
12
14
  */
13
- export declare function createStaticHandler(root: string): StaticHandler;
15
+ export declare function createStaticHandler(root: string, overrides?: Partial<Pick<HttpSettings, 'immutableCacheSeconds'>>): StaticHandler;
@@ -50,13 +50,15 @@ function isFileAt(path) {
50
50
  * Serves a built single-page app, whose `index.html` answers every path that is not a file.
51
51
  *
52
52
  * @param root - The directory holding the built app.
53
+ * @param [overrides] - How long a browser keeps a hashed file, when not `HTTP_DEFAULTS.immutableCacheSeconds`.
53
54
  * @returns The handler.
54
55
  *
55
56
  * @remarks
56
57
  * A hashed file that is missing is a 404, never the index: a browser would keep that page under the bundle's name.
57
58
  */
58
- export function createStaticHandler(root) {
59
+ export function createStaticHandler(root, overrides = {}) {
59
60
  const rootDir = resolve(root);
61
+ const immutableCacheSeconds = overrides.immutableCacheSeconds ?? HTTP_DEFAULTS.immutableCacheSeconds;
60
62
  return (request, response) => {
61
63
  const isRead = request.method === 'GET' || request.method === 'HEAD';
62
64
  if (isRead === false) {
@@ -86,7 +88,7 @@ export function createStaticHandler(root) {
86
88
  }
87
89
  const headers = {
88
90
  'content-type': CONTENT_TYPES[extname(filePath)] ?? UNKNOWN_TYPE,
89
- 'cache-control': isHashed ? `public, max-age=${HTTP_DEFAULTS.immutableCacheSeconds}, immutable` : 'no-cache',
91
+ 'cache-control': isHashed ? `public, max-age=${immutableCacheSeconds}, immutable` : 'no-cache',
90
92
  'x-content-type-options': 'nosniff',
91
93
  };
92
94
  if (request.method === 'HEAD') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cubicecho/server-kit",
3
- "version": "0.11.0",
3
+ "version": "0.11.1",
4
4
  "description": "The server code every cubicecho GraphQL backend shares: database boot, id columns and the checks that keep a schema to the standard.",
5
5
  "license": "MIT",
6
6
  "author": "Benjamin Van Treese",
package/skill/auth.md CHANGED
@@ -112,7 +112,7 @@ export async function sessionUserId(auth: Auth, headers: Headers): Promise<strin
112
112
 
113
113
  - `createAuth` has no written return type: `auth.api`'s type is built from the plugin list. Keep the plugins one array literal, with `signInPlugins` spread into it.
114
114
  - **An option after the preset's spread replaces the preset's whole value**, so a `session: { … }` of your own repeats `expiresIn`. Never add `emailAndPassword`.
115
- - Lifetimes and page paths are `AUTH_DEFAULTS` and `AUTH_PATHS`; override through `sessionTtlDays`, `magicLinkTtlMinutes` or `paths`.
115
+ - Lifetimes and page paths are `AUTH_DEFAULTS` and `AUTH_PATHS`; override through `sessionTtlDays`, `magicLinkTtlMinutes` or `paths`. How long a setup claim keeps others out is `SETUP_DEFAULTS.claimSeconds`, overridden by `signInPlugins({ claimSeconds })`.
116
116
  - `secret`, `sendMagicLink` and `pinned` are dependencies, not settings, so they stay in `AuthOptions`.
117
117
  - `sendsMagicLinks(auth)` reads the instance, not `SMTP_URL`, so a test's captured links count as on.
118
118
  - `better-auth`, `@better-auth/sso` and `@cubicecho/better-auth-oidc-pairing` are the server's own dependencies, all three even with `oidc: false`.
package/skill/boot.md CHANGED
@@ -264,7 +264,7 @@ const releaseLock = await holdPostgresLock(session, {
264
264
  ## Health and static files
265
265
 
266
266
  - **`/healthz` answers `{ ok, version }` and never says why it is not ok.** Anyone may ask, and a driver's error names hosts. `checkHealth` round-trips to Postgres and logs the error with its cause, so monitoring that wants the reason reads the log.
267
- - `createStaticHandler` serves the built app: `/assets/` and `/_expo/` files are kept for a year, and one that is gone is a 404. Any other path that is not a file is `index.html`.
267
+ - `createStaticHandler` serves the built app: `/assets/` and `/_expo/` files are kept for a year (`HTTP_DEFAULTS.immutableCacheSeconds`, overridden as its second argument), and one that is gone is a 404. Any other path that is not a file is `index.html`.
268
268
  - **It answers every path**, so `/healthz`, `/mcp` and `mountAuthRedirects` are mounted before it.
269
269
 
270
270
  ## In a service