mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 07:13:29 +00:00
Merge remote-tracking branch 'origin/main' into feat/1371-medication-note
# Conflicts: # CHANGELOG.md
This commit is contained in:
commit
4b500dc66c
25 files changed
+1199
-157
No files matched your search
@@ -430,6 +430,49 @@ describe("T4 — declared scopes are exported constants, never string literals",
|
||||
});
|
||||
});
|
||||
|
||||
describe("T4a — `measurements:write` opens exactly three doors", () => {
|
||||
it("the two measurement writes and the custom-metric value write, POST only", () => {
|
||||
// The set of files naming the scope IS its reach. The single and batch
|
||||
// measurement writes, and logging a value against a custom metric the
|
||||
// person already made. Not the measurement reads, not the custom-metric
|
||||
// list or detail, and not creating, editing or deleting a metric: a
|
||||
// fourth file here is a widening and belongs in review.
|
||||
const declaring = sourceFiles().filter((rel) => {
|
||||
const src = read(rel);
|
||||
return (
|
||||
requireAuthScopes(src).includes("MEASUREMENTS_WRITE_SCOPE") ||
|
||||
recordAuthScopes(src).includes("MEASUREMENTS_WRITE_SCOPE")
|
||||
);
|
||||
});
|
||||
expect(declaring).toEqual([
|
||||
"app/api/custom-metrics/[id]/entries/route.ts",
|
||||
"app/api/measurements/batch/route.ts",
|
||||
"app/api/measurements/route.ts",
|
||||
]);
|
||||
|
||||
// Within the custom-metric file, once, and on the POST: the GET beside it
|
||||
// lists the metric's values and must keep refusing the token.
|
||||
const entries = readSource(
|
||||
"src/app/api/custom-metrics/[id]/entries/route.ts",
|
||||
"MEASUREMENTS_WRITE_SCOPE",
|
||||
);
|
||||
expect(
|
||||
requireAuthScopes(entries).filter(
|
||||
(x) => x === "MEASUREMENTS_WRITE_SCOPE",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(recordAuthScopes(entries)).toEqual([]);
|
||||
const postBody = entries.slice(
|
||||
entries.indexOf("async function postCustomMetricEntry"),
|
||||
);
|
||||
expect(
|
||||
requireAuthScopes(postBody).filter(
|
||||
(x) => x === "MEASUREMENTS_WRITE_SCOPE",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("T4b — `documents:write` opens exactly two doors", () => {
|
||||
it("only the vault upload and the source-key lookup declare the scope", () => {
|
||||
// The scope admits a narrow token wherever it is named, so the set of
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { apiHandler, requireAuth, requireRecordAuth } from "@/lib/api-handler";
|
||||
import {
|
||||
apiHandler,
|
||||
isScopedCredential,
|
||||
requireAuth,
|
||||
requireRecordAuth,
|
||||
} from "@/lib/api-handler";
|
||||
import {
|
||||
apiError,
|
||||
apiSuccess,
|
||||
@@ -16,6 +21,7 @@ import { encryptNote } from "@/lib/crypto/note-cipher";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { withIdempotency } from "@/lib/idempotency";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes";
|
||||
import {
|
||||
createCustomMetricEntrySchema,
|
||||
listCustomMetricEntriesSchema,
|
||||
@@ -28,8 +34,9 @@ import {
|
||||
* GET lists the metric's values with offset pagination (the chart + history
|
||||
* feed). POST records a value, snapshotting the metric's current `unit` onto
|
||||
* the entry at write time (historical truth). `userId` is always narrowed from
|
||||
* the session and the parent metric is verified owner-scoped (a forged / foreign
|
||||
* id is a 404) before any value is read or written.
|
||||
* the session (or, on POST, the measurement-ingest token) and the parent metric
|
||||
* is verified owner-scoped (a forged / foreign id is a 404) before any value is
|
||||
* read or written.
|
||||
*/
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
@@ -105,7 +112,27 @@ async function postCustomMetricEntry(
|
||||
// product did not offer. Whoever builds a delegate-reachable way to log a
|
||||
// tracked value adds it back in the same diff: the argument for admitting it
|
||||
// was never wrong, and the GET arm above stays delegable meanwhile.
|
||||
const { user } = await requireAuth();
|
||||
//
|
||||
// It does accept the measurement-ingest token (#1377): a custom metric's
|
||||
// value is a reading the person defined themselves, and the bridge that
|
||||
// pushes their weight is the one that would push it. What that admits is
|
||||
// this POST and nothing beside it. The GET above names no scope, nor do the
|
||||
// metric's own create / edit / delete routes, so the token can add a value
|
||||
// to a metric that already exists and cannot list the metrics, read one
|
||||
// back, or make a new one. The id it writes to comes from the person, who
|
||||
// reads it off the metric's page; a token that has only ever been pasted
|
||||
// into a scale's uploader never learns one.
|
||||
//
|
||||
// `requireAuth` rather than the record resolver, so the selector refusal is
|
||||
// the undeclared-mode one every credential meets here: the token is on its
|
||||
// owner's record or nowhere. The ownership query below then turns any id
|
||||
// that is not that owner's live metric into the same 404 an unknown id gets.
|
||||
const auth = await requireAuth(MEASUREMENTS_WRITE_SCOPE);
|
||||
const { user } = auth;
|
||||
// A custom-metric entry has no source column, so the row cannot say a
|
||||
// bridge wrote it the way an `EXTERNAL` measurement does. The audit row
|
||||
// can, and it names the token, so revoking the right one is possible later.
|
||||
const ingestTokenId = isScopedCredential(auth) ? auth.session.id : null;
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
@@ -156,12 +183,20 @@ async function postCustomMetricEntry(
|
||||
await auditLog("customMetricEntry.create", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { customMetricId: id, entryId: created.id },
|
||||
details: {
|
||||
customMetricId: id,
|
||||
entryId: created.id,
|
||||
...(ingestTokenId ? { ingestTokenId } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: { name: "custom-metric.entry.create" },
|
||||
meta: { customMetricId: id, entryId: created.id },
|
||||
meta: {
|
||||
customMetricId: id,
|
||||
entryId: created.id,
|
||||
via_ingest_scope: ingestTokenId !== null,
|
||||
},
|
||||
});
|
||||
invalidateUserCorrelationPatterns(user.id);
|
||||
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* The record switcher inside the account menu, at phone and desktop width
|
||||
* (#1372).
|
||||
*
|
||||
* On a phone the account menu sits against the right edge of the top bar and
|
||||
* takes most of the width. The records used to open in a side sub-menu that
|
||||
* had room on neither side, so it ran off the screen and cut the names off.
|
||||
* Below `sm` they now unfold inside the account menu itself; at desktop width
|
||||
* the side sub-menu stays.
|
||||
*
|
||||
* The harness mounts the switcher the way the top bar does: a right-aligned
|
||||
* trigger, `align="end"`, a `w-60` menu.
|
||||
*
|
||||
* Mutation check, run: forcing the side sub-menu at every width (the
|
||||
* component before the fix) turns "unfolds the records inside the account
|
||||
* menu" red, because the entries land outside the viewport and outside the
|
||||
* account menu.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { page, userEvent } from "vitest/browser";
|
||||
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import type { AccountAccessEntry } from "@/lib/sharing/account-access-view";
|
||||
|
||||
import { renderWithApp } from "../../../../tests/browser/render";
|
||||
|
||||
const switchTo = vi.fn();
|
||||
const mutate = vi.fn();
|
||||
|
||||
vi.mock("@/hooks/use-account-switch", () => ({
|
||||
useAccountSwitch: () => ({ mutate, switchTo, isPending: false }),
|
||||
}));
|
||||
|
||||
import { AccountSwitcherMenuItems } from "../account-switcher-menu";
|
||||
|
||||
function entry(
|
||||
accountId: string,
|
||||
fullName: string,
|
||||
recordKind: "shared" | "managed",
|
||||
): AccountAccessEntry {
|
||||
return {
|
||||
accountId,
|
||||
username: accountId,
|
||||
displayName: null,
|
||||
fullName,
|
||||
access: "read",
|
||||
level: "read",
|
||||
sections: null,
|
||||
recordKind,
|
||||
canWrite: false,
|
||||
writableDomains: [],
|
||||
manageableDomains: [],
|
||||
};
|
||||
}
|
||||
|
||||
const ACCOUNTS = [
|
||||
entry("acct-a", "Alexandra Konstantinopoulou-Wetherington", "shared"),
|
||||
entry("acct-b", "Maximilian Oberhausen", "managed"),
|
||||
];
|
||||
|
||||
async function mountMenu() {
|
||||
await renderWithApp(
|
||||
<div className="flex justify-end">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger>Account</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-60">
|
||||
<DropdownMenuItem>Settings</DropdownMenuItem>
|
||||
<AccountSwitcherMenuItems />
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>,
|
||||
{
|
||||
user: {
|
||||
accountAccess: { accounts: ACCOUNTS, active: null, canSwitch: true },
|
||||
},
|
||||
},
|
||||
);
|
||||
await page.getByRole("button", { name: "Account" }).click();
|
||||
await expect
|
||||
.poll(() =>
|
||||
document.querySelector('[data-slot="account-switcher-trigger"]'),
|
||||
)
|
||||
.toBeTruthy();
|
||||
}
|
||||
|
||||
function trigger(): HTMLElement {
|
||||
return document.querySelector<HTMLElement>(
|
||||
'[data-slot="account-switcher-trigger"]',
|
||||
)!;
|
||||
}
|
||||
|
||||
function entries(): HTMLElement[] {
|
||||
return [
|
||||
...document.querySelectorAll<HTMLElement>(
|
||||
'[data-slot="account-switcher-entry"]',
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
switchTo.mockClear();
|
||||
mutate.mockClear();
|
||||
});
|
||||
|
||||
describe("the record switcher at phone width", () => {
|
||||
it("unfolds the records inside the account menu", async () => {
|
||||
await page.viewport(390, 844);
|
||||
await mountMenu();
|
||||
|
||||
await userEvent.click(trigger());
|
||||
await expect.poll(() => entries().length).toBe(ACCOUNTS.length);
|
||||
|
||||
const accountMenu = trigger().closest('[role="menu"]');
|
||||
for (const row of entries()) {
|
||||
// In the account menu, not in a menu of its own beside it.
|
||||
expect(row.closest('[role="menu"]')).toBe(accountMenu);
|
||||
const box = row.getBoundingClientRect();
|
||||
expect(box.left).toBeGreaterThanOrEqual(0);
|
||||
expect(box.right).toBeLessThanOrEqual(window.innerWidth);
|
||||
// A finger-sized row.
|
||||
expect(box.height).toBeGreaterThanOrEqual(44);
|
||||
}
|
||||
expect(document.querySelectorAll('[role="menu"]')).toHaveLength(1);
|
||||
expect(trigger().getAttribute("aria-expanded")).toBe("true");
|
||||
});
|
||||
|
||||
it("keeps the account menu open while the list unfolds and folds", async () => {
|
||||
await page.viewport(390, 844);
|
||||
await mountMenu();
|
||||
|
||||
expect(entries()).toHaveLength(0);
|
||||
expect(trigger().getAttribute("aria-expanded")).toBe("false");
|
||||
|
||||
await userEvent.click(trigger());
|
||||
await expect.poll(() => entries().length).toBe(ACCOUNTS.length);
|
||||
|
||||
await userEvent.click(trigger());
|
||||
await expect.poll(() => entries().length).toBe(0);
|
||||
// The account menu itself is still there.
|
||||
expect(trigger()).toBeTruthy();
|
||||
expect(trigger().getAttribute("aria-expanded")).toBe("false");
|
||||
});
|
||||
|
||||
it("opens the chosen record from the inline list", async () => {
|
||||
await page.viewport(390, 844);
|
||||
await mountMenu();
|
||||
|
||||
await userEvent.click(trigger());
|
||||
await expect.poll(() => entries().length).toBe(ACCOUNTS.length);
|
||||
await userEvent.click(
|
||||
document.querySelector<HTMLElement>(
|
||||
'[data-slot="account-switcher-entry"][data-account-id="acct-b"]',
|
||||
)!,
|
||||
);
|
||||
|
||||
expect(switchTo).toHaveBeenCalledTimes(1);
|
||||
expect(switchTo.mock.calls[0][0]).toBe("acct-b");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the record switcher at desktop width", () => {
|
||||
it("keeps the side sub-menu", async () => {
|
||||
await page.viewport(1280, 900);
|
||||
await mountMenu();
|
||||
|
||||
expect(trigger().hasAttribute("data-presentation")).toBe(false);
|
||||
await userEvent.click(trigger());
|
||||
await expect.poll(() => entries().length).toBe(ACCOUNTS.length);
|
||||
|
||||
const accountMenu = trigger().closest('[role="menu"]');
|
||||
for (const row of entries()) {
|
||||
const menu = row.closest('[role="menu"]');
|
||||
expect(menu).toBeTruthy();
|
||||
expect(menu).not.toBe(accountMenu);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { Check, Loader2, Users } from "lucide-react";
|
||||
import { useId, useState } from "react";
|
||||
import { Check, ChevronDown, Loader2, Users } from "lucide-react";
|
||||
|
||||
import {
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuSub,
|
||||
@@ -11,10 +13,15 @@ import {
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { useAccountSwitch } from "@/hooks/use-account-switch";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useIsMobile } from "@/hooks/use-is-mobile";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { resolveRecordPresentation } from "@/lib/navigation/record-presentation";
|
||||
import { sharedRecordLandingHref } from "@/lib/navigation/shared-record";
|
||||
import { accountLabel } from "@/lib/sharing/account-access-view";
|
||||
import {
|
||||
accountLabel,
|
||||
type AccountAccess,
|
||||
} from "@/lib/sharing/account-access-view";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* v1.36.0 — the switcher, as a slice of the user menu.
|
||||
@@ -35,16 +42,83 @@ import { accountLabel } from "@/lib/sharing/account-access-view";
|
||||
* "Your own record" is a first-class entry rather than only a banner action:
|
||||
* the way out has to be reachable from the same menu as the way in, because
|
||||
* that is where somebody will look for it.
|
||||
*
|
||||
* Below the `sm` breakpoint the records open inside the account menu rather
|
||||
* than in a sub-menu beside it. The phone's account menu sits against the
|
||||
* right edge and takes most of the width; a 240 px sub-menu has room on
|
||||
* neither side, and Radix only shifts a side menu along its own axis, so it
|
||||
* ran off the screen and cut the names off. The trigger keeps its slot and the
|
||||
* list keeps `account-switcher-menu`, so a journey that taps the trigger and
|
||||
* then an entry reads the same at either width.
|
||||
*/
|
||||
export function AccountSwitcherMenuItems() {
|
||||
const { user } = useAuth();
|
||||
const { t } = useTranslations();
|
||||
const switchAccount = useAccountSwitch();
|
||||
const inline = useIsMobile("sm");
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const listId = useId();
|
||||
|
||||
const access = user?.accountAccess;
|
||||
if (!access?.canSwitch) return null;
|
||||
|
||||
const activeId = access.active?.accountId ?? null;
|
||||
const label = t("recordSharing.switcher.label");
|
||||
const icon = switchAccount.isPending ? (
|
||||
<Loader2
|
||||
className="size-4 animate-spin motion-reduce:animate-none"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : (
|
||||
<Users className="size-4" aria-hidden="true" />
|
||||
);
|
||||
const rows = (
|
||||
<RecordRows
|
||||
access={access}
|
||||
activeId={activeId}
|
||||
inset={inline}
|
||||
switchAccount={switchAccount}
|
||||
/>
|
||||
);
|
||||
|
||||
if (inline) {
|
||||
return (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
data-slot="account-switcher-trigger"
|
||||
data-presentation="inline"
|
||||
aria-expanded={expanded}
|
||||
aria-controls={expanded ? listId : undefined}
|
||||
className="cursor-pointer"
|
||||
// Keep the account menu open: the trigger unfolds the list in place.
|
||||
onSelect={(event) => {
|
||||
event.preventDefault();
|
||||
setExpanded((open) => !open);
|
||||
}}
|
||||
>
|
||||
{icon}
|
||||
<span className="ml-2">{label}</span>
|
||||
<ChevronDown
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"ml-auto size-4 transition-transform motion-reduce:transition-none",
|
||||
expanded && "rotate-180",
|
||||
)}
|
||||
/>
|
||||
</DropdownMenuItem>
|
||||
{expanded && (
|
||||
<DropdownMenuGroup
|
||||
id={listId}
|
||||
data-slot="account-switcher-menu"
|
||||
aria-label={label}
|
||||
>
|
||||
{rows}
|
||||
</DropdownMenuGroup>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -54,72 +128,14 @@ export function AccountSwitcherMenuItems() {
|
||||
data-slot="account-switcher-trigger"
|
||||
className="min-h-11 py-2 sm:min-h-9"
|
||||
>
|
||||
{switchAccount.isPending ? (
|
||||
<Loader2
|
||||
className="size-4 animate-spin motion-reduce:animate-none"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : (
|
||||
<Users className="size-4" aria-hidden="true" />
|
||||
)}
|
||||
<span className="ml-2">{t("recordSharing.switcher.label")}</span>
|
||||
{icon}
|
||||
<span className="ml-2">{label}</span>
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuSubContent
|
||||
data-slot="account-switcher-menu"
|
||||
className="max-h-(--radix-dropdown-menu-content-available-height) w-60 overflow-x-hidden overflow-y-auto"
|
||||
>
|
||||
<DropdownMenuItem
|
||||
data-slot="account-switcher-own"
|
||||
className="cursor-pointer"
|
||||
disabled={switchAccount.isPending}
|
||||
onClick={() => switchAccount.mutate(null)}
|
||||
>
|
||||
<span className="truncate">
|
||||
{t("recordSharing.switcher.ownRecord")}
|
||||
</span>
|
||||
{activeId === null && (
|
||||
<span className="text-primary ml-auto text-xs">✓</span>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
{access.accounts.map((account) => {
|
||||
const presentation = resolveRecordPresentation(account);
|
||||
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={account.accountId}
|
||||
data-slot="account-switcher-entry"
|
||||
data-account-id={account.accountId}
|
||||
data-account-username={account.username}
|
||||
data-access-level={presentation.access}
|
||||
data-record-kind={presentation.recordKind}
|
||||
className="cursor-pointer"
|
||||
disabled={switchAccount.isPending}
|
||||
onClick={() =>
|
||||
switchAccount.switchTo(
|
||||
account.accountId,
|
||||
sharedRecordLandingHref(account.sections),
|
||||
)
|
||||
}
|
||||
>
|
||||
{/* Two lines, not three. The access level had a line of its
|
||||
own here and it never fit — a 240 px menu truncated
|
||||
"Kann verwalten" as often as it showed it, and the entry
|
||||
still said which kind of record this is on the line below.
|
||||
The level is what the banner states once you are inside,
|
||||
where it governs what the page lets you do. It stays on
|
||||
the row as `data-access-level` for the browser journeys. */}
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate">{accountLabel(account)}</span>
|
||||
<span className="text-muted-foreground truncate text-xs">
|
||||
{recordKindLabel(presentation.recordKind, t)}
|
||||
</span>
|
||||
</div>
|
||||
{activeId === account.accountId && (
|
||||
<Check className="text-primary ml-2 size-4 shrink-0" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
{rows}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
</>
|
||||
@@ -134,3 +150,81 @@ function recordKindLabel(
|
||||
? t("recordSharing.lookingAfter.kindManaged")
|
||||
: t("recordSharing.lookingAfter.kindShared");
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows themselves: your own record first, then every record the server
|
||||
* published. The same rows in the side sub-menu and in the inline list; the
|
||||
* inline list indents them under the trigger (`inset`).
|
||||
*/
|
||||
function RecordRows({
|
||||
access,
|
||||
activeId,
|
||||
inset,
|
||||
switchAccount,
|
||||
}: {
|
||||
access: AccountAccess;
|
||||
activeId: string | null;
|
||||
inset: boolean;
|
||||
switchAccount: ReturnType<typeof useAccountSwitch>;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
data-slot="account-switcher-own"
|
||||
inset={inset}
|
||||
className="cursor-pointer"
|
||||
disabled={switchAccount.isPending}
|
||||
onClick={() => switchAccount.mutate(null)}
|
||||
>
|
||||
<span className="truncate">
|
||||
{t("recordSharing.switcher.ownRecord")}
|
||||
</span>
|
||||
{activeId === null && (
|
||||
<span className="text-primary ml-auto text-xs">✓</span>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
{access.accounts.map((account) => {
|
||||
const presentation = resolveRecordPresentation(account);
|
||||
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={account.accountId}
|
||||
data-slot="account-switcher-entry"
|
||||
data-account-id={account.accountId}
|
||||
data-account-username={account.username}
|
||||
data-access-level={presentation.access}
|
||||
data-record-kind={presentation.recordKind}
|
||||
inset={inset}
|
||||
className="cursor-pointer"
|
||||
disabled={switchAccount.isPending}
|
||||
onClick={() =>
|
||||
switchAccount.switchTo(
|
||||
account.accountId,
|
||||
sharedRecordLandingHref(account.sections),
|
||||
)
|
||||
}
|
||||
>
|
||||
{/* Two lines, not three. The access level had a line of its
|
||||
own here and it never fit — a 240 px menu truncated
|
||||
"Kann verwalten" as often as it showed it, and the entry
|
||||
still said which kind of record this is on the line below.
|
||||
The level is what the banner states once you are inside,
|
||||
where it governs what the page lets you do. It stays on
|
||||
the row as `data-access-level` for the browser journeys. */}
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate">{accountLabel(account)}</span>
|
||||
<span className="text-muted-foreground truncate text-xs">
|
||||
{recordKindLabel(presentation.recordKind, t)}
|
||||
</span>
|
||||
</div>
|
||||
{activeId === account.accountId && (
|
||||
<Check className="text-primary ml-2 size-4 shrink-0" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { stubFetch } from "../../../../tests/browser/fetch-stub";
|
||||
import { renderWithApp } from "../../../../tests/browser/render";
|
||||
|
||||
import { WebPushCard } from "../web-push-card";
|
||||
import { WEB_PUSH_DOCS_HREF, WebPushCard } from "../web-push-card";
|
||||
|
||||
const SUBSCRIPTION = {
|
||||
endpoint: "https://push.example.test/send/abc",
|
||||
@@ -62,3 +62,69 @@ describe("WebPushCard", () => {
|
||||
expect(document.querySelector('[role="alert"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A browser whose push service refuses the registration, as Brave does with
|
||||
* push messaging switched off: `subscribe()` rejects with an `AbortError`.
|
||||
*/
|
||||
function refuseAtPushService(): void {
|
||||
vi.spyOn(Notification, "permission", "get").mockReturnValue("granted");
|
||||
vi.spyOn(navigator.serviceWorker, "getRegistration").mockResolvedValue(
|
||||
undefined,
|
||||
);
|
||||
const refusal = new DOMException(
|
||||
"Registration failed - push service error",
|
||||
"AbortError",
|
||||
);
|
||||
vi.spyOn(navigator.serviceWorker, "ready", "get").mockReturnValue(
|
||||
Promise.resolve({
|
||||
pushManager: { subscribe: () => Promise.reject(refusal) },
|
||||
} as unknown as ServiceWorkerRegistration),
|
||||
);
|
||||
}
|
||||
|
||||
function alertText(): string {
|
||||
return document.querySelector('[role="alert"]')?.textContent ?? "";
|
||||
}
|
||||
|
||||
describe("WebPushCard when the push service refuses", () => {
|
||||
afterEach(() => {
|
||||
delete (navigator as Navigator & { brave?: unknown }).brave;
|
||||
});
|
||||
|
||||
it("says the push service refused and links the docs", async () => {
|
||||
refuseAtPushService();
|
||||
const api = stubFetch().on("GET", "/api/notifications/vapid", {
|
||||
data: { publicKey: "BAAAAAAA" },
|
||||
});
|
||||
|
||||
const { screen } = await renderWithApp(<WebPushCard />);
|
||||
await screen.getByRole("button", { name: "Enable push" }).click();
|
||||
|
||||
await expect
|
||||
.poll(() => alertText())
|
||||
.toContain("Your browser's push service refused the registration");
|
||||
await expect
|
||||
.element(screen.getByRole("link", { name: "Help with browser push" }))
|
||||
.toHaveAttribute("href", WEB_PUSH_DOCS_HREF);
|
||||
// Nothing reached the server: the browser refused before a save.
|
||||
expect(api.calls("POST", "/api/notifications/web-push")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("names the setting in Brave", async () => {
|
||||
refuseAtPushService();
|
||||
Object.defineProperty(navigator, "brave", {
|
||||
value: { isBrave: async () => true },
|
||||
configurable: true,
|
||||
});
|
||||
stubFetch().on("GET", "/api/notifications/vapid", {
|
||||
data: { publicKey: "BAAAAAAA" },
|
||||
});
|
||||
|
||||
const { screen } = await renderWithApp(<WebPushCard />);
|
||||
await screen.getByRole("button", { name: "Enable push" }).click();
|
||||
|
||||
await expect.poll(() => alertText()).toContain("brave://settings/privacy");
|
||||
expect(alertText()).toContain("Use Google services for push messaging");
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { BellRing, Loader2 } from "lucide-react";
|
||||
import { BellRing, ExternalLink, Loader2 } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { InlineAction } from "@/components/ui/inline-action";
|
||||
import { DOCS_GUIDES_BASE } from "@/components/settings/integrations/setup-guide-link";
|
||||
import { TestConnectionButton } from "@/components/settings/test-connection-button";
|
||||
import { SettingsCard } from "@/components/settings/settings-card";
|
||||
import { SettingsCardActions } from "@/components/settings/_card-actions";
|
||||
@@ -14,6 +16,14 @@ import {
|
||||
saveWebPushSubscription,
|
||||
unsubscribeWebPush,
|
||||
} from "@/lib/notifications/web-push-subscription";
|
||||
import {
|
||||
classifyWebPushSubscribeFailure,
|
||||
isBraveBrowser,
|
||||
type WebPushSubscribeFailure,
|
||||
} from "@/lib/notifications/web-push-subscribe-failure";
|
||||
|
||||
/** The docs section on Browser Push, linked when the browser refused. */
|
||||
export const WEB_PUSH_DOCS_HREF = `${DOCS_GUIDES_BASE}/reminder-channels/#web-push-vapid`;
|
||||
|
||||
/** Convert a URL-safe base64 string to an ArrayBuffer (for VAPID key). */
|
||||
function urlBase64ToArrayBuffer(base64String: string): ArrayBuffer {
|
||||
@@ -43,6 +53,67 @@ export function needsHomeScreen(): boolean {
|
||||
|
||||
type Unsupported = "browser" | "install" | null;
|
||||
|
||||
/** What one press of "Enable push" ended in. */
|
||||
type SubscribeOutcome =
|
||||
"subscribed" | "not-configured" | "save-failed" | WebPushSubscribeFailure;
|
||||
|
||||
/**
|
||||
* Subscribe this browser and store the subscription on the server. The
|
||||
* browser's own refusal is classified apart from the server's answers around
|
||||
* it: Brave, for one, rejects with "push service error" until push messaging
|
||||
* is switched on in its privacy settings, and "Activation failed" told nobody
|
||||
* that.
|
||||
*/
|
||||
async function subscribeThisBrowser(): Promise<SubscribeOutcome> {
|
||||
const vapidRes = await apiFetchRaw("/api/notifications/vapid");
|
||||
if (!vapidRes.ok) return "not-configured";
|
||||
const vapidData = await vapidRes.json();
|
||||
const vapidPublicKey = vapidData.data.publicKey;
|
||||
|
||||
// Defer to the app-wide registration (`<ServiceWorkerRegistrar>` in the
|
||||
// root providers) rather than re-registering here — same scope, so a second
|
||||
// `register("/sw.js")` would only return the existing worker. `ready`
|
||||
// resolves with the active registration once it is controlling the page.
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
|
||||
let subscription: PushSubscription;
|
||||
try {
|
||||
subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: urlBase64ToArrayBuffer(vapidPublicKey),
|
||||
});
|
||||
} catch (error) {
|
||||
return classifyWebPushSubscribeFailure(error, {
|
||||
permission: Notification.permission,
|
||||
isBrave: isBraveBrowser(),
|
||||
});
|
||||
}
|
||||
|
||||
const res = await saveWebPushSubscription(subscription);
|
||||
return res.ok ? "subscribed" : "save-failed";
|
||||
}
|
||||
|
||||
function subscribeOutcomeMessage(
|
||||
outcome: SubscribeOutcome,
|
||||
t: ReturnType<typeof useTranslations>["t"],
|
||||
): string {
|
||||
switch (outcome) {
|
||||
case "subscribed":
|
||||
return t("settings.webPushSubscribed");
|
||||
case "not-configured":
|
||||
return t("settings.webPushNotConfigured");
|
||||
case "denied":
|
||||
return t("settings.webPushDenied");
|
||||
case "push-service":
|
||||
return t("settings.webPushServiceRefused");
|
||||
case "push-service-brave":
|
||||
return t("settings.webPushServiceRefusedBrave");
|
||||
case "save-failed":
|
||||
case "unknown":
|
||||
return t("settings.webPushSubscribeFailed");
|
||||
}
|
||||
}
|
||||
|
||||
export function WebPushCard() {
|
||||
const { t } = useTranslations();
|
||||
const [isSubscribed, setIsSubscribed] = useState(false);
|
||||
@@ -52,6 +123,7 @@ export function WebPushCard() {
|
||||
const [actionLoading, setActionLoading] = useState(false);
|
||||
const [msg, setMsg] = useState<string | null>(null);
|
||||
const [msgType, setMsgType] = useState<"success" | "error" | null>(null);
|
||||
const [showHelp, setShowHelp] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Async I/O (browser API + service worker registration). The lint rule
|
||||
@@ -95,50 +167,21 @@ export function WebPushCard() {
|
||||
setActionLoading(true);
|
||||
setMsg(null);
|
||||
setMsgType(null);
|
||||
setShowHelp(false);
|
||||
|
||||
let outcome: SubscribeOutcome;
|
||||
try {
|
||||
const vapidRes = await apiFetchRaw("/api/notifications/vapid");
|
||||
if (!vapidRes.ok) {
|
||||
setMsg(t("settings.webPushNotConfigured"));
|
||||
setMsgType("error");
|
||||
setActionLoading(false);
|
||||
return;
|
||||
}
|
||||
const vapidData = await vapidRes.json();
|
||||
const vapidPublicKey = vapidData.data.publicKey;
|
||||
|
||||
// Defer to the app-wide registration (`<ServiceWorkerRegistrar>` in
|
||||
// the root providers) rather than re-registering here — same scope,
|
||||
// so a second `register("/sw.js")` would only return the existing
|
||||
// worker. `ready` resolves with the active registration once it is
|
||||
// controlling the page.
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
|
||||
const subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: urlBase64ToArrayBuffer(vapidPublicKey),
|
||||
});
|
||||
|
||||
const res = await saveWebPushSubscription(subscription);
|
||||
if (res.ok) {
|
||||
setIsSubscribed(true);
|
||||
setMsg(t("settings.webPushSubscribed"));
|
||||
setMsgType("success");
|
||||
} else {
|
||||
setMsg(t("settings.webPushSubscribeFailed"));
|
||||
setMsgType("error");
|
||||
}
|
||||
outcome = await subscribeThisBrowser();
|
||||
} catch {
|
||||
if (Notification.permission === "denied") {
|
||||
setIsDenied(true);
|
||||
setMsg(t("settings.webPushDenied"));
|
||||
} else {
|
||||
setMsg(t("settings.webPushSubscribeFailed"));
|
||||
}
|
||||
setMsgType("error");
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
outcome = Notification.permission === "denied" ? "denied" : "unknown";
|
||||
}
|
||||
if (outcome === "subscribed") setIsSubscribed(true);
|
||||
if (outcome === "denied") setIsDenied(true);
|
||||
setMsg(subscribeOutcomeMessage(outcome, t));
|
||||
setMsgType(outcome === "subscribed" ? "success" : "error");
|
||||
// The push service refused: the fix is in the browser, so link the docs.
|
||||
setShowHelp(outcome === "push-service" || outcome === "push-service-brave");
|
||||
setActionLoading(false);
|
||||
}
|
||||
|
||||
async function handleUnsubscribe() {
|
||||
@@ -232,6 +275,18 @@ export function WebPushCard() {
|
||||
{msg}
|
||||
</p>
|
||||
)}
|
||||
{msg && showHelp && (
|
||||
<InlineAction asChild tone="primary" size="sm">
|
||||
<a
|
||||
href={WEB_PUSH_DOCS_HREF}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{t("settings.webPushHelpLink")}
|
||||
<ExternalLink aria-hidden="true" />
|
||||
</a>
|
||||
</InlineAction>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* How the Browser Push card reads a refusal from `pushManager.subscribe()`.
|
||||
*
|
||||
* The reported case is Brave with push messaging switched off, which rejects
|
||||
* with `AbortError: Registration failed - push service error` and used to
|
||||
* show only "Activation failed".
|
||||
*/
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
classifyWebPushSubscribeFailure,
|
||||
isBraveBrowser,
|
||||
} from "../web-push-subscribe-failure";
|
||||
|
||||
function domError(name: string, message: string): Error {
|
||||
const error = new Error(message);
|
||||
error.name = name;
|
||||
return error;
|
||||
}
|
||||
|
||||
const PUSH_SERVICE_ERROR = domError(
|
||||
"AbortError",
|
||||
"Registration failed - push service error",
|
||||
);
|
||||
|
||||
describe("classifyWebPushSubscribeFailure", () => {
|
||||
it("names the push service when the browser could not register with it", () => {
|
||||
expect(
|
||||
classifyWebPushSubscribeFailure(PUSH_SERVICE_ERROR, {
|
||||
permission: "granted",
|
||||
isBrave: false,
|
||||
}),
|
||||
).toBe("push-service");
|
||||
});
|
||||
|
||||
it("names Brave's setting when the browser is Brave", () => {
|
||||
expect(
|
||||
classifyWebPushSubscribeFailure(PUSH_SERVICE_ERROR, {
|
||||
permission: "granted",
|
||||
isBrave: true,
|
||||
}),
|
||||
).toBe("push-service-brave");
|
||||
});
|
||||
|
||||
it("reads any other AbortError from subscribe as the push service", () => {
|
||||
// Chromium also says "push service not available"; Firefox says
|
||||
// "Error retrieving push subscription." Both are the push service.
|
||||
for (const message of [
|
||||
"Registration failed - push service not available",
|
||||
"Error retrieving push subscription.",
|
||||
]) {
|
||||
expect(
|
||||
classifyWebPushSubscribeFailure(domError("AbortError", message), {
|
||||
permission: "granted",
|
||||
isBrave: false,
|
||||
}),
|
||||
).toBe("push-service");
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a blocked permission as blocked, whatever the error said", () => {
|
||||
expect(
|
||||
classifyWebPushSubscribeFailure(PUSH_SERVICE_ERROR, {
|
||||
permission: "denied",
|
||||
isBrave: true,
|
||||
}),
|
||||
).toBe("denied");
|
||||
});
|
||||
|
||||
it("does not blame the push service for a dismissed permission prompt", () => {
|
||||
expect(
|
||||
classifyWebPushSubscribeFailure(
|
||||
domError("NotAllowedError", "Registration failed - permission denied"),
|
||||
{ permission: "default", isBrave: true },
|
||||
),
|
||||
).toBe("unknown");
|
||||
expect(
|
||||
classifyWebPushSubscribeFailure(
|
||||
domError("AbortError", "Registration failed - permission denied"),
|
||||
{ permission: "default", isBrave: true },
|
||||
),
|
||||
).toBe("unknown");
|
||||
});
|
||||
|
||||
it("does not blame the push service for a key the browser would not take", () => {
|
||||
expect(
|
||||
classifyWebPushSubscribeFailure(
|
||||
domError(
|
||||
"AbortError",
|
||||
"Registration failed - missing applicationServerKey, and manifest empty or missing",
|
||||
),
|
||||
{ permission: "granted", isBrave: true },
|
||||
),
|
||||
).toBe("unknown");
|
||||
expect(
|
||||
classifyWebPushSubscribeFailure(
|
||||
domError(
|
||||
"InvalidAccessError",
|
||||
"The provided applicationServerKey is not valid.",
|
||||
),
|
||||
{ permission: "granted", isBrave: false },
|
||||
),
|
||||
).toBe("unknown");
|
||||
});
|
||||
|
||||
it("keeps the generic message for anything that is not an error object", () => {
|
||||
expect(
|
||||
classifyWebPushSubscribeFailure("boom", {
|
||||
permission: "granted",
|
||||
isBrave: false,
|
||||
}),
|
||||
).toBe("unknown");
|
||||
expect(
|
||||
classifyWebPushSubscribeFailure(new TypeError("Failed to fetch"), {
|
||||
permission: "granted",
|
||||
isBrave: false,
|
||||
}),
|
||||
).toBe("unknown");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isBraveBrowser", () => {
|
||||
const original = Object.getOwnPropertyDescriptor(globalThis, "navigator");
|
||||
|
||||
afterEach(() => {
|
||||
if (original) Object.defineProperty(globalThis, "navigator", original);
|
||||
});
|
||||
|
||||
function withNavigator(value: unknown): void {
|
||||
Object.defineProperty(globalThis, "navigator", {
|
||||
value,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
});
|
||||
}
|
||||
|
||||
it("is true when navigator.brave is present", () => {
|
||||
withNavigator({ brave: { isBrave: async () => true } });
|
||||
expect(isBraveBrowser()).toBe(true);
|
||||
});
|
||||
|
||||
it("is false for a Chromium without navigator.brave", () => {
|
||||
withNavigator({ userAgent: "Mozilla/5.0 Chrome/130" });
|
||||
expect(isBraveBrowser()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Why `pushManager.subscribe()` refused, in the terms the Browser Push card
|
||||
* explains to a person.
|
||||
*
|
||||
* Only the browser's own refusal is classified here. A missing VAPID key and
|
||||
* a failed save are server answers and keep their own messages in the card.
|
||||
*
|
||||
* - `denied`: notifications are blocked for this site
|
||||
* (`Notification.permission === "denied"`), whatever the error said.
|
||||
* - `push-service` / `push-service-brave`: the browser could not register
|
||||
* with its push service ("AbortError: Registration failed - push service
|
||||
* error"). The page did nothing wrong and cannot fix it; the browser has to
|
||||
* reach its push service. Brave ships with that switched off, which is the
|
||||
* common case, so Brave gets the setting named.
|
||||
* - `unknown`: anything else, which keeps the generic message. That includes
|
||||
* a dismissed permission prompt (`NotAllowedError`, or an `AbortError`
|
||||
* about permission in older Chromium builds): the permission is still
|
||||
* "default", the person can try again, and calling it a push-service fault
|
||||
* would send them to the wrong setting.
|
||||
*/
|
||||
export type WebPushSubscribeFailure =
|
||||
"denied" | "push-service" | "push-service-brave" | "unknown";
|
||||
|
||||
export interface WebPushSubscribeContext {
|
||||
/** `Notification.permission` after the attempt. */
|
||||
permission: NotificationPermission;
|
||||
/** The browser announces itself as Brave (`navigator.brave`). */
|
||||
isBrave: boolean;
|
||||
}
|
||||
|
||||
function errorName(error: unknown): string {
|
||||
return typeof error === "object" && error !== null && "name" in error
|
||||
? String((error as { name: unknown }).name)
|
||||
: "";
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return typeof error === "object" && error !== null && "message" in error
|
||||
? String((error as { message: unknown }).message)
|
||||
: "";
|
||||
}
|
||||
|
||||
export function classifyWebPushSubscribeFailure(
|
||||
error: unknown,
|
||||
{ permission, isBrave }: WebPushSubscribeContext,
|
||||
): WebPushSubscribeFailure {
|
||||
const name = errorName(error);
|
||||
const message = errorMessage(error);
|
||||
|
||||
if (permission === "denied") return "denied";
|
||||
if (name !== "AbortError") return "unknown";
|
||||
if (/permission/i.test(message)) return "unknown";
|
||||
// A key the server handed out that the browser would not take is the
|
||||
// server's problem, not the push service's.
|
||||
if (/applicationServerKey/i.test(message)) return "unknown";
|
||||
return isBrave ? "push-service-brave" : "push-service";
|
||||
}
|
||||
|
||||
/**
|
||||
* Brave exposes `navigator.brave` so a page can tell it apart from Chrome,
|
||||
* whose user agent it otherwise copies.
|
||||
*/
|
||||
export function isBraveBrowser(): boolean {
|
||||
if (typeof navigator === "undefined") return false;
|
||||
const brave = (navigator as Navigator & { brave?: unknown }).brave;
|
||||
return typeof brave === "object" && brave !== null;
|
||||
}
|
||||
@@ -2011,8 +2011,8 @@ export const authPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
summary: "Mint a measurement-ingest token",
|
||||
description:
|
||||
"Mints a Bearer scoped to exactly `measurements:write` and audits the mint. THE RESPONSE CARRIES THE RAW TOKEN — the only place it ever exists; it is stored as an HMAC and no path re-reveals it.\n\n" +
|
||||
"**What it can do.** `POST /api/measurements` and `POST /api/measurements/batch`, on its owner's own record. Rows it writes carry `source: EXTERNAL`, resolved from the credential rather than taken from the body, so a reading pushed by a bridge stays distinguishable from one typed in by hand and can be picked out with the source filter. A body naming ANY source is refused 422 rather than relabelled — honouring it would defeat the label, overriding it silently would hand the caller rows it did not ask for. `APPLE_HEALTH` is the one that would do real damage: it is half a dedup key the phone also writes into, it participates in the cross-source merge, and it is what decides the Apple Health card may claim a sync happened. For the same reason a write through this credential does not move the native client's sync checkpoint. The rows stay editable by their owner, unlike a connected provider's — the hardware behind the token is the user's own.\n\n" +
|
||||
"**What it cannot do.** Everything else, including the measurement reads on the same paths, the edit and delete legs, and the export — a scope grants what it names and nothing adjacent. It cannot be pointed at a shared record: a request carrying the account selector is refused 403 before any grant is read, whatever grants its holder actually has. And it cannot mint another token, this endpoint included.\n\n" +
|
||||
"**What it can do.** `POST /api/measurements` and `POST /api/measurements/batch`, on its owner's own record, and `POST /api/custom-metrics/{id}/entries` for a custom metric its owner already created (it cannot list, create, edit or delete metrics, so the id comes from the metric's page in the app). Measurement rows it writes carry `source: EXTERNAL`, resolved from the credential rather than taken from the body, so a reading pushed by a bridge stays distinguishable from one typed in by hand and can be picked out with the source filter. A body naming ANY source is refused 422 rather than relabelled — honouring it would defeat the label, overriding it silently would hand the caller rows it did not ask for. `APPLE_HEALTH` is the one that would do real damage: it is half a dedup key the phone also writes into, it participates in the cross-source merge, and it is what decides the Apple Health card may claim a sync happened. For the same reason a write through this credential does not move the native client's sync checkpoint. The rows stay editable by their owner, unlike a connected provider's — the hardware behind the token is the user's own.\n\n" +
|
||||
"**What it cannot do.** Everything else, including the measurement reads on the same paths, the custom-metric list and value reads, the edit and delete legs, and the export — a scope grants what it names and nothing adjacent. It cannot be pointed at a shared record: a request carrying the account selector is refused 403 before any grant is read, whatever grants its holder actually has. And it cannot mint another token, this endpoint included.\n\n" +
|
||||
"Minting requires a COOKIE SESSION with a fresh proof: a sign-in or `POST /api/auth/reproof` within the last five minutes (with a second factor, on an account that has one), otherwise 401 `auth.reproof.required` with `meta.methods`. No Bearer credential reaches this endpoint at any scope, wildcard included — not because a wildcard lacks the reach, but because of the lifetimes involved: a native access token lives a day and what it could mint here lives a year, so admitting one would let a short-lived compromise leave behind a credential that outlives revoking it. Gated by the operator's instance-wide API switch. Body capped at 16 KiB; 10 mints per user per minute, and at most 10 live tokens held at once. Tokens appear in `GET /api/tokens` and are revoked at `DELETE /api/tokens/{id}` like any other — revoking frees a slot against the ceiling.",
|
||||
requestBody: {
|
||||
required: true,
|
||||
|
||||
@@ -294,7 +294,8 @@ export const customMetricPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Custom metrics"],
|
||||
summary: "Log a value",
|
||||
description:
|
||||
"Records a value against the custom metric, snapshotting the metric's unit. Audits as `customMetricEntry.create`.",
|
||||
"Records a value against the custom metric, snapshotting the metric's unit. Audits as `customMetricEntry.create`.\n\n" +
|
||||
"**Narrow token.** Also reachable with a `measurements:write` Bearer (minted at `POST /api/tokens/measurements`), the supported way to push a custom metric's value from a script or a home-automation rule. Such a credential writes only to its owner's own live metrics: an id that is unknown, deleted, or another account's answers the same 404, and a request carrying the account selector is refused 403 before any sharing grant is read. This POST is all the scope reaches on custom metrics. The value list on this same path, the metric list, and creating, editing or deleting a metric or a value name no scope and refuse it 403, so the metric id has to come from its owner: it is the path segment after `/custom-metrics/` in the address of the metric's page in the app. The entry carries no source of its own; the audit row names the token that wrote it. Every other narrow token, `workouts:write` included, is refused 403.",
|
||||
requestParams: { path: z.object({ id: z.string() }) },
|
||||
parameters: [idempotencyKeyParameter],
|
||||
requestBody: {
|
||||
|
||||
Reference in new issue
Block a user