mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 23:33:29 +00:00
Merge remote-tracking branch 'origin/main' into work/dw-e
This commit is contained in:
commit
251b534660
41 files changed
+2416
-161
No files matched your search
@@ -74,6 +74,9 @@ describe("the acting-account carrier is read in one place", () => {
|
||||
const CARRIER_ALLOWLIST = [
|
||||
// Projects it off the session row it already loaded.
|
||||
"lib/auth/session.ts",
|
||||
// Reads it. The one statement of "what does this request say it is acting
|
||||
// as", for both transports and for every caller that has to ask.
|
||||
"lib/auth/acting-carrier.ts",
|
||||
// The resolver. The only thing that acts on the value.
|
||||
"lib/api-handler.ts",
|
||||
// v1.36.0 — the only thing that WRITES it: the switch endpoint sets it
|
||||
@@ -113,10 +116,32 @@ describe("the acting-account carrier is read in one place", () => {
|
||||
const namers = filesMatching(/x-healthlog-account/i);
|
||||
expect(namers.length).toBeGreaterThan(0);
|
||||
expect(namers).toEqual([
|
||||
"lib/api-handler.ts",
|
||||
"lib/auth/acting-carrier.ts",
|
||||
"lib/openapi/routes/account-sharing.ts",
|
||||
]);
|
||||
});
|
||||
|
||||
/**
|
||||
* Who may ask "which record does this request claim" without an auth
|
||||
* context in hand.
|
||||
*
|
||||
* `readClaimedActingAccount()` answers before any grant check has run, so a
|
||||
* caller that treats its answer as permission has skipped the only thing
|
||||
* that grants any. Exactly one caller exists, beside the file that declares
|
||||
* it: the idempotency wrapper, which uses the claim to pick a cache cell and
|
||||
* leaves the check to the handler it wraps. Everything else that needs the
|
||||
* acting account has an auth context by then and goes through
|
||||
* `requireRecordAuth`, which checks a live grant before returning. A second
|
||||
* caller here is a design question, not a patch.
|
||||
*/
|
||||
it("the unchecked claim has exactly two consumers", () => {
|
||||
const consumers = filesMatching(/readClaimedActingAccount/);
|
||||
expect(consumers.length).toBeGreaterThan(0);
|
||||
expect(consumers).toEqual([
|
||||
"lib/auth/acting-carrier.ts",
|
||||
"lib/idempotency.ts",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the cookie-only helpers cannot see the acting account", () => {
|
||||
|
||||
@@ -65,9 +65,13 @@ describe("T1 — the Bearer resolution set is frozen", () => {
|
||||
// `defaultUserIdResolver` — resolves the Bearer token to a user id so an
|
||||
// idempotency key files under its owner. It authorises nothing: the
|
||||
// handler still runs its own `requireAuth()`, and this resolver only
|
||||
// decides which user's cache cell a replay lands in. Narrow in reach and
|
||||
// deliberate, but it is a raw Bearer value becoming a user id, so it
|
||||
// belongs on this list rather than beside it.
|
||||
// decides which cache cell a replay lands in. Since delegated writes it
|
||||
// decides that from two values — the caller resolved here, and the record
|
||||
// the request claims, read through the one acting-account carrier reader
|
||||
// and folded into the key. Both are unchecked selectors; neither widens
|
||||
// what the handler will do. Narrow in reach and deliberate, but it is a
|
||||
// raw Bearer value becoming a user id, so it belongs on this list rather
|
||||
// than beside it.
|
||||
"lib/idempotency.ts",
|
||||
].sort();
|
||||
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -75,7 +75,16 @@ function request(): NextRequest {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// The whole shape `getSession()` returns. The session half carries the
|
||||
// acting-account carrier, which the idempotency wrapper reads to decide
|
||||
// whose record a cell belongs to — a fake that omitted it made the wrapper
|
||||
// fail on a field production always has.
|
||||
mocks.getSession.mockResolvedValue({
|
||||
session: {
|
||||
id: "session-1",
|
||||
expiresAt: new Date(Date.now() + 60_000),
|
||||
actingAsUserId: null,
|
||||
},
|
||||
user: { id: "user-1", role: "USER" },
|
||||
});
|
||||
mocks.findUnique.mockResolvedValue(null);
|
||||
|
||||
@@ -15,6 +15,10 @@ import {
|
||||
EVENT_DEFAULT_ENABLED,
|
||||
type EventType,
|
||||
} from "@/lib/notifications/types";
|
||||
import {
|
||||
eventDescriptionTranslationKey,
|
||||
eventTranslationKey,
|
||||
} from "@/lib/notifications/event-labels";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { apiGet, apiPut } from "@/lib/api/api-fetch";
|
||||
|
||||
@@ -38,17 +42,6 @@ interface PreferencesData {
|
||||
eventTypes: string[];
|
||||
}
|
||||
|
||||
/** Maps SCREAMING_SNAKE event type to translation key, e.g. MEDICATION_REMINDER → eventMedicationReminder */
|
||||
function eventTranslationKey(eventType: string): string {
|
||||
return (
|
||||
"notifications.event" +
|
||||
eventType
|
||||
.toLowerCase()
|
||||
.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase())
|
||||
.replace(/^./, (c) => c.toUpperCase())
|
||||
);
|
||||
}
|
||||
|
||||
export default function NotificationsPage() {
|
||||
const { isAuthenticated, isLoading: authLoading } = useAuth();
|
||||
const { t } = useTranslations();
|
||||
@@ -265,7 +258,7 @@ export default function NotificationsPage() {
|
||||
<tbody>
|
||||
{eventTypes.map((eventType, idx) => {
|
||||
const nameKey = eventTranslationKey(eventType);
|
||||
const descKey = nameKey + "Desc";
|
||||
const descKey = eventDescriptionTranslationKey(eventType);
|
||||
return (
|
||||
<tr
|
||||
key={eventType}
|
||||
@@ -311,7 +304,7 @@ export default function NotificationsPage() {
|
||||
<div className="space-y-4 md:hidden">
|
||||
{eventTypes.map((eventType) => {
|
||||
const nameKey = eventTranslationKey(eventType);
|
||||
const descKey = nameKey + "Desc";
|
||||
const descKey = eventDescriptionTranslationKey(eventType);
|
||||
return (
|
||||
<div
|
||||
key={eventType}
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -219,7 +219,11 @@ describe("withIdempotency", () => {
|
||||
);
|
||||
const wrapped = withIdempotency<[NextRequest]>(handler);
|
||||
await wrapped(makeRequest("POST", { "idempotency-key": "abc-12345678" }));
|
||||
expect(getSession).toHaveBeenCalledTimes(1);
|
||||
// Twice: once to resolve who is calling, once to read which record they
|
||||
// say they are acting on. The second read is what a delegated write costs
|
||||
// here, and it is a single indexed lookup on a request that is about to
|
||||
// write anyway.
|
||||
expect(getSession).toHaveBeenCalledTimes(2);
|
||||
expect(prisma.idempotencyKey.create).toHaveBeenCalledTimes(1);
|
||||
const persisted = vi.mocked(prisma.idempotencyKey.create).mock
|
||||
.calls[0][0] as { data: { userId: string } };
|
||||
@@ -536,3 +540,136 @@ describe("isCachableStatus do-not-cache rules (V3 audit)", () => {
|
||||
expect(stored.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The cell is scoped to the record the request claims, not only to the caller.
|
||||
*
|
||||
* `tests/integration/idempotency-record-scoped-cell.test.ts` proves the rows.
|
||||
* These prove the key the wrapper composes, which is what decides whether two
|
||||
* requests meet in one cell — including the two cases a row-level test cannot
|
||||
* show, because both end in no row at all.
|
||||
*/
|
||||
describe("withIdempotency — record-scoped cells", () => {
|
||||
const CLIENT_KEY = "abc-12345678";
|
||||
|
||||
/** Present these headers to the wrapper for the next call. */
|
||||
function present(values: Record<string, string>): void {
|
||||
vi.mocked(headers).mockResolvedValue({
|
||||
get: (name: string) => values[name.toLowerCase()] ?? null,
|
||||
} as unknown as ReturnType<typeof headers> extends Promise<infer T>
|
||||
? T
|
||||
: never);
|
||||
}
|
||||
|
||||
/** Sign the caller in over the cookie transport, optionally switched. */
|
||||
function cookieSession(actingAsUserId: string | null): void {
|
||||
vi.mocked(getSession).mockResolvedValue({
|
||||
session: {
|
||||
id: "s-1",
|
||||
expiresAt: new Date(Date.now() + 60_000),
|
||||
actingAsUserId,
|
||||
},
|
||||
user: { id: "u-1", role: "USER" },
|
||||
} as Awaited<ReturnType<typeof getSession>>);
|
||||
}
|
||||
|
||||
async function run(key = CLIENT_KEY): Promise<void> {
|
||||
const handler = vi.fn(async () =>
|
||||
NextResponse.json({ data: { ok: true }, error: null }, { status: 201 }),
|
||||
);
|
||||
const wrapped = withIdempotency<[NextRequest]>(handler, async () => "u-1");
|
||||
await wrapped(makeRequest("POST", { "idempotency-key": key }));
|
||||
}
|
||||
|
||||
/** The key the wrapper looked the cell up under. */
|
||||
function lookedUpKey(): string {
|
||||
const call = vi.mocked(prisma.idempotencyKey.findUnique).mock
|
||||
.calls[0][0] as {
|
||||
where: { userId_key_method_path: { userId: string; key: string } };
|
||||
};
|
||||
return call.where.userId_key_method_path.key;
|
||||
}
|
||||
|
||||
/** The row the wrapper claimed. */
|
||||
function claimed(): { userId: string; key: string } {
|
||||
return (
|
||||
vi.mocked(prisma.idempotencyKey.create).mock.calls[0][0] as {
|
||||
data: { userId: string; key: string };
|
||||
}
|
||||
).data;
|
||||
}
|
||||
|
||||
it("folds the account named by the Bearer selector into the key", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(null);
|
||||
present({ "x-healthlog-account": "owner-9" });
|
||||
|
||||
await run();
|
||||
|
||||
expect(lookedUpKey()).toBe(`owner-9|${CLIENT_KEY}`);
|
||||
// The owner column stays the ACTOR. It is a foreign key to `users` with a
|
||||
// cascade behind it, so it can only ever hold a real account id — which is
|
||||
// why the record moved into the key and not into here.
|
||||
expect(claimed()).toMatchObject({
|
||||
userId: "u-1",
|
||||
key: `owner-9|${CLIENT_KEY}`,
|
||||
});
|
||||
});
|
||||
|
||||
it("folds the account the cookie session is switched to", async () => {
|
||||
cookieSession("owner-7");
|
||||
present({});
|
||||
|
||||
await run();
|
||||
|
||||
expect(claimed().key).toBe(`owner-7|${CLIENT_KEY}`);
|
||||
});
|
||||
|
||||
it("keys a request with no acting account byte-for-byte as the client sent it", async () => {
|
||||
cookieSession(null);
|
||||
present({});
|
||||
|
||||
await run();
|
||||
|
||||
expect(lookedUpKey()).toBe(CLIENT_KEY);
|
||||
expect(claimed()).toMatchObject({ userId: "u-1", key: CLIENT_KEY });
|
||||
});
|
||||
|
||||
it("ignores a selector sent over the cookie transport", async () => {
|
||||
// The resolver refuses that request outright (`misplaced_selector`). The
|
||||
// cell must not pretend it named a record either — a claim the request was
|
||||
// never going to be served must not move where its answer is filed.
|
||||
cookieSession(null);
|
||||
present({ "x-healthlog-account": "owner-9" });
|
||||
|
||||
await run();
|
||||
|
||||
expect(claimed().key).toBe(CLIENT_KEY);
|
||||
});
|
||||
|
||||
it("refuses a client key that carries the separator", async () => {
|
||||
// The one way a caller could aim at somebody else's cell: send
|
||||
// `owner-9|abc-12345678` as the key from their own un-switched session. The
|
||||
// key validator does not admit the byte, so the header is malformed and the
|
||||
// wrapper does not cache at all.
|
||||
vi.mocked(getSession).mockResolvedValue(null);
|
||||
present({});
|
||||
|
||||
await run(`owner-9|${CLIENT_KEY}`);
|
||||
|
||||
expect(prisma.idempotencyKey.findUnique).not.toHaveBeenCalled();
|
||||
expect(prisma.idempotencyKey.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips the cache when the claimed account names nothing that could exist", async () => {
|
||||
// Longer than any account id. The request is refused downstream; caching it
|
||||
// would let a caller write an arbitrarily long key into the table on the
|
||||
// way to a 403.
|
||||
vi.mocked(getSession).mockResolvedValue(null);
|
||||
present({ "x-healthlog-account": "x".repeat(65) });
|
||||
|
||||
await run();
|
||||
|
||||
expect(prisma.idempotencyKey.findUnique).not.toHaveBeenCalled();
|
||||
expect(prisma.idempotencyKey.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+24
-84
@@ -19,6 +19,13 @@ import {
|
||||
STEP_UP_ELEVATION_TTL_SECONDS,
|
||||
} from "./auth/step-up";
|
||||
import { hashToken } from "./auth/hmac";
|
||||
import {
|
||||
carrierTarget,
|
||||
decideActingCarrier,
|
||||
readSelectorHeader,
|
||||
selectorNamesAnAccount,
|
||||
type ActingCarrier,
|
||||
} from "./auth/acting-carrier";
|
||||
import { AssistantDisabledError } from "./feature-flags";
|
||||
import { ConsentRequiredError } from "./ai/consent-guard";
|
||||
import { SCOPE_HEALTH_READ, SCOPE_HEALTH_WRITE } from "./mcp/oauth/config";
|
||||
@@ -597,69 +604,23 @@ async function authenticateBearer(
|
||||
//
|
||||
// One function decides, for every transport, whether this request acts on
|
||||
// somebody else's record — the same argument that put `resolveBearerToken` in
|
||||
// one file for two wires. Two carriers converge here because they are two
|
||||
// answers to one question, and two answers that live apart drift.
|
||||
// one file for two wires. Two carriers converge on one decision because they
|
||||
// are two answers to one question, and two answers that live apart drift.
|
||||
//
|
||||
// Neither carrier authorises anything. Both merely NAME an account; the grant
|
||||
// table decides, on this request, with no cached verdict anywhere. The
|
||||
// difference between them is who can set them:
|
||||
//
|
||||
// * The cookie transport carries it on the session ROW (`actingAsUserId`).
|
||||
// A browser cannot address that row — the cookie holds a secret whose hash
|
||||
// is the lookup key — so the value is server state, written only by the
|
||||
// switch endpoint after it has validated the grant.
|
||||
// * The Bearer transport carries it in a per-request HEADER. A long-lived
|
||||
// token must not accumulate switch state: stamping it on the ApiToken row
|
||||
// would make the credential itself ambient authority, and the token has to
|
||||
// keep meaning "this person" for as long as it exists.
|
||||
//
|
||||
// The header is a Bearer-only carrier. On a cookie request it is refused, not
|
||||
// ignored — a client that sends a selector over a transport that does not read
|
||||
// one believes it is selecting an account and is not, and the failure of that
|
||||
// belief is a support case about data that looks wrong.
|
||||
// That decision now lives in `./auth/acting-carrier`, because a second caller
|
||||
// needs it: the idempotency wrapper files its replay cell under the record a
|
||||
// request claims, and it runs before any auth context exists. What stays here
|
||||
// is what only this file may do — turning a claim into a data scope after a
|
||||
// live grant says so.
|
||||
|
||||
/**
|
||||
* The per-request account selector, on the Bearer transport only.
|
||||
* The selector header's name, re-exported.
|
||||
*
|
||||
* Cross-origin JavaScript cannot set it: a custom request header forces a CORS
|
||||
* preflight and this app sends no CORS headers at all, so the preflight is
|
||||
* never answered. It is a selector regardless — the grant table is what
|
||||
* authorises, and the header is treated as hostile input everywhere below.
|
||||
* It is declared beside the carrier reader it belongs to; every route-facing
|
||||
* helper is imported from this module, and the OpenAPI table and the suites
|
||||
* that drive a switched request were written against that path.
|
||||
*/
|
||||
export const ACCOUNT_SELECTOR_HEADER = "x-healthlog-account";
|
||||
|
||||
/**
|
||||
* Longest selector value worth a database round trip. Account ids are 25-char
|
||||
* cuids; anything past this names no account that could exist and is refused
|
||||
* as such, on the same path and with the same bytes as an unknown account.
|
||||
*/
|
||||
const MAX_SELECTOR_LENGTH = 64;
|
||||
|
||||
/**
|
||||
* What, if anything, this request says it is acting as.
|
||||
*
|
||||
* `misplaced-header` is its own case rather than an error thrown at read time
|
||||
* so that every mode below decides for itself — the modes disagree about the
|
||||
* session carrier and must not disagree about this one by accident.
|
||||
*/
|
||||
type ActingCarrier =
|
||||
| { kind: "none" }
|
||||
| { kind: "session"; accountId: string }
|
||||
| { kind: "header"; accountId: string }
|
||||
| { kind: "misplaced-header" };
|
||||
|
||||
/** The selector header, or null when the request did not send one. */
|
||||
async function readSelectorHeader(): Promise<string | null> {
|
||||
try {
|
||||
const headerList = await headers();
|
||||
return headerList.get(ACCOUNT_SELECTOR_HEADER);
|
||||
} catch {
|
||||
// Outside a Next.js request scope (direct unit invocation of a legacy
|
||||
// route) there is no header to read. Same posture as the Bearer branch of
|
||||
// `authenticateCaller`.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
export { ACCOUNT_SELECTOR_HEADER } from "./auth/acting-carrier";
|
||||
|
||||
/**
|
||||
* The acting-account carrier for this request.
|
||||
@@ -677,32 +638,11 @@ async function readSelectorHeader(): Promise<string | null> {
|
||||
* next request rather than from the next login.
|
||||
*/
|
||||
async function readActingCarrier(auth: AuthContext): Promise<ActingCarrier> {
|
||||
const header = await readSelectorHeader();
|
||||
|
||||
if (auth.authMethod === "bearer") {
|
||||
// No session row exists on this transport, so the header is the only
|
||||
// carrier there could be.
|
||||
return header === null
|
||||
? { kind: "none" }
|
||||
: { kind: "header", accountId: header };
|
||||
}
|
||||
|
||||
if (header !== null) return { kind: "misplaced-header" };
|
||||
|
||||
const stamped = auth.session.actingAsUserId ?? null;
|
||||
return stamped === null
|
||||
? { kind: "none" }
|
||||
: { kind: "session", accountId: stamped };
|
||||
}
|
||||
|
||||
/** Could this value name an account at all? */
|
||||
function selectorNamesAnAccount(value: string): boolean {
|
||||
return value.length > 0 && value.length <= MAX_SELECTOR_LENGTH;
|
||||
}
|
||||
|
||||
/** The account a carrier names, or null when it names nothing. */
|
||||
function carrierTarget(carrier: ActingCarrier): string | null {
|
||||
return "accountId" in carrier ? carrier.accountId : null;
|
||||
return decideActingCarrier({
|
||||
transport: auth.authMethod === "bearer" ? "bearer" : "cookie",
|
||||
stamped: auth.session.actingAsUserId ?? null,
|
||||
header: await readSelectorHeader(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* What a request says it is acting as.
|
||||
*
|
||||
* Two things in the app have to answer that question, and they have to answer
|
||||
* it the same way:
|
||||
*
|
||||
* * `requireRecordAuth` (`src/lib/api-handler.ts`), which turns the claim
|
||||
* into a data scope after checking a live grant.
|
||||
* * `withIdempotency` (`src/lib/idempotency.ts`), which files the replay cell
|
||||
* under the record the request claims — before any handler runs, so it
|
||||
* cannot wait for the grant check the handler performs.
|
||||
*
|
||||
* The claim is a SELECTOR and never an authorisation. Nothing in this file
|
||||
* looks at a grant, and no caller may treat a carrier as permission: the
|
||||
* account named here is an id to be checked. What it decides is only which
|
||||
* account is being named, and by which transport — the question `grants.ts`
|
||||
* warns must have exactly one answer, because a second implementation of it
|
||||
* drifts and the copy that drifts is the one nobody reads.
|
||||
*
|
||||
* The transport rules, unchanged from where they were first written:
|
||||
*
|
||||
* * The cookie transport carries the claim on the session ROW. A browser
|
||||
* cannot address that row, so the value is server state written only by
|
||||
* the switch endpoint after it validated a grant.
|
||||
* * The Bearer transport carries it in a per-request HEADER. A long-lived
|
||||
* token must not accumulate switch state.
|
||||
* * The header on a cookie request is `misplaced`, not ignored — a client
|
||||
* that believes it is selecting an account and is not produces a support
|
||||
* case about data that looks wrong.
|
||||
*/
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
|
||||
/**
|
||||
* The per-request account selector, on the Bearer transport only.
|
||||
*
|
||||
* Cross-origin JavaScript cannot set it: a custom request header forces a CORS
|
||||
* preflight and this app sends no CORS headers at all, so the preflight is
|
||||
* never answered. It is a selector regardless — the grant table is what
|
||||
* authorises, and the header is treated as hostile input everywhere it is read.
|
||||
*/
|
||||
export const ACCOUNT_SELECTOR_HEADER = "x-healthlog-account";
|
||||
|
||||
/**
|
||||
* Longest selector value worth a database round trip. Account ids are 25-char
|
||||
* cuids; anything past this names no account that could exist and is refused
|
||||
* as such, on the same path and with the same bytes as an unknown account.
|
||||
*/
|
||||
export const MAX_SELECTOR_LENGTH = 64;
|
||||
|
||||
/**
|
||||
* What, if anything, this request says it is acting as.
|
||||
*
|
||||
* `misplaced-header` is its own case rather than an error thrown at read time
|
||||
* so that every caller decides for itself — the callers disagree about what to
|
||||
* do with a misplaced claim and must not disagree about detecting one.
|
||||
*/
|
||||
export type ActingCarrier =
|
||||
| { kind: "none" }
|
||||
| { kind: "session"; accountId: string }
|
||||
| { kind: "header"; accountId: string }
|
||||
| { kind: "misplaced-header" };
|
||||
|
||||
/** The selector header, or null when the request did not send one. */
|
||||
export async function readSelectorHeader(): Promise<string | null> {
|
||||
try {
|
||||
const headerList = await headers();
|
||||
return headerList.get(ACCOUNT_SELECTOR_HEADER);
|
||||
} catch {
|
||||
// Outside a Next.js request scope (direct unit invocation of a legacy
|
||||
// route) there is no header to read. Same posture as the Bearer branch of
|
||||
// `authenticateCaller`.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The carrier decision itself, as a pure function of what the transport
|
||||
* carried. Pure on purpose: it is the one statement of the rule, and a rule
|
||||
* that needs a request context to be read is a rule that gets re-implemented.
|
||||
*/
|
||||
export function decideActingCarrier(input: {
|
||||
transport: "cookie" | "bearer";
|
||||
/** The session row's stamp. Ignored on the Bearer transport, which has none. */
|
||||
stamped: string | null;
|
||||
header: string | null;
|
||||
}): ActingCarrier {
|
||||
if (input.transport === "bearer") {
|
||||
// No session row exists on this transport, so the header is the only
|
||||
// carrier there could be.
|
||||
return input.header === null
|
||||
? { kind: "none" }
|
||||
: { kind: "header", accountId: input.header };
|
||||
}
|
||||
|
||||
if (input.header !== null) return { kind: "misplaced-header" };
|
||||
|
||||
return input.stamped === null
|
||||
? { kind: "none" }
|
||||
: { kind: "session", accountId: input.stamped };
|
||||
}
|
||||
|
||||
/** The account a carrier names, or null when it names nothing. */
|
||||
export function carrierTarget(carrier: ActingCarrier): string | null {
|
||||
return "accountId" in carrier ? carrier.accountId : null;
|
||||
}
|
||||
|
||||
/** Could this value name an account at all? */
|
||||
export function selectorNamesAnAccount(value: string): boolean {
|
||||
return value.length > 0 && value.length <= MAX_SELECTOR_LENGTH;
|
||||
}
|
||||
|
||||
/**
|
||||
* The account this request CLAIMS, resolved without an auth context in hand.
|
||||
*
|
||||
* For callers that run BEFORE authentication has been resolved into a context —
|
||||
* today that is the idempotency wrapper, which has to know which record a
|
||||
* request is aimed at before it decides whether the answer is already cached.
|
||||
* It resolves the session itself for exactly one reason: the transport decides
|
||||
* which carrier counts, and "there is a valid session" is what the transport
|
||||
* is. Guessing it from the presence of a cookie or an `Authorization` header
|
||||
* would be a second, weaker answer to a question this file exists to answer
|
||||
* once — and the case it gets wrong (a stale session cookie beside a live
|
||||
* Bearer token) is precisely a delegated write landing in the wrong cell.
|
||||
*
|
||||
* The cost is one indexed session lookup on a request that is already about to
|
||||
* write. It is not shared with the caller's own auth resolution because the
|
||||
* resolver a route passes to `withIdempotency` is pluggable, and threading a
|
||||
* session through that seam would make every custom resolver responsible for a
|
||||
* question none of them asks.
|
||||
*
|
||||
* Returns the CLAIMED account, unverified and unchecked. The grant check
|
||||
* happens later, inside the handler, on every request.
|
||||
*/
|
||||
export async function readClaimedActingAccount(): Promise<string | null> {
|
||||
const header = await readSelectorHeader();
|
||||
let session: Awaited<ReturnType<typeof getSession>> = null;
|
||||
try {
|
||||
session = await getSession();
|
||||
} catch {
|
||||
// A session that cannot be resolved is not a switched one. The request
|
||||
// still has to be authenticated by whatever wraps this call, and an
|
||||
// unauthenticated request claims nothing.
|
||||
session = null;
|
||||
}
|
||||
return carrierTarget(
|
||||
decideActingCarrier({
|
||||
transport: session ? "cookie" : "bearer",
|
||||
stamped: session?.session.actingAsUserId ?? null,
|
||||
header,
|
||||
}),
|
||||
);
|
||||
}
|
||||
+65
-1
@@ -6,12 +6,21 @@
|
||||
* retry within the TTL (24h) for the same `(userId, key, method, path)`
|
||||
* tuple returns the cached envelope as a 200 (carrying the original
|
||||
* status inside the JSON if needed) — no second side-effect.
|
||||
*
|
||||
* `userId` is the CALLER. Since a caller can act on somebody else's record,
|
||||
* the record the request claims is folded into `key` (see `cellKey`), so the
|
||||
* tuple identifies a request to one person's record rather than a request by
|
||||
* one person. A caller acting only as themselves is unaffected, byte for byte.
|
||||
*/
|
||||
import type { NextRequest } from "next/server";
|
||||
import { headers } from "next/headers";
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import {
|
||||
readClaimedActingAccount,
|
||||
selectorNamesAnAccount,
|
||||
} from "@/lib/auth/acting-carrier";
|
||||
import { hashToken } from "@/lib/auth/hmac";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { isP2002 } from "@/lib/prisma-errors";
|
||||
@@ -37,6 +46,34 @@ const PENDING_STATUS = 0;
|
||||
|
||||
const KEY_REGEX = /^[A-Za-z0-9_\-:.]{8,128}$/;
|
||||
|
||||
/**
|
||||
* Separates the record from the client's key inside a cell's `key` column.
|
||||
*
|
||||
* `KEY_REGEX` above does not admit it, which is the whole reason it was
|
||||
* chosen: a caller cannot hand-craft a key that lands in the cell of a request
|
||||
* they are not making. Changing either one without the other reopens that.
|
||||
*/
|
||||
const RECORD_SEPARATOR = "|";
|
||||
|
||||
/**
|
||||
* The `key` column for a request, given the record it claims to act on.
|
||||
*
|
||||
* Why the key and not the owner column: `IdempotencyKey.userId` is a foreign
|
||||
* key to `users` with a cascade behind it (`prisma/schema.prisma`), so it can
|
||||
* hold one real account id and nothing composite. It keeps holding the ACTOR —
|
||||
* which is what makes "two delegates, one owner, one key" two cells without
|
||||
* anything extra — and the record joins the other half of the composite unique
|
||||
* index instead.
|
||||
*
|
||||
* No carrier means the key the client sent, byte for byte. Every request that
|
||||
* is nobody's delegate therefore files exactly where it filed before, and the
|
||||
* fold cannot change the behaviour of a client that never heard of sharing.
|
||||
*/
|
||||
function cellKey(clientKey: string, actingAccountId: string | null): string {
|
||||
if (actingAccountId === null) return clientKey;
|
||||
return `${actingAccountId}${RECORD_SEPARATOR}${clientKey}`;
|
||||
}
|
||||
|
||||
export interface IdempotencyContext {
|
||||
userId: string;
|
||||
key: string;
|
||||
@@ -288,6 +325,11 @@ export function isCachableStatus(status: number): boolean {
|
||||
* /external clients — without it, every Bearer-authed retry was running
|
||||
* the handler again and creating duplicate measurements (audit C-4).
|
||||
*
|
||||
* It resolves the CALLER and only the caller — which record they are aiming at
|
||||
* is a separate question, answered by `readClaimedActingAccount()` above and
|
||||
* folded into the key. Neither answer authorises anything: the handler runs
|
||||
* its own `requireAuth()` / `requireRecordAuth()` either way.
|
||||
*
|
||||
* Exported for unit testing; production callers should let
|
||||
* `withIdempotency()` pick this up automatically via its default arg.
|
||||
*/
|
||||
@@ -374,10 +416,32 @@ export function withIdempotency<
|
||||
const userId = await userIdResolver(...args);
|
||||
if (!userId) return handler(...args);
|
||||
|
||||
// Which RECORD this request is aimed at, as claimed by the transport and
|
||||
// not yet checked against a grant — the check belongs to the handler, and
|
||||
// this runs before it. One delegate posting the same key first for one
|
||||
// person and then for another must not meet themselves in a single cell:
|
||||
// that replays the first person's response, writes nothing to the second
|
||||
// person's record, and reports success. Nothing errors and nothing logs a
|
||||
// conflict, which is why it is folded here rather than left to call sites.
|
||||
//
|
||||
// The consequence of using the CLAIM: inside the 24h window a delegate
|
||||
// whose grant has since ended can still replay a key they already
|
||||
// completed, without the grant check running. They receive bytes they
|
||||
// already had and nothing new is written — a fresh key from them is
|
||||
// refused, because that request reaches the handler.
|
||||
const claimedRecord = await readClaimedActingAccount();
|
||||
if (claimedRecord !== null && !selectorNamesAnAccount(claimedRecord)) {
|
||||
// A claim that names no account that could exist. The request is refused
|
||||
// downstream; skipping the cache keeps a caller from writing an
|
||||
// arbitrarily long key into the table on the way to that refusal, and
|
||||
// never lets one fall back onto the un-delegated cell.
|
||||
return handler(...args);
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const ctx: IdempotencyContext = {
|
||||
userId,
|
||||
key,
|
||||
key: cellKey(key, claimedRecord),
|
||||
method: request.method,
|
||||
path: url.pathname,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* v1.36.x — "somebody else marked your dose" helper.
|
||||
*
|
||||
* What is pinned here, and why each one is a property rather than an
|
||||
* observation:
|
||||
*
|
||||
* 1. The notification is addressed to the OWNER and names the acting person
|
||||
* and the medication. The delegate is not a recipient anywhere in this
|
||||
* file, because there is no delegate-directed push to assert.
|
||||
* 2. The self refusal lives in the helper, so a future call site that forgets
|
||||
* to compare ids still cannot notify somebody about their own dose.
|
||||
* 3. A snooze is not a marking and produces nothing.
|
||||
* 4. The medication is read scoped to the owner — the name that reaches a
|
||||
* lock screen comes from the recipient's own rows.
|
||||
* 5. Nothing here throws: a failed notification never fails the write that
|
||||
* produced it.
|
||||
*
|
||||
* Mutation check (run before this file was committed): deleting the
|
||||
* `actorId === ownerId` guard turns "fires nothing when the owner marks their
|
||||
* own dose" red with `expected "spy" to not be called at all, but actually
|
||||
* been called 1 times`. Deleting the `messageKey === null` return turns the
|
||||
* snooze case red the same way.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const dispatchLocalisedMock = vi.fn();
|
||||
const addWarningMock = vi.fn();
|
||||
|
||||
vi.mock("@/lib/notifications/dispatch-localised", () => ({
|
||||
dispatchLocalisedNotification: (...args: unknown[]) =>
|
||||
dispatchLocalisedMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({
|
||||
getEvent: () => ({ addWarning: addWarningMock, addMeta: vi.fn() }),
|
||||
}));
|
||||
|
||||
const userFindUnique = vi.fn();
|
||||
const medicationFindFirst = vi.fn();
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
user: { findUnique: (...a: unknown[]) => userFindUnique(...a) },
|
||||
medication: { findFirst: (...a: unknown[]) => medicationFindFirst(...a) },
|
||||
},
|
||||
}));
|
||||
|
||||
import {
|
||||
delegatedIntakeMessageKey,
|
||||
notifyDelegatedIntake,
|
||||
} from "@/lib/notifications/delegated-intake";
|
||||
|
||||
const OWNER = "owner-account";
|
||||
const DELEGATE = "delegate-account";
|
||||
const MEDICATION = "med-1";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
userFindUnique.mockResolvedValue({
|
||||
username: "wren",
|
||||
displayName: "Wren",
|
||||
});
|
||||
medicationFindFirst.mockResolvedValue({ name: "Ramipril" });
|
||||
dispatchLocalisedMock.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
describe("delegatedIntakeMessageKey", () => {
|
||||
it("maps a marking to its own body and a snooze to nothing", () => {
|
||||
expect(delegatedIntakeMessageKey("taken")).toBe(
|
||||
"notifications.sharedRecordIntake.bodyTaken",
|
||||
);
|
||||
expect(delegatedIntakeMessageKey("skipped")).toBe(
|
||||
"notifications.sharedRecordIntake.bodySkipped",
|
||||
);
|
||||
expect(delegatedIntakeMessageKey("snoozed")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("notifyDelegatedIntake", () => {
|
||||
it("notifies the owner, naming the acting person and the medication", async () => {
|
||||
await notifyDelegatedIntake({
|
||||
ownerId: OWNER,
|
||||
actorId: DELEGATE,
|
||||
medicationId: MEDICATION,
|
||||
status: "taken",
|
||||
});
|
||||
|
||||
expect(dispatchLocalisedMock).toHaveBeenCalledTimes(1);
|
||||
expect(dispatchLocalisedMock).toHaveBeenCalledWith({
|
||||
userId: OWNER,
|
||||
eventType: "SHARED_RECORD_INTAKE",
|
||||
titleKey: "notifications.sharedRecordIntake.title",
|
||||
messageKey: "notifications.sharedRecordIntake.bodyTaken",
|
||||
params: { name: "Wren", medication: "Ramipril" },
|
||||
metadata: { medicationId: MEDICATION },
|
||||
});
|
||||
});
|
||||
|
||||
it("carries the skipped body for a skipped dose", async () => {
|
||||
await notifyDelegatedIntake({
|
||||
ownerId: OWNER,
|
||||
actorId: DELEGATE,
|
||||
medicationId: MEDICATION,
|
||||
status: "skipped",
|
||||
});
|
||||
|
||||
expect(dispatchLocalisedMock.mock.calls[0][0]).toMatchObject({
|
||||
messageKey: "notifications.sharedRecordIntake.bodySkipped",
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the username when the acting account set no display name", async () => {
|
||||
userFindUnique.mockResolvedValue({ username: "wren", displayName: null });
|
||||
|
||||
await notifyDelegatedIntake({
|
||||
ownerId: OWNER,
|
||||
actorId: DELEGATE,
|
||||
medicationId: MEDICATION,
|
||||
status: "taken",
|
||||
});
|
||||
|
||||
expect(dispatchLocalisedMock.mock.calls[0][0].params).toMatchObject({
|
||||
name: "wren",
|
||||
});
|
||||
});
|
||||
|
||||
it("fires nothing when the owner marks their own dose", async () => {
|
||||
await notifyDelegatedIntake({
|
||||
ownerId: OWNER,
|
||||
actorId: OWNER,
|
||||
medicationId: MEDICATION,
|
||||
status: "taken",
|
||||
});
|
||||
|
||||
expect(dispatchLocalisedMock).not.toHaveBeenCalled();
|
||||
// Not even a lookup: the refusal is the first thing the helper does.
|
||||
expect(userFindUnique).not.toHaveBeenCalled();
|
||||
expect(medicationFindFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fires nothing for a snooze", async () => {
|
||||
await notifyDelegatedIntake({
|
||||
ownerId: OWNER,
|
||||
actorId: DELEGATE,
|
||||
medicationId: MEDICATION,
|
||||
status: "snoozed",
|
||||
});
|
||||
|
||||
expect(dispatchLocalisedMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reads the medication scoped to the owner", async () => {
|
||||
await notifyDelegatedIntake({
|
||||
ownerId: OWNER,
|
||||
actorId: DELEGATE,
|
||||
medicationId: MEDICATION,
|
||||
status: "taken",
|
||||
});
|
||||
|
||||
expect(medicationFindFirst).toHaveBeenCalledWith({
|
||||
where: { id: MEDICATION, userId: OWNER },
|
||||
select: { name: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("stays silent, with a warning, when the medication is not the owner's", async () => {
|
||||
medicationFindFirst.mockResolvedValue(null);
|
||||
|
||||
await notifyDelegatedIntake({
|
||||
ownerId: OWNER,
|
||||
actorId: DELEGATE,
|
||||
medicationId: MEDICATION,
|
||||
status: "taken",
|
||||
});
|
||||
|
||||
expect(dispatchLocalisedMock).not.toHaveBeenCalled();
|
||||
expect(addWarningMock).toHaveBeenCalledWith(
|
||||
expect.stringContaining("medication=missing"),
|
||||
);
|
||||
});
|
||||
|
||||
it("swallows a dispatch failure so the write that produced it survives", async () => {
|
||||
dispatchLocalisedMock.mockRejectedValue(new Error("telegram is down"));
|
||||
|
||||
await expect(
|
||||
notifyDelegatedIntake({
|
||||
ownerId: OWNER,
|
||||
actorId: DELEGATE,
|
||||
medicationId: MEDICATION,
|
||||
status: "taken",
|
||||
}),
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
expect(addWarningMock).toHaveBeenCalledWith(
|
||||
expect.stringContaining("telegram is down"),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -381,6 +381,58 @@ describe("dispatchNotification — per-event default policy (v1.4.25 W16c)", ()
|
||||
|
||||
expect(sendViaNtfyMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// v1.36.x — the delegated-dose event goes the other way from
|
||||
// PERSONAL_RECORD: ON without a row, because the owner invited the person
|
||||
// whose action produces it. Both positions of the preference are asserted,
|
||||
// so "default ON" cannot be true only because the dispatcher ignores the
|
||||
// event entirely.
|
||||
it("SHARED_RECORD_INTAKE defaults ON when no preference row exists", async () => {
|
||||
const channel = makeChannel({
|
||||
type: "NTFY",
|
||||
config: JSON.stringify({
|
||||
serverUrl: "https://ntfy.example",
|
||||
topic: "t",
|
||||
}),
|
||||
preferences: [],
|
||||
});
|
||||
vi.mocked(prisma.notificationChannel.findMany).mockResolvedValueOnce([
|
||||
channel,
|
||||
] as never);
|
||||
sendViaNtfyMock.mockResolvedValueOnce({ ok: true });
|
||||
|
||||
await dispatchNotification({
|
||||
eventType: "SHARED_RECORD_INTAKE",
|
||||
userId: "u-1",
|
||||
title: "Wren marked a dose",
|
||||
message: "Ramipril: marked as taken by Wren.",
|
||||
});
|
||||
|
||||
expect(sendViaNtfyMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("SHARED_RECORD_INTAKE is suppressed by an explicit per-channel opt-out", async () => {
|
||||
const channel = makeChannel({
|
||||
type: "NTFY",
|
||||
config: JSON.stringify({
|
||||
serverUrl: "https://ntfy.example",
|
||||
topic: "t",
|
||||
}),
|
||||
preferences: [{ eventType: "SHARED_RECORD_INTAKE", enabled: false }],
|
||||
});
|
||||
vi.mocked(prisma.notificationChannel.findMany).mockResolvedValueOnce([
|
||||
channel,
|
||||
] as never);
|
||||
|
||||
await dispatchNotification({
|
||||
eventType: "SHARED_RECORD_INTAKE",
|
||||
userId: "u-1",
|
||||
title: "Wren marked a dose",
|
||||
message: "Ramipril: marked as taken by Wren.",
|
||||
});
|
||||
|
||||
expect(sendViaNtfyMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("dispatchNotification — MOOD_REMINDER single source of truth (v1.7.0)", () => {
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* Every event type the /notifications matrix renders has words to render.
|
||||
*
|
||||
* The matrix builds its rows from `EVENT_TYPES` and derives each row's label
|
||||
* and description key from the event name, so a new event type silently gets a
|
||||
* row whether or not anybody wrote the two strings for it. That is not a
|
||||
* theory: `SECURITY_ALERT` shipped in v1.23 and rendered the raw key
|
||||
* `notifications.eventSecurityAlert` in the matrix until v1.36.x, because
|
||||
* nothing anywhere asserted the pairing — the forward i18n coverage test only
|
||||
* sees literal `t("…")` call sites, and this key is assembled from a runtime
|
||||
* value.
|
||||
*
|
||||
* So this test walks the event list the page walks, computes the keys the page
|
||||
* computes, and asserts both resolve in every locale bundle.
|
||||
*
|
||||
* Mutation check: remove `notifications.eventSharedRecordIntakeDesc` from
|
||||
* `messages/pl.json` and this file reports
|
||||
* `pl is missing notifications.eventSharedRecordIntakeDesc`.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { EVENT_TYPES } from "@/lib/notifications/types";
|
||||
import {
|
||||
eventDescriptionTranslationKey,
|
||||
eventTranslationKey,
|
||||
} from "@/lib/notifications/event-labels";
|
||||
|
||||
const MESSAGES_DIR = join(__dirname, "../../../../messages");
|
||||
|
||||
function bundle(locale: string): Record<string, unknown> {
|
||||
return JSON.parse(
|
||||
readFileSync(join(MESSAGES_DIR, `${locale}.json`), "utf8"),
|
||||
) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function resolve(root: Record<string, unknown>, key: string): unknown {
|
||||
return key
|
||||
.split(".")
|
||||
.reduce<unknown>(
|
||||
(node, part) =>
|
||||
node && typeof node === "object"
|
||||
? (node as Record<string, unknown>)[part]
|
||||
: undefined,
|
||||
root,
|
||||
);
|
||||
}
|
||||
|
||||
const LOCALES = readdirSync(MESSAGES_DIR)
|
||||
.filter((f) => f.endsWith(".json"))
|
||||
.map((f) => f.replace(/\.json$/, ""));
|
||||
|
||||
describe("notification event labels", () => {
|
||||
it("derives the key the matrix renders under", () => {
|
||||
expect(eventTranslationKey("MEDICATION_REMINDER")).toBe(
|
||||
"notifications.eventMedicationReminder",
|
||||
);
|
||||
expect(eventDescriptionTranslationKey("SHARED_RECORD_INTAKE")).toBe(
|
||||
"notifications.eventSharedRecordIntakeDesc",
|
||||
);
|
||||
});
|
||||
|
||||
it("has a label and a description for every event type, in every locale", () => {
|
||||
expect(LOCALES.length).toBeGreaterThanOrEqual(6);
|
||||
expect(EVENT_TYPES.length).toBeGreaterThan(10);
|
||||
|
||||
const missing: string[] = [];
|
||||
for (const locale of LOCALES) {
|
||||
const root = bundle(locale);
|
||||
for (const eventType of EVENT_TYPES) {
|
||||
for (const key of [
|
||||
eventTranslationKey(eventType),
|
||||
eventDescriptionTranslationKey(eventType),
|
||||
]) {
|
||||
const value = resolve(root, key);
|
||||
if (typeof value !== "string" || value.trim().length === 0) {
|
||||
missing.push(`${locale} is missing ${key}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the delegated-dose push copy", () => {
|
||||
it("interpolates the same names in every locale", () => {
|
||||
const keys = [
|
||||
"notifications.sharedRecordIntake.title",
|
||||
"notifications.sharedRecordIntake.bodyTaken",
|
||||
"notifications.sharedRecordIntake.bodySkipped",
|
||||
];
|
||||
const placeholders: Record<string, string[]> = {
|
||||
"notifications.sharedRecordIntake.title": ["{name}"],
|
||||
"notifications.sharedRecordIntake.bodyTaken": ["{name}", "{medication}"],
|
||||
"notifications.sharedRecordIntake.bodySkipped": [
|
||||
"{name}",
|
||||
"{medication}",
|
||||
],
|
||||
};
|
||||
|
||||
for (const locale of LOCALES) {
|
||||
const root = bundle(locale);
|
||||
for (const key of keys) {
|
||||
const value = resolve(root, key);
|
||||
expect(typeof value, `${locale} ${key}`).toBe("string");
|
||||
for (const token of placeholders[key]) {
|
||||
expect(value as string, `${locale} ${key}`).toContain(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* v1.36.x — "somebody else marked your dose".
|
||||
*
|
||||
* The one notification a delegated write produces. Everything else a delegate
|
||||
* adds to a shared record (a reading, a lab result, an allergy) is bookkeeping
|
||||
* and lives in the owner's activity view; a dose is a statement about the
|
||||
* owner's own body, and the owner is the person best placed to decide whether
|
||||
* they want to hear about it. So this rides the ordinary alert cascade with an
|
||||
* ordinary per-channel preference row, and nothing about it is special-cased
|
||||
* inside the dispatcher.
|
||||
*
|
||||
* Two properties are structural rather than observed:
|
||||
*
|
||||
* 1. **It refuses to fire on self.** The owner never gets a push about their
|
||||
* own dose. The refusal lives HERE, not at the call sites, so a future
|
||||
* route that calls this helper cannot forget it.
|
||||
* 2. **It addresses the owner and only the owner.** The delegate gets their
|
||||
* feedback from the response they are already awaiting, rendered in their
|
||||
* own session. There is no delegate-directed push and this file is not the
|
||||
* place to grow one: the dispatcher takes a `userId`, and under record
|
||||
* substitution that id is the owner by design.
|
||||
*
|
||||
* The medication is named in the push body, the same verbosity class as
|
||||
* MEDICATION_REMINDER, which has named medications on the lock screen since
|
||||
* v1.4.40. No dose figures ride along.
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getEvent } from "@/lib/logging/context";
|
||||
import { accountLabel } from "@/lib/sharing/account-access-view";
|
||||
import { dispatchLocalisedNotification } from "@/lib/notifications/dispatch-localised";
|
||||
|
||||
/**
|
||||
* The dose states the intake routes write. `"snoozed"` is deliberately in the
|
||||
* union: both intake routes can produce it, and the helper answering "that one
|
||||
* is not a marking" in one place beats every call site remembering to.
|
||||
*/
|
||||
export type DelegatedIntakeStatus = "taken" | "skipped" | "snoozed";
|
||||
|
||||
/**
|
||||
* Which body the push carries for a dose state, or `null` when the state is
|
||||
* not a marking at all.
|
||||
*
|
||||
* Pure, exported, and tested on its own: a snooze moves a dose, it does not
|
||||
* resolve it, and the web-push dose-clear draws the same line (`intake/route
|
||||
* .ts` clears the pending reminder for taken / skipped only). An owner woken
|
||||
* by "your carer postponed a dose by ten minutes" would be the noise this
|
||||
* whole event type is trying not to be.
|
||||
*/
|
||||
export function delegatedIntakeMessageKey(
|
||||
status: DelegatedIntakeStatus,
|
||||
): string | null {
|
||||
switch (status) {
|
||||
case "taken":
|
||||
return "notifications.sharedRecordIntake.bodyTaken";
|
||||
case "skipped":
|
||||
return "notifications.sharedRecordIntake.bodySkipped";
|
||||
case "snoozed":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface NotifyDelegatedIntakeInput {
|
||||
/** The account the dose belongs to — the recipient of the notification. */
|
||||
ownerId: string;
|
||||
/** The account that actually marked it. Equal to `ownerId` on a self-write. */
|
||||
actorId: string;
|
||||
/** The medication whose dose was marked. Resolved for its name, owner-scoped. */
|
||||
medicationId: string;
|
||||
/** What the dose was marked as. */
|
||||
status: DelegatedIntakeStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell the owner that somebody else marked one of their doses.
|
||||
*
|
||||
* Never throws: a notification that fails is not a reason to fail the write
|
||||
* that produced it. Await it — the call sites reach this only on a delegated
|
||||
* write, so the added latency lands on the caregiver's request and never on
|
||||
* the owner's own hot path, and awaiting is what makes "one row in
|
||||
* `push_attempts`" a thing a test can assert rather than a thing it can race.
|
||||
*/
|
||||
export async function notifyDelegatedIntake(
|
||||
input: NotifyDelegatedIntakeInput,
|
||||
): Promise<void> {
|
||||
const { ownerId, actorId, medicationId, status } = input;
|
||||
|
||||
// The self refusal. First, cheap, and unconditional.
|
||||
if (actorId === ownerId) return;
|
||||
|
||||
const messageKey = delegatedIntakeMessageKey(status);
|
||||
if (messageKey === null) return;
|
||||
|
||||
try {
|
||||
const [actor, medication] = await Promise.all([
|
||||
prisma.user.findUnique({
|
||||
where: { id: actorId },
|
||||
select: { username: true, displayName: true },
|
||||
}),
|
||||
// Scoped to the owner: the name in this body goes onto the owner's lock
|
||||
// screen, so it is read from the owner's own row set or not at all.
|
||||
prisma.medication.findFirst({
|
||||
where: { id: medicationId, userId: ownerId },
|
||||
select: { name: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
// Both halves of the sentence or none of it. An acting account that no
|
||||
// longer resolves is nobody we can name, and a medication that does not
|
||||
// resolve under the OWNER is not one whose name belongs on their lock
|
||||
// screen. Neither is reachable from the intake routes, which have both
|
||||
// rows in hand before they call; a warning to ops beats a push that says
|
||||
// "somebody marked something".
|
||||
if (!actor || !medication) {
|
||||
getEvent()?.addWarning(
|
||||
`notifyDelegatedIntake — nothing to name (actor=${actor ? "ok" : "missing"} medication=${medication ? "ok" : "missing"}), no notification sent`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await dispatchLocalisedNotification({
|
||||
userId: ownerId,
|
||||
eventType: "SHARED_RECORD_INTAKE",
|
||||
titleKey: "notifications.sharedRecordIntake.title",
|
||||
messageKey,
|
||||
params: {
|
||||
name: accountLabel(actor),
|
||||
medication: medication.name,
|
||||
},
|
||||
metadata: { medicationId },
|
||||
});
|
||||
} catch (err) {
|
||||
getEvent()?.addWarning(
|
||||
`notifyDelegatedIntake failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* The i18n key an event type is rendered under.
|
||||
*
|
||||
* The /notifications matrix builds its rows from the event list the server
|
||||
* publishes, so the label for a new event type is never written at a call site
|
||||
* — it is derived here. Extracted from the page so the derivation can be
|
||||
* pinned by a test without rendering anything, and so the guard that asserts
|
||||
* every event type actually HAS its two strings (label + description, six
|
||||
* locales) computes the key exactly the way the page does rather than a way
|
||||
* that agrees with it today.
|
||||
*
|
||||
* `MEDICATION_REMINDER` → `notifications.eventMedicationReminder`; the
|
||||
* description key is that plus `Desc`.
|
||||
*/
|
||||
export function eventTranslationKey(eventType: string): string {
|
||||
return (
|
||||
"notifications.event" +
|
||||
eventType
|
||||
.toLowerCase()
|
||||
.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase())
|
||||
.replace(/^./, (c) => c.toUpperCase())
|
||||
);
|
||||
}
|
||||
|
||||
/** The description key that sits under the label in the matrix row. */
|
||||
export function eventDescriptionTranslationKey(eventType: string): string {
|
||||
return `${eventTranslationKey(eventType)}Desc`;
|
||||
}
|
||||
@@ -112,6 +112,16 @@ export const EVENT_TYPES = [
|
||||
// morning window, so a concerning reading always stays on
|
||||
// `MEASUREMENT_ANOMALY` and this never bypasses Focus.
|
||||
"DAILY_BRIEFING",
|
||||
// v1.36.x — somebody with a write grant on this record marked one of the
|
||||
// owner's doses. The only notification a delegated write produces: every
|
||||
// other shared-record write is bookkeeping and stays in the owner's activity
|
||||
// view, while "somebody said I took my tablets" is a fact about the owner's
|
||||
// own body that they should not have to go looking for. Addressed to the
|
||||
// OWNER — the delegate learns what they did from the response in their own
|
||||
// session, not from a push (there is no channel that could carry it: the
|
||||
// dispatcher addresses a userId, and under record substitution that userId
|
||||
// is the owner by design). Default ON, see EVENT_DEFAULT_ENABLED.
|
||||
"SHARED_RECORD_INTAKE",
|
||||
] as const;
|
||||
export type EventType = (typeof EVENT_TYPES)[number];
|
||||
|
||||
@@ -179,6 +189,14 @@ export const EVENT_DEFAULT_ENABLED: Record<EventType, boolean> = {
|
||||
// channel that has no explicit enabled row, so a fresh account never
|
||||
// receives a morning push it did not ask for.
|
||||
DAILY_BRIEFING: false,
|
||||
// v1.36.x — ON by default, deliberately against the PERSONAL_RECORD opt-in
|
||||
// precedent. The event cannot exist unless the owner invited a second person
|
||||
// and gave them write access, so there is no backfill class of volume to
|
||||
// protect against; and an owner who has to discover a setting before they
|
||||
// learn that somebody else marks their doses was never told at all. The row
|
||||
// sits in the /notifications matrix from day one, so an owner who finds it
|
||||
// noisy silences it per channel with one switch.
|
||||
SHARED_RECORD_INTAKE: true,
|
||||
};
|
||||
|
||||
export const CHANNEL_TYPE_LABELS: Record<ChannelType, string> = {
|
||||
|
||||
@@ -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