phase-2: identity, from the landing hook to the profile screen
Flows A1 to A6 and E3 end to end. A visitor types a RUC on the landing page, sees their real filing dates, registers, verifies a six digit code, grants consent, completes a three step setup and lands on the first run screen, with the profile, consent and audit rows to show for it. API: public RUC lookup behind a token bucket (10/min/IP), the full /me surface (profile, dependents, consents, notification prefs, data export, account deletion), an append-only audit module that exports an insert and nothing else, and a PII module that is the only thing allowed near those tables. Deletion and consent revocation both freeze the account and drop every session, reusing better-auth's ban flag rather than adding a second notion of disabled. Nothing is destroyed yet: the purge is a job for phase 4. deadlineDigit is always derived server side, never accepted from the client. Web: landing with the RUC hook, registration, OTP verification, consent, the setup wizard, the profile screen with "Tus datos", and legal pages that ship as marked placeholders per COPY.md section 13. Money, Skeleton, Switch and EmptyState components added. The seed is now complete for identity: Maria at 4123456-1, filing digit 6 and day 19, with a dependant, consents and prefs; Carlos as an IVA-only company. Two real defects found by building the screens and fixed with tests: the OTP boxes dropped a digit because the handler fired effects inside a setState updater that React 19 invokes twice, and the switch knob rendered outside its track because translate-x-5.5 does not resolve. 232 vitest tests, 26 Playwright tests across mobile and desktop, coverage still 100% on the rules, typecheck and lint clean. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
80b10c958e
commit
0d7651b17c
@@ -1,19 +1,180 @@
|
||||
import {
|
||||
ConsentInput,
|
||||
DeleteAccountInput,
|
||||
DependentInput,
|
||||
NotificationPrefsInput,
|
||||
ProfileInput,
|
||||
} from '@impuestos/contracts';
|
||||
import { Hono } from 'hono';
|
||||
import { getProfile } from '../../modules/pii';
|
||||
import type { AppDeps, AppEnv } from '../context';
|
||||
import type { z } from 'zod';
|
||||
import { writeAudit } from '../../modules/audit';
|
||||
import {
|
||||
buildDataExport,
|
||||
createDependent,
|
||||
deactivateDependent,
|
||||
getNotificationPrefs,
|
||||
getProfile,
|
||||
listDependents,
|
||||
setConsent,
|
||||
softDeleteAccount,
|
||||
updateNotificationPrefs,
|
||||
upsertProfile,
|
||||
} from '../../modules/pii';
|
||||
import type { AppDeps, AppEnv, SessionUser } from '../context';
|
||||
import { HttpError } from '../errors';
|
||||
import { requireUser } from '../middleware';
|
||||
|
||||
export function meRoutes(deps: AppDeps): Hono<AppEnv> {
|
||||
const routes = new Hono<AppEnv>();
|
||||
const db = deps.handle.db;
|
||||
|
||||
// 404 until setup is complete: the client routes to onboarding (CONTRACTS.md section 3).
|
||||
routes.get('/profile', async (c) => {
|
||||
const user = requireUser(c);
|
||||
const profile = await getProfile(deps.handle.db, user.id);
|
||||
const profile = await getProfile(db, user.id);
|
||||
if (!profile) throw new HttpError('not_found');
|
||||
return c.json(profile);
|
||||
});
|
||||
|
||||
routes.put('/profile', async (c) => {
|
||||
const user = requireUser(c);
|
||||
const input = parse(ProfileInput, await body(c));
|
||||
|
||||
if (input.docType === 'ruc' && !input.ruc && !input.ci) {
|
||||
throw new HttpError('validation_error', { field: 'ruc' });
|
||||
}
|
||||
if (input.docType === 'ci' && !input.ci && !input.ruc) {
|
||||
throw new HttpError('validation_error', { field: 'ci' });
|
||||
}
|
||||
|
||||
const { profile, created } = await upsertProfile(db, user.id, input);
|
||||
await audit(c, deps, user, {
|
||||
action: created ? 'profile.create' : 'profile.update',
|
||||
resource: 'profiles',
|
||||
detail: { docType: profile.docType, taxpayerKind: profile.taxpayerKind },
|
||||
});
|
||||
return c.json(profile);
|
||||
});
|
||||
|
||||
routes.get('/dependents', async (c) => {
|
||||
const user = requireUser(c);
|
||||
return c.json(await listDependents(db, user.id));
|
||||
});
|
||||
|
||||
routes.post('/dependents', async (c) => {
|
||||
const user = requireUser(c);
|
||||
const dependent = await createDependent(db, user.id, parse(DependentInput, await body(c)));
|
||||
await audit(c, deps, user, {
|
||||
action: 'dependent.create',
|
||||
resource: `dependents/${dependent.id}`,
|
||||
});
|
||||
return c.json(dependent, 201);
|
||||
});
|
||||
|
||||
routes.delete('/dependents/:id', async (c) => {
|
||||
const user = requireUser(c);
|
||||
const id = c.req.param('id');
|
||||
if (!(await deactivateDependent(db, user.id, id))) throw new HttpError('not_found');
|
||||
await audit(c, deps, user, { action: 'dependent.delete', resource: `dependents/${id}` });
|
||||
return c.json({ ok: true } as const);
|
||||
});
|
||||
|
||||
/**
|
||||
* Revoking data processing consent is a withdrawal of the basis on which we hold the
|
||||
* data at all, so it freezes the account and drops every session, exactly like a
|
||||
* deletion (CONTRACTS.md section 3).
|
||||
*/
|
||||
routes.post('/consents', async (c) => {
|
||||
const user = requireUser(c);
|
||||
const input = parse(ConsentInput, await body(c));
|
||||
|
||||
await setConsent(db, user.id, input.kind, input.granted);
|
||||
await audit(c, deps, user, {
|
||||
action: input.granted ? 'consent.grant' : 'consent.revoke',
|
||||
resource: `consents/${input.kind}`,
|
||||
detail: { kind: input.kind },
|
||||
});
|
||||
|
||||
if (input.kind === 'data_processing' && !input.granted) {
|
||||
await softDeleteAccount(db, user.id, 'consent_revoked');
|
||||
}
|
||||
return c.json({ ok: true } as const);
|
||||
});
|
||||
|
||||
routes.get('/notification-prefs', async (c) => {
|
||||
const user = requireUser(c);
|
||||
return c.json(await getNotificationPrefs(db, user.id));
|
||||
});
|
||||
|
||||
routes.patch('/notification-prefs', async (c) => {
|
||||
const user = requireUser(c);
|
||||
const prefs = await updateNotificationPrefs(db, user.id, parse(NotificationPrefsInput, await body(c)));
|
||||
await audit(c, deps, user, {
|
||||
action: 'notification_prefs.update',
|
||||
resource: 'notification_prefs',
|
||||
});
|
||||
return c.json(prefs);
|
||||
});
|
||||
|
||||
routes.get('/data-export', async (c) => {
|
||||
const user = requireUser(c);
|
||||
const data = await buildDataExport(db, user.id);
|
||||
await audit(c, deps, user, { action: 'data.export', resource: 'data-export' });
|
||||
|
||||
const filename = `impuestos-datos-${new Date().toISOString().slice(0, 10)}.json`;
|
||||
c.header('content-disposition', `attachment; filename="${filename}"`);
|
||||
return c.json(data);
|
||||
});
|
||||
|
||||
routes.delete('/account', async (c) => {
|
||||
const user = requireUser(c);
|
||||
const input = parse(DeleteAccountInput, await body(c));
|
||||
|
||||
// Typing the email is the second confirmation. Compared case insensitively because
|
||||
// the keyboard on a phone will capitalise the first letter.
|
||||
if (input.confirmText.trim().toLowerCase() !== user.email.toLowerCase()) {
|
||||
throw new HttpError('validation_error', { field: 'confirmText' });
|
||||
}
|
||||
|
||||
await audit(c, deps, user, { action: 'account.delete', resource: 'user' });
|
||||
await softDeleteAccount(db, user.id, 'account_deleted');
|
||||
return c.json({ ok: true } as const);
|
||||
});
|
||||
|
||||
return routes;
|
||||
}
|
||||
|
||||
async function body(c: { req: { json: () => Promise<unknown> } }): Promise<unknown> {
|
||||
try {
|
||||
return await c.req.json();
|
||||
} catch {
|
||||
throw new HttpError('validation_error');
|
||||
}
|
||||
}
|
||||
|
||||
function parse<T>(schema: z.ZodType<T>, value: unknown): T {
|
||||
const result = schema.safeParse(value);
|
||||
if (!result.success) {
|
||||
const issue = result.error.issues[0];
|
||||
throw new HttpError('validation_error', {
|
||||
...(issue?.path.length ? { field: issue.path.join('.') } : {}),
|
||||
detail: result.error.issues,
|
||||
});
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
|
||||
function audit(
|
||||
c: { req: { header: (name: string) => string | undefined } },
|
||||
deps: AppDeps,
|
||||
user: SessionUser,
|
||||
entry: { action: Parameters<typeof writeAudit>[1]['action']; resource: string; detail?: Record<string, unknown> },
|
||||
): Promise<void> {
|
||||
return writeAudit(deps.handle.db, {
|
||||
actorUserId: user.id,
|
||||
actorRole: user.role,
|
||||
subjectUserId: user.id,
|
||||
ip: c.req.header('x-forwarded-for')?.split(',')[0]?.trim() ?? null,
|
||||
...entry,
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user