feat(auth): groundwork for signing in with Google (#340)
Nothing a customer can see. The schema change and the configuration land on their own so the widest-reaching edit in the project can be reviewed for what it is rather than buried inside a feature. The password hash becomes nullable. That is one line and it is not the work; the work is that every read of the column is now a question rather than a fact. Three places compared against it with bcrypt, and all three now ask first through one shared function. That function exists because the alternative is worse than a wrong answer. bcrypt.compare throws on a null hash rather than returning false, so any call site that forgot the check would answer a sign-in attempt with a 500 instead of a refusal. On the login route that is also an oracle, because it would happen for exactly the accounts that have no password. One function rather than a null check repeated three times means the question is asked identically everywhere and a fourth site cannot forget to ask it. Nothing writes a null yet. The first accounts without a password arrive with the sign-up path, which is why this is landed ahead of them. The identities table is a table rather than columns on customers, because one customer may eventually hold more than one. Columns would make a second provider a migration and a third an embarrassment. Its important column is the provider subject, and the comment on it is the whole security posture of the feature in one place: never the email. An email is a display value its owner can change and a provider may reassign; a subject is opaque and stable for the life of the account. Matching on the email would strand a customer who changed theirs and, far worse, hand their account to whoever inherited the old address. Unique across the provider and subject together, not the subject alone. The down migration drops the table and deliberately does not restore the NOT NULL. Re-adding it fails outright once a passwordless customer exists, and a down migration that destroys accounts to satisfy a constraint is far worse than a column that is merely more permissive than it needs to be. The redirect URI is derived from PUBLIC_URL, the same single source the WebAuthn Relying Party ID uses and for the same reason: Google compares it as an exact string and answers a mismatch with a message that says nothing about which half is wrong. Deriving it means the value is correct by construction anywhere the email links already are. The tests are mostly about what must not end up in it, since a trailing slash on PUBLIC_URL is an easy way to produce a URI that is one character from the registered one. The config also reports whether it is enabled at all, so a developer without credentials gets a storefront that works and simply does not offer the button, rather than one that offers it and fails. Absent rather than disabled, the same choice made for a browser without WebAuthn. Environment validation refuses to boot on one credential without the other, matching how the SMTP pair is handled. Half-configured is the case worth catching because the failure otherwise arrives at the moment a customer presses the button. The QA compose file sets both to empty, and the comment there says why at length rather than leaving it to look like an oversight. Google refuses a redirect URI whose host is not under a domain whose ownership has been proved by DNS, and nobody can prove ownership of anything under bermudalamb.synology.me because Synology owns the registrable domain above it. That is the same wall #285 hit with Cloudflare. So QA cannot run this at all until #313 moves it to a subdomain of the real domain, at which point it is two stack variables and one console entry, with no code change either way. Also corrects the record in #332, which lists account deletion as confirming with a password. It does not; the route takes none and the confirmation is a modal in the account page. Deletion needed no change here. Verified: backend tsc clean for src and tests, 550 unit tests pass including new coverage of the config derivation, the null-hash comparison and the environment rules; lint clean apart from warnings that predate this branch. The integration suite needs a database this machine has no Docker for. Closes #340 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
d69091d5ad
commit
9cc82002b8
@@ -102,7 +102,7 @@ export interface Customers {
|
||||
marketing_consent: Generated<boolean>;
|
||||
marketing_consent_at: Timestamp | null;
|
||||
marketing_consent_text: string | null;
|
||||
password_hash: string;
|
||||
password_hash: string | null;
|
||||
unsubscribe_token: string;
|
||||
}
|
||||
|
||||
@@ -115,6 +115,15 @@ export interface CustomerEmailChanges {
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export interface CustomerIdentities {
|
||||
created_at: Generated<Timestamp>;
|
||||
customer_id: number;
|
||||
id: Generated<number>;
|
||||
last_used_at: Timestamp | null;
|
||||
provider: string;
|
||||
provider_sub: string;
|
||||
}
|
||||
|
||||
export interface CustomerSessions {
|
||||
created_at: Generated<Timestamp>;
|
||||
customer_id: number;
|
||||
@@ -251,6 +260,7 @@ export interface DB {
|
||||
checkouts: Checkouts;
|
||||
customer_credentials: CustomerCredentials;
|
||||
customer_email_changes: CustomerEmailChanges;
|
||||
customer_identities: CustomerIdentities;
|
||||
customer_sessions: CustomerSessions;
|
||||
customer_tokens: CustomerTokens;
|
||||
customers: Customers;
|
||||
|
||||
@@ -152,6 +152,57 @@ function checkMail(env: NodeJS.ProcessEnv): EnvValidation {
|
||||
return { errors, warnings };
|
||||
}
|
||||
|
||||
/**
|
||||
* Google sign-in is all or nothing (#340).
|
||||
*
|
||||
* Half-configured is the case worth naming. With neither value set the feature
|
||||
* reports itself disabled and the button never appears, which is a legitimate
|
||||
* environment. With one set, the token exchange fails at the moment a customer
|
||||
* presses the button — the worst possible time to discover a typo in a stack
|
||||
* variable.
|
||||
*
|
||||
* An error rather than a warning, matching the SMTP pair above: both refuse to
|
||||
* start rather than serving something that is visibly offered and cannot work.
|
||||
*/
|
||||
function checkGoogleSignIn(env: NodeJS.ProcessEnv): EnvValidation {
|
||||
const hasId = isPresent(env, 'GOOGLE_CLIENT_ID');
|
||||
const hasSecret = isPresent(env, 'GOOGLE_CLIENT_SECRET');
|
||||
|
||||
if (hasId && !hasSecret) {
|
||||
return {
|
||||
errors: ['GOOGLE_CLIENT_SECRET is required when GOOGLE_CLIENT_ID is set — set both or neither.'],
|
||||
warnings: []
|
||||
};
|
||||
}
|
||||
if (hasSecret && !hasId) {
|
||||
return {
|
||||
errors: ['GOOGLE_CLIENT_ID is required when GOOGLE_CLIENT_SECRET is set — set both or neither.'],
|
||||
warnings: []
|
||||
};
|
||||
}
|
||||
if (!hasId) {
|
||||
return {
|
||||
errors: [],
|
||||
warnings: ['Google sign-in is not configured — the button will not be offered.']
|
||||
};
|
||||
}
|
||||
|
||||
// Only meaningful once the credentials exist, and only a warning: a
|
||||
// deployment with no PUBLIC_URL falls back to localhost, which is right for
|
||||
// local development and wrong everywhere else in a way worth saying out loud.
|
||||
if (!isPresent(env, 'PUBLIC_URL')) {
|
||||
return {
|
||||
errors: [],
|
||||
warnings: [
|
||||
'Google sign-in is configured but PUBLIC_URL is not, so the redirect URI falls back to ' +
|
||||
'localhost. Correct locally; anywhere else, Google will refuse the callback.'
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
return { errors: [], warnings: [] };
|
||||
}
|
||||
|
||||
function checkAdminGate(env: NodeJS.ProcessEnv): string[] {
|
||||
if (isPresent(env, 'ADMIN_GATE_SECRET')) {
|
||||
return [];
|
||||
@@ -227,6 +278,7 @@ function checkUploadsOrigin(env: NodeJS.ProcessEnv): EnvValidation {
|
||||
export function validateEnv(env: NodeJS.ProcessEnv): EnvValidation {
|
||||
const mail = checkMail(env);
|
||||
const uploads = checkUploadsOrigin(env);
|
||||
const google = checkGoogleSignIn(env);
|
||||
|
||||
return {
|
||||
errors: [
|
||||
@@ -234,8 +286,16 @@ export function validateEnv(env: NodeJS.ProcessEnv): EnvValidation {
|
||||
...checkDemoMode(env),
|
||||
...checkPayPal(env),
|
||||
...mail.errors,
|
||||
...uploads.errors
|
||||
...uploads.errors,
|
||||
...google.errors
|
||||
],
|
||||
warnings: [...mail.warnings, ...checkAdminGate(env), ...uploads.warnings, ...checkDraftingKey(env), ...checkIntakeActionSecret(env)]
|
||||
warnings: [
|
||||
...mail.warnings,
|
||||
...checkAdminGate(env),
|
||||
...uploads.warnings,
|
||||
...checkDraftingKey(env),
|
||||
...checkIntakeActionSecret(env),
|
||||
...google.warnings
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Who this application is, as far as Google is concerned (#340).
|
||||
*
|
||||
* ## Why the redirect URI is derived rather than written down
|
||||
*
|
||||
* It is registered in two places that must agree exactly: Google's console, and
|
||||
* every authorization request this server sends. Google compares them as
|
||||
* strings — scheme, host, port, path, trailing slash and case all count — and
|
||||
* answers a mismatch with `redirect_uri_mismatch`, which is accurate and tells
|
||||
* you nothing about which half is wrong.
|
||||
*
|
||||
* So it comes from `PUBLIC_URL`, the same value every customer-facing link is
|
||||
* already built from, exactly as the WebAuthn Relying Party ID does (#37). One
|
||||
* source, and it is the one that is already correct in any environment where
|
||||
* mail works.
|
||||
*
|
||||
* ## The consequence worth stating plainly
|
||||
*
|
||||
* Google refuses a redirect URI whose host is not under an **authorized
|
||||
* domain**, and a domain can only be authorized after ownership has been proved
|
||||
* by DNS in Search Console. `localhost` is the sole exemption.
|
||||
*
|
||||
* `qa-redefined-designs.bermudalamb.synology.me` therefore **cannot ever be
|
||||
* used**: Synology owns the registrable domain above it, so there is no record
|
||||
* to add and nothing to prove. This is the same wall #285 hit with Cloudflare.
|
||||
*
|
||||
* | Environment | Redirect URI | Works |
|
||||
* | --- | --- | --- |
|
||||
* | Local | `http://localhost:3000/...` | Yes, by exemption |
|
||||
* | QA on the Synology host | — | **No, and cannot** |
|
||||
* | QA on `qa.redefined-designs.com` | `https://qa.redefined-designs.com/...` | After #313 |
|
||||
* | Production | `https://redefined-designs.com/...` | After #313 |
|
||||
*
|
||||
* So this feature is built and exercised locally, and QA cannot see it until QA
|
||||
* moves onto a subdomain of the real domain. That is a `PUBLIC_URL` change and
|
||||
* one console entry, not a code change — this module follows `PUBLIC_URL`
|
||||
* wherever it points. See #345.
|
||||
*/
|
||||
|
||||
/** The callback path. One constant, because it appears in two sentences. */
|
||||
export const GOOGLE_CALLBACK_PATH = '/api/auth/google/callback';
|
||||
|
||||
/**
|
||||
* Local development, where `PUBLIC_URL` is legitimately unset.
|
||||
*
|
||||
* `envValidation` requires `PUBLIC_URL` only when SMTP is configured, so a local
|
||||
* setup that cannot send mail does not have it. Falling back to the backend's
|
||||
* own port rather than refusing keeps that setup working, and `localhost` is
|
||||
* the one host Google will accept without an authorized domain — so the fallback
|
||||
* is also the only value that could possibly work here.
|
||||
*/
|
||||
const LOCAL_ORIGIN = 'http://localhost:3000';
|
||||
|
||||
export interface GoogleConfig {
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
/** Absolute, and byte-identical to what is registered in Google's console. */
|
||||
redirectUri: string;
|
||||
/**
|
||||
* Whether to offer Google sign-in at all.
|
||||
*
|
||||
* False when either credential is missing, and the button is then **absent
|
||||
* rather than disabled** — the same choice #41 made for a browser without
|
||||
* WebAuthn. A developer without credentials gets a storefront that works and
|
||||
* simply does not offer the option, rather than one that offers it and fails.
|
||||
*/
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Google configuration for this environment.
|
||||
*
|
||||
* Takes the environment as an argument so it can be tested without touching
|
||||
* `process.env`, and reads it on each call rather than at import time: the
|
||||
* module would otherwise capture whatever was set when it was first required,
|
||||
* which in tests is whatever the previous suite happened to leave behind.
|
||||
*
|
||||
* Throws on a `PUBLIC_URL` that is set but unparseable, for the reason
|
||||
* `relyingParty` does: that is a deployment already producing broken links in
|
||||
* every email, so failing here is not the first thing to go wrong — it is the
|
||||
* first thing to say so.
|
||||
*/
|
||||
export function googleConfig(env: NodeJS.ProcessEnv = process.env): GoogleConfig {
|
||||
const clientId = (env.GOOGLE_CLIENT_ID ?? '').trim();
|
||||
const clientSecret = (env.GOOGLE_CLIENT_SECRET ?? '').trim();
|
||||
const publicUrl = (env.PUBLIC_URL ?? '').trim();
|
||||
|
||||
let base = LOCAL_ORIGIN;
|
||||
if (publicUrl !== '') {
|
||||
try {
|
||||
// `origin` normalises away any path, trailing slash or default port,
|
||||
// which is what makes the result stable regardless of how PUBLIC_URL was
|
||||
// written. A trailing slash there would otherwise produce a double slash
|
||||
// here and a mismatch at Google.
|
||||
base = new URL(publicUrl).origin;
|
||||
} catch {
|
||||
throw new Error(
|
||||
`PUBLIC_URL is not a URL (${publicUrl}), so the Google redirect URI cannot be derived ` +
|
||||
'from it. Google compares that value as an exact string, so this is refused rather ' +
|
||||
'than guessed at.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
clientId,
|
||||
clientSecret,
|
||||
redirectUri: `${base}${GOOGLE_CALLBACK_PATH}`,
|
||||
// Both, or neither. One without the other cannot complete a token exchange,
|
||||
// and offering a button that always fails is worse than offering none.
|
||||
enabled: clientId !== '' && clientSecret !== ''
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import bcrypt from 'bcryptjs';
|
||||
|
||||
/**
|
||||
* How expensive a password hash is, and why that differs under test.
|
||||
*
|
||||
@@ -47,3 +49,30 @@ export function hashRoundsFor(nodeEnv: string | undefined): number {
|
||||
|
||||
/** Resolved once at import: NODE_ENV does not change while the process runs. */
|
||||
export const PASSWORD_HASH_ROUNDS = hashRoundsFor(process.env.NODE_ENV);
|
||||
|
||||
/**
|
||||
* Whether a supplied password matches a stored hash that may not exist (#340).
|
||||
*
|
||||
* `customers.password_hash` became nullable when social sign-in arrived, and a
|
||||
* null one is not an edge case to tidy away — it is a customer who signed up
|
||||
* through Google and has never set a password. There is nothing to compare
|
||||
* against, so the answer is no.
|
||||
*
|
||||
* This exists because the alternative is worse than a wrong answer.
|
||||
* `bcrypt.compare` throws `Illegal arguments` on a null hash rather than
|
||||
* returning false, so every call site that forgot the check would answer a
|
||||
* sign-in attempt with a 500 instead of a refusal — and a 500 on the login route
|
||||
* is also an oracle, since it happens for exactly the accounts that have no
|
||||
* password.
|
||||
*
|
||||
* One function rather than a null check repeated at each call site, so the
|
||||
* question is asked the same way in all three places and a fourth cannot forget
|
||||
* to ask it.
|
||||
*/
|
||||
export async function passwordMatches(
|
||||
supplied: unknown,
|
||||
storedHash: string | null | undefined
|
||||
): Promise<boolean> {
|
||||
if (!storedHash) return false;
|
||||
return bcrypt.compare(String(supplied ?? ''), storedHash);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { PASSWORD_HASH_ROUNDS } from '../passwordHashing';
|
||||
import { PASSWORD_HASH_ROUNDS, passwordMatches } from '../passwordHashing';
|
||||
import crypto from 'node:crypto';
|
||||
import { pool, requireRow } from '../db';
|
||||
import { requireCustomer } from '../middleware/customerAuth';
|
||||
@@ -57,7 +57,7 @@ interface CustomerRow {
|
||||
* Kept in step with the schema by hand; nothing checks this against Postgres.
|
||||
*/
|
||||
interface CustomerRecord extends CustomerRow {
|
||||
password_hash: string;
|
||||
password_hash: string | null;
|
||||
disabled_at: Date | null;
|
||||
unsubscribe_token: string;
|
||||
marketing_consent_at: Date | null;
|
||||
@@ -418,7 +418,7 @@ router.post('/login', asyncRoute(async (req: Request, res: Response) => {
|
||||
const { email, password } = req.body;
|
||||
const { rows } = await pool.query<CustomerRecord>(`SELECT * FROM customers WHERE email = $1`, [String(email || '').toLowerCase().trim()]);
|
||||
const customer = rows[0];
|
||||
if (!customer || !(await bcrypt.compare(password || '', customer.password_hash))) {
|
||||
if (!customer || !(await passwordMatches(password, customer.password_hash))) {
|
||||
return res.status(401).json({ error: 'invalid email or password' });
|
||||
}
|
||||
// Only after the password checks out, so a wrong password still looks like a
|
||||
@@ -519,7 +519,7 @@ router.post('/change-password', requireCustomer, asyncRoute(async (req: Request,
|
||||
}
|
||||
const { rows } = await pool.query<CustomerRecord>(`SELECT * FROM customers WHERE id = $1`, [req.customerId]);
|
||||
const customer = requireRow(rows, 'the signed-in customer');
|
||||
if (!(await bcrypt.compare(currentPassword || '', customer.password_hash))) {
|
||||
if (!(await passwordMatches(currentPassword, customer.password_hash))) {
|
||||
return res.status(401).json({ error: 'current password is incorrect' });
|
||||
}
|
||||
const newHash = await bcrypt.hash(newPassword, PASSWORD_HASH_ROUNDS);
|
||||
@@ -552,7 +552,7 @@ router.put('/me/email', requireCustomer, asyncRoute(async (req: Request, res: Re
|
||||
const { rows } = await pool.query<CustomerRecord>(`SELECT * FROM customers WHERE id = $1`, [req.customerId]);
|
||||
const customer = requireRow(rows, 'the signed-in customer');
|
||||
|
||||
if (!(await bcrypt.compare(String(currentPassword ?? ''), customer.password_hash))) {
|
||||
if (!(await passwordMatches(currentPassword, customer.password_hash))) {
|
||||
return res.status(401).json({ error: 'current password is incorrect' });
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user