Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

fix: better role based control, share logic and safe fetch

Carl-Gerhard Lindesvärd5faad3226df8
diff --git a/apps/api/package.json b/apps/api/package.json
index 80f48a063..3b845cc46 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -50,7 +50,6 @@
"fastify-raw-body": "^5.0.0",
"fastify-zod-openapi": "^5.6.1",
"groupmq": "catalog:",
- "ipaddr.js": "^2.5.0",
"jsonwebtoken": "^9.0.2",
"pino": "catalog:",
"pino-pretty": "catalog:",
@@ -60,7 +59,6 @@
"sqlstring": "^2.3.3",
"superjson": "^1.13.3",
"svix": "^1.24.0",
- "undici": "^8.10.0",
"url-metadata": "^5.4.1",
"uuid": "^9.0.1",
"zod": "catalog:"
diff --git a/apps/api/src/controllers/webhook.controller.ts b/apps/api/src/controllers/webhook.controller.ts
index 4f6ace1b1..0432daa9c 100644
--- a/apps/api/src/controllers/webhook.controller.ts
+++ b/apps/api/src/controllers/webhook.controller.ts
@@ -7,6 +7,7 @@ const __dirname = dirname(__filename);
import { tryCatch } from '@openpanel/common';
import { db, getOrganizationByProjectIdCached } from '@openpanel/db';
+import { safeWebhookFetcher } from '@openpanel/integrations/src/safe-fetcher';
import {
sendSlackNotification,
slackInstaller,
@@ -80,6 +81,7 @@ export async function slackWebhook(
// Send a notification first to confirm the connection
await sendSlackNotification({
+ fetcher: safeWebhookFetcher,
webhookUrl: parsedJson.data.incoming_webhook.url,
message:
'👋 Hello. You have successfully connected OpenPanel.dev to your Slack workspace.',
diff --git a/apps/api/src/utils/safe-fetch.ts b/apps/api/src/utils/safe-fetch.ts
index 8e3019866..8cb361103 100644
--- a/apps/api/src/utils/safe-fetch.ts
+++ b/apps/api/src/utils/safe-fetch.ts
@@ -1,305 +1,22 @@
-import dns from 'node:dns/promises';
-import net from 'node:net';
-import ipaddr from 'ipaddr.js';
-import { Agent, fetch as undiciFetch } from 'undici';
-
/**
- * SSRF guard for the endpoints that fetch user-supplied URLs (the favicon/OG
- * proxy and the public site checker).
+ * The SSRF guard lives in `@openpanel/common/server/safe-fetch` so that every
+ * outbound-fetch site in the monorepo can reach it - the api controllers, the
+ * worker's webhook delivery and the importer's remote-file reader alike. It
+ * used to live here, which is why the importer never called it
+ * (GHSA-cj2r-3x54-88h7).
*
- * Two things have to be true for the guard to hold:
- *
- * 1. Every address a hostname resolves to must be publicly routable. Checking
- * only the first A record lets an attacker publish a second AAAA record.
- * 2. The socket must connect to the address we validated. Resolving and then
- * handing the hostname to `fetch` re-resolves it, so a DNS rebind between
- * the two lookups reaches the internal target anyway. We pin the validated
- * address into the connection instead.
- *
- * Redirects are followed manually so every hop goes through the same checks.
- */
-
-export class BlockedUrlError extends Error {
- constructor(message: string) {
- super(message);
- this.name = 'BlockedUrlError';
- }
-}
-
-/**
- * ipaddr.js range names that are not publicly routable. `unicast` is the only
- * range we accept; this list is spelled out so the intent is reviewable.
- */
-const BLOCKED_RANGES = new Set([
- 'unspecified', // 0.0.0.0/8, ::
- 'broadcast', // 255.255.255.255
- 'multicast', // 224.0.0.0/4, ff00::/8
- 'linkLocal', // 169.254.0.0/16 (cloud metadata), fe80::/10
- 'loopback', // 127.0.0.0/8, ::1
- 'private', // 10/8, 172.16/12, 192.168/16
- 'uniqueLocal', // fc00::/7
- 'carrierGradeNat', // 100.64.0.0/10
- 'reserved', // 192.0.0.0/24, 198.18/15, 240/4, 2001::/32, ...
- 'benchmarking',
- 'as112',
- 'amt',
- 'rfc6052', // 64:ff9b::/96
- 'rfc6145',
- 'teredo',
- '6to4', // 2002::/16
-]);
-
-export function isBlockedIp(ip: string): boolean {
- let parsed: ipaddr.IPv4 | ipaddr.IPv6;
- try {
- parsed = ipaddr.parse(ip);
- } catch {
- // Unparseable means we cannot prove it is safe.
- return true;
- }
-
- // ::ffff:127.0.0.1 and friends must be judged as the IPv4 address they carry.
- if (parsed.kind() === 'ipv6') {
- const v6 = parsed as ipaddr.IPv6;
- if (v6.isIPv4MappedAddress()) {
- return isBlockedIp(v6.toIPv4Address().toString());
- }
- }
-
- return BLOCKED_RANGES.has(parsed.range());
-}
-
-/**
- * Resolve a hostname, rejecting it entirely if any address is non-public.
- */
-async function resolvePublicAddresses(hostname: string): Promise<string[]> {
- // WHATWG URL keeps the brackets around IPv6 literals ("[::1]").
- const host =
- hostname.startsWith('[') && hostname.endsWith(']')
- ? hostname.slice(1, -1)
- : hostname;
-
- // A bare IP in the URL never hits DNS, so check it directly.
- if (net.isIP(host)) {
- if (isBlockedIp(host)) {
- throw new BlockedUrlError(`Refusing to connect to ${host}`);
- }
- return [host];
- }
-
- let addresses: { address: string }[];
- try {
- // `lookup` rather than `resolve4`/`resolve6` so /etc/hosts and the system
- // resolver are honoured the same way the real connection would.
- addresses = await dns.lookup(host, { all: true, verbatim: true });
- } catch {
- throw new BlockedUrlError(`Could not resolve ${host}`);
- }
-
- if (addresses.length === 0) {
- throw new BlockedUrlError(`Could not resolve ${host}`);
- }
-
- for (const { address } of addresses) {
- if (isBlockedIp(address)) {
- throw new BlockedUrlError(
- `Refusing to connect to ${host} (resolves to a non-public address)`,
- );
- }
- }
-
- return addresses.map((entry) => entry.address);
-}
-
-/**
- * Validate a URL's scheme and destination without fetching it. Use this to
- * guard non-fetch outbound connections (raw TCP, TLS handshakes).
- * Throws {@link BlockedUrlError} when the URL must not be requested.
- */
-export async function assertPublicUrl(url: URL): Promise<string[]> {
- if (url.protocol !== 'http:' && url.protocol !== 'https:') {
- throw new BlockedUrlError('Only http/https URLs are allowed');
- }
- return resolvePublicAddresses(url.hostname);
-}
-
-/** Validate a bare hostname (no URL available), e.g. before a TLS probe. */
-export async function assertPublicHostname(
- hostname: string,
-): Promise<string[]> {
- return resolvePublicAddresses(hostname);
-}
-
-/**
- * A dispatcher that only ever connects to `address`, so the socket cannot end
- * up somewhere other than the address we just validated.
- */
-function createPinnedAgent(address: string): Agent {
- const family = net.isIPv6(address) ? 6 : 4;
- return new Agent({
- connect: {
- lookup: (_hostname, options, callback) => {
- if (options.all) {
- (callback as unknown as (
- err: null,
- addresses: { address: string; family: number }[],
- ) => void)(null, [{ address, family }]);
- return;
- }
- callback(null, address, family);
- },
- },
- });
-}
-
-export interface SafeFetchOptions {
- headers?: Record<string, string>;
- method?: string;
- /** Abort the whole chain after this many milliseconds. */
- timeoutMs?: number;
- maxRedirects?: number;
- /**
- * When false, a 3xx is returned as-is instead of being followed. Callers
- * that walk the chain themselves still get per-hop validation and pinning.
- */
- followRedirects?: boolean;
- /** Reject responses whose body exceeds this many bytes. */
- maxBytes?: number;
-}
-
-export interface SafeFetchResult {
- status: number;
- headers: Headers;
- body: Buffer;
- finalUrl: string;
- /** Every URL that was requested, in order, with the status it returned. */
- chain: { url: string; status: number }[];
-}
-
-const DEFAULT_MAX_REDIRECTS = 5;
-const DEFAULT_TIMEOUT_MS = 10_000;
-const DEFAULT_MAX_BYTES = 5_000_000;
-const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);
-
-async function readBodyWithLimit(
- body: ReadableStream<Uint8Array> | null,
- maxBytes: number,
-): Promise<Buffer> {
- if (!body) {
- return Buffer.alloc(0);
- }
-
- const chunks: Uint8Array[] = [];
- let total = 0;
- const reader = body.getReader();
-
- try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) {
- break;
- }
- if (!value) {
- continue;
- }
- total += value.byteLength;
- if (total > maxBytes) {
- throw new BlockedUrlError('Response exceeded the size limit');
- }
- chunks.push(value);
- }
- } finally {
- reader.releaseLock();
- await body.cancel().catch(() => {
- // best effort
- });
- }
-
- return Buffer.concat(chunks);
-}
-
-/**
- * `fetch` with SSRF protection: every hop is resolved, checked and pinned to
- * the validated address, and the body is read under a size cap.
- * Throws {@link BlockedUrlError} if any hop points somewhere non-public.
+ * This module stays as a re-export so the existing `@/utils/safe-fetch` imports
+ * keep working.
*/
-export async function safeFetch(
- input: string | URL,
- options: SafeFetchOptions = {},
-): Promise<SafeFetchResult> {
- const followRedirects = options.followRedirects ?? true;
- const maxRedirects = followRedirects
- ? (options.maxRedirects ?? DEFAULT_MAX_REDIRECTS)
- : 0;
- const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
- const chain: { url: string; status: number }[] = [];
-
- const controller = new AbortController();
- const timeout = setTimeout(
- () => controller.abort(),
- options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
- );
-
- try {
- let current = input instanceof URL ? input : new URL(input);
-
- for (let hop = 0; ; hop++) {
- const [address] = await assertPublicUrl(current);
- const agent = createPinnedAgent(address!);
-
- let status: number;
- let headers: Headers;
- let body: Buffer;
- let location: string | null;
-
- try {
- const response = await undiciFetch(current, {
- method: options.method ?? 'GET',
- headers: options.headers,
- signal: controller.signal,
- // Handled below so every hop is re-validated.
- redirect: 'manual',
- dispatcher: agent,
- });
-
- status = response.status;
- headers = response.headers as unknown as Headers;
- location = response.headers.get('location');
-
- if (followRedirects && REDIRECT_STATUS.has(status) && location) {
- await response.body?.cancel().catch(() => {
- // best effort
- });
- body = Buffer.alloc(0);
- } else {
- body = await readBodyWithLimit(
- response.body as ReadableStream<Uint8Array> | null,
- maxBytes,
- );
- }
- } finally {
- await agent.close().catch(() => {
- // best effort
- });
- }
-
- chain.push({ url: current.toString(), status });
-
- if (!(followRedirects && REDIRECT_STATUS.has(status) && location)) {
- return { status, headers, body, finalUrl: current.toString(), chain };
- }
-
- if (hop >= maxRedirects) {
- throw new BlockedUrlError('Too many redirects');
- }
-
- try {
- current = new URL(location, current);
- } catch {
- throw new BlockedUrlError('Invalid redirect location');
- }
- }
- } finally {
- clearTimeout(timeout);
- }
-}
+export {
+ BlockedUrlError,
+ assertPublicHostname,
+ assertPublicUrl,
+ createPinnedAgent,
+ isBlockedIp,
+ safeFetch,
+ safeFetchStream,
+ type SafeFetchOptions,
+ type SafeFetchResult,
+ type SafeFetchStreamResult,
+} from '@openpanel/common/server/safe-fetch';
diff --git a/apps/start/src/components/overview/overview-share.tsx b/apps/start/src/components/overview/overview-share.tsx
index 55b160476..a48e0bd44 100644
--- a/apps/start/src/components/overview/overview-share.tsx
+++ b/apps/start/src/components/overview/overview-share.tsx
@@ -6,6 +6,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
+import { useAppParams } from '@/hooks/use-app-params';
import { useTRPC } from '@/integrations/trpc/react';
import { pushModal } from '@/modals';
import { useMutation, useQuery } from '@tanstack/react-query';
@@ -17,9 +18,10 @@ interface OverviewShareProps {
}
export function OverviewShare({ projectId }: OverviewShareProps) {
+ const { organizationId } = useAppParams();
const trpc = useTRPC();
const query = useQuery(
- trpc.share.overview.queryOptions(
+ trpc.share.overviewSettings.queryOptions(
{
projectId,
},
@@ -71,7 +73,8 @@ export function OverviewShare({ projectId }: OverviewShareProps) {
<DropdownMenuItem
onClick={() => {
mutation.mutate({
- ...data,
+ organizationId,
+ projectId,
public: false,
password: null,
});
diff --git a/apps/start/src/components/settings/invites/columns.tsx b/apps/start/src/components/settings/invites/columns.tsx
index d335a1cfb..beccebc82 100644
--- a/apps/start/src/components/settings/invites/columns.tsx
+++ b/apps/start/src/components/settings/invites/columns.tsx
@@ -119,18 +119,19 @@ function AccessCell({
return (
<>
- {access.map((id) => {
- const project = projects.find((p) => p.id === id);
+ {access.map((grant) => {
+ const project = projects.find((p) => p.id === grant.projectId);
if (!project) {
return (
- <Badge key={id} className="mr-1">
+ <Badge key={grant.projectId} className="mr-1">
Unknown
</Badge>
);
}
return (
- <Badge key={id} color="blue" className="mr-1">
+ <Badge key={grant.projectId} color="blue" className="mr-1">
{project.name}
+ {grant.level === 'read' ? ' (read-only)' : ''}
</Badge>
);
})}
diff --git a/apps/start/src/components/settings/project-access-grants.tsx b/apps/start/src/components/settings/project-access-grants.tsx
new file mode 100644
index 000000000..8ad3e120b
--- /dev/null
+++ b/apps/start/src/components/settings/project-access-grants.tsx
@@ -0,0 +1,94 @@
+import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import type { IProjectAccessGrant } from '@openpanel/validation';
+
+interface ProjectAccessGrantsProps {
+ value: IProjectAccessGrant[];
+ onChange: (value: IProjectAccessGrant[]) => void;
+ projects: { id: string; name: string }[];
+}
+
+/**
+ * Picks the projects a member may reach and, for each, whether they may change
+ * anything in it. The level used to be hardcoded server-side, so `read` was
+ * assigned to people who were meant to have `write` - and nothing enforced it
+ * either way. Both halves are real now, so it has to be chooseable.
+ */
+export function ProjectAccessGrants({
+ value,
+ onChange,
+ projects,
+}: ProjectAccessGrantsProps) {
+ const selectedIds = value.map((grant) => grant.projectId);
+
+ const handleSelectionChange = (ids: string[]) => {
+ onChange(
+ ids.map(
+ (projectId) =>
+ value.find((grant) => grant.projectId === projectId) ?? {
+ projectId,
+ // Write is the default: restricting someone is the deliberate act.
+ level: 'write' as const,
+ },
+ ),
+ );
+ };
+
+ const handleLevelChange = (projectId: string, level: 'read' | 'write') => {
+ onChange(
+ value.map((grant) =>
+ grant.projectId === projectId ? { ...grant, level } : grant,
+ ),
+ );
+ };
+
+ return (
+ <div className="col gap-2">
+ <ComboboxAdvanced
+ placeholder="Restrict access to projects"
+ value={selectedIds}
+ onChange={(ids) => handleSelectionChange(ids as string[])}
+ items={projects.map((project) => ({
+ label: project.name,
+ value: project.id,
+ }))}
+ />
+
+ {value.length > 0 && (
+ <div className="col divide-y rounded-lg border">
+ {value.map((grant) => (
+ <div
+ key={grant.projectId}
+ className="row items-center justify-between gap-2 p-2"
+ >
+ <span className="truncate text-sm">
+ {projects.find((project) => project.id === grant.projectId)
+ ?.name ?? grant.projectId}
+ </span>
+ <Select
+ value={grant.level}
+ onValueChange={(level) =>
+ handleLevelChange(grant.projectId, level as 'read' | 'write')
+ }
+ >
+ <SelectTrigger className="w-36 shrink-0">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="write">Can edit</SelectItem>
+ <SelectItem value="read">Read-only</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/start/src/modals/create-invite.tsx b/apps/start/src/modals/create-invite.tsx
index e05e228a6..5b851bca8 100644
--- a/apps/start/src/modals/create-invite.tsx
+++ b/apps/start/src/modals/create-invite.tsx
@@ -1,6 +1,5 @@
import { InputWithLabel } from '@/components/forms/input-with-label';
import { Button } from '@/components/ui/button';
-import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import {
@@ -18,6 +17,7 @@ import { Controller, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
+import { ProjectAccessGrants } from '@/components/settings/project-access-grants';
import { useTRPC } from '@/integrations/trpc/react';
import type { IServiceProject } from '@openpanel/db';
import { zInviteUser } from '@openpanel/validation';
@@ -153,14 +153,10 @@ export default function CreateInvite() {
render={({ field }) => (
<div>
<Label>Restrict access</Label>
- <ComboboxAdvanced
- placeholder="Restrict access to projects"
+ <ProjectAccessGrants
value={field.value}
onChange={field.onChange}
- items={projects.map((item) => ({
- label: item.name,
- value: item.id,
- }))}
+ projects={projects}
/>
<p className="mt-1 text-sm text-muted-foreground">
Leave empty to give access to all projects
diff --git a/apps/start/src/modals/edit-member.tsx b/apps/start/src/modals/edit-member.tsx
index c1f1bb0e6..e8c36fdca 100644
--- a/apps/start/src/modals/edit-member.tsx
+++ b/apps/start/src/modals/edit-member.tsx
@@ -1,6 +1,6 @@
import { ButtonContainer } from '@/components/button-container';
import { Button } from '@/components/ui/button';
-import { ComboboxAdvanced } from '@/components/ui/combobox-advanced';
+import { ProjectAccessGrants } from '@/components/settings/project-access-grants';
import { useTRPC } from '@/integrations/trpc/react';
import { handleError } from '@/integrations/trpc/react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
@@ -8,6 +8,7 @@ import { useState } from 'react';
import { toast } from 'sonner';
import type { IServiceMember } from '@openpanel/db';
+import type { IProjectAccessGrant } from '@openpanel/validation';
import { popModal } from '.';
import { ModalContent, ModalHeader } from './Modal/Container';
@@ -18,9 +19,14 @@ export default function EditMember(member: EditMemberProps) {
const queryClient = useQueryClient();
const trpc = useTRPC();
- const [access, setAccess] = useState<string[]>(
- member.access?.map((a) => a.projectId) ?? [],
- );
+ const toGrants = (): IProjectAccessGrant[] =>
+ member.access?.map((a) => ({
+ projectId: a.projectId,
+ // `admin` is not offered per project - it collapses to write here.
+ level: a.level === 'read' ? ('read' as const) : ('write' as const),
+ })) ?? [];
+
+ const [access, setAccess] = useState<IProjectAccessGrant[]>(toGrants);
const projectsQuery = useQuery(
trpc.project.list.queryOptions({ organizationId: member.organizationId }),
@@ -30,7 +36,7 @@ export default function EditMember(member: EditMemberProps) {
trpc.organization.updateMemberAccess.mutationOptions({
onError(error) {
handleError(error);
- setAccess(member.access?.map((a) => a.projectId) ?? []);
+ setAccess(toGrants());
},
onSuccess() {
toast.success('Access updated');
@@ -56,11 +62,10 @@ export default function EditMember(member: EditMemberProps) {
/>
<div className="col gap-4">
- <ComboboxAdvanced
- placeholder="Restrict access to projects"
+ <ProjectAccessGrants
value={access}
- onChange={(newAccess) => setAccess(newAccess as string[])}
- items={projects.map((p) => ({ label: p.name, value: p.id }))}
+ onChange={setAccess}
+ projects={projects}
/>
<ButtonContainer>
diff --git a/apps/start/src/modals/share-dashboard-modal.tsx b/apps/start/src/modals/share-dashboard-modal.tsx
index 3a2e1ca83..5ac705540 100644
--- a/apps/start/src/modals/share-dashboard-modal.tsx
+++ b/apps/start/src/modals/share-dashboard-modal.tsx
@@ -37,7 +37,8 @@ export default function ShareDashboardModal({
// Fetch current share status
const shareQuery = useQuery(
- trpc.share.dashboard.queryOptions({
+ trpc.share.dashboardSettings.queryOptions({
+ projectId,
dashboardId,
}),
);
@@ -52,7 +53,7 @@ export default function ShareDashboardModal({
resolver: zodResolver(validator),
defaultValues: {
public: true,
- password: existingShare?.password ? '••••••••' : '',
+ password: existingShare?.hasPassword ? '••••••••' : '',
projectId,
organizationId,
dashboardId,
@@ -65,7 +66,7 @@ export default function ShareDashboardModal({
trpc.share.createDashboard.mutationOptions({
onError: handleError,
onSuccess(res) {
- queryClient.invalidateQueries(trpc.share.dashboard.pathFilter());
+ queryClient.invalidateQueries(trpc.share.dashboardSettings.pathFilter());
toast('Success', {
description: `Your dashboard is now ${
res.public ? 'public' : 'private'
diff --git a/apps/start/src/modals/share-overview-modal.tsx b/apps/start/src/modals/share-overview-modal.tsx
index 5d4b35630..ced7a9660 100644
--- a/apps/start/src/modals/share-overview-modal.tsx
+++ b/apps/start/src/modals/share-overview-modal.tsx
@@ -33,7 +33,7 @@ export default function ShareOverviewModal() {
// Fetch current share status
const shareQuery = useQuery(
- trpc.share.overview.queryOptions({
+ trpc.share.overviewSettings.queryOptions({
projectId,
}),
);
@@ -48,7 +48,7 @@ export default function ShareOverviewModal() {
resolver: zodResolver(validator),
defaultValues: {
public: true,
- password: existingShare?.password ? '••••••••' : '',
+ password: existingShare?.hasPassword ? '••••••••' : '',
projectId,
organizationId,
},
@@ -60,7 +60,7 @@ export default function ShareOverviewModal() {
trpc.share.createOverview.mutationOptions({
onError: handleError,
onSuccess(res) {
- queryClient.invalidateQueries(trpc.share.overview.pathFilter());
+ queryClient.invalidateQueries(trpc.share.overviewSettings.pathFilter());
toast('Success', {
description: `Your overview is now ${
res.public ? 'public' : 'private'
diff --git a/apps/start/src/modals/share-report-modal.tsx b/apps/start/src/modals/share-report-modal.tsx
index be98d241d..139180e58 100644
--- a/apps/start/src/modals/share-report-modal.tsx
+++ b/apps/start/src/modals/share-report-modal.tsx
@@ -33,7 +33,8 @@ export default function ShareReportModal({ reportId }: { reportId: string }) {
// Fetch current share status
const shareQuery = useQuery(
- trpc.share.report.queryOptions({
+ trpc.share.reportSettings.queryOptions({
+ projectId,
reportId,
}),
);
@@ -48,7 +49,7 @@ export default function ShareReportModal({ reportId }: { reportId: string }) {
resolver: zodResolver(validator),
defaultValues: {
public: true,
- password: existingShare?.password ? '••••••••' : '',
+ password: existingShare?.hasPassword ? '••••••••' : '',
projectId,
organizationId,
reportId,
@@ -61,7 +62,7 @@ export default function ShareReportModal({ reportId }: { reportId: string }) {
trpc.share.createReport.mutationOptions({
onError: handleError,
onSuccess(res) {
- queryClient.invalidateQueries(trpc.share.report.pathFilter());
+ queryClient.invalidateQueries(trpc.share.reportSettings.pathFilter());
toast('Success', {
description: `Your report is now ${res.public ? 'public' : 'private'}`,
action: res.public
diff --git a/apps/start/src/routes/share.dashboard.$shareId.tsx b/apps/start/src/routes/share.dashboard.$shareId.tsx
index f6d76fa7c..139932fbd 100644
--- a/apps/start/src/routes/share.dashboard.$shareId.tsx
+++ b/apps/start/src/routes/share.dashboard.$shareId.tsx
@@ -36,7 +36,9 @@ export const Route = createFileRoute('/share/dashboard/$shareId')({
return { share };
},
head: ({ loaderData }) => {
- if (!loaderData || !loaderData.share) {
+ const share = loaderData?.share;
+
+ if (!share) {
return {
meta: [
{
@@ -46,10 +48,21 @@ export const Route = createFileRoute('/share/dashboard/$shareId')({
};
}
+ // A locked share deliberately carries no dashboard, so title it by owner.
+ if (share.requiresPassword) {
+ return {
+ meta: [
+ {
+ title: `${share.organization?.name} - OpenPanel.dev`,
+ },
+ ],
+ };
+ }
+
return {
meta: [
{
- title: `${loaderData.share.dashboard?.name} - ${loaderData.share.organization?.name} - OpenPanel.dev`,
+ title: `${share.dashboard?.name} - ${share.organization?.name} - OpenPanel.dev`,
},
],
};
@@ -82,20 +95,15 @@ function RouteComponent() {
}),
);
- const hasAccess = shareQuery.data?.hasAccess;
-
- if (!shareQuery.data) {
- throw notFound();
- }
+ const share = shareQuery.data;
- if (!shareQuery.data.public) {
+ if (!share) {
throw notFound();
}
- const share = shareQuery.data;
-
- // Handle password protection
- if (share.password && !hasAccess) {
+ // The server refuses non-public shares outright and withholds the dashboard
+ // until the password cookie is present, so this only picks the UI.
+ if (share.requiresPassword) {
return <ShareEnterPassword shareId={share.id} shareType="dashboard" />;
}
diff --git a/apps/start/src/routes/share.overview.$shareId.tsx b/apps/start/src/routes/share.overview.$shareId.tsx
index 8befd5471..0d8fccf18 100644
--- a/apps/start/src/routes/share.overview.$shareId.tsx
+++ b/apps/start/src/routes/share.overview.$shareId.tsx
@@ -36,7 +36,9 @@ export const Route = createFileRoute('/share/overview/$shareId')({
return { share };
},
head: ({ loaderData }) => {
- if (!loaderData || !loaderData.share) {
+ const share = loaderData?.share;
+
+ if (!share) {
return {
meta: [
{
@@ -49,7 +51,7 @@ export const Route = createFileRoute('/share/overview/$shareId')({
return {
meta: [
{
- title: `${loaderData.share.project?.name} - ${loaderData.share.organization?.name} - OpenPanel.dev`,
+ title: `${share.project?.name} - ${share.organization?.name} - OpenPanel.dev`,
},
],
};
@@ -74,28 +76,24 @@ function RouteComponent() {
}),
);
- const hasAccess = shareQuery.data?.hasAccess;
- // Check if share exists and is public
if (shareQuery.isLoading) {
return <div>Loading...</div>;
}
- if (!shareQuery.data) {
- throw notFound();
- }
+ const share = shareQuery.data;
- if (!shareQuery.data.public) {
+ if (!share) {
throw notFound();
}
- const share = shareQuery.data;
- const projectId = share.projectId;
-
- // Handle password protection
- if (share.password && !hasAccess) {
+ // The server refuses non-public shares outright and withholds projectId
+ // until the password cookie is present, so this only picks the UI.
+ if (share.requiresPassword) {
return <ShareEnterPassword shareId={share.id} />;
}
+ const projectId = share.projectId;
+
const isHeaderVisible =
header !== '0' && header !== 0 && header !== 'false' && header !== false;
diff --git a/apps/start/src/routes/share.report.$shareId.tsx b/apps/start/src/routes/share.report.$shareId.tsx
index 3425f0db6..e908e3f6a 100644
--- a/apps/start/src/routes/share.report.$shareId.tsx
+++ b/apps/start/src/routes/share.report.$shareId.tsx
@@ -32,7 +32,9 @@ export const Route = createFileRoute('/share/report/$shareId')({
return { share };
},
head: ({ loaderData }) => {
- if (!loaderData || !loaderData.share) {
+ const share = loaderData?.share;
+
+ if (!share) {
return {
meta: [
{
@@ -42,10 +44,21 @@ export const Route = createFileRoute('/share/report/$shareId')({
};
}
+ // A locked share deliberately carries no report, so title it by owner only.
+ if (share.requiresPassword) {
+ return {
+ meta: [
+ {
+ title: `${share.organization?.name} - OpenPanel.dev`,
+ },
+ ],
+ };
+ }
+
return {
meta: [
{
- title: `${loaderData.share.report.name || 'Report'} - ${loaderData.share.organization?.name} - OpenPanel.dev`,
+ title: `${share.report.name || 'Report'} - ${share.organization?.name} - OpenPanel.dev`,
},
],
};
@@ -71,20 +84,15 @@ function RouteComponent() {
}),
);
- const hasAccess = shareQuery.data?.hasAccess;
-
- if (!shareQuery.data) {
- throw notFound();
- }
+ const share = shareQuery.data;
- if (!shareQuery.data.public) {
+ if (!share) {
throw notFound();
}
- const share = shareQuery.data;
-
- // Handle password protection
- if (share.password && !hasAccess) {
+ // The server refuses non-public shares outright and withholds the report
+ // until the password cookie is present, so this only picks the UI.
+ if (share.requiresPassword) {
return <ShareEnterPassword shareId={share.id} shareType="report" />;
}
diff --git a/apps/worker/src/jobs/notification.ts b/apps/worker/src/jobs/notification.ts
index 702fa93e3..d56bc24df 100644
--- a/apps/worker/src/jobs/notification.ts
+++ b/apps/worker/src/jobs/notification.ts
@@ -2,6 +2,8 @@ import type { Job } from 'bullmq';
import { Prisma, db } from '@openpanel/db';
import { sendDiscordNotification } from '@openpanel/integrations/src/discord';
+import { postWebhook } from '@openpanel/integrations/src/fetcher';
+import { safeWebhookFetcher } from '@openpanel/integrations/src/safe-fetcher';
import { sendSlackNotification } from '@openpanel/integrations/src/slack';
import { execute as executeJavaScriptTemplate } from '@openpanel/js-runtime';
import type { NotificationQueuePayload } from '@openpanel/queue';
@@ -73,17 +75,20 @@ export async function notificationJob(job: Job<NotificationQueuePayload>) {
};
}
- return fetch(integration.config.url, {
- method: 'POST',
- headers: {
- ...(integration.config.headers ?? {}),
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(body),
- });
+ // The webhook URL, its headers and (in javascript mode) its body are
+ // all user-controlled, and this runs inside our network. Re-validate
+ // the destination on every send rather than trusting it from when it
+ // was saved.
+ return postWebhook(
+ safeWebhookFetcher,
+ integration.config.url,
+ body,
+ integration.config.headers ?? {},
+ );
}
case 'discord': {
return sendDiscordNotification({
+ fetcher: safeWebhookFetcher,
webhookUrl: integration.config.url,
message: [
`🔔 **${notification.title}**`,
@@ -94,6 +99,7 @@ export async function notificationJob(job: Job<NotificationQueuePayload>) {
case 'slack': {
return sendSlackNotification({
+ fetcher: safeWebhookFetcher,
webhookUrl: integration.config.incoming_webhook.url,
message: [`🔔 *${notification.title}*`, notification.message].join(
'\n',
diff --git a/packages/common/package.json b/packages/common/package.json
index 60dbdac91..ec0ce3c01 100644
--- a/packages/common/package.json
+++ b/packages/common/package.json
@@ -6,7 +6,8 @@
"exports": {
".": "./index.ts",
"./server": "./server/index.ts",
- "./server/get-client-ip": "./server/get-client-ip.ts"
+ "./server/get-client-ip": "./server/get-client-ip.ts",
+ "./server/safe-fetch": "./server/safe-fetch.ts"
},
"scripts": {
"test": "vitest",
@@ -16,6 +17,7 @@
"dependencies": {
"@openpanel/constants": "workspace:*",
"date-fns": "^3.3.1",
+ "ipaddr.js": "^2.5.0",
"lru-cache": "^11.2.4",
"luxon": "^3.7.2",
"mathjs": "^12.3.2",
@@ -24,6 +26,7 @@
"slugify": "^1.6.6",
"superjson": "^1.13.3",
"ua-parser-js": "^2.0.6",
+ "undici": "^8.10.0",
"unique-names-generator": "^4.7.1"
},
"devDependencies": {
diff --git a/apps/api/src/utils/safe-fetch.test.ts b/packages/common/server/safe-fetch.test.ts
similarity index 58%
rename from apps/api/src/utils/safe-fetch.test.ts
rename to packages/common/server/safe-fetch.test.ts
index c04951dfa..19d774736 100644
--- a/apps/api/src/utils/safe-fetch.test.ts
+++ b/packages/common/server/safe-fetch.test.ts
@@ -1,7 +1,12 @@
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
-import { BlockedUrlError, isBlockedIp, safeFetch } from './safe-fetch';
+import {
+ BlockedUrlError,
+ isBlockedIp,
+ safeFetch,
+ safeFetchStream,
+} from './safe-fetch';
describe('isBlockedIp', () => {
it('blocks the ranges an SSRF payload aims at', () => {
@@ -113,3 +118,78 @@ describe('safeFetch', () => {
);
});
});
+
+describe('safeFetchStream', () => {
+ let secretServer: http.Server;
+ let redirectServer: http.Server;
+ let secretPort: number;
+ let redirectPort: number;
+
+ beforeAll(async () => {
+ secretServer = http.createServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'text/csv' });
+ res.end('INTERNAL-SECRET');
+ });
+ await new Promise<void>((resolve) =>
+ secretServer.listen(0, '127.0.0.1', resolve),
+ );
+ secretPort = (secretServer.address() as AddressInfo).port;
+
+ redirectServer = http.createServer((_req, res) => {
+ res.writeHead(302, {
+ location: `http://127.0.0.1:${secretPort}/export.csv`,
+ });
+ res.end();
+ });
+ await new Promise<void>((resolve) =>
+ redirectServer.listen(0, '127.0.0.1', resolve),
+ );
+ redirectPort = (redirectServer.address() as AddressInfo).port;
+ });
+
+ afterAll(async () => {
+ await new Promise<void>((resolve) => secretServer.close(() => resolve()));
+ await new Promise<void>((resolve) => redirectServer.close(() => resolve()));
+ });
+
+ // The streaming variant is what the importer uses, so it has to hold the
+ // same line as safeFetch - a second implementation that forgot one of these
+ // is exactly how the importer ended up unguarded in the first place.
+ it('refuses to fetch a loopback address directly', async () => {
+ await expect(
+ safeFetchStream(`http://127.0.0.1:${secretPort}/export.csv`, {
+ timeoutMs: 3000,
+ }),
+ ).rejects.toBeInstanceOf(BlockedUrlError);
+ });
+
+ it('refuses to fetch a hostname that resolves to loopback', async () => {
+ await expect(
+ safeFetchStream(`http://localhost:${secretPort}/export.csv`, {
+ timeoutMs: 3000,
+ }),
+ ).rejects.toBeInstanceOf(BlockedUrlError);
+ });
+
+ it('refuses a redirect that points at an internal address', async () => {
+ await expect(
+ safeFetchStream(`http://127.0.0.1:${redirectPort}/export.csv`, {
+ timeoutMs: 3000,
+ }),
+ ).rejects.toBeInstanceOf(BlockedUrlError);
+ });
+
+ it('refuses cloud instance metadata', async () => {
+ await expect(
+ safeFetchStream('http://169.254.169.254/latest/meta-data/', {
+ timeoutMs: 3000,
+ }),
+ ).rejects.toBeInstanceOf(BlockedUrlError);
+ });
+
+ it('refuses non-http schemes', async () => {
+ await expect(safeFetchStream('file:///etc/passwd')).rejects.toBeInstanceOf(
+ BlockedUrlError,
+ );
+ });
+});
diff --git a/packages/common/server/safe-fetch.ts b/packages/common/server/safe-fetch.ts
new file mode 100644
index 000000000..2f5cfddd9
--- /dev/null
+++ b/packages/common/server/safe-fetch.ts
@@ -0,0 +1,414 @@
+import dns from 'node:dns/promises';
+import net from 'node:net';
+import ipaddr from 'ipaddr.js';
+import { Agent, fetch as undiciFetch } from 'undici';
+
+/**
+ * SSRF guard for the endpoints that fetch user-supplied URLs (the favicon/OG
+ * proxy and the public site checker).
+ *
+ * Two things have to be true for the guard to hold:
+ *
+ * 1. Every address a hostname resolves to must be publicly routable. Checking
+ * only the first A record lets an attacker publish a second AAAA record.
+ * 2. The socket must connect to the address we validated. Resolving and then
+ * handing the hostname to `fetch` re-resolves it, so a DNS rebind between
+ * the two lookups reaches the internal target anyway. We pin the validated
+ * address into the connection instead.
+ *
+ * Redirects are followed manually so every hop goes through the same checks.
+ */
+
+export class BlockedUrlError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'BlockedUrlError';
+ }
+}
+
+/**
+ * ipaddr.js range names that are not publicly routable. `unicast` is the only
+ * range we accept; this list is spelled out so the intent is reviewable.
+ */
+const BLOCKED_RANGES = new Set([
+ 'unspecified', // 0.0.0.0/8, ::
+ 'broadcast', // 255.255.255.255
+ 'multicast', // 224.0.0.0/4, ff00::/8
+ 'linkLocal', // 169.254.0.0/16 (cloud metadata), fe80::/10
+ 'loopback', // 127.0.0.0/8, ::1
+ 'private', // 10/8, 172.16/12, 192.168/16
+ 'uniqueLocal', // fc00::/7
+ 'carrierGradeNat', // 100.64.0.0/10
+ 'reserved', // 192.0.0.0/24, 198.18/15, 240/4, 2001::/32, ...
+ 'benchmarking',
+ 'as112',
+ 'amt',
+ 'rfc6052', // 64:ff9b::/96
+ 'rfc6145',
+ 'teredo',
+ '6to4', // 2002::/16
+]);
+
+export function isBlockedIp(ip: string): boolean {
+ let parsed: ipaddr.IPv4 | ipaddr.IPv6;
+ try {
+ parsed = ipaddr.parse(ip);
+ } catch {
+ // Unparseable means we cannot prove it is safe.
+ return true;
+ }
+
+ // ::ffff:127.0.0.1 and friends must be judged as the IPv4 address they carry.
+ if (parsed.kind() === 'ipv6') {
+ const v6 = parsed as ipaddr.IPv6;
+ if (v6.isIPv4MappedAddress()) {
+ return isBlockedIp(v6.toIPv4Address().toString());
+ }
+ }
+
+ return BLOCKED_RANGES.has(parsed.range());
+}
+
+/**
+ * Resolve a hostname, rejecting it entirely if any address is non-public.
+ */
+async function resolvePublicAddresses(hostname: string): Promise<string[]> {
+ // WHATWG URL keeps the brackets around IPv6 literals ("[::1]").
+ const host =
+ hostname.startsWith('[') && hostname.endsWith(']')
+ ? hostname.slice(1, -1)
+ : hostname;
+
+ // A bare IP in the URL never hits DNS, so check it directly.
+ if (net.isIP(host)) {
+ if (isBlockedIp(host)) {
+ throw new BlockedUrlError(`Refusing to connect to ${host}`);
+ }
+ return [host];
+ }
+
+ let addresses: { address: string }[];
+ try {
+ // `lookup` rather than `resolve4`/`resolve6` so /etc/hosts and the system
+ // resolver are honoured the same way the real connection would.
+ addresses = await dns.lookup(host, { all: true, verbatim: true });
+ } catch {
+ throw new BlockedUrlError(`Could not resolve ${host}`);
+ }
+
+ if (addresses.length === 0) {
+ throw new BlockedUrlError(`Could not resolve ${host}`);
+ }
+
+ for (const { address } of addresses) {
+ if (isBlockedIp(address)) {
+ throw new BlockedUrlError(
+ `Refusing to connect to ${host} (resolves to a non-public address)`,
+ );
+ }
+ }
+
+ return addresses.map((entry) => entry.address);
+}
+
+/**
+ * Validate a URL's scheme and destination without fetching it. Use this to
+ * guard non-fetch outbound connections (raw TCP, TLS handshakes).
+ * Throws {@link BlockedUrlError} when the URL must not be requested.
+ */
+export async function assertPublicUrl(url: URL): Promise<string[]> {
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
+ throw new BlockedUrlError('Only http/https URLs are allowed');
+ }
+ return resolvePublicAddresses(url.hostname);
+}
+
+/** Validate a bare hostname (no URL available), e.g. before a TLS probe. */
+export async function assertPublicHostname(
+ hostname: string,
+): Promise<string[]> {
+ return resolvePublicAddresses(hostname);
+}
+
+/**
+ * A dispatcher that only ever connects to `address`, so the socket cannot end
+ * up somewhere other than the address we just validated.
+ */
+export function createPinnedAgent(address: string): Agent {
+ const family = net.isIPv6(address) ? 6 : 4;
+ return new Agent({
+ connect: {
+ lookup: (_hostname, options, callback) => {
+ if (options.all) {
+ (callback as unknown as (
+ err: null,
+ addresses: { address: string; family: number }[],
+ ) => void)(null, [{ address, family }]);
+ return;
+ }
+ callback(null, address, family);
+ },
+ },
+ });
+}
+
+export interface SafeFetchOptions {
+ headers?: Record<string, string>;
+ method?: string;
+ /** Request body, for the POST callers (webhook delivery). */
+ body?: string;
+ /** Abort the whole chain after this many milliseconds. */
+ timeoutMs?: number;
+ maxRedirects?: number;
+ /**
+ * When false, a 3xx is returned as-is instead of being followed. Callers
+ * that walk the chain themselves still get per-hop validation and pinning.
+ */
+ followRedirects?: boolean;
+ /** Reject responses whose body exceeds this many bytes. */
+ maxBytes?: number;
+ /** Caller-owned cancellation, combined with the timeout above. */
+ signal?: AbortSignal;
+}
+
+export interface SafeFetchResult {
+ status: number;
+ headers: Headers;
+ body: Buffer;
+ finalUrl: string;
+ /** Every URL that was requested, in order, with the status it returned. */
+ chain: { url: string; status: number }[];
+}
+
+const DEFAULT_MAX_REDIRECTS = 5;
+const DEFAULT_TIMEOUT_MS = 10_000;
+const DEFAULT_MAX_BYTES = 5_000_000;
+const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);
+
+async function readBodyWithLimit(
+ body: ReadableStream<Uint8Array> | null,
+ maxBytes: number,
+): Promise<Buffer> {
+ if (!body) {
+ return Buffer.alloc(0);
+ }
+
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ const reader = body.getReader();
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) {
+ break;
+ }
+ if (!value) {
+ continue;
+ }
+ total += value.byteLength;
+ if (total > maxBytes) {
+ throw new BlockedUrlError('Response exceeded the size limit');
+ }
+ chunks.push(value);
+ }
+ } finally {
+ reader.releaseLock();
+ await body.cancel().catch(() => {
+ // best effort
+ });
+ }
+
+ return Buffer.concat(chunks);
+}
+
+export interface SafeFetchStreamResult {
+ status: number;
+ headers: Headers;
+ /** The live response body. Consume it, then call {@link close}. */
+ body: ReadableStream<Uint8Array> | null;
+ finalUrl: string;
+ chain: { url: string; status: number }[];
+ /** Release the pinned connection. Safe to call more than once. */
+ close: () => Promise<void>;
+}
+
+function combineSignals(
+ timeoutSignal: AbortSignal,
+ callerSignal?: AbortSignal,
+): AbortSignal {
+ return callerSignal
+ ? AbortSignal.any([timeoutSignal, callerSignal])
+ : timeoutSignal;
+}
+
+/**
+ * Walk the redirect chain, resolving/validating/pinning every hop.
+ *
+ * Returns the final response together with the agent that owns its connection.
+ * The caller must close that agent once it is done with the body - which is
+ * what lets the streaming variant hand the body out without buffering it.
+ */
+async function walkToFinalResponse(
+ input: string | URL,
+ options: SafeFetchOptions,
+ signal: AbortSignal,
+): Promise<{
+ response: Awaited<ReturnType<typeof undiciFetch>>;
+ agent: Agent;
+ finalUrl: string;
+ chain: { url: string; status: number }[];
+}> {
+ const followRedirects = options.followRedirects ?? true;
+ const maxRedirects = followRedirects
+ ? (options.maxRedirects ?? DEFAULT_MAX_REDIRECTS)
+ : 0;
+ const chain: { url: string; status: number }[] = [];
+
+ let current = input instanceof URL ? input : new URL(input);
+
+ for (let hop = 0; ; hop++) {
+ const [address] = await assertPublicUrl(current);
+ const agent = createPinnedAgent(address!);
+
+ let response: Awaited<ReturnType<typeof undiciFetch>>;
+ try {
+ response = await undiciFetch(current, {
+ method: options.method ?? 'GET',
+ headers: options.headers,
+ body: options.body,
+ signal,
+ // Handled below so every hop is re-validated.
+ redirect: 'manual',
+ dispatcher: agent,
+ });
+ } catch (error) {
+ await agent.close().catch(() => {
+ // best effort
+ });
+ throw error;
+ }
+
+ const status = response.status;
+ const location = response.headers.get('location');
+ chain.push({ url: current.toString(), status });
+
+ if (!(followRedirects && REDIRECT_STATUS.has(status) && location)) {
+ return { response, agent, finalUrl: current.toString(), chain };
+ }
+
+ // A redirect hop is discarded entirely; the next one is validated afresh.
+ await response.body?.cancel().catch(() => {
+ // best effort
+ });
+ await agent.close().catch(() => {
+ // best effort
+ });
+
+ if (hop >= maxRedirects) {
+ throw new BlockedUrlError('Too many redirects');
+ }
+
+ try {
+ current = new URL(location, current);
+ } catch {
+ throw new BlockedUrlError('Invalid redirect location');
+ }
+ }
+}
+
+/**
+ * `fetch` with SSRF protection: every hop is resolved, checked and pinned to
+ * the validated address, and the body is read under a size cap.
+ * Throws {@link BlockedUrlError} if any hop points somewhere non-public.
+ */
+export async function safeFetch(
+ input: string | URL,
+ options: SafeFetchOptions = {},
+): Promise<SafeFetchResult> {
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
+ const controller = new AbortController();
+ const timeout = setTimeout(
+ () => controller.abort(),
+ options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
+ );
+
+ try {
+ const { response, agent, finalUrl, chain } = await walkToFinalResponse(
+ input,
+ options,
+ combineSignals(controller.signal, options.signal),
+ );
+
+ try {
+ const body = await readBodyWithLimit(
+ response.body as ReadableStream<Uint8Array> | null,
+ maxBytes,
+ );
+ return {
+ status: response.status,
+ headers: response.headers as unknown as Headers,
+ body,
+ finalUrl,
+ chain,
+ };
+ } finally {
+ await agent.close().catch(() => {
+ // best effort
+ });
+ }
+ } finally {
+ clearTimeout(timeout);
+ }
+}
+
+/**
+ * Same guarantees as {@link safeFetch}, but hands back the live body instead of
+ * buffering it. For callers that stream large responses through a parser and
+ * cannot hold them in memory (the importer's remote CSV reader).
+ *
+ * `timeoutMs` bounds the connection and redirect walk only - once the caller
+ * owns the stream, a long download is legitimate, so cancellation after that
+ * point is the caller's job via `options.signal`.
+ */
+export async function safeFetchStream(
+ input: string | URL,
+ options: SafeFetchOptions = {},
+): Promise<SafeFetchStreamResult> {
+ const controller = new AbortController();
+ const timeout = setTimeout(
+ () => controller.abort(),
+ options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
+ );
+
+ try {
+ const { response, agent, finalUrl, chain } = await walkToFinalResponse(
+ input,
+ options,
+ combineSignals(controller.signal, options.signal),
+ );
+
+ let closed = false;
+ return {
+ status: response.status,
+ headers: response.headers as unknown as Headers,
+ body: response.body as ReadableStream<Uint8Array> | null,
+ finalUrl,
+ chain,
+ close: async () => {
+ if (closed) {
+ return;
+ }
+ closed = true;
+ await response.body?.cancel().catch(() => {
+ // best effort
+ });
+ await agent.close().catch(() => {
+ // best effort
+ });
+ },
+ };
+ } finally {
+ clearTimeout(timeout);
+ }
+}
diff --git a/packages/db/prisma/migrations/20260825120000_backfill_project_access_read_to_write/migration.sql b/packages/db/prisma/migrations/20260825120000_backfill_project_access_read_to_write/migration.sql
new file mode 100644
index 000000000..a7c01d279
--- /dev/null
+++ b/packages/db/prisma/migrations/20260825120000_backfill_project_access_read_to_write/migration.sql
@@ -0,0 +1,21 @@
+-- Until now `ProjectAccess.level` was read by exactly three procedures (the
+-- import ones) and ignored by the other 26 mutating procedures, so the value
+-- was effectively inert. Two code paths wrote it and they disagreed:
+--
+-- * accepting an invite -> level = 'write'
+-- (packages/db/src/services/organization.service.ts)
+-- * editing a member -> level = 'read', hardcoded
+-- (organization.updateMemberAccess)
+--
+-- `updateMemberAccess` took a bare list of project ids: the admin chose WHICH
+-- projects, never WHAT level. No UI has ever offered a level choice, so every
+-- stored 'read' row is that hardcoded constant rather than anyone's intent.
+--
+-- Enforcement of the level starts with this release. Without this backfill,
+-- every member who was ever edited through the members modal would silently
+-- become read-only on every project the moment it deploys.
+--
+-- Lossless: no deliberate read grant can exist yet. Read-only access becomes
+-- expressible from this release onward, via the level selector on the invite
+-- and edit-member modals.
+UPDATE "project_access" SET "level" = 'write' WHERE "level" = 'read';
diff --git a/packages/db/prisma/migrations/20260825120100_invite_project_access_levels/migration.sql b/packages/db/prisma/migrations/20260825120100_invite_project_access_levels/migration.sql
new file mode 100644
index 000000000..6ef43acd1
--- /dev/null
+++ b/packages/db/prisma/migrations/20260825120100_invite_project_access_levels/migration.sql
@@ -0,0 +1,22 @@
+-- `Invite.projectAccess` was a text[] of project ids, so an invite could say
+-- WHICH projects the new member gets but not at WHAT level - the level was
+-- decided later by whichever code path happened to create the ProjectAccess
+-- rows. Now that the level is enforced, an admin has to be able to express it
+-- at invite time, so the column carries [{ projectId, level }].
+--
+-- Existing pending invites are converted to the level that accepting them
+-- would have produced anyway ('write', from connectUserToOrganization), so no
+-- pending invite changes meaning.
+ALTER TABLE "invites" ADD COLUMN "projectAccess_json" JSONB NOT NULL DEFAULT '[]';
+
+UPDATE "invites"
+SET "projectAccess_json" = COALESCE(
+ (
+ SELECT jsonb_agg(jsonb_build_object('projectId', pid, 'level', 'write'))
+ FROM unnest("projectAccess") AS pid
+ ),
+ '[]'::jsonb
+);
+
+ALTER TABLE "invites" DROP COLUMN "projectAccess";
+ALTER TABLE "invites" RENAME COLUMN "projectAccess_json" TO "projectAccess";
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index 10b219161..4b8c75be7 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -215,7 +215,8 @@ model Invite {
createdById String
organizationId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
- projectAccess String[]
+ /// [IPrismaInviteProjectAccess]
+ projectAccess Json @default("[]")
expiresAt DateTime
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
diff --git a/packages/db/src/services/access.service.ts b/packages/db/src/services/access.service.ts
index 53cf364a3..4404a0fcc 100644
--- a/packages/db/src/services/access.service.ts
+++ b/packages/db/src/services/access.service.ts
@@ -1,15 +1,47 @@
+import type { AccessLevel } from '../generated/prisma/client';
import { cacheable } from '@openpanel/redis';
import { db } from '../prisma-client';
import { getProjectById } from './project.service';
+export type IProjectAccess = { level: AccessLevel };
+
+/** Access levels that may mutate. `admin` is a superset of `write`. */
+const WRITE_LEVELS: ReadonlySet<AccessLevel> = new Set<AccessLevel>([
+ 'write',
+ 'admin',
+]);
+
+export function canWriteProject(access: IProjectAccess | null): boolean {
+ return !!access && WRITE_LEVELS.has(access.level);
+}
+
+/**
+ * Resolve a user's access to one project.
+ *
+ * Returns a single shape - `{ level }` or `null` - on purpose. This used to
+ * return `true` for members with no explicit ProjectAccess rows and the row
+ * itself otherwise, which forced every caller into a `typeof access !==
+ * 'boolean'` dance. 26 of 29 mutating procedures skipped the level check
+ * entirely as a result (GHSA-f9rx-pxgw-c6rg); with one shape, omitting the
+ * check is a type error rather than a silent grant.
+ *
+ * NOTE: the cache key is versioned. Changing the return shape without renaming
+ * it would serve old-shape entries for up to 5 minutes across a rolling deploy.
+ */
export const getProjectAccess = cacheable(
- 'getProjectAccess',
- async ({ userId, projectId }: { userId: string; projectId: string }) => {
+ 'getProjectAccessV2',
+ async ({
+ userId,
+ projectId,
+ }: {
+ userId: string;
+ projectId: string;
+ }): Promise<IProjectAccess | null> => {
try {
// Check if user has access to the project
const project = await getProjectById(projectId);
if (!project?.organizationId) {
- return false;
+ return null;
}
const [projectAccess, member] = await Promise.all([
@@ -27,13 +59,21 @@ export const getProjectAccess = cacheable(
}),
]);
- if (projectAccess.length === 0 && member) {
- return true;
+ if (!member) {
+ return null;
}
- return projectAccess.find((item) => item.projectId === projectId);
+ // No explicit per-project grants means org-wide default access, and the
+ // default is write.
+ if (projectAccess.length === 0) {
+ return { level: 'write' };
+ }
+
+ const row = projectAccess.find((item) => item.projectId === projectId);
+
+ return row ? { level: row.level } : null;
} catch (err) {
- return false;
+ return null;
}
},
60 * 5
diff --git a/packages/db/src/services/organization.service.ts b/packages/db/src/services/organization.service.ts
index 7c1f4a303..7aeca5a68 100644
--- a/packages/db/src/services/organization.service.ts
+++ b/packages/db/src/services/organization.service.ts
@@ -189,14 +189,18 @@ export async function connectUserToOrganization({
});
if (invite.projectAccess.length > 0) {
- for (const projectId of invite.projectAccess) {
- await getProjectAccess.clear({ userId: user.id, projectId });
+ for (const grant of invite.projectAccess) {
+ await getProjectAccess.clear({
+ userId: user.id,
+ projectId: grant.projectId,
+ });
await db.projectAccess.create({
data: {
- projectId,
+ projectId: grant.projectId,
userId: user.id,
organizationId: invite.organizationId,
- level: 'write',
+ // The level the inviting admin chose, not a hardcoded default.
+ level: grant.level,
},
});
}
diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts
index aacd6d1e7..28e5210be 100644
--- a/packages/db/src/types.ts
+++ b/packages/db/src/types.ts
@@ -1,6 +1,7 @@
import type {
CohortDefinition,
IImportConfig,
+ IProjectAccessGrant,
IIntegrationConfig,
INotificationRuleConfig,
IProjectFilters,
@@ -21,6 +22,7 @@ declare global {
type IPrismaIntegrationConfig = IIntegrationConfig;
type IPrismaNotificationPayload = INotificationPayload;
type IPrismaProjectFilters = IProjectFilters[];
+ type IPrismaInviteProjectAccess = IProjectAccessGrant[];
type IPrismaProjectInsightPayload = InsightPayload;
type IPrismaWidgetOptions = IWidgetOptions;
type IPrismaClickhouseEvent = IClickhouseEvent;
diff --git a/packages/importer/src/providers/umami.test.ts b/packages/importer/src/providers/umami.test.ts
new file mode 100644
index 000000000..a386a6ae2
--- /dev/null
+++ b/packages/importer/src/providers/umami.test.ts
@@ -0,0 +1,78 @@
+import http from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { UmamiProvider } from './umami';
+
+/**
+ * The umami provider fetches a caller-supplied `fileUrl`. Before
+ * GHSA-cj2r-3x54-88h7 it used a bare `fetch`, which let any org member point it
+ * at loopback, RFC1918 or 169.254.169.254 and read the upstream status back out
+ * of `Import.errorMessage`. Both halves are covered here: the connection must
+ * not happen, and nothing about the target may leak into the thrown message.
+ */
+describe('umami remote file SSRF guard', () => {
+ let internalServer: http.Server;
+ let internalPort: number;
+ let hits: string[] = [];
+
+ beforeAll(async () => {
+ internalServer = http.createServer((req, res) => {
+ hits.push(req.url ?? '');
+ // A deliberately unmistakable status - if it ever surfaces in an error
+ // message, the oracle is back.
+ res.writeHead(418, { 'content-type': 'text/csv' });
+ res.end('INTERNAL_ONLY_SECRET\n');
+ });
+ await new Promise<void>((resolve) =>
+ internalServer.listen(0, '127.0.0.1', resolve),
+ );
+ internalPort = (internalServer.address() as AddressInfo).port;
+ });
+
+ afterAll(async () => {
+ await new Promise<void>((resolve) => internalServer.close(() => resolve()));
+ });
+
+ const drain = async (fileUrl: string) => {
+ const provider = new UmamiProvider('pid', {
+ provider: 'umami',
+ type: 'file',
+ fileUrl,
+ projectMapper: [],
+ });
+
+ for await (const _event of provider.parseSource()) {
+ // parseSource must throw before yielding anything
+ }
+ };
+
+ it('refuses a loopback fileUrl and never connects', async () => {
+ hits = [];
+
+ await expect(
+ drain(`http://127.0.0.1:${internalPort}/secret.csv`),
+ ).rejects.toThrow();
+
+ expect(hits).toEqual([]);
+ });
+
+ it('refuses cloud instance metadata', async () => {
+ await expect(
+ drain('http://169.254.169.254/latest/meta-data/'),
+ ).rejects.toThrow();
+ });
+
+ it('does not leak the upstream status or URL in the error', async () => {
+ hits = [];
+ const target = `http://127.0.0.1:${internalPort}/secret.csv`;
+
+ const error = await drain(target).catch((err: unknown) => err as Error);
+
+ expect(error).toBeInstanceOf(Error);
+ // The old message was `Failed to fetch remote file: 418 I'm a Teapot`.
+ expect(error.message).not.toContain('418');
+ expect(error.message).not.toContain('Teapot');
+ expect(error.message).not.toContain(target);
+ expect(hits).toEqual([]);
+ });
+});
diff --git a/packages/importer/src/providers/umami.ts b/packages/importer/src/providers/umami.ts
index 71eb14bff..758ddd85b 100644
--- a/packages/importer/src/providers/umami.ts
+++ b/packages/importer/src/providers/umami.ts
@@ -8,6 +8,7 @@ import {
getReferrerWithQuery,
parseReferrer,
} from '@openpanel/common/server';
+import { safeFetchStream } from '@openpanel/common/server/safe-fetch';
import { formatClickhouseDate, type IClickhouseEvent } from '@openpanel/db';
import type { ILogger } from '@openpanel/logger';
import type { IUmamiImportConfig } from '@openpanel/validation';
@@ -16,6 +17,16 @@ import { assocPath } from 'ramda';
import { z } from 'zod';
import { BaseImportProvider } from '../base-provider';
+/**
+ * Bounds for a remote Umami export. `parseRemoteFile` has always accepted these
+ * but `parseSource` never passed them, so every guard inside it was dead code
+ * and the download was unbounded.
+ */
+const MAX_IMPORT_BYTES = 2_000_000_000; // 2 GB
+const MAX_IMPORT_ROWS = 50_000_000;
+/** Bounds the connection and redirect walk only, not the download itself. */
+const IMPORT_CONNECT_TIMEOUT_MS = 30_000;
+
export const zUmamiRawEvent = z.object({
// Required fields
event_type: z.coerce.number(),
@@ -76,7 +87,10 @@ export class UmamiProvider extends BaseImportProvider<UmamiRawEvent> {
}
async *parseSource(): AsyncGenerator<UmamiRawEvent, void, unknown> {
- yield* this.parseRemoteFile(this.config.fileUrl);
+ yield* this.parseRemoteFile(this.config.fileUrl, {
+ maxBytes: MAX_IMPORT_BYTES,
+ maxRows: MAX_IMPORT_ROWS,
+ });
}
private async *parseRemoteFile(
@@ -89,6 +103,7 @@ export class UmamiProvider extends BaseImportProvider<UmamiRawEvent> {
): AsyncGenerator<UmamiRawEvent, void, unknown> {
const { signal, maxBytes, maxRows } = opts;
const controller = new AbortController();
+ let closeRemote: (() => Promise<void>) | undefined;
// Link to caller's signal for cancellation
if (signal) {
@@ -97,11 +112,24 @@ export class UmamiProvider extends BaseImportProvider<UmamiRawEvent> {
});
}
- const res = await fetch(url, { signal: controller.signal });
- if (!(res.ok && res.body)) {
- throw new Error(
- `Failed to fetch remote file: ${res.status} ${res.statusText}`
+ // safeFetchStream resolves the host, refuses non-public addresses, pins the
+ // socket to the address it validated and re-checks every redirect hop, so a
+ // caller-supplied fileUrl cannot reach loopback, RFC1918 or cloud metadata
+ // (GHSA-cj2r-3x54-88h7).
+ const res = await safeFetchStream(url, {
+ signal: controller.signal,
+ timeoutMs: IMPORT_CONNECT_TIMEOUT_MS,
+ });
+ closeRemote = res.close;
+
+ if (!(res.status >= 200 && res.status < 300 && res.body)) {
+ // Deliberately opaque: the status of an internal host is exactly the
+ // oracle this endpoint used to hand back through Import.errorMessage.
+ this.logger?.error(
+ { status: res.status, finalUrl: res.finalUrl },
+ 'Failed to fetch remote import file'
);
+ throw new Error('Failed to fetch remote file');
}
const contentType = res.headers.get('content-type') || '';
@@ -206,13 +234,13 @@ export class UmamiProvider extends BaseImportProvider<UmamiRawEvent> {
yield record as UmamiRawEvent;
}
} catch (err) {
- throw new Error(
- `Failed to parse remote file from ${url}: ${
- err instanceof Error ? err.message : String(err)
- }`
- );
+ this.logger?.error({ err, url }, 'Failed to parse remote import file');
+ throw new Error('Failed to parse remote file');
} finally {
controller.abort(); // ensure fetch stream is torn down
+ await closeRemote?.().catch(() => {
+ // best effort
+ });
}
}
diff --git a/packages/integrations/package.json b/packages/integrations/package.json
index 59acc578f..b860444bf 100644
--- a/packages/integrations/package.json
+++ b/packages/integrations/package.json
@@ -8,7 +8,8 @@
},
"dependencies": {
"@slack/bolt": "^3.18.0",
- "@slack/oauth": "^3.0.0"
+ "@slack/oauth": "^3.0.0",
+ "@openpanel/common": "workspace:*"
},
"devDependencies": {
"@openpanel/tsconfig": "workspace:*",
diff --git a/packages/integrations/src/discord.ts b/packages/integrations/src/discord.ts
index 58087f5f6..8505a21d4 100644
--- a/packages/integrations/src/discord.ts
+++ b/packages/integrations/src/discord.ts
@@ -1,27 +1,30 @@
// Cred to (@OpenStatusHQ) https://github.com/openstatusHQ/openstatus/blob/main/packages/notifications/discord/src/index.ts
+import {
+ browserFetcher,
+ postWebhook,
+ type WebhookFetcher,
+ type WebhookResult,
+} from './fetcher';
+
export function sendDiscordNotification({
webhookUrl,
message,
+ fetcher = browserFetcher,
}: {
webhookUrl: string;
message: string;
-}) {
- return fetch(webhookUrl, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- content: message,
- avatar_url: 'https://openpanel.dev/logo.jpg',
- username: 'OpenPanel Notifications',
- }),
- }).catch((err) => {
- return {
- ok: false,
- json: () => Promise.resolve({}),
- };
+ /**
+ * Server callers MUST pass `safeWebhookFetcher` from `./safe-fetcher` - the
+ * webhook URL is user-supplied and stored, so sending from inside our network
+ * with a bare `fetch` makes this an SSRF probe.
+ */
+ fetcher?: WebhookFetcher;
+}): Promise<WebhookResult> {
+ return postWebhook(fetcher, webhookUrl, {
+ content: message,
+ avatar_url: 'https://openpanel.dev/logo.jpg',
+ username: 'OpenPanel Notifications',
});
}
diff --git a/packages/integrations/src/fetcher.ts b/packages/integrations/src/fetcher.ts
new file mode 100644
index 000000000..2b9ea569f
--- /dev/null
+++ b/packages/integrations/src/fetcher.ts
@@ -0,0 +1,53 @@
+/**
+ * Webhook delivery is reachable from two very different places:
+ *
+ * - the dashboard's "send test notification" button, which runs in the
+ * browser and is just the user calling their own webhook, and
+ * - the worker, which sends from inside our network and therefore must not be
+ * usable as an SSRF probe.
+ *
+ * Injecting the transport keeps this module browser-safe (a plain `fetch`) while
+ * letting server callers pass the SSRF-guarded one from `./safe-fetcher`, which
+ * pulls in `node:dns`/`undici` and must never reach a client bundle.
+ */
+
+export type WebhookFetcher = (
+ url: string,
+ init: {
+ method: string;
+ headers: Record<string, string>;
+ body: string;
+ },
+) => Promise<{ status: number }>;
+
+export interface WebhookResult {
+ ok: boolean;
+ status: number;
+}
+
+export const browserFetcher: WebhookFetcher = async (url, init) => {
+ const res = await fetch(url, init);
+ return { status: res.status };
+};
+
+export async function postWebhook(
+ fetcher: WebhookFetcher,
+ url: string,
+ body: unknown,
+ extraHeaders: Record<string, string> = {},
+): Promise<WebhookResult> {
+ try {
+ const { status } = await fetcher(url, {
+ method: 'POST',
+ headers: {
+ ...extraHeaders,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(body),
+ });
+
+ return { ok: status >= 200 && status < 300, status };
+ } catch {
+ return { ok: false, status: 0 };
+ }
+}
diff --git a/packages/integrations/src/safe-fetcher.ts b/packages/integrations/src/safe-fetcher.ts
new file mode 100644
index 000000000..93bf19abb
--- /dev/null
+++ b/packages/integrations/src/safe-fetcher.ts
@@ -0,0 +1,21 @@
+import { safeFetch } from '@openpanel/common/server/safe-fetch';
+import type { WebhookFetcher } from './fetcher';
+
+/**
+ * Server-side webhook transport. Resolves the host, refuses non-publicly
+ * routable addresses, pins the socket to the address it validated and
+ * re-validates every redirect hop, so a stored webhook URL cannot be used to
+ * reach loopback, RFC1918 neighbours or cloud metadata.
+ *
+ * Node-only - never import this from browser code.
+ */
+export const safeWebhookFetcher: WebhookFetcher = async (url, init) => {
+ const res = await safeFetch(url, {
+ method: init.method,
+ headers: init.headers,
+ body: init.body,
+ timeoutMs: 10_000,
+ });
+
+ return { status: res.status };
+};
diff --git a/packages/integrations/src/slack.ts b/packages/integrations/src/slack.ts
index 893751510..2fadd009c 100644
--- a/packages/integrations/src/slack.ts
+++ b/packages/integrations/src/slack.ts
@@ -1,6 +1,12 @@
// Cred to (@c_alares) https://github.com/christianalares/seventy-seven/blob/main/packages/integrations/src/slack/index.ts
import * as Slack from '@slack/bolt';
+import {
+ browserFetcher,
+ postWebhook,
+ type WebhookFetcher,
+ type WebhookResult,
+} from './fetcher';
const { LogLevel, App: SlackApp } = Slack;
import { InstallProvider } from '@slack/oauth';
@@ -44,17 +50,16 @@ export const getSlackInstallUrl = ({
export function sendSlackNotification({
webhookUrl,
message,
+ fetcher = browserFetcher,
}: {
webhookUrl: string;
message: string;
-}) {
- return fetch(webhookUrl, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- text: message,
- }),
- });
+ /**
+ * Server callers MUST pass `safeWebhookFetcher` from `./safe-fetcher`. The URL
+ * comes from Slack's OAuth response rather than raw user input, but it is
+ * still a stored URL we POST to from inside our network.
+ */
+ fetcher?: WebhookFetcher;
+}): Promise<WebhookResult> {
+ return postWebhook(fetcher, webhookUrl, { text: message });
}
diff --git a/packages/trpc/src/access.test.ts b/packages/trpc/src/access.test.ts
new file mode 100644
index 000000000..25f82d56d
--- /dev/null
+++ b/packages/trpc/src/access.test.ts
@@ -0,0 +1,131 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { getProjectAccess, getOrganizationAccess, getProjectById } = vi.hoisted(
+ () => ({
+ getProjectAccess: vi.fn(),
+ getOrganizationAccess: vi.fn(),
+ getProjectById: vi.fn(),
+ }),
+);
+
+vi.mock('@openpanel/db', () => ({
+ getProjectAccess,
+ getOrganizationAccess,
+ getProjectById,
+ getClientAccess: vi.fn(),
+ // The real implementation - `admin` is a superset of `write`.
+ canWriteProject: (access: { level: string } | null) =>
+ !!access && (access.level === 'write' || access.level === 'admin'),
+}));
+
+import {
+ requireOrganizationAdmin,
+ requireProjectAccess,
+ requireProjectAdmin,
+} from './access';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+/**
+ * GHSA-f9rx-pxgw-c6rg: 26 of 29 mutating procedures tested `if (!access)`,
+ * and a `{ level: 'read' }` row is a truthy object, so read-only members could
+ * delete projects and publish private analytics.
+ */
+describe('requireProjectAccess', () => {
+ it('rejects a non-member at every level', async () => {
+ getProjectAccess.mockResolvedValue(null);
+
+ await expect(
+ requireProjectAccess({ userId: 'u', projectId: 'p', level: 'read' }),
+ ).rejects.toThrow('You do not have access to this project');
+ });
+
+ it('rejects a read-level member from writing', async () => {
+ getProjectAccess.mockResolvedValue({ level: 'read' });
+
+ await expect(
+ requireProjectAccess({ userId: 'u', projectId: 'p', level: 'write' }),
+ ).rejects.toThrow('read-only');
+ });
+
+ it('lets a read-level member read', async () => {
+ getProjectAccess.mockResolvedValue({ level: 'read' });
+
+ await expect(
+ requireProjectAccess({ userId: 'u', projectId: 'p', level: 'read' }),
+ ).resolves.toEqual({ level: 'read' });
+ });
+
+ it.each(['write', 'admin'])('lets a %s-level member write', async (level) => {
+ getProjectAccess.mockResolvedValue({ level });
+
+ await expect(
+ requireProjectAccess({ userId: 'u', projectId: 'p', level: 'write' }),
+ ).resolves.toEqual({ level });
+ });
+});
+
+describe('requireOrganizationAdmin', () => {
+ it('rejects a plain member', async () => {
+ getOrganizationAccess.mockResolvedValue({ role: 'org:member' });
+
+ await expect(
+ requireOrganizationAdmin({ userId: 'u', organizationId: 'o' }),
+ ).rejects.toThrow('Only organization admins');
+ });
+
+ it('rejects a non-member', async () => {
+ getOrganizationAccess.mockResolvedValue(null);
+
+ await expect(
+ requireOrganizationAdmin({ userId: 'u', organizationId: 'o' }),
+ ).rejects.toThrow('Only organization admins');
+ });
+
+ it('allows an org admin', async () => {
+ getOrganizationAccess.mockResolvedValue({ role: 'org:admin' });
+
+ await expect(
+ requireOrganizationAdmin({ userId: 'u', organizationId: 'o' }),
+ ).resolves.toEqual({ role: 'org:admin' });
+ });
+});
+
+describe('requireProjectAdmin', () => {
+ it('resolves the org from the project, then requires admin', async () => {
+ getProjectById.mockResolvedValue({ organizationId: 'o' });
+ getOrganizationAccess.mockResolvedValue({ role: 'org:member' });
+
+ await expect(
+ requireProjectAdmin({ userId: 'u', projectId: 'p' }),
+ ).rejects.toThrow('Only organization admins');
+
+ expect(getOrganizationAccess).toHaveBeenCalledWith({
+ userId: 'u',
+ organizationId: 'o',
+ });
+ });
+
+ it('rejects when the project has no organization', async () => {
+ getProjectById.mockResolvedValue(null);
+
+ await expect(
+ requireProjectAdmin({ userId: 'u', projectId: 'p' }),
+ ).rejects.toThrow('You do not have access to this project');
+
+ expect(getOrganizationAccess).not.toHaveBeenCalled();
+ });
+
+ // A write-level member must not be able to schedule a project for deletion
+ // just because they can edit reports in it.
+ it('allows an org admin', async () => {
+ getProjectById.mockResolvedValue({ organizationId: 'o' });
+ getOrganizationAccess.mockResolvedValue({ role: 'org:admin' });
+
+ await expect(
+ requireProjectAdmin({ userId: 'u', projectId: 'p' }),
+ ).resolves.toEqual({ role: 'org:admin' });
+ });
+});
diff --git a/packages/trpc/src/access.ts b/packages/trpc/src/access.ts
index 29e24fd08..215ae9837 100644
--- a/packages/trpc/src/access.ts
+++ b/packages/trpc/src/access.ts
@@ -1,5 +1,106 @@
+import {
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectAccess,
+ getProjectById,
+} from '@openpanel/db';
+import { TRPCForbiddenError } from './errors';
+
export {
getOrganizationAccess,
getProjectAccess,
getClientAccess,
} from '@openpanel/db';
+
+/**
+ * The permission ladder.
+ *
+ * Two independent controls, each with one job:
+ *
+ * - ADMIN is the organization role (`member.role === 'org:admin'`). It gates
+ * destruction and billing.
+ * - WRITE is the per-project access level. It gates every mutation. `admin`
+ * level counts as a superset of `write`.
+ * - READ is the floor: membership of the project, which is what queries need.
+ *
+ * They are deliberately separate. Project levels were unenforced for so long
+ * that the value stored on most rows was never chosen by anyone, so hanging
+ * destructive operations off the org role avoids retroactively giving meaning
+ * to that data.
+ */
+
+/**
+ * Assert the caller may act on a project at the given level.
+ *
+ * Prefer this over calling `getProjectAccess` and testing truthiness: a truthy
+ * result only proves membership, which is how a read-only member could delete
+ * reports and publish private analytics (GHSA-f9rx-pxgw-c6rg).
+ */
+export async function requireProjectAccess({
+ userId,
+ projectId,
+ level,
+}: {
+ userId: string;
+ projectId: string;
+ level: 'read' | 'write';
+}) {
+ const access = await getProjectAccess({ userId, projectId });
+
+ if (!access) {
+ throw new TRPCForbiddenError('You do not have access to this project');
+ }
+
+ if (level === 'write' && !canWriteProject(access)) {
+ throw new TRPCForbiddenError(
+ 'You have read-only access to this project',
+ );
+ }
+
+ return access;
+}
+
+/** Assert the caller is an admin of the organization. */
+export async function requireOrganizationAdmin({
+ userId,
+ organizationId,
+ message = 'Only organization admins can do this',
+}: {
+ userId: string;
+ organizationId: string;
+ message?: string;
+}) {
+ const access = await getOrganizationAccess({ userId, organizationId });
+
+ if (access?.role !== 'org:admin') {
+ throw new TRPCForbiddenError(message);
+ }
+
+ return access;
+}
+
+/**
+ * Assert the caller is an admin of the organization that owns a project, for
+ * the destructive procedures that only receive a `projectId`.
+ */
+export async function requireProjectAdmin({
+ userId,
+ projectId,
+ message,
+}: {
+ userId: string;
+ projectId: string;
+ message?: string;
+}) {
+ const project = await getProjectById(projectId);
+
+ if (!project?.organizationId) {
+ throw new TRPCForbiddenError('You do not have access to this project');
+ }
+
+ return requireOrganizationAdmin({
+ userId,
+ organizationId: project.organizationId,
+ message,
+ });
+}
diff --git a/packages/trpc/src/routers/client.ts b/packages/trpc/src/routers/client.ts
index 5c09b47ef..75e2fefa5 100644
--- a/packages/trpc/src/routers/client.ts
+++ b/packages/trpc/src/routers/client.ts
@@ -5,7 +5,7 @@ import type { Prisma } from '@openpanel/db';
import { db } from '@openpanel/db';
import { hashPassword } from '@openpanel/common/server';
-import { getClientAccess } from '../access';
+import { getClientAccess, requireOrganizationAdmin } from '../access';
import { TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
@@ -58,7 +58,15 @@ export const clientRouter = createTRPCRouter({
type: z.enum(['read', 'write', 'root']).optional(),
}),
)
- .mutation(async ({ input }) => {
+ .mutation(async ({ input, ctx }) => {
+ // Minting an ingestion credential - a `root` one at the caller's choosing
+ // - is admin-tier, not something any org member should be able to do.
+ await requireOrganizationAdmin({
+ userId: ctx.session.userId,
+ organizationId: input.organizationId,
+ message: 'Only organization admins can create API clients',
+ });
+
const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
const data: Prisma.ClientCreateArgs['data'] = {
organizationId: input.organizationId,
@@ -82,15 +90,22 @@ export const clientRouter = createTRPCRouter({
}),
)
.mutation(async ({ input, ctx }) => {
- const access = await getClientAccess({
- userId: ctx.session.userId,
- clientId: input.id,
+ const client = await db.client.findUnique({
+ where: { id: input.id },
+ select: { organizationId: true },
});
- if (!access) {
+ if (!client?.organizationId) {
throw new TRPCForbiddenError('You do not have access to this client');
}
+ // Revoking a credential breaks ingestion for whoever is using it.
+ await requireOrganizationAdmin({
+ userId: ctx.session.userId,
+ organizationId: client.organizationId,
+ message: 'Only organization admins can delete API clients',
+ });
+
await db.client.delete({
where: {
id: input.id,
diff --git a/packages/trpc/src/routers/cohort.ts b/packages/trpc/src/routers/cohort.ts
index 22ffa06ac..dd73fa49a 100644
--- a/packages/trpc/src/routers/cohort.ts
+++ b/packages/trpc/src/routers/cohort.ts
@@ -19,7 +19,7 @@ import {
zCohortUpdate,
} from '@openpanel/validation';
import { z } from 'zod';
-import { getProjectAccess } from '../access';
+import { getProjectAccess, requireProjectAccess } from '../access';
import { TRPCForbiddenError, TRPCNotFoundError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
@@ -97,15 +97,12 @@ export const cohortRouter = createTRPCRouter({
throw new TRPCNotFoundError('Cohort not found');
}
- const access = await getProjectAccess({
- projectId: existingCohort.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId!,
+ projectId: existingCohort.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this cohort');
- }
-
const cohort = await db.cohort.update({
where: { id },
data: {
@@ -134,15 +131,12 @@ export const cohortRouter = createTRPCRouter({
throw new TRPCNotFoundError('Cohort not found');
}
- const access = await getProjectAccess({
- projectId: cohort.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId!,
+ projectId: cohort.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this cohort');
- }
-
await db.cohort.delete({ where: { id: input.id } });
deleteCohortMembership(input.id, cohort.projectId).catch((err) => {
@@ -280,15 +274,12 @@ export const cohortRouter = createTRPCRouter({
throw new TRPCNotFoundError('Cohort not found');
}
- const access = await getProjectAccess({
- projectId: cohort.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId!,
+ projectId: cohort.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this cohort');
- }
-
if (cohort.isStatic) {
throw new Error(
'Cannot refresh static cohorts — they are one-time snapshots'
diff --git a/packages/trpc/src/routers/conversation.ts b/packages/trpc/src/routers/conversation.ts
index 984d48942..f81056faf 100644
--- a/packages/trpc/src/routers/conversation.ts
+++ b/packages/trpc/src/routers/conversation.ts
@@ -9,7 +9,7 @@ import {
upsertConversationTitle,
} from '@openpanel/db';
-import { getProjectAccess } from '../access';
+import { getProjectAccess, requireProjectAccess } from '../access';
import { TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
@@ -55,6 +55,9 @@ export const conversationRouter = createTRPCRouter({
}),
rename: protectedProcedure
+ // A conversation belongs to the caller, not to the project - titling your
+ // own chat is not a project mutation. Ownership is enforced below.
+ .meta({ readOnlyMutation: true })
.input(
z.object({
id: z.string(),
@@ -82,13 +85,11 @@ export const conversationRouter = createTRPCRouter({
});
}
} else {
- const access = await getProjectAccess({
- projectId: input.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId,
+ projectId: input.projectId,
+ level: 'read',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
}
// Derive organizationId from the project — we never trust a
// client-supplied value here, even if the caller has access to
diff --git a/packages/trpc/src/routers/dashboard.ts b/packages/trpc/src/routers/dashboard.ts
index 259db5587..b8393c43e 100644
--- a/packages/trpc/src/routers/dashboard.ts
+++ b/packages/trpc/src/routers/dashboard.ts
@@ -10,7 +10,7 @@ import {
} from '@openpanel/db';
import type { Prisma } from '@openpanel/db';
-import { getProjectAccess } from '../access';
+import { getProjectAccess, requireProjectAccess } from '../access';
import { TRPCForbiddenError, TRPCNotFoundError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
@@ -57,15 +57,12 @@ export const dashboardRouter = createTRPCRouter({
}),
)
.mutation(async ({ input, ctx }) => {
- const access = await getProjectAccess({
- projectId: input.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId,
+ projectId: input.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
const project = await getProjectById(input.projectId);
if (!project) {
@@ -95,15 +92,12 @@ export const dashboardRouter = createTRPCRouter({
},
});
- const access = await getProjectAccess({
- projectId: dashboard.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId,
+ projectId: dashboard.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this dashboard');
- }
-
return db.dashboard.update({
where: {
id: input.id,
@@ -127,15 +121,12 @@ export const dashboardRouter = createTRPCRouter({
},
});
- const access = await getProjectAccess({
- projectId: dashboard.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId,
+ projectId: dashboard.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this dashboard');
- }
-
try {
if (input.forceDelete) {
await db.report.deleteMany({
diff --git a/packages/trpc/src/routers/gsc.ts b/packages/trpc/src/routers/gsc.ts
index 6bc8df8f3..ba3c182fb 100644
--- a/packages/trpc/src/routers/gsc.ts
+++ b/packages/trpc/src/routers/gsc.ts
@@ -16,7 +16,7 @@ import {
import { gscQueue } from '@openpanel/queue';
import { zRange, zTimeInterval } from '@openpanel/validation';
import { z } from 'zod';
-import { getProjectAccess } from '../access';
+import { getProjectAccess, requireProjectAccess } from '../access';
import { TRPCForbiddenError, TRPCNotFoundError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
@@ -76,13 +76,11 @@ export const gscRouter = createTRPCRouter({
initiateOAuth: protectedProcedure
.input(z.object({ projectId: z.string() }))
.mutation(async ({ input, ctx }) => {
- const access = await getProjectAccess({
- projectId: input.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId,
+ projectId: input.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
const state = Arctic.generateState();
const codeVerifier = Arctic.generateCodeVerifier();
@@ -116,13 +114,11 @@ export const gscRouter = createTRPCRouter({
selectSite: protectedProcedure
.input(z.object({ projectId: z.string(), siteUrl: z.string() }))
.mutation(async ({ input, ctx }) => {
- const access = await getProjectAccess({
- projectId: input.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId,
+ projectId: input.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
const conn = await db.gscConnection.findUnique({
where: { projectId: input.projectId },
@@ -150,13 +146,11 @@ export const gscRouter = createTRPCRouter({
disconnect: protectedProcedure
.input(z.object({ projectId: z.string() }))
.mutation(async ({ input, ctx }) => {
- const access = await getProjectAccess({
- projectId: input.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId,
+ projectId: input.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
await db.gscConnection.deleteMany({
where: { projectId: input.projectId },
diff --git a/packages/trpc/src/routers/import.ts b/packages/trpc/src/routers/import.ts
index 24450a94b..8171fa3b9 100644
--- a/packages/trpc/src/routers/import.ts
+++ b/packages/trpc/src/routers/import.ts
@@ -4,7 +4,7 @@ import { db } from '@openpanel/db';
import { importQueue } from '@openpanel/queue';
import { zCreateImport } from '@openpanel/validation';
-import { getProjectAccess } from '../access';
+import { getProjectAccess, requireProjectAccess } from '../access';
import {
TRPCForbiddenError,
TRPCBadRequestError,
@@ -62,17 +62,12 @@ export const importRouter = createTRPCRouter({
create: protectedProcedure
.input(zCreateImport)
.mutation(async ({ input, ctx }) => {
- const access = await getProjectAccess({
- projectId: input.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId,
+ projectId: input.projectId,
+ level: 'write',
});
- if (!access || (typeof access !== 'boolean' && access.level === 'read')) {
- throw new TRPCForbiddenError(
- 'You do not have permission to create imports for this project',
- );
- }
-
const organization = await db.organization.findFirst({
where: {
projects: {
@@ -133,17 +128,12 @@ export const importRouter = createTRPCRouter({
},
});
- const access = await getProjectAccess({
- projectId: importRecord.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId,
+ projectId: importRecord.projectId,
+ level: 'write',
});
- if (!access || (typeof access !== 'boolean' && access.level === 'read')) {
- throw new TRPCForbiddenError(
- 'You do not have permission to delete imports for this project',
- );
- }
-
if (importRecord.jobId) {
const job = await importQueue.getJob(importRecord.jobId);
if (job) {
@@ -167,17 +157,12 @@ export const importRouter = createTRPCRouter({
},
});
- const access = await getProjectAccess({
- projectId: importRecord.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId,
+ projectId: importRecord.projectId,
+ level: 'write',
});
- if (!access || (typeof access !== 'boolean' && access.level === 'read')) {
- throw new TRPCForbiddenError(
- 'You do not have permission to retry imports for this project',
- );
- }
-
// Only allow retry for failed imports
if (importRecord.status !== 'failed') {
throw new Error('Only failed imports can be retried');
diff --git a/packages/trpc/src/routers/insight.ts b/packages/trpc/src/routers/insight.ts
index d5938f991..6b2856a24 100644
--- a/packages/trpc/src/routers/insight.ts
+++ b/packages/trpc/src/routers/insight.ts
@@ -7,7 +7,7 @@ import {
import { getRedisCache } from '@openpanel/redis';
import type { InsightPayload } from '@openpanel/validation';
import { z } from 'zod';
-import { getProjectAccess } from '../access';
+import { getProjectAccess, requireProjectAccess } from '../access';
import { TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
@@ -148,15 +148,14 @@ export const insightRouter = createTRPCRouter({
},
});
- const access = await getProjectAccess({
+ // Reads an existing insight and explains it. Nothing about the project
+ // changes, so a read-level member may do it.
+ await requireProjectAccess({
userId: ctx.session.userId,
projectId: insight.projectId,
+ level: 'read',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
// Serve a cached explanation if the insight hasn't changed since we
// computed it. Skips both the ClickHouse queries and the LLM call.
const cacheKey = `insight-explain:${insightId}:${insight.lastUpdatedAt.getTime()}`;
diff --git a/packages/trpc/src/routers/notification.ts b/packages/trpc/src/routers/notification.ts
index ec74d2de5..16efac4f3 100644
--- a/packages/trpc/src/routers/notification.ts
+++ b/packages/trpc/src/routers/notification.ts
@@ -10,7 +10,7 @@ import {
} from '@openpanel/db';
import { zCreateNotificationRule } from '@openpanel/validation';
-import { getProjectAccess } from '../access';
+import { requireProjectAccess } from '../access';
import { TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
@@ -87,17 +87,12 @@ export const notificationRouter = createTRPCRouter({
},
});
- const access = await getProjectAccess({
+ await requireProjectAccess({
userId: ctx.session.userId,
projectId: existing.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError(
- 'You do not have access to this project',
- );
- }
-
return db.notificationRule.update({
where: {
id: input.id,
@@ -151,15 +146,12 @@ export const notificationRouter = createTRPCRouter({
},
});
- const access = await getProjectAccess({
+ await requireProjectAccess({
userId: ctx.session.userId,
projectId: rule.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
return db.notificationRule.delete({
where: {
id,
diff --git a/packages/trpc/src/routers/organization.ts b/packages/trpc/src/routers/organization.ts
index e81a0333b..806f3f447 100644
--- a/packages/trpc/src/routers/organization.ts
+++ b/packages/trpc/src/routers/organization.ts
@@ -9,7 +9,11 @@ import {
getOrganizationById,
getOrganizations,
} from '@openpanel/db';
-import { zEditOrganization, zInviteUser } from '@openpanel/validation';
+import {
+ zEditOrganization,
+ zInviteUser,
+ zUpdateMemberAccess,
+} from '@openpanel/validation';
import { generateSecureId } from '@openpanel/common/server';
import { sendEmail } from '@openpanel/email';
@@ -211,7 +215,7 @@ export const organizationRouter = createTRPCRouter({
organizationId: input.organizationId,
role: input.role,
createdById: ctx.session.userId,
- projectAccess: input.access || [],
+ projectAccess: input.access ?? [],
expiresAt: addDays(new Date(), 3),
},
include: {
@@ -324,13 +328,7 @@ export const organizationRouter = createTRPCRouter({
}),
updateMemberAccess: protectedProcedure
- .input(
- z.object({
- userId: z.string(),
- organizationId: z.string(),
- access: z.array(z.string()),
- }),
- )
+ .input(zUpdateMemberAccess)
.mutation(async ({ input, ctx }) => {
if (input.userId === ctx.session.userId) {
throw new TRPCForbiddenError('You cannot update your own access');
@@ -353,11 +351,14 @@ export const organizationRouter = createTRPCRouter({
},
}),
db.projectAccess.createMany({
- data: input.access.map((projectId) => ({
+ // The level comes from the admin's choice. This used to be hardcoded
+ // to 'read', which was harmless only because nothing enforced the
+ // level (GHSA-f9rx-pxgw-c6rg).
+ data: input.access.map((grant) => ({
userId: input.userId,
organizationId: input.organizationId,
- projectId: projectId,
- level: 'read',
+ projectId: grant.projectId,
+ level: grant.level,
})),
}),
]);
diff --git a/packages/trpc/src/routers/overview.ts b/packages/trpc/src/routers/overview.ts
index 350c5fb84..0bb74a47e 100644
--- a/packages/trpc/src/routers/overview.ts
+++ b/packages/trpc/src/routers/overview.ts
@@ -62,12 +62,23 @@ const overviewProcedure = publicProcedure.use(
};
if (rawInput.shareId) {
- await validateOverviewShareAccess(rawInput.shareId, rawInput.projectId, {
- cookies: ctx.cookies,
- session: ctx.session?.userId
- ? { userId: ctx.session.userId }
- : undefined,
- });
+ // validateOverviewShareAccess only throws for missing/non-public shares.
+ // A password-protected share without the unlock cookie comes back as
+ // `{ isValid: false }`, so ignoring the result leaves the data open to
+ // anyone holding the link. The chart path does the same check.
+ const shareValidation = await validateOverviewShareAccess(
+ rawInput.shareId,
+ rawInput.projectId,
+ {
+ cookies: ctx.cookies,
+ session: ctx.session?.userId
+ ? { userId: ctx.session.userId }
+ : undefined,
+ }
+ );
+ if (!shareValidation.isValid) {
+ throw new TRPCForbiddenError('You do not have access to this share');
+ }
} else {
if (!ctx.session?.userId) {
throw new TRPCAccessError('Authentication required');
@@ -502,6 +513,8 @@ export const overviewRouter = createTRPCRouter({
// last year") into structured filter changes the dashboard can apply
// through the same handlers the chat panel uses.
runFilterCommand: protectedProcedure
+ // Computes filter changes for the caller's own UI; changes no project state.
+ .meta({ readOnlyMutation: true })
.input(
z.object({
projectId: z.string(),
diff --git a/packages/trpc/src/routers/project.ts b/packages/trpc/src/routers/project.ts
index 34819c733..e1b6f9e3b 100644
--- a/packages/trpc/src/routers/project.ts
+++ b/packages/trpc/src/routers/project.ts
@@ -14,7 +14,11 @@ import {
import { zOnboardingProject, zProjectUpdate } from '@openpanel/validation';
import { addHours } from 'date-fns';
import { z } from 'zod';
-import { getProjectAccess } from '../access';
+import {
+ getProjectAccess,
+ requireProjectAccess,
+ requireProjectAdmin,
+} from '../access';
import { TRPCForbiddenError, TRPCBadRequestError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
@@ -57,15 +61,12 @@ export const projectRouter = createTRPCRouter({
update: protectedProcedure
.input(zProjectUpdate)
.mutation(async ({ input, ctx }) => {
- const access = await getProjectAccess({
+ await requireProjectAccess({
userId: ctx.session.userId,
projectId: input.id,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
const res = await db.project.update({
where: {
id: input.id,
@@ -164,15 +165,13 @@ export const projectRouter = createTRPCRouter({
})
)
.mutation(async ({ input, ctx }) => {
- const access = await getProjectAccess({
+ // Destroying a project is admin-tier, matching project.create.
+ await requireProjectAdmin({
userId: ctx.session.userId,
projectId: input.projectId,
+ message: 'Only organization admins can delete projects',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
await db.project.update({
where: {
id: input.projectId,
@@ -191,15 +190,12 @@ export const projectRouter = createTRPCRouter({
})
)
.mutation(async ({ input, ctx }) => {
- const access = await getProjectAccess({
+ await requireProjectAdmin({
userId: ctx.session.userId,
projectId: input.projectId,
+ message: 'Only organization admins can cancel a project deletion',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
const project = await db.project.findUnique({
where: {
id: input.projectId,
diff --git a/packages/trpc/src/routers/reference.ts b/packages/trpc/src/routers/reference.ts
index 7a7d121a6..8f208a3cf 100644
--- a/packages/trpc/src/routers/reference.ts
+++ b/packages/trpc/src/routers/reference.ts
@@ -3,7 +3,7 @@ import { z } from 'zod';
import { db, getChartStartEndDate, getSettingsForProject } from '@openpanel/db';
import { zCreateReference, zRange } from '@openpanel/validation';
-import { getProjectAccess } from '../access';
+import { getProjectAccess, requireProjectAccess } from '../access';
import { TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';
@@ -62,15 +62,12 @@ export const referenceRouter = createTRPCRouter({
where: { id: input.id },
});
- const access = await getProjectAccess({
+ await requireProjectAccess({
userId: ctx.session.userId,
projectId: existing.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
return db.reference.update({
where: { id: input.id },
data: {
@@ -89,15 +86,12 @@ export const referenceRouter = createTRPCRouter({
},
});
- const access = await getProjectAccess({
+ await requireProjectAccess({
userId: ctx.session.userId,
projectId: reference.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
return db.reference.delete({
where: {
id,
diff --git a/packages/trpc/src/routers/report.ts b/packages/trpc/src/routers/report.ts
index 789766482..3b89874a5 100644
--- a/packages/trpc/src/routers/report.ts
+++ b/packages/trpc/src/routers/report.ts
@@ -8,7 +8,7 @@ import {
} from '@openpanel/db';
import { zReport } from '@openpanel/validation';
-import { getProjectAccess } from '../access';
+import { getProjectAccess, requireProjectAccess } from '../access';
import {
TRPCBadRequestError,
TRPCForbiddenError,
@@ -45,15 +45,12 @@ export const reportRouter = createTRPCRouter({
},
});
- const access = await getProjectAccess({
+ await requireProjectAccess({
userId: ctx.session.userId,
projectId: dashboard.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
return db.report.create({
data: {
projectId: dashboard.projectId,
@@ -91,15 +88,12 @@ export const reportRouter = createTRPCRouter({
},
});
- const access = await getProjectAccess({
+ await requireProjectAccess({
userId: ctx.session.userId,
projectId: dbReport.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
return db.report.update({
where: {
id: reportId,
@@ -138,15 +132,12 @@ export const reportRouter = createTRPCRouter({
},
});
- const access = await getProjectAccess({
+ await requireProjectAccess({
userId: ctx.session.userId,
projectId: report.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
if (report.dashboardId === dashboardId) {
throw new TRPCBadRequestError('Report is already on this dashboard');
}
@@ -200,15 +191,12 @@ export const reportRouter = createTRPCRouter({
},
});
- const access = await getProjectAccess({
+ await requireProjectAccess({
userId: ctx.session.userId,
projectId: report.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
return db.report.delete({
where: {
id: reportId,
@@ -228,15 +216,12 @@ export const reportRouter = createTRPCRouter({
},
});
- const access = await getProjectAccess({
+ await requireProjectAccess({
userId: ctx.session.userId,
projectId: report.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
return db.report.create({
data: {
projectId: report.projectId,
@@ -303,15 +288,12 @@ export const reportRouter = createTRPCRouter({
},
});
- const access = await getProjectAccess({
+ await requireProjectAccess({
userId: ctx.session.userId,
projectId: report.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
// Upsert the layout (create if doesn't exist, update if it does)
return db.reportLayout.upsert({
where: {
@@ -385,15 +367,12 @@ export const reportRouter = createTRPCRouter({
}),
)
.mutation(async ({ input: { dashboardId, projectId }, ctx }) => {
- const access = await getProjectAccess({
+ await requireProjectAccess({
userId: ctx.session.userId,
projectId: projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
// Same as `getLayouts`: bind the dashboard to the access-checked project
// before deleting anything, so a foreign dashboard cannot be wiped.
const dashboard = await getDashboardById(dashboardId, projectId);
diff --git a/packages/trpc/src/routers/share.test.ts b/packages/trpc/src/routers/share.test.ts
new file mode 100644
index 000000000..1f22ecff3
--- /dev/null
+++ b/packages/trpc/src/routers/share.test.ts
@@ -0,0 +1,153 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// vi.mock is hoisted above the module scope, so the spies have to be too.
+const {
+ shareReportFindUnique,
+ shareDashboardFindUnique,
+ shareOverviewFindUnique,
+} = vi.hoisted(() => ({
+ shareReportFindUnique: vi.fn(),
+ shareDashboardFindUnique: vi.fn(),
+ shareOverviewFindUnique: vi.fn(),
+}));
+
+vi.mock('@openpanel/db', () => ({
+ db: {
+ shareReport: { findUnique: shareReportFindUnique },
+ shareDashboard: { findUnique: shareDashboardFindUnique },
+ shareOverview: { findUnique: shareOverviewFindUnique },
+ },
+ transformReport: (report: unknown) => report,
+ getDashboardById: vi.fn(),
+ getReportById: vi.fn(),
+ getReportsByDashboardId: vi.fn(),
+ getShareDashboardById: vi.fn(),
+ getProjectById: vi.fn(),
+ getProjectAccess: vi.fn(),
+ getOrganizationAccess: vi.fn(),
+ getClientAccess: vi.fn(),
+ canWriteProject: vi.fn(),
+ runWithAlsSession: (_id: unknown, fn: () => unknown) => fn(),
+}));
+
+import { shareRouter } from './share';
+
+const PASSWORD_HASH =
+ '$argon2id$v=19$m=19456,t=2,p=1$NTb6p8dXsP2b1WpDU22i/w$ILi3tmTMYg5TSrjvVktAbixLHPH5PjvvbQypR9bZuoQ';
+
+const REPORT = {
+ id: 'report-uuid',
+ name: 'Q4 Revenue — CONFIDENTIAL',
+ events: [{ name: 'checkout_completed_SECRET_EVENT' }],
+ breakdowns: [{ name: 'CONFIDENTIAL_breakdown' }],
+};
+
+/** An unauthenticated caller: no session, no unlock cookie. */
+const anonCaller = (cookies: Record<string, string> = {}) =>
+ shareRouter.createCaller({
+ req: { log: { info: vi.fn(), error: vi.fn() } },
+ res: {},
+ session: null,
+ setCookie: vi.fn(),
+ cookies,
+ } as never);
+
+const privatePasswordProtectedShare = {
+ id: 'SECRT1',
+ public: false,
+ password: PASSWORD_HASH,
+ projectId: 'victim-project',
+ organization: { name: 'VictimOrg' },
+ project: { name: 'Victim Project' },
+ report: REPORT,
+ dashboard: { name: 'Confidential Dashboard' },
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+/**
+ * GHSA-7gv7-c464-9wh8: these three procedures spread the whole share row into
+ * the response, so an unauthenticated caller holding a share link received the
+ * argon2 password hash - and, for reports, the full report definition - while
+ * the same response said they had no access.
+ */
+describe('share lookups do not leak the password hash', () => {
+ it('refuses a non-public report share outright', async () => {
+ shareReportFindUnique.mockResolvedValue(privatePasswordProtectedShare);
+
+ await expect(
+ anonCaller().report({ shareId: 'SECRT1' }),
+ ).rejects.toThrow('Report share not found');
+ });
+
+ it('refuses a non-public dashboard share outright', async () => {
+ shareDashboardFindUnique.mockResolvedValue(privatePasswordProtectedShare);
+
+ await expect(
+ anonCaller().dashboard({ shareId: 'SECRT1' }),
+ ).rejects.toThrow('Dashboard share not found');
+ });
+
+ it('refuses a non-public overview share outright', async () => {
+ shareOverviewFindUnique.mockResolvedValue(privatePasswordProtectedShare);
+
+ await expect(
+ anonCaller().overview({ shareId: 'SECRT1' }),
+ ).rejects.toThrow('Share not found');
+ });
+
+ it('withholds the hash and the report from a locked public share', async () => {
+ shareReportFindUnique.mockResolvedValue({
+ ...privatePasswordProtectedShare,
+ public: true,
+ });
+
+ const res = await anonCaller().report({ shareId: 'SECRT1' });
+
+ expect(res.requiresPassword).toBe(true);
+ expect(JSON.stringify(res)).not.toContain('$argon2id');
+ expect(JSON.stringify(res)).not.toContain('CONFIDENTIAL');
+ expect(res).not.toHaveProperty('password');
+ expect(res).not.toHaveProperty('report');
+ expect(res).not.toHaveProperty('projectId');
+ });
+
+ it('withholds projectId from a locked overview share', async () => {
+ shareOverviewFindUnique.mockResolvedValue({
+ ...privatePasswordProtectedShare,
+ public: true,
+ });
+
+ const res = await anonCaller().overview({ shareId: 'SECRT1' });
+
+ expect(res.requiresPassword).toBe(true);
+ expect(res).not.toHaveProperty('projectId');
+ expect(JSON.stringify(res)).not.toContain('$argon2id');
+ });
+
+ it('serves the report once unlocked, still without the hash', async () => {
+ shareReportFindUnique.mockResolvedValue({
+ ...privatePasswordProtectedShare,
+ public: true,
+ });
+
+ const res = await anonCaller({
+ 'shared-report-SECRT1': '1',
+ }).report({ shareId: 'SECRT1' });
+
+ expect(res.requiresPassword).toBe(false);
+ expect(res).toHaveProperty('report');
+ expect(JSON.stringify(res)).not.toContain('$argon2id');
+ });
+
+ it('never selects the row by reportId, so object ids are not addressable', async () => {
+ // The union input used to accept { reportId }, which let anyone knowing a
+ // report id read the share row without ever seeing a share link.
+ await expect(
+ // @ts-expect-error - deliberately calling the removed input shape
+ anonCaller().report({ reportId: 'report-uuid' }),
+ ).rejects.toThrow();
+ });
+});
diff --git a/packages/trpc/src/routers/share.ts b/packages/trpc/src/routers/share.ts
index 0e595111d..df122efe3 100644
--- a/packages/trpc/src/routers/share.ts
+++ b/packages/trpc/src/routers/share.ts
@@ -6,7 +6,6 @@ import {
getReportById,
getReportsByDashboardId,
getShareDashboardById,
- getShareReportById,
transformReport,
} from '@openpanel/db';
import {
@@ -17,7 +16,7 @@ import {
import { hashPassword } from '@openpanel/auth';
import { z } from 'zod';
-import { getProjectAccess } from '../access';
+import { requireProjectAccess } from '../access';
import {
TRPCAccessError,
TRPCForbiddenError,
@@ -27,57 +26,88 @@ import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';
const uid = new ShortUniqueId({ length: 6 });
+/**
+ * Share lookups are split in two on purpose.
+ *
+ * The `overview`/`dashboard`/`report` procedures are unauthenticated and serve
+ * the public viewer, addressed only by `shareId` (the value in the share link).
+ * They project an explicit allow-list of columns and refuse to hand back any
+ * shared content until the `public` flag and the password cookie have both been
+ * checked. Returning the row and letting the client decide is what leaked the
+ * argon2 password hash and private report definitions (GHSA-7gv7-c464-9wh8).
+ *
+ * The `*Settings` procedures are authenticated and serve the owner's share
+ * modal, addressed by the underlying object id. They never return the hash
+ * either - only whether one is set.
+ */
+
+/** Shape returned to a viewer who has not unlocked a password-protected share. */
+function lockedShare(
+ id: string,
+ organization: { name: string },
+ project: { name: string },
+) {
+ return {
+ id,
+ requiresPassword: true as const,
+ organization,
+ project,
+ };
+}
+
export const shareRouter = createTRPCRouter({
overview: publicProcedure
- .input(
- z
- .object({
- projectId: z.string(),
- })
- .or(
- z.object({
- shareId: z.string(),
- }),
- ),
- )
+ .input(z.object({ shareId: z.string() }))
.query(async ({ input, ctx }) => {
const share = await db.shareOverview.findUnique({
- include: {
- organization: {
- select: {
- name: true,
- },
- },
- project: {
- select: {
- name: true,
- },
- },
+ where: { id: input.shareId },
+ select: {
+ id: true,
+ public: true,
+ password: true,
+ projectId: true,
+ organization: { select: { name: true } },
+ project: { select: { name: true } },
},
- where:
- 'projectId' in input
- ? {
- projectId: input.projectId,
- }
- : {
- id: input.shareId,
- },
});
- if (!share) {
- // Throw error if shareId is provided, otherwise return null
- if ('shareId' in input) {
- throw new TRPCNotFoundError('Share not found');
- }
+ if (!share || !share.public) {
+ throw new TRPCNotFoundError('Share not found');
+ }
+
+ const hasAccess = !!ctx.cookies[`shared-overview-${share.id}`];
+ if (share.password && !hasAccess) {
+ return lockedShare(share.id, share.organization, share.project);
+ }
+
+ return {
+ id: share.id,
+ requiresPassword: false as const,
+ organization: share.organization,
+ project: share.project,
+ projectId: share.projectId,
+ };
+ }),
+ overviewSettings: protectedProcedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ input }) => {
+ const share = await db.shareOverview.findUnique({
+ where: { projectId: input.projectId },
+ select: { id: true, public: true, password: true },
+ });
+
+ if (!share) {
return null;
}
return {
- ...share,
- hasAccess: !!ctx.cookies[`shared-overview-${share?.id}`],
+ id: share.id,
+ public: share.public,
+ hasPassword: !!share.password,
};
}),
+
createOverview: protectedProcedure
.input(zShareOverview)
.mutation(async ({ input }) => {
@@ -85,7 +115,7 @@ export const shareRouter = createTRPCRouter({
? await hashPassword(input.password)
: null;
- return db.shareOverview.upsert({
+ const share = await db.shareOverview.upsert({
where: {
projectId: input.projectId,
},
@@ -100,76 +130,78 @@ export const shareRouter = createTRPCRouter({
public: input.public,
password: passwordHash,
},
+ select: { id: true, public: true, password: true },
});
+
+ return {
+ id: share.id,
+ public: share.public,
+ hasPassword: !!share.password,
+ };
}),
// Dashboard sharing
dashboard: publicProcedure
- .input(
- z
- .object({
- dashboardId: z.string(),
- })
- .or(
- z.object({
- shareId: z.string(),
- }),
- ),
- )
+ .input(z.object({ shareId: z.string() }))
.query(async ({ input, ctx }) => {
const share = await db.shareDashboard.findUnique({
- include: {
- organization: {
- select: {
- name: true,
- },
- },
- project: {
- select: {
- name: true,
- },
- },
- dashboard: {
- select: {
- name: true,
- },
- },
+ where: { id: input.shareId },
+ select: {
+ id: true,
+ public: true,
+ password: true,
+ organization: { select: { name: true } },
+ project: { select: { name: true } },
+ dashboard: { select: { name: true } },
},
- where:
- 'dashboardId' in input
- ? {
- dashboardId: input.dashboardId,
- }
- : {
- id: input.shareId,
- },
});
- if (!share) {
- if ('shareId' in input) {
- throw new TRPCNotFoundError('Dashboard share not found');
- }
+ if (!share || !share.public) {
+ throw new TRPCNotFoundError('Dashboard share not found');
+ }
+
+ const hasAccess = !!ctx.cookies[`shared-dashboard-${share.id}`];
+ if (share.password && !hasAccess) {
+ return lockedShare(share.id, share.organization, share.project);
+ }
+
+ return {
+ id: share.id,
+ requiresPassword: false as const,
+ organization: share.organization,
+ project: share.project,
+ dashboard: share.dashboard,
+ };
+ }),
+
+ dashboardSettings: protectedProcedure
+ .input(z.object({ projectId: z.string(), dashboardId: z.string() }))
+ .query(async ({ input }) => {
+ const share = await db.shareDashboard.findUnique({
+ where: { dashboardId: input.dashboardId },
+ select: { id: true, public: true, password: true, projectId: true },
+ });
+
+ if (!share || share.projectId !== input.projectId) {
return null;
}
return {
- ...share,
- hasAccess: !!ctx.cookies[`shared-dashboard-${share?.id}`],
+ id: share.id,
+ public: share.public,
+ hasPassword: !!share.password,
};
}),
createDashboard: protectedProcedure
.input(zShareDashboard)
.mutation(async ({ input, ctx }) => {
- const access = await getProjectAccess({
- projectId: input.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId,
+ projectId: input.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
const dashboard = await getDashboardById(
input.dashboardId,
input.projectId,
@@ -182,7 +214,7 @@ export const shareRouter = createTRPCRouter({
? await hashPassword(input.password)
: null;
- return db.shareDashboard.upsert({
+ const share = await db.shareDashboard.upsert({
where: {
dashboardId: input.dashboardId,
},
@@ -198,7 +230,14 @@ export const shareRouter = createTRPCRouter({
public: input.public,
password: passwordHash,
},
+ select: { id: true, public: true, password: true },
});
+
+ return {
+ id: share.id,
+ public: share.public,
+ hasPassword: !!share.password,
+ };
}),
dashboardReports: publicProcedure
@@ -225,68 +264,68 @@ export const shareRouter = createTRPCRouter({
// Report sharing
report: publicProcedure
- .input(
- z
- .object({
- reportId: z.string(),
- })
- .or(
- z.object({
- shareId: z.string(),
- }),
- ),
- )
+ .input(z.object({ shareId: z.string() }))
.query(async ({ input, ctx }) => {
const share = await db.shareReport.findUnique({
- include: {
- organization: {
- select: {
- name: true,
- },
- },
- project: {
- select: {
- name: true,
- },
- },
+ where: { id: input.shareId },
+ select: {
+ id: true,
+ public: true,
+ password: true,
+ projectId: true,
+ organization: { select: { name: true } },
+ project: { select: { name: true } },
report: true,
},
- where:
- 'reportId' in input
- ? {
- reportId: input.reportId,
- }
- : {
- id: input.shareId,
- },
});
- if (!share) {
- if ('shareId' in input) {
- throw new TRPCNotFoundError('Report share not found');
- }
- return null;
+ if (!share || !share.public) {
+ throw new TRPCNotFoundError('Report share not found');
+ }
+
+ const hasAccess = !!ctx.cookies[`shared-report-${share.id}`];
+ if (share.password && !hasAccess) {
+ return lockedShare(share.id, share.organization, share.project);
}
return {
- ...share,
- hasAccess: !!ctx.cookies[`shared-report-${share?.id}`],
+ id: share.id,
+ requiresPassword: false as const,
+ organization: share.organization,
+ project: share.project,
+ projectId: share.projectId,
report: transformReport(share.report),
};
}),
+ reportSettings: protectedProcedure
+ .input(z.object({ projectId: z.string(), reportId: z.string() }))
+ .query(async ({ input }) => {
+ const share = await db.shareReport.findUnique({
+ where: { reportId: input.reportId },
+ select: { id: true, public: true, password: true, projectId: true },
+ });
+
+ if (!share || share.projectId !== input.projectId) {
+ return null;
+ }
+
+ return {
+ id: share.id,
+ public: share.public,
+ hasPassword: !!share.password,
+ };
+ }),
+
createReport: protectedProcedure
.input(zShareReport)
.mutation(async ({ input, ctx }) => {
- const access = await getProjectAccess({
- projectId: input.projectId,
+ await requireProjectAccess({
userId: ctx.session.userId,
+ projectId: input.projectId,
+ level: 'write',
});
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
-
const report = await getReportById(input.reportId);
if (!report || report.projectId !== input.projectId) {
throw new TRPCNotFoundError('Report not found');
@@ -296,7 +335,7 @@ export const shareRouter = createTRPCRouter({
? await hashPassword(input.password)
: null;
- return db.shareReport.upsert({
+ const share = await db.shareReport.upsert({
where: {
reportId: input.reportId,
},
@@ -312,6 +351,13 @@ export const shareRouter = createTRPCRouter({
public: input.public,
password: passwordHash,
},
+ select: { id: true, public: true, password: true },
});
+
+ return {
+ id: share.id,
+ public: share.public,
+ hasPassword: !!share.password,
+ };
}),
});
diff --git a/packages/trpc/src/trpc.ts b/packages/trpc/src/trpc.ts
index b32340e6c..23cd0cc79 100644
--- a/packages/trpc/src/trpc.ts
+++ b/packages/trpc/src/trpc.ts
@@ -12,7 +12,7 @@ import {
createTrpcRedisLimiter,
defaultFingerPrint,
} from '@trpc-limiter/redis';
-import { getOrganizationAccess, getProjectAccess } from './access';
+import { getOrganizationAccess, requireProjectAccess } from './access';
import { TRPCForbiddenError } from './errors';
export const rateLimitMiddleware = ({
@@ -60,7 +60,19 @@ export async function createContext({ req, res }: CreateFastifyContextOptions) {
}
export type Context = Awaited<ReturnType<typeof createContext>>;
-const t = initTRPC.context<Context>().create({
+/**
+ * Per-procedure metadata consulted by `enforceAccess`.
+ *
+ * A tRPC mutation is not always a mutation of project *state* - the AI helpers
+ * are one-shot compute that happen to be modelled as mutations. Those may run
+ * at read level. The default is write, so forgetting to set this fails closed.
+ */
+export interface Meta {
+ /** This mutation does not change project state; read access is enough. */
+ readOnlyMutation?: boolean;
+}
+
+const t = initTRPC.context<Context>().meta<Meta>().create({
transformer: superjson,
errorFormatter({ shape, error }) {
return {
@@ -95,7 +107,7 @@ const enforceUserIsAuthed = t.middleware(async ({ ctx, next }) => {
});
// Only used on protected routes
-const enforceAccess = t.middleware(async ({ ctx, next, type, getRawInput }) => {
+const enforceAccess = t.middleware(async ({ ctx, next, type, meta, getRawInput }) => {
const sessionId = ctx.session?.session?.id ?? null;
return runWithAlsSession(sessionId, async () => {
const rawInput = await getRawInput();
@@ -104,14 +116,17 @@ const enforceAccess = t.middleware(async ({ ctx, next, type, getRawInput }) => {
}
if (has('projectId', rawInput)) {
- const access = await getProjectAccess({
+ // Fails closed: any procedure that takes a top-level projectId requires
+ // write access to mutate, including ones added later. Procedures that
+ // resolve the project from a reportId/dashboardId/etc. are invisible to
+ // this check and call requireProjectAccess in the handler instead.
+ const needsWrite = type === 'mutation' && !meta?.readOnlyMutation;
+
+ await requireProjectAccess({
userId: ctx.session.userId!,
projectId: rawInput.projectId as string,
+ level: needsWrite ? 'write' : 'read',
});
-
- if (!access) {
- throw new TRPCForbiddenError('You do not have access to this project');
- }
}
if (has('organizationId', rawInput)) {
diff --git a/packages/validation/src/index.ts b/packages/validation/src/index.ts
index 03f85682b..4516b4ce9 100644
--- a/packages/validation/src/index.ts
+++ b/packages/validation/src/index.ts
@@ -322,11 +322,29 @@ export const zReport = zReportInput.extend({
// Alias for backward compatibility
export const zChartInput = zReportInput;
+/**
+ * A per-project grant. `read` means exactly that: the member can look at the
+ * project but no mutation will be accepted for it. `admin` is not offered here
+ * - destructive operations hang off the organization role instead, so a third
+ * project level would be a second way to say `write`.
+ */
+export const zProjectAccessGrant = z.object({
+ projectId: z.string(),
+ level: z.enum(['read', 'write']),
+});
+export type IProjectAccessGrant = z.infer<typeof zProjectAccessGrant>;
+
export const zInviteUser = z.object({
email: z.string().email(),
organizationId: z.string(),
role: z.enum(['org:admin', 'org:member']),
- access: z.array(z.string()),
+ access: z.array(zProjectAccessGrant),
+});
+
+export const zUpdateMemberAccess = z.object({
+ userId: z.string(),
+ organizationId: z.string(),
+ access: z.array(zProjectAccessGrant),
});
export const zShareOverview = z.object({
@@ -671,11 +689,33 @@ const zProjectMapper = z.object({
to: z.string().min(1),
});
+/**
+ * `z.string().url()` alone accepts `file:`, `gopher:` and friends. Restricting
+ * the scheme here gives the user an immediate form error instead of a job that
+ * fails later. It is NOT the SSRF control - the value is stored and fetched
+ * afterwards, so the destination is re-validated at fetch time by
+ * `safeFetchStream`.
+ */
+export const zHttpUrl = z
+ .string()
+ .url()
+ .refine(
+ (value) => {
+ try {
+ const { protocol } = new URL(value);
+ return protocol === 'http:' || protocol === 'https:';
+ } catch {
+ return false;
+ }
+ },
+ { message: 'Only http and https URLs are allowed' },
+ );
+
const createFileImportConfig = <T extends string>(provider: T) =>
z.object({
provider: z.literal(provider),
type: z.literal('file'),
- fileUrl: z.string().url(),
+ fileUrl: zHttpUrl,
});
// Import configs
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6fa0eb71c..70ababd8f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -223,9 +223,6 @@ importers:
groupmq:
specifier: 'catalog:'
version: 2.0.0-next.6([email protected])
- ipaddr.js:
- specifier: ^2.5.0
- version: 2.5.0
jsonwebtoken:
specifier: ^9.0.2
version: 9.0.2
@@ -253,9 +250,6 @@ importers:
svix:
specifier: ^1.24.0
version: 1.24.0
- undici:
- specifier: ^8.10.0
- version: 8.10.0
url-metadata:
specifier: ^5.4.1
version: 5.4.1
@@ -1178,6 +1172,9 @@ importers:
date-fns:
specifier: ^3.3.1
version: 3.3.1
+ ipaddr.js:
+ specifier: ^2.5.0
+ version: 2.5.0
lru-cache:
specifier: ^11.2.4
version: 11.2.4
@@ -1202,6 +1199,9 @@ importers:
ua-parser-js:
specifier: ^2.0.6
version: 2.0.6
+ undici:
+ specifier: ^8.10.0
+ version: 8.10.0
unique-names-generator:
specifier: ^4.7.1
version: 4.7.1
@@ -1462,6 +1462,9 @@ importers:
packages/integrations:
dependencies:
+ '@openpanel/common':
+ specifier: workspace:*
+ version: link:../common
'@slack/bolt':
specifier: ^3.18.0
version: 3.21.4