mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 15:42:24 +00:00
Merge pull request #705 from MBombeck/work/dw-b
Offer read or read-and-add when you invite somebody
This commit is contained in:
25 files changed
+867
-58
No files matched your search
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* `POST /api/account/grants` — the level a request carries is the level the row
|
||||
* gets.
|
||||
*
|
||||
* The assertion is deliberately on the WRITE the route performs rather than on
|
||||
* the JSON it answers with: a response echoing the request would pass either
|
||||
* way, and the failure this pins is the one where a field is validated,
|
||||
* annotated on, and then dropped on the way to the database. So every case
|
||||
* reads the `data` object handed to `accountGrant.create`.
|
||||
*
|
||||
* Where the default lives matters and is asserted here rather than assumed: an
|
||||
* omitted `access` becomes READ in the invite schema and nowhere else —
|
||||
* `inviteGrant` takes the level as a required argument. Move the default and
|
||||
* the third case below goes red.
|
||||
*
|
||||
* What this file cannot see: the browser. That the level a person picks on the
|
||||
* invitation form reaches this route at all is proven in
|
||||
* `e2e/account-sharing.spec.ts`, which reads the posted body — the component
|
||||
* test renders the control and stays green with the control wired to a
|
||||
* constant.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/api-handler", async () => {
|
||||
const actual =
|
||||
await vi.importActual<typeof import("@/lib/api-handler")>(
|
||||
"@/lib/api-handler",
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
apiHandler: <T extends (...args: never[]) => Promise<Response>>(h: T): T =>
|
||||
h,
|
||||
requireAuth: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
user: { findFirst: vi.fn() },
|
||||
accountGrant: { create: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/rate-limit", () => ({
|
||||
checkRateLimit: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ allowed: true, remaining: 9, resetAt: 0 }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
|
||||
import { POST } from "../route";
|
||||
import { requireAuth } from "@/lib/api-handler";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
const OWNER = { id: "owner-1" };
|
||||
const INVITEE = { id: "invitee-1", username: "housemate", displayName: null };
|
||||
|
||||
function request(body: Record<string, unknown>): NextRequest {
|
||||
return new NextRequest("http://localhost/api/account/grants", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
/** The `data` object the route's write reached the client with. */
|
||||
function writtenRow(): Record<string, unknown> {
|
||||
const calls = vi.mocked(prisma.accountGrant.create).mock.calls;
|
||||
expect(calls).toHaveLength(1);
|
||||
return (calls[0][0] as { data: Record<string, unknown> }).data;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(requireAuth).mockResolvedValue({
|
||||
user: OWNER,
|
||||
} as unknown as Awaited<ReturnType<typeof requireAuth>>);
|
||||
vi.mocked(prisma.user.findFirst).mockResolvedValue(
|
||||
INVITEE as never as Awaited<ReturnType<typeof prisma.user.findFirst>>,
|
||||
);
|
||||
vi.mocked(prisma.accountGrant.create).mockImplementation((async (args: {
|
||||
data: Record<string, unknown>;
|
||||
}) => ({
|
||||
id: "grant-1",
|
||||
grantorId: OWNER.id,
|
||||
granteeId: INVITEE.id,
|
||||
acceptedAt: null,
|
||||
revokedAt: null,
|
||||
revokedBy: null,
|
||||
lastUsedAt: null,
|
||||
expiresAt: null,
|
||||
...args.data,
|
||||
})) as never);
|
||||
});
|
||||
|
||||
describe("invitation access level", () => {
|
||||
it("stores WRITE when the invitation offers it", async () => {
|
||||
const res = await POST(
|
||||
request({ identifier: "housemate", access: "WRITE" }),
|
||||
);
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(writtenRow().access).toBe("WRITE");
|
||||
const body = (await res.json()) as { data: { access: string } };
|
||||
expect(body.data.access).toBe("WRITE");
|
||||
});
|
||||
|
||||
it("stores READ when the invitation offers it", async () => {
|
||||
const res = await POST(
|
||||
request({ identifier: "housemate", access: "READ" }),
|
||||
);
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(writtenRow().access).toBe("READ");
|
||||
});
|
||||
|
||||
it("mints READ for a client that does not send the field", async () => {
|
||||
// An older client's payload stays valid, and it stays NARROW. This is the
|
||||
// case that must never widen by accident.
|
||||
const res = await POST(request({ identifier: "housemate" }));
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(writtenRow().access).toBe("READ");
|
||||
});
|
||||
|
||||
it("refuses a level that is not one of the two, without writing a row", async () => {
|
||||
const res = await POST(
|
||||
request({ identifier: "housemate", access: "ADMIN" }),
|
||||
);
|
||||
|
||||
expect(res.status).toBe(422);
|
||||
expect(prisma.accountGrant.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("records the level on the audit row", async () => {
|
||||
// "Who was given what, and by whom" is the question this row answers. An
|
||||
// entry naming the invitation without its level answers half of it.
|
||||
await POST(request({ identifier: "housemate", access: "WRITE" }));
|
||||
|
||||
expect(auditLog).toHaveBeenCalledWith(
|
||||
"sharing.grant.invited",
|
||||
expect.objectContaining({
|
||||
userId: OWNER.id,
|
||||
details: expect.objectContaining({ access: "WRITE" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,10 @@
|
||||
* 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.
|
||||
* `POST` offers a grant to somebody already registered on this instance, at
|
||||
* the level the owner chose. There is no route that raises a live grant: the
|
||||
* level is settled when the invitation is written and the only way to a wider
|
||||
* one is a fresh invitation the delegate accepts again.
|
||||
*
|
||||
* **Neither is delegable, and that is structural.** Both resolve through bare
|
||||
* `requireAuth()`, which refuses outright while the caller is acting on
|
||||
@@ -111,7 +114,7 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
});
|
||||
}
|
||||
|
||||
const { identifier, expiresAt } = parsed.data;
|
||||
const { identifier, expiresAt, access } = 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.
|
||||
@@ -129,18 +132,30 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
}
|
||||
|
||||
try {
|
||||
// `inviteGrant` decides everything about the row: READ and only READ, the
|
||||
// `inviteGrant` decides everything about the row except the level: the
|
||||
// self-grant refusal, and the one-live-grant-per-pair rule the partial
|
||||
// unique index backs. None of it is re-decided here.
|
||||
// unique index backs. Neither is re-decided here. The level travels from
|
||||
// the parsed body, where the schema is the one place an omitted field
|
||||
// becomes READ, and it is fixed for the life of the row — the domain
|
||||
// module has no transition that raises it.
|
||||
const grant = await inviteGrant({
|
||||
grantorId: user.id,
|
||||
granteeId: invitee.id,
|
||||
access,
|
||||
expiresAt: expiresAt ? new Date(expiresAt) : null,
|
||||
});
|
||||
|
||||
// The level is on the audit row, not only in the response: "who was given
|
||||
// what, and by whom" is the question this row exists to answer, and an
|
||||
// entry that recorded the invitation without its level would answer half
|
||||
// of it.
|
||||
await auditLog("sharing.grant.invited", {
|
||||
userId: user.id,
|
||||
details: { grantId: grant.id, granteeId: invitee.id },
|
||||
details: {
|
||||
grantId: grant.id,
|
||||
granteeId: invitee.id,
|
||||
access: grant.access,
|
||||
},
|
||||
ipAddress: getClientIp(request),
|
||||
}).catch(() => {});
|
||||
|
||||
@@ -148,6 +163,7 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
action: { name: "sharing.grant.invited" },
|
||||
meta: {
|
||||
grant_id: grant.id,
|
||||
access: grant.access,
|
||||
expires: expiresAt !== null && expiresAt !== undefined,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* The access level, on the three screens that decide it.
|
||||
*
|
||||
* What an SSR render can prove, and what it cannot, stated up front because the
|
||||
* distinction is the reason this file is shaped the way it is. It can prove
|
||||
* that a control exists, that a sentence is on the page beside it, and that a
|
||||
* row states its level before the button that accepts it. It CANNOT prove that
|
||||
* the chosen level reaches the server: there is no click here, so the submit
|
||||
* path never runs, and every assertion below stays green with the form wired
|
||||
* back to a constant. That half is the browser journey's
|
||||
* (`e2e/account-sharing.spec.ts`, which reads the posted body), and the
|
||||
* database half is `src/app/api/account/grants/__tests__/`.
|
||||
*
|
||||
* The invitation copy is asserted by its promise rather than by its wording:
|
||||
* "cannot edit or delete" is the sentence somebody's expectation is set by, and
|
||||
* a rewrite that quietly drops it should fail here.
|
||||
*/
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import type { GrantList, GrantRow } from "@/lib/queries/use-account-grants";
|
||||
|
||||
const grantsRef: { value: GrantList } = { value: { given: [], received: [] } };
|
||||
|
||||
vi.mock("@/lib/queries/use-account-grants", async (importOriginal) => {
|
||||
const actual =
|
||||
await importOriginal<typeof import("@/lib/queries/use-account-grants")>();
|
||||
return {
|
||||
...actual,
|
||||
useInviteGrant: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useAccountGrants: () => ({
|
||||
data: grantsRef.value,
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
refetch: vi.fn(),
|
||||
}),
|
||||
useRecordActivity: () => ({
|
||||
data: undefined,
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
refetch: vi.fn(),
|
||||
}),
|
||||
useAcceptGrant: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useRenounceGrant: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useRevokeGrant: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/hooks/use-account-switch", () => ({
|
||||
useAccountSwitch: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
}));
|
||||
|
||||
import { GrantInviteCard } from "../grant-invite-card";
|
||||
import { GrantsReceivedCard } from "../grants-received-card";
|
||||
import { revokeBody } from "../grants-given-card";
|
||||
|
||||
function render(node: React.ReactNode): string {
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider initialLocale="en">{node}</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
const BASE: GrantRow = {
|
||||
id: "g1",
|
||||
account: { id: "acct-1", username: "housemate", displayName: "Jo" },
|
||||
access: "READ",
|
||||
state: "PENDING",
|
||||
invitedAt: "2026-01-02T10:00:00.000Z",
|
||||
acceptedAt: null,
|
||||
expiresAt: null,
|
||||
lastUsedAt: null,
|
||||
revokedAt: null,
|
||||
revokedBy: null,
|
||||
};
|
||||
|
||||
describe("offering a level", () => {
|
||||
it("offers both levels and preselects the narrower one", () => {
|
||||
const html = render(<GrantInviteCard />);
|
||||
expect(html).toContain('data-slot="grant-invite-access"');
|
||||
expect(html).toContain('data-access="READ"');
|
||||
expect(html).toContain('data-access="WRITE"');
|
||||
// The narrow level is the one somebody chooses their way out of.
|
||||
expect(html).toContain('data-access="READ" data-selected="true"');
|
||||
expect(html).toContain('data-access="WRITE" data-selected="false"');
|
||||
});
|
||||
|
||||
it("says what the wider level actually does, and what it does not", () => {
|
||||
const html = render(<GrantInviteCard />);
|
||||
// The thing a person reading "write access" gets wrong.
|
||||
expect(html).toContain("cannot edit or delete anything");
|
||||
expect(html).toContain("marking a dose as taken");
|
||||
// And the narrow option still says it is narrow.
|
||||
expect(html).toContain("They cannot add or change anything.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("accepting a level", () => {
|
||||
it("states the level and what accepting it means before the button", () => {
|
||||
grantsRef.value = {
|
||||
given: [],
|
||||
received: [{ ...BASE, access: "WRITE" }],
|
||||
};
|
||||
const html = render(<GrantsReceivedCard />);
|
||||
|
||||
expect(html).toContain('data-grant-access="WRITE"');
|
||||
expect(html).toContain("Can read and add entries");
|
||||
expect(html).toContain('data-slot="grant-write-consent"');
|
||||
// In document order the consent sits ahead of the control it qualifies.
|
||||
expect(html.indexOf('data-slot="grant-write-consent"')).toBeLessThan(
|
||||
html.indexOf('data-slot="grant-accept"'),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not ask a read invitation for a write consent", () => {
|
||||
grantsRef.value = { given: [], received: [{ ...BASE, access: "READ" }] };
|
||||
const html = render(<GrantsReceivedCard />);
|
||||
expect(html).toContain('data-grant-access="READ"');
|
||||
expect(html).not.toContain('data-slot="grant-write-consent"');
|
||||
});
|
||||
|
||||
it("stops saying it once the invitation has been answered", () => {
|
||||
// A sentence about a decision already taken is nagging, not consent.
|
||||
grantsRef.value = {
|
||||
given: [],
|
||||
received: [
|
||||
{
|
||||
...BASE,
|
||||
access: "WRITE",
|
||||
state: "ACTIVE",
|
||||
acceptedAt: "2026-01-02T11:00:00.000Z",
|
||||
},
|
||||
],
|
||||
};
|
||||
const html = render(<GrantsReceivedCard />);
|
||||
expect(html).not.toContain('data-slot="grant-write-consent"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("ending an access, and what it says about what was entered", () => {
|
||||
const t = (key: string, params?: Record<string, string | number>): string =>
|
||||
params ? `${key}(${JSON.stringify(params)})` : key;
|
||||
|
||||
it("says nothing about entries for a grant that could not make any", () => {
|
||||
const body = revokeBody({
|
||||
t,
|
||||
access: "READ",
|
||||
name: "Jo",
|
||||
retentionDays: 90,
|
||||
});
|
||||
expect(body).toContain("recordSharing.given.revokeBody");
|
||||
expect(body).not.toContain("revokeEntriesStay");
|
||||
expect(body).not.toContain("revokeAttribution");
|
||||
});
|
||||
|
||||
it("tells a write owner that the entries stay and stay attributed", () => {
|
||||
const body = revokeBody({
|
||||
t,
|
||||
access: "WRITE",
|
||||
name: "Jo",
|
||||
retentionDays: 90,
|
||||
});
|
||||
expect(body).toContain("recordSharing.given.revokeEntriesStay");
|
||||
expect(body).toContain('revokeAttribution({"days":90})');
|
||||
});
|
||||
|
||||
it("omits the window rather than inventing one", () => {
|
||||
// The number is the operator's setting. A compiled-in 365 here would be
|
||||
// exactly the invented value the sentence exists to avoid.
|
||||
const body = revokeBody({ t, access: "WRITE", name: "Jo" });
|
||||
expect(body).toContain("recordSharing.given.revokeEntriesStay");
|
||||
expect(body).not.toContain("revokeAttribution");
|
||||
});
|
||||
});
|
||||
@@ -13,12 +13,21 @@ import { useTranslations } from "@/lib/i18n/context";
|
||||
import { useInviteGrant } from "@/lib/queries/use-account-grants";
|
||||
|
||||
/**
|
||||
* v1.36.0 — offering somebody read access to this record.
|
||||
* v1.36.0 — offering somebody access to this record.
|
||||
*
|
||||
* One field, because there is one decision: who. The access level is not
|
||||
* offered — v1 grants read and only read, and a control whose only setting is
|
||||
* its default is a promise about a future release rather than a choice about
|
||||
* this one.
|
||||
* Two decisions: who, and what they may do. The level is a choice at the
|
||||
* invitation and only there — a grant is READ or WRITE from the moment it is
|
||||
* offered, nothing widens it later, and the way to a wider one is a fresh
|
||||
* invitation the other person accepts again. So this form is the one screen
|
||||
* where the owner's half of that consent is given, and the option labels have
|
||||
* to be worth reading.
|
||||
*
|
||||
* The capability sentences say what actually ships rather than the word
|
||||
* "write", which people read as larger than it is. A delegate can ADD:
|
||||
* readings, results, observations, a medication, a dose marked as taken. They
|
||||
* cannot edit or delete anything, including what they added ten seconds ago.
|
||||
* A person who learns that from a support reply rather than from this card was
|
||||
* not told.
|
||||
*
|
||||
* The invitation confers nothing until the other person accepts it. The card
|
||||
* says so above the field rather than after the submit, because that is the
|
||||
@@ -35,6 +44,9 @@ export function GrantInviteCard() {
|
||||
const invite = useInviteGrant();
|
||||
const [identifier, setIdentifier] = useState("");
|
||||
const [expiresOn, setExpiresOn] = useState("");
|
||||
// READ preselected. The narrower level is the one somebody should have to
|
||||
// choose their way out of, not into.
|
||||
const [access, setAccess] = useState<GrantAccessLevel>("READ");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [invited, setInvited] = useState<string | null>(null);
|
||||
|
||||
@@ -45,11 +57,12 @@ export function GrantInviteCard() {
|
||||
setError(null);
|
||||
setInvited(null);
|
||||
invite.mutate(
|
||||
{ identifier: value, expiresAt: endOfDayIso(expiresOn) },
|
||||
{ identifier: value, access, expiresAt: endOfDayIso(expiresOn) },
|
||||
{
|
||||
onSuccess: (grant) => {
|
||||
setIdentifier("");
|
||||
setExpiresOn("");
|
||||
setAccess("READ");
|
||||
setInvited(grant.account.username);
|
||||
},
|
||||
onError: (err) => setError(t(inviteErrorKey(err))),
|
||||
@@ -82,6 +95,30 @@ export function GrantInviteCard() {
|
||||
{t("recordSharing.invite.identifierHint")}
|
||||
</p>
|
||||
</div>
|
||||
<fieldset className="space-y-1.5" data-slot="grant-invite-access">
|
||||
{/* The `Label` primitive is a `<label>` and cannot name a group, so
|
||||
the legend mirrors its type and its trailing colon by hand rather
|
||||
than mislabelling one radio as the heading of both. */}
|
||||
<legend className="pl-1 text-sm leading-none font-medium after:content-[':']">
|
||||
{t("recordSharing.invite.accessLegend")}
|
||||
</legend>
|
||||
<div className="space-y-2">
|
||||
<AccessOption
|
||||
level="READ"
|
||||
selected={access === "READ"}
|
||||
onSelect={() => setAccess("READ")}
|
||||
label={t("recordSharing.invite.accessReadLabel")}
|
||||
capability={t("recordSharing.invite.accessReadCapability")}
|
||||
/>
|
||||
<AccessOption
|
||||
level="WRITE"
|
||||
selected={access === "WRITE"}
|
||||
onSelect={() => setAccess("WRITE")}
|
||||
label={t("recordSharing.invite.accessWriteLabel")}
|
||||
capability={t("recordSharing.invite.accessWriteCapability")}
|
||||
/>
|
||||
</div>
|
||||
</fieldset>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="grant-invite-expires">
|
||||
{t("recordSharing.invite.expiresLabel")}
|
||||
@@ -122,6 +159,63 @@ export function GrantInviteCard() {
|
||||
);
|
||||
}
|
||||
|
||||
/** The two levels an invitation can carry, as the client names them. */
|
||||
export type GrantAccessLevel = "READ" | "WRITE";
|
||||
|
||||
/**
|
||||
* One level, with the sentence that says what it actually does.
|
||||
*
|
||||
* The capability line is not decoration and it is not a tooltip: it is the
|
||||
* part the owner is consenting to, so it sits under the label where it has to
|
||||
* be read past rather than behind an info icon. Muted because it describes the
|
||||
* option rather than being the option (UI-STANDARDS §3), `text-xs` because
|
||||
* that is the meta floor.
|
||||
*/
|
||||
function AccessOption({
|
||||
level,
|
||||
selected,
|
||||
onSelect,
|
||||
label,
|
||||
capability,
|
||||
}: {
|
||||
level: GrantAccessLevel;
|
||||
selected: boolean;
|
||||
onSelect: () => void;
|
||||
label: string;
|
||||
capability: string;
|
||||
}) {
|
||||
return (
|
||||
<label
|
||||
data-slot="grant-invite-access-option"
|
||||
data-access={level}
|
||||
data-selected={selected ? "true" : "false"}
|
||||
className={[
|
||||
"flex min-h-11 cursor-pointer items-start gap-3 rounded-md border p-3 transition-colors",
|
||||
selected
|
||||
? "border-primary bg-primary/5"
|
||||
: "border-border hover:bg-muted/40",
|
||||
].join(" ")}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="grant-invite-access"
|
||||
value={level}
|
||||
checked={selected}
|
||||
onChange={onSelect}
|
||||
className="sr-only"
|
||||
/>
|
||||
<span className="space-y-1">
|
||||
<span className="text-foreground block text-sm font-medium">
|
||||
{label}
|
||||
</span>
|
||||
<span className="text-muted-foreground block text-xs">
|
||||
{capability}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The chosen day, as the instant access stops.
|
||||
*
|
||||
|
||||
@@ -46,10 +46,18 @@ export function GrantRowItem({
|
||||
/** What ended it reads differently depending on who is looking. */
|
||||
side,
|
||||
actions,
|
||||
notice,
|
||||
}: {
|
||||
grant: GrantRow;
|
||||
side: "given" | "received";
|
||||
actions?: ReactNode;
|
||||
/**
|
||||
* Something the person has to read before they act on this row, rendered in
|
||||
* the content column rather than beside the button: consent copy is content
|
||||
* (UI-STANDARDS §3), and a sentence squeezed into the action column would
|
||||
* wrap into a stripe nobody reads.
|
||||
*/
|
||||
notice?: ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
const fmt = useFormatters();
|
||||
@@ -61,6 +69,11 @@ export function GrantRowItem({
|
||||
data-slot="grant-row"
|
||||
data-grant-id={grant.id}
|
||||
data-grant-state={grant.state}
|
||||
// The level, as an attribute rather than only as a sentence: the browser
|
||||
// journey has to be able to prove that the level a person picked on the
|
||||
// invitation form is the level the server stored, and asserting on
|
||||
// viewport text would pin the copy instead of the value.
|
||||
data-grant-access={grant.access}
|
||||
className="flex flex-wrap items-start justify-between gap-3 py-3"
|
||||
>
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
@@ -113,6 +126,7 @@ export function GrantRowItem({
|
||||
</div>
|
||||
)}
|
||||
</dl>
|
||||
{notice}
|
||||
</div>
|
||||
{actions && <div className="flex shrink-0 items-center">{actions}</div>}
|
||||
</li>
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useTranslations } from "@/lib/i18n/context";
|
||||
import { accountLabel } from "@/lib/sharing/account-access-view";
|
||||
import {
|
||||
useAccountGrants,
|
||||
useRecordActivity,
|
||||
useRevokeGrant,
|
||||
type GrantRow,
|
||||
} from "@/lib/queries/use-account-grants";
|
||||
@@ -29,11 +30,21 @@ import {
|
||||
* health record to somebody. The confirm dialog exists only because the click
|
||||
* target sits in a list and a mis-tap should not end an access silently; it
|
||||
* names the person and the act.
|
||||
*
|
||||
* What the dialog SAYS depends on what the grant could do: see
|
||||
* {@link revokeBody}.
|
||||
*/
|
||||
|
||||
export function GrantsGivenCard() {
|
||||
const { t } = useTranslations();
|
||||
const { data, isLoading, isError, refetch } = useAccountGrants();
|
||||
const revoke = useRevokeGrant();
|
||||
// Read for one number: how long the activity view can still say who entered
|
||||
// what. The activity card on this same page holds the query, so this is the
|
||||
// cached answer rather than a second request — and when the server has not
|
||||
// answered yet, the sentence that would need the number is left out instead
|
||||
// of being written around a guessed 365.
|
||||
const activity = useRecordActivity();
|
||||
|
||||
const given = data?.given ?? [];
|
||||
|
||||
@@ -95,7 +106,12 @@ export function GrantsGivenCard() {
|
||||
: t("recordSharing.given.revoke")
|
||||
}
|
||||
title={t("recordSharing.given.revokeTitle", { name })}
|
||||
body={t("recordSharing.given.revokeBody", { name })}
|
||||
body={revokeBody({
|
||||
t,
|
||||
access: grant.access,
|
||||
name,
|
||||
retentionDays: activity.data?.retentionDays,
|
||||
})}
|
||||
confirmLabel={t("recordSharing.given.revokeConfirm")}
|
||||
pending={revoke.isPending}
|
||||
onConfirm={() => revoke.mutate(grant.id)}
|
||||
@@ -103,3 +119,43 @@ export function GrantsGivenCard() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What ending this particular access does, as one paragraph.
|
||||
*
|
||||
* Exported and pure because the dialog it feeds only exists after a click, and
|
||||
* an SSR render cannot see inside it — the same reason `endOfDayIso` is
|
||||
* exported from the invite card. The composition is the thing worth pinning:
|
||||
* which sentences appear, and which one is omitted when its number is unknown.
|
||||
*
|
||||
* Two extra sentences for a grant that could add entries, and only for one: a
|
||||
* read grant never put anything in the record, so telling its owner that
|
||||
* "anything they entered stays" would describe something that cannot have
|
||||
* happened. The last sentence is the honest bound on attribution — the activity
|
||||
* view answers "who entered what" for as long as the audit window reaches, and
|
||||
* that window is the operator's setting. It is said with the number the server
|
||||
* resolved, or not said at all.
|
||||
*/
|
||||
export function revokeBody({
|
||||
t,
|
||||
access,
|
||||
name,
|
||||
retentionDays,
|
||||
}: {
|
||||
t: (key: string, params?: Record<string, string | number>) => string;
|
||||
access: GrantRow["access"];
|
||||
name: string;
|
||||
/** Undefined until the server has said what the window is. */
|
||||
retentionDays?: number;
|
||||
}): string {
|
||||
const lines = [t("recordSharing.given.revokeBody", { name })];
|
||||
if (access === "WRITE") {
|
||||
lines.push(t("recordSharing.given.revokeEntriesStay"));
|
||||
if (retentionDays !== undefined) {
|
||||
lines.push(
|
||||
t("recordSharing.given.revokeAttribution", { days: retentionDays }),
|
||||
);
|
||||
}
|
||||
}
|
||||
return lines.join(" ");
|
||||
}
|
||||
@@ -78,6 +78,7 @@ export function GrantsReceivedCard() {
|
||||
key={grant.id}
|
||||
grant={grant}
|
||||
side="received"
|
||||
notice={renderConsent(grant)}
|
||||
actions={renderActions(grant)}
|
||||
/>
|
||||
))}
|
||||
@@ -87,6 +88,27 @@ export function GrantsReceivedCard() {
|
||||
</SettingsCard>
|
||||
);
|
||||
|
||||
/**
|
||||
* The delegate's half of the consent, on the screen where they give it.
|
||||
*
|
||||
* A write invitation asks for something a read invitation does not: that the
|
||||
* person put entries into somebody else's health record under their own
|
||||
* name, permanently, with no way to take one back. That is worth one
|
||||
* sentence before the button rather than a sentence after the first entry.
|
||||
* Shown only while the invitation is unanswered — once accepted, the level
|
||||
* is the row's own line and this would be nagging.
|
||||
*/
|
||||
function renderConsent(grant: GrantRow) {
|
||||
if (grant.state !== "PENDING" || grant.access !== "WRITE") return null;
|
||||
return (
|
||||
<p data-slot="grant-write-consent" className="text-foreground text-sm">
|
||||
{t("recordSharing.received.writeConsent", {
|
||||
name: accountLabel(grant.account),
|
||||
})}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
function renderActions(grant: GrantRow) {
|
||||
if (grant.state === "PENDING") {
|
||||
return (
|
||||
|
||||
@@ -32,7 +32,7 @@ import { dataEnvelope, errorEnvelope, stdResponses } from "./shared";
|
||||
inviteGrantSchema.meta({
|
||||
id: "AccountGrantInvite",
|
||||
description:
|
||||
"Offer read access to another account on this instance. `identifier` is the invitee's username or e-mail, matched case-insensitively — the same identifier they sign in with. `expiresAt` is optional; omitted or null means the grant runs until somebody ends it. The access level is not a parameter: v1 grants READ only.",
|
||||
"Offer access to another account on this instance. `identifier` is the invitee's username or e-mail, matched case-insensitively — the same identifier they sign in with. `expiresAt` is optional; omitted or null means the grant runs until somebody ends it. `access` is READ when omitted, so a client that does not know about the field keeps working: READ can read the record and change nothing, WRITE can additionally ADD entries (readings, results, observations, a medication, a marked dose) and can still edit or delete nothing, including its own. The level is fixed when the invitation is written — no endpoint raises a live grant, because that would widen what the delegate accepted without asking them again. The way up is a new invitation the delegate accepts.",
|
||||
});
|
||||
|
||||
switchAccountSchema.meta({
|
||||
@@ -205,7 +205,7 @@ const accountAccessEntry = z
|
||||
canWrite: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"Whether this caller may CHANGE that record. Resolved server-side; `false` for every grant in v1. Render it; never derive it.",
|
||||
"Whether this caller may ADD to that record: true for an accepted WRITE grant, false for a READ one. It never means edit or delete, which stay with the owner at both levels. Resolved server-side. Render it; never derive it.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
@@ -327,9 +327,9 @@ export const accountSharingPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
post: {
|
||||
tags: ["Account sharing"],
|
||||
summary: "Invite an account to read this record",
|
||||
summary: "Invite an account to this record",
|
||||
description:
|
||||
"Offers read access to somebody already registered on this instance; the grant confers nothing until they accept it. An identifier that names no account answers 404 — a deliberate disclosure to an authenticated caller on a household instance, rate-limited to 10 invitations an hour, and the alternative (a silent pending row for a mistyped username) is worse. Refused while acting on another account, so a delegate can neither invite nor re-delegate.",
|
||||
"Offers access to somebody already registered on this instance, at READ or WRITE; the grant confers nothing until they accept it. An identifier that names no account answers 404 — a deliberate disclosure to an authenticated caller on a household instance, rate-limited to 10 invitations an hour, and the alternative (a silent pending row for a mistyped username) is worse. Refused while acting on another account, so a delegate can neither invite nor re-delegate.",
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: { "application/json": { schema: inviteGrantSchema } },
|
||||
|
||||
@@ -120,6 +120,13 @@ export interface InviteInput {
|
||||
identifier: string;
|
||||
/** ISO-8601 with offset, or null for a grant that runs until somebody ends it. */
|
||||
expiresAt: string | null;
|
||||
/**
|
||||
* What the invitation offers. Required rather than optional even though the
|
||||
* server defaults an omitted field to READ: a caller that does not name the
|
||||
* level has not decided it, and this is the one moment the level can be
|
||||
* decided at all.
|
||||
*/
|
||||
access: "READ" | "WRITE";
|
||||
}
|
||||
|
||||
export function useInviteGrant() {
|
||||
|
||||
@@ -16,9 +16,11 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
grantAllows,
|
||||
grantState,
|
||||
inviteGrant,
|
||||
isGrantActive,
|
||||
type GrantLifecycle,
|
||||
} from "@/lib/sharing/grants";
|
||||
import type { AccountGrant, Prisma } from "@/generated/prisma/client";
|
||||
|
||||
const NOW = new Date("2026-08-02T12:00:00.000Z");
|
||||
const EARLIER = new Date("2026-08-01T12:00:00.000Z");
|
||||
@@ -131,3 +133,82 @@ describe("grantAllows", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The level the caller offered is the level the row is written with.
|
||||
*
|
||||
* A capture client rather than a database: what is asserted here is the `data`
|
||||
* object this module hands the client, which is the one thing a fake can see
|
||||
* honestly. That the column then holds the value, that the enum accepts it and
|
||||
* that the partial unique index still applies are properties of Postgres and
|
||||
* live in `tests/integration/account-grant-lifecycle.test.ts` — a fake that
|
||||
* returned whatever it was given would report all three as working.
|
||||
*
|
||||
* There is no upgrade test because there is no upgrade: no function in this
|
||||
* module raises the level of a row that exists, and the way to a wider grant
|
||||
* is a new invitation the delegate accepts again.
|
||||
*/
|
||||
describe("inviteGrant", () => {
|
||||
function captureDb(): {
|
||||
db: Pick<Prisma.TransactionClient, "accountGrant">;
|
||||
writes: Array<{ access: string; grantorId: string; granteeId: string }>;
|
||||
} {
|
||||
const writes: Array<{
|
||||
access: string;
|
||||
grantorId: string;
|
||||
granteeId: string;
|
||||
}> = [];
|
||||
const db = {
|
||||
accountGrant: {
|
||||
create: async (args: {
|
||||
data: { access: string; grantorId: string; granteeId: string };
|
||||
}) => {
|
||||
writes.push(args.data);
|
||||
return { id: "grant-1", ...args.data } as unknown as AccountGrant;
|
||||
},
|
||||
},
|
||||
} as unknown as Pick<Prisma.TransactionClient, "accountGrant">;
|
||||
return { db, writes };
|
||||
}
|
||||
|
||||
it("writes the level it was given", async () => {
|
||||
for (const access of ["READ", "WRITE"] as const) {
|
||||
const { db, writes } = captureDb();
|
||||
const row = await inviteGrant(
|
||||
{ grantorId: "owner", granteeId: "delegate", access },
|
||||
db,
|
||||
);
|
||||
expect(writes).toHaveLength(1);
|
||||
expect(writes[0].access).toBe(access);
|
||||
expect(row.access).toBe(access);
|
||||
}
|
||||
});
|
||||
|
||||
it("still refuses a self-grant before anything is written", async () => {
|
||||
const { db, writes } = captureDb();
|
||||
await expect(
|
||||
inviteGrant(
|
||||
{ grantorId: "solo", granteeId: "solo", access: "WRITE" },
|
||||
db,
|
||||
),
|
||||
).rejects.toMatchObject({ code: "self_grant" });
|
||||
expect(writes).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("confers the offered level only after acceptance", () => {
|
||||
// The two halves of the write consent, as the state machine sees them: the
|
||||
// owner's is the row, the delegate's is `acceptedAt`. Neither alone is
|
||||
// enough, and the pending row proves it.
|
||||
const offered = {
|
||||
revokedAt: null,
|
||||
expiresAt: null,
|
||||
access: "WRITE" as const,
|
||||
};
|
||||
expect(grantAllows({ ...offered, acceptedAt: null }, "write", NOW)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(grantAllows({ ...offered, acceptedAt: EARLIER }, "write", NOW)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -20,9 +20,13 @@ export interface AccountAccessEntry {
|
||||
accountId: string;
|
||||
username: string;
|
||||
displayName: string | null;
|
||||
/** The grant's level. `"read"` throughout v1. */
|
||||
/** The grant's level, as the owner offered it and the caller accepted it. */
|
||||
access: "read" | "write";
|
||||
/** May this caller change that record. Resolved server-side; `false` in v1. */
|
||||
/**
|
||||
* May this caller ADD to that record. Resolved server-side. It never means
|
||||
* edit or delete: those stay with the owner at both levels, and no field
|
||||
* here offers them.
|
||||
*/
|
||||
canWrite: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,11 +14,12 @@
|
||||
* `canSwitch` and `canWrite`; it never computes them, and there is nothing in
|
||||
* the payload it could compute them from.
|
||||
*
|
||||
* `canWrite` is `false` for every entry in v1, because `inviteGrant` writes
|
||||
* READ and only READ. It is resolved here through {@link grantAllows} against
|
||||
* the real row rather than hardcoded, so the day a WRITE grant exists the
|
||||
* answer changes without this file being edited — and, more importantly, so
|
||||
* that nobody has to remember that it should.
|
||||
* `canWrite` is resolved here through {@link grantAllows} against the real
|
||||
* row rather than stored or hardcoded, which is why the level becoming an
|
||||
* invitation choice needed no edit to this file: an accepted WRITE grant
|
||||
* started answering true the moment one could exist. It answers "may add to
|
||||
* this record" and never "may change it" — editing and deleting stay with the
|
||||
* owner at both levels, and no field here offers them.
|
||||
*
|
||||
* What is deliberately NOT published: the other account's avatar. The avatar
|
||||
* bytes are owner-scoped (`/api/user/avatar/{id}` refuses any id but the
|
||||
|
||||
+34
-17
@@ -1,11 +1,12 @@
|
||||
/**
|
||||
* v1.36.0 — the account-grant state machine. One file, one set of rules.
|
||||
*
|
||||
* A grant is one account's standing permission to read another account's
|
||||
* record, and the row is also the durable record of the consent that created
|
||||
* it (there is no second receipt table — see the model docblock in
|
||||
* `prisma/schema.prisma`). Everything that decides what a grant currently
|
||||
* MEANS lives here, and nothing else in the tree is allowed to decide it.
|
||||
* A grant is one account's standing permission to open another account's
|
||||
* record — to read it, and where the grant says so to add to it. The row is
|
||||
* also the durable record of the consent that created it (there is no second
|
||||
* receipt table — see the model docblock in `prisma/schema.prisma`).
|
||||
* Everything that decides what a grant currently MEANS lives here, and nothing
|
||||
* else in the tree is allowed to decide it.
|
||||
*
|
||||
* Why one file rather than the rules at the call sites: two consumers read
|
||||
* these rows for different reasons — the acting-account resolver on every
|
||||
@@ -20,7 +21,7 @@
|
||||
* Bearer perimeter that shouts at a mention is the right direction to be
|
||||
* wrong in.)
|
||||
*
|
||||
* Three properties are the whole point, and each is a decision made HERE and
|
||||
* Four properties are the whole point, and each is a decision made HERE and
|
||||
* nowhere else:
|
||||
*
|
||||
* * **Pending confers nothing.** An invitation is not access. A row with
|
||||
@@ -36,6 +37,11 @@
|
||||
* the shape it does. Re-inviting the same person mints a NEW row; the
|
||||
* partial unique index in migration 0292 keeps at most one LIVE row per
|
||||
* pair while the history piles up underneath.
|
||||
* * **The level never widens.** A row is READ or WRITE from the moment it is
|
||||
* offered, and no transition here raises it. Widening a grant somebody has
|
||||
* already accepted would change what they agreed to without asking them
|
||||
* again, and the delegate's consent is half of what makes a write grant
|
||||
* legitimate. {@link inviteGrant} carries the reasoning.
|
||||
*
|
||||
* Every write below is a CONDITIONAL update — the state the transition
|
||||
* requires is in the `where`, not in a read the caller performed a moment
|
||||
@@ -145,10 +151,8 @@ export function isGrantActive(
|
||||
*
|
||||
* Active first, then the level. A READ grant permits reads only; a WRITE grant
|
||||
* permits both, because write access to a record without read access describes
|
||||
* nothing anyone asked for. v1 never writes a WRITE row (see
|
||||
* {@link inviteGrant}), so in v1 this answers `false` for every write — which
|
||||
* is the fail-closed arm the resolver wants, reached by the data rather than
|
||||
* by a special case.
|
||||
* nothing anyone asked for. The state outranks the level in both directions: a
|
||||
* revoked WRITE grant permits nothing at all, and no level survives an expiry.
|
||||
*/
|
||||
export function grantAllows(
|
||||
grant: GrantLifecycle & { access: AccountGrantAccess },
|
||||
@@ -164,8 +168,16 @@ export function grantAllows(
|
||||
export interface InviteGrantInput {
|
||||
/** The account whose record is being shared. */
|
||||
grantorId: string;
|
||||
/** The account being invited to read it. */
|
||||
/** The account being invited to it. */
|
||||
granteeId: string;
|
||||
/**
|
||||
* What the invitation offers. Required, with no default in this module: a
|
||||
* level nobody named is a level nobody chose, and the one place an omitted
|
||||
* request field becomes READ is the invite schema
|
||||
* (`src/lib/validations/account-sharing.ts`). Two defaults agreeing today is
|
||||
* how they disagree later.
|
||||
*/
|
||||
access: AccountGrantAccess;
|
||||
/** Optional lapse date. Null = the grant runs until somebody ends it. */
|
||||
expiresAt?: Date | null;
|
||||
}
|
||||
@@ -173,11 +185,16 @@ export interface InviteGrantInput {
|
||||
/**
|
||||
* Offer a grant. The delegate has access only once they accept it.
|
||||
*
|
||||
* `access` is not a parameter. v1 grants READ and only READ (design §14): the
|
||||
* column exists from day one so that delegated writes become enforcement work
|
||||
* instead of migration work, and leaving the level out of the input is what
|
||||
* makes "v1 never grants write" a property of this file rather than a promise
|
||||
* in a comment.
|
||||
* The level is fixed here and never moves. There is no widen, no PATCH, no
|
||||
* upgrade endpoint, and the absence is the design rather than a gap: write
|
||||
* access needs two consents, the owner's because it is their record and the
|
||||
* delegate's because they are being asked to put something into somebody's
|
||||
* health record under their own name. Acceptance is the single moment those
|
||||
* two meet, and it happens once. Raising a live grant afterwards would carry
|
||||
* one consent, and it would not be the delegate's. The way up is a new
|
||||
* invitation at the level meant, accepted again — the partial unique index
|
||||
* permits it as soon as the old row is ended, and the cost is one revoke and
|
||||
* one accept.
|
||||
*
|
||||
* Self-grants are refused here rather than by a database CHECK — migration
|
||||
* 0292 carries the reason (the schema-driven wipe seeder plants a row with
|
||||
@@ -198,7 +215,7 @@ export async function inviteGrant(
|
||||
data: {
|
||||
grantorId: input.grantorId,
|
||||
granteeId: input.granteeId,
|
||||
access: "READ",
|
||||
access: input.access,
|
||||
invitedAt: now,
|
||||
expiresAt: input.expiresAt ?? null,
|
||||
},
|
||||
|
||||
@@ -5,10 +5,6 @@
|
||||
* and only two of them carry a body worth validating. What is NOT here is as
|
||||
* deliberate as what is:
|
||||
*
|
||||
* * No `access` level. v1 grants READ and only READ, and the level is not a
|
||||
* parameter anywhere in the stack — `inviteGrant` hardcodes it. A field
|
||||
* here would be an input the domain module then ignores, which is the
|
||||
* shape of a promise nobody kept.
|
||||
* * No `userId`, `grantorId` or `granteeId` on any body. Both sides of a
|
||||
* grant come from the authenticated session and the row itself. A body
|
||||
* field naming a party would be an authorization decision made by the
|
||||
@@ -43,6 +39,23 @@ export const inviteGrantSchema = z.object({
|
||||
* remember to renew is worse than one that does not exist.
|
||||
*/
|
||||
expiresAt: z.iso.datetime({ offset: true }).nullable().optional(),
|
||||
/**
|
||||
* What the invitation offers, and the ONLY place the level is defaulted.
|
||||
*
|
||||
* `inviteGrant` takes the level as a required argument, so the domain module
|
||||
* never guesses; this line is the single answer to "what does an omitted
|
||||
* field mean", which keeps an older client's payload valid without a second
|
||||
* copy of the same decision further down. A grant is READ or WRITE from the
|
||||
* moment it is offered and stays that way: there is no endpoint that widens
|
||||
* a live grant, because widening it would carry one consent and it would not
|
||||
* be the delegate's. The way up is a new invitation, accepted again.
|
||||
*/
|
||||
access: z
|
||||
.enum(["READ", "WRITE"])
|
||||
.default("READ")
|
||||
.describe(
|
||||
"READ can read the record and change nothing. WRITE can additionally ADD entries (readings, results, observations, a medication, a marked dose) and can still edit or delete nothing, including its own. Omitted means READ, so a client that predates the field keeps working. The level is fixed when the invitation is written: no endpoint raises a live grant, because that would widen what the delegate accepted without asking them again. The way up is a new invitation the delegate accepts.",
|
||||
),
|
||||
});
|
||||
|
||||
export type InviteGrantBody = z.infer<typeof inviteGrantSchema>;
|
||||
|
||||
Reference in new issue
Block a user