Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
7e0bdb8
fix(audit): record passkey deletion
Bccorb Nov 8, 2026
6b1205a
feat(webhooks): signed, retried webhooks built from the audit log
Bccorb Nov 8, 2026
1866332
fix(deps): use @seamless-auth/types 0.39.0
Bccorb Nov 8, 2026
d6efa56
feat(hooks): post_login and pre_token login hooks as signed callouts
Bccorb Nov 8, 2026
fdf7b16
feat(claims): static custom claims for roles and OpenID clients
Bccorb Nov 8, 2026
8730f93
feat(claims): share one token budget between permissions and custom c…
Bccorb Nov 8, 2026
edebb7c
feat(oidc): sign roles, permissions and custom claims into provider t…
Bccorb Nov 8, 2026
108a784
docs(claims): record role-name order for custom claims
Bccorb Nov 8, 2026
590caa1
feat(oidc): refuse changed provider claims as claims_mismatch so the …
Bccorb Nov 8, 2026
5503f1c
Merge remote-tracking branch 'origin/feat/custom-claims' into feat/oi…
Bccorb Nov 8, 2026
ba740fc
feat(webhooks): catch a re-enabled endpoint up on what it missed
Bccorb Nov 8, 2026
794284e
chore: merge feat/signed-webhooks into feat/login-hooks
Bccorb Nov 8, 2026
5c1d6f5
chore: merge feat/login-hooks into feat/custom-claims
Bccorb Nov 8, 2026
1a82a0e
Merge remote-tracking branch 'origin/feat/custom-claims' into feat/oi…
Bccorb Nov 8, 2026
bf9108b
fix(deps): use @seamless-auth/types 0.40.0
Bccorb Nov 8, 2026
7027943
fix(oidc): return empty customClaims and regenerate api types for typ…
Bccorb Nov 8, 2026
f523249
Merge remote-tracking branch 'origin/feat/signed-webhooks' into adopt…
Bccorb Nov 8, 2026
13c14ed
refactor(login-hooks): type refusal bodies with the shared error schemas
Bccorb Nov 8, 2026
4e295d1
Merge remote-tracking branch 'origin/feat/login-hooks' into adopt/cus…
Bccorb Nov 8, 2026
cfc145f
refactor(custom-claims): use the shared claim schemas directly
Bccorb Nov 8, 2026
e32e823
docs(adr): record that the shared claim schemas now generate
Bccorb Nov 8, 2026
cab0295
Merge remote-tracking branch 'origin/feat/custom-claims' into adopt/o…
Bccorb Nov 8, 2026
beaa58f
refactor(oidc): use the shared account claims and sign refusal schemas
Bccorb Nov 8, 2026
150992c
chore: merge main into feat/oidc-provider-claims after #584 was squashed
Bccorb Nov 8, 2026
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
10 changes: 10 additions & 0 deletions .changeset/provider-token-claims.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'seamless-auth-api': minor
---

Let OpenID Provider tokens carry roles, permissions and custom claims (seamless-auth-oidc-provider#47).

- `GET /oidc/accounts/:id` now returns the ADR 0004 permission claims (`permissions`, `org_roles`, `org_permissions`, or `permissions_omitted`) and `customClaims`, computed for the session and client the lookup names, with the same shared 1 KiB budget as a first-party token. An omission writes `custom_claims_omitted` with the client id.
- Custom claims for a provider token add the client's `oidc_client` set after the instance and organization role sets and before the session's `pre_token` hook claims.
- `org_id` for a provider token is now the session's active organization, while the user is still a member, instead of the user's oldest membership. This is a behavior change for provider clients that read `org_id`.
- `/oidc/sign` signs these claims only with the values it computes again for that session and client. A different value, a custom claim name it did not compute, or a permission or custom claim set carried in part is refused with the new code `claims_mismatch` (403), which the provider answers by reading the account again and retrying once. A reserved or unlisted name is still `malformed_signing_input`. Client credentials tokens still carry none of them.
6 changes: 6 additions & 0 deletions docs/adr/0005-extensibility-callouts.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,12 @@ They must be read back to sign, so they cannot be hashed. They are AES-256-GCM e
- Separate 1 KiB budgets for permissions and custom claims did not fit the server adapter's session cookie: 5670 bytes against 4096 at both, with only about 136 bytes of custom claims fitting beside a full permission set. Brandon chose the shared budget and the order in E6 on 2026-11-07. At the shared budget the worst-case cookie measures 3868 bytes.
- A set can only be written for a role or client that exists, and retiring the role or deleting the client deletes its set.
- `z.json()` in the shared claim schemas overflowed the OpenAPI generator. `@seamless-auth/types` 0.40.0 describes a claim value as a union bounded at the claim depth, so the route schemas use the shared ones directly.
- Provider tokens (seamless-auth-oidc-provider#47):
- Brandon chose the scope names on 2026-11-07: `permissions` releases `roles`, `permissions`, `org_id`, `org_roles` and `org_permissions` (or `permissions_omitted`), and `custom_claims` releases every custom claim the API resolves for the user and the client. They apply to ID tokens, userinfo, and a user's access token for a resource when the grant holds the scope. `seamless` still releases `roles` and `org_id` alone.
- The API computes the claims for the session and client (`GET /oidc/accounts/:id`), with the client's set after the role sets and before the session's hook claims and the shared budget applied, and `/oidc/sign` computes them again and signs only an exact match. The edge never reads custom claim tables.
- `org_id` in a provider token is now the session's active organization, as in a first-party token, rather than the user's oldest membership.
- A role or membership can change between the edge's read and its sign. `/oidc/sign` answers that, and any other account claim that does not match, with `claims_mismatch`, a new refusal code, and the edge reads the account again and retries once. A second mismatch fails the token request with `server_error`. Brandon chose this on 2026-11-07.
- The budget is applied to everything the account has, whatever the scopes, so a client that asks only for `permissions` can see `permissions_omitted` because of custom claims it did not ask for.

## Consequences

Expand Down
4 changes: 2 additions & 2 deletions src/controllers/oidcEdge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ import { OidcPayload } from '../models/oidcPayloads.js';
import { Session } from '../models/sessions.js';
import type { AuthEventType } from '../schemas/authEvent.types.js';
import { AuthEventService } from '../services/authEventService.js';
import { getOidcAccountClaims } from '../services/oidcAccountClaims.js';
import { getOidcAuthContext, isUuid } from '../services/oidcAuthContext.js';
import { sendBackchannelLogout } from '../services/oidcBackchannelLogout.js';
import {
findActiveOidcClient,
getOidcAccountClaims,
getOidcClientMetadata,
getOidcClientResources,
verifyOidcClientSecret,
Expand Down Expand Up @@ -200,7 +200,7 @@ export async function getOidcAccount(req: Req<OidcAccountIdParams>, res: Respons
// read the claims of anyone who is not signing in through it.
if (!session || session.userId !== req.params.id) return res.status(404).json(NOT_FOUND);

const claims = await getOidcAccountClaims(req.params.id);
const claims = await getOidcAccountClaims(session, clientId, { recordOmission: true });
return claims ? res.status(200).json(claims) : res.status(404).json(NOT_FOUND);
}

Expand Down
7 changes: 6 additions & 1 deletion src/services/customClaimService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,18 +118,21 @@ function setsFor(rows: CustomClaim[], kind: CustomClaimSourceKind, names: string

/**
* Instance role sets, then organization role sets (only while the membership exists), then the
* session's hook claims. A later source wins per name, and roles of one kind apply in name order,
* OpenID Provider client's set (provider tokens only), then the session's hook claims. A later
* source wins per name, and roles of one kind apply in name order,
* so the result does not depend on the order roles were granted in. Reserved names are filtered
* again here, whatever was stored. The token budget is applied by `authorizationClaims`.
*/
export async function resolveCustomClaims({
roles,
organizationRoles,
clientId,
hookClaims,
transaction,
}: {
roles: string[];
organizationRoles: string[];
clientId?: string | null;
hookClaims: ClaimSet | null | undefined;
transaction?: Transaction;
}): Promise<ClaimSet> {
Expand All @@ -138,6 +141,7 @@ export async function resolveCustomClaims({
...(organizationRoles.length
? [{ sourceKind: 'organization_role', sourceName: { [Op.in]: organizationRoles } }]
: []),
...(clientId ? [{ sourceKind: 'oidc_client', sourceName: clientId }] : []),
];
const rows = wanted.length
? await CustomClaim.findAll({ where: { [Op.or]: wanted }, transaction })
Expand All @@ -147,6 +151,7 @@ export async function resolveCustomClaims({
for (const set of [
...setsFor(rows, 'instance_role', roles),
...setsFor(rows, 'organization_role', organizationRoles),
...(clientId ? setsFor(rows, 'oidc_client', [clientId]) : []),
hookClaims ?? {},
]) {
for (const [name, value] of Object.entries(set)) {
Expand Down
104 changes: 104 additions & 0 deletions src/services/oidcAccountClaims.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* Copyright © 2026 Fells Code, LLC
* Licensed under the Apache License, Version 2.0
* See LICENSE file in the project root for full license information
*/

import type { CustomClaimSet, OidcAccountClaims } from '@seamless-auth/types';

import { User } from '../models/users.js';
import {
AUTHORIZATION_CLAIMS_BUDGET_BYTES,
authorizationClaims,
resolveAuthorization,
} from './accessTokenService.js';
import { AuthEventService } from './authEventService.js';
import { resolveCustomClaims } from './customClaimService.js';
import { isUuid } from './oidcAuthContext.js';

type ProviderSession = {
id: string;
userId: string;
organizationId?: string | null;
recovery?: boolean | null;
hookClaims?: Record<string, unknown> | null;
};

/** The permission claims a provider token carries together or not at all. */
export const PERMISSION_CLAIMS = [
'permissions',
'permissions_omitted',
'org_roles',
'org_permissions',
] as const;

/**
* Computed the way `mintAccessToken` computes a first-party token, plus the client's own set,
* so `/oidc/accounts/:id` and `/oidc/sign` arrive at the same values. `org_id` is the session's
* active organization, as in a first-party token.
*/
export async function getOidcAccountClaims(
session: ProviderSession,
clientId: string,
{ recordOmission = false }: { recordOmission?: boolean } = {},
): Promise<OidcAccountClaims | null> {
if (!isUuid(session.userId)) return null;

const user = await User.findOne({ where: { id: session.userId } });

if (!user || user.revoked) return null;

const recovery = session.recovery === true;
const authorization = await resolveAuthorization({
userId: user.id,
roles: user.roles,
organizationId: session.organizationId,
recovery,
});
// The hook decided its claims for the session's organization, so they go with it.
const leftOrganization = Boolean(session.organizationId && !authorization.organizationId);

const budgeted = authorizationClaims(
authorization,
recovery
? {}
: await resolveCustomClaims({
roles: user.roles ?? [],
organizationRoles: authorization.organizationRoles,
clientId,
hookClaims: leftOrganization ? null : session.hookClaims,
}),
);

if (recordOmission && budgeted.customClaimsOmitted) {
await AuthEventService.logContext({
userId: user.id,
sessionId: session.id,
type: 'custom_claims_omitted',
metadata: {
bytes: budgeted.customClaimsOmitted.bytes,
budgetBytes: AUTHORIZATION_CLAIMS_BUDGET_BYTES,
clientId,
},
});
}

return {
sub: user.id,
email: user.email,
email_verified: user.emailVerified === true,
...(user.phone
? { phone_number: user.phone, phone_number_verified: user.phoneVerified === true }
: {}),
roles: user.roles ?? [],
org_id: authorization.organizationId,
...(recovery ? {} : budgeted.authorization),
// Every source is held to CustomClaimSetSchema when written, so the merged set is one.
customClaims: budgeted.customClaims as CustomClaimSet,
};
}

/** Every claim a provider token for this account may carry, by the name it is signed under. */
export function providerTokenClaims({ customClaims, ...claims }: OidcAccountClaims) {
return { ...customClaims, ...claims } as Record<string, unknown>;
}
24 changes: 0 additions & 24 deletions src/services/oidcClientRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

import {
APPLICATION_NOTICE_SCOPE,
type OidcAccountClaims,
type OidcClientMetadata,
type OidcPublicJwk,
oidcRedirectUriKind,
Expand All @@ -21,9 +20,6 @@ import { getSystemConfig } from '../config/getSystemConfig.js';
import { OidcClientResource } from '../models/oidcClientResources.js';
import { OidcClient } from '../models/oidcClients.js';
import { OidcResource } from '../models/oidcResources.js';
import { User } from '../models/users.js';
import { isUuid } from './oidcAuthContext.js';
import { getDefaultOrganizationIdForUser } from './organizationService.js';

const SHARED_SECRET_METHODS = new Set(['client_secret_basic', 'client_secret_post']);
const DEVICE_CODE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
Expand Down Expand Up @@ -203,23 +199,3 @@ export async function getOidcClientResourceScopes(clientId: string) {
const resources = await getOidcClientResources(clientId);
return new Map(resources.map((resource) => [resource.identifier, new Set(resource.scopes)]));
}

export async function getOidcAccountClaims(userId: string): Promise<OidcAccountClaims | null> {
if (!isUuid(userId)) return null;

const user = await User.findOne({ where: { id: userId } });

if (!user || user.revoked) return null;

return {
sub: user.id,
email: user.email,
email_verified: user.emailVerified === true,
...(user.phone
? { phone_number: user.phone, phone_number_verified: user.phoneVerified === true }
: {}),
roles: user.roles ?? [],
org_id: await getDefaultOrganizationIdForUser(user.id),
customClaims: {},
};
}
99 changes: 81 additions & 18 deletions src/services/oidcSigning.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
*/

import {
CUSTOM_CLAIM_NAME_PATTERN,
isReservedClaimName,
type OidcSignRefusalCode,
type OidcSignRequest,
seamlessBuiltInResource,
Expand All @@ -15,12 +17,13 @@ import { constants, sign } from 'crypto';
import { getSystemConfig } from '../config/getSystemConfig.js';
import { Session } from '../models/sessions.js';
import { parseDurationToSeconds } from '../utils/utils.js';
import { deriveAcrAmr, resolveCurrentSession, sessionAuthTime } from './oidcAuthContext.js';
import {
findActiveOidcClient,
getOidcAccountClaims,
getOidcClientResourceScopes,
} from './oidcClientRegistry.js';
PERMISSION_CLAIMS,
providerTokenClaims,
} from './oidcAccountClaims.js';
import { deriveAcrAmr, resolveCurrentSession, sessionAuthTime } from './oidcAuthContext.js';
import { findActiveOidcClient, getOidcClientResourceScopes } from './oidcClientRegistry.js';
import { hasOidcGrantForSession, recordSessionExchangeToken } from './oidcPayloadStore.js';
import { getActiveOidcSigningKey, OidcProviderKeysError } from './oidcProviderKeys.js';

Expand Down Expand Up @@ -79,15 +82,41 @@ const ALLOWED_CLAIMS: Record<OidcSignRequest['kind'], ReadonlySet<string>> = {
]),
};

// Released by scope, so they may be present, but only with the account's own values.
const IDENTITY_CLAIMS = [
// Released by scope, so they may be present, but only with the values the API computes for the
// account and client. Custom claims (ADR 0005 E6) are any other name a custom claim may have.
const ACCOUNT_CLAIMS = new Set<string>([
'email',
'email_verified',
'phone_number',
'phone_number_verified',
'roles',
'org_id',
] as const;
...PERMISSION_CLAIMS,
]);

function isAccountClaimName(claim: string) {
return (
ACCOUNT_CLAIMS.has(claim) ||
(CUSTOM_CLAIM_NAME_PATTERN.test(claim) && !isReservedClaimName(claim))
);
}

/** JSON equality that ignores object key order, which a JSONB round trip does not keep. */
function canonical(value: unknown): unknown {
if (Array.isArray(value)) return value.map(canonical);
if (value && typeof value === 'object') {
return Object.fromEntries(
Object.keys(value)
.sort()
.map((key) => [key, canonical((value as JsonObject)[key])]),
);
}
return value;
}

function sameJson(a: unknown, b: unknown) {
return JSON.stringify(canonical(a ?? null)) === JSON.stringify(canonical(b ?? null));
}

function isSessionExchangeToken(request: OidcSignRequest, claims: JsonObject) {
return request.kind === 'access_token' && scopesOf(claims).includes(SESSION_EXCHANGE_SCOPE);
Expand Down Expand Up @@ -186,9 +215,7 @@ export async function signForOidcEdge(request: OidcSignRequest): Promise<OidcSig
const allowsIdentity = request.kind !== 'client_credentials';
if (
Object.keys(claims).some(
(claim) =>
!allowed.has(claim) &&
!(allowsIdentity && (IDENTITY_CLAIMS as readonly string[]).includes(claim)),
(claim) => !allowed.has(claim) && !(allowsIdentity && isAccountClaimName(claim)),
)
) {
return refuse('malformed_signing_input');
Expand Down Expand Up @@ -323,14 +350,10 @@ async function checkUserToken(
return refuse('auth_context_mismatch', session.userId);
}

if (IDENTITY_CLAIMS.some((claim) => claim in claims)) {
const account = await getOidcAccountClaims(session.userId);
const mismatch = IDENTITY_CLAIMS.some(
(claim) =>
claim in claims &&
JSON.stringify(claims[claim]) !== JSON.stringify(account?.[claim] ?? null),
);
if (!account || mismatch) return refuse('subject_mismatch', session.userId);
const released = Object.keys(claims).filter((claim) => !ALLOWED_CLAIMS[request.kind].has(claim));
if (released.length > 0) {
const refusal = await checkAccountClaims(session, client.id, claims, released);
if (refusal) return refusal;
}

if (request.kind === 'id_token') {
Expand All @@ -351,6 +374,46 @@ async function checkUserToken(
: null;
}

/**
* The edge releases account claims by scope, but every value is the API's: it computes them
* again here for this session and client, the same way `/oidc/accounts/:id` did, and signs
* only what matches. A custom claim name it did not compute is one it never checked. The
* permission claims and the custom claims are each carried whole or not at all (ADR 0005 E6),
* since a partial list looks complete. Each is `claims_mismatch`: a change since the edge's
* read looks the same as a forgery, so the edge reads the account again and retries once.
*/
async function checkAccountClaims(
session: NonNullable<Awaited<ReturnType<typeof resolveCurrentSession>>>,
clientId: string,
claims: JsonObject,
released: string[],
): Promise<OidcSignOutcome | null> {
const account = await getOidcAccountClaims(session, clientId);
if (!account) return refuse('subject_mismatch', session.userId);

const expected = providerTokenClaims(account);
if (
released.some(
(claim) =>
(!ACCOUNT_CLAIMS.has(claim) && !(claim in expected)) ||
!sameJson(claims[claim], expected[claim]),
)
) {
return refuse('claims_mismatch', session.userId);
}

const sets = [
PERMISSION_CLAIMS.filter((claim) => claim in expected),
Object.keys(account.customClaims),
];
for (const set of sets) {
const carried = set.filter((claim) => claim in claims).length;
if (carried > 0 && carried < set.length) return refuse('claims_mismatch', session.userId);
}

return null;
}

/** ADR 0003, X2: a token useful nowhere else, that lives briefly and can be told apart. */
function checkSessionExchangeToken(
request: OidcSignRequest,
Expand Down
Loading
Loading