Skip to content

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

share: HMAC the share-access cookie

Carl-Gerhard Lindesvärd35de695a0ddf
diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.ts
index a4cd9280c..4a52f0ed8 100644
--- a/apps/api/src/config/env.ts
+++ b/apps/api/src/config/env.ts
@@ -850,6 +850,7 @@ function deriveCoreConfig(raw: RawEnv): CoreConfig {
googleGsc: { ...googleClient, redirectUri: raw.GSC_GOOGLE_REDIRECT_URI },
},
cookies: {
+ secret: raw.COOKIE_SECRET,
extraMultiPartTlds: raw.COOKIE_TLDS.map((tld) => tld.toLowerCase()),
customDomain: raw.CUSTOM_COOKIE_DOMAIN,
},
diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts
index b104d0178..a4a92e028 100644
--- a/packages/core/src/config.ts
+++ b/packages/core/src/config.ts
@@ -48,6 +48,8 @@ export interface AuthConfig {
}
export interface CookieConfig {
+ /** COOKIE_SECRET: keys the share-access HMAC. Empty means shares stay locked. */
+ secret: string;
/** COOKIE_TLDS: extra multi-part public suffixes, lowercased. */
extraMultiPartTlds: string[];
/** CUSTOM_COOKIE_DOMAIN: overrides the domain derived from the dashboard. */
diff --git a/packages/core/src/modules/auth/auth.rpc.ts b/packages/core/src/modules/auth/auth.rpc.ts
index 00862661c..225919296 100644
--- a/packages/core/src/modules/auth/auth.rpc.ts
+++ b/packages/core/src/modules/auth/auth.rpc.ts
@@ -131,6 +131,6 @@ export const authRouter = createTRPCRouter({
signInShare: publicProcedure
.input(zSignInShare)
.mutation(({ input, ctx }) =>
- signInToShare(() => ctx.services, input, ctx.setCookie)
+ signInToShare(ctx, () => ctx.services, input, ctx.setCookie)
),
});
diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.ts
index a59f80616..d98e57e0a 100644
--- a/packages/core/src/modules/auth/auth.service.ts
+++ b/packages/core/src/modules/auth/auth.service.ts
@@ -303,6 +303,10 @@ import {
TRPCForbiddenError,
TRPCNotFoundError,
} from '../../rpc/errors';
+import {
+ createShareAccessToken,
+ shareAccessCookieName,
+} from '../../shared/share-access';
import { connectUserToOrganization } from '../organization/organization.service';
import { getUserAccount } from '../user/user.service';
import {
@@ -875,7 +879,11 @@ export interface SignInShareInput {
/** Share's three lookups arrive through the composition root's thunk
* (ADR-022 R3), not a dynamic import: `share.service.ts` statically imports
* this file's `hashPassword`, so a static edge back would be a real cycle. */
+/** A week, as V1's `maxAge` was. */
+const SHARE_ACCESS_MAX_AGE_SECONDS = 60 * 60 * 24 * 7;
+
export async function signInToShare(
+ deps: ServiceDeps,
services: () => Services,
input: SignInShareInput,
setCookie: ISetCookie
@@ -885,17 +893,13 @@ export async function signInToShare(
services().share;
let share: { password: string | null; public: boolean } | null = null;
- let cookieName = '';
if (shareType === 'overview') {
share = await getShareOverviewById(shareId);
- cookieName = `shared-overview-${shareId}`;
} else if (shareType === 'dashboard') {
share = await getShareDashboardById(shareId);
- cookieName = `shared-dashboard-${shareId}`;
} else if (shareType === 'report') {
share = await getShareReportById(shareId);
- cookieName = `shared-report-${shareId}`;
}
if (!share) {
@@ -914,7 +918,17 @@ export async function signInToShare(
throw new TRPCForbiddenError('Incorrect password');
}
- setCookie(cookieName, '1', { maxAge: 60 * 60 * 24 * 7 });
+ // The value is the proof, not the presence: a constant let anyone unlock a
+ // password-protected share by inventing the cookie (GHSA-p6c2-mq9r-cx3r).
+ setCookie(
+ shareAccessCookieName(shareType, shareId),
+ createShareAccessToken(deps.config.cookies.secret, {
+ type: shareType,
+ id: shareId,
+ passwordHash: share.password,
+ }),
+ { maxAge: SHARE_ACCESS_MAX_AGE_SECONDS }
+ );
return true;
}
diff --git a/packages/core/src/modules/auth/src/cookie-domain.test.ts b/packages/core/src/modules/auth/src/cookie-domain.test.ts
index 2e95a2e3d..dd1f6fa91 100644
--- a/packages/core/src/modules/auth/src/cookie-domain.test.ts
+++ b/packages/core/src/modules/auth/src/cookie-domain.test.ts
@@ -9,7 +9,7 @@ const parse = (url: string) => parseCookieDomain(testCoreConfig(), url);
const parseWithTlds = (extraMultiPartTlds: string[], url: string) =>
parseCookieDomain(
testCoreConfig({
- cookies: { extraMultiPartTlds, customDomain: undefined },
+ cookies: { secret: 'test', extraMultiPartTlds, customDomain: undefined },
}),
url
);
@@ -477,6 +477,7 @@ describe('parseCookieDomain', () => {
parseCookieDomain(
testCoreConfig({
cookies: {
+ secret: 'test',
extraMultiPartTlds: [],
customDomain: '.openpanel.dev',
},
diff --git a/packages/core/src/modules/share/share.service.test.ts b/packages/core/src/modules/share/share.service.test.ts
index 25e815edb..389c56978 100644
--- a/packages/core/src/modules/share/share.service.test.ts
+++ b/packages/core/src/modules/share/share.service.test.ts
@@ -5,7 +5,9 @@
// `afterAll` restores the real module instead of re-applying the mock.
import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';
+import { testCoreConfig } from '../../../test/config-fixture';
import { testServices } from '../../../test/service-deps';
+import { createShareAccessToken } from '../../shared/share-access';
interface FakeShare {
id: string;
@@ -224,6 +226,7 @@ beforeAll(async () => {
subject = createShareService(
{
db: { shareOverview, shareDashboard, shareReport },
+ config: testCoreConfig(),
} as unknown as import('../../services').ServiceDeps,
testServices()
);
@@ -244,6 +247,20 @@ function cookies(values: Record<string, string> = {}) {
return { get: (name: string) => values[name] };
}
+/** The cookie a viewer gets from `signInToShare` — an HMAC, not a constant. */
+function unlocked(
+ type: 'overview' | 'dashboard' | 'report',
+ id: string,
+ passwordHash: string
+) {
+ return cookies({
+ [`shared-${type}-${id}`]: createShareAccessToken(
+ testCoreConfig().cookies.secret,
+ { type, id, passwordHash }
+ ),
+ });
+}
+
test('getShareOverview throws NOT_FOUND when the share is missing or not public', async () => {
await expect(
subject.getShareOverview('missing', cookies())
@@ -261,6 +278,45 @@ test('getShareOverview throws NOT_FOUND when the share is missing or not public'
).rejects.toMatchObject({ code: 'NOT_FOUND' });
});
+test('getShareOverview stays locked for a forged cookie (GHSA-p6c2-mq9r-cx3r)', async () => {
+ overviewStore.set('share_1', {
+ id: 'share_1',
+ organizationId: 'org_1',
+ projectId: 'proj_1',
+ public: true,
+ password: 'hashed',
+ });
+
+ const result = await subject.getShareOverview(
+ 'share_1',
+ cookies({ 'shared-overview-share_1': '1' })
+ );
+
+ expect(result).toMatchObject({ requiresPassword: true });
+});
+
+test('getShareOverview stays locked for a token minted for another share', async () => {
+ overviewStore.set('share_1', {
+ id: 'share_1',
+ organizationId: 'org_1',
+ projectId: 'proj_1',
+ public: true,
+ password: 'hashed',
+ });
+ const stolen = createShareAccessToken(testCoreConfig().cookies.secret, {
+ type: 'overview',
+ id: 'share_2',
+ passwordHash: 'hashed',
+ });
+
+ const result = await subject.getShareOverview(
+ 'share_1',
+ cookies({ 'shared-overview-share_1': stolen })
+ );
+
+ expect(result).toMatchObject({ requiresPassword: true });
+});
+
test('getShareOverview returns a locked shape when password-protected without the unlock cookie', async () => {
overviewStore.set('share_1', {
id: 'share_1',
@@ -292,7 +348,7 @@ test('getShareOverview unlocks with the shared-overview cookie', async () => {
const result = await subject.getShareOverview(
'share_1',
- cookies({ 'shared-overview-share_1': '1' })
+ unlocked('overview', 'share_1', 'hashed')
);
expect(result).toMatchObject({ id: 'share_1', requiresPassword: false });
});
diff --git a/packages/core/src/modules/share/share.service.ts b/packages/core/src/modules/share/share.service.ts
index b65fc73e7..b66e7988c 100644
--- a/packages/core/src/modules/share/share.service.ts
+++ b/packages/core/src/modules/share/share.service.ts
@@ -16,6 +16,7 @@ import ShortUniqueId from 'short-unique-id';
import { TRPCForbiddenError, TRPCNotFoundError } from '../../rpc/errors';
import type { ServiceDeps, Services } from '../../services';
import { getProjectAccess } from '../../shared/access-lookups';
+import { hasShareAccess, type ShareType } from '../../shared/share-access';
import { hashPassword } from '../auth/auth.service';
import { getDashboardById } from '../dashboard/dashboard.service';
import {
@@ -171,7 +172,11 @@ export async function validateShareAccess(
return { projectId, isValid: true };
}
- const hasCookie = !!ctx.cookies.get(`shared-dashboard-${shareId}`);
+ const hasCookie = hasShareAccess(deps.config.cookies.secret, ctx.cookies, {
+ type: 'dashboard',
+ id: shareId,
+ passwordHash: dashboardShare.password,
+ });
const hasMemberAccess =
ctx.session?.userId &&
(await getProjectAccess({ userId: ctx.session.userId, projectId }));
@@ -195,7 +200,11 @@ export async function validateShareAccess(
return { projectId, isValid: true };
}
- const hasCookie = !!ctx.cookies.get(`shared-report-${shareId}`);
+ const hasCookie = hasShareAccess(deps.config.cookies.secret, ctx.cookies, {
+ type: 'report',
+ id: shareId,
+ passwordHash: reportShare.password,
+ });
const hasMemberAccess =
ctx.session?.userId &&
(await getProjectAccess({ userId: ctx.session.userId, projectId }));
@@ -234,7 +243,11 @@ export async function validateOverviewShareAccess(
return { isValid: true };
}
- const hasCookie = !!ctx.cookies.get(`shared-overview-${shareId}`);
+ const hasCookie = hasShareAccess(deps.config.cookies.secret, ctx.cookies, {
+ type: 'overview',
+ id: shareId,
+ passwordHash: share.password,
+ });
const hasMemberAccess =
ctx.session?.userId &&
(await getProjectAccess({ userId: ctx.session.userId, projectId }));
@@ -271,6 +284,60 @@ export async function validateOverviewShareAccess(
// The `*Settings`/`create*` functions are for the owner's share modal and
// never return the password hash either — only whether one is set.
+/** The share rows these readers hold: an id and the stored password hash. */
+function isUnlocked(
+ deps: ServiceDeps,
+ cookies: CookieReader,
+ type: ShareType,
+ share: { id: string; password: string | null }
+): boolean {
+ if (!share.password) {
+ return true;
+ }
+ return hasShareAccess(deps.config.cookies.secret, cookies, {
+ type,
+ id: share.id,
+ passwordHash: share.password,
+ });
+}
+
+/**
+ * Whether an anonymous viewer may read project-scoped side data — chart
+ * annotations today — for a project.
+ *
+ * Allowed only when the project has a share of one of `kinds` that is public
+ * and, if password-protected, unlocked with a verified cookie. A share row
+ * merely existing is not enough: a share is switched off by setting
+ * `public: false` and the row stays, and a password share must not leak
+ * through a side endpoint the share page itself would refuse.
+ */
+export async function hasAnonymousShareAccessToProject(
+ deps: ServiceDeps,
+ projectId: string,
+ cookies: CookieReader,
+ kinds: ShareType[] = ['overview', 'dashboard', 'report']
+): Promise<boolean> {
+ const db = deps.db;
+ const select = { id: true, password: true } as const;
+ const where = { projectId, public: true } as const;
+
+ const [overviews, dashboards, reports] = await Promise.all([
+ kinds.includes('overview')
+ ? db.shareOverview.findMany({ where, select })
+ : [],
+ kinds.includes('dashboard')
+ ? db.shareDashboard.findMany({ where, select })
+ : [],
+ kinds.includes('report') ? db.shareReport.findMany({ where, select }) : [],
+ ]);
+
+ return (
+ overviews.some((share) => isUnlocked(deps, cookies, 'overview', share)) ||
+ dashboards.some((share) => isUnlocked(deps, cookies, 'dashboard', share)) ||
+ reports.some((share) => isUnlocked(deps, cookies, 'report', share))
+ );
+}
+
/** Shape returned to a viewer who has not unlocked a password-protected share. */
function lockedShare(
id: string,
@@ -307,8 +374,7 @@ export async function getShareOverview(
throw new TRPCNotFoundError('Share not found');
}
- const hasAccess = !!cookies.get(`shared-overview-${share.id}`);
- if (share.password && !hasAccess) {
+ if (share.password && !isUnlocked(deps, cookies, 'overview', share)) {
return lockedShare(share.id, share.organization, share.project);
}
@@ -392,8 +458,7 @@ export async function getShareDashboard(
throw new TRPCNotFoundError('Dashboard share not found');
}
- const hasAccess = !!cookies.get(`shared-dashboard-${share.id}`);
- if (share.password && !hasAccess) {
+ if (share.password && !isUnlocked(deps, cookies, 'dashboard', share)) {
return lockedShare(share.id, share.organization, share.project);
}
@@ -487,8 +552,7 @@ export async function getShareDashboardReports(
// gone" and hard-navigates to /login, which made every password-protected
// share unusable. A locked share is an authorization refusal, like the
// share guards in overview.rpc.ts and chart.rpc.ts.
- const hasAccess = !!cookies.get(`shared-dashboard-${share.id}`);
- if (share.password && !hasAccess) {
+ if (share.password && !isUnlocked(deps, cookies, 'dashboard', share)) {
throw new TRPCForbiddenError('Password required');
}
@@ -518,8 +582,7 @@ export async function getShareReport(
throw new TRPCNotFoundError('Report share not found');
}
- const hasAccess = !!cookies.get(`shared-report-${share.id}`);
- if (share.password && !hasAccess) {
+ if (share.password && !isUnlocked(deps, cookies, 'report', share)) {
return lockedShare(share.id, share.organization, share.project);
}
diff --git a/packages/core/src/shared/share-access.test.ts b/packages/core/src/shared/share-access.test.ts
new file mode 100644
index 000000000..198b4aabc
--- /dev/null
+++ b/packages/core/src/shared/share-access.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from 'bun:test';
+import {
+ createShareAccessToken,
+ hasShareAccess,
+ shareAccessCookieName,
+} from './share-access';
+
+const SECRET = 'test-cookie-secret';
+const SHARE = {
+ type: 'dashboard' as const,
+ id: 'share_1',
+ passwordHash: '$argon2id$v=19$hash-a',
+};
+
+function jar(entries: Record<string, string>) {
+ return { get: (name: string) => entries[name] };
+}
+
+function unlocked(share = SHARE, secret = SECRET) {
+ return jar({
+ [shareAccessCookieName(share.type, share.id)]: createShareAccessToken(
+ secret,
+ share
+ ),
+ });
+}
+
+describe('share access cookie', () => {
+ it('accepts the token it issued', () => {
+ expect(hasShareAccess(SECRET, unlocked(), SHARE)).toBe(true);
+ });
+
+ it('refuses a forged value — the bypass this replaces', () => {
+ const forged = jar({
+ [shareAccessCookieName('dashboard', 'share_1')]: '1',
+ });
+ expect(hasShareAccess(SECRET, forged, SHARE)).toBe(false);
+ });
+
+ it('refuses a missing cookie', () => {
+ expect(hasShareAccess(SECRET, jar({}), SHARE)).toBe(false);
+ });
+
+ it('refuses a token minted for another share', () => {
+ const other = { ...SHARE, id: 'share_2' };
+ const cookies = jar({
+ [shareAccessCookieName('dashboard', 'share_1')]: createShareAccessToken(
+ SECRET,
+ other
+ ),
+ });
+ expect(hasShareAccess(SECRET, cookies, SHARE)).toBe(false);
+ });
+
+ it('refuses a token minted for another share type', () => {
+ const cookies = jar({
+ [shareAccessCookieName('dashboard', 'share_1')]: createShareAccessToken(
+ SECRET,
+ { ...SHARE, type: 'report' }
+ ),
+ });
+ expect(hasShareAccess(SECRET, cookies, SHARE)).toBe(false);
+ });
+
+ it('stops working when the password changes', () => {
+ const cookies = unlocked();
+ const rotated = { ...SHARE, passwordHash: '$argon2id$v=19$hash-b' };
+ expect(hasShareAccess(SECRET, cookies, rotated)).toBe(false);
+ });
+
+ it('refuses a token minted under another secret', () => {
+ const cookies = unlocked(SHARE, 'someone-elses-secret');
+ expect(hasShareAccess(SECRET, cookies, SHARE)).toBe(false);
+ });
+
+ it('refuses rather than keying the HMAC with a blank secret', () => {
+ expect(() => createShareAccessToken('', SHARE)).toThrow('COOKIE_SECRET');
+ expect(() => hasShareAccess('', unlocked(), SHARE)).toThrow(
+ 'COOKIE_SECRET'
+ );
+ });
+});
diff --git a/packages/core/src/shared/share-access.ts b/packages/core/src/shared/share-access.ts
new file mode 100644
index 000000000..6eef20e9c
--- /dev/null
+++ b/packages/core/src/shared/share-access.ts
@@ -0,0 +1,67 @@
+// Proof that a viewer entered the password of a password-protected share.
+//
+// Ported from packages/common/server/share-access.ts (main #510), with one
+// change the layering forces: nothing in core reads `process.env` (R7), so the
+// secret arrives as an argument instead of being read from COOKIE_SECRET here.
+
+import { createHmac, timingSafeEqual } from 'node:crypto';
+
+export type ShareType = 'overview' | 'dashboard' | 'report';
+
+export interface ShareAccessInput {
+ type: ShareType;
+ /** The public share id — the value in the share link. */
+ id: string;
+ /** The stored argon2 hash of the share password. */
+ passwordHash: string;
+}
+
+/** What the rpc/http layer hands in; `CookieJar` and Elysia's cookie both fit. */
+interface CookieReader {
+ get(name: string): string | undefined;
+}
+
+export function shareAccessCookieName(type: ShareType, id: string): string {
+ return `shared-${type}-${id}`;
+}
+
+function requireSecret(secret: string): string {
+ if (!secret) {
+ throw new Error(
+ 'COOKIE_SECRET is not set; password-protected shares cannot be unlocked without it'
+ );
+ }
+ return secret;
+}
+
+/**
+ * An HMAC over the share type, share id and the *current* password hash, so
+ * the cookie cannot be forged without the secret, cannot be replayed against
+ * another share, and stops working the moment the owner changes or removes
+ * the password. Checking only that the cookie existed is what let anyone
+ * bypass the password (GHSA-p6c2-mq9r-cx3r).
+ */
+export function createShareAccessToken(
+ secret: string,
+ { type, id, passwordHash }: ShareAccessInput
+): string {
+ return createHmac('sha256', requireSecret(secret))
+ .update(`share-access:${type}:${id}:${passwordHash}`)
+ .digest('base64url');
+}
+
+export function hasShareAccess(
+ secret: string,
+ cookies: CookieReader,
+ share: ShareAccessInput
+): boolean {
+ const presented = cookies.get(shareAccessCookieName(share.type, share.id));
+ if (!presented) {
+ return false;
+ }
+
+ const expected = Buffer.from(createShareAccessToken(secret, share));
+ const actual = Buffer.from(presented);
+ // timingSafeEqual throws on a length mismatch, so the length is compared first.
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
+}
diff --git a/packages/core/test/config-fixture.ts b/packages/core/test/config-fixture.ts
index f33917dc6..cd4417359 100644
--- a/packages/core/test/config-fixture.ts
+++ b/packages/core/test/config-fixture.ts
@@ -36,7 +36,11 @@ export function testCoreConfig(
google: { clientId: '', clientSecret: '', redirectUri: '' },
googleGsc: { clientId: '', clientSecret: '', redirectUri: '' },
},
- cookies: { extraMultiPartTlds: [], customDomain: undefined },
+ cookies: {
+ secret: 'test-cookie-secret',
+ extraMultiPartTlds: [],
+ customDomain: undefined,
+ },
ai: {
openai: {
apiKey: undefined,