Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(api): send auth emails from the Worker through a Supabase hook

spacesdriveac14e992eab6
diff --git a/backend/container.ts b/backend/container.ts
index 4f2560d..6c987df 100644
--- a/backend/container.ts
+++ b/backend/container.ts
@@ -3,6 +3,7 @@ import { createAnalyticsCacheRepository } from './repositories/analyticsCacheRep
import { createScheduledPostRepository } from './repositories/scheduledPostRepository.ts';
import { createTrackedPostRepository } from './repositories/trackedPostRepository.ts';
import { createSettingsRepository } from './repositories/settingsRepository.ts';
+import { createEmailQuotaRepository } from './repositories/emailQuotaRepository.ts';
import { createAccountService } from './services/accountService.ts';
import { createYouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';
import { createInstagramAnalyticsService } from './services/instagramAnalyticsService.ts';
@@ -15,6 +16,7 @@ import { createTrackedContentService } from './services/trackedContentService.ts
import { createOverviewService } from './services/overviewService.ts';
import { createSettingsService } from './services/settingsService.ts';
import { createInstagramConnectService } from './services/instagramConnectService.ts';
+import { createAuthEmailService } from './services/authEmailService.ts';
import type { AccountService } from './services/accountService.ts';
import type { YouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';
import type { InstagramAnalyticsService } from './services/instagramAnalyticsService.ts';
@@ -27,6 +29,7 @@ import type { TrackedContentService } from './services/trackedContentService.ts'
import type { OverviewService } from './services/overviewService.ts';
import type { SettingsService } from './services/settingsService.ts';
import type { InstagramConnectService } from './services/instagramConnectService.ts';
+import type { AuthEmailService } from './services/authEmailService.ts';
import type { AppConfig } from './lib/config.ts';
import type { RequestContext } from './types/context.ts';
import type { Redis, SupabaseClient } from './types/app.ts';
@@ -34,6 +37,8 @@ import type { Redis, SupabaseClient } from './types/app.ts';
export interface Clients {
supabase: SupabaseClient;
redis: Redis | null;
+ // fails fast instead of retrying; the email counters use it to stay inside the auth hook's time budget
+ rateLimitRedis: Redis | null;
}
export interface Services {
@@ -49,6 +54,7 @@ export interface Services {
overview: OverviewService;
settings: SettingsService;
instagramConnect: InstagramConnectService;
+ authEmail: AuthEmailService;
}
// the composition root: wires repositories into services for one request or one cron run; building them is cheap
@@ -72,5 +78,6 @@ export function createServices(clients: Clients, config: AppConfig, context: Req
overview: createOverviewService({ accounts, tracked, cache, config }),
settings: createSettingsService({ settings, config }),
instagramConnect: createInstagramConnectService({ accounts, config, context }),
+ authEmail: createAuthEmailService({ quota: createEmailQuotaRepository(clients.rateLimitRedis), config, context }),
};
}
diff --git a/backend/controllers/authHookController.ts b/backend/controllers/authHookController.ts
new file mode 100644
index 0000000..699d2c1
--- /dev/null
+++ b/backend/controllers/authHookController.ts
@@ -0,0 +1,9 @@
+import { controller, servicesFor } from './http.ts';
+import { jsonBody } from '../middleware/validate.ts';
+import { parseAuthEmailHook } from '../validators/authHookValidators.ts';
+
+// called by Supabase Auth, not a browser: verifyAuthHook has already checked the signature and the webhook-id
+export const sendAuthEmail = controller.createHandlers(jsonBody(parseAuthEmailHook), async c => {
+ await servicesFor(c).authEmail.send(c.req.valid('json'), c.req.header('webhook-id') ?? '');
+ return c.json({});
+});
diff --git a/backend/controllers/http.ts b/backend/controllers/http.ts
index 8cf635f..34d6d61 100644
--- a/backend/controllers/http.ts
+++ b/backend/controllers/http.ts
@@ -18,5 +18,6 @@ export function pathParam(c: AppContext, name: string): string {
// the request's services, built from the clients the middleware created and the request context
export function servicesFor(c: AppContext): Services {
- return createServices({ supabase: c.get('supabase'), redis: c.get('redis') }, readConfig(c.env), requestContextOf(c));
+ const clients = { supabase: c.get('supabase'), redis: c.get('redis'), rateLimitRedis: c.get('rateLimitRedis') };
+ return createServices(clients, readConfig(c.env), requestContextOf(c));
}
diff --git a/backend/jobs/scheduled.ts b/backend/jobs/scheduled.ts
index 91a7792..b191a00 100644
--- a/backend/jobs/scheduled.ts
+++ b/backend/jobs/scheduled.ts
@@ -1,6 +1,6 @@
import { createServices } from '../container.ts';
import { getSupabase } from '../database/supabase.ts';
-import { getRedis } from '../database/redis.ts';
+import { getRedis, getRateLimitRedis } from '../database/redis.ts';
import { readConfig } from '../lib/config.ts';
import { createLogger } from '../lib/logger.ts';
import type { Env } from '../types/env.ts';
@@ -21,7 +21,8 @@ function cronContext(cron: string): RequestContext {
// the cron entry point: the same services the API uses, built from the Worker env instead of a request
export async function runScheduledJob(cron: string, env: Env): Promise<void> {
const context = cronContext(cron);
- const services = createServices({ supabase: getSupabase(env), redis: getRedis(env) }, readConfig(env), context);
+ const clients = { supabase: getSupabase(env), redis: getRedis(env), rateLimitRedis: getRateLimitRedis(env) };
+ const services = createServices(clients, readConfig(env), context);
if (cron === PUBLISH_DUE_POSTS_CRON) {
const run = await services.scheduledPublisher.publishDue();
diff --git a/backend/lib/config.ts b/backend/lib/config.ts
index a77d4f9..7f992f3 100644
--- a/backend/lib/config.ts
+++ b/backend/lib/config.ts
@@ -5,6 +5,8 @@ const DEFAULT_FRONTEND_URL = 'http://localhost:5173';
const DEV_ORIGINS = ['http://localhost:5173', 'http://127.0.0.1:5173'];
const LOCAL_HOSTNAMES = ['localhost', '127.0.0.1'];
const CALLBACK_PATH = '/api/auth/instagram/callback';
+// Resend's free plan sends 100 emails a day
+const DEFAULT_EMAIL_DAILY_LIMIT = 100;
export interface CloudinaryConfig {
cloudName: string;
@@ -19,11 +21,22 @@ export interface InstagramOAuthConfig {
appSecret: string | undefined;
}
+// the Send Email hook; each value is undefined when its Worker secret is not set
+export interface AuthEmailConfig {
+ hookSecret: string | undefined;
+ resendApiKey: string | undefined;
+ from: string | undefined;
+ dailyLimit: number;
+ // email links point at Supabase Auth's verify endpoint
+ supabaseUrl: string;
+}
+
export interface AppConfig {
youtubeApiKey: string | undefined;
instagram: InstagramOAuthConfig;
cloudinary: CloudinaryConfig | null;
allowedOrigins: string[];
+ authEmail: AuthEmailConfig;
}
// pasted secrets can carry a byte order mark or stray whitespace
@@ -71,6 +84,22 @@ export function readInstagramOAuthConfig(env: Env): InstagramOAuthConfig {
};
}
+// a missing, malformed or non-positive limit falls back to the default rather than stopping every email
+function dailyLimitOf(value: string | undefined): number {
+ const limit = Number(cleanSecret(value));
+ return Number.isInteger(limit) && limit > 0 ? limit : DEFAULT_EMAIL_DAILY_LIMIT;
+}
+
+export function readAuthEmailConfig(env: Env): AuthEmailConfig {
+ return {
+ hookSecret: cleanSecret(env.SEND_EMAIL_HOOK_SECRET),
+ resendApiKey: cleanSecret(env.RESEND_API_KEY),
+ from: cleanSecret(env.EMAIL_FROM),
+ dailyLimit: dailyLimitOf(env.EMAIL_DAILY_LIMIT),
+ supabaseUrl: cleanUrl(env.SUPABASE_URL, '').replace(/\/$/, ''),
+ };
+}
+
export function readConfig(env: Env): AppConfig {
const cloudName = cleanSecret(env.CLOUDINARY_CLOUD_NAME);
const uploadPreset = cleanSecret(env.CLOUDINARY_UPLOAD_PRESET);
@@ -79,5 +108,6 @@ export function readConfig(env: Env): AppConfig {
instagram: readInstagramOAuthConfig(env),
cloudinary: cloudName && uploadPreset ? { cloudName, uploadPreset } : null,
allowedOrigins: allowedOrigins(env),
+ authEmail: readAuthEmailConfig(env),
};
}
diff --git a/backend/lib/errors.ts b/backend/lib/errors.ts
index 0b2a1a8..02c098a 100644
--- a/backend/lib/errors.ts
+++ b/backend/lib/errors.ts
@@ -42,6 +42,13 @@ export class ConflictError extends AppError {
}
}
+// a daily allowance is used up; the per-request rate limiter answers its own 429s with retryAfter
+export class RateLimitedError extends AppError {
+ constructor(message: string) {
+ super('RATE_LIMITED', message);
+ }
+}
+
export class NotConfiguredError extends AppError {
constructor(message: string) {
super('NOT_CONFIGURED', message);
diff --git a/backend/lib/webhookSignature.ts b/backend/lib/webhookSignature.ts
new file mode 100644
index 0000000..6e623e7
--- /dev/null
+++ b/backend/lib/webhookSignature.ts
@@ -0,0 +1,40 @@
+// Standard Webhooks (https://www.standardwebhooks.com), as Supabase Auth hooks sign them:
+// HMAC-SHA256 over "id.timestamp.body" with the base64 key from a "v1,whsec_<base64>" secret.
+const TOLERANCE_SECONDS = 5 * 60;
+const SECRET_PREFIX = /^(v1,)?whsec_/;
+
+export interface WebhookHeaders {
+ id: string | undefined;
+ timestamp: string | undefined;
+ signature: string | undefined;
+}
+
+function fromBase64(text: string): Uint8Array<ArrayBuffer> | null {
+ try {
+ return Uint8Array.from(atob(text), char => char.charCodeAt(0));
+ } catch {
+ return null;
+ }
+}
+
+// true only for a signature made with the secret within five minutes of now, which stops replays of old requests
+export async function verifyWebhookSignature(secret: string, headers: WebhookHeaders, body: string, nowMs = Date.now()): Promise<boolean> {
+ const { id, timestamp, signature } = headers;
+ if (!id || !timestamp || !signature || !/^\d+$/.test(timestamp)) return false;
+ if (Math.abs(nowMs / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) return false;
+
+ const keyBytes = fromBase64(secret.replace(SECRET_PREFIX, ''));
+ if (!keyBytes) return false;
+ const key = await crypto.subtle.importKey('raw', keyBytes, { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
+ const signed = new TextEncoder().encode(`${id}.${timestamp}.${body}`);
+
+ // the header lists "v1,<base64>" entries separated by spaces, one per active key
+ for (const entry of signature.split(' ')) {
+ const [version, value] = entry.split(',');
+ if (version !== 'v1' || !value) continue;
+ const candidate = fromBase64(value);
+ // subtle.verify compares in constant time
+ if (candidate && await crypto.subtle.verify('HMAC', key, candidate, signed)) return true;
+ }
+ return false;
+}
diff --git a/backend/middleware/authHook.ts b/backend/middleware/authHook.ts
new file mode 100644
index 0000000..398579e
--- /dev/null
+++ b/backend/middleware/authHook.ts
@@ -0,0 +1,23 @@
+import type { Next } from 'hono';
+import { readAuthEmailConfig } from '../lib/config.ts';
+import { NotConfiguredError, UnauthorizedError } from '../lib/errors.ts';
+import { verifyWebhookSignature } from '../lib/webhookSignature.ts';
+import type { AppContext } from '../types/app.ts';
+
+// the hook route is public, so the signature is what proves the request came from this project's Supabase Auth
+export async function verifyAuthHook(c: AppContext, next: Next): Promise<void> {
+ const { hookSecret } = readAuthEmailConfig(c.env);
+ if (!hookSecret) throw new NotConfiguredError('Email sending is not set up: the SEND_EMAIL_HOOK_SECRET Worker secret is missing');
+
+ // hono caches the body, so the validator after this reads the same text
+ const body = await c.req.text();
+ const headers = {
+ id: c.req.header('webhook-id'),
+ timestamp: c.req.header('webhook-timestamp'),
+ signature: c.req.header('webhook-signature'),
+ };
+ if (!await verifyWebhookSignature(hookSecret, headers, body)) {
+ throw new UnauthorizedError('The hook signature is missing, invalid or expired');
+ }
+ await next();
+}
diff --git a/backend/middleware/errorHandler.ts b/backend/middleware/errorHandler.ts
index ffbb0c8..583e8cb 100644
--- a/backend/middleware/errorHandler.ts
+++ b/backend/middleware/errorHandler.ts
@@ -5,6 +5,7 @@ import { errorFields } from '../lib/logger.ts';
import { requestLogger } from './requestContext.ts';
import type { AppContext } from '../types/app.ts';
import type { ApiErrorCode, ApiFailure } from '../../shared/types/domain.ts';
+import type { AuthHookFailure } from '../types/authHook.ts';
const STATUS_BY_CODE: Record<ApiErrorCode, ContentfulStatusCode> = {
VALIDATION_ERROR: 400,
@@ -34,8 +35,14 @@ export function errorBody(c: AppContext, code: ApiErrorCode, message: string): A
return { success: false, code, message, requestId: c.get('requestId') };
}
-// last in the pipeline: every error thrown by a controller, service, repository or middleware ends here
-export function errorHandler(err: Error, c: AppContext): Response {
+interface Failure {
+ code: ApiErrorCode;
+ status: ContentfulStatusCode;
+ message: string;
+}
+
+// logs the error with the request id and decides the code, status and the message the client may see
+function describeFailure(err: Error, c: AppContext): Failure {
const log = requestLogger(c);
if (err instanceof AppError) {
@@ -43,18 +50,30 @@ export function errorHandler(err: Error, c: AppContext): Response {
const fields = { code: err.code, status, ...errorFields(err) };
if (status >= 500) log.error('request failed', fields);
else log.warn('request rejected', fields);
- return c.json(errorBody(c, err.code, err.message), status);
+ return { code: err.code, status, message: err.message };
}
// hono's own errors, such as a malformed JSON body in a validator
if (err instanceof HTTPException) {
const code = CODE_BY_STATUS[err.status] ?? 'INTERNAL_ERROR';
log.warn('request rejected', { code, status: err.status, ...errorFields(err) });
- return c.json(errorBody(c, code, err.message || 'The request could not be processed'), err.status);
+ return { code, status: err.status, message: err.message || 'The request could not be processed' };
}
log.error('unhandled error', { code: 'INTERNAL_ERROR', status: 500, ...errorFields(err) });
- return c.json(errorBody(c, 'INTERNAL_ERROR', INTERNAL_MESSAGE), 500);
+ return { code: 'INTERNAL_ERROR', status: 500, message: INTERNAL_MESSAGE };
+}
+
+// last in the pipeline: every error thrown by a controller, service, repository or middleware ends here
+export function errorHandler(err: Error, c: AppContext): Response {
+ const { code, status, message } = describeFailure(err, c);
+ return c.json(errorBody(c, code, message), status);
+}
+
+// Supabase Auth hooks expect { error: { http_code, message } } and show the message to the person signing up
+export function authHookErrorHandler(err: Error, c: AppContext): Response {
+ const { status, message } = describeFailure(err, c);
+ return c.json({ error: { http_code: status, message } } satisfies AuthHookFailure, status);
}
export function notFoundHandler(c: AppContext): Response {
diff --git a/backend/repositories/emailQuotaRepository.ts b/backend/repositories/emailQuotaRepository.ts
new file mode 100644
index 0000000..dcfe3f8
--- /dev/null
+++ b/backend/repositories/emailQuotaRepository.ts
@@ -0,0 +1,57 @@
+import type { Redis } from '../types/app.ts';
+
+// the counters outlive their UTC day by a day, so a send just before midnight is still counted when the day rolls
+const COUNTER_TTL_SECONDS = 2 * 24 * 60 * 60;
+
+// atomic, so two hook calls at once cannot both take the last email of the day;
+// a refused send increments nothing, so one address asking again and again cannot use up the day's allowance
+const CLAIM_SCRIPT = `
+local daily = tonumber(redis.call('GET', KEYS[1]) or '0')
+local recipient = tonumber(redis.call('GET', KEYS[2]) or '0')
+if recipient >= tonumber(ARGV[2]) then return 2 end
+if daily >= tonumber(ARGV[1]) then return 1 end
+redis.call('INCR', KEYS[1])
+redis.call('EXPIRE', KEYS[1], ARGV[3])
+redis.call('INCR', KEYS[2])
+redis.call('EXPIRE', KEYS[2], ARGV[3])
+return 0
+`;
+
+const OUTCOMES = ['claimed', 'daily_limit', 'recipient_limit'] as const;
+
+// unknown: Redis is not configured or did not answer, so the email provider's own quota is the only cap
+export type EmailClaim = typeof OUTCOMES[number] | 'unknown';
+
+export interface EmailClaimRequest {
+ recipient: string;
+ // the UTC date, YYYY-MM-DD, the counters belong to
+ day: string;
+ dailyLimit: number;
+ recipientLimit: number;
+}
+
+export interface EmailQuotaRepository {
+ claim(request: EmailClaimRequest): Promise<EmailClaim>;
+}
+
+// the key holds a hash, never the address itself
+async function recipientKey(recipient: string): Promise<string> {
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(recipient.trim().toLowerCase()));
+ return [...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, '0')).join('');
+}
+
+export function createEmailQuotaRepository(redis: Redis | null): EmailQuotaRepository {
+ return {
+ async claim({ recipient, day, dailyLimit, recipientLimit }) {
+ if (!redis) return 'unknown';
+ try {
+ const keys = [`email:day:${day}`, `email:to:${await recipientKey(recipient)}:${day}`];
+ const result = await redis.createScript<number>(CLAIM_SCRIPT).exec(keys, [String(dailyLimit), String(recipientLimit), String(COUNTER_TTL_SECONDS)]);
+ return OUTCOMES[result] ?? 'unknown';
+ } catch {
+ // like the cache, Redis is optional: the email still goes out, capped by the provider's quota
+ return 'unknown';
+ }
+ },
+ };
+}
diff --git a/backend/routes/authHookRoutes.ts b/backend/routes/authHookRoutes.ts
new file mode 100644
index 0000000..eda0262
--- /dev/null
+++ b/backend/routes/authHookRoutes.ts
@@ -0,0 +1,14 @@
+import { Hono } from 'hono';
+import { sendAuthEmail } from '../controllers/authHookController.ts';
+import { verifyAuthHook } from '../middleware/authHook.ts';
+import { authHookErrorHandler } from '../middleware/errorHandler.ts';
+import type { AppEnv } from '../types/app.ts';
+
+const router = new Hono<AppEnv>();
+
+// Supabase Auth reads failures in its own shape, so this table answers errors with the hook error handler
+router.onError(authHookErrorHandler);
+
+router.post('/auth/email-hook', verifyAuthHook, ...sendAuthEmail);
+
+export default router;
diff --git a/backend/routes/index.ts b/backend/routes/index.ts
index 755369c..13bd9b7 100644
--- a/backend/routes/index.ts
+++ b/backend/routes/index.ts
@@ -1,5 +1,6 @@
import { Hono } from 'hono';
import accountRoutes from './accountRoutes.ts';
+import authHookRoutes from './authHookRoutes.ts';
import analyticsRoutes from './analyticsRoutes.ts';
import instagramAuthRoutes from './instagramAuthRoutes.ts';
import overviewRoutes from './overviewRoutes.ts';
@@ -14,10 +15,12 @@ import { rateLimit, clientIp } from '../middleware/rateLimit.ts';
import { RATE_LIMIT_RULES } from '../lib/rateLimit/rules.ts';
import type { AppEnv } from '../types/app.ts';
-// reachable without a token: the health check, and the OAuth redirect, whose signed state names the user
+// reachable without a token: the health check, the OAuth redirect, whose signed state names the user,
+// and Supabase Auth's email hook, whose signature proves where it came from
export const publicRoutes = new Hono<AppEnv>();
publicRoutes.get('/health', ...getHealth);
publicRoutes.get('/auth/instagram/callback', rateLimit(RATE_LIMIT_RULES.oauth, clientIp), ...handleInstagramCallback);
+publicRoutes.route('/', authHookRoutes);
// mounted behind requireAuth and the per-user rate limits in app.ts
export const protectedRoutes = new Hono<AppEnv>();
diff --git a/backend/services/authEmailService.ts b/backend/services/authEmailService.ts
new file mode 100644
index 0000000..338dde5
--- /dev/null
+++ b/backend/services/authEmailService.ts
@@ -0,0 +1,81 @@
+import { NotConfiguredError, RateLimitedError, UpstreamError } from '../lib/errors.ts';
+import { composeAuthEmails } from './email/authEmails.ts';
+import { sendEmail } from './email/resendApi.ts';
+import type { AuthEmail } from './email/authEmails.ts';
+import type { EmailQuotaRepository } from '../repositories/emailQuotaRepository.ts';
+import type { AppConfig } from '../lib/config.ts';
+import type { AuthEmailHook } from '../types/authHook.ts';
+import type { RequestContext } from '../types/context.ts';
+
+// enough for a few resends and a password reset, while one address cannot use up the day's allowance
+export const RECIPIENT_DAILY_LIMIT = 5;
+
+// shown on the sign-up form, which also points to the Google button
+export const DAILY_LIMIT_MESSAGE = 'Twiligent has sent all the verification emails it can today. Sign in with Google instead, or try again tomorrow.';
+export const RECIPIENT_LIMIT_MESSAGE = 'This address has received the most codes allowed today. Use the latest code you received, or try again tomorrow.';
+
+// Resend's answers when the account itself has run out
+const PROVIDER_QUOTA_REASONS = ['daily_quota_exceeded', 'monthly_quota_exceeded'];
+
+export interface AuthEmailDeps {
+ quota: EmailQuotaRepository;
+ config: AppConfig;
+ context: RequestContext;
+ now?: () => Date;
+}
+
+export interface AuthEmailService {
+ send(hook: AuthEmailHook, webhookId: string): Promise<void>;
+}
+
+export function createAuthEmailService({ quota, config, context, now = () => new Date() }: AuthEmailDeps): AuthEmailService {
+ const { resendApiKey, from, dailyLimit, supabaseUrl } = config.authEmail;
+
+ // the counters follow the UTC day, as Resend's daily quota does
+ const today = () => now().toISOString().slice(0, 10);
+
+ async function claim(email: AuthEmail): Promise<void> {
+ const outcome = await quota.claim({ recipient: email.to, day: today(), dailyLimit, recipientLimit: RECIPIENT_DAILY_LIMIT });
+ if (outcome === 'daily_limit') throw new RateLimitedError(DAILY_LIMIT_MESSAGE);
+ if (outcome === 'recipient_limit') throw new RateLimitedError(RECIPIENT_LIMIT_MESSAGE);
+ if (outcome === 'unknown') context.log.warn('email counter unavailable', { reason: 'redis' });
+ }
+
+ async function deliver(email: AuthEmail, apiKey: string, sender: string, idempotencyKey: string): Promise<void> {
+ try {
+ await sendEmail({ apiKey, from: sender, message: email, idempotencyKey }, context.signal);
+ } catch (err) {
+ if (err instanceof UpstreamError && PROVIDER_QUOTA_REASONS.includes(err.reason)) throw new RateLimitedError(DAILY_LIMIT_MESSAGE);
+ throw err;
+ }
+ }
+
+ return {
+ async send(hook, webhookId) {
+ if (!resendApiKey || !from) {
+ throw new NotConfiguredError('Email sending is not set up: the RESEND_API_KEY and EMAIL_FROM Worker secrets are required');
+ }
+
+ const emails = composeAuthEmails(hook, supabaseUrl);
+ if (emails.length === 0) {
+ context.log.warn('auth email skipped', { action: hook.action, reason: 'unknown action' });
+ return;
+ }
+
+ for (const [index, email] of emails.entries()) {
+ try {
+ await claim(email);
+ await deliver(email, resendApiKey, from, `${webhookId}-${index}`);
+ } catch (err) {
+ // a notice reports a change already made, so losing it must not fail the user's action
+ if (email.notice && err instanceof RateLimitedError) {
+ context.log.warn('auth email skipped', { action: hook.action, reason: 'limit reached' });
+ continue;
+ }
+ throw err;
+ }
+ }
+ context.log.info('auth email sent', { action: hook.action, count: emails.length });
+ },
+ };
+}
diff --git a/backend/services/email/authEmails.ts b/backend/services/email/authEmails.ts
new file mode 100644
index 0000000..9da1527
--- /dev/null
+++ b/backend/services/email/authEmails.ts
@@ -0,0 +1,163 @@
+import type { AuthEmailHook } from '../../types/authHook.ts';
+
+export interface EmailMessage {
+ to: string;
+ subject: string;
+ text: string;
+ html: string;
+}
+
+// a notice only reports a change already made, so it may be skipped when the daily cap is reached
+export interface AuthEmail extends EmailMessage {
+ notice: boolean;
+}
+
+interface CodeEmailCopy {
+ subject: string;
+ lead: string;
+ // the label of the link that does the same as the code; omitted when there is no link
+ linkLabel?: string;
+}
+
+const CODE_EMAILS: Record<string, CodeEmailCopy> = {
+ signup: {
+ subject: 'Your Twiligent verification code',
+ lead: 'Enter this code on the sign-up page to confirm your email and finish creating your account.',
+ linkLabel: 'Or confirm your email with this link',
+ },
+ recovery: {
+ subject: 'Reset your Twiligent password',
+ lead: 'Enter this code to choose a new password.',
+ linkLabel: 'Or reset your password with this link',
+ },
+ magiclink: {
+ subject: 'Your Twiligent sign-in code',
+ lead: 'Enter this code to sign in.',
+ linkLabel: 'Or sign in with this link',
+ },
+ email: {
+ subject: 'Your Twiligent sign-in code',
+ lead: 'Enter this code to sign in.',
+ linkLabel: 'Or sign in with this link',
+ },
+ invite: {
+ subject: 'You have been invited to Twiligent',
+ lead: 'You have been invited to create a Twiligent account. Enter this code to accept the invitation.',
+ linkLabel: 'Or accept the invitation with this link',
+ },
+ reauthentication: {
+ subject: 'Your Twiligent confirmation code',
+ lead: 'Enter this code to confirm it is you.',
+ },
+};
+
+const NOTICES: Record<string, string> = {
+ password_changed_notification: 'The password for your Twiligent account was changed.',
+ email_changed_notification: 'The email address for your Twiligent account was changed.',
+ phone_changed_notification: 'The phone number for your Twiligent account was changed.',
+ identity_linked_notification: 'A new sign-in method was added to your Twiligent account.',
+ identity_unlinked_notification: 'A sign-in method was removed from your Twiligent account.',
+ mfa_factor_enrolled_notification: 'Two-step verification was turned on for your Twiligent account.',
+ mfa_factor_unenrolled_notification: 'A two-step verification method was removed from your Twiligent account.',
+};
+
+const IGNORE_NOTE = 'If you did not ask for this, you can ignore this email.';
+const NOTICE_NOTE = 'If this was not you, reset your password and review the sign-in methods on your account.';
+
+function escapeHtml(value: string): string {
+ return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
+}
+
+// the same endpoint Supabase's default templates link to; it verifies the hash and redirects to the app
+function verifyUrl(supabaseUrl: string, tokenHash: string, type: string, redirectTo: string): string {
+ const params = new URLSearchParams({ token: tokenHash, type });
+ if (redirectTo) params.set('redirect_to', redirectTo);
+ return `${supabaseUrl}/auth/v1/verify?${params}`;
+}
+
+function paragraph(text: string): string {
+ return `<p style="margin:0 0 16px;font-size:15px;line-height:1.5;color:#3f3f46">${escapeHtml(text)}</p>`;
+}
+
+function layout(blocks: string[]): string {
+ return `<!doctype html><html><body style="margin:0;padding:24px;background:#ffffff;font-family:Arial,Helvetica,sans-serif">`
+ + `<div style="max-width:480px;margin:0 auto">${blocks.join('')}</div></body></html>`;
+}
+
+interface CodeEmailParts {
+ to: string;
+ copy: CodeEmailCopy;
+ code: string;
+ link: string | undefined;
+}
+
+function codeEmail({ to, copy, code, link }: CodeEmailParts): AuthEmail {
+ const text = [copy.lead, '', code, '', 'The code works once and expires soon.'];
+ const html = [
+ paragraph(copy.lead),
+ `<p style="margin:0 0 16px;font-size:32px;font-weight:bold;letter-spacing:6px;font-family:'Courier New',monospace;color:#18181b">${escapeHtml(code)}</p>`,
+ paragraph('The code works once and expires soon.'),
+ ];
+ if (link && copy.linkLabel) {
+ text.push('', `${copy.linkLabel}: ${link}`);
+ html.push(`<p style="margin:0 0 16px;font-size:15px"><a href="${escapeHtml(link)}" style="color:#4f46e5">${escapeHtml(copy.linkLabel)}</a></p>`);
+ }
+ text.push('', IGNORE_NOTE);
+ html.push(paragraph(IGNORE_NOTE));
+ return { to, subject: copy.subject, text: text.join('\n'), html: layout(html), notice: false };
+}
+
+function noticeEmail(to: string, message: string): AuthEmail {
+ return {
+ to,
+ subject: 'A change to your Twiligent account',
+ text: [message, '', NOTICE_NOTE].join('\n'),
+ html: layout([paragraph(message), paragraph(NOTICE_NOTE)]),
+ notice: true,
+ };
+}
+
+// Secure Email Change sends a code to both addresses; Supabase names the hashes the other way round
+function emailChangeEmails(hook: AuthEmailHook, supabaseUrl: string): AuthEmail[] {
+ const link = (hash: string) => (hash ? verifyUrl(supabaseUrl, hash, 'email_change', hook.redirectTo) : undefined);
+ const toNew = (code: string, hash: string): AuthEmail => codeEmail({
+ to: hook.newEmail ?? hook.email,
+ copy: {
+ subject: 'Confirm your new Twiligent email address',
+ lead: 'Enter this code to confirm this address as the new email for your Twiligent account.',
+ linkLabel: 'Or confirm the new address with this link',
+ },
+ code,
+ link: link(hash),
+ });
+
+ if (hook.token && hook.tokenNew && hook.newEmail) {
+ return [
+ codeEmail({
+ to: hook.email,
+ copy: {
+ subject: 'Confirm the change to your Twiligent email address',
+ lead: `Enter this code to confirm moving your Twiligent account to ${hook.newEmail}.`,
+ linkLabel: 'Or confirm the change with this link',
+ },
+ code: hook.token,
+ link: link(hook.tokenHashNew),
+ }),
+ toNew(hook.tokenNew, hook.tokenHash),
+ ];
+ }
+ return [toNew(hook.token || hook.tokenNew, hook.tokenHash || hook.tokenHashNew)];
+}
+
+// the emails one hook call asks for; an action this Worker does not know yields none
+export function composeAuthEmails(hook: AuthEmailHook, supabaseUrl: string): AuthEmail[] {
+ if (hook.action === 'email_change') return emailChangeEmails(hook, supabaseUrl);
+
+ const notice = NOTICES[hook.action];
+ if (notice) return [noticeEmail(hook.email, notice)];
+
+ const copy = CODE_EMAILS[hook.action];
+ if (!copy || !hook.token) return [];
+ const link = hook.tokenHash ? verifyUrl(supabaseUrl, hook.tokenHash, hook.action, hook.redirectTo) : undefined;
+ return [codeEmail({ to: hook.email, copy, code: hook.token, link })];
+}
diff --git a/backend/services/email/resendApi.ts b/backend/services/email/resendApi.ts
new file mode 100644
index 0000000..1222a45
--- /dev/null
+++ b/backend/services/email/resendApi.ts
@@ -0,0 +1,48 @@
+import { UpstreamError, UpstreamTimeoutError, isAbortError } from '../../lib/errors.ts';
+import type { EmailMessage } from './authEmails.ts';
+
+const SEND_URL = 'https://api.resend.com/emails';
+
+// Supabase gives the whole hook call 5 seconds, so a slow send is abandoned before Supabase gives up on the Worker
+const SEND_TIMEOUT_MS = 4000;
+
+// Resend's error body; name is the machine-readable reason, such as daily_quota_exceeded
+interface ResendErrorBody {
+ name?: string;
+ message?: string;
+}
+
+export interface ResendSend {
+ apiKey: string;
+ from: string;
+ message: EmailMessage;
+ // the same key on a retried hook call makes Resend skip the duplicate
+ idempotencyKey: string;
+}
+
+export async function sendEmail({ apiKey, from, message, idempotencyKey }: ResendSend, signal?: AbortSignal): Promise<void> {
+ const timeout = AbortSignal.timeout(SEND_TIMEOUT_MS);
+ let response: Response;
+ try {
+ response = await fetch(SEND_URL, {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${apiKey}`,
+ 'Content-Type': 'application/json',
+ 'Idempotency-Key': idempotencyKey,
+ },
+ body: JSON.stringify({ from, to: [message.to], subject: message.subject, text: message.text, html: message.html }),
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
+ });
+ } catch (err) {
+ if (isAbortError(err)) throw new UpstreamTimeoutError('Resend', err);
+ throw new UpstreamError(`Resend unreachable (${(err as Error).message})`, { cause: err });
+ }
+ if (response.ok) return;
+
+ const body = await response.json().catch(() => null) as ResendErrorBody | null;
+ throw new UpstreamError(`Resend could not send the email: ${body?.message || `status ${response.status}`}`, {
+ reason: body?.name ?? '',
+ status: response.status,
+ });
+}
diff --git a/backend/tests/fixtures/authHook.ts b/backend/tests/fixtures/authHook.ts
new file mode 100644
index 0000000..d14c8da
--- /dev/null
+++ b/backend/tests/fixtures/authHook.ts
@@ -0,0 +1,53 @@
+import type { AuthEmailHook } from '../../types/authHook.ts';
+
+// a Supabase-style hook secret: "v1,whsec_" and a base64 key
+export const HOOK_KEY = 'c2VjcmV0LWtleS1mb3ItdGVzdHM=';
+export const HOOK_SECRET = `v1,whsec_${HOOK_KEY}`;
+
+// signs the way Supabase Auth does: HMAC-SHA256 over "id.timestamp.body", base64, prefixed with "v1,"
+export async function signWebhook(id: string, timestamp: number, body: string, key = HOOK_KEY): Promise<string> {
+ const keyBytes = Uint8Array.from(atob(key), char => char.charCodeAt(0));
+ const cryptoKey = await crypto.subtle.importKey('raw', keyBytes, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
+ const signature = await crypto.subtle.sign('HMAC', cryptoKey, new TextEncoder().encode(`${id}.${timestamp}.${body}`));
+ return `v1,${btoa(String.fromCharCode(...new Uint8Array(signature)))}`;
+}
+
+export async function signedHeaders(body: string, id = 'msg_1', timestamp = Math.floor(Date.now() / 1000)): Promise<Record<string, string>> {
+ return {
+ 'Content-Type': 'application/json',
+ 'webhook-id': id,
+ 'webhook-timestamp': String(timestamp),
+ 'webhook-signature': await signWebhook(id, timestamp, body),
+ };
+}
+
+export function signupPayload(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ user: { id: 'user-1', email: '[email protected]' },
+ email_data: {
+ token: '123456',
+ token_hash: 'hash-abc',
+ redirect_to: 'https://app.example.com/',
+ email_action_type: 'signup',
+ site_url: 'https://app.example.com',
+ token_new: '',
+ token_hash_new: '',
+ ...overrides,
+ },
+ };
+}
+
+export function hook(overrides: Partial<AuthEmailHook> = {}): AuthEmailHook {
+ return {
+ email: '[email protected]',
+ newEmail: undefined,
+ action: 'signup',
+ token: '123456',
+ tokenHash: 'hash-abc',
+ tokenNew: '',
+ tokenHashNew: '',
+ redirectTo: 'https://app.example.com/',
+ siteUrl: 'https://app.example.com',
+ ...overrides,
+ };
+}
diff --git a/backend/tests/fixtures/routeHarness.ts b/backend/tests/fixtures/routeHarness.ts
index ef037c0..64e673e 100644
--- a/backend/tests/fixtures/routeHarness.ts
+++ b/backend/tests/fixtures/routeHarness.ts
@@ -5,6 +5,7 @@ import type { Env } from '../../types/env.ts';
export interface CallOptions {
json?: unknown;
+ headers?: Record<string, string>;
env?: Partial<Env>;
}
@@ -41,6 +42,7 @@ export async function callRoute(app: Hono<AppEnv>, method: string, path: string,
init.body = typeof options.json === 'string' ? options.json : JSON.stringify(options.json);
init.headers = { 'Content-Type': 'application/json' };
}
+ if (options.headers) init.headers = { ...init.headers, ...options.headers };
const response = await app.request(path, init, options.env ?? {});
const result: RouteResult = { status: response.status, body: await response.text() };
const location = response.headers.get('location');
diff --git a/backend/tests/lib/webhookSignature.test.ts b/backend/tests/lib/webhookSignature.test.ts
new file mode 100644
index 0000000..b2401eb
--- /dev/null
+++ b/backend/tests/lib/webhookSignature.test.ts
@@ -0,0 +1,57 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { verifyWebhookSignature } from '../../lib/webhookSignature.ts';
+import { HOOK_SECRET, signWebhook } from '../fixtures/authHook.ts';
+
+const NOW_MS = 1_760_000_000_000;
+const NOW = NOW_MS / 1000;
+const BODY = '{"user":{"email":"[email protected]"}}';
+const OTHER_KEY = btoa('another key');
+
+interface Headers {
+ id?: string;
+ timestamp?: string;
+ signature?: string;
+}
+
+function verify({ id, timestamp, signature }: Headers, body = BODY, secret = HOOK_SECRET) {
+ return verifyWebhookSignature(secret, { id, timestamp, signature }, body, NOW_MS);
+}
+
+test('a request signed with the hook secret is accepted, with or without the v1, prefix on the secret', async () => {
+ const signature = await signWebhook('msg_1', NOW, BODY);
+ assert.equal(await verify({ id: 'msg_1', timestamp: String(NOW), signature }), true);
+ assert.equal(await verify({ id: 'msg_1', timestamp: String(NOW), signature }, BODY, HOOK_SECRET.replace('v1,', '')), true);
+});
+
+test('any one valid entry in a list of signatures is enough', async () => {
+ const valid = await signWebhook('msg_1', NOW, BODY);
+ const other = await signWebhook('msg_1', NOW, BODY, OTHER_KEY);
+ assert.equal(await verify({ id: 'msg_1', timestamp: String(NOW), signature: `${other} ${valid}` }), true);
+});
+
+test('a changed body, id or timestamp, another key, or a missing header is rejected', async () => {
+ const signature = await signWebhook('msg_1', NOW, BODY);
+ assert.equal(await verify({ id: 'msg_1', timestamp: String(NOW), signature }, `${BODY} `), false);
+ assert.equal(await verify({ id: 'msg_2', timestamp: String(NOW), signature }), false);
+ assert.equal(await verify({ id: 'msg_1', timestamp: String(NOW + 1), signature }), false);
+ assert.equal(await verify({ id: 'msg_1', timestamp: String(NOW), signature: await signWebhook('msg_1', NOW, BODY, OTHER_KEY) }), false);
+ assert.equal(await verify({ timestamp: String(NOW), signature }), false);
+ assert.equal(await verify({ id: 'msg_1', signature }), false);
+ assert.equal(await verify({ id: 'msg_1', timestamp: String(NOW) }), false);
+});
+
+test('a signature more than five minutes from now is rejected, so old requests cannot be replayed', async () => {
+ for (const [timestamp, accepted] of [[NOW - 301, false], [NOW + 301, false], [NOW - 299, true]] as const) {
+ const signature = await signWebhook('msg_1', timestamp, BODY);
+ assert.equal(await verify({ id: 'msg_1', timestamp: String(timestamp), signature }), accepted);
+ }
+});
+
+test('malformed headers and secrets are rejected without throwing', async () => {
+ const signature = await signWebhook('msg_1', NOW, BODY);
+ assert.equal(await verify({ id: 'msg_1', timestamp: 'soon', signature }), false);
+ assert.equal(await verify({ id: 'msg_1', timestamp: String(NOW), signature: 'v1,%%%' }), false);
+ assert.equal(await verify({ id: 'msg_1', timestamp: String(NOW), signature: signature.replace('v1,', 'v2,') }), false);
+ assert.equal(await verify({ id: 'msg_1', timestamp: String(NOW), signature }, BODY, 'v1,whsec_%%%'), false);
+});
diff --git a/backend/tests/repositories/emailQuotaRepository.test.ts b/backend/tests/repositories/emailQuotaRepository.test.ts
new file mode 100644
index 0000000..3125e37
--- /dev/null
+++ b/backend/tests/repositories/emailQuotaRepository.test.ts
@@ -0,0 +1,60 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { createEmailQuotaRepository } from '../../repositories/emailQuotaRepository.ts';
+import type { Redis } from '../../types/app.ts';
+
+interface ScriptCall {
+ keys: string[];
+ args: string[];
+}
+
+// runs the claim rules in memory, the way the Lua script does in Redis
+function counterRedis(): { redis: Redis; counts: Map<string, number>; calls: ScriptCall[] } {
+ const counts = new Map<string, number>();
+ const calls: ScriptCall[] = [];
+ const redis = {
+ createScript() {
+ return {
+ async exec(keys: string[], args: string[]) {
+ calls.push({ keys, args });
+ const [dailyKey, recipientKey] = keys;
+ if ((counts.get(recipientKey) ?? 0) >= Number(args[1])) return 2;
+ if ((counts.get(dailyKey) ?? 0) >= Number(args[0])) return 1;
+ counts.set(dailyKey, (counts.get(dailyKey) ?? 0) + 1);
+ counts.set(recipientKey, (counts.get(recipientKey) ?? 0) + 1);
+ return 0;
+ },
+ };
+ },
+ };
+ return { redis: redis as unknown as Redis, counts, calls };
+}
+
+const request = (recipient: string) => ({ recipient, day: '2026-10-14', dailyLimit: 3, recipientLimit: 2 });
+
+test('claims count per UTC day and per address, and a refused claim counts nothing', async () => {
+ const { redis, counts } = counterRedis();
+ const quota = createEmailQuotaRepository(redis);
+ assert.equal(await quota.claim(request('[email protected]')), 'claimed');
+ assert.equal(await quota.claim(request('[email protected] ')), 'claimed');
+ assert.equal(await quota.claim(request('[email protected]')), 'recipient_limit');
+ assert.equal(await quota.claim(request('[email protected]')), 'claimed');
+ assert.equal(await quota.claim(request('[email protected]')), 'daily_limit');
+ assert.equal(counts.get('email:day:2026-10-14'), 3);
+});
+
+test('the keys hold a hash of the address, never the address, and the counters expire after two days', async () => {
+ const { redis, calls } = counterRedis();
+ await createEmailQuotaRepository(redis).claim(request('[email protected]'));
+ const [{ keys, args }] = calls;
+ assert.equal(keys[0], 'email:day:2026-10-14');
+ assert.match(keys[1], /^email:to:[0-9a-f]{64}:2026-10-14$/);
+ assert.equal(keys.join(' ').includes('example.com'), false);
+ assert.deepEqual(args, ['3', '2', '172800']);
+});
+
+test('without Redis, or when Redis fails, the outcome is unknown instead of an error', async () => {
+ assert.equal(await createEmailQuotaRepository(null).claim(request('[email protected]')), 'unknown');
+ const failing = { createScript: () => ({ exec: async () => { throw new Error('down'); } }) } as unknown as Redis;
+ assert.equal(await createEmailQuotaRepository(failing).claim(request('[email protected]')), 'unknown');
+});
diff --git a/backend/tests/routes/authHookRoutes.test.ts b/backend/tests/routes/authHookRoutes.test.ts
new file mode 100644
index 0000000..7671734
--- /dev/null
+++ b/backend/tests/routes/authHookRoutes.test.ts
@@ -0,0 +1,88 @@
+import { test, describe, afterEach, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import authHookRouter from '../../routes/authHookRoutes.ts';
+import { createApp } from '../../app.ts';
+import { DAILY_LIMIT_MESSAGE } from '../../services/authEmailService.ts';
+import { fakeSupabase } from '../fixtures/fakeSupabase.ts';
+import { mountWithContext, callRoute } from '../fixtures/routeHarness.ts';
+import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock } from '../fixtures/fakeFetch.ts';
+import { HOOK_SECRET, signedHeaders, signupPayload } from '../fixtures/authHook.ts';
+import type { Redis } from '../../types/app.ts';
+import type { Env } from '../../types/env.ts';
+
+const ENV: Partial<Env> = {
+ SUPABASE_URL: 'https://project.supabase.co',
+ SUPABASE_ANON_KEY: 'anon',
+ SUPABASE_SERVICE_KEY: 'service',
+ SEND_EMAIL_HOOK_SECRET: HOOK_SECRET,
+ RESEND_API_KEY: 're_test',
+ EMAIL_FROM: 'Twiligent <[email protected]>',
+};
+
+let fetchMock: FetchMock | null = null;
+
+afterEach(() => {
+ fetchMock?.restore();
+ fetchMock = null;
+ mock.restoreAll();
+});
+
+function quietLogs() {
+ for (const method of ['log', 'warn', 'error'] as const) mock.method(console, method, () => undefined);
+}
+
+// answers every claim with one outcome: 0 claimed, 1 daily limit, 2 per-address limit
+function claimRedis(outcome: number): Redis {
+ return { createScript: () => ({ exec: async () => outcome }) } as unknown as Redis;
+}
+
+function mount(outcome = 0) {
+ return mountWithContext(app => app.route('/', authHookRouter), { supabase: fakeSupabase([]), redis: null, rateLimitRedis: claimRedis(outcome) });
+}
+
+async function postHook(app: ReturnType<typeof mount>, payload: unknown, headers?: Record<string, string>, env: Partial<Env> = ENV) {
+ const body = JSON.stringify(payload);
+ const response = await callRoute(app, 'POST', '/auth/email-hook', { json: body, headers: headers ?? await signedHeaders(body), env });
+ return { status: response.status, body: JSON.parse(response.body) as unknown };
+}
+
+describe('Supabase Auth email hook route', () => {
+ test('a signed request sends the email and answers an empty object', async () => {
+ quietLogs();
+ fetchMock = installFetch(() => reply({ id: 'email-1' }));
+ assert.deepEqual(await postHook(mount(), signupPayload()), { status: 200, body: {} });
+ assert.equal(fetchMock.requests.length, 1);
+ assert.equal((fetchMock.requests[0].headers as Record<string, string>)['Idempotency-Key'], 'msg_1-0');
+ });
+
+ test('failures use the hook error shape, so Supabase shows the message on the sign-up form', async () => {
+ quietLogs();
+ fetchMock = installFetch(() => reply({ id: 'email-1' }));
+ assert.deepEqual(await postHook(mount(1), signupPayload()), { status: 429, body: { error: { http_code: 429, message: DAILY_LIMIT_MESSAGE } } });
+ assert.equal(fetchMock.requests.length, 0);
+
+ const unsigned = await postHook(mount(), signupPayload(), { 'webhook-id': 'msg_1', 'webhook-timestamp': '1', 'webhook-signature': 'v1,abc' });
+ assert.deepEqual(unsigned, { status: 401, body: { error: { http_code: 401, message: 'The hook signature is missing, invalid or expired' } } });
+
+ const malformed = await postHook(mount(), { user: {}, email_data: { email_action_type: 'signup' } });
+ assert.deepEqual(malformed, { status: 400, body: { error: { http_code: 400, message: 'The hook payload has no user email' } } });
+
+ const { SEND_EMAIL_HOOK_SECRET: _secret, ...withoutSecret } = ENV;
+ const notConfigured = await postHook(mount(), signupPayload(), undefined, withoutSecret);
+ assert.equal(notConfigured.status, 503);
+ });
+
+ test('in the full app the hook is public, and an unsigned call never reaches Resend', async () => {
+ quietLogs();
+ fetchMock = installFetch(() => reply({ id: 'email-1' }));
+ const response = await createApp().request('/api/auth/email-hook', {
+ method: 'POST',
+ body: JSON.stringify(signupPayload()),
+ headers: { 'Content-Type': 'application/json' },
+ }, ENV);
+ assert.equal(response.status, 401);
+ assert.deepEqual(await response.json(), { error: { http_code: 401, message: 'The hook signature is missing, invalid or expired' } });
+ assert.equal(fetchMock.requests.length, 0);
+ });
+});
diff --git a/backend/tests/services/authEmailService.test.ts b/backend/tests/services/authEmailService.test.ts
new file mode 100644
index 0000000..6c5e32c
--- /dev/null
+++ b/backend/tests/services/authEmailService.test.ts
@@ -0,0 +1,124 @@
+import { test, afterEach, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import { createAuthEmailService, DAILY_LIMIT_MESSAGE, RECIPIENT_DAILY_LIMIT, RECIPIENT_LIMIT_MESSAGE } from '../../services/authEmailService.ts';
+import { readConfig } from '../../lib/config.ts';
+import { createLogger } from '../../lib/logger.ts';
+import { NotConfiguredError, RateLimitedError, UpstreamError } from '../../lib/errors.ts';
+import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock } from '../fixtures/fakeFetch.ts';
+import { hook } from '../fixtures/authHook.ts';
+import type { EmailClaim, EmailClaimRequest, EmailQuotaRepository } from '../../repositories/emailQuotaRepository.ts';
+import type { Env } from '../../types/env.ts';
+
+const EMAIL_ENV: Partial<Env> = {
+ SUPABASE_URL: 'https://project.supabase.co',
+ RESEND_API_KEY: 're_test',
+ EMAIL_FROM: 'Twiligent <[email protected]>',
+};
+
+let fetchMock: FetchMock | null = null;
+let logLines: Record<string, unknown>[] = [];
+
+afterEach(() => {
+ fetchMock?.restore();
+ fetchMock = null;
+ mock.restoreAll();
+});
+
+function quotaAnswering(...outcomes: EmailClaim[]): EmailQuotaRepository & { claims: EmailClaimRequest[] } {
+ const claims: EmailClaimRequest[] = [];
+ return {
+ claims,
+ async claim(request) {
+ claims.push(request);
+ return outcomes[claims.length - 1] ?? 'claimed';
+ },
+ };
+}
+
+function service(quota: EmailQuotaRepository, env: Partial<Env> = EMAIL_ENV) {
+ logLines = [];
+ for (const method of ['log', 'warn', 'error'] as const) {
+ mock.method(console, method, (line: string) => logLines.push(JSON.parse(line) as Record<string, unknown>));
+ }
+ const context = { requestId: 'req-1', signal: new AbortController().signal, log: createLogger({ requestId: 'req-1' }) };
+ return createAuthEmailService({ quota, config: readConfig(env as Env), context, now: () => new Date('2026-10-14T23:59:00Z') });
+}
+
+test('a code email is counted against the UTC day, then sent through Resend with the webhook id as idempotency key', async () => {
+ fetchMock = installFetch(() => reply({ id: 'email-1' }));
+ const quota = quotaAnswering();
+ await service(quota).send(hook(), 'msg_1');
+
+ assert.deepEqual(quota.claims, [{ recipient: '[email protected]', day: '2026-10-14', dailyLimit: 100, recipientLimit: RECIPIENT_DAILY_LIMIT }]);
+ const [request] = fetchMock.requests;
+ assert.equal(request.url, 'https://api.resend.com/emails');
+ assert.deepEqual(request.headers, { 'Authorization': 'Bearer re_test', 'Content-Type': 'application/json', 'Idempotency-Key': 'msg_1-0' });
+ const body = JSON.parse(request.body ?? '{}') as Record<string, unknown>;
+ assert.deepEqual([body.from, body.to, body.subject], ['Twiligent <[email protected]>', ['[email protected]'], 'Your Twiligent verification code']);
+ assert.deepEqual(logLines.map(line => line.message), ['auth email sent']);
+});
+
+test('EMAIL_DAILY_LIMIT sets the daily cap', async () => {
+ fetchMock = installFetch(() => reply({ id: 'email-1' }));
+ const quota = quotaAnswering();
+ await service(quota, { ...EMAIL_ENV, EMAIL_DAILY_LIMIT: '250' }).send(hook(), 'msg_1');
+ assert.equal(quota.claims[0].dailyLimit, 250);
+});
+
+test('past the daily cap nothing is sent and the error tells the person to use Google', async () => {
+ fetchMock = installFetch(() => reply({ id: 'email-1' }));
+ await assert.rejects(service(quotaAnswering('daily_limit')).send(hook(), 'msg_1'), (err: unknown) => {
+ assert.ok(err instanceof RateLimitedError);
+ assert.equal(err.message, DAILY_LIMIT_MESSAGE);
+ return true;
+ });
+ assert.equal(fetchMock.requests.length, 0);
+});
+
+test('past the per-address cap the error asks for the latest code', async () => {
+ fetchMock = installFetch(() => reply({ id: 'email-1' }));
+ await assert.rejects(service(quotaAnswering('recipient_limit')).send(hook(), 'msg_1'), { message: RECIPIENT_LIMIT_MESSAGE });
+ assert.equal(fetchMock.requests.length, 0);
+});
+
+test('Resend\'s own quota errors give the same Google message; other Resend errors stay upstream errors', async () => {
+ fetchMock = installFetch(() => reply({ name: 'daily_quota_exceeded', message: 'You have reached your daily email sending quota.' }, 429));
+ await assert.rejects(service(quotaAnswering()).send(hook(), 'msg_1'), { message: DAILY_LIMIT_MESSAGE });
+ fetchMock.restore();
+
+ fetchMock = installFetch(() => reply({ name: 'validation_error', message: 'The from address domain is not verified.' }, 403));
+ await assert.rejects(service(quotaAnswering()).send(hook(), 'msg_1'), (err: unknown) => {
+ assert.ok(err instanceof UpstreamError);
+ assert.equal(err.message, 'Resend could not send the email: The from address domain is not verified.');
+ return true;
+ });
+});
+
+test('without Redis the email still goes out, and the missing counter is logged', async () => {
+ fetchMock = installFetch(() => reply({ id: 'email-1' }));
+ await service(quotaAnswering('unknown')).send(hook(), 'msg_1');
+ assert.equal(fetchMock.requests.length, 1);
+ assert.deepEqual(logLines.map(line => line.message), ['email counter unavailable', 'auth email sent']);
+});
+
+test('a notice past a cap is skipped instead of failing the change it reports', async () => {
+ fetchMock = installFetch(() => reply({ id: 'email-1' }));
+ await service(quotaAnswering('daily_limit')).send(hook({ action: 'password_changed_notification', token: '' }), 'msg_1');
+ assert.equal(fetchMock.requests.length, 0);
+ assert.deepEqual(logLines.map(line => [line.message, line.reason]), [['auth email skipped', 'limit reached'], ['auth email sent', undefined]]);
+});
+
+test('Secure Email Change sends two emails with their own idempotency keys', async () => {
+ fetchMock = installFetch(() => reply({ id: 'email-1' }));
+ const change = hook({ action: 'email_change', email: '[email protected]', newEmail: '[email protected]', token: '111111', tokenNew: '222222', tokenHashNew: 'h2' });
+ await service(quotaAnswering()).send(change, 'msg_9');
+ assert.deepEqual(fetchMock.requests.map(request => (request.headers as Record<string, string>)['Idempotency-Key']), ['msg_9-0', 'msg_9-1']);
+});
+
+test('an unknown action sends nothing, and missing Resend secrets are a configuration error', async () => {
+ fetchMock = installFetch(() => reply({ id: 'email-1' }));
+ await service(quotaAnswering()).send(hook({ action: 'something_new' }), 'msg_1');
+ assert.equal(fetchMock.requests.length, 0);
+ await assert.rejects(service(quotaAnswering(), { SUPABASE_URL: 'https://project.supabase.co' }).send(hook(), 'msg_1'), NotConfiguredError);
+});
diff --git a/backend/tests/services/email/authEmails.test.ts b/backend/tests/services/email/authEmails.test.ts
new file mode 100644
index 0000000..3321c57
--- /dev/null
+++ b/backend/tests/services/email/authEmails.test.ts
@@ -0,0 +1,57 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { composeAuthEmails } from '../../../services/email/authEmails.ts';
+import { hook } from '../../fixtures/authHook.ts';
+
+const SUPABASE_URL = 'https://project.supabase.co';
+
+test('a sign-up email carries the code and a link to Supabase Auth\'s verify endpoint', () => {
+ const [email, ...rest] = composeAuthEmails(hook(), SUPABASE_URL);
+ assert.equal(rest.length, 0);
+ assert.equal(email.to, '[email protected]');
+ assert.equal(email.subject, 'Your Twiligent verification code');
+ assert.equal(email.notice, false);
+ const link = 'https://project.supabase.co/auth/v1/verify?token=hash-abc&type=signup&redirect_to=https%3A%2F%2Fapp.example.com%2F';
+ assert.ok(email.text.includes('\n123456\n'));
+ assert.ok(email.text.includes(link));
+ assert.ok(email.html.includes('>123456<'));
+ assert.ok(email.html.includes(link.replace(/&/g, '&amp;')));
+});
+
+test('without a redirect the link leaves redirect_to out, and without a hash there is no link', () => {
+ const [noRedirect] = composeAuthEmails(hook({ action: 'recovery', redirectTo: '' }), SUPABASE_URL);
+ assert.ok(noRedirect.text.includes('verify?token=hash-abc&type=recovery\n'));
+ const [reauth] = composeAuthEmails(hook({ action: 'reauthentication', tokenHash: '' }), SUPABASE_URL);
+ assert.equal(reauth.text.includes('http'), false);
+ assert.equal(reauth.subject, 'Your Twiligent confirmation code');
+});
+
+test('values from the payload are escaped in the HTML', () => {
+ const [email] = composeAuthEmails(hook({ action: 'email_change', email: '[email protected]', newEmail: '<b>@example.com', token: '111111', tokenNew: '222222', tokenHashNew: 'h"1' }), SUPABASE_URL);
+ assert.ok(email.html.includes('&lt;b&gt;@example.com'));
+ assert.equal(email.html.includes('<b>@'), false);
+ assert.ok(email.html.includes('token=h%221'));
+});
+
+test('Secure Email Change sends one code to each address, pairing the hashes the way Supabase names them', () => {
+ const emails = composeAuthEmails(hook({
+ action: 'email_change', email: '[email protected]', newEmail: '[email protected]',
+ token: '111111', tokenHash: 'hash-for-new', tokenNew: '222222', tokenHashNew: 'hash-for-current',
+ }), SUPABASE_URL);
+ assert.deepEqual(emails.map(email => email.to), ['[email protected]', '[email protected]']);
+ assert.ok(emails[0].text.includes('111111') && emails[0].text.includes('token=hash-for-current'));
+ assert.ok(emails[1].text.includes('222222') && emails[1].text.includes('token=hash-for-new'));
+});
+
+test('an email change without Secure Email Change sends one email to the new address', () => {
+ const emails = composeAuthEmails(hook({ action: 'email_change', email: '[email protected]', newEmail: '[email protected]', token: '333333' }), SUPABASE_URL);
+ assert.deepEqual(emails.map(email => [email.to, email.text.includes('333333')]), [['[email protected]', true]]);
+});
+
+test('a notification is a notice without a code, and an unknown action or a missing code sends nothing', () => {
+ const [notice] = composeAuthEmails(hook({ action: 'password_changed_notification', token: '', tokenHash: '' }), SUPABASE_URL);
+ assert.equal(notice.notice, true);
+ assert.ok(notice.text.startsWith('The password for your Twiligent account was changed.'));
+ assert.deepEqual(composeAuthEmails(hook({ action: 'something_new' }), SUPABASE_URL), []);
+ assert.deepEqual(composeAuthEmails(hook({ token: '' }), SUPABASE_URL), []);
+});
diff --git a/backend/tests/validators/authHookValidators.test.ts b/backend/tests/validators/authHookValidators.test.ts
new file mode 100644
index 0000000..67ec03a
--- /dev/null
+++ b/backend/tests/validators/authHookValidators.test.ts
@@ -0,0 +1,35 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { parseAuthEmailHook } from '../../validators/authHookValidators.ts';
+import { ValidationError } from '../../lib/errors.ts';
+import { signupPayload } from '../fixtures/authHook.ts';
+
+test('reads the user and email data Supabase sends', () => {
+ const payload = signupPayload();
+ (payload.user as Record<string, unknown>).new_email = '[email protected]';
+ assert.deepEqual(parseAuthEmailHook(payload), {
+ email: '[email protected]',
+ newEmail: '[email protected]',
+ action: 'signup',
+ token: '123456',
+ tokenHash: 'hash-abc',
+ tokenNew: '',
+ tokenHashNew: '',
+ redirectTo: 'https://app.example.com/',
+ siteUrl: 'https://app.example.com',
+ });
+});
+
+test('optional fields default to empty and a blank new email counts as none', () => {
+ const parsed = parseAuthEmailHook({ user: { email: '[email protected]', new_email: '' }, email_data: { email_action_type: 'password_changed_notification' } });
+ assert.equal(parsed.newEmail, undefined);
+ assert.equal(parsed.token, '');
+ assert.equal(parsed.redirectTo, '');
+});
+
+test('a payload without a user email, an email action or the two objects is a validation error', () => {
+ assert.throws(() => parseAuthEmailHook({ email_data: {} }), ValidationError);
+ assert.throws(() => parseAuthEmailHook({ user: {}, email_data: { email_action_type: 'signup' } }), /no user email/);
+ assert.throws(() => parseAuthEmailHook({ user: { email: '[email protected]' }, email_data: {} }), /no email action/);
+ assert.throws(() => parseAuthEmailHook({ user: { email: '[email protected]' }, email_data: { email_action_type: 'signup', token: 5 } }), /token must be text/);
+});
diff --git a/backend/types/authHook.ts b/backend/types/authHook.ts
new file mode 100644
index 0000000..9d3b75b
--- /dev/null
+++ b/backend/types/authHook.ts
@@ -0,0 +1,24 @@
+// what Supabase Auth's Send Email hook sends, after validators/authHookValidators.ts has read it
+export interface AuthEmailHook {
+ email: string;
+ // set on email_change: the address the user is moving to
+ newEmail: string | undefined;
+ // signup, recovery, magiclink, invite, email_change, email, reauthentication or a *_notification
+ action: string;
+ // the 6-digit code; empty for notifications
+ token: string;
+ tokenHash: string;
+ // on email_change with Secure Email Change on, the second code and hash
+ tokenNew: string;
+ tokenHashNew: string;
+ redirectTo: string;
+ siteUrl: string;
+}
+
+// the error body Supabase Auth reads from a hook; it passes the message to the client
+export interface AuthHookFailure {
+ error: {
+ http_code: number;
+ message: string;
+ };
+}
diff --git a/backend/types/env.ts b/backend/types/env.ts
index a957ef1..1df22fb 100644
--- a/backend/types/env.ts
+++ b/backend/types/env.ts
@@ -14,4 +14,11 @@ export interface Env {
ALLOWED_ORIGINS?: string;
UPSTASH_REDIS_REST_URL?: string;
UPSTASH_REDIS_REST_TOKEN?: string;
+ // Supabase Auth's Send Email hook: the hook secret (v1,whsec_...) and the Resend account that delivers the emails
+ SEND_EMAIL_HOOK_SECRET?: string;
+ RESEND_API_KEY?: string;
+ // the sender, such as "Twiligent <[email protected]>", on a domain verified in Resend
+ EMAIL_FROM?: string;
+ // emails a day across all users; defaults to 100, Resend's free daily quota
+ EMAIL_DAILY_LIMIT?: string;
}
diff --git a/backend/validators/authHookValidators.ts b/backend/validators/authHookValidators.ts
new file mode 100644
index 0000000..51b9ead
--- /dev/null
+++ b/backend/validators/authHookValidators.ts
@@ -0,0 +1,27 @@
+import { ValidationError } from '../lib/errors.ts';
+import { isObject, optionalString, requiredString } from './fields.ts';
+import type { Fields } from './fields.ts';
+import type { AuthEmailHook } from '../types/authHook.ts';
+
+function objectField(fields: Fields, name: string): Fields {
+ const value = fields[name];
+ if (!isObject(value)) throw new ValidationError(`${name} must be an object`);
+ return value;
+}
+
+// the signature is already checked, so a malformed payload means a Supabase change this Worker does not know yet
+export function parseAuthEmailHook(body: Fields): AuthEmailHook {
+ const user = objectField(body, 'user');
+ const data = objectField(body, 'email_data');
+ return {
+ email: requiredString(user, 'email', 'The hook payload has no user email'),
+ newEmail: optionalString(user, 'new_email') || undefined,
+ action: requiredString(data, 'email_action_type', 'The hook payload has no email action'),
+ token: optionalString(data, 'token') ?? '',
+ tokenHash: optionalString(data, 'token_hash') ?? '',
+ tokenNew: optionalString(data, 'token_new') ?? '',
+ tokenHashNew: optionalString(data, 'token_hash_new') ?? '',
+ redirectTo: optionalString(data, 'redirect_to') ?? '',
+ siteUrl: optionalString(data, 'site_url') ?? '',
+ };
+}