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
140 changes: 5 additions & 135 deletions server/src/addie/mcp/admin-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11259,21 +11259,6 @@ Use add_committee_leader to assign a leader.`;
// MEMBERSHIP INVITE HANDLERS
// ============================================

function actionToHeader(action: string): string {
switch (action) {
case "invited":
return "Invitation sent";
case "member_added":
return "Added to org";
case "role_updated":
return "Role updated";
case "no_change":
return "No change";
default:
return "Done";
}
}

function formatRelativeDays(d: Date): string {
const diffMs = d.getTime() - Date.now();
const days = Math.round(diffMs / 86400000);
Expand Down Expand Up @@ -11537,126 +11522,11 @@ Use add_committee_leader to assign a leader.`;
}
});

handlers.set("add_member_to_org", async (input) => {
const email = ((input.email as string) || "").trim().toLowerCase();
const orgId = input.org_id as string;
const role = (input.role as string) ?? "member";
const seatType = (input.seat_type as string) ?? "community_only";

if (!email || !email.includes("@")) {
return "❌ email is required (a valid email address).";
}
if (!orgId || !orgId.startsWith("org_")) {
return "❌ org_id is required (org_…).";
}
if (!["member", "admin", "owner"].includes(role)) {
return `❌ role must be one of: member, admin, owner (got: ${role}).`;
}
if (!["contributor", "community_only"].includes(seatType)) {
return `❌ seat_type must be one of: contributor, community_only (got: ${seatType}).`;
}

const adminUser = memberContext?.workos_user;
if (!adminUser) {
return "❌ Cannot add member — no signed-in admin context.";
}

const apiKey = process.env.ADMIN_API_KEY;
if (!apiKey) {
return "❌ ADMIN_API_KEY is not configured on the server.";
}
// Match the base-URL precedence used by member-tools.ts:getBaseUrl —
// BASE_URL (production) wins; otherwise PORT/CONDUCTOR_PORT for local.
const baseUrl =
process.env.BASE_URL ||
`http://localhost:${
process.env.PORT || process.env.CONDUCTOR_PORT || "3000"
}`;
const endpoint = `${baseUrl}/api/organizations/${encodeURIComponent(
orgId,
)}/members/by-email`;

try {
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({ email, role, seat_type: seatType }),
signal: AbortSignal.timeout(10000),
});
const data = (await response.json().catch(() => ({}))) as Record<
string,
unknown
>;
if (!response.ok) {
const errorMsg =
(data.message as string) ||
(data.error as string) ||
`HTTP ${response.status}`;
logger.warn(
{ status: response.status, orgId, email, error: errorMsg },
"add_member_to_org route returned non-OK",
);
return `❌ Failed to add ${email} to ${orgId}: ${errorMsg}`;
}

const action = data.action as string;
logger.info(
{
orgId,
email,
action,
role,
seatType,
adminUserId: adminUser.workos_user_id,
},
"Addie called add_member_to_org",
);

// Mirror the route's response shape rather than reflecting the input —
// e.g. the route may keep an existing seat_type when adding to an org
// the user already has a seat in.
const responseSeatType =
(data.seat_type as string | undefined) ?? seatType;

let md = `## ${actionToHeader(action)}\n\n`;
md += `**Email:** ${email}\n`;
md += `**Org:** ${orgId}\n`;

if (action === "invited") {
const invitation = data.invitation as
| Record<string, unknown>
| undefined;
const expiresAt = invitation?.expires_at as string | undefined;
md += `**Invited as:** member (must be promoted after acceptance for higher roles)\n`;
md += `**Requested role:** ${role}\n`;
md += `**Seat type:** ${responseSeatType}\n`;
if (expiresAt) md += `**Invite expires:** ${expiresAt.slice(0, 10)}\n`;
if (invitation?.accept_invitation_url) {
md += `\nThey'll receive an email with a sign-up link.\n`;
}
} else if (action === "member_added") {
md += `**Role:** ${role}\n`;
md += `**Seat type:** ${responseSeatType}\n`;
md += `\nThey already had a WorkOS account; added directly to the org.\n`;
} else if (action === "role_updated") {
const previousRole = data.previous_role as string | null | undefined;
md += `**New role:** ${role}\n`;
md += `**Previous role:** ${previousRole ?? "(none)"}\n`;
} else if (action === "no_change") {
md += `\nNo change — they already have role ${role}.\n`;
} else {
md += `**Action:** ${action ?? "unknown"}\n`;
}
return md;
} catch (error) {
logger.error({ error, orgId, email }, "Error calling members/by-email");
return `❌ Failed to add member: ${
error instanceof Error ? error.message : "Unknown error"
}`;
}
// The old HTTP adapter replaced its human caller with ADMIN_API_KEY.
// MemberContext supplies canonical person metadata, not an immutable exact
// credential/organization/epoch proof. Do not launder that into admin writes.
handlers.set("add_member_to_org", async () => {
return "❌ Organization membership changes require the signed-in organization management page. Addie cannot forward an exact authenticated actor for this operation.";
});

handlers.set("diagnose_signin_block", async (input) => {
Expand Down
22 changes: 21 additions & 1 deletion server/src/auth/workos-jwt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,14 @@
* token issued by the MCP OAuth flow works across both surfaces.
*/

import { createRemoteJWKSet, errors, jwtVerify, type JWTPayload, type JWTVerifyGetKey } from 'jose';
import {
createRemoteJWKSet,
decodeProtectedHeader,
errors,
jwtVerify,
type JWTPayload,
type JWTVerifyGetKey,
} from 'jose';
import { createLogger } from '../logger.js';

const logger = createLogger('workos-jwt');
Expand All @@ -21,6 +28,7 @@ export function isInvalidWorkOSJWTError(error: unknown): boolean {
'ERR_JWS_INVALID', 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED',
'ERR_JWKS_NO_MATCHING_KEY',
'ERR_JOSE_ALG_NOT_ALLOWED', 'ERR_JOSE_NOT_SUPPORTED',
'ERR_WORKOS_TOKEN_INVALID_HEADER', 'ERR_WORKOS_TOKEN_INVALID_KID',
].includes(code);
}

Expand Down Expand Up @@ -125,6 +133,18 @@ export function looksLikeJWT(token: string): boolean {
* signature verification against our shared JWKS.
*/
export async function verifyWorkOSJWT(token: string): Promise<VerifiedWorkOSToken> {
let protectedHeader: ReturnType<typeof decodeProtectedHeader>;
try {
protectedHeader = decodeProtectedHeader(token);
} catch (cause) {
throw Object.assign(new Error('Token protected header is malformed'), {
code: 'ERR_WORKOS_TOKEN_INVALID_HEADER',
cause,
});
}
if (protectedHeader.kid !== undefined && typeof protectedHeader.kid !== 'string') {
throw Object.assign(new Error('Token key id must be a string'), { code: 'ERR_WORKOS_TOKEN_INVALID_KID' });
}
const jwksInstance = getJWKS();

const { payload } = await jwtVerify(token,
Expand Down
5 changes: 4 additions & 1 deletion server/src/db/api-key-management-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const SNAPSHOT_SQL = `
SELECT pg_catalog.pg_is_in_recovery() AS in_recovery,
credential.workos_user_id AS authenticated_user_id,
primary_binding.workos_user_id AS canonical_user_id, binding.identity_id,
binding.xmin::text AS binding_version,
COALESCE(primary_binding.primary_count, 0)::text AS primary_count,
EXISTS (
SELECT 1 FROM registry_audit_log audit
Expand Down Expand Up @@ -46,6 +47,7 @@ interface SnapshotRow {
authenticated_user_id: string | null;
canonical_user_id: string | null;
identity_id: string | null;
binding_version: string | null;
authorization_epoch: string;
email: string | null;
email_verified: boolean;
Expand All @@ -57,12 +59,13 @@ function snapshotFromRow(row: SnapshotRow | undefined, organizationId: string |
if (!row || row.in_recovery) throw new AuthorizationSnapshotUnavailableError();
// Grant-free management must retain the primary snapshot's terminal
// lifecycle boundary, including stale provider recreation and bad routing.
if (row.terminal_marker || !row.authenticated_user_id || !row.identity_id
if (row.terminal_marker || !row.authenticated_user_id || !row.identity_id || !row.binding_version
|| row.primary_count !== '1' || !row.canonical_user_id) return null;
return Object.freeze({
authenticatedUserId: row.authenticated_user_id,
canonicalUserId: row.canonical_user_id,
identityId: row.identity_id,
bindingVersion: row.binding_version,
selectedOrganizationId: organizationId,
authorizationEpoch: row.authorization_epoch,
credential: Object.freeze({
Expand Down
58 changes: 56 additions & 2 deletions server/src/db/identity-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,9 @@ export const CREDENTIAL_MUTATION_ADMISSION_TIMEOUT_MS = 1_000;

/**
* Keep one connection free for confirmed deletion and bound admission wait.
* Guard callbacks must use their supplied client and must not perform provider
* I/O, so each admitted mutation consumes exactly one pool connection.
* Guard mutation callbacks must use their supplied client and must not perform
* provider I/O. A serialized prefetch may use the admitted connection before
* the credential lock is acquired, so confirmed deletion can still progress.
*/
const credentialMutationAdmission = {
active: 0,
Expand Down Expand Up @@ -427,6 +428,7 @@ async function withCredentialEventMutation<T>(
workosUserId: string,
mode: CredentialMutationMode,
mutation: (client: PoolClient) => Promise<T>,
serializedPrefetch?: () => Promise<void>,
): Promise<CredentialEventMutationResult<T>> {
const releaseCapacity = await acquireCredentialMutationPoolCapacity();
try {
Expand All @@ -436,6 +438,45 @@ async function withCredentialEventMutation<T>(
try {
await client.query('BEGIN');
await client.query(`SET LOCAL lock_timeout = '${CREDENTIAL_MUTATION_LOCK_TIMEOUT_MS}ms'`);
if (serializedPrefetch) {
// Membership provider reads can be slow, so serialize them on a
// distinct lock before taking the credential-revocation lock. This
// preserves webhook ordering without delaying a confirmed deletion.
await client.query(`SELECT pg_advisory_xact_lock(hashtextextended($1, 6828))`, [workosUserId]);

// Avoid provider reads for a credential that is already inactive.
// This is only an optimization: deletion can race this read, and the
// locked lifecycle check below remains the authority before effects.
const preflight = await client.query<{
user_exists: boolean;
binding_exists: boolean;
primary_count: string;
}>(
`SELECT EXISTS (
SELECT 1 FROM users WHERE workos_user_id = $1
) AS user_exists,
EXISTS (
SELECT 1 FROM identity_workos_users WHERE workos_user_id = $1
) AS binding_exists,
COALESCE((
SELECT COUNT(*)
FROM identity_workos_users actor_iwu
JOIN identity_workos_users primary_iwu
ON primary_iwu.identity_id = actor_iwu.identity_id
AND primary_iwu.is_primary = TRUE
WHERE actor_iwu.workos_user_id = $1
), 0)::text AS primary_count`,
[workosUserId],
);
const state = preflight.rows[0];
if (state?.user_exists !== true
|| state.binding_exists !== true
|| Number(state.primary_count) !== 1) {
await client.query('COMMIT');
return { applied: false };
}
await serializedPrefetch();
}
const { identityId } = await lockCredentialThenIdentityMutation(client, workosUserId);
if (await hasConfirmedDeletionTombstone(client, workosUserId)) {
await client.query('COMMIT');
Expand Down Expand Up @@ -505,6 +546,19 @@ export async function withActiveCredentialEventMutation<T>(
return withCredentialEventMutation(workosUserId, 'active', mutation);
}

/**
* Serialize read-only provider state for one credential before taking the
* credential lifecycle lock, then recheck the locked lifecycle before local
* effects. The prefetch must be bounded and must not perform provider writes.
*/
export async function withActiveCredentialEventMutationAfterSerializedPrefetch<T>(
workosUserId: string,
prefetch: () => Promise<void>,
mutation: (client: PoolClient) => Promise<T>,
): Promise<CredentialEventMutationResult<T>> {
return withCredentialEventMutation(workosUserId, 'active', mutation, prefetch);
}

/** Apply one atomic authority mutation to a sorted set of live credentials. */
export async function withActiveCredentialSetMutation<T>(
workosUserIds: string[],
Expand Down
Loading
Loading