Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Resolve the database, public URL and auth secret without typed settings
Claudefa2cf9fa7e79
diff --git a/.env.example b/.env.exampleindex 3e16e31..66b9441 100644--- a/.env.example+++ b/.env.example@@ -1,12 +1,16 @@# Postgres. `npm run db:start` runs one locally with these credentials.DATABASE_URL=postgres://signudoc:[email protected]:5432/signudoc-# Public application URL used for absolute links, auth callbacks, and emails.+# Public URL of the app, used for links, auth callbacks, and emails.+# On Vercel, leave this unset: the project's own domain is used.APP_URL=http://localhost:3000-# Better Auth. Generate the secret with: openssl rand -hex 32-BETTER_AUTH_SECRET=replace-with-better-auth-secret-BETTER_AUTH_URL=http://localhost:3000+# Optional. BETTER_AUTH_URL defaults to APP_URL. BETTER_AUTH_SECRET defaults+# to a value derived from the database password; set your own (for example+# with `openssl rand -hex 32`) if you want sign-ins to survive a database+# password change.+# BETTER_AUTH_URL=http://localhost:3000+# BETTER_AUTH_SECRET=# Shared secret for the internal retention job route.RETENTION_JOB_SECRET=replace-with-internal-retention-job-secretdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 71e03ea..a6afdb1 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -14,7 +14,7 @@ permissions:jobs:check:- name: Typecheck, lint, build+ name: Typecheck, lint, unit tests, buildruns-on: ubuntu-lateststeps:- uses: actions/checkout@v6@@ -25,14 +25,11 @@ jobs:- run: npm ci- run: npm run typecheck- run: npm run lint- # The build prerenders the legal pages, which read these values. They- # are placeholders, not secrets.+ - run: npm test+ # The build prerenders the legal pages, which read the support address.- run: npm run buildenv:NEXT_TELEMETRY_DISABLED: "1"- APP_URL: https://ci.signudoc.example- BETTER_AUTH_URL: https://ci.signudoc.example- BETTER_AUTH_SECRET: ci-only-placeholder-secret-0123456789abcdefSUPPORT_EMAIL: [email protected]e2e:diff --git a/db/database-url.mjs b/db/database-url.mjsnew file mode 100644index 0000000..7a51f88--- /dev/null+++ b/db/database-url.mjs@@ -0,0 +1,157 @@+// Finds the Postgres connection string in the environment and prepares it for+// the pg driver. Plain JavaScript so that both the app and db/migrate.mjs+// (which runs before anything is compiled) share one implementation.++/**+ * Environment variables that can hold the connection string, as pairs of+ * [the URL the app uses, a direct URL for migrations when there is one].+ * The first pair with a URL wins, so a URL someone set by hand as+ * DATABASE_URL is never paired with an unrelated POSTGRES_URL_NON_POOLING.+ *+ * - DATABASE_URL / DATABASE_URL_UNPOOLED: set by hand, or by Neon through+ * the Vercel Marketplace.+ * - POSTGRES_URL / POSTGRES_URL_NON_POOLING: set by Supabase through the+ * Vercel Marketplace.+ */+const DATABASE_URL_PAIRS = [+ ["DATABASE_URL", "DATABASE_URL_UNPOOLED"],+ ["POSTGRES_URL", "POSTGRES_URL_NON_POOLING"],+];++export const DATABASE_URL_VARIABLES = DATABASE_URL_PAIRS.map(+ ([runtimeName]) => runtimeName,+);++/**+ * @param {Readonly<Record<string, string | undefined>>} env+ * @param {string} name+ * @returns {string | undefined}+ */+function readConfiguredValue(env, name) {+ const value = env[name]?.trim();++ if (!value || value.toLowerCase().startsWith("replace-with-")) {+ return undefined;+ }++ return value;+}++/**+ * The connection string the running app should use.+ *+ * @param {Readonly<Record<string, string | undefined>>} [env]+ * @returns {{ name: string, value: string } | null}+ */+export function resolveDatabaseUrl(env = process.env) {+ for (const [runtimeName] of DATABASE_URL_PAIRS) {+ const value = readConfiguredValue(env, runtimeName);++ if (value) {+ return { name: runtimeName, value };+ }+ }++ return null;+}++/**+ * The connection string migrations should use. A direct connection is+ * preferred because session-level advisory locks and DDL are not reliable+ * through a transaction-mode pooler.+ *+ * @param {Readonly<Record<string, string | undefined>>} [env]+ * @returns {{ name: string, value: string } | null}+ */+export function resolveMigrationDatabaseUrl(env = process.env) {+ for (const [runtimeName, directName] of DATABASE_URL_PAIRS) {+ const runtimeValue = readConfiguredValue(env, runtimeName);++ if (!runtimeValue) {+ continue;+ }++ const directValue = readConfiguredValue(env, directName);++ return directValue+ ? { name: directName, value: directValue }+ : { name: runtimeName, value: runtimeValue };+ }++ return null;+}++/**+ * @param {string} hostname+ * @returns {boolean}+ */+function isSupabaseHost(hostname) {+ return (+ hostname.endsWith(".supabase.com") || hostname.endsWith(".supabase.co")+ );+}++/**+ * Makes the TLS behaviour of a connection string explicit.+ *+ * pg currently treats sslmode=require, prefer and verify-ca as verify-full+ * and prints a warning that this will change in its next major version.+ *+ * - For most hosts (Neon included) the URL is rewritten to sslmode=verify-full,+ * which is what pg does today and keeps full certificate verification after+ * that change.+ * - Supabase serves a certificate from its own authority, which Node does not+ * trust by default, so verify-full fails there. For Supabase hosts the URL+ * gets libpq semantics instead, where sslmode=require means "encrypt, do+ * not verify", exactly as psql and Supabase's own documentation read it.+ *+ * A URL that already says uselibpqcompat, verify-full, no-verify or disable,+ * or has no sslmode at all, is returned unchanged.+ *+ * @param {string} connectionString+ * @returns {string}+ */+export function normalizeDatabaseUrl(connectionString) {+ /** @type {URL} */+ let url;++ try {+ url = new URL(connectionString);+ } catch {+ return connectionString;+ }++ const sslMode = url.searchParams.get("sslmode");++ if (+ url.searchParams.has("uselibpqcompat") ||+ (sslMode !== "require" && sslMode !== "prefer" && sslMode !== "verify-ca")+ ) {+ return connectionString;+ }++ if (isSupabaseHost(url.hostname)) {+ url.searchParams.set("uselibpqcompat", "true");+ url.searchParams.set("sslmode", "require");+ } else {+ url.searchParams.set("sslmode", "verify-full");+ }++ return url.toString();+}++/**+ * The password inside a connection string, or undefined if there is none.+ *+ * @param {string} connectionString+ * @returns {string | undefined}+ */+export function readDatabasePassword(connectionString) {+ try {+ const password = decodeURIComponent(new URL(connectionString).password);++ return password.length > 0 ? password : undefined;+ } catch {+ return undefined;+ }+}diff --git a/db/database-url.test.mjs b/db/database-url.test.mjsnew file mode 100644index 0000000..14f527c--- /dev/null+++ b/db/database-url.test.mjs@@ -0,0 +1,71 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import {+ normalizeDatabaseUrl,+ readDatabasePassword,+ resolveDatabaseUrl,+ resolveMigrationDatabaseUrl,+} from "./database-url.mjs";++test("migrations prefer the direct URL that belongs to the URL in use", () => {+ assert.deepEqual(+ resolveMigrationDatabaseUrl({+ DATABASE_URL: "postgres://a",+ DATABASE_URL_UNPOOLED: "postgres://a-direct",+ POSTGRES_URL_NON_POOLING: "postgres://unrelated",+ }),+ { name: "DATABASE_URL_UNPOOLED", value: "postgres://a-direct" },+ );+ assert.deepEqual(+ resolveMigrationDatabaseUrl({+ DATABASE_URL: "postgres://a",+ POSTGRES_URL_NON_POOLING: "postgres://unrelated",+ }),+ { name: "DATABASE_URL", value: "postgres://a" },+ );+ assert.deepEqual(+ resolveMigrationDatabaseUrl({+ POSTGRES_URL: "postgres://b",+ POSTGRES_URL_NON_POOLING: "postgres://b-direct",+ }),+ { name: "POSTGRES_URL_NON_POOLING", value: "postgres://b-direct" },+ );+ assert.equal(resolveMigrationDatabaseUrl({}), null);+});++test("an unpooled URL alone is not enough for the app", () => {+ assert.equal(+ resolveDatabaseUrl({ DATABASE_URL_UNPOOLED: "postgres://a-direct" }),+ null,+ );+});++test("TLS settings are made explicit", () => {+ assert.equal(+ normalizeDatabaseUrl("postgres://u:[email protected]/app?sslmode=require"),+ "postgres://u:[email protected]/app?sslmode=verify-full",+ );+ assert.equal(+ normalizeDatabaseUrl(+ "postgres://u:[email protected]:5432/postgres?sslmode=require",+ ),+ "postgres://u:[email protected]:5432/postgres?sslmode=require&uselibpqcompat=true",+ );++ for (const unchanged of [+ "postgres://u:[email protected]:5432/app",+ "postgres://u:[email protected]/app?sslmode=disable",+ "postgres://u:[email protected]/app?sslmode=no-verify",+ "postgres://u:[email protected]/app?sslmode=require&uselibpqcompat=true",+ "not a url",+ ]) {+ assert.equal(normalizeDatabaseUrl(unchanged), unchanged);+ }+});++test("the password is read decoded", () => {+ assert.equal(readDatabasePassword("postgres://u:p%40ss@h/db"), "p@ss");+ assert.equal(readDatabasePassword("postgres://u@h/db"), undefined);+ assert.equal(readDatabasePassword("nonsense"), undefined);+});diff --git a/db/migrate.mjs b/db/migrate.mjsindex ef04b5b..01bc1c5 100644--- a/db/migrate.mjs+++ b/db/migrate.mjs@@ -16,6 +16,12 @@ import { fileURLToPath, pathToFileURL } from "node:url";import pg from "pg";+import {+ DATABASE_URL_VARIABLES,+ normalizeDatabaseUrl,+ resolveMigrationDatabaseUrl,+} from "./database-url.mjs";+const DEFAULT_MIGRATIONS_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)),"migrations",@@ -24,37 +30,6 @@ const DEFAULT_MIGRATIONS_DIR = path.join(// Arbitrary constant shared by every migrator so two builds cannot run at once.const ADVISORY_LOCK_ID = 746108321;-// A direct connection is preferred: session-level advisory locks and DDL do-// not work reliably through a transaction-mode pooler.-const DATABASE_URL_VARIABLES = [- "DATABASE_URL_UNPOOLED",- "POSTGRES_URL_NON_POOLING",- "DATABASE_URL",- "POSTGRES_URL",-];--function readConfiguredValue(env, name) {- const value = env[name]?.trim();-- if (!value || value.toLowerCase().startsWith("replace-with-")) {- return undefined;- }-- return value;-}--export function resolveMigrationDatabaseUrl(env = process.env) {- for (const name of DATABASE_URL_VARIABLES) {- const value = readConfiguredValue(env, name);-- if (value) {- return { name, value };- }- }-- return null;-}-export async function listMigrationFiles(migrationsDir = DEFAULT_MIGRATIONS_DIR,) {@@ -70,7 +45,7 @@ export async function runMigrations({}) {const client = new pg.Client({application_name: "signudoc-migrate",- connectionString,+ connectionString: normalizeDatabaseUrl(connectionString),connectionTimeoutMillis: 15_000,});@@ -168,7 +143,7 @@ async function main() {if (optional) {console.warn(- `${message} Skipping; the app applies pending migrations on first use instead.`,+ `${message} Skipping. Run "npm run db:migrate" once a database is connected, or deploy again.`,);return;}diff --git a/package-lock.json b/package-lock.jsonindex aaa3f48..57d7b7c 100644--- a/package-lock.json+++ b/package-lock.json@@ -12,6 +12,7 @@"@aws-sdk/client-s3": "^3.1012.0","@aws-sdk/s3-request-presigner": "^3.1012.0","@pdf-lib/fontkit": "^1.1.1",+ "@vercel/functions": "^3.11.1","better-auth": "^1.7.21","class-variance-authority": "^0.7.1","clsx": "^2.1.1",@@ -4794,6 +4795,75 @@"win32"]},+ "node_modules/@vercel/cli-config": {+ "version": "0.3.8",+ "resolved": "https://registry.npmjs.org/@vercel/cli-config/-/cli-config-0.3.8.tgz",+ "integrity": "sha512-C6av1p4tN+rHIcD0rdlsx3y9SaosRUU67dbgrjbLG8KdAK8oNVzfKg0ckV+1qWh5VC/Ft1BN3Pg/PuXSKNFVOA==",+ "license": "Apache-2.0",+ "dependencies": {+ "xdg-app-paths": "5",+ "zod": "^4.6.6"+ }+ },+ "node_modules/@vercel/cli-exec": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@vercel/cli-exec/-/cli-exec-1.0.1.tgz",+ "integrity": "sha512-g9XerViJ/paZujufXYcu5XYI2vU2rtB4sgdpjUHde5RnOkdmpu0ngH46LCFGHoPXO/C+qDPSczIHIRN+8Q2YKQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "execa": "5.1.1"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/@vercel/functions": {+ "version": "3.11.1",+ "resolved": "https://registry.npmjs.org/@vercel/functions/-/functions-3.11.1.tgz",+ "integrity": "sha512-tZoePP4TRh25G5VNsWuLanANvfq0wdbvoUdabhoc8UT2QxIXj6mfoqXE4ycOm6CZyZuAN9dHqU51vuijPXjTcg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@vercel/oidc": "4.0.8"+ },+ "engines": {+ "node": ">= 20"+ },+ "peerDependencies": {+ "@aws-sdk/credential-provider-web-identity": "*",+ "ws": ">=8"+ },+ "peerDependenciesMeta": {+ "@aws-sdk/credential-provider-web-identity": {+ "optional": true+ },+ "ws": {+ "optional": true+ }+ }+ },+ "node_modules/@vercel/oidc": {+ "version": "4.0.8",+ "resolved": "https://registry.npmjs.org/@vercel/oidc/-/oidc-4.0.8.tgz",+ "integrity": "sha512-8wcmhuhrEsQlgTvPfRIeE4Y2geSaid0a1DP+um1PfNK4ETjqnfGTL5k5l7vS2T8A2gOx/MV7yNGxUJTs+0tqPQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@vercel/cli-config": "0.3.8",+ "@vercel/cli-exec": "1.0.1",+ "jose": "^5.9.6"+ },+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@vercel/oidc/node_modules/jose": {+ "version": "5.10.0",+ "resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz",+ "integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },"node_modules/acorn": {"version": "8.19.0","resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz",@@ -5458,7 +5528,6 @@"version": "7.0.6","resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz","integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",- "dev": true,"license": "MIT","dependencies": {"path-key": "^3.1.0",@@ -6308,6 +6377,29 @@"node": ">=0.10.0"}},+ "node_modules/execa": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz",+ "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==",+ "license": "MIT",+ "dependencies": {+ "cross-spawn": "^7.0.3",+ "get-stream": "^6.0.0",+ "human-signals": "^2.1.0",+ "is-stream": "^2.0.0",+ "merge-stream": "^2.0.0",+ "npm-run-path": "^4.0.1",+ "onetime": "^5.1.2",+ "signal-exit": "^3.0.3",+ "strip-final-newline": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/execa?sponsor=1"+ }+ },"node_modules/fast-deep-equal": {"version": "3.1.3","resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",@@ -6564,6 +6656,18 @@"node": ">= 0.4"}},+ "node_modules/get-stream": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",+ "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/get-symbol-description": {"version": "1.1.0","resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz",@@ -6769,6 +6873,15 @@"hermes-estree": "0.25.1"}},+ "node_modules/human-signals": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz",+ "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=10.17.0"+ }+ },"node_modules/ignore": {"version": "5.3.2","resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",@@ -7139,6 +7252,18 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/is-stream": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",+ "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/is-string": {"version": "1.1.1","resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz",@@ -7247,7 +7372,6 @@"version": "2.0.0","resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz","integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",- "dev": true,"license": "ISC"},"node_modules/iterator.prototype": {@@ -7781,6 +7905,12 @@"node": ">= 0.4"}},+ "node_modules/merge-stream": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",+ "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",+ "license": "MIT"+ },"node_modules/merge2": {"version": "1.4.1","resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",@@ -7805,6 +7935,15 @@"node": ">=8.6"}},+ "node_modules/mimic-fn": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",+ "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/minimatch": {"version": "3.1.5","resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",@@ -7980,6 +8119,18 @@"node": ">=18"}},+ "node_modules/npm-run-path": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz",+ "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },"node_modules/object-assign": {"version": "4.1.1","resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",@@ -8103,6 +8254,21 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/onetime": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",+ "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",+ "license": "MIT",+ "dependencies": {+ "mimic-fn": "^2.1.0"+ },+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/optionator": {"version": "0.9.4","resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",@@ -8121,6 +8287,15 @@"node": ">= 0.8.0"}},+ "node_modules/os-paths": {+ "version": "4.4.0",+ "resolved": "https://registry.npmjs.org/os-paths/-/os-paths-4.4.0.tgz",+ "integrity": "sha512-wrAwOeXp1RRMFfQY8Sy7VaGVmPocaLwSFOYCGKSyo8qmJ+/yaafCl5BCA1IQZWqFSRBrKDYFeR9d/VyQzfH/jg==",+ "license": "MIT",+ "engines": {+ "node": ">= 6.0"+ }+ },"node_modules/own-keys": {"version": "1.0.1","resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.1.tgz",@@ -8204,7 +8379,6 @@"version": "3.1.1","resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz","integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",- "dev": true,"license": "MIT","engines": {"node": ">=8"@@ -9051,7 +9225,6 @@"version": "2.0.0","resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz","integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",- "dev": true,"license": "MIT","dependencies": {"shebang-regex": "^3.0.0"@@ -9064,7 +9237,6 @@"version": "3.0.0","resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz","integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",- "dev": true,"license": "MIT","engines": {"node": ">=8"@@ -9146,6 +9318,12 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/signal-exit": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",+ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",+ "license": "ISC"+ },"node_modules/source-map-js": {"version": "1.2.2","resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",@@ -9318,6 +9496,15 @@"node": ">=4"}},+ "node_modules/strip-final-newline": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz",+ "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/strip-json-comments": {"version": "3.1.1","resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",@@ -9804,7 +9991,6 @@"version": "2.0.2","resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz","integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",- "dev": true,"license": "ISC","dependencies": {"isexe": "^2.0.0"@@ -9915,6 +10101,31 @@"node": ">=0.10.0"}},+ "node_modules/xdg-app-paths": {+ "version": "5.5.1",+ "resolved": "https://registry.npmjs.org/xdg-app-paths/-/xdg-app-paths-5.5.1.tgz",+ "integrity": "sha512-hI3flOB4PLZIy5prbtTpirobtPE2ZtZ52szO+2mM9Efp6ErM398La+C1lIpNWDfNoQk+6Lsi6nMcCwVB7pxeMQ==",+ "license": "MIT",+ "dependencies": {+ "os-paths": "^4.0.1",+ "xdg-portable": "^7.2.0"+ },+ "engines": {+ "node": ">= 6.0"+ }+ },+ "node_modules/xdg-portable": {+ "version": "7.3.0",+ "resolved": "https://registry.npmjs.org/xdg-portable/-/xdg-portable-7.3.0.tgz",+ "integrity": "sha512-sqMMuL1rc0FmMBOzCpd0yuy9trqF2yTTVe+E9ogwCSWQCdDEtQUwrZPT6AxqtsFGRNxycgncbP/xmOOSPw5ZUw==",+ "license": "MIT",+ "dependencies": {+ "os-paths": "^4.0.1"+ },+ "engines": {+ "node": ">= 6.0"+ }+ },"node_modules/xtend": {"version": "4.0.2","resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",diff --git a/package.json b/package.jsonindex 9b5b050..4741c98 100644--- a/package.json+++ b/package.json@@ -19,12 +19,14 @@"lint": "eslint .","format": "prettier --write .","format:check": "prettier --check .",+ "test": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON --test \"src/**/*.test.ts\" \"db/**/*.test.mjs\"","test:e2e": "playwright test"},"dependencies": {"@aws-sdk/client-s3": "^3.1012.0","@aws-sdk/s3-request-presigner": "^3.1012.0","@pdf-lib/fontkit": "^1.1.1",+ "@vercel/functions": "^3.11.1","better-auth": "^1.7.21","class-variance-authority": "^0.7.1","clsx": "^2.1.1",diff --git a/src/lib/auth/server.ts b/src/lib/auth/server.tsindex a60df61..c8b3a4e 100644--- a/src/lib/auth/server.ts+++ b/src/lib/auth/server.ts@@ -12,8 +12,12 @@ import {type TransactionalEmailMessage,} from "../services/email.ts";import { withUserEmailLegalFooter } from "../services/email-legal-footer.ts";-import { assertServiceConfig } from "../services/service-config.ts";-import { getEnv, type EnvSource } from "../utils/env.ts";+import { requireConfigValue } from "../services/service-config.ts";+import {+ getEnv,+ resolveDeploymentOrigins,+ type EnvSource,+} from "../utils/env.ts";type CreateAppAuthOptions = {database?: Pool;@@ -26,7 +30,6 @@ type AppAuth = ReturnType<typeof createAppAuth>;let cachedAuth: AppAuth | null = null;const LOOPBACK_HOST_ALIASES = ["127.0.0.1", "localhost"] as const;-const AUTH_ENV_KEYS = ["BETTER_AUTH_SECRET", "BETTER_AUTH_URL"] as const;function isLoopbackHost(hostname: string): boolean {return (@@ -124,16 +127,33 @@ function buildChangeEmailConfirmationMessage(input: {};}+// The email service is created when a message is sent, not when auth is set+// up. Email that is not configured yet then fails that one message (and is+// logged) instead of taking sign-in down with it.function sendAuthEmailInBackground(- emailService: EmailService,+ getEmailService: () => EmailService,message: TransactionalEmailMessage,) {- void emailService.send(message).catch((error) => {- console.error(- `Failed to send auth email "${message.template}" to ${message.to}:`,- error,- );- });+ void Promise.resolve()+ .then(() => getEmailService().send(message))+ .catch((error: unknown) => {+ console.error(+ `Failed to send auth email "${message.template}" to ${message.to}:`,+ error,+ );+ });+}++// In production, new passwords are checked against the Have I Been Pwned+// breach list, which needs outbound HTTPS to api.pwnedpasswords.com. If the+// check cannot be reached, sign-up fails rather than accepting the password.+// PASSWORD_BREACH_CHECK=off turns it off for networks without that access+// and for the end-to-end test.+function isPasswordBreachCheckEnabled(env: EnvSource): boolean {+ return (+ env.NODE_ENV === "production" &&+ env.PASSWORD_BREACH_CHECK?.trim().toLowerCase() !== "off"+ );}export function createAppAuth({@@ -141,13 +161,26 @@ export function createAppAuth({env = process.env,includeNextCookies = true,}: CreateAppAuthOptions = {}) {- assertServiceConfig("auth", AUTH_ENV_KEYS, env);-const appEnv = getEnv(env);const authEnv = appEnv.auth;- const emailService = createEmailService({ env });+ const secret = requireConfigValue(+ "auth",+ "BETTER_AUTH_SECRET",+ authEnv.betterAuthSecret,+ );+ const baseURL = requireConfigValue(+ "auth",+ "BETTER_AUTH_URL",+ authEnv.betterAuthUrl,+ );+ let cachedEmailService: EmailService | null = null;+ const emailService = () => {+ cachedEmailService ??= createEmailService({ env });++ return cachedEmailService;+ };const plugins = [- ...(env.NODE_ENV === "production"+ ...(isPasswordBreachCheckEnabled(env)? [haveIBeenPwned({customPasswordCompromisedMessage:@@ -157,21 +190,27 @@ export function createAppAuth({: []),...(includeNextCookies ? [nextCookies()] : []),];- const secret = authEnv.betterAuthSecret!;-return betterAuth({trustedOrigins: async () => {const trustedOrigins = new Set<string>();addTrustedOrigin(trustedOrigins, appEnv.appUrl);- addTrustedOrigin(trustedOrigins, authEnv.betterAuthUrl);+ addTrustedOrigin(trustedOrigins, baseURL);++ // On Vercel the same deployment also answers on its own vercel.app+ // URLs, which are the same app and so are trusted too.+ for (const origin of resolveDeploymentOrigins(env)) {+ addTrustedOrigin(trustedOrigins, origin);+ }return Array.from(trustedOrigins);},advanced: {- useSecureCookies: env.NODE_ENV === "production",+ // Secure cookies whenever the site is served over HTTPS, which is+ // always in production except for a build run on localhost.+ useSecureCookies: baseURL.startsWith("https://"),},- baseURL: authEnv.betterAuthUrl!,+ baseURL,database,emailVerification: {sendOnSignIn: true,diff --git a/src/lib/db/connection.ts b/src/lib/db/connection.tsindex fef7b96..ace5aff 100644--- a/src/lib/db/connection.ts+++ b/src/lib/db/connection.ts@@ -1,3 +1,4 @@+import { attachDatabasePool } from "@vercel/functions";import pg, {Pool,type PoolClient,@@ -6,9 +7,7 @@ import pg, {} from "pg";import { getEnv } from "../utils/env.ts";-import { assertServiceConfig } from "../services/service-config.ts";--const DATABASE_ENV_KEYS = ["DATABASE_URL"] as const;+import { requireConfigValue } from "../services/service-config.ts";declare global {var __signudocPgPool: Pool | undefined;@@ -33,13 +32,18 @@ export function getDb(): Pool {return cachedPool;}- assertServiceConfig("database", DATABASE_ENV_KEYS, process.env);-+ const isOnVercel = process.env.VERCEL === "1";const pool = new Pool({application_name: "signudoc",- connectionString: getEnv().databaseUrl!,+ connectionString: requireConfigValue(+ "database",+ "DATABASE_URL",+ getEnv().databaseUrl,+ ),connectionTimeoutMillis: 10_000,- idleTimeoutMillis: 30_000,+ // A Vercel function instance is suspended between requests, so idle+ // connections are released quickly there instead of being left to die.+ idleTimeoutMillis: isOnVercel ? 5_000 : 30_000,max: process.env.NODE_ENV === "production" ? 10 : 5,});@@ -47,6 +51,12 @@ export function getDb(): Pool {console.error("[db] Postgres pool error", error);});+ if (isOnVercel) {+ // Keeps the instance alive just long enough to close idle connections+ // before it is suspended, so they do not pile up on the database.+ attachDatabasePool(pool);+ }+if (process.env.NODE_ENV !== "production") {globalThis.__signudocPgPool = pool;}diff --git a/src/lib/services/downloads.ts b/src/lib/services/downloads.tsindex 83870d4..9d59516 100644--- a/src/lib/services/downloads.ts+++ b/src/lib/services/downloads.ts@@ -3,11 +3,9 @@ import {type DownloadFileType,} from "../types/domain.ts";import { getEnv, type EnvSource } from "../utils/env.ts";-import { assertServiceConfig } from "./service-config.ts";+import { requireConfigValue } from "./service-config.ts";import { issueOpaqueToken } from "./opaque-tokens.ts";-const DOWNLOAD_ENV_KEYS = ["APP_URL"] as const;-export type IssuedDownloadLink = {exp: number;fileType: DownloadFileType;@@ -29,12 +27,8 @@ type DownloadTokenConfig = {function getDownloadTokenConfig({env = process.env,}: DownloadTokenOptions = {}): DownloadTokenConfig {- assertServiceConfig("downloads", DOWNLOAD_ENV_KEYS, env);-- const appEnv = getEnv(env);-return {- appUrl: appEnv.appUrl!,+ appUrl: requireConfigValue("downloads", "APP_URL", getEnv(env).appUrl),defaultTtlSeconds: RECIPIENT_DOWNLOAD_LINK_TTL_SECONDS,};}diff --git a/src/lib/services/email-legal-footer.ts b/src/lib/services/email-legal-footer.tsindex 19b60de..43f798a 100644--- a/src/lib/services/email-legal-footer.ts+++ b/src/lib/services/email-legal-footer.ts@@ -1,9 +1,7 @@import { publicLegalLinks } from "../legal.ts";import { getEnv, type EnvSource } from "../utils/env.ts";import { escapeHtml } from "../utils/html.ts";-import { assertServiceConfig } from "./service-config.ts";--const APP_URL_ENV_KEYS = ["APP_URL"] as const;+import { requireConfigValue } from "./service-config.ts";type EmailBodyContent = {htmlBody: string;@@ -11,12 +9,11 @@ type EmailBodyContent = {};function getAbsoluteLegalLinks(env: EnvSource = process.env) {- assertServiceConfig("app", APP_URL_ENV_KEYS, env);- const { appUrl } = getEnv(env);+ const appUrl = requireConfigValue("app", "APP_URL", getEnv(env).appUrl);return publicLegalLinks.map((link) => ({...link,- url: new URL(link.href, appUrl!).toString(),+ url: new URL(link.href, appUrl).toString(),}));}diff --git a/src/lib/services/service-config.ts b/src/lib/services/service-config.tsindex f9a2fde..353991d 100644--- a/src/lib/services/service-config.ts+++ b/src/lib/services/service-config.ts@@ -35,3 +35,16 @@ export function assertServiceConfig(throw new ServiceConfigurationError(serviceName, missingVariables);}}++/** Returns a resolved setting, or fails naming the variable that would set it. */+export function requireConfigValue<T>(+ serviceName: string,+ variableName: string,+ value: T | undefined,+): T {+ if (value === undefined) {+ throw new ServiceConfigurationError(serviceName, [variableName]);+ }++ return value;+}diff --git a/src/lib/services/signing-links.ts b/src/lib/services/signing-links.tsindex b605c54..669511e 100644--- a/src/lib/services/signing-links.ts+++ b/src/lib/services/signing-links.ts@@ -1,10 +1,8 @@import { SIGNING_LINK_TTL_SECONDS } from "../types/domain.ts";import { getEnv, type EnvSource } from "../utils/env.ts";-import { assertServiceConfig } from "./service-config.ts";+import { requireConfigValue } from "./service-config.ts";import { issueOpaqueToken } from "./opaque-tokens.ts";-const SIGNING_LINK_ENV_KEYS = ["APP_URL"] as const;-export type IssuedSigningLink = {exp: number;iat: number;@@ -25,12 +23,8 @@ type SigningLinkConfig = {function getSigningLinkConfig({env = process.env,}: SigningLinkOptions = {}): SigningLinkConfig {- assertServiceConfig("signing links", SIGNING_LINK_ENV_KEYS, env);-- const appEnv = getEnv(env);-return {- appUrl: appEnv.appUrl!,+ appUrl: requireConfigValue("signing links", "APP_URL", getEnv(env).appUrl),defaultTtlSeconds: SIGNING_LINK_TTL_SECONDS,};}diff --git a/src/lib/signing.ts b/src/lib/signing.tsindex 3d36ea4..b52820b 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -57,13 +57,11 @@ import {createStorageService,type StorageService,} from "./services/storage.ts";-import { assertServiceConfig } from "./services/service-config.ts";+import { requireConfigValue } from "./services/service-config.ts";import { RECIPIENT_DOWNLOAD_LINK_TTL_SECONDS } from "./types/domain.ts";import { getEnv } from "./utils/env.ts";import { escapeHtml } from "./utils/html.ts";-const APP_URL_ENV_KEYS = ["APP_URL"] as const;-type SigningRequestMeta = {ipAddress?: string | null;userAgent?: string | null;@@ -234,9 +232,9 @@ function normalizeSenderName(sender: SenderRow): string {}function getEnvelopeUrl(envelopeId: string): string {- assertServiceConfig("app", APP_URL_ENV_KEYS, process.env);+ const appUrl = requireConfigValue("app", "APP_URL", getEnv().appUrl);- return new URL(`/envelopes/${envelopeId}`, getEnv().appUrl!).toString();+ return new URL(`/envelopes/${envelopeId}`, appUrl).toString();}const RECIPIENT_DOWNLOAD_LINK_TTL_DAYS =diff --git a/src/lib/utils/env.test.ts b/src/lib/utils/env.test.tsnew file mode 100644index 0000000..1a55627--- /dev/null+++ b/src/lib/utils/env.test.ts@@ -0,0 +1,148 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import {+ getEnv,+ isLocalDeployment,+ resolveAppUrl,+ resolveAuthSecret,+ resolveAuthUrl,+ resolveDatabaseUrl,+ resolveDeploymentOrigins,+} from "./env.ts";++const NEON_URL =+ "postgres://app:[email protected]/neondb?sslmode=require";++const vercelProduction = {+ NODE_ENV: "production",+ VERCEL: "1",+ VERCEL_BRANCH_URL: "signudoc-git-main-acme.vercel.app",+ VERCEL_ENV: "production",+ VERCEL_PROJECT_PRODUCTION_URL: "sign.acme.com",+ VERCEL_URL: "signudoc-abc123-acme.vercel.app",+};++test("a fresh Vercel install resolves everything from what Vercel provides", () => {+ const env = getEnv({ ...vercelProduction, DATABASE_URL: NEON_URL });++ assert.equal(env.appUrl, "https://sign.acme.com");+ assert.equal(env.auth.betterAuthUrl, "https://sign.acme.com");+ assert.match(env.auth.betterAuthSecret ?? "", /^[0-9a-f]{64}$/);+ assert.match(env.databaseUrl ?? "", /sslmode=verify-full/);+});++test("a preview deployment uses its own branch URL", () => {+ const env = { ...vercelProduction, VERCEL_ENV: "preview" };++ assert.equal(resolveAppUrl(env), "https://signudoc-git-main-acme.vercel.app");+ assert.deepEqual(resolveDeploymentOrigins(env), [+ "https://signudoc-abc123-acme.vercel.app",+ "https://signudoc-git-main-acme.vercel.app",+ "https://sign.acme.com",+ ]);+});++test("explicit settings win over the Vercel defaults", () => {+ const env = {+ ...vercelProduction,+ APP_URL: "https://docs.example.org",+ BETTER_AUTH_SECRET: "x".repeat(40),+ BETTER_AUTH_URL: "https://auth.example.org",+ DATABASE_URL: NEON_URL,+ };++ assert.equal(resolveAppUrl(env), "https://docs.example.org");+ assert.equal(resolveAuthUrl(env), "https://auth.example.org");+ assert.equal(resolveAuthSecret(env), "x".repeat(40));+});++test("placeholders from .env.example count as not set", () => {+ const env = {+ APP_URL: "replace-with-app-url",+ BETTER_AUTH_SECRET: "replace-with-better-auth-secret",+ DATABASE_URL: "replace-with-database-url",+ };++ assert.equal(resolveAppUrl(env), undefined);+ assert.equal(resolveAuthSecret(env), undefined);+ assert.equal(resolveDatabaseUrl(env), undefined);+});++test("the derived secret is stable and follows the database password", () => {+ const first = resolveAuthSecret({ DATABASE_URL: NEON_URL });+ const again = resolveAuthSecret({ DATABASE_URL: NEON_URL });+ const otherPassword = resolveAuthSecret({+ DATABASE_URL: NEON_URL.replace(+ "npg_Abc123Def456Ghi7",+ "npg_Zyx987Wvu654Tsr3",+ ),+ });+ const samePasswordOtherHost = resolveAuthSecret({+ POSTGRES_URL: NEON_URL.replace("ep-cool-1", "ep-cool-1-pooler"),+ });++ assert.equal(first, again);+ assert.notEqual(first, otherPassword);+ assert.equal(first, samePasswordOtherHost);+});++test("a weak database password is not used to derive a production secret", () => {+ const weak = "postgres://signudoc:[email protected]:5432/signudoc";++ assert.equal(+ resolveAuthSecret({ DATABASE_URL: weak, NODE_ENV: "production" }),+ undefined,+ );+ assert.match(+ resolveAuthSecret({ DATABASE_URL: weak, NODE_ENV: "development" }) ?? "",+ /^[0-9a-f]{64}$/,+ );+});++test("production rejects a short secret and a plain HTTP public URL", () => {+ assert.throws(+ () =>+ resolveAuthSecret({+ BETTER_AUTH_SECRET: "short",+ NODE_ENV: "production",+ }),+ /at least 32 characters/,+ );+ assert.throws(+ () =>+ resolveAppUrl({+ APP_URL: "http://docs.example.org",+ NODE_ENV: "production",+ }),+ /must use HTTPS/,+ );+});++test("a production build may run on localhost, but not on Vercel", () => {+ const local = { APP_URL: "http://localhost:3000", NODE_ENV: "production" };++ assert.equal(resolveAppUrl(local), "http://localhost:3000");+ assert.equal(isLocalDeployment(local), true);+ assert.equal(+ isLocalDeployment({ ...local, APP_URL: "https://docs.example.org" }),+ false,+ );+ assert.throws(+ () => resolveAppUrl({ ...local, VERCEL: "1" }),+ /must not use localhost on Vercel/,+ );+});++test("Supabase's POSTGRES_URL is used when DATABASE_URL is not set", () => {+ const supabase =+ "postgres://postgres.ref:[email protected]:6543/postgres?sslmode=require&supa=base-pooler.x";+ const resolved = resolveDatabaseUrl({ POSTGRES_URL: supabase });++ assert.match(resolved ?? "", /uselibpqcompat=true/);+ assert.match(resolved ?? "", /sslmode=require/);+ assert.equal(+ resolveDatabaseUrl({ DATABASE_URL: NEON_URL, POSTGRES_URL: supabase }),+ NEON_URL.replace("sslmode=require", "sslmode=verify-full"),+ );+});diff --git a/src/lib/utils/env.ts b/src/lib/utils/env.tsindex b593dd5..1eaacbc 100644--- a/src/lib/utils/env.ts+++ b/src/lib/utils/env.ts@@ -1,3 +1,11 @@+import { createHmac } from "node:crypto";++import {+ normalizeDatabaseUrl,+ readDatabasePassword,+ resolveDatabaseUrl as findDatabaseUrl,+} from "../../../db/database-url.mjs";+export type EnvSource = Readonly<Record<string, string | undefined>>;export class MissingEnvError extends Error {@@ -7,6 +15,9 @@ export class MissingEnvError extends Error {}}+const PLACEHOLDER_PREFIX = "replace-with-";++// Values copied from .env.example and never filled in count as not set.function readEnv(env: EnvSource, variableName: string): string | undefined {const value = env[variableName];@@ -16,29 +27,44 @@ function readEnv(env: EnvSource, variableName: string): string | undefined {const trimmedValue = value.trim();- return trimmedValue.length > 0 ? trimmedValue : undefined;+ if (+ trimmedValue.length === 0 ||+ trimmedValue.toLowerCase().startsWith(PLACEHOLDER_PREFIX)+ ) {+ return undefined;+ }++ return trimmedValue;}-function isLocalhostUrl(value: string): boolean {- try {- const parsedUrl = new URL(value);+function isProduction(env: EnvSource): boolean {+ return env.NODE_ENV === "production";+}- return (- parsedUrl.hostname === "localhost" ||- parsedUrl.hostname === "127.0.0.1" ||- parsedUrl.hostname === "::1"- );- } catch {- return false;- }+function isOnVercel(env: EnvSource): boolean {+ return readEnv(env, "VERCEL") === "1";}-function assertProductionHttpsUrl(+function isLoopbackHostname(hostname: string): boolean {+ return (+ hostname === "localhost" ||+ hostname === "127.0.0.1" ||+ hostname === "::1" ||+ hostname === "[::1]"+ );+}++// An explicitly configured public URL has to be HTTPS in production. The one+// exception is a loopback address, so a production build can be run and+// tested on the machine it was built on. That exception does not apply on+// Vercel, where a localhost URL can only be a mistake.+function validatePublicUrl(variableName: string,- value: string | undefined,-) {- if (!value) {- throw new MissingEnvError(variableName);+ value: string,+ env: EnvSource,+): string {+ if (!isProduction(env)) {+ return value;}let parsedUrl: URL;@@ -51,42 +77,164 @@ function assertProductionHttpsUrl();}+ if (isLoopbackHostname(parsedUrl.hostname)) {+ if (isOnVercel(env)) {+ throw new Error(`${variableName} must not use localhost on Vercel.`);+ }++ return value;+ }+if (parsedUrl.protocol !== "https:") {throw new Error(`${variableName} must use HTTPS in production.`);}- if (isLocalhostUrl(value)) {- throw new Error(`${variableName} must not use localhost in production.`);+ return value;+}++// On Vercel the public URL is known without anyone typing it in.+// Production uses the project's production domain (the shortest custom+// domain, or the vercel.app one). A preview uses its own branch URL, so its+// links and auth callbacks stay on the preview.+function resolveVercelUrl(env: EnvSource): string | undefined {+ if (!isOnVercel(env)) {+ return undefined;+ }++ const vercelEnv = readEnv(env, "VERCEL_ENV");+ let host: string | undefined;++ if (vercelEnv === "production") {+ host =+ readEnv(env, "VERCEL_PROJECT_PRODUCTION_URL") ??+ readEnv(env, "VERCEL_URL");+ } else if (vercelEnv === "preview") {+ host = readEnv(env, "VERCEL_BRANCH_URL") ?? readEnv(env, "VERCEL_URL");}++ return host ? `https://${host}` : undefined;}-function assertStrongSecret(- variableName: string,- value: string | undefined,- minimumLength = 32,-) {- if (!value) {- throw new MissingEnvError(variableName);+/** Other URLs this deployment answers on, such as its unique vercel.app URL. */+export function resolveDeploymentOrigins(+ env: EnvSource = process.env,+): string[] {+ if (!isOnVercel(env)) {+ return [];}- if (value.length < minimumLength) {- throw new Error(- `${variableName} must be at least ${String(minimumLength)} characters in production.`,- );+ return ["VERCEL_URL", "VERCEL_BRANCH_URL", "VERCEL_PROJECT_PRODUCTION_URL"]+ .map((variableName) => readEnv(env, variableName))+ .filter((host) => host !== undefined)+ .map((host) => `https://${host}`);+}++export function resolveAppUrl(+ env: EnvSource = process.env,+): string | undefined {+ const configuredUrl = readEnv(env, "APP_URL");++ if (configuredUrl) {+ return validatePublicUrl("APP_URL", configuredUrl, env);}++ return resolveVercelUrl(env);}-function assertProductionEnv(- appEnv: ReturnType<typeof getEnv>,- env: EnvSource,-) {- if (env.NODE_ENV !== "production") {- return;+/**+ * True when the app is served from this machine (localhost), which is how a+ * production build is run for local testing and the end-to-end test.+ */+export function isLocalDeployment(env: EnvSource = process.env): boolean {+ const appUrl = resolveAppUrl(env);++ if (!appUrl || isOnVercel(env)) {+ return false;+ }++ try {+ return isLoopbackHostname(new URL(appUrl).hostname);+ } catch {+ return false;+ }+}++export function resolveAuthUrl(+ env: EnvSource = process.env,+): string | undefined {+ const configuredUrl = readEnv(env, "BETTER_AUTH_URL");++ if (configuredUrl) {+ return validatePublicUrl("BETTER_AUTH_URL", configuredUrl, env);+ }++ return resolveAppUrl(env);+}++export function resolveDatabaseUrl(+ env: EnvSource = process.env,+): string | undefined {+ const databaseUrl = findDatabaseUrl(env);++ return databaseUrl ? normalizeDatabaseUrl(databaseUrl.value) : undefined;+}++const MINIMUM_SECRET_LENGTH = 32;+const MINIMUM_PASSWORD_LENGTH_FOR_DERIVED_SECRET = 12;+const DERIVED_SECRET_CONTEXT = "signudoc/better-auth-secret/v1";++let lastDerivedSecret: { password: string; secret: string } | null = null;++// When BETTER_AUTH_SECRET is not set, the auth secret is derived from the+// database password, so a fresh install needs nothing typed in. Anyone who+// holds the database password can already read and write every session, so+// this gives them nothing new. Changing the database password signs+// everyone out; set BETTER_AUTH_SECRET to avoid that.+function deriveAuthSecret(env: EnvSource): string | undefined {+ const databaseUrl = findDatabaseUrl(env);+ const password = databaseUrl+ ? readDatabasePassword(databaseUrl.value)+ : undefined;++ if (!password) {+ return undefined;+ }++ if (+ isProduction(env) &&+ password.length < MINIMUM_PASSWORD_LENGTH_FOR_DERIVED_SECRET+ ) {+ return undefined;}- assertProductionHttpsUrl("APP_URL", appEnv.appUrl);- assertProductionHttpsUrl("BETTER_AUTH_URL", appEnv.auth.betterAuthUrl);- assertStrongSecret("BETTER_AUTH_SECRET", appEnv.auth.betterAuthSecret);+ if (lastDerivedSecret?.password !== password) {+ lastDerivedSecret = {+ password,+ secret: createHmac("sha256", password)+ .update(DERIVED_SECRET_CONTEXT)+ .digest("hex"),+ };+ }++ return lastDerivedSecret.secret;+}++export function resolveAuthSecret(+ env: EnvSource = process.env,+): string | undefined {+ const configuredSecret = readEnv(env, "BETTER_AUTH_SECRET");++ if (!configuredSecret) {+ return deriveAuthSecret(env);+ }++ if (isProduction(env) && configuredSecret.length < MINIMUM_SECRET_LENGTH) {+ throw new Error(+ `BETTER_AUTH_SECRET must be at least ${String(MINIMUM_SECRET_LENGTH)} characters in production.`,+ );+ }++ return configuredSecret;}export function hasEnv(@@ -96,13 +244,16 @@ export function hasEnv(return readEnv(env, variableName) !== undefined;}+// Every value is optional here. Code that needs one checks it at the point of+// use (see requireConfigValue), so a missing email setting cannot stop a page+// that never sends email from rendering.export function getEnv(env: EnvSource = process.env) {- const appEnv = {- databaseUrl: readEnv(env, "DATABASE_URL"),- appUrl: readEnv(env, "APP_URL"),+ return {+ databaseUrl: resolveDatabaseUrl(env),+ appUrl: resolveAppUrl(env),auth: {- betterAuthSecret: readEnv(env, "BETTER_AUTH_SECRET"),- betterAuthUrl: readEnv(env, "BETTER_AUTH_URL"),+ betterAuthSecret: resolveAuthSecret(env),+ betterAuthUrl: resolveAuthUrl(env),},email: {apiKey: readEnv(env, "RESEND_API_KEY"),@@ -119,10 +270,6 @@ export function getEnv(env: EnvSource = process.env) {secretAccessKey: readEnv(env, "R2_SECRET_ACCESS_KEY"),},};-- assertProductionEnv(appEnv, env);-- return appEnv;}export type AppEnv = ReturnType<typeof getEnv>;diff --git a/proxy.ts b/src/proxy.tssimilarity index 100%rename from proxy.tsrename to src/proxy.ts