@schbang/payload-sso 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Schbang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,115 @@
1
- # Temporary Holding Version
1
+ # @schbang/payload-sso
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ OpenID Connect single sign-on for [Payload CMS](https://payloadcms.com) 3.x. It works with Okta, Azure AD (Entra ID), Google Workspace, Keycloak and any other standard OIDC provider.
4
+
5
+ - Users are created on their first SSO login.
6
+ - IdP groups are mapped to Payload roles on every login, so the IdP stays the source of truth.
7
+ - Email and password login keeps working for local accounts.
8
+ - An SSO login creates a normal Payload session, so logout, refresh, session revocation and the admin panel work unchanged.
9
+ - Built on [`openid-client`](https://github.com/panva/openid-client) and [`jose`](https://github.com/panva/jose). No hand-written crypto.
10
+
11
+ Read [SECURITY.md](./SECURITY.md) before you deploy this.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ pnpm add @schbang/payload-sso
17
+ ```
18
+
19
+ ```ts
20
+ // payload.config.ts
21
+ import { ssoPlugin } from '@schbang/payload-sso'
22
+
23
+ export default buildConfig({
24
+ serverURL: process.env.NEXT_PUBLIC_SERVER_URL, // required, https in production
25
+ plugins: [
26
+ ssoPlugin({
27
+ providers: [
28
+ {
29
+ id: 'okta',
30
+ label: 'Okta',
31
+ type: 'oidc',
32
+ issuer: process.env.OKTA_ISSUER!, // e.g. https://acme.okta.com/oauth2/default
33
+ clientId: process.env.OKTA_CLIENT_ID!,
34
+ clientSecret: process.env.OKTA_CLIENT_SECRET!,
35
+ scopes: ['openid', 'email', 'profile', 'groups'],
36
+ allowedEmailDomains: ['acme.com'],
37
+ },
38
+ ],
39
+ roles: {
40
+ values: ['admin', 'editor', 'viewer'],
41
+ default: 'viewer',
42
+ mapping: { 'cms-admins': 'admin', 'cms-editors': 'editor' },
43
+ },
44
+ }),
45
+ ],
46
+ })
47
+ ```
48
+
49
+ Then run `payload generate:importmap` (this adds the "Sign in with …" buttons) and `payload generate:types`. On SQL databases, also create a migration.
50
+
51
+ In the IdP, register a web application (confidential client) with this redirect URI:
52
+
53
+ ```
54
+ <serverURL>/api/<users-collection>/sso/<provider id>/callback
55
+ ```
56
+
57
+ ## Providers
58
+
59
+ | IdP | `issuer` | Restrict sign-in with | Groups |
60
+ | --- | --- | --- | --- |
61
+ | Okta | `https://<org>.okta.com/oauth2/<server>` | `allowedEmailDomains` | Add a `groups` claim to the ID token and request the `groups` scope |
62
+ | Azure AD / Entra ID | `https://login.microsoftonline.com/<tenant-id>/v2.0` | `azureTenantId`, required and equal to the issuer's tenant (+ `allowedEmailDomains`) | Enable "groups" in token configuration; the values are group **object IDs**, so map those |
63
+ | Google Workspace | `https://accounts.google.com` | `googleHostedDomain`, required (+ `allowedEmailDomains`) | Not available over OIDC: users get `roles.default` |
64
+ | Keycloak | `https://<host>/realms/<realm>` | `allowedEmailDomains` | Add a "Group Membership" mapper (full path off) |
65
+
66
+ Azure `common`, `organizations` and `consumers` issuers and the personal-account tenant are refused, and Azure guest accounts are refused at login. The IdP must mark the email as verified (`email_verified: true`). The exception is a tenant-pinned Azure issuer, because Azure doesn't send that claim. Only plain ASCII email addresses are accepted.
67
+
68
+ ## Options
69
+
70
+ | Option | Default | Description |
71
+ | --- | --- | --- |
72
+ | `collection` | `admin.user` | Auth collection that users sign into |
73
+ | `providers[]` | required | See the provider fields below |
74
+ | `roles.values` | required | Allowed role values |
75
+ | `roles.default` | required | Role every SSO user gets |
76
+ | `roles.mapping` | `{}` | IdP group → role or roles |
77
+ | `roles.field` | `'roles'` | Field that stores roles. It is added as a hasMany select if missing |
78
+ | `roles.adminRole` | `'admin'` | May manage roles. The very first user gets this role |
79
+ | `roles.canManage` | user has `adminRole` | Custom check for who may edit roles |
80
+ | `autoProvision` | `true` | Create users on their first SSO login |
81
+ | `allowPasswordLoginForSSOUsers` | `false` | Let SSO-linked users also sign in or reset their password with a password |
82
+ | `maxSessionHours` | `12` | After this long, refresh is refused and the user must sign in through the IdP again |
83
+
84
+ The plugin also sets safe access on the users collection, but only for the access functions you leave unset: create, delete and unlock for role managers, update for yourself or role managers. On https it marks the session cookie Secure.
85
+
86
+ Provider fields:
87
+
88
+ - `id`: lowercase letters, numbers and hyphens.
89
+ - `label`: the button text.
90
+ - `type: 'oidc'`.
91
+ - `issuer`, `clientId`, `clientSecret`.
92
+ - `scopes`: default `openid email profile`.
93
+ - `allowedEmailDomains`, `googleHostedDomain`, `azureTenantId`: who may sign in. With `autoProvision`, at least one is required.
94
+ - `groupsClaim`: default `groups`.
95
+ - `linkByEmail`: default `false`. Links an existing account with the same email, but only if the IdP marks the email as verified. Linking signs out the account's existing sessions and disables its password and API key.
96
+ - `allowInsecureIssuer`: allows an http issuer on localhost, for development only. It is refused in production.
97
+
98
+ The plugin refuses to start when the configuration is unsafe. That includes a missing or non-https `serverURL`, an http issuer, Azure `common`, auto-provisioning with no domain or tenant restriction, and unknown roles.
99
+
100
+ ## How a login works
101
+
102
+ 1. The button sends the browser to `/api/users/sso/<id>/authorize`. That endpoint sets a short-lived encrypted cookie holding `state`, `nonce`, the PKCE verifier and where to return to, then redirects to the IdP.
103
+ 2. The IdP redirects back to `/api/users/sso/<id>/callback`. `openid-client` exchanges the code and checks the ID token: signature, issuer, audience, expiry and nonce.
104
+ 3. The plugin applies the domain, tenant and verified-email rules, then finds the user by IdP identity (issuer + subject). If none matches, it either links an existing account (only with `linkByEmail`) or creates a new user. Roles are recalculated from groups.
105
+ 4. A normal Payload session is created, and the browser is sent back to the admin panel.
106
+
107
+ Any failure sends the user to `/admin/login?sso=error` with a generic message. The specific reason goes to the server log.
108
+
109
+ ## Local testing
110
+
111
+ The repository's dev harness includes a Keycloak realm (`dev/keycloak`). Start it with `docker compose up -d`. It provides test users and groups for checking the whole flow before you connect a real IdP.
112
+
113
+ ## License
114
+
115
+ MIT
package/SECURITY.md ADDED
@@ -0,0 +1,52 @@
1
+ # Security notes: @schbang/payload-sso
2
+
3
+ This plugin decides who gets into the CMS admin panel. Read this before you deploy it.
4
+
5
+ ## Threat model and protections
6
+
7
+ | Threat | Protection |
8
+ | --- | --- |
9
+ | **Login CSRF / session fixation.** An attacker signs a victim in as the attacker. | `state`, `nonce` and the PKCE (S256) verifier are sealed in an encrypted, single-use cookie bound to the browser. The cookie is `__Host-` prefixed on https, HttpOnly and SameSite=Lax, lives 10 minutes and is cleared on every callback. A callback without the matching cookie fails. |
10
+ | **Code interception or replay** | PKCE, a single-use transaction cookie and single-use authorization codes. |
11
+ | **Forged or tampered ID token** | `openid-client` checks the signature against the IdP's JWKS (non-repudiation checks on), plus `iss`, `aud`, `exp`, `nonce` and `azp`. |
12
+ | **Open redirect** | `returnTo` must be a same-origin path, and must also pass Payload's `getSafeRedirect`. It is sealed in the encrypted cookie. |
13
+ | **Host-header injection** | `redirect_uri` and the token-exchange URL are built from `serverURL`. The Host header is never used. |
14
+ | **Wrong tenant or domain** | `allowedEmailDomains` must match the domain exactly. A Google issuer must have `googleHostedDomain`. Azure issuers must be tenant-pinned (`common`, `organizations` and the consumer tenant are refused), `tid` is checked, and guest accounts (an `idp` claim) are refused. |
15
+ | **Unverified email** | `email_verified` must be `true`. The exception is a tenant-pinned Azure issuer, where the tenant's own admins set the email. |
16
+ | **Account takeover by email (nOAuth)** | Users are matched on issuer + subject. Email linking is off by default. When it is on, the IdP must vouch for the email, the local account must have verified it (if verification is enabled), and linking revokes all existing sessions, the old password and API keys. An account that is already linked is never linked to a second identity, and SSO users can't change their own email (the IdP owns it). |
17
+ | **Unicode look-alike emails** | Only plain ASCII addresses are accepted. The check runs before lowercasing. |
18
+ | **Privilege escalation** | Only role managers (`roles.canManage`, default: the `admin` role) can set roles. `ssoIdentities` can only be written by the plugin. Where the host sets no access, the auth collection gets safe defaults: create, delete and unlock for role managers; update for yourself or role managers. |
19
+ | **Password fallback bypass** | SSO-linked users cannot log in with a password, reset their password, change it or enable API keys (unless `allowPasswordLoginForSSOUsers` is set). |
20
+ | **Stale access after IdP changes** | Roles are recalculated on every SSO login. Refresh is refused once a session is older than `maxSessionHours` (default 12), which forces a new IdP login. |
21
+ | **Locked or gated accounts** | Locked accounts are refused. The host's `beforeLogin` hooks run for SSO logins too. |
22
+ | **Information leaks** | The browser always gets the same generic error. Logs contain only a short reason, not tokens or claims. |
23
+ | **Unsafe configuration** | The plugin refuses to start with `auth.useSessions: false` (session revocation and the refresh cap need it), without an https `serverURL`, with an http issuer (except localhost in development), with an untrusted Azure or Google setup, with auto-provisioning or linking but no domain or tenant restriction, or with unknown roles. |
24
+
25
+ ## Deployment checklist
26
+
27
+ 1. Serve the app over **https** and set `serverURL` to that https origin. The plugin then marks the session cookie Secure.
28
+ 2. Keep `clientSecret` and `PAYLOAD_SECRET` in environment variables or a secret manager. Rotating `PAYLOAD_SECRET` invalidates all sessions and in-flight logins.
29
+ 3. Register exactly one redirect URI per provider in the IdP: `<serverURL>/api/<users>/sso/<id>/callback`.
30
+ 4. Restrict who may sign in. Use `allowedEmailDomains`, plus `azureTenantId` (Azure) or `googleHostedDomain` (Google). In the IdP, assign the app only to the people who need it.
31
+ 5. Groups:
32
+ - **Okta:** add a `groups` claim to the ID token.
33
+ - **Azure:** emit group object IDs, and map those IDs. With more than 200 groups Azure sends an overflow reference instead, and users get only the default role.
34
+ - **Keycloak:** add a group membership mapper. Prefer full paths, so a subgroup can't impersonate `cms-admins`.
35
+ 6. If you define your own `access` on the users collection, make sure non-admins can't edit, delete or create other users. The plugin's safe defaults apply only to the access functions you leave unset.
36
+ 7. Keep `auth.tokenExpiration` short (the default is 2 hours) and `maxSessionHours` at the longest time a removed employee may keep access.
37
+ 8. Add rate limiting for `/api/*/sso/*` at your proxy or CDN.
38
+
39
+ ## Known gaps
40
+
41
+ - **No IdP logout.** Logging out of Payload ends the Payload session only. The IdP session stays, so on a shared computer the next person can click "Sign in with …" and get in without a password. Users of shared computers must also sign out of the IdP.
42
+ - **No push deprovisioning (SCIM / back-channel logout).** A user removed from the IdP keeps access until their token expires or `maxSessionHours` passes, whichever comes first. Deleting an SSO user in the CMS doesn't block them either: auto-provisioning recreates them on their next login. Remove them in the IdP.
43
+ - **Google Workspace groups** are not available over OIDC, so Google users get only the default role.
44
+ - **No built-in rate limiting.**
45
+ - **Session internals.** The plugin writes Payload's `sessions` entries the same way Payload does internally. The peer range is limited to versions covered by the session canary test; check that test before you upgrade Payload.
46
+ - **Azure guest detection** relies on Entra putting an `idp` claim in guest ID tokens. This hasn't been tested against a live tenant yet, so add `allowedEmailDomains` as a second check.
47
+ - **Concurrent edits on Postgres or Mongo.** The callback runs in a transaction, but an admin editing the same user in the same instant could be overwritten by the login. SQLite serialises writes, so it isn't affected.
48
+ - **First user.** As in plain Payload, whoever completes "create first user" on an empty deployment becomes admin.
49
+
50
+ ## Reporting
51
+
52
+ Report security issues privately to the Schbang engineering team, not in public issues.
@@ -0,0 +1,18 @@
1
+ type Props = {
2
+ ssoCollection: string;
3
+ ssoProviders: {
4
+ id: string;
5
+ label: string;
6
+ }[];
7
+ payload?: {
8
+ config: {
9
+ routes: {
10
+ api: string;
11
+ };
12
+ };
13
+ };
14
+ searchParams?: Record<string, string | string[] | undefined>;
15
+ };
16
+ /** Server component under the login form: one link per provider, no client JS. */
17
+ export declare const SSOButtons: ({ ssoCollection, ssoProviders, payload, searchParams }: Props) => import("react/jsx-runtime").JSX.Element;
18
+ export {};
@@ -0,0 +1,8 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /** Server component under the login form: one link per provider, no client JS. */
3
+ export const SSOButtons = ({ ssoCollection, ssoProviders, payload, searchParams }) => {
4
+ const api = payload?.config.routes.api ?? '/api';
5
+ const failed = searchParams?.sso === 'error';
6
+ const redirect = typeof searchParams?.redirect === 'string' ? searchParams.redirect : undefined;
7
+ return (_jsxs("div", { style: { display: 'grid', gap: 8, marginTop: 24 }, children: [failed && (_jsx("p", { role: "alert", style: { color: 'var(--theme-error-500)', margin: 0 }, children: "Single sign-on failed. Try again or contact your administrator." })), ssoProviders.map((p) => (_jsxs("a", { className: "btn btn--style-secondary btn--size-large", href: `${api}/${ssoCollection}/sso/${encodeURIComponent(p.id)}/authorize${redirect ? `?returnTo=${encodeURIComponent(redirect)}` : ''}`, children: ["Sign in with ", p.label] }, p.id)))] }));
8
+ };
@@ -0,0 +1,3 @@
1
+ import { type Endpoint } from 'payload';
2
+ import type { ResolvedOptions } from './options.js';
3
+ export declare const makeEndpoints: (opts: ResolvedOptions) => Endpoint[];
@@ -0,0 +1,121 @@
1
+ import { commitTransaction, generateCookie, initTransaction, killTransaction, parseCookies, } from 'payload';
2
+ import { client, getOIDCConfig } from './oidc.js';
3
+ import { resolveUser, SSOError } from './provision.js';
4
+ import { safeReturnTo } from './redirect.js';
5
+ import { startSession } from './session.js';
6
+ import { openTx, sealTx, TX_COOKIE, TX_TTL_SECONDS } from './txCookie.js';
7
+ export const makeEndpoints = (opts) => {
8
+ const secure = opts.serverURL.startsWith('https:');
9
+ // __Host- cookies can't be set by sibling subdomains (cookie tossing); the prefix needs Secure + Path=/.
10
+ const cookieName = secure ? `__Host-${TX_COOKIE}` : TX_COOKIE;
11
+ const providers = new Map(opts.providers.map((p) => [p.id, p]));
12
+ const paths = (req) => {
13
+ const { routes } = req.payload.config;
14
+ const base = `${routes.api}/${opts.collection}/sso`;
15
+ return { base, admin: routes.admin, loginError: `${routes.admin}/login?sso=error` };
16
+ };
17
+ const txCookie = (req, value, maxAge) => generateCookie({
18
+ name: cookieName,
19
+ value,
20
+ path: secure ? '/' : paths(req).base,
21
+ httpOnly: true,
22
+ sameSite: 'Lax', // must survive the top-level redirect back from the IdP
23
+ secure,
24
+ maxAge,
25
+ returnCookieAsObject: false,
26
+ });
27
+ const redirect = (location, cookies = []) => {
28
+ const headers = new Headers({ Location: location, 'Cache-Control': 'no-store' });
29
+ for (const c of cookies)
30
+ headers.append('Set-Cookie', c);
31
+ return new Response(null, { status: 302, headers });
32
+ };
33
+ const authorize = {
34
+ path: '/sso/:provider/authorize',
35
+ method: 'get',
36
+ handler: async (req) => {
37
+ const p = providers.get(String(req.routeParams?.provider));
38
+ if (!p)
39
+ return Response.json({ error: 'Unknown provider' }, { status: 404 });
40
+ try {
41
+ const config = await getOIDCConfig(p);
42
+ const returnTo = safeReturnTo(req.searchParams.get('returnTo'), paths(req).admin);
43
+ const tx = {
44
+ provider: p.id,
45
+ state: client.randomState(),
46
+ nonce: client.randomNonce(),
47
+ verifier: client.randomPKCECodeVerifier(),
48
+ returnTo,
49
+ };
50
+ const url = client.buildAuthorizationUrl(config, {
51
+ redirect_uri: `${opts.serverURL}${paths(req).base}/${p.id}/callback`,
52
+ response_type: 'code',
53
+ scope: (p.scopes ?? ['openid', 'email', 'profile']).join(' '),
54
+ state: tx.state,
55
+ nonce: tx.nonce,
56
+ code_challenge: await client.calculatePKCECodeChallenge(tx.verifier),
57
+ code_challenge_method: 'S256',
58
+ ...(p.googleHostedDomain ? { hd: p.googleHostedDomain } : {}),
59
+ });
60
+ return redirect(url.href, [txCookie(req, await sealTx(tx, req.payload.secret), TX_TTL_SECONDS)]);
61
+ }
62
+ catch (err) {
63
+ req.payload.logger.error({ err, msg: `[payload-sso] ${p.id}: authorize failed` });
64
+ return redirect(paths(req).loginError);
65
+ }
66
+ },
67
+ };
68
+ const callback = {
69
+ path: '/sso/:provider/callback',
70
+ method: 'get',
71
+ handler: async (req) => {
72
+ const { loginError, base } = paths(req);
73
+ const clear = txCookie(req, '', 0); // one-time: always cleared
74
+ const p = providers.get(String(req.routeParams?.provider));
75
+ if (!p)
76
+ return redirect(loginError, [clear]);
77
+ try {
78
+ const tx = await openTx(parseCookies(req.headers).get(cookieName), req.payload.secret);
79
+ if (!tx)
80
+ throw new SSOError('missing, expired or invalid transaction cookie');
81
+ if (tx.provider !== p.id)
82
+ throw new SSOError('transaction is for another provider');
83
+ // Built from serverURL, not the Host header; only the query string comes from the request.
84
+ const currentUrl = new URL(`${opts.serverURL}${base}/${p.id}/callback`);
85
+ currentUrl.search = new URL(req.url ?? '', 'http://x.invalid').search;
86
+ const config = await getOIDCConfig(p);
87
+ const tokens = await client.authorizationCodeGrant(config, currentUrl, {
88
+ pkceCodeVerifier: tx.verifier,
89
+ expectedState: tx.state,
90
+ expectedNonce: tx.nonce,
91
+ idTokenExpected: true,
92
+ });
93
+ const claims = tokens.claims();
94
+ if (!claims)
95
+ throw new SSOError('no id_token claims');
96
+ // User sync and session creation succeed or fail together.
97
+ const shouldCommit = await initTransaction(req);
98
+ try {
99
+ const { user, linked } = await resolveUser(p, claims, opts, req);
100
+ const session = await startSession(req, opts.collection, user, { revokeOthers: linked });
101
+ if (shouldCommit)
102
+ await commitTransaction(req);
103
+ return redirect(tx.returnTo, [clear, session]);
104
+ }
105
+ catch (err) {
106
+ await killTransaction(req);
107
+ throw err;
108
+ }
109
+ }
110
+ catch (err) {
111
+ // Log the reason only: library errors can carry IdP responses and claims (PII).
112
+ const reason = err instanceof SSOError
113
+ ? err.message
114
+ : `${err?.name ?? 'Error'}: ${String(err?.message ?? err).slice(0, 200)}`;
115
+ req.payload.logger.warn(`[payload-sso] ${p.id}: login refused: ${reason}`);
116
+ return redirect(loginError, [clear]);
117
+ }
118
+ },
119
+ };
120
+ return [authorize, callback];
121
+ };
@@ -0,0 +1 @@
1
+ export { SSOButtons } from '../components/SSOButtons.js';
@@ -0,0 +1 @@
1
+ export { SSOButtons } from '../components/SSOButtons.js';
@@ -0,0 +1,15 @@
1
+ import { type Access, type CollectionBeforeChangeHook, type CollectionBeforeLoginHook, type CollectionBeforeOperationHook, type FieldAccess } from 'payload';
2
+ import type { ResolvedOptions } from './options.js';
3
+ export declare const makeGuards: (opts: ResolvedOptions) => {
4
+ beforeLogin: CollectionBeforeLoginHook;
5
+ beforeOperation: CollectionBeforeOperationHook;
6
+ beforeChange: CollectionBeforeChangeHook;
7
+ canSetRoles: FieldAccess;
8
+ canReadIdentities: FieldAccess;
9
+ collectionAccess: {
10
+ create: Access;
11
+ update: Access;
12
+ delete: Access;
13
+ unlock: Access;
14
+ };
15
+ };
package/dist/guards.js ADDED
@@ -0,0 +1,80 @@
1
+ import { APIError, } from 'payload';
2
+ import { ssoSessionStartedAt } from './session.js';
3
+ const isSSOUser = (doc) => Array.isArray(doc?.ssoIdentities) &&
4
+ doc.ssoIdentities.length > 0;
5
+ const ssoOnly = () => new APIError('This account signs in with single sign-on.', 403);
6
+ export const makeGuards = (opts) => {
7
+ const allowPw = opts.allowPasswordLoginForSSOUsers;
8
+ const maxSessionMs = opts.maxSessionHours * 3_600_000;
9
+ const canManage = (req) => Promise.resolve(opts.roles.canManage(req));
10
+ const countUsers = async (req) => (await req.payload.count({ collection: opts.collection, overrideAccess: true, req })).totalDocs;
11
+ /** Password login for SSO-linked users (e.g. someone removed from the IdP). Skipped for the SSO login itself. */
12
+ const beforeLogin = ({ context, user }) => {
13
+ if (!allowPw && !context.ssoSync && isSSOUser(user))
14
+ throw ssoOnly();
15
+ return user;
16
+ };
17
+ const beforeOperation = async ({ args, operation, req }) => {
18
+ // Password reset logs the user in, so block it for SSO-linked users too.
19
+ if (operation === 'resetPassword' && !allowPw) {
20
+ const token = args.data?.token;
21
+ if (typeof token === 'string' && token) {
22
+ const user = await req.payload.db.findOne({
23
+ collection: opts.collection,
24
+ req,
25
+ where: { resetPasswordToken: { equals: token } },
26
+ });
27
+ if (isSSOUser(user))
28
+ throw ssoOnly();
29
+ }
30
+ }
31
+ // Refresh can't re-check the IdP, so cap how long an SSO session can be kept alive.
32
+ if (operation === 'refresh') {
33
+ const startedAt = ssoSessionStartedAt(req.user?._sid);
34
+ if (startedAt !== null && Date.now() - startedAt > maxSessionMs) {
35
+ throw new APIError('Your single sign-on session has expired. Please sign in again.', 401);
36
+ }
37
+ }
38
+ return args;
39
+ };
40
+ const beforeChange = async ({ context, data, operation, originalDoc, req }) => {
41
+ if (operation === 'create' && !context.ssoSync && (await countUsers(req)) === 0) {
42
+ // The very first user becomes admin, so someone can manage roles afterwards.
43
+ data[opts.roles.field] = [opts.roles.adminRole];
44
+ }
45
+ if (!allowPw && operation === 'update' && !context.ssoSync && isSSOUser(originalDoc)) {
46
+ // Password changes and API keys would give SSO-linked users a way in that skips the IdP.
47
+ if (data.password)
48
+ throw ssoOnly();
49
+ if (data.enableAPIKey === true || (typeof data.apiKey === 'string' && data.apiKey))
50
+ throw ssoOnly();
51
+ }
52
+ // The IdP owns an SSO user's email; changing it could be used to squat a colleague's address.
53
+ if (operation === 'update' &&
54
+ !context.ssoSync &&
55
+ isSSOUser(originalDoc) &&
56
+ typeof data.email === 'string' &&
57
+ data.email.toLowerCase() !== String(originalDoc?.email ?? '').toLowerCase() &&
58
+ !(await canManage(req))) {
59
+ throw new APIError('The email of a single sign-on account is managed by the identity provider.', 403);
60
+ }
61
+ return data;
62
+ };
63
+ /** Only role managers may set roles; the very first user may (beforeChange then forces adminRole). */
64
+ const canSetRoles = async ({ req }) => (await canManage(req)) || (await countUsers(req)) === 0;
65
+ const isSelf = (req, id) => Boolean(req.user && req.user.collection === opts.collection && id !== undefined && String(req.user.id) === String(id));
66
+ /** Read own identities, or any if you manage roles. */
67
+ const canReadIdentities = async ({ req, id }) => isSelf(req, id) || (await canManage(req));
68
+ /**
69
+ * Safe defaults for the auth collection's own access, used only where the host left it unset.
70
+ * Payload's default lets any signed-in user create, edit and delete every user, which SSO
71
+ * auto-provisioning would hand to every employee.
72
+ */
73
+ const collectionAccess = {
74
+ create: (async ({ req }) => (await canManage(req)) || (await countUsers(req)) === 0),
75
+ update: (async ({ req, id }) => isSelf(req, id) || (await canManage(req))),
76
+ delete: (async ({ req }) => canManage(req)),
77
+ unlock: (async ({ req }) => canManage(req)),
78
+ };
79
+ return { beforeLogin, beforeOperation, beforeChange, canSetRoles, canReadIdentities, collectionAccess };
80
+ };
@@ -0,0 +1,7 @@
1
+ export { ssoPlugin } from './plugin.js';
2
+ export type { OIDCProvider, SSOPluginOptions } from './options.js';
3
+ export { safeReturnTo } from './redirect.js';
4
+ export { openTx, sealTx, TX_COOKIE } from './txCookie.js';
5
+ export { ssoSessionStartedAt, startSession } from './session.js';
6
+ export { checkPolicy, resolveUser, rolesFor } from './provision.js';
7
+ export { resolveOptions } from './options.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { ssoPlugin } from './plugin.js';
2
+ export { safeReturnTo } from './redirect.js';
3
+ export { openTx, sealTx, TX_COOKIE } from './txCookie.js';
4
+ export { ssoSessionStartedAt, startSession } from './session.js';
5
+ export { checkPolicy, resolveUser, rolesFor } from './provision.js';
6
+ export { resolveOptions } from './options.js';
package/dist/oidc.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import * as client from 'openid-client';
2
+ import type { OIDCProvider } from './options.js';
3
+ /** Discovery is cached per provider; a failed discovery is retried on the next login. */
4
+ export declare const getOIDCConfig: (p: OIDCProvider) => Promise<client.Configuration>;
5
+ export { client };
package/dist/oidc.js ADDED
@@ -0,0 +1,18 @@
1
+ import * as client from 'openid-client';
2
+ const configs = new Map();
3
+ /** Discovery is cached per provider; a failed discovery is retried on the next login. */
4
+ export const getOIDCConfig = (p) => {
5
+ let cfg = configs.get(p.id);
6
+ if (!cfg) {
7
+ const insecure = p.allowInsecureIssuer && new URL(p.issuer).protocol === 'http:';
8
+ cfg = client.discovery(new URL(p.issuer), p.clientId, p.clientSecret, undefined, {
9
+ // Verify the ID token signature against the IdP's JWKS too, not only TLS.
10
+ execute: [client.enableNonRepudiationChecks, ...(insecure ? [client.allowInsecureRequests] : [])],
11
+ timeout: 10,
12
+ });
13
+ cfg.catch(() => configs.delete(p.id));
14
+ configs.set(p.id, cfg);
15
+ }
16
+ return cfg;
17
+ };
18
+ export { client };
@@ -0,0 +1,61 @@
1
+ import type { CollectionSlug, Config, PayloadRequest } from 'payload';
2
+ export type OIDCProvider = {
3
+ id: string;
4
+ label: string;
5
+ type: 'oidc';
6
+ /** Tenant-specific for Azure: https://login.microsoftonline.com/<tenant-id>/v2.0 */
7
+ issuer: string;
8
+ clientId: string;
9
+ clientSecret: string;
10
+ /** Default ['openid', 'email', 'profile'] */
11
+ scopes?: string[];
12
+ /** Exact email domains allowed to sign in, e.g. ['schbang.com'] */
13
+ allowedEmailDomains?: string[];
14
+ /** Google Workspace domain; checked against the `hd` claim */
15
+ googleHostedDomain?: string;
16
+ /** Azure tenant id; checked against the `tid` claim */
17
+ azureTenantId?: string;
18
+ /** Claim holding the user's groups. Default 'groups' */
19
+ groupsClaim?: string;
20
+ /** Link an existing account with the same email (only when the IdP says email_verified). Default false */
21
+ linkByEmail?: boolean;
22
+ /** Allow an http:// issuer. Only for localhost, refused when NODE_ENV=production */
23
+ allowInsecureIssuer?: boolean;
24
+ };
25
+ export type SSOPluginOptions = {
26
+ /** Auth collection to sign users into. Default: config.admin.user */
27
+ collection?: string;
28
+ providers: OIDCProvider[];
29
+ roles: {
30
+ /** Default 'roles'. Added as a hasMany select if the collection lacks it */
31
+ field?: string;
32
+ values: string[];
33
+ /** Given to every SSO user */
34
+ default: string;
35
+ /** Role that may manage roles, and that the first user gets. Default 'admin' */
36
+ adminRole?: string;
37
+ /** IdP group -> role(s) */
38
+ mapping?: Record<string, string | string[]>;
39
+ /** Who may change roles. Default: the user has adminRole */
40
+ canManage?: (req: PayloadRequest) => boolean | Promise<boolean>;
41
+ };
42
+ /** Create users on first SSO login. Default true */
43
+ autoProvision?: boolean;
44
+ /** Let SSO-linked users also sign in with a password. Default false */
45
+ allowPasswordLoginForSSOUsers?: boolean;
46
+ /**
47
+ * Hours an SSO session may be kept alive by refreshing before the user must sign in
48
+ * through the IdP again (which re-checks groups and account status). Default 12
49
+ */
50
+ maxSessionHours?: number;
51
+ };
52
+ export type ResolvedOptions = Required<Omit<SSOPluginOptions, 'roles' | 'collection'>> & {
53
+ collection: CollectionSlug;
54
+ roles: Required<Omit<SSOPluginOptions['roles'], 'mapping' | 'canManage'>> & {
55
+ mapping: Record<string, string[]>;
56
+ canManage: (req: PayloadRequest) => boolean | Promise<boolean>;
57
+ };
58
+ serverURL: string;
59
+ };
60
+ /** Throws on any configuration that would be unsafe to run. */
61
+ export declare const resolveOptions: (opts: SSOPluginOptions, config: Config) => ResolvedOptions;
@@ -0,0 +1,123 @@
1
+ const ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
2
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
3
+ const MICROSOFT_HOSTS = new Set(['login.microsoftonline.com', 'login.microsoft.com', 'sts.windows.net', 'login.windows.net']);
4
+ const GOOGLE_HOSTS = new Set(['accounts.google.com']);
5
+ const AZURE_TENANT_PATH = /^\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(\/v2\.0)?\/?$/i;
6
+ const MSA_CONSUMER_TENANT = '9188040d-6c67-4c5b-b112-36a304b66dad';
7
+ /** Throws on any configuration that would be unsafe to run. */
8
+ export const resolveOptions = (opts, config) => {
9
+ const fail = (msg) => {
10
+ throw new Error(`[payload-sso] ${msg}`);
11
+ };
12
+ const collection = opts.collection ?? config.admin?.user;
13
+ if (!collection)
14
+ fail('set `collection` or config.admin.user');
15
+ const target = config.collections?.find((c) => c.slug === collection);
16
+ if (!target?.auth)
17
+ fail(`collection "${collection}" must be an auth collection`);
18
+ if (typeof target.auth === 'object' && target.auth.useSessions === false) {
19
+ fail(`collection "${collection}" must keep auth.useSessions on (needed to revoke and cap SSO sessions)`);
20
+ }
21
+ // Callback URLs are built from serverURL, never from the Host header.
22
+ const serverURL = config.serverURL?.replace(/\/+$/, '');
23
+ if (!serverURL)
24
+ fail('config.serverURL is required');
25
+ let server;
26
+ try {
27
+ server = new URL(serverURL);
28
+ }
29
+ catch {
30
+ return fail('config.serverURL is not a valid URL');
31
+ }
32
+ if (server.protocol !== 'https:' && !LOCAL_HOSTS.has(server.hostname)) {
33
+ fail('config.serverURL must use https outside localhost');
34
+ }
35
+ if (!opts.providers?.length)
36
+ fail('at least one provider is required');
37
+ const autoProvision = opts.autoProvision ?? true;
38
+ const ids = new Set();
39
+ for (const p of opts.providers) {
40
+ if (p.type !== 'oidc')
41
+ fail(`provider "${p.id}": only type 'oidc' is supported`);
42
+ if (!ID_RE.test(p.id))
43
+ fail(`provider id "${p.id}" must match ${ID_RE}`);
44
+ if (ids.has(p.id))
45
+ fail(`duplicate provider id "${p.id}"`);
46
+ ids.add(p.id);
47
+ if (!p.clientId || !p.clientSecret)
48
+ fail(`provider "${p.id}": clientId and clientSecret are required`);
49
+ let issuer;
50
+ try {
51
+ issuer = new URL(p.issuer);
52
+ }
53
+ catch {
54
+ return fail(`provider "${p.id}": issuer is not a valid URL`);
55
+ }
56
+ if (issuer.protocol !== 'https:') {
57
+ if (!p.allowInsecureIssuer)
58
+ fail(`provider "${p.id}": issuer must use https`);
59
+ if (!LOCAL_HOSTS.has(issuer.hostname))
60
+ fail(`provider "${p.id}": allowInsecureIssuer only works for localhost`);
61
+ if (process.env.NODE_ENV === 'production')
62
+ fail(`provider "${p.id}": allowInsecureIssuer is refused in production`);
63
+ }
64
+ if (MICROSOFT_HOSTS.has(issuer.hostname)) {
65
+ // openid-client relaxes issuer checks for Microsoft hosts, so pin the tenant here.
66
+ const tenant = AZURE_TENANT_PATH.exec(issuer.pathname)?.[1]?.toLowerCase();
67
+ if (!tenant)
68
+ fail(`provider "${p.id}": Azure issuer must be tenant-specific: https://login.microsoftonline.com/<tenant-id>/v2.0`);
69
+ if (tenant === MSA_CONSUMER_TENANT)
70
+ fail(`provider "${p.id}": the personal Microsoft account tenant is not allowed`);
71
+ if (p.azureTenantId?.toLowerCase() !== tenant)
72
+ fail(`provider "${p.id}": azureTenantId must equal the issuer's tenant id`);
73
+ }
74
+ else if (p.azureTenantId) {
75
+ fail(`provider "${p.id}": azureTenantId is only valid for a Microsoft issuer`);
76
+ }
77
+ if (GOOGLE_HOSTS.has(issuer.hostname) && !p.googleHostedDomain) {
78
+ // Consumer Google accounts can be registered on corporate addresses; only hd proves Workspace membership.
79
+ fail(`provider "${p.id}": Google needs googleHostedDomain`);
80
+ }
81
+ if ((autoProvision || p.linkByEmail) && !p.allowedEmailDomains?.length && !p.googleHostedDomain && !p.azureTenantId) {
82
+ fail(`provider "${p.id}": autoProvision/linkByEmail need allowedEmailDomains, googleHostedDomain or azureTenantId`);
83
+ }
84
+ }
85
+ const { values, default: def } = opts.roles ?? {};
86
+ if (!values?.length)
87
+ fail('roles.values is required');
88
+ const adminRole = opts.roles.adminRole ?? 'admin';
89
+ for (const r of [def, adminRole])
90
+ if (!values.includes(r))
91
+ fail(`role "${r}" is not in roles.values`);
92
+ const mapping = {};
93
+ for (const [group, r] of Object.entries(opts.roles.mapping ?? {})) {
94
+ mapping[group] = Array.isArray(r) ? r : [r];
95
+ for (const role of mapping[group])
96
+ if (!values.includes(role))
97
+ fail(`mapped role "${role}" is not in roles.values`);
98
+ }
99
+ const field = opts.roles.field ?? 'roles';
100
+ const maxSessionHours = opts.maxSessionHours ?? 12;
101
+ if (!(maxSessionHours > 0))
102
+ fail('maxSessionHours must be positive');
103
+ return {
104
+ collection: collection,
105
+ providers: opts.providers,
106
+ autoProvision,
107
+ allowPasswordLoginForSSOUsers: opts.allowPasswordLoginForSSOUsers ?? false,
108
+ maxSessionHours,
109
+ serverURL: serverURL,
110
+ roles: {
111
+ field,
112
+ values,
113
+ default: def,
114
+ adminRole,
115
+ mapping,
116
+ canManage: opts.roles.canManage ??
117
+ ((req) => {
118
+ const roles = req.user?.[field];
119
+ return Array.isArray(roles) && roles.includes(adminRole);
120
+ }),
121
+ },
122
+ };
123
+ };
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'payload';
2
+ import { type SSOPluginOptions } from './options.js';
3
+ export declare const ssoPlugin: (options: SSOPluginOptions) => Plugin;
package/dist/plugin.js ADDED
@@ -0,0 +1,75 @@
1
+ import { makeEndpoints } from './endpoints.js';
2
+ import { makeGuards } from './guards.js';
3
+ import { resolveOptions } from './options.js';
4
+ export const ssoPlugin = (options) => (config) => {
5
+ const opts = resolveOptions(options, config);
6
+ const guards = makeGuards(opts);
7
+ const rolesField = opts.roles.field;
8
+ const identitiesField = {
9
+ name: 'ssoIdentities',
10
+ type: 'array',
11
+ // Written only by the plugin (Local API with overrideAccess).
12
+ access: { create: () => false, update: () => false, read: guards.canReadIdentities },
13
+ admin: { readOnly: true, description: 'Linked single sign-on identities' },
14
+ fields: [
15
+ { name: 'provider', type: 'text', required: true },
16
+ { name: 'key', type: 'text', required: true, index: true },
17
+ ],
18
+ };
19
+ const withRoleAccess = (f) => 'name' in f && f.name === rolesField
20
+ ? { ...f, access: { ...f.access, create: guards.canSetRoles, update: guards.canSetRoles } }
21
+ : f;
22
+ const patch = (c) => {
23
+ const hasRoles = c.fields.some((f) => 'name' in f && f.name === rolesField);
24
+ const rolesDef = {
25
+ name: rolesField,
26
+ type: 'select',
27
+ hasMany: true,
28
+ options: opts.roles.values,
29
+ defaultValue: [opts.roles.default],
30
+ saveToJWT: true,
31
+ };
32
+ const h = c.hooks ?? {};
33
+ const auth = typeof c.auth === 'object' ? c.auth : {};
34
+ return {
35
+ ...c,
36
+ // Fill only what the host left unset; Payload's default lets any user edit every user.
37
+ access: {
38
+ ...c.access,
39
+ ...Object.fromEntries(Object.entries(guards.collectionAccess).map(([k, fn]) => [k, c.access?.[k] ?? fn])),
40
+ },
41
+ // On https the session cookie must be Secure (Payload defaults it to false).
42
+ auth: opts.serverURL.startsWith('https:') && auth.cookies?.secure === undefined
43
+ ? { ...auth, cookies: { ...auth.cookies, secure: true } }
44
+ : c.auth,
45
+ fields: [...(hasRoles ? c.fields : [...c.fields, rolesDef]).map(withRoleAccess), identitiesField],
46
+ endpoints: [...(c.endpoints || []), ...makeEndpoints(opts)],
47
+ hooks: {
48
+ ...h,
49
+ beforeLogin: [guards.beforeLogin, ...(h.beforeLogin ?? [])],
50
+ beforeOperation: [guards.beforeOperation, ...(h.beforeOperation ?? [])],
51
+ beforeChange: [guards.beforeChange, ...(h.beforeChange ?? [])],
52
+ },
53
+ };
54
+ };
55
+ return {
56
+ ...config,
57
+ collections: (config.collections ?? []).map((c) => (c.slug === opts.collection ? patch(c) : c)),
58
+ admin: {
59
+ ...config.admin,
60
+ components: {
61
+ ...config.admin?.components,
62
+ afterLogin: [
63
+ ...(config.admin?.components?.afterLogin ?? []),
64
+ {
65
+ path: '@schbang/payload-sso/rsc#SSOButtons',
66
+ serverProps: {
67
+ ssoCollection: opts.collection,
68
+ ssoProviders: opts.providers.map(({ id, label }) => ({ id, label })),
69
+ },
70
+ },
71
+ ],
72
+ },
73
+ },
74
+ };
75
+ };
@@ -0,0 +1,31 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import type { OIDCProvider, ResolvedOptions } from './options.js';
3
+ /** A login refusal with an internal reason (logged, never shown to the browser). */
4
+ export declare class SSOError extends Error {
5
+ }
6
+ type Claims = Record<string, unknown> & {
7
+ iss: string;
8
+ sub: string;
9
+ };
10
+ type Identity = {
11
+ provider: string;
12
+ key: string;
13
+ };
14
+ export type UserDoc = Record<string, unknown> & {
15
+ id: string | number;
16
+ email: string;
17
+ ssoIdentities?: Identity[];
18
+ };
19
+ /** Applies the provider's sign-in policy and returns the normalised email. */
20
+ export declare const checkPolicy: (p: OIDCProvider, claims: Claims) => string;
21
+ /** default role + mapped groups. The IdP is the source of truth, so this replaces existing roles. */
22
+ export declare const rolesFor: (p: OIDCProvider, claims: Claims, opts: ResolvedOptions, req: PayloadRequest) => string[];
23
+ /**
24
+ * Finds, links or creates the user for this IdP identity and syncs roles.
25
+ * `linked` is true when an existing local account was just linked; the caller must then revoke its other sessions.
26
+ */
27
+ export declare const resolveUser: (p: OIDCProvider, claims: Claims, opts: ResolvedOptions, req: PayloadRequest) => Promise<{
28
+ user: UserDoc;
29
+ linked: boolean;
30
+ }>;
31
+ export {};
@@ -0,0 +1,138 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ /** A login refusal with an internal reason (logged, never shown to the browser). */
3
+ export class SSOError extends Error {
4
+ }
5
+ // ASCII only: avoids Unicode case-folding tricks (e.g. the Kelvin sign lowercasing to "k").
6
+ const EMAIL_RE = /^[\x21-\x3f\x41-\x7e]+@[a-z0-9.-]+$/i;
7
+ /** Applies the provider's sign-in policy and returns the normalised email. */
8
+ export const checkPolicy = (p, claims) => {
9
+ if (typeof claims.email !== 'string')
10
+ throw new SSOError('no email claim');
11
+ const raw = claims.email.trim();
12
+ // Check before lowercasing: toLowerCase() itself folds some non-ASCII letters into ASCII.
13
+ if (!EMAIL_RE.test(raw))
14
+ throw new SSOError('email is not a plain ASCII address');
15
+ const email = raw.toLowerCase();
16
+ if (p.azureTenantId) {
17
+ // Entra sends no email_verified. The email is set by the pinned tenant's admins, so trust
18
+ // comes from tid, and guests (users from other tenants/IdPs) are refused.
19
+ if (claims.tid !== p.azureTenantId)
20
+ throw new SSOError('tid claim mismatch');
21
+ if (claims.idp !== undefined && claims.idp !== claims.iss)
22
+ throw new SSOError('guest account refused');
23
+ }
24
+ else if (claims.email_verified !== true) {
25
+ throw new SSOError('email not verified by IdP');
26
+ }
27
+ const domain = email.slice(email.lastIndexOf('@') + 1);
28
+ if (p.allowedEmailDomains?.length && !p.allowedEmailDomains.map((d) => d.toLowerCase()).includes(domain)) {
29
+ throw new SSOError(`email domain "${domain}" not allowed`);
30
+ }
31
+ if (p.googleHostedDomain && claims.hd !== p.googleHostedDomain)
32
+ throw new SSOError('hd claim mismatch');
33
+ return email;
34
+ };
35
+ /** default role + mapped groups. The IdP is the source of truth, so this replaces existing roles. */
36
+ export const rolesFor = (p, claims, opts, req) => {
37
+ const claimNames = claims._claim_names;
38
+ const groupsClaim = p.groupsClaim ?? 'groups';
39
+ const overflow = claimNames && Object.hasOwn(claimNames, groupsClaim);
40
+ if (overflow)
41
+ req.payload.logger.warn(`[payload-sso] ${p.id}: groups claim overflow; granting default role only`);
42
+ const raw = overflow ? [] : claims[groupsClaim];
43
+ const groups = Array.isArray(raw) ? raw.filter((g) => typeof g === 'string') : [];
44
+ const roles = new Set([opts.roles.default]);
45
+ for (const g of groups)
46
+ if (Object.hasOwn(opts.roles.mapping, g))
47
+ for (const r of opts.roles.mapping[g])
48
+ roles.add(r);
49
+ return [...roles];
50
+ };
51
+ /**
52
+ * Finds, links or creates the user for this IdP identity and syncs roles.
53
+ * `linked` is true when an existing local account was just linked; the caller must then revoke its other sessions.
54
+ */
55
+ export const resolveUser = async (p, claims, opts, req) => {
56
+ const { payload } = req;
57
+ const email = checkPolicy(p, claims);
58
+ // One field, so issuer and subject can't match across different array entries.
59
+ const key = `${claims.iss}|${claims.sub}`;
60
+ const roles = rolesFor(p, claims, opts, req);
61
+ const authConfig = payload.collections[opts.collection].config.auth;
62
+ const common = {
63
+ collection: opts.collection,
64
+ overrideAccess: true,
65
+ showHiddenFields: true, // lockUntil, _verified are hidden fields
66
+ depth: 0,
67
+ req,
68
+ context: { ssoSync: true },
69
+ };
70
+ // Hidden fields are needed for the checks above, but must not reach session, hooks or req.user.
71
+ const visible = async (id) => {
72
+ // sessions is access-protected rather than hidden, so overrideAccess would return it.
73
+ const { sessions: _sessions, ...doc } = (await payload.findByID({ ...common, showHiddenFields: false, id }));
74
+ return doc;
75
+ };
76
+ const byIdentity = await payload.find({ ...common, where: { 'ssoIdentities.key': { equals: key } }, limit: 2 });
77
+ if (byIdentity.docs.length > 1)
78
+ throw new SSOError('identity linked to several users');
79
+ let user = byIdentity.docs[0];
80
+ let linked = false;
81
+ if (!user) {
82
+ const byEmail = (await payload.find({ ...common, where: { email: { equals: email } }, limit: 1 })).docs[0];
83
+ if (byEmail) {
84
+ // Never take over an existing account unless explicitly allowed and the IdP vouches for the email.
85
+ if (!p.linkByEmail || (!p.azureTenantId && claims.email_verified !== true)) {
86
+ throw new SSOError('an account with this email exists and linking is not allowed');
87
+ }
88
+ // Only link pure local accounts: otherwise a user who changed their email to a colleague's
89
+ // would receive that colleague's identity and roles.
90
+ if (byEmail.ssoIdentities?.length)
91
+ throw new SSOError('account with this email is already linked to another identity');
92
+ // The local account must have proven it owns the email, or anyone could pre-create it.
93
+ if (authConfig.verify && byEmail._verified !== true)
94
+ throw new SSOError('local account email never verified');
95
+ user = byEmail;
96
+ linked = true;
97
+ }
98
+ else if (opts.autoProvision) {
99
+ const created = (await payload.create({
100
+ ...common,
101
+ data: {
102
+ email,
103
+ password: randomBytes(32).toString('base64url'),
104
+ [opts.roles.field]: roles,
105
+ ssoIdentities: [{ provider: p.id, key }],
106
+ ...(authConfig.verify ? { _verified: true } : {}),
107
+ },
108
+ disableVerificationEmail: true,
109
+ }));
110
+ return { user: await visible(created.id), linked: false };
111
+ }
112
+ else {
113
+ throw new SSOError('no account and autoProvision is off');
114
+ }
115
+ }
116
+ const lockUntil = user.lockUntil;
117
+ if (lockUntil && new Date(lockUntil) > new Date())
118
+ throw new SSOError('account locked');
119
+ const identities = user.ssoIdentities ?? [];
120
+ await payload.update({
121
+ ...common,
122
+ id: user.id,
123
+ data: {
124
+ [opts.roles.field]: roles,
125
+ ...(identities.some((i) => i.key === key)
126
+ ? {}
127
+ : { ssoIdentities: [...identities.map(({ provider, key }) => ({ provider, key })), { provider: p.id, key }] }),
128
+ // Linking takes the account over for SSO: kill the old password and API key.
129
+ ...(linked
130
+ ? {
131
+ password: randomBytes(32).toString('base64url'),
132
+ ...(authConfig.useAPIKey ? { enableAPIKey: false, apiKey: null } : {}),
133
+ }
134
+ : {}),
135
+ },
136
+ });
137
+ return { user: await visible(user.id), linked };
138
+ };
@@ -0,0 +1,2 @@
1
+ /** Returns `value` only if it is a same-origin path; otherwise `fallback`. */
2
+ export declare const safeReturnTo: (value: string | null | undefined, fallback: string) => string;
@@ -0,0 +1,21 @@
1
+ import { getSafeRedirect } from 'payload/shared';
2
+ /** Returns `value` only if it is a same-origin path; otherwise `fallback`. */
3
+ export const safeReturnTo = (value, fallback) => {
4
+ if (!value || value.length > 2048)
5
+ return fallback;
6
+ // Must be a path: one leading slash, no scheme-relative (//), no backslash tricks, no control chars.
7
+ if (!value.startsWith('/') || value.startsWith('//') || value.includes('\\'))
8
+ return fallback;
9
+ if (/[\u0000-\u001f\u007f]/.test(value))
10
+ return fallback;
11
+ try {
12
+ const base = 'http://x.invalid';
13
+ if (new URL(value, base).origin !== base)
14
+ return fallback;
15
+ }
16
+ catch {
17
+ return fallback;
18
+ }
19
+ // Payload's own checks too (encoded slashes, /http..., /javascript:).
20
+ return getSafeRedirect({ redirectTo: value, fallbackTo: fallback });
21
+ };
@@ -0,0 +1,14 @@
1
+ import { type CollectionSlug, type PayloadRequest } from 'payload';
2
+ /** SSO session ids carry their login time, so refresh can enforce a maximum lifetime. */
3
+ export declare const ssoSessionStartedAt: (sid: unknown) => number | null;
4
+ /**
5
+ * Starts a normal Payload session, mirroring loginOperation: beforeLogin hooks, a `sessions`
6
+ * entry, a signed token, afterLogin hooks and the payload-token cookie. Returns the Set-Cookie value.
7
+ * `revokeOthers` drops every existing session (used when an existing account is first linked).
8
+ */
9
+ export declare const startSession: (req: PayloadRequest, slug: CollectionSlug, user: Record<string, unknown> & {
10
+ id: string | number;
11
+ email: string;
12
+ }, { revokeOthers }?: {
13
+ revokeOthers?: boolean;
14
+ }) => Promise<string>;
@@ -0,0 +1,56 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { generatePayloadCookie, getFieldsToSign, jwtSign } from 'payload';
3
+ const SID_RE = /^sso-(\d+)-/;
4
+ /** SSO session ids carry their login time, so refresh can enforce a maximum lifetime. */
5
+ export const ssoSessionStartedAt = (sid) => {
6
+ const m = typeof sid === 'string' ? SID_RE.exec(sid) : null;
7
+ return m ? Number(m[1]) * 1000 : null;
8
+ };
9
+ /**
10
+ * Starts a normal Payload session, mirroring loginOperation: beforeLogin hooks, a `sessions`
11
+ * entry, a signed token, afterLogin hooks and the payload-token cookie. Returns the Set-Cookie value.
12
+ * `revokeOthers` drops every existing session (used when an existing account is first linked).
13
+ */
14
+ export const startSession = async (req, slug, user, { revokeOthers = false } = {}) => {
15
+ const { payload } = req;
16
+ const collectionConfig = payload.collections[slug].config;
17
+ const auth = collectionConfig.auth;
18
+ req.context.ssoSync = true;
19
+ let sessionUser = {
20
+ ...user,
21
+ collection: slug,
22
+ _strategy: 'payload-sso',
23
+ };
24
+ // Same gate loginOperation runs: host hooks can still refuse (e.g. disabled users).
25
+ for (const hook of collectionConfig.hooks?.beforeLogin ?? []) {
26
+ sessionUser = (await hook({ collection: collectionConfig, context: req.context, req, user: sessionUser })) || sessionUser;
27
+ }
28
+ let sid;
29
+ if (auth.useSessions) {
30
+ // shortcut: mirrors payload/dist/auth/sessions.js (addSessionToUser is not exported); the session canary test breaks if Payload changes it
31
+ const raw = (await payload.db.findOne({ collection: slug, req, where: { id: { equals: user.id } } }));
32
+ if (!raw)
33
+ throw new Error('user vanished before session start');
34
+ const now = new Date();
35
+ sid = `sso-${Math.floor(now.getTime() / 1000)}-${randomUUID()}`;
36
+ const sessions = revokeOthers ? [] : (raw.sessions ?? []).filter((s) => new Date(s.expiresAt) > now);
37
+ sessions.push({ id: sid, createdAt: now, expiresAt: new Date(now.getTime() + auth.tokenExpiration * 1000) });
38
+ // Write the whole document, as Payload does: a partial { sessions } update makes the SQL adapters
39
+ // drop the user's other array rows (e.g. ssoIdentities). updatedAt: null keeps the timestamp.
40
+ await payload.db.updateOne({
41
+ collection: slug,
42
+ id: user.id,
43
+ data: { ...raw, sessions, updatedAt: null },
44
+ req,
45
+ returning: false,
46
+ });
47
+ }
48
+ const fieldsToSign = getFieldsToSign({ collectionConfig, email: user.email, sid, user: sessionUser });
49
+ const { token } = await jwtSign({ fieldsToSign, secret: payload.secret, tokenExpiration: auth.tokenExpiration });
50
+ // Same hooks loginOperation runs, so audit logging and project hooks see SSO logins.
51
+ req.user = { ...sessionUser, _sid: sid };
52
+ for (const hook of collectionConfig.hooks?.afterLogin ?? []) {
53
+ await hook({ collection: collectionConfig, context: req.context, req, token, user: sessionUser });
54
+ }
55
+ return generatePayloadCookie({ collectionAuthConfig: auth, cookiePrefix: payload.config.cookiePrefix, token });
56
+ };
@@ -0,0 +1,14 @@
1
+ export declare const TX_COOKIE = "payload-sso-tx";
2
+ declare const TTL_SECONDS = 600;
3
+ export type Tx = {
4
+ provider: string;
5
+ state: string;
6
+ nonce: string;
7
+ verifier: string;
8
+ returnTo: string;
9
+ };
10
+ /** Encrypts and authenticates the login transaction (AES-256-GCM via JWE). */
11
+ export declare const sealTx: (tx: Tx, secret: string) => Promise<string>;
12
+ /** Returns null for a missing, tampered, malformed or expired cookie. */
13
+ export declare const openTx: (value: string | undefined, secret: string) => Promise<Tx | null>;
14
+ export { TTL_SECONDS as TX_TTL_SECONDS };
@@ -0,0 +1,31 @@
1
+ import { hkdfSync } from 'node:crypto';
2
+ import { EncryptJWT, jwtDecrypt } from 'jose';
3
+ export const TX_COOKIE = 'payload-sso-tx';
4
+ const TTL_SECONDS = 600;
5
+ const keyFor = (secret) => new Uint8Array(hkdfSync('sha256', secret, 'payload-sso', 'tx-cookie-v1', 32));
6
+ /** Encrypts and authenticates the login transaction (AES-256-GCM via JWE). */
7
+ export const sealTx = (tx, secret) => new EncryptJWT({ ...tx })
8
+ .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
9
+ .setIssuedAt()
10
+ .setExpirationTime(`${TTL_SECONDS}s`)
11
+ .encrypt(keyFor(secret));
12
+ /** Returns null for a missing, tampered, malformed or expired cookie. */
13
+ export const openTx = async (value, secret) => {
14
+ if (!value)
15
+ return null;
16
+ try {
17
+ const { payload } = await jwtDecrypt(value, keyFor(secret), {
18
+ keyManagementAlgorithms: ['dir'],
19
+ contentEncryptionAlgorithms: ['A256GCM'],
20
+ maxTokenAge: TTL_SECONDS,
21
+ });
22
+ const { provider, state, nonce, verifier, returnTo } = payload;
23
+ if ([provider, state, nonce, verifier, returnTo].some((v) => typeof v !== 'string'))
24
+ return null;
25
+ return { provider, state, nonce, verifier, returnTo };
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ };
31
+ export { TTL_SECONDS as TX_TTL_SECONDS };
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@schbang/payload-sso",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "OIDC single sign-on for Payload CMS (Okta, Azure AD, Google) with group-to-role mapping",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/arjusm/Payload-SSO-Login.git"
9
+ },
10
+ "homepage": "https://github.com/arjusm/Payload-SSO-Login#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/arjusm/Payload-SSO-Login/issues"
13
+ },
14
+ "type": "module",
15
+ "main": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "default": "./dist/index.js"
22
+ },
23
+ "./rsc": {
24
+ "types": "./dist/exports/rsc.d.ts",
25
+ "import": "./dist/exports/rsc.js",
26
+ "default": "./dist/exports/rsc.js"
27
+ }
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "SECURITY.md"
32
+ ],
33
+ "keywords": [
34
+ "payload",
35
+ "payloadcms",
36
+ "payload-plugin",
37
+ "sso",
38
+ "oidc"
39
+ ],
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "dependencies": {
44
+ "jose": "^6.3.0",
45
+ "openid-client": "^6.9.1"
46
+ },
47
+ "devDependencies": {
48
+ "@types/react": "19.2.14",
49
+ "payload": "3.94.2",
50
+ "react": "19.2.9",
51
+ "typescript": "5.7.3"
52
+ },
53
+ "peerDependencies": {
54
+ "payload": ">=3.94.2 <4",
55
+ "react": "^19.0.0"
56
+ },
57
+ "scripts": {
58
+ "build": "tsc -p tsconfig.json"
59
+ }
6
60
  }