feat(sharing): invite, accept, switch, revoke, renounce

The lifecycle surface under /api/account. An owner offers read access to
somebody already on the instance, the delegate accepts, either side ends
it, and a browser session points itself at a record it has been granted.

Ending a grant clears the acting-account carrier on every session of the
delegate pointing at that record, in the same transaction that stamps the
row. Split apart, a revocation would leave a browser inside a record it
can no longer read: every request refused, the banner still naming the
owner, nothing on screen able to explain it.

Revocation has no step-up and no confirmation step. Reducing access must
never be harder than granting it was.

Grant management is non-delegable by construction rather than by a check:
every route here resolves through bare requireAuth(), which refuses while
the caller is acting on another account, so no code path through them
runs as somebody else. The switch endpoint is the one actor surface, and
it is the way back out. A delegate already inside a record renounces
after switching out, one request, rather than the fail-closed default
growing an exception that later gets widened.

The state machine is not re-implemented anywhere: routes call the grant
module's predicate and its transitions, and the session carrier has one
writer.
This commit is contained in:
Marc-André Bombeck committed 2026-08-02 13:04:25 +02:00
1 parent 843c74c98c
commit 56447a9457
14 files changed
+2519 -1

No files matched your search

@@ -0,0 +1,121 @@
/**
* `POST /api/account/grants/[id]/accept` — the delegate accepts an invitation.
*
* The handshake exists because being handed read access to somebody's health
* record is not something to impose silently: an invitation confers nothing
* until the person named on it says yes, which is why `isGrantActive` fails a
* row with `acceptedAt IS NULL` and why this route is the only thing that can
* set it.
*
* The acceptance is also the consent record. `acceptedAt` and `acceptedIp` are
* stamped here and never anywhere else, on the same row that carries who
* offered the access and when it ended — one row, one history, no second
* receipt table to disagree with it.
*
* Not delegable: bare `requireAuth()` refuses under a switch, so nobody can
* accept an invitation while acting as somebody else. The delegate is the
* session user, never a body field, and `acceptGrant` puts that id in the
* `where` of a conditional update — so an invitation addressed to another
* account matches nothing and is refused as not-yours rather than accepted by
* the wrong person.
*/
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import { checkRateLimit } from "@/lib/rate-limit";
import { GRANT_PARTY_SELECT, toGrantView } from "@/lib/sharing/grant-view";
import { acceptGrant, GrantError } from "@/lib/sharing/grants";
type RouteParams = { params: Promise<{ id: string }> };
/**
* Thirty a minute. Accepting is a one-shot transition per row, so the only
* traffic this bounds is somebody guessing grant ids — which the conditional
* update already refuses; the limit just stops them doing it quickly.
*/
const ACCEPT_LIMIT = 30;
const ACCEPT_WINDOW_MS = 60 * 1000;
export const POST = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireAuth();
const rl = await checkRateLimit(
`sharing:accept:${user.id}`,
ACCEPT_LIMIT,
ACCEPT_WINDOW_MS,
);
if (!rl.allowed) {
return apiError("Too many attempts, try again later", 429);
}
const { id } = await params;
const ip = getClientIp(request);
try {
const grant = await acceptGrant({
grantId: id,
granteeId: user.id,
ip,
});
const grantor = await prisma.user.findUniqueOrThrow({
where: { id: grant.grantorId },
select: GRANT_PARTY_SELECT,
});
// Filed under the delegate, because accepting is the delegate's own act
// and `actorUserId` NULL means exactly that. The owner's side of this
// fact is not an audit row at all — it is `acceptedAt` on the grant,
// which their panel reads.
await auditLog("sharing.grant.accepted", {
userId: user.id,
details: { grantId: grant.id, grantorId: grant.grantorId },
ipAddress: ip,
}).catch(() => {});
annotate({
action: { name: "sharing.grant.accepted" },
meta: { grant_id: grant.id },
});
return apiSuccess(toGrantView(grant, grantor));
} catch (err) {
if (err instanceof GrantError) return acceptErrorResponse(err);
throw err;
}
},
);
/**
* Why the acceptance was refused.
*
* `not_found` and `not_grantee` deliberately answer the same 404: an
* invitation addressed to somebody else is, as far as this caller is
* concerned, not there. Confirming it exists would tell a stranger that a
* particular grant id is real and that two accounts share a record.
*/
function acceptErrorResponse(err: GrantError): Response {
switch (err.code) {
case "expired":
return apiError("That invitation has lapsed", 410, {
errorCode: "sharing.accept.expired",
});
case "already_revoked":
return apiError("That invitation was withdrawn", 410, {
errorCode: "sharing.accept.revoked",
});
case "not_pending":
return apiError("That invitation was already accepted", 409, {
errorCode: "sharing.accept.not_pending",
});
default:
return apiError("Invitation not found", 404, {
errorCode: "sharing.accept.not_found",
});
}
}
@@ -0,0 +1,93 @@
/**
* `POST /api/account/grants/[id]/renounce` — the delegate hands the access back.
*
* The same transition as the owner's revoke, attributed to the other party:
* `revokedBy = GRANTEE`, so the record can tell "she withdrew it" from "he
* decided he no longer wanted it". Two facts, one column, because they are
* answers to the same question and a trail that conflated them would misread
* an ordinary handover as a fallout.
*
* Its own verb rather than a second meaning for DELETE. The owner's revoke and
* the delegate's renunciation look identical in the database and are entirely
* different acts; letting one endpoint mean both would put a `revokedBy`
* decision inside a caller-identity check, which is exactly the sort of branch
* that gets simplified later by somebody who does not know why it was there.
*
* Frictionless for the same reason as revocation, and cleaned up in the same
* transaction: every session of theirs sitting inside that record leaves with
* the grant, including the ones on other devices.
*
* Not delegable: bare `requireAuth()`, so this cannot be done while acting as
* somebody else, and the delegate is the session user rather than a body field.
* That costs a browser already inside the record one extra request — switch
* out, then renounce — and the exchange is worth it. Grant management is the
* one surface where a delegate acting as somebody else must have no reach at
* all, and "except this one endpoint, which only ever reduces" is precisely
* the kind of exception that gets widened by somebody who reads the exception
* and not the reason. Ending the access is still one click; the client makes
* the switch-back call on the way.
*/
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import { GRANT_PARTY_SELECT, toGrantView } from "@/lib/sharing/grant-view";
import { GrantError, renounceGrantAndClearSwitch } from "@/lib/sharing/grants";
type RouteParams = { params: Promise<{ id: string }> };
export const POST = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireAuth();
const { id } = await params;
try {
const { grant, sessionsCleared } = await renounceGrantAndClearSwitch({
grantId: id,
granteeId: user.id,
});
const grantor = await prisma.user.findUniqueOrThrow({
where: { id: grant.grantorId },
select: GRANT_PARTY_SELECT,
});
await auditLog("sharing.grant.renounced", {
userId: user.id,
details: {
grantId: grant.id,
grantorId: grant.grantorId,
sessionsCleared,
},
ipAddress: getClientIp(request),
}).catch(() => {});
annotate({
action: { name: "sharing.grant.renounced" },
meta: { grant_id: grant.id, sessions_cleared: sessionsCleared },
});
return apiSuccess({
...toGrantView(grant, grantor),
sessionsCleared,
});
} catch (err) {
if (err instanceof GrantError) return renounceErrorResponse(err);
throw err;
}
},
);
function renounceErrorResponse(err: GrantError): Response {
if (err.code === "already_revoked") {
return apiError("That access has already ended", 409, {
errorCode: "sharing.renounce.already_ended",
});
}
return apiError("Grant not found", 404, {
errorCode: "sharing.renounce.not_found",
});
}
+97
View File
@@ -0,0 +1,97 @@
/**
* `DELETE /api/account/grants/[id]` — the owner withdraws access.
*
* **No step-up, no typed confirmation, no second factor, no ceremony.** That
* is a decision, not an omission: reducing access must never be harder than
* granting it was. Everything else in this product that guards a destructive
* act guards it because the act is hard to undo — this one is the undo. A
* person who wants their health record closed to somebody gets it closed on
* the first click, and if they change their mind the invitation costs one
* request to send again.
*
* Enforcement is the delegate's next request, not their next login: the
* resolver re-reads the grant every time, so seconds, not sessions. What this
* route adds on top is that the delegate's browser leaves too — the same
* transaction clears the acting-account carrier on every session of theirs
* pointing at this record, so a delegate sitting inside it lands back in their
* own account instead of on a wall of 403s under a banner still naming the
* owner.
*
* Despite the verb, nothing is deleted. `revokeGrant` stamps `revokedAt` and
* `revokedBy` on a row that stays, because "who had access, from when to when,
* and who ended it" is a question a deleted row cannot answer. DELETE is the
* right HTTP verb for "end this thing"; it is not a promise about storage.
*
* Not delegable: bare `requireAuth()` refuses under a switch, and the owner is
* the session user, so a delegate can neither revoke somebody else's grant nor
* hand their own to a third party.
*/
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiError, apiSuccess, getClientIp } from "@/lib/api-response";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import { GRANT_PARTY_SELECT, toGrantView } from "@/lib/sharing/grant-view";
import { GrantError, revokeGrantAndClearSwitch } from "@/lib/sharing/grants";
type RouteParams = { params: Promise<{ id: string }> };
export const DELETE = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireAuth();
const { id } = await params;
try {
const { grant, sessionsCleared } = await revokeGrantAndClearSwitch({
grantId: id,
grantorId: user.id,
});
const grantee = await prisma.user.findUniqueOrThrow({
where: { id: grant.granteeId },
select: GRANT_PARTY_SELECT,
});
await auditLog("sharing.grant.revoked", {
userId: user.id,
details: {
grantId: grant.id,
granteeId: grant.granteeId,
sessionsCleared,
},
ipAddress: getClientIp(request),
}).catch(() => {});
annotate({
action: { name: "sharing.grant.revoked" },
meta: { grant_id: grant.id, sessions_cleared: sessionsCleared },
});
return apiSuccess({
...toGrantView(grant, grantee),
sessionsCleared,
});
} catch (err) {
if (err instanceof GrantError) return revokeErrorResponse(err);
throw err;
}
},
);
/**
* A grant that is not this caller's to end reads as absent, for the same
* reason it does on the accept path: a distinguishable refusal would confirm
* that a given grant id exists.
*/
function revokeErrorResponse(err: GrantError): Response {
if (err.code === "already_revoked") {
return apiError("That access has already ended", 409, {
errorCode: "sharing.revoke.already_ended",
});
}
return apiError("Grant not found", 404, {
errorCode: "sharing.revoke.not_found",
});
}
+188
View File
@@ -0,0 +1,188 @@
/**
* `/api/account/grants` — the owner's side of account sharing.
*
* `GET` lists both directions at once: the grants this account has given, and
* the grants it has received. One endpoint rather than two because they are
* one question — "who can see my record, and whose can I see" — and because a
* client that has to call twice will eventually render half an answer.
*
* `POST` offers a grant to somebody already registered on this instance.
*
* **Neither is delegable, and that is structural.** Both resolve through bare
* `requireAuth()`, which refuses outright while the caller is acting on
* another account. So a delegate cannot invite anybody into the record they
* were given access to, cannot widen their own grant, and cannot pass it on:
* the route does not have a re-delegation check that somebody could soften, it
* has no code path that runs under a switch at all. The grantor is then taken
* from the session on top of that — never from the body — so even if the mode
* changed, the grant it wrote would be the caller's own record.
*
* On the enumeration question, stated plainly rather than left implicit: an
* invitation to an unknown identifier is refused with "no such account", which
* tells the inviter whether that person exists here. That is a disclosure, it
* is deliberate, and the alternative is worse — an invite that silently goes
* nowhere for a mistyped username leaves the owner staring at a pending row
* that will never be accepted. The instance is a household, the caller is
* already authenticated, and the rate limit below bounds how fast the surface
* can be walked.
*/
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import {
apiError,
apiSuccess,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import { checkRateLimit } from "@/lib/rate-limit";
import {
GRANT_PARTY_SELECT,
toGrantView,
type GrantParty,
} from "@/lib/sharing/grant-view";
import { GrantError, inviteGrant } from "@/lib/sharing/grants";
import { inviteGrantSchema } from "@/lib/validations/account-sharing";
/**
* Ten invitations an hour, per account.
*
* Generous for the household case (nobody invites their third family member
* twice a minute) and tight enough that the account-existence disclosure above
* cannot be turned into a user-directory dump.
*/
const INVITE_LIMIT = 10;
const INVITE_WINDOW_MS = 60 * 60 * 1000;
/** How much history a list call returns per direction. */
const MAX_GRANTS_PER_DIRECTION = 100;
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
annotate({ action: { name: "sharing.grants.list" } });
const [given, received] = await Promise.all([
prisma.accountGrant.findMany({
where: { grantorId: user.id },
orderBy: { createdAt: "desc" },
take: MAX_GRANTS_PER_DIRECTION,
include: { grantee: { select: GRANT_PARTY_SELECT } },
}),
prisma.accountGrant.findMany({
where: { granteeId: user.id },
orderBy: { createdAt: "desc" },
take: MAX_GRANTS_PER_DIRECTION,
include: { grantor: { select: GRANT_PARTY_SELECT } },
}),
]);
// Revoked and expired rows come back too. They are the consent record — "who
// had access, from when to when, and who ended it" is the question the table
// exists to answer, and a list that quietly dropped the ended rows would
// leave the panel unable to answer it. `state` says which are live.
const now = new Date();
return apiSuccess({
given: given.map((g) => toGrantView(g, g.grantee, now)),
received: received.map((g) => toGrantView(g, g.grantor, now)),
});
});
export const POST = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
const rl = await checkRateLimit(
`sharing:invite:${user.id}`,
INVITE_LIMIT,
INVITE_WINDOW_MS,
);
if (!rl.allowed) {
return apiError("Too many invitations, try again later", 429);
}
const { data: rawBody, error: jsonError } = await safeJson(request, {
maxBytes: 8 * 1024,
});
if (jsonError) return jsonError;
const parsed = inviteGrantSchema.safeParse(rawBody);
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422, {
errorCode: "sharing.invite.invalid",
});
}
const { identifier, expiresAt } = parsed.data;
// Either column, case-insensitively — the same lookup the login form does,
// so the name somebody signs in with is the name they can be invited by.
const invitee = await prisma.user.findFirst({
where: {
OR: [
{ email: { equals: identifier, mode: "insensitive" } },
{ username: { equals: identifier, mode: "insensitive" } },
],
},
select: GRANT_PARTY_SELECT,
});
if (!invitee) {
return apiError("No account with that name or e-mail", 404);
}
try {
// `inviteGrant` decides everything about the row: READ and only READ, the
// self-grant refusal, and the one-live-grant-per-pair rule the partial
// unique index backs. None of it is re-decided here.
const grant = await inviteGrant({
grantorId: user.id,
granteeId: invitee.id,
expiresAt: expiresAt ? new Date(expiresAt) : null,
});
await auditLog("sharing.grant.invited", {
userId: user.id,
details: { grantId: grant.id, granteeId: invitee.id },
ipAddress: getClientIp(request),
}).catch(() => {});
annotate({
action: { name: "sharing.grant.invited" },
meta: {
grant_id: grant.id,
expires: expiresAt !== null && expiresAt !== undefined,
},
});
return apiSuccess(toGrantView(grant, invitee as GrantParty), 201);
} catch (err) {
if (err instanceof GrantError) return grantErrorResponse(err);
throw err;
}
});
/**
* A refused transition, as an HTTP answer.
*
* The mapping lives here rather than inside the domain module because status
* codes are a transport concern and the state machine is not — it hands back a
* stable code and lets each consumer say what that means on its own wire.
*/
function grantErrorResponse(err: GrantError): Response {
switch (err.code) {
case "self_grant":
return apiError("An account cannot be shared with itself", 422, {
errorCode: "sharing.invite.self",
});
case "duplicate_live_grant":
return apiError("That account already has access", 409, {
errorCode: "sharing.invite.duplicate",
});
default:
return apiError("Invitation refused", 422, {
errorCode: "sharing.invite.refused",
});
}
}
+129
View File
@@ -0,0 +1,129 @@
/**
* `POST /api/account/switch` — point this browser at a record, or back at its own.
*
* Cookie transport only. The Bearer carrier is a per-request header, and that
* difference is not an inconsistency to be smoothed over: stamping a switch on
* a long-lived token would make the credential itself ambient authority, and
* the token has to keep meaning "this person" for as long as it exists. A
* Bearer caller reaching this endpoint has misunderstood its own transport, so
* it is refused rather than quietly ignored.
*
* An actor surface — `requireActorAuth()` — and it has to be, because this is
* the way back. Under the fail-closed default every route refuses while a
* switch is on; if this one did too, a switched browser could enter a record
* and never leave it, which turns a read-only convenience into a trap. So the
* mode is declared, and the declaration is narrow: the only row this handler
* touches is the caller's own session.
*
* What it writes is a SELECTOR, not a permission. The grant is validated here
* before the stamp so a client gets an immediate, honest refusal instead of a
* switch that appears to work and 403s on the next page — but the stamp itself
* authorises nothing, and the resolver re-checks the grant on every request
* that follows. A value stranded here by a revocation seconds later confers
* exactly nothing.
*/
import { NextRequest } from "next/server";
import {
apiHandler,
requireActorAuth,
SharingAccessDeniedError,
} from "@/lib/api-handler";
import {
apiError,
apiSuccess,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import { pointSessionAt } from "@/lib/sharing/acting-session";
import { findActiveGrant } from "@/lib/sharing/grants";
import { switchAccountSchema } from "@/lib/validations/account-sharing";
export const POST = apiHandler(async (request: NextRequest) => {
const auth = await requireActorAuth();
if (auth.authMethod !== "cookie") {
return apiError(
"Account switching is a browser-session feature; send the account selector header instead",
400,
{ errorCode: "sharing.switch.wrong_transport" },
);
}
const { data: rawBody, error: jsonError } = await safeJson(request, {
maxBytes: 4 * 1024,
});
if (jsonError) return jsonError;
const parsed = switchAccountSchema.safeParse(rawBody);
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422, {
errorCode: "sharing.switch.invalid",
});
}
const { accountId } = parsed.data;
const ip = getClientIp(request);
if (accountId === null) {
await pointSessionAt(auth.session.id, auth.user.id, null);
await auditLog("sharing.switch.off", {
userId: auth.user.id,
details: {},
ipAddress: ip,
}).catch(() => {});
annotate({ action: { name: "sharing.switch.off" } });
return apiSuccess({ actingAs: null });
}
// The same predicate the resolver uses, on the same table, with no second
// idea of "active" anywhere in this file. If this route decided for itself,
// it would drift from the resolver in exactly one direction: a switch the
// panel accepts and the next request refuses, or worse, the reverse.
const grant = await findActiveGrant({
grantorId: accountId,
granteeId: auth.user.id,
});
if (!grant) {
// The flat refusal, with no reason on the wire. An account that does not
// exist and an account that granted nothing are the same empty row from
// the same query, so a caller learns nothing about who has an account here.
await auditLog("sharing.access.denied", {
userId: auth.user.id,
details: { reason: "switch_no_active_grant", target: accountId },
ipAddress: ip,
}).catch(() => {});
throw new SharingAccessDeniedError();
}
const owner = await prisma.user.findUniqueOrThrow({
where: { id: grant.grantorId },
select: { id: true, username: true, displayName: true },
});
await pointSessionAt(auth.session.id, auth.user.id, owner.id);
await auditLog("sharing.switch.on", {
userId: auth.user.id,
details: { grantId: grant.id, grantorId: owner.id },
ipAddress: ip,
}).catch(() => {});
annotate({
action: { name: "sharing.switch.on" },
meta: { grant_id: grant.id },
});
return apiSuccess({
actingAs: {
accountId: owner.id,
username: owner.username,
displayName: owner.displayName,
access: grant.access,
},
});
});