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 | 1x 1x 1x 1x 113x 63x 63x 61x 9x 9x 52x 52x 52x 50x 48x 48x 48x 2x 48x 48x 1x 68x 68x 64x 64x 1x 1x 63x 63x 1x 45x 45x 45x 41x 41x 41x 1x 1x 40x 40x 39x 9x 30x 30x 30x 2x 2x 28x 28x 28x 21x 21x 21x 6x 15x 15x 24x 14x 1x 1x 1x 22x 22x 14x 14x 14x 14x 10x 10x 9x 1x 1x 22x 22x 1x 1x 1x 1x 4x 4x 2x 1x 1x | /**
* Partner login (F-21).
*
* WhatsApp OTP against `partners`, with open self-registration. No Better Auth, no user row — see
* lib/rrm/partner-session.ts for why, and for the token and OTP mechanics.
*
* The one rule that shapes every handler here: **request-otp always answers
* `{ok:true}`**. Unknown number, malformed number, opted-out number, rate
* limited, WhatsApp down — same body, same 200. Anything else turns a public
* endpoint into a "is this agent registered with Interioring" lookup, which is
* both a competitor's list and a phishing script's targeting file. The send
* itself goes through `waitUntil` for the same reason: an awaited WhatsApp call
* would make a known number measurably slower than an unknown one, and a
* stopwatch is as good as an error message.
*
* Responses are the bare shapes of the partner contract (`{ok:true}`,
* `{error:"..."}`), not the `success()`/`handleError()` envelope used by the
* admin and marketplace routers.
*
* Mounted at `/api/partner/auth`. Requires `contextMiddleware` (for `dal`)
* ahead of it. No session guard — these ARE the endpoints that create one.
*/
import type { Context } from "hono";
import { Hono } from "hono";
import { z } from "zod";
import type { Dal } from "../../dal";
import { PartnerAlreadyExistsError } from "../../dal/partners/partners.dal";
import {
PARTNER_CLOSINGS_BANDS,
PARTNER_LANGUAGES,
} from "../../db/schema/enums";
import { sendWhatsAppOtp } from "../../lib/communication/whatsapp-otp";
import { logger } from "../../lib/logger";
import {
checkOtp,
clearOtp,
clearPartnerSessionCookie,
generateOtpCode,
mintPartnerSession,
OTP_LENGTH,
type OtpKv,
otpMaxRequests,
resolvePartnerSession,
setPartnerSessionCookie,
storeOtp,
takeOtpRateLimit,
} from "../../lib/rrm/partner-session";
import { flagRetroactiveSelfReferrals } from "../../services/partners/referral.service";
import { toProspectPhoneNorm } from "../../services/rrm/prospect-resolver.service";
type Env = {
Bindings: CloudflareBindings;
Variables: { dal: Dal };
};
const partnerAuth = new Hono<Env>();
const requestSchema = z.object({
// Format is not validated here. An unusable number gets the same `{ok:true}`
// as a valid unknown one — a 400 on a typo would separate the two.
phone: z.string().trim().min(1).max(32),
});
const verifySchema = z.object({
phone: z.string().trim().min(1).max(32),
code: z
.string()
.trim()
.regex(new RegExp(`^\\d{${OTP_LENGTH}}$`)),
/**
* Registration fields. Optional, because the SAME endpoint signs in a
* returning partner and enrols a new one — and the client cannot know which
* it is doing without asking us first, which would be an oracle on whether a
* given number is a partner.
*
* So the client sends the code alone; a 409 `registration_required` is how
* it learns to show the name field, and it retries with the same code. The
* partner is never asked to work out which flow they are in.
*/
name: z.string().trim().min(1).max(120).optional(),
firmName: z.string().trim().max(160).optional(),
closingsBand: z.enum(PARTNER_CLOSINGS_BANDS).optional(),
/**
* The version of the consent line the client showed. Not `z.literal`: a
* stale or mistyped version must not fail the whole parse, because that
* surfaces as `invalid_code` — a lie about which thing was wrong, and one
* that burns nothing but tells the partner to check their code. It is
* compared below, where a mismatch gets the same 409 as an absent one.
*/
consentVersion: z.string().trim().min(1).max(64).optional(),
});
/**
* What someone agrees to by creating a partner account here, versioned so
* "what were they actually told" is answerable years later (DPDP s.6).
*
* Dated, like the go form's `partners-v1-2026-08` — and DELIBERATELY a
* different string, because it names different words. The go form's version
* belongs to the text on that form; this one belongs to the line on the
* registration screen. Change the words in `apps/partner/src/lib/copy.ts`,
* change this, and change the copy there in the same edit.
*/
export const PARTNER_CONSENT_VERSION = "partner-app-v1-2026-09";
async function jsonBody(c: Context<Env>): Promise<unknown> {
return c.req.json().catch(() => null);
}
/**
* Everything after "the body parsed". Returns nothing in every branch — the
* caller's response does not depend on what happened in here.
*/
async function issueOtp(
c: Context<Env>,
kv: OtpKv,
rawPhone: string,
): Promise<void> {
const phoneNorm = toProspectPhoneNorm(rawPhone);
if (!phoneNorm) return;
// Before the D1 read, so an attacker cannot use this endpoint to hammer the
// prospects table either. The budget is spent whether or not the number is
// known, so the limiter itself cannot be probed as an oracle.
if (
!(await takeOtpRateLimit(
kv,
phoneNorm,
Date.now(),
otpMaxRequests(c.env.ENVIRONMENT),
))
) {
// Masked: the house convention logs prospect ids, not numbers, and this
// path runs for numbers we may have no relationship with at all.
logger.warn(
`[partner-auth] OTP rate limit hit for number ending ${phoneNorm.slice(-4)}`,
);
return;
}
// Open self-registration (owner decision, 30 Aug): an UNKNOWN number now
// gets a code, because that code is how it becomes a partner. What is still
// refused is a number that has asked us to stop.
//
// Two separate stop conditions, and both must hold:
// - a suspended partner (FR-F-7) — their session is dead, and issuing a
// fresh code would hand it straight back;
// - `do_not_contact` on an RRM prospect, which is an opt-out from a person
// we cold-contacted. It is a hard stop on outbound INCLUDING
// transactional sends, so it outranks their wish to log in; lifting it
// is an operator action.
const dal = c.get("dal");
const [partner, prospect] = await Promise.all([
dal.partners.findByPhone(phoneNorm),
dal.rrmProspects.findByPhone(phoneNorm),
]);
if (partner?.suspendedAt) return;
if (prospect?.doNotContact) return;
const code = generateOtpCode();
// Stored before the send is scheduled: the code must be redeemable the
// instant it lands on the handset.
await storeOtp(kv, phoneNorm, code);
const send = sendWhatsAppOtp(
c.env,
`+${phoneNorm}`,
code,
c.get("dal"),
).catch((err: unknown) => {
logger.error("[partner-auth] OTP send failed", err);
});
// `c.executionCtx` itself throws when unset (test harnesses), not just
// `.waitUntil` — so both the read and the call live inside the same try.
try {
c.executionCtx.waitUntil(send);
} catch {
/* executionCtx unavailable in tests; the promise still runs */
}
}
partnerAuth.post("/request-otp", async (c) => {
const parsed = requestSchema.safeParse(await jsonBody(c));
// A body that isn't `{phone: string}` is a client bug, not a phone number,
// so rejecting it reveals nothing about any prospect.
if (!parsed.success) return c.json({ error: "bad_request" }, 400);
const kv = c.env.KV_CACHE;
if (!kv) {
logger.error("[partner-auth] KV_CACHE binding missing — OTP login is down");
return c.json({ error: "unavailable" }, 503);
}
await issueOtp(c, kv, parsed.data.phone);
return c.json({ ok: true });
});
partnerAuth.post("/verify-otp", async (c) => {
// Every failure below is this identical 401: no code, expired, wrong,
// attempts exhausted, unknown number, opted out.
const rejected = () => c.json({ error: "invalid_code" }, 401);
const parsed = verifySchema.safeParse(await jsonBody(c));
if (!parsed.success) return rejected();
const kv = c.env.KV_CACHE;
const secret = c.env.RRM_TOKEN_SECRET;
if (!kv || !secret) {
logger.error("[partner-auth] KV_CACHE or RRM_TOKEN_SECRET missing");
return c.json({ error: "unavailable" }, 503);
}
const phoneNorm = toProspectPhoneNorm(parsed.data.phone);
if (!phoneNorm) return rejected();
if (
!(await checkOtp(
kv,
phoneNorm,
parsed.data.code,
Date.now(),
otpMaxRequests(c.env.ENVIRONMENT),
))
)
return rejected();
const dal = c.get("dal");
// Re-checked after the code matched: state may have changed in the five
// minutes since it was sent.
const [existing, prospect] = await Promise.all([
dal.partners.findByPhone(phoneNorm),
dal.rrmProspects.findByPhone(phoneNorm),
]);
if (existing?.suspendedAt || prospect?.doNotContact) {
await clearOtp(kv, phoneNorm);
return rejected();
}
let partner = existing;
let registered = false;
if (!partner) {
// REGISTRATION. A name is required to create one. A known prospect
// already gave us theirs on the go form, so they are not asked twice;
// an unknown number has to be, and the client may not have collected it
// yet — a returning partner is not asked for it. When it is absent we
// say so rather than inventing a placeholder, and the client shows the
// one extra field.
const name = parsed.data.name?.trim() || prospect?.name?.trim();
/*
* Consent, recorded on the ACCOUNT rather than one join away.
*
* A prospect who filled the go form already agreed, so that evidence is
* copied and they are not asked twice. Everyone else agrees here: a
* self-registered number we have never messaged, and a cold-lane
* prospect imported from a listing who never gave us a basis. The
* client sends the version of the line it showed them.
*
* A version we do not recognise counts as absent. This column is
* evidence of what someone was told, and a string a browser invented
* proves nothing — so it earns the same 409 and a retry with the line
* actually on the screen.
*/
const consent = prospect?.consentVersion
? {
consentVersion: prospect.consentVersion,
consentAt: prospect.consentAt,
}
: parsed.data.consentVersion === PARTNER_CONSENT_VERSION
? { consentVersion: PARTNER_CONSENT_VERSION, consentAt: new Date() }
: null;
if (!name || !consent) {
// The code is deliberately NOT burned on the way out. This 409 is an
// ASK, not a spend: the client could not have known to send a name or
// an acceptance —
// being told in advance would be the membership oracle this whole
// design refuses — so it collects one and retries with THIS SAME
// code. Clearing here dead-ends every registration on a 401, which
// is to say nobody can ever join.
return c.json({ error: "registration_required" }, 409);
}
try {
partner = await dal.partners.create({
phoneNorm,
name,
...consent,
// The body wins; what the go form collected is the fallback.
firmName:
parsed.data.firmName?.trim() || prospect?.firmName?.trim() || null,
closingsBand: parsed.data.closingsBand ?? null,
// The language they chose (or we detected) on the go form. The two
// enums are the same triple today; `find` rather than a cast so a
// value the partner column does not know falls to "en" instead of
// into the INSERT.
language: PARTNER_LANGUAGES.find((l) => l === prospect?.locale) ?? "en",
// The single column joining the two domains (DM-9). Set when this
// number was already a recruitment target, so the campaign can tell
// which of its prospects actually joined — and so a joined partner
// can be suppressed from further recruitment (FR-A-10).
prospectId: prospect?.id ?? null,
source: prospect ? "rrm_recruited" : "self_registered",
});
registered = true;
} catch (error) {
Iif (!(error instanceof PartnerAlreadyExistsError)) throw error;
// Two taps of the same code, racing. The unique index refused the
// second INSERT, which is the correct outcome — and the correct
// response is still "you are signed in", not an error, because the
// partner did nothing wrong.
partner = await dal.partners.findByPhone(phoneNorm);
Iif (!partner) throw error;
}
}
// Single use — a code that has been spent cannot be replayed. AFTER the
// registration branch, not before it: the 409 above must leave the code
// live for the retry. A create() that throws something other than the
// unique-index race never reaches this line, so that code stays redeemable
// — the right side to fail on, since the partner has no account yet.
await clearOtp(kv, phoneNorm);
if (registered) {
// FR-F-2's retroactive half: someone may have referred this number
// before its owner enrolled. Flags for an operator, never auto-voids.
// Deliberately not awaited into the response path — a slow sweep must
// not delay a login, and a failed one must not fail it.
const sweep = flagRetroactiveSelfReferrals({ db: dal.db }, partner).catch(
(err: unknown) => {
logger.error(
"[partner-auth] retroactive self-referral sweep failed",
err,
);
},
);
try {
c.executionCtx.waitUntil(sweep);
} catch {
/* executionCtx unavailable in tests; the promise still runs */
}
// The conversion the campaign is measured on. `joined` is the top rank
// of the stage machine, so the move is legal from any non-terminal
// stage; a refusal (already joined — `do_not_contact` cannot reach
// here) is logged and nothing more. The partner has an account and a
// code that is now spent, so NOTHING on this path may fail the login.
if (prospect) {
try {
const staged = await dal.rrmProspects.setStage(prospect.id, "joined", {
actorType: "system",
reason: "partner_registered",
});
if (!staged.changed) {
logger.warn(
`[partner-auth] prospect ${prospect.id} not moved to joined: ${staged.reason}`,
);
}
} catch (err) {
logger.error(
`[partner-auth] failed to mark prospect ${prospect.id} joined`,
err,
);
}
}
}
setPartnerSessionCookie(c, await mintPartnerSession(partner.id, secret));
return c.json({ ok: true, name: partner.name, registered });
});
partnerAuth.post("/logout", (c) => {
// The token is stateless, so this only drops the browser's copy. Real
// revocation is `do_not_contact` / erasure, which every request re-checks.
clearPartnerSessionCookie(c);
return c.json({ ok: true });
});
partnerAuth.get("/session", async (c) => {
const partner = await resolvePartnerSession(c, c.get("dal"));
if (!partner) return c.json({ authenticated: false });
// A suspended partner is NOT authenticated — every guarded route refuses
// them — but the reason travels with the answer so the login screen can
// say what happened instead of looping them through a code they can never
// spend. FR-F-7: silent suspension is not permitted.
if (partner.suspendedAt) {
return c.json({
authenticated: false,
suspended: true,
suspendedReason: partner.suspendedReason ?? null,
});
}
return c.json({ authenticated: true, name: partner.name });
});
export default partnerAuth;
|