Merge pull request #704 from MBombeck/fix/grant-invite-expiry

Let somebody actually set the date a shared access lapses on
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-08-02 21:21:24 +02:00
commit 1efd337f53
10 files changed
+153 -15

No files matched your search

+34
View File
@@ -172,6 +172,13 @@ test.describe("account sharing", () => {
await ownerContext.close();
});
/** A `YYYY-MM-DD` day the date input accepts, N days from now. */
function isoDayFromNow(days: number): string {
const d = new Date();
d.setDate(d.getDate() + days);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}
test("the owner invites, and the invitation confers nothing yet", async () => {
await ownerPage.goto("/settings/access");
@@ -187,7 +194,34 @@ test.describe("account sharing", () => {
await identifier.fill(E2E_USER.username);
await expect(submit).toBeEnabled({ timeout: 1000 });
}).toPass({ timeout: 15_000 });
// The lapse date, through the real form and onto the real wire.
//
// `expiresAt` was accepted, stored and annotated on by the route from the
// day the grant model shipped, while the card sent a hardcoded `null`. The
// component test cannot see that: it renders the control and checks the
// date mapping, and BOTH still pass with the card wired back to `null`.
// Only reading the posted body proves the value a person typed is the
// value the server receives, which is the half that was missing.
const lapse = ownerPage.locator('[data-slot="grant-invite-expires"]');
await expect(lapse).toBeVisible();
const chosenDay = isoDayFromNow(30);
await lapse.fill(chosenDay);
const invitePost = ownerPage.waitForRequest(
(req) =>
req.method() === "POST" && req.url().endsWith("/api/account/grants"),
);
await submit.click();
const posted = JSON.parse((await invitePost).postData() ?? "{}") as {
expiresAt?: string | null;
};
expect(
posted.expiresAt,
"the invitation must carry the day the owner chose",
).toBeTruthy();
// End of the chosen day, not the midnight that starts it.
expect(posted.expiresAt).toContain(chosenDay.slice(0, 8));
const row = ownerPage
.locator('[data-slot="grants-given-list"] [data-slot="grant-row"]')
+2
View File
@@ -9424,6 +9424,8 @@
"identifierLabel": "Benutzername oder E-Mail",
"identifierPlaceholder": "Der Name, mit dem sie sich anmeldet",
"identifierHint": "Die Person braucht ein Konto auf dieser Instanz. An eine E-Mail-Adresse ohne Registrierung lässt sich keine Einladung schicken.",
"expiresLabel": "Zugriff endet am (optional)",
"expiresHint": "Leer lassen für Zugriff, der gilt, bis ihn jemand beendet. Ein Datum wird bei jeder Anfrage geprüft, der Zugriff endet also am Ende dieses Tages von selbst.",
"submit": "Einladung senden",
"submitting": "Wird gesendet…",
"sent": "Einladung an {name} gesendet.",
+2
View File
@@ -9424,6 +9424,8 @@
"identifierLabel": "Username or e-mail",
"identifierPlaceholder": "The name they sign in with",
"identifierHint": "They need an account on this instance. Invitations cannot be sent to an e-mail address that has not registered.",
"expiresLabel": "Access ends on (optional)",
"expiresHint": "Leave this empty for access that lasts until somebody ends it. A date here is checked on every request, so access stops on its own at the end of that day.",
"submit": "Send invitation",
"submitting": "Sending…",
"sent": "Invitation sent to {name}.",
+2
View File
@@ -9424,6 +9424,8 @@
"identifierLabel": "Usuario o correo electrónico",
"identifierPlaceholder": "El nombre con el que inicia sesión",
"identifierHint": "Necesita una cuenta en esta instancia. No se pueden enviar invitaciones a una dirección que no se haya registrado.",
"expiresLabel": "El acceso termina el (opcional)",
"expiresHint": "Déjalo vacío para un acceso que dure hasta que alguien lo termine. Una fecha aquí se comprueba en cada petición, así que el acceso se detiene solo al final de ese día.",
"submit": "Enviar invitación",
"submitting": "Enviando…",
"sent": "Invitación enviada a {name}.",
+2
View File
@@ -9424,6 +9424,8 @@
"identifierLabel": "Nom d'utilisateur ou e-mail",
"identifierPlaceholder": "Le nom avec lequel elle se connecte",
"identifierHint": "Cette personne a besoin d'un compte sur cette instance. Une invitation ne peut pas être envoyée à une adresse non inscrite.",
"expiresLabel": "L'accès prend fin le (facultatif)",
"expiresHint": "Laissez ce champ vide pour un accès qui dure jusqu'à ce que quelqu'un y mette fin. Une date ici est vérifiée à chaque requête, l'accès s'arrête donc de lui-même à la fin de cette journée.",
"submit": "Envoyer l'invitation",
"submitting": "Envoi…",
"sent": "Invitation envoyée à {name}.",
+2
View File
@@ -9424,6 +9424,8 @@
"identifierLabel": "Nome utente o e-mail",
"identifierPlaceholder": "Il nome con cui accede",
"identifierHint": "Serve un account su questa istanza. Non è possibile inviare inviti a un indirizzo non registrato.",
"expiresLabel": "L'accesso termina il (facoltativo)",
"expiresHint": "Lascia vuoto per un accesso che dura finché qualcuno non lo termina. Una data qui viene controllata a ogni richiesta, quindi l'accesso si interrompe da solo alla fine di quel giorno.",
"submit": "Invia invito",
"submitting": "Invio…",
"sent": "Invito inviato a {name}.",
+2
View File
@@ -9424,6 +9424,8 @@
"identifierLabel": "Nazwa użytkownika lub e-mail",
"identifierPlaceholder": "Nazwa, którą się loguje",
"identifierHint": "Ta osoba potrzebuje konta na tej instancji. Nie można wysłać zaproszenia na niezarejestrowany adres.",
"expiresLabel": "Dostęp kończy się (opcjonalnie)",
"expiresHint": "Zostaw puste, aby dostęp trwał, dopóki ktoś go nie zakończy. Data jest sprawdzana przy każdym żądaniu, więc dostęp kończy się sam z końcem tego dnia.",
"submit": "Wyślij zaproszenie",
"submitting": "Wysyłanie…",
"sent": "Zaproszenie wysłane do {name}.",
@@ -519,20 +519,6 @@ const REGISTRY: DestructiveEntry[] = [
undetected:
"Same shape as the card above, and one step further out of reach: renouncing is a POST, so not even a DELETE goes out. The path (`/api/account/grants/{id}/renounce`) names an act the D2 vocabulary does not carry, and it lives in the hook regardless. Registered by hand.",
},
{
file: "components/settings/access/grant-invite-card.tsx",
destroys:
"nothing — it offers access, and the offer confers nothing until the other person accepts it",
recovery: "permanent",
confirm: [],
unconfirmed: [
{
control: "the invitation form",
reason:
"D3 flags this file for `expiresAt: null` in the invite payload, reading it as a field being blanked. It is not: null means the grant runs until somebody ends it, which is the common household case and the absence of an expiry rather than the removal of one. The form creates a pending row and destroys nothing, and gating a creation behind a confirmation dialog would teach people to click through the dialogs that do guard a loss.",
},
],
},
// ── Admin ───────────────────────────────────────────────────────────────
{
@@ -0,0 +1,65 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vitest";
import { I18nProvider } from "@/lib/i18n/context";
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 }),
};
});
import { GrantInviteCard, endOfDayIso } from "../grant-invite-card";
/**
* The lapse date, at both ends.
*
* `expiresAt` was accepted by the invite route, stored, and annotated on from
* the day the grant model shipped, while the card sent a hardcoded `null`. A
* release note said an invitation could carry a lapse date and no one could
* set one. That is the two-ended failure this repository keeps rediscovering,
* so both ends are pinned here: the control exists in the rendered form, and
* the value it produces is the END of the chosen day rather than the midnight
* that starts it.
*
* Project convention is SSR-only, no `@testing-library/react`; the mapping is
* exported so its contract can be pinned without a click, and the submit path
* is covered by the sharing browser spec.
*/
function render(node: React.ReactNode): string {
return renderToStaticMarkup(
<I18nProvider initialLocale="en">{node}</I18nProvider>,
);
}
describe("grant invitation lapse date", () => {
it("offers a date control on the invitation form", () => {
const html = render(<GrantInviteCard />);
expect(html).toContain('data-slot="grant-invite-expires"');
expect(html).toContain('type="date"');
});
it("maps a chosen day to the end of that day, not its midnight", () => {
const iso = endOfDayIso("2026-09-30");
expect(iso).not.toBeNull();
const end = new Date(iso as string);
// Read back in the same zone the mapping used, so the assertion holds
// wherever the suite runs rather than only under the pinned UTC clock.
expect(end.getFullYear()).toBe(2026);
expect(end.getMonth()).toBe(8);
expect(end.getDate()).toBe(30);
expect(end.getHours()).toBe(23);
expect(end.getMinutes()).toBe(59);
});
it("treats an empty field as no lapse date", () => {
expect(endOfDayIso("")).toBeNull();
});
it("refuses a value that is not a date rather than sending an invalid instant", () => {
expect(endOfDayIso("not-a-date")).toBeNull();
});
});
@@ -34,6 +34,7 @@ export function GrantInviteCard() {
const { t } = useTranslations();
const invite = useInviteGrant();
const [identifier, setIdentifier] = useState("");
const [expiresOn, setExpiresOn] = useState("");
const [error, setError] = useState<string | null>(null);
const [invited, setInvited] = useState<string | null>(null);
@@ -44,10 +45,11 @@ export function GrantInviteCard() {
setError(null);
setInvited(null);
invite.mutate(
{ identifier: value, expiresAt: null },
{ identifier: value, expiresAt: endOfDayIso(expiresOn) },
{
onSuccess: (grant) => {
setIdentifier("");
setExpiresOn("");
setInvited(grant.account.username);
},
onError: (err) => setError(t(inviteErrorKey(err))),
@@ -80,6 +82,22 @@ export function GrantInviteCard() {
{t("recordSharing.invite.identifierHint")}
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="grant-invite-expires">
{t("recordSharing.invite.expiresLabel")}
</Label>
<Input
id="grant-invite-expires"
data-slot="grant-invite-expires"
type="date"
value={expiresOn}
min={tomorrowIso()}
onChange={(e) => setExpiresOn(e.target.value)}
/>
<p className="text-muted-foreground text-xs">
{t("recordSharing.invite.expiresHint")}
</p>
</div>
<Button
type="submit"
data-slot="grant-invite-submit"
@@ -104,6 +122,29 @@ export function GrantInviteCard() {
);
}
/**
* The chosen day, as the instant access stops.
*
* A date input yields a bare `YYYY-MM-DD`, and the grant's `expiresAt` is
* checked live against `now` on every request. Anchoring at the END of the
* chosen day in the browser's own zone is what makes "until the 30th" mean the
* 30th rather than the midnight that starts it, which is the reading anybody
* picking a date has in mind. Empty means no lapse date, which is the default
* and stays the common case.
*/
export function endOfDayIso(day: string): string | null {
if (day.length === 0) return null;
const end = new Date(`${day}T23:59:59.999`);
return Number.isNaN(end.getTime()) ? null : end.toISOString();
}
/** The earliest day worth offering: a grant that lapses today confers nothing. */
function tomorrowIso(): string {
const d = new Date();
d.setDate(d.getDate() + 1);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}
/**
* The message for a refused invitation.
*