Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ change — no migration required.
Every entry maps to a fired event in the codebase. If you change a payload
shape or add an event, update both the `ACTIVITY_EVENTS` tuple and this table.

Rows written by the signup, slot, and field services (`signup.*`, `slot.*`,
`field.*`) may also carry `viaClientId`: the connected app's client id
(usually a URL) when the change came through the MCP server rather than the
browser. It is added by `recordActivity` whenever the actor came through
`activityActor` with a bearer-token actor, and is not listed per event. The
`oauth.*` events identify the app by `clientDomain` instead.

### Signup lifecycle

| event | actor | payload | fired from |
Expand Down
3 changes: 2 additions & 1 deletion src/app/(legal)/privacy/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,8 @@ export default function PrivacyPage() {
single-use code that establishes it. Access tokens themselves are not stored. The
activity log records that a connection was approved, declined, or disconnected,
together with the app's domain (or its configured identifier, for a
pre-registered app). It never records a token or an email address.
pre-registered app), and, for every change a connected app makes on your behalf,
which app made it. It never records a token or an email address.
Comment thread
richshaw marked this conversation as resolved.
Resolved
</p>
<p>
You can see and end every connection from <strong>Connected apps</strong> in your account
Expand Down
49 changes: 45 additions & 4 deletions src/auth/bearer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ import {
import { createLocalJWKSet, errors as joseErrors, jwtVerify, type JSONWebKeySet } from 'jose';
import { getDb } from '@/db/client';
import { log } from '@/lib/log';
import type { Actor } from '@/lib/policy';
import type { Actor, WorkspaceRole } from '@/lib/policy';
import { mcpResourceUrl, oauthIssuer } from '@/oauth/config';
import { getSigningKeys, resetSigningKeysCache } from '@/oauth/instance';
import { protectedResourceMetadataUrl } from '@/oauth/resource-metadata';
import { parseScopeString, type Scope } from '@/oauth/scopes';
import { loadOrganizerSessionById, toActor } from './organizer-session';
import { loadOrganizerSessionById, toActor, type OrganizerSession } from './organizer-session';

/**
* The seam between the authorization server and the MCP layer.
Expand All @@ -31,10 +31,42 @@ import { loadOrganizerSessionById, toActor } from './organizer-session';
* organizer is a viewer, because the actor is the same one
* `requireWorkspaceWrite` already judges.
*/
export interface BearerWorkspace {
id: string;
slug: string;
name: string;
role: WorkspaceRole;
}

export type BearerResolution =
| { ok: true; actor: Extract<Actor, { kind: 'organizer' }>; scopes: Scope[]; clientId: string }
| {
ok: true;
actor: Extract<Actor, { kind: 'organizer' }>;
scopes: Scope[];
clientId: string;
/** The organizer's default workspace, for tools called without one. */
defaultWorkspaceId: string | null;
/** Every workspace the organizer belongs to, with names for display. */
workspaces: BearerWorkspace[];
/**
* What the SDK verified, for handing back to SDK code that wants it
* (the MCP handler's pass-through auth info). Carries the raw token;
* never log it.
*/
authInfo: AuthInfo;
}
| { ok: false; response: Response };

/** The organizer's memberships in the shape the MCP layer shows to a client. */
export function bearerWorkspaces(session: OrganizerSession): BearerWorkspace[] {
return session.memberships.map((m) => ({
id: m.workspaceId,
slug: m.workspaceSlug,
name: m.workspaceName,
role: m.role,
}));
}

export async function resolveBearerActor(
request: Request,
opts: { requiredScopes?: Scope[] } = {},
Expand Down Expand Up @@ -69,7 +101,16 @@ export async function resolveBearerActor(
}),
};
}
return { ok: true, actor, scopes: parseScopeString(auth.scopes.join(' ')), clientId: auth.clientId };
return {
ok: true,
// Spread rather than mutate: `toActor` is React-cached and the object may be shared.
actor: { ...actor, via: { clientId: auth.clientId } },
scopes: parseScopeString(auth.scopes.join(' ')),
clientId: auth.clientId,
defaultWorkspaceId: session.defaultWorkspaceId,
workspaces: bearerWorkspaces(session),
authInfo: auth,
};
}

/**
Expand Down
7 changes: 4 additions & 3 deletions src/auth/organizer-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ import type { Actor, WorkspaceRole } from '@/lib/policy';
* (`./session.ts`, via Auth.js) and the bearer-token path (`./bearer.ts`).
* Both hand an organizer id to `loadOrganizerSessionById` and both run the
* result through `toActor`, so a token and a cookie for the same organizer
* produce byte-identical actors — the property every workspace-scoping
* guard in `src/lib/policy.ts` relies on. This module deliberately imports
* nothing from Auth.js.
* produce the same actor — the property every workspace-scoping guard in
* `src/lib/policy.ts` relies on. The bearer path adds one field on top,
* `via`, naming the connected app; nothing in the policy layer reads it.
* This module deliberately imports nothing from Auth.js.
*/
export interface OrganizerSession {
organizerId: string;
Expand Down
27 changes: 27 additions & 0 deletions src/lib/activity.db.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { eq } from 'drizzle-orm';
import { activity } from '@/db/schema/activity';
import { getDb, type Db } from '@/db/client';
import { organizers } from '@/db/schema/organizers';
import { workspaces } from '@/db/schema/workspaces';
Expand Down Expand Up @@ -85,6 +86,32 @@ describe('recordActivity → organizers.last_active_at', () => {
expect(after.getTime()).toBeGreaterThan(before.getTime());
});

it('writes viaClientId into the payload only when the actor names a connected app', async () => {
await recordActivity(fx.db, {
signupId: null,
workspaceId: fx.workspaceId,
actor: { actorId: fx.organizerId, actorType: 'organizer', clientId: 'https://client.example/meta.json' },
eventType: 'signup.updated',
payload: { changed: ['title'] },
});
await recordActivity(fx.db, {
signupId: null,
workspaceId: fx.workspaceId,
actor: { actorId: fx.organizerId, actorType: 'organizer' },
eventType: 'signup.published',
payload: { from: 'draft', to: 'open' },
});
const rows = await fx.db
.select({ eventType: activity.eventType, payload: activity.payload })
.from(activity)
.where(eq(activity.workspaceId, fx.workspaceId));
expect(rows.find((r) => r.eventType === 'signup.updated')?.payload).toEqual({
changed: ['title'],
viaClientId: 'https://client.example/meta.json',
});
expect(rows.find((r) => r.eventType === 'signup.published')?.payload).toEqual({ from: 'draft', to: 'open' });
});

it('does not advance last_active_at when actorType is system', async () => {
const before = await readLastActiveAt(fx.db, fx.organizerId);
await new Promise((resolve) => setTimeout(resolve, 5));
Expand Down
37 changes: 37 additions & 0 deletions src/lib/activity.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { describe, expect, it } from 'vitest';
import { activityActor } from './activity';
import { ServiceException } from './errors';
import type { Actor } from './policy';

const base: Actor = {
kind: 'organizer',
id: 'org_1',
email: 'a@example.com',
workspaceIds: ['ws_1'],
workspaceRoles: { ws_1: 'owner' },
};

describe('activityActor', () => {
it('maps a browser organizer to a plain organizer actor', () => {
expect(activityActor(base)).toEqual({ actorId: 'org_1', actorType: 'organizer' });
});

it('carries the connected app id when the actor came through a bearer token', () => {
expect(activityActor({ ...base, via: { clientId: 'https://claude.ai/oauth/x' } })).toEqual({
actorId: 'org_1',
actorType: 'organizer',
clientId: 'https://claude.ai/oauth/x',
});
});

it('refuses anything that is not an organizer with unauthorized, like requireOrganizerId', () => {
let thrown: unknown;
try {
activityActor({ kind: 'anonymous' });
} catch (e) {
thrown = e;
}
expect(thrown).toBeInstanceOf(ServiceException);
expect((thrown as ServiceException).serviceError.code).toBe('unauthorized');
});
});
21 changes: 20 additions & 1 deletion src/lib/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,27 @@ import { activity, type ActivityEvent } from '@/db/schema/activity';
import { organizers } from '@/db/schema/organizers';
import type { Db, Queryable } from '@/db/client';
import { makeId } from './ids';
import { requireOrganizer, type Actor } from './policy';

export interface ActivityActor {
actorId: string | null;
actorType: 'organizer' | 'participant' | 'system';
/** The connected app that made the change on the organizer's behalf, if any. */
clientId?: string;
}

/**
* The activity-log identity of an organizer actor. A browser session gives
* a plain organizer row; a bearer-token session also names the connected
* app, which `recordActivity` writes into the row's payload as
* `viaClientId`. Throws `unauthorized` for participants and anonymous
* actors, exactly like `requireOrganizerId`.
*/
export function activityActor(actor: Actor): ActivityActor {
requireOrganizer(actor);
return actor.via
? { actorId: actor.id, actorType: 'organizer', clientId: actor.via.clientId }
: { actorId: actor.id, actorType: 'organizer' };
}

export async function recordActivity(
Expand All @@ -19,14 +36,16 @@ export async function recordActivity(
payload?: Record<string, unknown>;
},
) {
const given = args.payload ?? {};
const payload = args.actor.clientId ? { ...given, viaClientId: args.actor.clientId } : given;
await db.insert(activity).values({
id: makeId('act'),
signupId: args.signupId ?? null,
workspaceId: args.workspaceId ?? null,
actorId: args.actor.actorId,
actorType: args.actor.actorType,
eventType: args.eventType,
payload: args.payload ?? {},
payload,
});

if (args.actor.actorType === 'organizer' && args.actor.actorId !== null) {
Expand Down
7 changes: 7 additions & 0 deletions src/lib/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ export type Actor =
workspaceIds: string[];
/** Parallel to workspaceIds; each entry is the role in that workspace. */
workspaceRoles: Record<string, WorkspaceRole>;
/**
* Set only when the actor arrived through a connected app's bearer
* token (`src/auth/bearer.ts`). Names the app so the activity log can
* say which app made a change. Never set by the cookie path, and
* never read by the policy functions in this file.
*/
via?: { clientId: string };
}
| {
kind: 'participant';
Expand Down
8 changes: 7 additions & 1 deletion src/oauth/flow.db.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,15 @@ describe('authorization code flow on Postgres', () => {
const seam = await resolveBearerActor(bearer(tokens.access_token));
expect(seam.ok).toBe(true);
if (seam.ok) {
expect(seam.actor).toEqual(organizerActor);
// Same actor the cookie path builds, plus the app that carried it.
expect(seam.actor).toEqual({ ...organizerActor, via: { clientId: CLIENT } });
expect(seam.scopes).toEqual(['signups:read', 'signups:write']);
expect(seam.clientId).toBe(CLIENT);
expect(seam.defaultWorkspaceId).toBe(workspaceId);
expect(seam.workspaces).toEqual([
{ id: workspaceId, slug: organizerId.toLowerCase(), name: 'Flow', role: 'owner' },
]);
expect(seam.authInfo).toMatchObject({ token: tokens.access_token, clientId: CLIENT, scopes: ['signups:read', 'signups:write'] });
}
const noHeader = await resolveBearerActor(bearer());
expect(noHeader.ok).toBe(false);
Expand Down
12 changes: 6 additions & 6 deletions src/services/signups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import { commitments } from '@/db/schema/commitments';
import { signups } from '@/db/schema/signups';
import { slotFields } from '@/db/schema/slot-fields';
import { slots } from '@/db/schema/slots';
import { recordActivity } from '@/lib/activity';
import { activityActor, recordActivity } from '@/lib/activity';
import { serviceError, ServiceException, type ServiceError } from '@/lib/errors';
import { makeId } from '@/lib/ids';
import { parseInputSafe } from '@/lib/parse';
import { requireOrganizerId, requireWorkspaceAccess, requireWorkspaceWrite, type Actor } from '@/lib/policy';
import { requireWorkspaceAccess, requireWorkspaceWrite, type Actor } from '@/lib/policy';
import { err, ok, type Result } from '@/lib/result';
import { DEFAULT_TEMPLATE, type SignupTemplate } from '@/lib/signup-templates';
import { toSlug } from '@/lib/slug';
Expand Down Expand Up @@ -187,7 +187,7 @@ export async function createSignup(
await recordActivity(tx, {
signupId: inserted.id,
workspaceId,
actor: { actorId: requireOrganizerId(actor), actorType: 'organizer' },
actor: activityActor(actor),
eventType: 'signup.created',
payload: {
templateId: template.id,
Expand Down Expand Up @@ -296,7 +296,7 @@ export async function updateSignup(
await recordActivity(tx, {
signupId,
workspaceId: row.workspaceId,
actor: { actorId: requireOrganizerId(actor), actorType: 'organizer' },
actor: activityActor(actor),
eventType: 'signup.updated',
payload: { changed: Object.keys(data) },
});
Expand Down Expand Up @@ -366,7 +366,7 @@ export async function deleteSignup(
await recordActivity(tx, {
signupId,
workspaceId: row.workspaceId,
actor: { actorId: requireOrganizerId(actor), actorType: 'organizer' },
actor: activityActor(actor),
eventType: 'signup.deleted',
payload: { status: row.status },
});
Expand Down Expand Up @@ -426,7 +426,7 @@ async function transitionStatus(
await recordActivity(tx, {
signupId,
workspaceId: row.workspaceId,
actor: { actorId: requireOrganizerId(actor), actorType: 'organizer' },
actor: activityActor(actor),
eventType,
payload: { from: row.status, to },
});
Expand Down
9 changes: 4 additions & 5 deletions src/services/slot-fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@ import type { Db, Queryable } from '@/db/client';
import { signups } from '@/db/schema/signups';
import { slotFields } from '@/db/schema/slot-fields';
import { slots } from '@/db/schema/slots';
import { recordActivity } from '@/lib/activity';
import { activityActor, recordActivity } from '@/lib/activity';
import { serviceError, type ServiceError } from '@/lib/errors';
import { makeId } from '@/lib/ids';
import { parseInputSafe } from '@/lib/parse';
import {
requireOrganizerId,
requireWorkspaceAccess,
requireWorkspaceWrite,
type Actor,
Expand Down Expand Up @@ -220,7 +219,7 @@ export async function addField(
await recordActivity(tx, {
signupId,
workspaceId: signupRow.workspaceId,
actor: { actorId: requireOrganizerId(actor), actorType: 'organizer' },
actor: activityActor(actor),
eventType: 'field.created',
payload: {
fieldId: row.id,
Expand Down Expand Up @@ -325,7 +324,7 @@ export async function updateField(
await recordActivity(tx, {
signupId: existing.signupId,
workspaceId: existing.workspaceId,
actor: { actorId: requireOrganizerId(actor), actorType: 'organizer' },
actor: activityActor(actor),
eventType: 'field.updated',
payload: {
fieldId: row.id,
Expand Down Expand Up @@ -406,7 +405,7 @@ export async function deleteField(
await recordActivity(tx, {
signupId: existing.signupId,
workspaceId: existing.workspaceId,
actor: { actorId: requireOrganizerId(actor), actorType: 'organizer' },
actor: activityActor(actor),
eventType: 'field.deleted',
payload: {
fieldId,
Expand Down
Loading
Loading