@skylab-kulubu/inscribed-auth 0.1.0 → 0.2.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/README.md CHANGED
@@ -63,6 +63,17 @@ export const authOptions = createCmsAuthOptions({
63
63
  });
64
64
  ```
65
65
 
66
+ By default `createCmsAuthOptions` also:
67
+
68
+ - sets `pages.signIn` to `/api/signin` so **every** sign-in redirect (including
69
+ the silent re-auth after a token refresh fails) jumps straight into Keycloak
70
+ instead of NextAuth's "Sign in with X" picker. Mount that route (next file)
71
+ for it to work, or pass `signInPage: false` to keep the built-in picker.
72
+ - ends the Keycloak SSO session on sign-out (RP-initiated logout via
73
+ `id_token_hint`), so signing out of the app also signs the user out of
74
+ Keycloak — otherwise the next visit silently re-authenticates against the
75
+ still-live SSO session.
76
+
66
77
  ### `app/api/auth/[...nextauth]/route.js` — NextAuth handler
67
78
 
68
79
  ```js
@@ -76,7 +87,11 @@ export { handler as GET, handler as POST };
76
87
  ### `app/api/signin/route.js` — one-click sign-in
77
88
 
78
89
  `/api/signin?callbackUrl=...` jumps straight into the Keycloak flow, skipping
79
- NextAuth's provider-picker page. Link to it from anywhere (`<a href="/api/signin">`).
90
+ NextAuth's provider-picker page. `createCmsAuthOptions` wires this as the default
91
+ `pages.signIn`, so NextAuth sends unauthenticated users here automatically; you
92
+ can also link to it from anywhere (`<a href="/api/signin">`). **Mount it** — with
93
+ `signInPage` defaulting to `/api/signin`, sign-in 404s if this route is missing
94
+ (or set `signInPage: false`).
80
95
 
81
96
  ```js
82
97
  export { GET } from "@skylab-kulubu/inscribed-auth/signin";
@@ -133,7 +148,6 @@ NEXTAUTH_SECRET=<run: openssl rand -base64 32>
133
148
  CMS_URL=https://<your-cms-host>
134
149
  # Optional:
135
150
  # CMS_CDN_URL=https://<your-cdn-host>
136
- # NEXT_PUBLIC_CMS_URL=https://<your-cms-host> # read by inscribed core, client-side
137
151
  ```
138
152
 
139
153
  | Var | Required | Purpose |
@@ -143,20 +157,29 @@ CMS_URL=https://<your-cms-host>
143
157
  | `KEYCLOAK_ISSUER` | ✅ | Realm issuer URL |
144
158
  | `NEXTAUTH_URL` | ✅ | App base URL for NextAuth |
145
159
  | `NEXTAUTH_SECRET` | ✅ | NextAuth JWT/session secret |
146
- | `CMS_URL` | ✅ | inscribed backend base URL |
147
- | `CMS_CDN_URL` | — | Asset CDN base (read by inscribed) |
148
- | `NEXT_PUBLIC_CMS_URL` | — | Client-side base URL (read by inscribed) |
160
+ | `CMS_URL` | ✅ | inscribed backend base URL (→ `config.baseUrl`) |
161
+ | `CMS_CDN_URL` | — | Asset CDN base ( `config.cdnUrl`) |
149
162
 
150
163
  ## Admin access
151
164
 
152
165
  Admin operations require the `cms:access` Keycloak **client role**, both for the
153
- logged-in user (admin UI) and the service account (sync). If sync returns `403`,
154
- `onSyncError` dumps the service token's `azp` / `aud` / `resource_access` claims
155
- and tells you exactly which role mapping is missing:
156
-
157
- ```
158
- Keycloak Admin Clients <client> Service account roles assign "cms:access"
159
- ```
166
+ logged-in user (admin UI) and the service account (sync). The role belongs to
167
+ the **inscribed backend's** Keycloak client (the resource server, e.g.
168
+ `skycms`) not the frontend login client (`KEYCLOAK_CLIENT_ID`). As long as the
169
+ backend client is mapped into the token audience, the role rides along under
170
+ `resource_access["<backend-client>"]`; the SDK reads roles from every client in
171
+ `resource_access`, so it doesn't matter that the role isn't keyed under the
172
+ frontend client / token `azp`.
173
+
174
+ Grant the backend client's `cms:access` role to each principal in Keycloak Admin:
175
+
176
+ - **Admin users** → Users → \<user\> → Role mapping → assign `cms:access`
177
+ - **Service account (sync)** → Clients → `KEYCLOAK_CLIENT_ID` → Service account
178
+ roles → assign `cms:access`
179
+
180
+ If sync still returns `403`, `onSyncError` dumps the service token's `azp` /
181
+ `aud` / `resource_access` claims and reports which client (if any) actually
182
+ holds `cms:access`.
160
183
 
161
184
  ## License
162
185
 
package/dist/config.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { g as getClientCredentialsToken, d as debugServiceTokenClaims } from './service-token-COa7hHuV.js';
1
+ import { g as getClientCredentialsToken, d as debugServiceTokenClaims } from './service-token-CHJDdnHv.js';
2
2
 
3
3
  /**
4
4
  * @file `@skylab-kulubu/inscribed-auth/config` — `cms-sync` CLI wiring.
package/dist/config.js CHANGED
@@ -50,10 +50,16 @@ async function debugServiceTokenClaims() {
50
50
  console.error(` aud: ${JSON.stringify(claims.aud)}`);
51
51
  console.error(` scope: ${claims.scope}`);
52
52
  console.error(` resource_access: ${JSON.stringify(claims.resource_access)}`);
53
- const ourRoles = claims.resource_access?.[claims.azp]?.roles ?? [];
54
- console.error(` -> roles for "${claims.azp}": ${JSON.stringify(ourRoles)}`);
55
- if (!ourRoles.includes("cms:access")) {
56
- console.error(` ! "cms:access" role missing on service account.`);
53
+ const ra = claims.resource_access ?? {};
54
+ const holder = Object.keys(ra).find((c) => ra[c]?.roles?.includes("cms:access"));
55
+ if (holder) {
56
+ console.error(` -> "cms:access" found under resource_access["${holder}"].`);
57
+ if (holder !== claims.azp) {
58
+ console.error(` (owned by backend client "${holder}", not azp "${claims.azp}" - expected)`);
59
+ }
60
+ } else {
61
+ console.error(` ! "cms:access" role missing from every client in resource_access.`);
62
+ console.error(` Assign the backend client's "cms:access" role to this service account:`);
57
63
  console.error(` Keycloak Admin -> Clients -> ${claims.azp} -> Service account roles -> Assign "cms:access".`);
58
64
  }
59
65
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/service-token.mjs","../src/config.mjs"],"sourcesContent":["/**\n * @file Keycloak client-credentials service-token provider.\n *\n * Part of `@skylab-kulubu/inscribed-auth`. The inscribed core is backend-neutral:\n * it only knows the `ServiceTokenProvider` contract (`() => Promise<string>`)\n * and defaults to \"no token\". This module implements that contract against\n * Keycloak and is wired into the SDK via `createCmsPage({ getServiceToken })`\n * (consumer `lib/cms.jsx`) and the `cms-sync` CLI (consumer `cms.config.mjs`,\n * which re-exports from `@skylab-kulubu/inscribed-auth/config`).\n *\n * `.mjs` so the plain-Node `cms-sync` CLI can `import()` the resolved `./config`\n * entry as ESM regardless of the consuming app's `\"type\"`. (Skylab apps stay\n * CommonJS so next-auth v4's Keycloak provider resolves through Webpack's CJS\n * interop — see the provider-injection note in `options.js`.)\n *\n * Server / build-time only. Reads KEYCLOAK_CLIENT_ID, KEYCLOAK_CLIENT_SECRET,\n * KEYCLOAK_ISSUER. Returns \"\" when those vars are absent so reads degrade to\n * unauthenticated. In-process cache shared across requests, re-fetched 30s\n * before expiry.\n */\n\n/** @type {{ token: string; expiresAt: number } | null} */\nlet cache = null;\n\n/**\n * Implements the SDK's `ServiceTokenProvider` contract: `() => Promise<string>`.\n * @returns {Promise<string>}\n */\nexport async function getClientCredentialsToken() {\n const clientId = process.env.KEYCLOAK_CLIENT_ID;\n const clientSecret = process.env.KEYCLOAK_CLIENT_SECRET;\n const issuer = process.env.KEYCLOAK_ISSUER;\n\n if (!clientId || !clientSecret || !issuer) return \"\";\n\n if (cache && cache.expiresAt > Date.now() + 30_000) return cache.token;\n\n const res = await fetch(`${issuer}/protocol/openid-connect/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"client_credentials\",\n client_id: clientId,\n client_secret: clientSecret,\n }),\n cache: \"no-store\",\n });\n\n if (!res.ok) {\n throw new Error(\n `[inscribed-auth] Keycloak token request failed: ${res.status} ${await res.text()}`,\n );\n }\n\n const { access_token, expires_in } = await res.json();\n cache = { token: access_token, expiresAt: Date.now() + expires_in * 1000 };\n return access_token;\n}\n\n/**\n * Drop the cached service token so the next call re-fetches. Intentionally NOT\n * part of the public `./server` surface — kept here for internal use and for\n * anyone who deep-imports the raw module (e.g. token rotation in tests).\n */\nexport function invalidateClientCredentialsToken() {\n cache = null;\n}\n\n/**\n * On a sync failure, fetch the service token directly and dump the claims the\n * backend's `CmsAccessPolicy` checks (`azp`, `aud`, `resource_access`). Most\n * 403s come from the service account missing the `cms:access` role mapping in\n * Keycloak - this prints exactly what's there. Wired as `onSyncError` in the\n * `./config` entry.\n */\nexport async function debugServiceTokenClaims() {\n const { KEYCLOAK_CLIENT_ID, KEYCLOAK_CLIENT_SECRET, KEYCLOAK_ISSUER } = process.env;\n if (!KEYCLOAK_CLIENT_ID || !KEYCLOAK_CLIENT_SECRET || !KEYCLOAK_ISSUER) return;\n\n const res = await fetch(`${KEYCLOAK_ISSUER}/protocol/openid-connect/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"client_credentials\",\n client_id: KEYCLOAK_CLIENT_ID,\n client_secret: KEYCLOAK_CLIENT_SECRET,\n }),\n });\n if (!res.ok) {\n console.error(`[cms-sync:debug] Token fetch failed: ${res.status} ${await res.text()}`);\n return;\n }\n\n const { access_token } = await res.json();\n const [, payload] = access_token.split(\".\");\n const claims = JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf8\"));\n\n console.error(\"[cms-sync:debug] Service token claims:\");\n console.error(` azp: ${claims.azp}`);\n console.error(` sub: ${claims.sub}`);\n console.error(` aud: ${JSON.stringify(claims.aud)}`);\n console.error(` scope: ${claims.scope}`);\n console.error(` resource_access: ${JSON.stringify(claims.resource_access)}`);\n\n const ourRoles = claims.resource_access?.[claims.azp]?.roles ?? [];\n console.error(` -> roles for \"${claims.azp}\": ${JSON.stringify(ourRoles)}`);\n if (!ourRoles.includes(\"cms:access\")) {\n console.error(` ! \"cms:access\" role missing on service account.`);\n console.error(` Keycloak Admin -> Clients -> ${claims.azp} -> Service account roles -> Assign \"cms:access\".`);\n }\n}\n","/**\n * @file `@skylab-kulubu/inscribed-auth/config` — `cms-sync` CLI wiring.\n *\n * The `cms-sync` CLI is a plain Node binary - it can't receive function props\n * the way the React tree does - so it loads the consumer's `cms.config.{js,mjs}`\n * from the project root to learn how to obtain a service token (and, optionally,\n * how to diagnose failures). This entry lets that config file be a one-liner:\n *\n * // cms.config.mjs (consumer project root)\n * export { getServiceToken, onSyncError } from \"@skylab-kulubu/inscribed-auth/config\";\n *\n * Resolves to ESM so the CLI's dynamic `import()` works regardless of the\n * consuming app's `\"type\"`.\n */\n\nimport {\n getClientCredentialsToken,\n debugServiceTokenClaims,\n} from \"./lib/service-token.mjs\";\n\n/** Service token for build-time `POST /cms/sync`. */\nexport const getServiceToken = getClientCredentialsToken;\n\n/** Called when a sync fails - dumps Keycloak claims to explain 403s. */\nexport const onSyncError = () => debugServiceTokenClaims();\n"],"mappings":";AAsBA,IAAI,QAAQ;AAMZ,eAAsB,4BAA4B;AAChD,QAAM,WAAW,QAAQ,IAAI;AAC7B,QAAM,eAAe,QAAQ,IAAI;AACjC,QAAM,SAAS,QAAQ,IAAI;AAE3B,MAAI,CAAC,YAAY,CAAC,gBAAgB,CAAC,OAAQ,QAAO;AAElD,MAAI,SAAS,MAAM,YAAY,KAAK,IAAI,IAAI,IAAQ,QAAO,MAAM;AAEjE,QAAM,MAAM,MAAM,MAAM,GAAG,MAAM,kCAAkC;AAAA,IACjE,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,oCAAoC;AAAA,IAC/D,MAAM,IAAI,gBAAgB;AAAA,MACxB,YAAY;AAAA,MACZ,WAAW;AAAA,MACX,eAAe;AAAA,IACjB,CAAC;AAAA,IACD,OAAO;AAAA,EACT,CAAC;AAED,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,IAAI;AAAA,MACR,mDAAmD,IAAI,MAAM,IAAI,MAAM,IAAI,KAAK,CAAC;AAAA,IACnF;AAAA,EACF;AAEA,QAAM,EAAE,cAAc,WAAW,IAAI,MAAM,IAAI,KAAK;AACpD,UAAQ,EAAE,OAAO,cAAc,WAAW,KAAK,IAAI,IAAI,aAAa,IAAK;AACzE,SAAO;AACT;AAkBA,eAAsB,0BAA0B;AAC9C,QAAM,EAAE,oBAAoB,wBAAwB,gBAAgB,IAAI,QAAQ;AAChF,MAAI,CAAC,sBAAsB,CAAC,0BAA0B,CAAC,gBA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["/**\n * @file Keycloak client-credentials service-token provider.\n *\n * Part of `@skylab-kulubu/inscribed-auth`. The inscribed core is backend-neutral:\n * it only knows the `ServiceTokenProvider` contract (`() => Promise<string>`)\n * and defaults to \"no token\". This module implements that contract against\n * Keycloak and is wired into the SDK via `createCmsPage({ getServiceToken })`\n * (consumer `lib/cms.jsx`) and the `cms-sync` CLI (consumer `cms.config.mjs`,\n * which re-exports from `@skylab-kulubu/inscribed-auth/config`).\n *\n * `.mjs` so the plain-Node `cms-sync` CLI can `import()` the resolved `./config`\n * entry as ESM regardless of the consuming app's `\"type\"`. (Skylab apps stay\n * CommonJS so next-auth v4's Keycloak provider resolves through Webpack's CJS\n * interop — see the provider-injection note in `options.js`.)\n *\n * Server / build-time only. Reads KEYCLOAK_CLIENT_ID, KEYCLOAK_CLIENT_SECRET,\n * KEYCLOAK_ISSUER. Returns \"\" when those vars are absent so reads degrade to\n * unauthenticated. In-process cache shared across requests, re-fetched 30s\n * before expiry.\n */\n\n/** @type {{ token: string; expiresAt: number } | null} */\nlet cache = null;\n\n/**\n * Implements the SDK's `ServiceTokenProvider` contract: `() => Promise<string>`.\n * @returns {Promise<string>}\n */\nexport async function getClientCredentialsToken() {\n const clientId = process.env.KEYCLOAK_CLIENT_ID;\n const clientSecret = process.env.KEYCLOAK_CLIENT_SECRET;\n const issuer = process.env.KEYCLOAK_ISSUER;\n\n if (!clientId || !clientSecret || !issuer) return \"\";\n\n if (cache && cache.expiresAt > Date.now() + 30_000) return cache.token;\n\n const res = await fetch(`${issuer}/protocol/openid-connect/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"client_credentials\",\n client_id: clientId,\n client_secret: clientSecret,\n }),\n cache: \"no-store\",\n });\n\n if (!res.ok) {\n throw new Error(\n `[inscribed-auth] Keycloak token request failed: ${res.status} ${await res.text()}`,\n );\n }\n\n const { access_token, expires_in } = await res.json();\n cache = { token: access_token, expiresAt: Date.now() + expires_in * 1000 };\n return access_token;\n}\n\n/**\n * Drop the cached service token so the next call re-fetches. Intentionally NOT\n * part of the public `./server` surface — kept here for internal use and for\n * anyone who deep-imports the raw module (e.g. token rotation in tests).\n */\nexport function invalidateClientCredentialsToken() {\n cache = null;\n}\n\n/**\n * On a sync failure, fetch the service token directly and dump the claims the\n * backend's `CmsAccessPolicy` checks (`azp`, `aud`, `resource_access`). Most\n * 403s come from the service account missing the `cms:access` role mapping in\n * Keycloak - this prints exactly what's there. Wired as `onSyncError` in the\n * `./config` entry.\n */\nexport async function debugServiceTokenClaims() {\n const { KEYCLOAK_CLIENT_ID, KEYCLOAK_CLIENT_SECRET, KEYCLOAK_ISSUER } = process.env;\n if (!KEYCLOAK_CLIENT_ID || !KEYCLOAK_CLIENT_SECRET || !KEYCLOAK_ISSUER) return;\n\n const res = await fetch(`${KEYCLOAK_ISSUER}/protocol/openid-connect/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"client_credentials\",\n client_id: KEYCLOAK_CLIENT_ID,\n client_secret: KEYCLOAK_CLIENT_SECRET,\n }),\n });\n if (!res.ok) {\n console.error(`[cms-sync:debug] Token fetch failed: ${res.status} ${await res.text()}`);\n return;\n }\n\n const { access_token } = await res.json();\n const [, payload] = access_token.split(\".\");\n const claims = JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf8\"));\n\n console.error(\"[cms-sync:debug] Service token claims:\");\n console.error(` azp: ${claims.azp}`);\n console.error(` sub: ${claims.sub}`);\n console.error(` aud: ${JSON.stringify(claims.aud)}`);\n console.error(` scope: ${claims.scope}`);\n console.error(` resource_access: ${JSON.stringify(claims.resource_access)}`);\n\n // `cms:access` is a *client role* of the inscribed backend's Keycloak client\n // (e.g. \"skycms\"), assigned to this service account. It therefore lands under\n // resource_access[<backend-client>], NOT under azp (this frontend client).\n // Scan every client so we report where the role actually is.\n const ra = claims.resource_access ?? {};\n const holder = Object.keys(ra).find((c) => ra[c]?.roles?.includes(\"cms:access\"));\n if (holder) {\n console.error(` -> \"cms:access\" found under resource_access[\"${holder}\"].`);\n if (holder !== claims.azp) {\n console.error(` (owned by backend client \"${holder}\", not azp \"${claims.azp}\" - expected)`);\n }\n } else {\n console.error(` ! \"cms:access\" role missing from every client in resource_access.`);\n console.error(` Assign the backend client's \"cms:access\" role to this service account:`);\n console.error(` Keycloak Admin -> Clients -> ${claims.azp} -> Service account roles -> Assign \"cms:access\".`);\n }\n}\n","/**\n * @file `@skylab-kulubu/inscribed-auth/config` — `cms-sync` CLI wiring.\n *\n * The `cms-sync` CLI is a plain Node binary - it can't receive function props\n * the way the React tree does - so it loads the consumer's `cms.config.{js,mjs}`\n * from the project root to learn how to obtain a service token (and, optionally,\n * how to diagnose failures). This entry lets that config file be a one-liner:\n *\n * // cms.config.mjs (consumer project root)\n * export { getServiceToken, onSyncError } from \"@skylab-kulubu/inscribed-auth/config\";\n *\n * Resolves to ESM so the CLI's dynamic `import()` works regardless of the\n * consuming app's `\"type\"`.\n */\n\nimport {\n getClientCredentialsToken,\n debugServiceTokenClaims,\n} from \"./lib/service-token.mjs\";\n\n/** Service token for build-time `POST /cms/sync`. */\nexport const getServiceToken = getClientCredentialsToken;\n\n/** Called when a sync fails - dumps Keycloak claims to explain 403s. */\nexport const onSyncError = () => debugServiceTokenClaims();\n"],"mappings":";AAsBA,IAAI,QAAQ;AAMZ,eAAsB,4BAA4B;AAChD,QAAM,WAAW,QAAQ,IAAI;AAC7B,QAAM,eAAe,QAAQ,IAAI;AACjC,QAAM,SAAS,QAAQ,IAAI;AAE3B,MAAI,CAAC,YAAY,CAAC,gBAAgB,CAAC,OAAQ,QAAO;AAElD,MAAI,SAAS,MAAM,YAAY,KAAK,IAAI,IAAI,IAAQ,QAAO,MAAM;AAEjE,QAAM,MAAM,MAAM,MAAM,GAAG,MAAM,kCAAkC;AAAA,IACjE,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,oCAAoC;AA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U,OAAO,GAAG,CAAC,EAAE;AAChE,UAAQ,MAAM,sBAAsB,OAAO,KAAK,EAAE;AAClD,UAAQ,MAAM,sBAAsB,KAAK,UAAU,OAAO,eAAe,CAAC,EAAE;AAM5E,QAAM,KAAK,OAAO,mBAAmB,CAAC;AACtC,QAAM,SAAS,OAAO,KAAK,EAAE,EAAE,KAAK,CAAC,MAAM,GAAG,CAAC,GAAG,OAAO,SAAS,YAAY,CAAC;AAC/E,MAAI,QAAQ;AACV,YAAQ,MAAM,kDAAkD,MAAM,KAAK;AAC3E,QAAI,WAAW,OAAO,KAAK;AACzB,cAAQ,MAAM,kCAAkC,MAAM,eAAe,OAAO,GAAG,eAAe;AAAA,IAChG;AAAA,EACF,OAAO;AACL,YAAQ,MAAM,qEAAqE;AACnF,YAAQ,MAAM,6EAA6E;AAC3F,YAAQ,MAAM,qCAAqC,OAAO,GAAG,mDAAmD;AAAA,EAClH;AACF;;;ACnGO,IAAM,kBAAkB;AAGxB,IAAM,cAAc,MAAM,wBAAwB;","names":[]}
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import { jsx } from "react/jsx-runtime";
8
8
  function Inner({ config, isAdmin, userSub, initialBlocks, onAfterSave, children }) {
9
9
  const { data: session } = useSession();
10
10
  useEffect(() => {
11
- if (session?.error === "RefreshAccessTokenError") signIn();
11
+ if (session?.error === "RefreshAccessTokenError") signIn("keycloak");
12
12
  }, [session?.error]);
13
13
  const getAccessToken = useCallback(
14
14
  async () => (
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.jsx"],"sourcesContent":["\"use client\";\n\n/**\n * @file `@skylab-kulubu/inscribed-auth` — client entry.\n *\n * NextAuth-aware wrapper around inscribed's `CmsProvider`. The inscribed core is\n * auth-agnostic; this is Skylab's NextAuth + Keycloak client wiring.\n *\n * Wraps children with NextAuth's `SessionProvider` (so you don't need to add it\n * to `layout.jsx`) and feeds `useSession()` into `CmsProvider` so admin saves\n * include a valid `Authorization: Bearer` header automatically.\n *\n * This is the only client surface in the package; keeping it isolated in the\n * `.` entry is what lets the top-level `\"use client\"` above survive bundling.\n */\n\nimport { SessionProvider, signIn, signOut, useSession } from \"next-auth/react\";\nimport { useCallback, useEffect, useMemo } from \"react\";\n\nimport { CmsProvider } from \"inscribed\";\n\n/**\n * @import { CmsConfig, BlockResponse } from \"inscribed\"\n */\n\n/**\n * Inner component: needs to be inside `SessionProvider` to call `useSession`.\n *\n * @param {{\n * config: CmsConfig | { baseUrl: string },\n * isAdmin: boolean,\n * userSub: string | null,\n * initialBlocks?: BlockResponse[],\n * onAfterSave?: (slug: string) => void | Promise<void>,\n * children: React.ReactNode,\n * }} props\n */\nfunction Inner({ config, isAdmin, userSub, initialBlocks, onAfterSave, children }) {\n const { data: session } = useSession();\n\n useEffect(() => {\n if (session?.error === \"RefreshAccessTokenError\") signIn();\n }, [session?.error]);\n\n const getAccessToken = useCallback(\n async () => /** @type {string} */ (session?.accessToken ?? \"\"),\n [session?.accessToken],\n );\n\n // Surface identity for the admin panel footer. Re-build only when the\n // underlying values change so CmsProvider's memo doesn't bust on every\n // render of this component.\n const userInfo = useMemo(\n () =>\n session?.user\n ? {\n name: session.user.name ?? null,\n email: session.user.email ?? null,\n image: session.user.image ?? null,\n }\n : null,\n [session?.user?.name, session?.user?.email, session?.user?.image],\n );\n\n const onSignOut = useCallback(() => {\n signOut({ callbackUrl: \"/\" });\n }, []);\n\n return (\n <CmsProvider config={config} isAdmin={isAdmin} userSub={userSub}\n initialBlocks={initialBlocks} onAfterSave={onAfterSave}\n getAccessToken={isAdmin ? getAccessToken : undefined}\n userInfo={userInfo}\n onSignOut={onSignOut}\n >\n {children}\n </CmsProvider>\n );\n}\n\n/**\n * Drop-in replacement for `CmsProvider` when using NextAuth + Keycloak.\n *\n * The parent Server Component should:\n * 1. Call `getServerSession(authOptions)` to get the session\n * 2. Derive `isAdmin` (e.g. `session !== null`) and `userSub` (`session?.user?.id`)\n * 3. Server-fetch `initialBlocks` with `getCmsContent`\n * 4. Pass `onAfterSave={revalidateCmsSlug}` from `inscribed/actions`\n *\n * @param {{\n * config: CmsConfig | { baseUrl: string },\n * isAdmin: boolean,\n * userSub: string | null,\n * initialBlocks?: BlockResponse[],\n * onAfterSave?: (slug: string) => void | Promise<void>,\n * session?: import(\"next-auth\").Session | null,\n * children: React.ReactNode,\n * }} props\n */\nexport function NextAuthCmsProvider({ session, ...props }) {\n return (\n <SessionProvider session={session}>\n <Inner {...props} />\n </SessionProvider>\n );\n}\n"],"mappings":";;;AAgBA,SAAS,iBAAiB,QAAQ,SAAS,kBAAkB;AAC7D,SAAS,aAAa,WAAW,eAAe;AAEhD,SAAS,mBAAmB;AAkDxB;AAhCJ,SAAS,MAAM,EAAE,QAAQ,SAAS,SAAS,eAAe,aAAa,SAAS,GAAG;AACjF,QAAM,EAAE,MAAM,QAAQ,IAAI,WAAW;AAErC,YAAU,MAAM;AACd,QAAI,SAAS,UAAU,0BAA2B,QAAO;AAAA,EAC3D,GAAG,CAAC,SAAS,KAAK,CAAC;AAEnB,QAAM,iBAAiB;AAAA,IACrB;AAAA;AAAA,MAAmC,SAAS,eAAe;AAAA;AAAA,IAC3D,CAAC,SAAS,WAAW;AAAA,EACvB;AAKA,QAAM,WAAW;AAAA,IACf,MACE,SAAS,OACL;AAAA,MACE,MAAM,QAAQ,KAAK,QAAQ;AAAA,MAC3B,OAAO,QAAQ,KAAK,SAAS;AAAA,MAC7B,OAAO,QAAQ,KAAK,SAAS;AAAA,IAC/B,IACA;AAAA,IACN,CAAC,SAAS,MAAM,MAAM,SAAS,MAAM,OAAO,SAAS,MAAM,KAAK;AAAA,EAClE;AAEA,QAAM,YAAY,YAAY,MAAM;AAClC,YAAQ,EAAE,aAAa,IAAI,CAAC;AAAA,EAC9B,GAAG,CAAC,CAAC;AAEL,SACE;AAAA,IAAC;AAAA;AAAA,MAAY;AAAA,MAAgB;AAAA,MAAkB;AAAA,MAC7C;AAAA,MAA8B;AAAA,MAC9B,gBAAgB,UAAU,iBAAiB;AAAA,MAC3C;AAAA,MACA;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;AAqBO,SAAS,oBAAoB,EAAE,SAAS,GAAG,MAAM,GAAG;AACzD,SACE,oBAAC,mBAAgB,SACf,8BAAC,SAAO,GAAG,OAAO,GACpB;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../src/index.jsx"],"sourcesContent":["\"use client\";\n\n/**\n * @file `@skylab-kulubu/inscribed-auth` — client entry.\n *\n * NextAuth-aware wrapper around inscribed's `CmsProvider`. The inscribed core is\n * auth-agnostic; this is Skylab's NextAuth + Keycloak client wiring.\n *\n * Wraps children with NextAuth's `SessionProvider` (so you don't need to add it\n * to `layout.jsx`) and feeds `useSession()` into `CmsProvider` so admin saves\n * include a valid `Authorization: Bearer` header automatically.\n *\n * This is the only client surface in the package; keeping it isolated in the\n * `.` entry is what lets the top-level `\"use client\"` above survive bundling.\n */\n\nimport { SessionProvider, signIn, signOut, useSession } from \"next-auth/react\";\nimport { useCallback, useEffect, useMemo } from \"react\";\n\nimport { CmsProvider } from \"inscribed\";\n\n/**\n * @import { CmsConfig, BlockResponse } from \"inscribed\"\n */\n\n/**\n * Inner component: needs to be inside `SessionProvider` to call `useSession`.\n *\n * @param {{\n * config: CmsConfig | { baseUrl: string },\n * isAdmin: boolean,\n * userSub: string | null,\n * initialBlocks?: BlockResponse[],\n * onAfterSave?: (slug: string) => void | Promise<void>,\n * children: React.ReactNode,\n * }} props\n */\nfunction Inner({ config, isAdmin, userSub, initialBlocks, onAfterSave, children }) {\n const { data: session } = useSession();\n\n useEffect(() => {\n // Pass the provider id explicitly. Bare `signIn()` redirects to NextAuth's\n // provider-picker (\"Sign in with Keycloak\") interstitial; `signIn(\"keycloak\")`\n // POSTs straight into the Keycloak flow and silently re-auths while the\n // Keycloak SSO session is still alive - no extra page, no extra click.\n if (session?.error === \"RefreshAccessTokenError\") signIn(\"keycloak\");\n }, [session?.error]);\n\n const getAccessToken = useCallback(\n async () => /** @type {string} */ (session?.accessToken ?? \"\"),\n [session?.accessToken],\n );\n\n // Surface identity for the admin panel footer. Re-build only when the\n // underlying values change so CmsProvider's memo doesn't bust on every\n // render of this component.\n const userInfo = useMemo(\n () =>\n session?.user\n ? {\n name: session.user.name ?? null,\n email: session.user.email ?? null,\n image: session.user.image ?? null,\n }\n : null,\n [session?.user?.name, session?.user?.email, session?.user?.image],\n );\n\n const onSignOut = useCallback(() => {\n signOut({ callbackUrl: \"/\" });\n }, []);\n\n return (\n <CmsProvider config={config} isAdmin={isAdmin} userSub={userSub}\n initialBlocks={initialBlocks} onAfterSave={onAfterSave}\n getAccessToken={isAdmin ? getAccessToken : undefined}\n userInfo={userInfo}\n onSignOut={onSignOut}\n >\n {children}\n </CmsProvider>\n );\n}\n\n/**\n * Drop-in replacement for `CmsProvider` when using NextAuth + Keycloak.\n *\n * The parent Server Component should:\n * 1. Call `getServerSession(authOptions)` to get the session\n * 2. Derive `isAdmin` (e.g. `session !== null`) and `userSub` (`session?.user?.id`)\n * 3. Server-fetch `initialBlocks` with `getCmsContent`\n * 4. Pass `onAfterSave={revalidateCmsSlug}` from `inscribed/actions`\n *\n * @param {{\n * config: CmsConfig | { baseUrl: string },\n * isAdmin: boolean,\n * userSub: string | null,\n * initialBlocks?: BlockResponse[],\n * onAfterSave?: (slug: string) => void | Promise<void>,\n * session?: import(\"next-auth\").Session | null,\n * children: React.ReactNode,\n * }} props\n */\nexport function NextAuthCmsProvider({ session, ...props }) {\n return (\n <SessionProvider session={session}>\n <Inner {...props} />\n </SessionProvider>\n );\n}"],"mappings":";;;AAgBA,SAAS,iBAAiB,QAAQ,SAAS,kBAAkB;AAC7D,SAAS,aAAa,WAAW,eAAe;AAEhD,SAAS,mBAAmB;AAsDxB;AApCJ,SAAS,MAAM,EAAE,QAAQ,SAAS,SAAS,eAAe,aAAa,SAAS,GAAG;AACjF,QAAM,EAAE,MAAM,QAAQ,IAAI,WAAW;AAErC,YAAU,MAAM;AAKd,QAAI,SAAS,UAAU,0BAA2B,QAAO,UAAU;AAAA,EACrE,GAAG,CAAC,SAAS,KAAK,CAAC;AAEnB,QAAM,iBAAiB;AAAA,IACrB;AAAA;AAAA,MAAmC,SAAS,eAAe;AAAA;AAAA,IAC3D,CAAC,SAAS,WAAW;AAAA,EACvB;AAKA,QAAM,WAAW;AAAA,IACf,MACE,SAAS,OACL;AAAA,MACE,MAAM,QAAQ,KAAK,QAAQ;AAAA,MAC3B,OAAO,QAAQ,KAAK,SAAS;AAAA,MAC7B,OAAO,QAAQ,KAAK,SAAS;AAAA,IAC/B,IACA;AAAA,IACN,CAAC,SAAS,MAAM,MAAM,SAAS,MAAM,OAAO,SAAS,MAAM,KAAK;AAAA,EAClE;AAEA,QAAM,YAAY,YAAY,MAAM;AAClC,YAAQ,EAAE,aAAa,IAAI,CAAC;AAAA,EAC9B,GAAG,CAAC,CAAC;AAEL,SACE;AAAA,IAAC;AAAA;AAAA,MAAY;AAAA,MAAgB;AAAA,MAAkB;AAAA,MAC7C;AAAA,MAA8B;AAAA,MAC9B,gBAAgB,UAAU,iBAAiB;AAAA,MAC3C;AAAA,MACA;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;AAqBO,SAAS,oBAAoB,EAAE,SAAS,GAAG,MAAM,GAAG;AACzD,SACE,oBAAC,mBAAgB,SACf,8BAAC,SAAO,GAAG,OAAO,GACpB;AAEJ;","names":[]}
package/dist/server.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as next_auth from 'next-auth';
2
- export { d as debugServiceTokenClaims, g as getClientCredentialsToken } from './service-token-COa7hHuV.js';
2
+ export { d as debugServiceTokenClaims, g as getClientCredentialsToken } from './service-token-CHJDdnHv.js';
3
3
 
4
4
  /**
5
5
  * @typedef {Object} CmsAuthMeta
@@ -18,6 +18,11 @@ export { d as debugServiceTokenClaims, g as getClientCredentialsToken } from './
18
18
  * Override admin gating with arbitrary logic. Wins over `adminRole`.
19
19
  * @property {number} [refreshLeadTimeMs]
20
20
  * Refresh access tokens this many ms before expiry. Default 10 000.
21
+ * @property {string|false} [signInPage]
22
+ * Path NextAuth redirects unauthenticated users to. Defaults to
23
+ * `"/api/signin"` (the package's auto-submit route) so sign-in jumps straight
24
+ * into Keycloak instead of NextAuth's built-in "Sign in with X" picker. Set
25
+ * `false` to keep the picker.
21
26
  * @property {Partial<import("next-auth").AuthOptions["callbacks"]>} [extraCallbacks]
22
27
  * Extra callbacks merged on top of the built-in ones. Each callback runs
23
28
  * AFTER the built-in version and receives the already-augmented value.
@@ -96,6 +101,13 @@ type CreateCmsAuthOptionsInput = {
96
101
  * Refresh access tokens this many ms before expiry. Default 10 000.
97
102
  */
98
103
  refreshLeadTimeMs?: number | undefined;
104
+ /**
105
+ * Path NextAuth redirects unauthenticated users to. Defaults to
106
+ * `"/api/signin"` (the package's auto-submit route) so sign-in jumps straight
107
+ * into Keycloak instead of NextAuth's built-in "Sign in with X" picker. Set
108
+ * `false` to keep the picker.
109
+ */
110
+ signInPage?: string | false | undefined;
99
111
  /**
100
112
  * Extra callbacks merged on top of the built-in ones. Each callback runs
101
113
  * AFTER the built-in version and receives the already-augmented value.
package/dist/server.js CHANGED
@@ -7,6 +7,7 @@ function createCmsAuthOptions(input) {
7
7
  adminRole = "cms:access",
8
8
  isAdmin,
9
9
  refreshLeadTimeMs = 1e4,
10
+ signInPage = "/api/signin",
10
11
  extraCallbacks,
11
12
  extraOptions
12
13
  } = input ?? {};
@@ -15,7 +16,6 @@ function createCmsAuthOptions(input) {
15
16
  "createCmsAuthOptions: `provider` is required. Import a NextAuth provider (e.g. `next-auth/providers/keycloak`) in your own auth file and pass the configured instance."
16
17
  );
17
18
  }
18
- const keycloakClientId = process.env.KEYCLOAK_CLIENT_ID ?? "";
19
19
  const base = {
20
20
  providers: [provider],
21
21
  callbacks: {
@@ -28,13 +28,14 @@ function createCmsAuthOptions(input) {
28
28
  next.accessTokenExpires = typeof account.expires_at === "number" ? account.expires_at * 1e3 : 0;
29
29
  next.sub = account.providerAccountId ?? next.sub;
30
30
  next.error = void 0;
31
- next.clientRoles = readClientRoles(account.access_token, keycloakClientId);
31
+ next.idToken = account.id_token;
32
+ next.clientRoles = readClientRoles(account.access_token);
32
33
  } else if (
33
34
  // 2. Previous refresh failed - bail until the user re-authenticates.
34
35
  next.error !== "RefreshAccessTokenError" && // 3. Token still valid (with lead time) - return as-is.
35
36
  (typeof next.accessTokenExpires !== "number" || Date.now() >= next.accessTokenExpires - refreshLeadTimeMs)
36
37
  ) {
37
- next = await refreshAccessToken(next, keycloakClientId);
38
+ next = await refreshAccessToken(next);
38
39
  }
39
40
  if (extraCallbacks?.jwt) {
40
41
  const overridden = await extraCallbacks.jwt({ ...args, token: next });
@@ -65,7 +66,25 @@ function createCmsAuthOptions(input) {
65
66
  )
66
67
  ) : {}
67
68
  },
68
- ...extraOptions
69
+ ...extraOptions,
70
+ pages: {
71
+ ...signInPage ? { signIn: signInPage } : {},
72
+ ...extraOptions?.pages
73
+ },
74
+ events: {
75
+ ...extraOptions?.events,
76
+ // Federated (RP-initiated) logout: also end the Keycloak SSO session, so
77
+ // the next sign-in doesn't silently re-authenticate against a still-live
78
+ // session. A consumer-supplied signOut (preserved by the spread above)
79
+ // still runs afterwards.
80
+ async signOut(message) {
81
+ const token = message && "token" in message ? message.token : null;
82
+ await endKeycloakSession(token?.idToken);
83
+ if (typeof extraOptions?.events?.signOut === "function") {
84
+ await extraOptions.events.signOut(message);
85
+ }
86
+ }
87
+ }
69
88
  };
70
89
  const meta = {
71
90
  adminRole: isAdmin ? null : adminRole,
@@ -98,20 +117,21 @@ function withCmsAuth(authOptions) {
98
117
  deriveUserSub: (session) => session?.user?.id ?? null
99
118
  };
100
119
  }
101
- function readClientRoles(accessToken, clientId) {
102
- if (!accessToken || !clientId) return [];
120
+ function readClientRoles(accessToken) {
121
+ if (!accessToken) return [];
103
122
  const segments = accessToken.split(".");
104
123
  if (segments.length < 2) return [];
105
124
  try {
106
125
  const payload = JSON.parse(
107
126
  Buffer.from(segments[1], "base64url").toString("utf8")
108
127
  );
109
- return payload?.resource_access?.[clientId]?.roles ?? [];
128
+ const resourceAccess = payload?.resource_access ?? {};
129
+ return Object.values(resourceAccess).flatMap((client) => client?.roles ?? []);
110
130
  } catch {
111
131
  return [];
112
132
  }
113
133
  }
114
- async function refreshAccessToken(token, keycloakClientId) {
134
+ async function refreshAccessToken(token) {
115
135
  try {
116
136
  const issuer = process.env.KEYCLOAK_ISSUER ?? "";
117
137
  const response = await fetch(`${issuer}/protocol/openid-connect/token`, {
@@ -131,7 +151,8 @@ async function refreshAccessToken(token, keycloakClientId) {
131
151
  accessToken: refreshed.access_token,
132
152
  accessTokenExpires: Date.now() + refreshed.expires_in * 1e3,
133
153
  refreshToken: refreshed.refresh_token ?? token.refreshToken,
134
- clientRoles: readClientRoles(refreshed.access_token, keycloakClientId),
154
+ idToken: refreshed.id_token ?? token.idToken,
155
+ clientRoles: readClientRoles(refreshed.access_token),
135
156
  error: void 0
136
157
  };
137
158
  } catch (error) {
@@ -143,6 +164,18 @@ async function refreshAccessToken(token, keycloakClientId) {
143
164
  };
144
165
  }
145
166
  }
167
+ async function endKeycloakSession(idToken) {
168
+ const issuer = process.env.KEYCLOAK_ISSUER;
169
+ if (!idToken || !issuer) return;
170
+ try {
171
+ await fetch(
172
+ `${issuer}/protocol/openid-connect/logout?${new URLSearchParams({
173
+ id_token_hint: idToken
174
+ })}`
175
+ );
176
+ } catch {
177
+ }
178
+ }
146
179
 
147
180
  // src/lib/service-token.mjs
148
181
  var cache = null;
@@ -196,10 +229,16 @@ async function debugServiceTokenClaims() {
196
229
  console.error(` aud: ${JSON.stringify(claims.aud)}`);
197
230
  console.error(` scope: ${claims.scope}`);
198
231
  console.error(` resource_access: ${JSON.stringify(claims.resource_access)}`);
199
- const ourRoles = claims.resource_access?.[claims.azp]?.roles ?? [];
200
- console.error(` -> roles for "${claims.azp}": ${JSON.stringify(ourRoles)}`);
201
- if (!ourRoles.includes("cms:access")) {
202
- console.error(` ! "cms:access" role missing on service account.`);
232
+ const ra = claims.resource_access ?? {};
233
+ const holder = Object.keys(ra).find((c) => ra[c]?.roles?.includes("cms:access"));
234
+ if (holder) {
235
+ console.error(` -> "cms:access" found under resource_access["${holder}"].`);
236
+ if (holder !== claims.azp) {
237
+ console.error(` (owned by backend client "${holder}", not azp "${claims.azp}" - expected)`);
238
+ }
239
+ } else {
240
+ console.error(` ! "cms:access" role missing from every client in resource_access.`);
241
+ console.error(` Assign the backend client's "cms:access" role to this service account:`);
203
242
  console.error(` Keycloak Admin -> Clients -> ${claims.azp} -> Service account roles -> Assign "cms:access".`);
204
243
  }
205
244
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/options.js","../src/lib/service-token.mjs"],"sourcesContent":["/**\n * @file Pre-wired NextAuth options for inscribed CMS apps (Skylab auth adapter).\n *\n * Part of `@skylab-kulubu/inscribed-auth`. The inscribed core is auth-agnostic;\n * this module is Skylab's NextAuth + Keycloak server wiring on top of it.\n *\n * `createCmsAuthOptions()` returns a complete `AuthOptions` object suitable\n * for `NextAuth(...)` in `app/api/auth/[...nextauth]/route.js`. It bundles:\n * - JWT callback that persists Keycloak access/refresh tokens\n * - Silent refresh of expired access tokens\n * - Client-role extraction from the access token\n * - Session callback that exposes `accessToken`, `user.id`, `user.clientRoles`\n *\n * The OAuth provider itself stays on the consumer side - import\n * `next-auth/providers/keycloak` (or any other provider) in your own\n * `lib/auth.js` and pass the configured instance via `provider`. Importing\n * NextAuth provider modules from a bundled package breaks Webpack's\n * CJS/ESM interop and the provider resolves to `undefined` at runtime.\n *\n * Admin metadata (`adminRole` / `isAdmin`) is stamped onto the returned\n * options so `createCmsPage({ ...withCmsAuth(authOptions) })` can derive admin\n * gating automatically without the caller wiring a separate `deriveAdmin`.\n */\n\nimport { getServerSession } from \"next-auth\";\n\n/** @type {unique symbol} */\nconst CMS_META = Symbol.for(\"inscribed/auth.meta\");\n\n/**\n * @typedef {Object} CmsAuthMeta\n * @property {string|null} adminRole\n * @property {((session: *) => boolean)|null} isAdmin\n */\n\n/**\n * @typedef {Object} CreateCmsAuthOptionsInput\n * @property {*} provider\n * Configured NextAuth provider instance. Import the provider module on\n * the consumer side (typically `next-auth/providers/keycloak`) and pass\n * the result of calling it. Required.\n * @property {string} [adminRole]\n * Keycloak client role required for admin access. Default `\"cms:access\"`.\n * @property {(session: *) => boolean} [isAdmin]\n * Override admin gating with arbitrary logic. Wins over `adminRole`.\n * @property {number} [refreshLeadTimeMs]\n * Refresh access tokens this many ms before expiry. Default 10 000.\n * @property {Partial<import(\"next-auth\").AuthOptions[\"callbacks\"]>} [extraCallbacks]\n * Extra callbacks merged on top of the built-in ones. Each callback runs\n * AFTER the built-in version and receives the already-augmented value.\n * @property {Partial<import(\"next-auth\").AuthOptions>} [extraOptions]\n * Anything else (pages, cookies, events, ...) merged onto the result.\n */\n\n/**\n * Build a ready-to-use NextAuth `AuthOptions` object.\n *\n * @param {CreateCmsAuthOptionsInput} input\n * @returns {import(\"next-auth\").AuthOptions & { [CMS_META]: CmsAuthMeta }}\n */\nexport function createCmsAuthOptions(input) {\n const {\n provider,\n adminRole = \"cms:access\",\n isAdmin,\n refreshLeadTimeMs = 10_000,\n extraCallbacks,\n extraOptions,\n } = input ?? {};\n\n if (!provider) {\n throw new Error(\n \"createCmsAuthOptions: `provider` is required. Import a NextAuth provider \" +\n \"(e.g. `next-auth/providers/keycloak`) in your own auth file and pass \" +\n \"the configured instance.\",\n );\n }\n\n const keycloakClientId = process.env.KEYCLOAK_CLIENT_ID ?? \"\";\n\n /** @type {import(\"next-auth\").AuthOptions} */\n const base = {\n providers: [provider],\n callbacks: {\n async jwt(args) {\n const { token, account } = args;\n let next = token;\n\n // 1. Initial sign-in: copy tokens off the OAuth account.\n if (account) {\n next.accessToken = account.access_token;\n next.refreshToken = account.refresh_token;\n next.accessTokenExpires =\n typeof account.expires_at === \"number\" ? account.expires_at * 1000 : 0;\n next.sub = account.providerAccountId ?? next.sub;\n next.error = undefined;\n next.clientRoles = readClientRoles(account.access_token, keycloakClientId);\n } else if (\n // 2. Previous refresh failed - bail until the user re-authenticates.\n next.error !== \"RefreshAccessTokenError\" &&\n // 3. Token still valid (with lead time) - return as-is.\n (typeof next.accessTokenExpires !== \"number\" ||\n Date.now() >= next.accessTokenExpires - refreshLeadTimeMs)\n ) {\n // 4. Expired (or about to) - silently refresh.\n next = await refreshAccessToken(next, keycloakClientId);\n }\n\n if (extraCallbacks?.jwt) {\n const overridden = await extraCallbacks.jwt({ ...args, token: next });\n if (overridden !== undefined) return overridden;\n }\n return next;\n },\n\n async session(args) {\n const { session, token } = args;\n session.accessToken = /** @type {string|undefined} */ (token.accessToken);\n session.error = token.error;\n if (session.user) {\n session.user.id = /** @type {string} */ (token.sub ?? \"\");\n session.user.clientRoles =\n /** @type {string[]} */ (token.clientRoles ?? []);\n }\n\n if (extraCallbacks?.session) {\n const overridden = await extraCallbacks.session(args);\n if (overridden !== undefined) return overridden;\n }\n return session;\n },\n\n ...(extraCallbacks\n ? Object.fromEntries(\n Object.entries(extraCallbacks).filter(\n ([key]) => key !== \"jwt\" && key !== \"session\",\n ),\n )\n : {}),\n },\n ...extraOptions,\n };\n\n /** @type {CmsAuthMeta} */\n const meta = {\n adminRole: isAdmin ? null : adminRole,\n isAdmin: isAdmin ?? null,\n };\n\n return Object.assign(base, { [CMS_META]: meta });\n}\n\n/**\n * Read CMS admin metadata previously stamped by `createCmsAuthOptions`.\n * Returns null if the options didn't come from the factory.\n *\n * @param {*} authOptions\n * @returns {CmsAuthMeta|null}\n */\nexport function readCmsAuthMeta(authOptions) {\n if (!authOptions || typeof authOptions !== \"object\") return null;\n return authOptions[CMS_META] ?? null;\n}\n\n/**\n * Decide whether a session belongs to a CMS admin. Uses `isAdmin` callback\n * when provided, otherwise checks for the named Keycloak client role.\n * Falls back to `false` when no metadata is available.\n *\n * @param {*} session\n * @param {CmsAuthMeta|null} [meta]\n * @returns {boolean}\n */\nexport function isCmsAdmin(session, meta) {\n if (!session) return false;\n if (!meta) return false;\n if (meta.isAdmin) return Boolean(meta.isAdmin(session));\n if (meta.adminRole) {\n /** @type {string[]} */\n const roles = session.user?.clientRoles ?? [];\n return roles.includes(meta.adminRole);\n }\n return false;\n}\n\n/**\n * Adapt NextAuth `authOptions` into the auth-agnostic callbacks\n * `createCmsPage` expects, so the inscribed core never has to import next-auth.\n * Spread the result into the factory:\n *\n * import { withCmsAuth } from \"@skylab-kulubu/inscribed-auth/server\";\n * createCmsPage({ ...withCmsAuth(authOptions), config, Provider, ... });\n *\n * - `getSession` resolves the server session via `getServerSession`.\n * - `deriveAdmin` uses the admin metadata stamped by `createCmsAuthOptions`\n * (falls back to `session != null` when the options didn't come from the\n * factory).\n * - `deriveUserSub` reads `session.user.id`.\n *\n * @param {import(\"next-auth\").AuthOptions} authOptions\n * @returns {{ getSession: () => Promise<*|null>, deriveAdmin: (session: *) => boolean, deriveUserSub: (session: *) => string | null }}\n */\nexport function withCmsAuth(authOptions) {\n if (!authOptions) {\n throw new Error(\"withCmsAuth: `authOptions` is required\");\n }\n const meta = readCmsAuthMeta(authOptions);\n return {\n getSession: () => getServerSession(authOptions),\n deriveAdmin: meta\n ? (session) => isCmsAdmin(session, meta)\n : (session) => session != null,\n deriveUserSub: (session) => session?.user?.id ?? null,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\n/**\n * Decode a Keycloak access token (JWT) and return roles scoped to the\n * given client. Signature isn't verified - the token came from Keycloak\n * directly via the OAuth flow, so trust is established.\n *\n * @param {string|undefined} accessToken\n * @param {string} clientId\n * @returns {string[]}\n */\nfunction readClientRoles(accessToken, clientId) {\n if (!accessToken || !clientId) return [];\n const segments = accessToken.split(\".\");\n if (segments.length < 2) return [];\n try {\n const payload = JSON.parse(\n Buffer.from(segments[1], \"base64url\").toString(\"utf8\"),\n );\n return payload?.resource_access?.[clientId]?.roles ?? [];\n } catch {\n return [];\n }\n}\n\n/**\n * Exchange the refresh token for a new access token at Keycloak.\n *\n * @param {*} token\n * @param {string} keycloakClientId\n */\nasync function refreshAccessToken(token, keycloakClientId) {\n try {\n const issuer = process.env.KEYCLOAK_ISSUER ?? \"\";\n const response = await fetch(`${issuer}/protocol/openid-connect/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: process.env.KEYCLOAK_CLIENT_ID ?? \"\",\n client_secret: process.env.KEYCLOAK_CLIENT_SECRET ?? \"\",\n grant_type: \"refresh_token\",\n refresh_token: token.refreshToken,\n }),\n });\n\n const refreshed = await response.json();\n if (!response.ok) throw refreshed;\n\n return {\n ...token,\n accessToken: refreshed.access_token,\n accessTokenExpires: Date.now() + refreshed.expires_in * 1000,\n refreshToken: refreshed.refresh_token ?? token.refreshToken,\n clientRoles: readClientRoles(refreshed.access_token, keycloakClientId),\n error: undefined,\n };\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"[inscribed-auth] Refresh token error:\", error);\n return {\n ...token,\n accessToken: undefined,\n error: \"RefreshAccessTokenError\",\n };\n }\n}\n","/**\n * @file Keycloak client-credentials service-token provider.\n *\n * Part of `@skylab-kulubu/inscribed-auth`. The inscribed core is backend-neutral:\n * it only knows the `ServiceTokenProvider` contract (`() => Promise<string>`)\n * and defaults to \"no token\". This module implements that contract against\n * Keycloak and is wired into the SDK via `createCmsPage({ getServiceToken })`\n * (consumer `lib/cms.jsx`) and the `cms-sync` CLI (consumer `cms.config.mjs`,\n * which re-exports from `@skylab-kulubu/inscribed-auth/config`).\n *\n * `.mjs` so the plain-Node `cms-sync` CLI can `import()` the resolved `./config`\n * entry as ESM regardless of the consuming app's `\"type\"`. (Skylab apps stay\n * CommonJS so next-auth v4's Keycloak provider resolves through Webpack's CJS\n * interop — see the provider-injection note in `options.js`.)\n *\n * Server / build-time only. Reads KEYCLOAK_CLIENT_ID, KEYCLOAK_CLIENT_SECRET,\n * KEYCLOAK_ISSUER. Returns \"\" when those vars are absent so reads degrade to\n * unauthenticated. In-process cache shared across requests, re-fetched 30s\n * before expiry.\n */\n\n/** @type {{ token: string; expiresAt: number } | null} */\nlet cache = null;\n\n/**\n * Implements the SDK's `ServiceTokenProvider` contract: `() => Promise<string>`.\n * @returns {Promise<string>}\n */\nexport async function getClientCredentialsToken() {\n const clientId = process.env.KEYCLOAK_CLIENT_ID;\n const clientSecret = process.env.KEYCLOAK_CLIENT_SECRET;\n const issuer = process.env.KEYCLOAK_ISSUER;\n\n if (!clientId || !clientSecret || !issuer) return \"\";\n\n if (cache && cache.expiresAt > Date.now() + 30_000) return cache.token;\n\n const res = await fetch(`${issuer}/protocol/openid-connect/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"client_credentials\",\n client_id: clientId,\n client_secret: clientSecret,\n }),\n cache: \"no-store\",\n });\n\n if (!res.ok) {\n throw new Error(\n `[inscribed-auth] Keycloak token request failed: ${res.status} ${await res.text()}`,\n );\n }\n\n const { access_token, expires_in } = await res.json();\n cache = { token: access_token, expiresAt: Date.now() + expires_in * 1000 };\n return access_token;\n}\n\n/**\n * Drop the cached service token so the next call re-fetches. Intentionally NOT\n * part of the public `./server` surface — kept here for internal use and for\n * anyone who deep-imports the raw module (e.g. token rotation in tests).\n */\nexport function invalidateClientCredentialsToken() {\n cache = null;\n}\n\n/**\n * On a sync failure, fetch the service token directly and dump the claims the\n * backend's `CmsAccessPolicy` checks (`azp`, `aud`, `resource_access`). Most\n * 403s come from the service account missing the `cms:access` role mapping in\n * Keycloak - this prints exactly what's there. Wired as `onSyncError` in the\n * `./config` entry.\n */\nexport async function debugServiceTokenClaims() {\n const { KEYCLOAK_CLIENT_ID, KEYCLOAK_CLIENT_SECRET, KEYCLOAK_ISSUER } = process.env;\n if (!KEYCLOAK_CLIENT_ID || !KEYCLOAK_CLIENT_SECRET || !KEYCLOAK_ISSUER) return;\n\n const res = await fetch(`${KEYCLOAK_ISSUER}/protocol/openid-connect/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"client_credentials\",\n client_id: KEYCLOAK_CLIENT_ID,\n client_secret: KEYCLOAK_CLIENT_SECRET,\n }),\n });\n if (!res.ok) {\n console.error(`[cms-sync:debug] Token fetch failed: ${res.status} ${await res.text()}`);\n return;\n }\n\n const { access_token } = await res.json();\n const [, payload] = access_token.split(\".\");\n const claims = JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf8\"));\n\n console.error(\"[cms-sync:debug] Service token claims:\");\n console.error(` azp: ${claims.azp}`);\n console.error(` sub: ${claims.sub}`);\n console.error(` aud: ${JSON.stringify(claims.aud)}`);\n console.error(` scope: ${claims.scope}`);\n console.error(` resource_access: ${JSON.stringify(claims.resource_access)}`);\n\n const ourRoles = claims.resource_access?.[claims.azp]?.roles ?? [];\n console.error(` -> roles for \"${claims.azp}\": ${JSON.stringify(ourRoles)}`);\n if (!ourRoles.includes(\"cms:access\")) {\n console.error(` ! \"cms:access\" role missing on service account.`);\n console.error(` Keycloak Admin -> Clients -> ${claims.azp} -> Service account roles -> Assign \"cms:access\".`);\n }\n}\n"],"mappings":";AAwBA,SAAS,wBAAwB;AAGjC,IAAM,WAAW,uBAAO,IAAI,qBAAqB;AAiC1C,SAAS,qBAAqB,OAAO;AAC1C,QAAM;AAAA,IACJ;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA,oBAAoB;AAAA,IACpB;AAAA,IACA;AAAA,EACF,IAAI,SAAS,CAAC;AAEd,MAAI,CAAC,UAAU;AACb,UAAM,IAAI;AAAA,MACR;AAAA,IAGF;AAAA,EACF;AAEA,QAAM,mBAAmB,QAAQ,IAAI,sBAAsB;AAG3D,QAAM,OAAO;AAAA,IACX,WAAW,CAAC,QAAQ;AAAA,IACpB,WAAW;AAAA,MACT,MAAM,IAAI,MAAM;AACd,cAAM,EAAE,OAAO,QAAQ,IAAI;AAC3B,YAAI,OAAO;AAGX,YAAI,SAAS;AACX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AAQ,MAAM,sBAAsB,KAAK,UAAU,OAAO,eAAe,CAAC,EAAE;AAE5E,QAAM,WAAW,OAAO,kBAAkB,OAAO,GAAG,GAAG,SAAS,CAAC;AACjE,UAAQ,MAAM,mBAAmB,OAAO,GAAG,MAAM,KAAK,UAAU,QAAQ,CAAC,EAAE;AAC3E,MAAI,CAAC,SAAS,SAAS,YAAY,GAAG;AACpC,YAAQ,MAAM,mDAAmD;AACjE,YAAQ,MAAM,qCAAqC,OAAO,GAAG,mDAAmD;AAAA,EAClH;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/lib/options.js","../src/lib/service-token.mjs"],"sourcesContent":["/**\n * @file Pre-wired NextAuth options for inscribed CMS apps (Skylab auth adapter).\n *\n * Part of `@skylab-kulubu/inscribed-auth`. The inscribed core is auth-agnostic;\n * this module is Skylab's NextAuth + Keycloak server wiring on top of it.\n *\n * `createCmsAuthOptions()` returns a complete `AuthOptions` object suitable\n * for `NextAuth(...)` in `app/api/auth/[...nextauth]/route.js`. It bundles:\n * - JWT callback that persists Keycloak access/refresh tokens\n * - Silent refresh of expired access tokens\n * - Client-role extraction from the access token\n * - Session callback that exposes `accessToken`, `user.id`, `user.clientRoles`\n *\n * The OAuth provider itself stays on the consumer side - import\n * `next-auth/providers/keycloak` (or any other provider) in your own\n * `lib/auth.js` and pass the configured instance via `provider`. Importing\n * NextAuth provider modules from a bundled package breaks Webpack's\n * CJS/ESM interop and the provider resolves to `undefined` at runtime.\n *\n * Admin metadata (`adminRole` / `isAdmin`) is stamped onto the returned\n * options so `createCmsPage({ ...withCmsAuth(authOptions) })` can derive admin\n * gating automatically without the caller wiring a separate `deriveAdmin`.\n */\n\nimport { getServerSession } from \"next-auth\";\n\n/** @type {unique symbol} */\nconst CMS_META = Symbol.for(\"inscribed/auth.meta\");\n\n/**\n * @typedef {Object} CmsAuthMeta\n * @property {string|null} adminRole\n * @property {((session: *) => boolean)|null} isAdmin\n */\n\n/**\n * @typedef {Object} CreateCmsAuthOptionsInput\n * @property {*} provider\n * Configured NextAuth provider instance. Import the provider module on\n * the consumer side (typically `next-auth/providers/keycloak`) and pass\n * the result of calling it. Required.\n * @property {string} [adminRole]\n * Keycloak client role required for admin access. Default `\"cms:access\"`.\n * @property {(session: *) => boolean} [isAdmin]\n * Override admin gating with arbitrary logic. Wins over `adminRole`.\n * @property {number} [refreshLeadTimeMs]\n * Refresh access tokens this many ms before expiry. Default 10 000.\n * @property {string|false} [signInPage]\n * Path NextAuth redirects unauthenticated users to. Defaults to\n * `\"/api/signin\"` (the package's auto-submit route) so sign-in jumps straight\n * into Keycloak instead of NextAuth's built-in \"Sign in with X\" picker. Set\n * `false` to keep the picker.\n * @property {Partial<import(\"next-auth\").AuthOptions[\"callbacks\"]>} [extraCallbacks]\n * Extra callbacks merged on top of the built-in ones. Each callback runs\n * AFTER the built-in version and receives the already-augmented value.\n * @property {Partial<import(\"next-auth\").AuthOptions>} [extraOptions]\n * Anything else (pages, cookies, events, ...) merged onto the result.\n */\n\n/**\n * Build a ready-to-use NextAuth `AuthOptions` object.\n *\n * @param {CreateCmsAuthOptionsInput} input\n * @returns {import(\"next-auth\").AuthOptions & { [CMS_META]: CmsAuthMeta }}\n */\nexport function createCmsAuthOptions(input) {\n const {\n provider,\n adminRole = \"cms:access\",\n isAdmin,\n refreshLeadTimeMs = 10_000,\n signInPage = \"/api/signin\",\n extraCallbacks,\n extraOptions,\n } = input ?? {};\n\n if (!provider) {\n throw new Error(\n \"createCmsAuthOptions: `provider` is required. Import a NextAuth provider \" +\n \"(e.g. `next-auth/providers/keycloak`) in your own auth file and pass \" +\n \"the configured instance.\",\n );\n }\n\n /** @type {import(\"next-auth\").AuthOptions} */\n const base = {\n providers: [provider],\n callbacks: {\n async jwt(args) {\n const { token, account } = args;\n let next = token;\n\n // 1. Initial sign-in: copy tokens off the OAuth account.\n if (account) {\n next.accessToken = account.access_token;\n next.refreshToken = account.refresh_token;\n next.accessTokenExpires =\n typeof account.expires_at === \"number\" ? account.expires_at * 1000 : 0;\n next.sub = account.providerAccountId ?? next.sub;\n next.error = undefined;\n next.idToken = account.id_token;\n next.clientRoles = readClientRoles(account.access_token);\n } else if (\n // 2. Previous refresh failed - bail until the user re-authenticates.\n next.error !== \"RefreshAccessTokenError\" &&\n // 3. Token still valid (with lead time) - return as-is.\n (typeof next.accessTokenExpires !== \"number\" ||\n Date.now() >= next.accessTokenExpires - refreshLeadTimeMs)\n ) {\n // 4. Expired (or about to) - silently refresh.\n next = await refreshAccessToken(next);\n }\n\n if (extraCallbacks?.jwt) {\n const overridden = await extraCallbacks.jwt({ ...args, token: next });\n if (overridden !== undefined) return overridden;\n }\n return next;\n },\n\n async session(args) {\n const { session, token } = args;\n session.accessToken = /** @type {string|undefined} */ (token.accessToken);\n session.error = token.error;\n if (session.user) {\n session.user.id = /** @type {string} */ (token.sub ?? \"\");\n session.user.clientRoles =\n /** @type {string[]} */ (token.clientRoles ?? []);\n }\n\n if (extraCallbacks?.session) {\n const overridden = await extraCallbacks.session(args);\n if (overridden !== undefined) return overridden;\n }\n return session;\n },\n\n ...(extraCallbacks\n ? Object.fromEntries(\n Object.entries(extraCallbacks).filter(\n ([key]) => key !== \"jwt\" && key !== \"session\",\n ),\n )\n : {}),\n },\n ...extraOptions,\n pages: {\n ...(signInPage ? { signIn: signInPage } : {}),\n ...extraOptions?.pages,\n },\n events: {\n ...extraOptions?.events,\n // Federated (RP-initiated) logout: also end the Keycloak SSO session, so\n // the next sign-in doesn't silently re-authenticate against a still-live\n // session. A consumer-supplied signOut (preserved by the spread above)\n // still runs afterwards.\n async signOut(message) {\n const token = message && \"token\" in message ? message.token : null;\n await endKeycloakSession(token?.idToken);\n if (typeof extraOptions?.events?.signOut === \"function\") {\n await extraOptions.events.signOut(message);\n }\n },\n },\n };\n\n /** @type {CmsAuthMeta} */\n const meta = {\n adminRole: isAdmin ? null : adminRole,\n isAdmin: isAdmin ?? null,\n };\n\n return Object.assign(base, { [CMS_META]: meta });\n}\n\n/**\n * Read CMS admin metadata previously stamped by `createCmsAuthOptions`.\n * Returns null if the options didn't come from the factory.\n *\n * @param {*} authOptions\n * @returns {CmsAuthMeta|null}\n */\nexport function readCmsAuthMeta(authOptions) {\n if (!authOptions || typeof authOptions !== \"object\") return null;\n return authOptions[CMS_META] ?? null;\n}\n\n/**\n * Decide whether a session belongs to a CMS admin. Uses `isAdmin` callback\n * when provided, otherwise checks for the named Keycloak client role.\n * Falls back to `false` when no metadata is available.\n *\n * @param {*} session\n * @param {CmsAuthMeta|null} [meta]\n * @returns {boolean}\n */\nexport function isCmsAdmin(session, meta) {\n if (!session) return false;\n if (!meta) return false;\n if (meta.isAdmin) return Boolean(meta.isAdmin(session));\n if (meta.adminRole) {\n /** @type {string[]} */\n const roles = session.user?.clientRoles ?? [];\n return roles.includes(meta.adminRole);\n }\n return false;\n}\n\n/**\n * Adapt NextAuth `authOptions` into the auth-agnostic callbacks\n * `createCmsPage` expects, so the inscribed core never has to import next-auth.\n * Spread the result into the factory:\n *\n * import { withCmsAuth } from \"@skylab-kulubu/inscribed-auth/server\";\n * createCmsPage({ ...withCmsAuth(authOptions), config, Provider, ... });\n *\n * - `getSession` resolves the server session via `getServerSession`.\n * - `deriveAdmin` uses the admin metadata stamped by `createCmsAuthOptions`\n * (falls back to `session != null` when the options didn't come from the\n * factory).\n * - `deriveUserSub` reads `session.user.id`.\n *\n * @param {import(\"next-auth\").AuthOptions} authOptions\n * @returns {{ getSession: () => Promise<*|null>, deriveAdmin: (session: *) => boolean, deriveUserSub: (session: *) => string | null }}\n */\nexport function withCmsAuth(authOptions) {\n if (!authOptions) {\n throw new Error(\"withCmsAuth: `authOptions` is required\");\n }\n const meta = readCmsAuthMeta(authOptions);\n return {\n getSession: () => getServerSession(authOptions),\n deriveAdmin: meta\n ? (session) => isCmsAdmin(session, meta)\n : (session) => session != null,\n deriveUserSub: (session) => session?.user?.id ?? null,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\n/**\n * Decode a Keycloak access token (JWT) and return the principal's client roles\n * aggregated across every entry in `resource_access`. We aggregate rather than\n * scope to a single client because the admin role (`cms:access`) is a client\n * role of the inscribed backend's Keycloak client (e.g. \"skycms\"), not the\n * frontend client the token was issued to (`azp`/`KEYCLOAK_CLIENT_ID`). That\n * backend client only appears in `resource_access` because it's mapped into the\n * token audience, so reading the role straight from `resource_access` is exact\n * and needs no extra config. Signature isn't verified - the token came from\n * Keycloak directly via the OAuth flow, so trust is established.\n *\n * @param {string|undefined} accessToken\n * @returns {string[]}\n */\nfunction readClientRoles(accessToken) {\n if (!accessToken) return [];\n const segments = accessToken.split(\".\");\n if (segments.length < 2) return [];\n try {\n const payload = JSON.parse(\n Buffer.from(segments[1], \"base64url\").toString(\"utf8\"),\n );\n const resourceAccess = payload?.resource_access ?? {};\n return Object.values(resourceAccess).flatMap((client) => client?.roles ?? []);\n } catch {\n return [];\n }\n}\n\n/**\n * Exchange the refresh token for a new access token at Keycloak.\n *\n * @param {*} token\n */\nasync function refreshAccessToken(token) {\n try {\n const issuer = process.env.KEYCLOAK_ISSUER ?? \"\";\n const response = await fetch(`${issuer}/protocol/openid-connect/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: process.env.KEYCLOAK_CLIENT_ID ?? \"\",\n client_secret: process.env.KEYCLOAK_CLIENT_SECRET ?? \"\",\n grant_type: \"refresh_token\",\n refresh_token: token.refreshToken,\n }),\n });\n\n const refreshed = await response.json();\n if (!response.ok) throw refreshed;\n\n return {\n ...token,\n accessToken: refreshed.access_token,\n accessTokenExpires: Date.now() + refreshed.expires_in * 1000,\n refreshToken: refreshed.refresh_token ?? token.refreshToken,\n idToken: refreshed.id_token ?? token.idToken,\n clientRoles: readClientRoles(refreshed.access_token),\n error: undefined,\n };\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"[inscribed-auth] Refresh token error:\", error);\n return {\n ...token,\n accessToken: undefined,\n error: \"RefreshAccessTokenError\",\n };\n }\n}\n\n/**\n * RP-initiated (federated) logout: end the user's Keycloak SSO session so the\n * next sign-in doesn't silently re-authenticate against a still-live session.\n * Best-effort - the NextAuth session is already cleared by the time this runs,\n * so a failure here just means the Keycloak session lingers until it expires.\n *\n * @param {string|undefined} idToken\n */\nasync function endKeycloakSession(idToken) {\n const issuer = process.env.KEYCLOAK_ISSUER;\n if (!idToken || !issuer) return;\n try {\n await fetch(\n `${issuer}/protocol/openid-connect/logout?${new URLSearchParams({\n id_token_hint: idToken,\n })}`,\n );\n } catch {\n /* swallow: best-effort SSO logout */\n }\n}\n","/**\n * @file Keycloak client-credentials service-token provider.\n *\n * Part of `@skylab-kulubu/inscribed-auth`. The inscribed core is backend-neutral:\n * it only knows the `ServiceTokenProvider` contract (`() => Promise<string>`)\n * and defaults to \"no token\". This module implements that contract against\n * Keycloak and is wired into the SDK via `createCmsPage({ getServiceToken })`\n * (consumer `lib/cms.jsx`) and the `cms-sync` CLI (consumer `cms.config.mjs`,\n * which re-exports from `@skylab-kulubu/inscribed-auth/config`).\n *\n * `.mjs` so the plain-Node `cms-sync` CLI can `import()` the resolved `./config`\n * entry as ESM regardless of the consuming app's `\"type\"`. (Skylab apps stay\n * CommonJS so next-auth v4's Keycloak provider resolves through Webpack's CJS\n * interop — see the provider-injection note in `options.js`.)\n *\n * Server / build-time only. Reads KEYCLOAK_CLIENT_ID, KEYCLOAK_CLIENT_SECRET,\n * KEYCLOAK_ISSUER. Returns \"\" when those vars are absent so reads degrade to\n * unauthenticated. In-process cache shared across requests, re-fetched 30s\n * before expiry.\n */\n\n/** @type {{ token: string; expiresAt: number } | null} */\nlet cache = null;\n\n/**\n * Implements the SDK's `ServiceTokenProvider` contract: `() => Promise<string>`.\n * @returns {Promise<string>}\n */\nexport async function getClientCredentialsToken() {\n const clientId = process.env.KEYCLOAK_CLIENT_ID;\n const clientSecret = process.env.KEYCLOAK_CLIENT_SECRET;\n const issuer = process.env.KEYCLOAK_ISSUER;\n\n if (!clientId || !clientSecret || !issuer) return \"\";\n\n if (cache && cache.expiresAt > Date.now() + 30_000) return cache.token;\n\n const res = await fetch(`${issuer}/protocol/openid-connect/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"client_credentials\",\n client_id: clientId,\n client_secret: clientSecret,\n }),\n cache: \"no-store\",\n });\n\n if (!res.ok) {\n throw new Error(\n `[inscribed-auth] Keycloak token request failed: ${res.status} ${await res.text()}`,\n );\n }\n\n const { access_token, expires_in } = await res.json();\n cache = { token: access_token, expiresAt: Date.now() + expires_in * 1000 };\n return access_token;\n}\n\n/**\n * Drop the cached service token so the next call re-fetches. Intentionally NOT\n * part of the public `./server` surface — kept here for internal use and for\n * anyone who deep-imports the raw module (e.g. token rotation in tests).\n */\nexport function invalidateClientCredentialsToken() {\n cache = null;\n}\n\n/**\n * On a sync failure, fetch the service token directly and dump the claims the\n * backend's `CmsAccessPolicy` checks (`azp`, `aud`, `resource_access`). Most\n * 403s come from the service account missing the `cms:access` role mapping in\n * Keycloak - this prints exactly what's there. Wired as `onSyncError` in the\n * `./config` entry.\n */\nexport async function debugServiceTokenClaims() {\n const { KEYCLOAK_CLIENT_ID, KEYCLOAK_CLIENT_SECRET, KEYCLOAK_ISSUER } = process.env;\n if (!KEYCLOAK_CLIENT_ID || !KEYCLOAK_CLIENT_SECRET || !KEYCLOAK_ISSUER) return;\n\n const res = await fetch(`${KEYCLOAK_ISSUER}/protocol/openid-connect/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"client_credentials\",\n client_id: KEYCLOAK_CLIENT_ID,\n client_secret: KEYCLOAK_CLIENT_SECRET,\n }),\n });\n if (!res.ok) {\n console.error(`[cms-sync:debug] Token fetch failed: ${res.status} ${await res.text()}`);\n return;\n }\n\n const { access_token } = await res.json();\n const [, payload] = access_token.split(\".\");\n const claims = JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf8\"));\n\n console.error(\"[cms-sync:debug] Service token claims:\");\n console.error(` azp: ${claims.azp}`);\n console.error(` sub: ${claims.sub}`);\n console.error(` aud: ${JSON.stringify(claims.aud)}`);\n console.error(` scope: ${claims.scope}`);\n console.error(` resource_access: ${JSON.stringify(claims.resource_access)}`);\n\n // `cms:access` is a *client role* of the inscribed backend's Keycloak client\n // (e.g. \"skycms\"), assigned to this service account. It therefore lands under\n // resource_access[<backend-client>], NOT under azp (this frontend client).\n // Scan every client so we report where the role actually is.\n const ra = claims.resource_access ?? {};\n const holder = Object.keys(ra).find((c) => ra[c]?.roles?.includes(\"cms:access\"));\n if (holder) {\n console.error(` -> \"cms:access\" found under resource_access[\"${holder}\"].`);\n if (holder !== claims.azp) {\n console.error(` (owned by backend client \"${holder}\", not azp \"${claims.azp}\" - expected)`);\n }\n } else {\n console.error(` ! \"cms:access\" role missing from every client in resource_access.`);\n console.error(` Assign the backend client's \"cms:access\" role to this service account:`);\n console.error(` Keycloak Admin -> Clients -> ${claims.azp} -> Service account roles -> Assign \"cms:access\".`);\n }\n}\n"],"mappings":";AAwBA,SAAS,wBAAwB;AAGjC,IAAM,WAAW,uBAAO,IAAI,qBAAqB;AAsC1C,SAAS,qBAAqB,OAAO;AAC1C,QAAM;AAAA,IACJ;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA,oBAAoB;AAAA,IACpB,aAAa;AAAA,IACb;AAAA,IACA;AAAA,EACF,IAAI,SAAS,CAAC;AAEd,MAAI,CAAC,UAAU;AACb,UAAM,IAAI;AAAA,MACR;AAAA,IAGF;AAAA,EACF;AAGA,QAAM,OAAO;AAAA,IACX,WAAW,CAAC,QAAQ;AAAA,IACpB,WAAW;AAAA,MACT,MAAM,IAAI,MAAM;AACd,cAAM,EAAE,OAAO,QAAQ,IAAI;AAC3B,YAAI,OAAO;AAGX,YAAI,SAAS;AACX,eAAK,cAAc,QAAQ;AAC3B,eAAK,eAAe,QAAQ;AAC5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{
93
93
  console.error(` scope: ${claims.scope}`);
94
94
  console.error(` resource_access: ${JSON.stringify(claims.resource_access)}`);
95
95
 
96
- const ourRoles = claims.resource_access?.[claims.azp]?.roles ?? [];
97
- console.error(` -> roles for "${claims.azp}": ${JSON.stringify(ourRoles)}`);
98
- if (!ourRoles.includes("cms:access")) {
99
- console.error(` ! "cms:access" role missing on service account.`);
96
+ // `cms:access` is a *client role* of the inscribed backend's Keycloak client
97
+ // (e.g. "skycms"), assigned to this service account. It therefore lands under
98
+ // resource_access[<backend-client>], NOT under azp (this frontend client).
99
+ // Scan every client so we report where the role actually is.
100
+ const ra = claims.resource_access ?? {};
101
+ const holder = Object.keys(ra).find((c) => ra[c]?.roles?.includes("cms:access"));
102
+ if (holder) {
103
+ console.error(` -> "cms:access" found under resource_access["${holder}"].`);
104
+ if (holder !== claims.azp) {
105
+ console.error(` (owned by backend client "${holder}", not azp "${claims.azp}" - expected)`);
106
+ }
107
+ } else {
108
+ console.error(` ! "cms:access" role missing from every client in resource_access.`);
109
+ console.error(` Assign the backend client's "cms:access" role to this service account:`);
100
110
  console.error(` Keycloak Admin -> Clients -> ${claims.azp} -> Service account roles -> Assign "cms:access".`);
101
111
  }
102
112
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skylab-kulubu/inscribed-auth",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Skylab's opt-in NextAuth + Keycloak adapter (auth + service token) for the inscribed CMS.",
5
5
  "type": "module",
6
6
  "license": "MIT",