All files / lib/rrm partner-session.ts

98.19% Statements 109/111
94.36% Branches 67/71
100% Functions 19/19
100% Lines 94/94

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487                                                                                                            2x   2x                                 2x   2x 2x   2x         2x 2x                             2x     107x                       50x 49x 49x                         32x 32x   17x 17x 16x 16x   16x 16x   14x               22x                       10x                         2x                       10x   19x   10x 1x       9x                                                     21x   11x       11x 4x   7x       21x 4x   3x                   166x 159x         298x 298x   298x 298x 298x   298x       238x 238x 167x 167x   1x                                           159x 159x   159x       159x   144x 144x     144x                   62x         62x             25x         58x 58x 348x 58x                                                                     79x 79x 79x   63x 2x 2x         61x 3x   58x 58x       58x                                                               17x 17x   16x       16x                 10x                     2x         21x 21x   13x 13x     6x 6x                           7x 3x 3x           4x 4x 4x    
/**
 * Partner sessions and login OTPs (F-21).
 *
 * Partners are `partners` rows, not `users`. Better Auth is not involved and
 * must not be: a prospect has no user row, no password, and no tenant role, and
 * bending Better Auth around that would mean creating shadow users for people
 * who never signed up for the platform.
 *
 * So: an HMAC-signed cookie, and nothing else. The token is
 * `mintVisitToken("ps1|<prospectId>|<expEpochSeconds>")` — the visit-token
 * codec from ./token.ts reused verbatim rather than a second copy of the same
 * WebCrypto plumbing. The `ps1|` prefix is domain separation: a `?p=` visit
 * token decodes to a bare prospect id, which has no separator and is therefore
 * rejected here, and a session token decodes to something no `visit_token`
 * column ever held. Neither can be spent as the other.
 *
 * The cookie is a bearer token with a 30-day life and no server-side record, so
 * signature validity is only half the check: every request re-reads the
 * prospect and refuses a row that is gone or `do_not_contact`. That is what
 * makes revocation immediate instead of eventual — see `resolvePartnerSession`.
 *
 * WebCrypto only. No node:crypto.
 */
 
import type { Context, MiddlewareHandler } from "hono";
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
import type { Partner } from "../../dal/partners/partners.dal";
import type { RrmProspect } from "../../db/schema/rrm";
import { mintVisitToken, verifyVisitToken } from "./token";
 
/**
 * The three KV operations this module uses, and nothing else. `KVNamespace`
 * satisfies it; so does a Map-backed stub, which is why the tests need no cast.
 */
export type OtpKv = {
	get(key: string): Promise<string | null>;
	put(
		key: string,
		value: string,
		options?: { expirationTtl?: number },
	): Promise<void>;
	delete(key: string): Promise<void>;
};
 
/** The one lookup the session guard needs. `Dal` satisfies it. */
export type PartnerReader = {
	partners: { findById(id: string): Promise<Partner | null> };
};
 
export type ProspectReader = {
	rrmProspects: { findById(id: string): Promise<RrmProspect | undefined> };
};
 
/** Cookie name. Dotted to sit apart from Better Auth's `__Secure-` family. */
export const PARTNER_SESSION_COOKIE = "partner.session";
 
export const PARTNER_SESSION_TTL_SECONDS = 60 * 60 * 24 * 30;
 
/** Payload version + domain separator. Bump if the payload shape changes. */
/**
 * `pt1`, not `ps1`.
 *
 * The session used to carry an `rrm_prospects` id, because that was the only
 * partner-shaped row that existed. It now carries a `partners.id`. The prefix
 * changes with the meaning so an old cookie cannot be read as a new one — the
 * two id spaces are both UUIDs, so without this a stale `ps1` token would
 * resolve a prospect id against the partners table and either 401 confusingly
 * or, far worse, hit an unrelated row.
 *
 * Old cookies therefore fail closed and the partner signs in again. That costs
 * nothing today: the programme has no live partners, since the RRM Phase 1
 * gate has not passed.
 */
const SESSION_PREFIX = "pt1";
 
export const OTP_LENGTH = 6;
export const OTP_TTL_SECONDS = 300;
/** Wrong guesses allowed before the code is dead. */
export const OTP_MAX_ATTEMPTS = 5;
/**
 * OTP actions per phone per window — sends AND guesses, out of one budget (see
 * `checkOtp`). The number shares the platform login sender.
 */
export const OTP_MAX_REQUESTS = 5;
export const OTP_RATE_WINDOW_SECONDS = 60 * 60;
 
/**
 * The same budget, on a laptop, where it protects nothing.
 *
 * Five actions an hour is right for the public internet: the budget is shared
 * between sends and wrong guesses precisely so a resend cannot refill an
 * attacker's attempts. On localhost the only person it rate-limits is the
 * developer, and it bites fast — two logins with one mistyped code and the
 * hour is gone, with no way to wait it out except waiting.
 *
 * The limit is RAISED rather than removed, so the limiter still runs in local
 * and a bug in it still shows up there. Only `local`: `dev` is deployed, sends
 * real messages, and is reachable by anyone who knows the URL.
 */
export const OTP_MAX_REQUESTS_LOCAL = 1000;
 
export function otpMaxRequests(environment: string | undefined): number {
	return environment === "local" ? OTP_MAX_REQUESTS_LOCAL : OTP_MAX_REQUESTS;
}
 
// ─────────────────────────────────────────────────────────────────────────────
// Token
// ─────────────────────────────────────────────────────────────────────────────
 
export async function mintPartnerSession(
	partnerId: string,
	secret: string,
	nowMs: number = Date.now(),
): Promise<string> {
	if (!partnerId) throw new Error("mintPartnerSession: partnerId is required");
	const exp = Math.floor(nowMs / 1000) + PARTNER_SESSION_TTL_SECONDS;
	return mintVisitToken(`${SESSION_PREFIX}|${partnerId}|${exp}`, secret);
}
 
/**
 * Signature + expiry only. The caller MUST still confirm the prospect exists
 * and is contactable — `resolvePartnerSession` is the only thing that should
 * call this directly.
 */
export async function readPartnerSession(
	token: string | null | undefined,
	secret: string,
	nowMs: number = Date.now(),
): Promise<string | null> {
	const payload = await verifyVisitToken(token, secret);
	if (!payload) return null;
 
	const parts = payload.split("|");
	if (parts.length !== 3) return null;
	const [prefix, partnerId, rawExp] = parts;
	Iif (prefix !== SESSION_PREFIX || !partnerId) return null;
 
	const exp = Number(rawExp);
	if (!Number.isFinite(exp) || exp * 1000 <= nowMs) return null;
 
	return partnerId;
}
 
// ─────────────────────────────────────────────────────────────────────────────
// Cookie
// ─────────────────────────────────────────────────────────────────────────────
 
export function setPartnerSessionCookie(c: Context, token: string): void {
	setCookie(c, PARTNER_SESSION_COOKIE, token, {
		httpOnly: true,
		// Unconditional: browsers treat http://localhost as a secure context, so
		// this does not need an environment branch to work in dev.
		secure: true,
		sameSite: "Lax",
		path: "/",
		maxAge: PARTNER_SESSION_TTL_SECONDS,
	});
}
 
export function clearPartnerSessionCookie(c: Context): void {
	deleteCookie(c, PARTNER_SESSION_COOKIE, {
		httpOnly: true,
		secure: true,
		sameSite: "Lax",
		path: "/",
	});
}
 
// ─────────────────────────────────────────────────────────────────────────────
// Cross-origin writes
// ─────────────────────────────────────────────────────────────────────────────
 
/** Nothing changes on these, so they need no Origin. */
const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
 
/**
 * Exact match against `ALLOWED_ORIGINS`, and the same localhost fallback the
 * CORS middleware in index.ts uses when it is unset. Deliberately the same list
 * and the same matching: a second allowlist is a second thing to keep in sync,
 * and a guard stricter than the transport is a 403 nobody can reproduce.
 */
function originAllowed(
	origin: string,
	configured: string | undefined,
): boolean {
	const list = (configured ?? "")
		.split(",")
		.map((o) => o.trim())
		.filter(Boolean);
	if (list.length === 0)
		return (
			origin.startsWith("http://localhost:") ||
			origin.startsWith("http://127.0.0.1:")
		);
	return list.includes(origin);
}
 
/**
 * `null` when a state-changing request may proceed; otherwise the response to
 * send instead of running the handler.
 *
 * `SameSite=Lax` stops another SITE from riding this cookie. It does NOT stop
 * another ORIGIN under interioring.com, because cookies are scoped to the
 * registrable domain. So an HTML injection anywhere under the brand can serve
 * `<form method="post" enctype="text/plain">` at a partner endpoint whose field
 * NAME spells `{"upiId":"attacker@ybl"}` — a CORS-safelisted request: no
 * preflight, cookie attached, and the attacker never reads the reply, so the
 * CORS allowlist never enters into it. The prize is a partner's whole released
 * balance re-pointed at someone else's VPA for an operator to pay by hand.
 *
 * Two gates, and the second is the load-bearing one: the injected form's Origin
 * IS on the allowlist, so only the JSON content type stops it. A form post
 * cannot declare `application/json` — the three form encodings are all it has.
 *
 * Better Auth guards platform logins the same way, via `trustedOrigins`.
 *
 * Exported so the public auth lane (request-otp / verify-otp / logout, which
 * cannot sit behind a session guard) can adopt the same check rather than grow
 * a second copy of it.
 */
export function rejectCrossOriginWrite(c: Context): Response | null {
	if (SAFE_METHODS.has(c.req.method)) return null;
 
	const origin = c.req.header("Origin");
	// A missing Origin is refused rather than waved through: browsers always
	// send one on a state-changing request, so the only callers this costs are
	// non-browsers, of which the partner surface has none.
	if (!origin || !originAllowed(origin, c.env?.ALLOWED_ORIGINS))
		return c.json({ error: "forbidden_origin" }, 403);
 
	const mediaType = (c.req.header("Content-Type") ?? "")
		.split(";")[0]
		.trim()
		.toLowerCase();
	if (mediaType !== "application/json")
		return c.json({ error: "unsupported_media_type" }, 415);
 
	return null;
}
 
// ─────────────────────────────────────────────────────────────────────────────
// OTP storage (KV — these live for five minutes and must not touch D1)
// ─────────────────────────────────────────────────────────────────────────────
 
type OtpRecord = { code: string; exp: number; attempts: number };
type RateRecord = { count: number; resetAt: number };
 
const otpKey = (phoneNorm: string) => `rrm:partner:otp:${phoneNorm}`;
const rateKey = (phoneNorm: string) => `rrm:partner:otp:rl:${phoneNorm}`;
 
/** Uniform over 000000–999999. Rejection sampling, so no modulo bias. */
export function generateOtpCode(): string {
	// 2^32 - (2^32 % 1e6). Values at or above this would skew the low digits.
	const ceiling = 4_294_000_000;
	const buf = new Uint32Array(1);
	let value: number;
	do {
		crypto.getRandomValues(buf);
		value = buf[0];
	} while (value >= ceiling);
	return String(value % 1_000_000).padStart(OTP_LENGTH, "0");
}
 
async function readJson<T>(kv: OtpKv, key: string): Promise<T | null> {
	const raw = await kv.get(key);
	if (!raw) return null;
	try {
		return JSON.parse(raw) as T;
	} catch {
		return null;
	}
}
 
/**
 * Returns false when this phone has spent its window.
 *
 * The window is enforced from the stored `resetAt`, not from KV's TTL — TTL is
 * garbage collection, and a limit that only exists as an expiry cannot be
 * tested or reasoned about.
 *
 * ponytail: KV has no atomic increment, so concurrent requests can slip an
 * extra send or two past the cap. Same trade-off the existing rate-limit
 * middleware documents. Move to a Durable Object if the cap ever has to be
 * exact.
 */
export async function takeOtpRateLimit(
	kv: OtpKv,
	phoneNorm: string,
	nowMs: number = Date.now(),
	maxRequests: number = OTP_MAX_REQUESTS,
): Promise<boolean> {
	const key = rateKey(phoneNorm);
	const existing = await readJson<RateRecord>(kv, key);
	const record =
		existing && existing.resetAt > nowMs
			? existing
			: { count: 0, resetAt: nowMs + OTP_RATE_WINDOW_SECONDS * 1000 };
 
	if (record.count >= maxRequests) return false;
 
	record.count += 1;
	await kv.put(key, JSON.stringify(record), {
		expirationTtl: Math.max(60, Math.ceil((record.resetAt - nowMs) / 1000)),
	});
	return true;
}
 
/** One live code per phone. A resend replaces the previous code and its attempts. */
export async function storeOtp(
	kv: OtpKv,
	phoneNorm: string,
	code: string,
	nowMs: number = Date.now(),
): Promise<void> {
	const record: OtpRecord = {
		code,
		exp: nowMs + OTP_TTL_SECONDS * 1000,
		attempts: 0,
	};
	await kv.put(otpKey(phoneNorm), JSON.stringify(record), {
		// Floor of 60s is a KV constraint, not a policy choice; `exp` is the policy.
		expirationTtl: Math.max(60, OTP_TTL_SECONDS),
	});
}
 
export async function clearOtp(kv: OtpKv, phoneNorm: string): Promise<void> {
	await kv.delete(otpKey(phoneNorm));
}
 
/** Constant-time compare. Length is not secret; the digits are. */
function timingSafeEqual(a: string, b: string): boolean {
	Iif (a.length !== b.length) return false;
	let diff = 0;
	for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
	return diff === 0;
}
 
/**
 * True only for the live code. Every failure mode — no code, expired code,
 * wrong code, attempts exhausted, per-phone budget spent — returns the same
 * false, and the caller returns the same 401 for all of them.
 *
 * The attempt counter is written BEFORE the comparison, so a wrong guess can
 * never skip the increment by way of an early return.
 *
 * Each guess against a live code also spends one unit of that phone's OTP
 * budget — the same budget `request-otp` spends — so a successful login costs
 * two units (the send, then the guess) out of `OTP_MAX_REQUESTS` per hour.
 *
 * ponytail: KV has no atomic increment and serves reads from a ~60s edge
 * cache, so NEITHER `attempts` NOR the budget is exact — a burst landing
 * inside one cache window can get more guesses than either number suggests.
 * These are ceilings, not guarantees, and this comment is here so nobody reads
 * `OTP_MAX_ATTEMPTS` as one. What the budget adds over the attempt counter is
 * the part a race cannot win back: `storeOtp` resets `attempts` to 0, so a
 * resend used to hand an attacker a fresh five, whereas the budget is shared
 * with the send path and a resend spends it rather than refilling it. So a
 * spray is bounded per phone per hour instead of per code. Exactness needs a
 * counter that can increment atomically: a Durable Object, or the native
 * `RL_AUTH` rate-limit binding keyed on the phone instead of the IP. Do that
 * before this OTP guards anything larger than a payout request.
 */
export async function checkOtp(
	kv: OtpKv,
	phoneNorm: string,
	code: string,
	nowMs: number = Date.now(),
	maxRequests: number = OTP_MAX_REQUESTS,
): Promise<boolean> {
	const key = otpKey(phoneNorm);
	const record = await readJson<OtpRecord>(kv, key);
	if (!record) return false;
 
	if (record.exp <= nowMs || record.attempts >= OTP_MAX_ATTEMPTS) {
		await kv.delete(key);
		return false;
	}
 
	// Charged only once a live code exists, so verify-otp cannot be pointed at a
	// stranger's number to burn a budget they were never issued a code against.
	if (!(await takeOtpRateLimit(kv, phoneNorm, nowMs, maxRequests)))
		return false;
 
	record.attempts += 1;
	await kv.put(key, JSON.stringify(record), {
		expirationTtl: Math.max(60, Math.ceil((record.exp - nowMs) / 1000)),
	});
 
	return timingSafeEqual(record.code, code);
}
 
// ─────────────────────────────────────────────────────────────────────────────
// Session resolution
// ─────────────────────────────────────────────────────────────────────────────
 
export type PartnerSessionVariables = {
	partnerId: string;
	/**
	 * The row the middleware already had to fetch to authorise the request.
	 * Downstream handlers read it instead of issuing the same query again.
	 */
	partner: Partner;
};
 
/**
 * Cookie → partner, or null.
 *
 * The D1 read is not an optimisation to skip: a partner who has been erased or
 * flagged `do_not_contact` loses access on their next request, not in 30 days
 * when the signature happens to expire.
 *
 * `dal` is a parameter rather than a context variable so the function does not
 * pin an Env type — `Context` is invariant in its Variables, and a helper that
 * demanded one specific shape could not be called from a router that declared
 * its own.
 */
export async function resolvePartnerSession(
	c: Context,
	dal: PartnerReader,
): Promise<Partner | null> {
	const secret = c.env.RRM_TOKEN_SECRET as string | undefined;
	if (!secret) return null;
 
	const partnerId = await readPartnerSession(
		getCookie(c, PARTNER_SESSION_COOKIE),
		secret,
	);
	if (!partnerId) return null;
 
	// Re-read on EVERY request rather than trusting the token's claims. The
	// token is stateless, so this is the only place a suspension can take
	// effect — FR-F-7 requires a suspended partner's session to die, and
	// without this read it would live for the cookie's full 30 days.
	//
	// A SUSPENDED partner is returned, not discarded. The guard turns them into
	// a 403 carrying the reason; see requirePartnerSession for why.
	return (await dal.partners.findById(partnerId)) ?? null;
}
 
/**
 * Guard for every partner route other than the auth endpoints themselves.
 * Publishes `partnerId` and `partner` (see `PartnerSessionVariables`) on the
 * context. Requires `contextMiddleware` to have set `dal` first.
 *
 * Deliberately untyped in its Env so it mounts on any router without forcing
 * that router's `Variables` to match this file's.
 */
export const requirePartnerSession: MiddlewareHandler = async (c, next) => {
	// Before anything else: a cross-origin write is refused whether or not the
	// cookie is good, and costs no database read. Every state-changing partner
	// route sits behind this guard (index.ts mounts it on /me and /payouts), so
	// this one line covers the surface rather than one endpoint.
	const crossOrigin = rejectCrossOriginWrite(c);
	if (crossOrigin) return crossOrigin;
 
	const partner = await resolvePartnerSession(c, c.get("dal"));
	if (!partner) {
		// A cookie that no longer resolves is dead weight that would be replayed
		// on every subsequent request; drop it here.
		clearPartnerSessionCookie(c);
		return c.json({ error: "unauthenticated" }, 401);
	}
 
	// Suspension: 403 WITH THE REASON, not a bare 401.
	//
	// FR-F-7 says "silent suspension is not permitted" — the partner is told,
	// with a reason and a way to reply. The obvious implementation refuses a
	// suspended partner the way it refuses a bad cookie, and that quietly makes
	// the requirement unsatisfiable: every screen that could carry the
	// explanation sits behind this guard, so the partner is bounced to a login
	// page that cannot tell them anything and will not let them back in.
	//
	// The session is still dead — nothing below this line runs, no referral is
	// created, no payout requested. What changes is that the refusal says why.
	if (partner.suspendedAt) {
		clearPartnerSessionCookie(c);
		return c.json(
			{ error: "suspended", reason: partner.suspendedReason ?? null },
			403,
		);
	}
 
	c.set("partnerId", partner.id);
	c.set("partner", partner);
	await next();
};