[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M78D26M8ACKDBK61YNGHZM2T":3,"skill-same:01M78D26M8ACKDBK61YNGHZM2T":53},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":31,"commitSha":32,"skillDirectory":33,"forksCount":34,"repositoryHtmlUrl":35,"repositoryHomepageUrl":36,"ownerHtmlUrl":37,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":38,"install":39,"resources":52},"01M78D26M8ACKDBK61YNGHZM2T","keycloak",null,"Configure Keycloak realm\u002Fclient settings, integrate Auth.js v5 OIDC in the web portal (project.json → mainApp), set Keycloak Helm values (init\u002Ffull stage), recover bootstrap admin, or debug KC_HOSTNAME\u002Fissuer mismatches. Do not use for Helm chart templating (use helm-chart-expert), GCP firewall rules (use kubernetes-deployment), or database migrations (use migration-check).","atretyak1985\u002Fswarmery","atretyak1985","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1436737?v=4","01M78CTSX57YH0EYY9YGH0TWKX","Andrii Tretiak","01M78CTSXRPJPYQ7GNPMP45TYX",8,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Fplugins\u002Finfra-pack\u002Fskills\u002Fkeycloak\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: keycloak\ndescription: \"Configure Keycloak realm\u002Fclient settings, integrate Auth.js v5 OIDC in the web portal (project.json → mainApp), set Keycloak Helm values (init\u002Ffull stage), recover bootstrap admin, or debug KC_HOSTNAME\u002Fissuer mismatches. Do not use for Helm chart templating (use helm-chart-expert), GCP firewall rules (use kubernetes-deployment), or database migrations (use migration-check).\"\nversion: \"1.0.0\"\nowner: \"swarmery-infra\"\nallowed-tools: Read, Bash, Write, Edit, Grep, Glob, WebFetch, WebSearch\ndocs:\n  status: reviewed\n  source_sha: 47cf71e1a20f\n  updated: 2026-08-06\n---\n\n# Purpose\n\nProvide Keycloak identity and access management patterns for the platform. Cover realm setup, client configuration for Auth.js v5 in the web portal repo (project.json → mainApp), two-stage Helm deployment (init\u002Ffull), bootstrap admin recovery, issuer mismatch fixes, and NetworkPolicy requirements. For Helm chart template authoring beyond Keycloak values, defer to `helm-chart-expert`. For GCP firewall or ingress debugging, defer to `kubernetes-deployment`.\n\n# When to use\n\n- Configuring the `\u003Ckeycloak-realm>` realm, clients, roles, or groups in Keycloak\n- Integrating Auth.js v5 with Keycloak OIDC in the web portal\n- Setting up Keycloak Helm values (init stage or full stage with ingress)\n- Debugging Auth.js `error=Configuration` or issuer mismatch (`iss` claim)\n- Recovering from bootstrap admin failures (existing database, OOM-kill)\n- Configuring NetworkPolicy for ingress-to-Keycloak traffic\n\n# When NOT to use\n\n- Authoring Helm chart templates or `_helpers.tpl` -- use `helm-chart-expert`\n- Debugging GCP firewall rules or minikube tunnel -- use `kubernetes-deployment`\n- Checking migration safety -- use `migration-check`\n- Detecting IaC config drift -- use `infrastructure-as-code`\n\n# Required environment\n\n- Runtime: `.claude\u002Fskills\u002Fkeycloak\u002FSKILL.md`\n- Tools: `kubectl`, `helm`, `bash`\n- Keycloak version: 26.x (codecentric\u002Fkeycloakx Helm chart)\n- Setup script: the infrastructure repo's `files\u002Fkeycloak\u002Fsetup-keycloak.sh` (or the project's equivalent)\n- Namespace: environment-specific (`\u003Cinfra-namespace>`)\n\n# Inputs\n\n- `operation: enum` -- one of: `realm-setup`, `auth-integration`, `debug-auth`, `bootstrap-recovery`, `helm-values`\n- `environment: string` -- target environment (localdev, `\u003CenvAlias>`, prod)\n- `symptom: string` (optional) -- error message or behavior being debugged\n\n# Outputs\n\n- Format: configuration YAML, Auth.js TypeScript code, or a diagnostic command sequence\n- Length budget: max 150 lines per response; for multi-operation tasks, produce one section per operation\n- For `debug-auth`: ordered diagnosis steps with specific kubectl\u002Fcurl commands\n- For `bootstrap-recovery`: step-by-step recovery procedure with safety warnings\n\n# Procedure\n\n1. **Identify operation and environment** -- Confirm which Keycloak operation is needed and which environment.\n   **Checkpoint:** Operation type determined.\n\n2. **Check prerequisites** -- Verify Keycloak pod is running (`kubectl get pods -n $NAMESPACE | grep keycloak`). For auth debugging, verify both internal DNS and ingress are reachable.\n   **Checkpoint:** Keycloak pod status confirmed.\n\n3. **Apply configuration** -- Use the appropriate pattern (Helm values, setup script, or Auth.js config).\n   **Checkpoint:** Config applied or code change suggested.\n\n4. **Verify** -- For auth integration, confirm the OIDC discovery endpoint is reachable and the issuer URL matches `AUTH_KEYCLOAK_ISSUER`. Run: `curl \u003Cissuer>\u002F.well-known\u002Fopenid-configuration` and verify the JSON `issuer` field.\n   **Checkpoint:** Discovery endpoint returns valid JSON with matching issuer.\n\n# Self-check\n\n- [ ] No plaintext passwords -- used `$KC_ADMIN_PASSWORD` or equivalent placeholder\n- [ ] Issuer URL matches the `AUTH_KEYCLOAK_ISSUER` env var format\n- [ ] Used `kubernetes.io\u002Fmetadata.name` for NetworkPolicy namespace selectors, not custom `name:` labels\n- [ ] Distinguished between `KC_HOSTNAME` (routing) and `KC_HOSTNAME_URL` (token issuer) when both are needed\n- [ ] Verified whether the database is fresh before suggesting bootstrap admin vars will work\n- [ ] Did not suggest running `kc.sh bootstrap-admin user` inside a pod (causes OOM-kill)\n\n# Common mistakes\n\n- DO NOT hardcode admin passwords in values examples -- use `$KC_ADMIN_PASSWORD` placeholder with a `# LOCAL DEV ONLY` comment\n- DO NOT use `name: ingress-nginx` as a namespace selector label -- minikube addon does not add it; use `kubernetes.io\u002Fmetadata.name: ingress-nginx`\n- DO NOT run `\u002Fopt\u002Fkeycloak\u002Fbin\u002Fkc.sh bootstrap-admin user` inside a running pod -- starts a second JVM, causes OOM-kill at 1Gi memory limit\n- DO NOT assume `KC_BOOTSTRAP_ADMIN_*` vars work on an existing database -- they only take effect on first startup with an empty auth database\n- DO NOT rely on client-side auth checks alone -- always re-verify in the route handler or server action\n- DO NOT use `NEXTAUTH_URL` -- this is Auth.js v4 naming. In Auth.js v5, the env var is `AUTH_URL`\n\n# Escalation\n\n- STOP when: the Keycloak pod is in CrashLoopBackOff and logs show a database connection error (may need PostgreSQL debugging)\n- STOP when: the user wants to modify production Keycloak security settings\n- STOP when: the issuer mismatch involves a certificate trust chain issue\n\n# Examples\n\n## Example: Two-stage Helm deployment\n\n**Stage 1 -- Init (bootstrap without ingress):**\n```yaml\n# values.init.localdev.yaml\nkeycloak:\n  enabled: true\n  command: [\"\u002Fopt\u002Fkeycloak\u002Fbin\u002Fkc.sh\"]\n  args: [\"start-dev\"]\n  database:\n    vendor: postgres\n    hostname: \u003Cinfra-release>-postgresql.$NAMESPACE.svc.cluster.local\n    port: 5432\n    database: user_access\n    existingSecret: \u003Cinfra-release>-postgresql\n    existingSecretKey: postgres-password\n  extraEnv: |\n    - name: KC_BOOTSTRAP_ADMIN_USERNAME\n      value: admin\n    - name: KC_BOOTSTRAP_ADMIN_PASSWORD\n      value: \"$KC_ADMIN_PASSWORD\"   # LOCAL DEV ONLY -- never use in staging\u002Fprod\n```\n\n**Stage 2 -- Full (add ingress + hostname):**\n```yaml\n# values.localdev.yaml\nkeycloak:\n  enabled: true\n  extraEnv: |\n    - name: KC_HOSTNAME\n      value: \"keycloak.\u003Clocaldev-host>\"\n    - name: KC_HOSTNAME_STRICT\n      value: \"false\"\n  ingress:\n    enabled: true\n    ingressClassName: nginx\n    rules:\n      - host: \"keycloak.\u003Clocaldev-host>\"\n        paths:\n          - path: \u002F\n            pathType: Prefix\n```\n\n## Example: Auth.js v5 integration in the web portal\n\n```typescript\n\u002F\u002F \u003CmainApp>\u002Fsrc\u002Fauth.ts\nimport NextAuth from \"next-auth\";\nimport Keycloak from \"next-auth\u002Fproviders\u002Fkeycloak\";\n\nexport const { handlers, auth, signIn, signOut } = NextAuth({\n  providers: [\n    Keycloak({\n      clientId: process.env.KEYCLOAK_CLIENT_ID!,\n      clientSecret: process.env.KEYCLOAK_CLIENT_SECRET!,\n      issuer: process.env.KEYCLOAK_ISSUER!,\n    }),\n  ],\n  callbacks: {\n    async jwt({ token, account, profile }) {\n      if (account) {\n        token.accessToken = account.access_token;\n        token.roles = (profile as { realm_access?: { roles?: string[] } })\n          ?.realm_access?.roles ?? [];\n      }\n      return token;\n    },\n    async session({ session, token }) {\n      session.accessToken = token.accessToken as string | undefined;\n      session.roles = (token.roles as string[] | undefined) ?? [];\n      return session;\n    },\n  },\n});\n```\n\nRequired env vars: `AUTH_SECRET`, `AUTH_URL`, `KEYCLOAK_CLIENT_ID`, `KEYCLOAK_CLIENT_SECRET`, `KEYCLOAK_ISSUER`.\n\nNote: `AUTH_URL` replaces the Auth.js v4 `NEXTAUTH_URL`. Do not use `NEXTAUTH_URL` in Auth.js v5 projects.\n\n## Example: Diagnosing issuer mismatch (error=Configuration)\n\n**Symptom:** Auth.js callback returns `error=Configuration`. Browser shows redirect loop.\n\n**Cause:** the web portal pod exchanges tokens via internal cluster DNS (`\u003Cinfra-release>-keycloak-http.$NAMESPACE.svc.cluster.local`). Keycloak embeds that internal URL as the `iss` claim. Auth.js rejects it because `iss` does not match `KEYCLOAK_ISSUER` (the public HTTPS URL).\n\n**Fix:** Add `KC_HOSTNAME_URL` to Keycloak env vars:\n```yaml\nkeycloak:\n  extraEnv: |\n    - name: KC_HOSTNAME\n      value: \"keycloak.staging.example.com\"\n    - name: KC_HOSTNAME_URL\n      value: \"https:\u002F\u002Fkeycloak.staging.example.com\"\n    - name: KC_HOSTNAME_STRICT\n      value: \"true\"\n```\n\n- `KC_HOSTNAME` controls request routing and admin console hostname\n- `KC_HOSTNAME_URL` controls the full base URL in JWT `iss` claims and OIDC discovery\n- Both are needed when internal and external URLs differ\n\n## Example: Bootstrap admin recovery (existing database)\n\n`KC_BOOTSTRAP_ADMIN_*` vars only take effect on first startup with an empty database.\n\n**Recovery procedure:**\n```bash\n# 1. Scale Keycloak to 0\nkubectl scale deployment \u003Cinfra-release>-keycloak -n \"$NAMESPACE\" --replicas=0\n\n# 2. Drop and recreate the auth database\nkubectl exec -n \"$NAMESPACE\" \u003Cinfra-release>-postgresql-0 -- \\\n  psql -U postgres -c \"DROP DATABASE user_access;\"\nkubectl exec -n \"$NAMESPACE\" \u003Cinfra-release>-postgresql-0 -- \\\n  psql -U postgres -c \"CREATE DATABASE user_access;\"\n\n# 3. Scale Keycloak back up (bootstrap vars now take effect)\nkubectl scale deployment \u003Cinfra-release>-keycloak -n \"$NAMESPACE\" --replicas=1\n\n# 4. Re-run setup script to recreate realms, clients, users\n.\u002Ffiles\u002Fkeycloak\u002Fsetup-keycloak.sh local\n```\n\n# Failure modes\n\n| Mode | Symptom | Fix |\n|------|---------|-----|\n| error=Configuration | Redirect loop or error page after login | Decode JWT, check `iss` vs `KEYCLOAK_ISSUER`; add `KC_HOSTNAME_URL` |\n| Bootstrap admin fails | Keycloak starts but admin login fails, no error in logs | Check if the auth DB has existing data; drop\u002Frecreate DB |\n| NetworkPolicy blocks ingress | Keycloak unreachable via ingress but port-forward works | Use `kubernetes.io\u002Fmetadata.name: ingress-nginx` selector |\n| TLS 308 redirect timeout | `ERR_CONNECTION_TIMED_OUT` on HTTPS, HTTP works | Check GCP firewall for `allow-https` rule; see `kubernetes-deployment` |\n\n# Related skills\n\n- `helm-chart-expert` -- defer for Helm template authoring; compose when Keycloak values need template-level changes\n- `kubernetes-deployment` -- defer for GCP firewall, minikube tunnel, and ingress debugging\n- `infrastructure-as-code` -- defer for drift detection; compose when Keycloak Helm values override was applied manually\n- `migration-check` -- no direct overlap; Keycloak manages its own database schema\n\n# How to use\n\n## What it does\n\nThis skill gives you working Keycloak patterns for a Kubernetes platform: realm and client setup, Auth.js v5 OIDC wiring in the web portal, two-stage Helm values (init then full with ingress), bootstrap admin recovery, and the `KC_HOSTNAME` vs `KC_HOSTNAME_URL` distinction that causes most issuer mismatches. It knows the traps — OOM-killed bootstrap commands, NetworkPolicy selectors that silently drop ingress traffic, v4 env var names in a v5 project.\n\n## When to use it\n\n- Login fails with `error=Configuration` or a redirect loop, and you suspect the `iss` claim.\n- You are adding Keycloak sign-in to the web portal with Auth.js v5 and need the provider, callbacks, and env vars.\n- You need Keycloak Helm values for a fresh environment, either the init stage or the full stage with ingress.\n- The admin account no longer works on an existing database and you need a safe recovery path.\n\n## When not to use it\n\n- Authoring Helm chart templates or `_helpers.tpl` — use `helm-chart-expert`.\n- Cloud firewall rules, tunnels, or general ingress debugging — use `kubernetes-deployment`.\n- Checking whether a database migration is safe to run — use `migration-check`.\n- Detecting drift between committed IaC and the live cluster — use `infrastructure-as-code`.\n\n## How to invoke\n\n```\nSkill(skill: \"infra-pack:keycloak\")\n```\n\nInvoke it, then describe the operation and the target environment. The skill picks the matching pattern and walks the four-step procedure: identify the operation, check that the Keycloak pod is up, apply the config, then verify against the OIDC discovery endpoint.\n\n## Inputs\n\n- `operation` — one of `realm-setup`, `auth-integration`, `debug-auth`, `bootstrap-recovery`, `helm-values` — required.\n- `environment` — the target environment, such as localdev, `\u003CenvAlias>`, or prod — required.\n- `symptom` — the error message or observed behavior you are debugging — optional.\n\n## What you get back\n\nConfiguration YAML, Auth.js TypeScript, or an ordered sequence of `kubectl`\u002F`curl` commands — capped at about 150 lines, one section per operation. Debugging answers come as ranked diagnosis steps; recovery answers come as a numbered procedure with safety warnings. Passwords always appear as placeholders such as `$KC_ADMIN_PASSWORD`, never as literals.\n\n## Worked example\n\n```\nSkill(skill: \"infra-pack:keycloak\")\n\n\"Login on \u003CenvAlias> returns error=Configuration after the callback.\n operation: debug-auth, environment: \u003CenvAlias>\"\n```\n\nThe skill has you decode the JWT and compare its `iss` claim against `KEYCLOAK_ISSUER`. The pod exchanges tokens over internal cluster DNS, so Keycloak stamps the internal URL into `iss` and Auth.js rejects it. You get back Helm `extraEnv` adding `KC_HOSTNAME_URL` with the public HTTPS base URL alongside `KC_HOSTNAME`, plus a `curl \u003Cissuer>\u002F.well-known\u002Fopenid-configuration` check to confirm the fix.\n\n## Related\n\n- `helm-chart-expert` — prefer it when the change is in the chart templates, not the Keycloak values.\n- `kubernetes-deployment` — prefer it when Keycloak is unreachable at the network layer rather than misconfigured.\n- `infrastructure-as-code` — prefer it when Helm values were changed by hand and you need to detect the drift.\n","# Purpose\n\nProvide Keycloak identity and access management patterns for the platform. Cover realm setup, client configuration for Auth.js v5 in the web portal repo (project.json → mainApp), two-stage Helm deployment (init\u002Ffull), bootstrap admin recovery, issuer mismatch fixes, and NetworkPolicy requirements. For Helm chart template authoring beyond Keycloak values, defer to `helm-chart-expert`. For GCP firewall or ingress debugging, defer to `kubernetes-deployment`.\n\n# When to use\n\n- Configuring the `\u003Ckeycloak-realm>` realm, clients, roles, or groups in Keycloak\n- Integrating Auth.js v5 with Keycloak OIDC in the web portal\n- Setting up Keycloak Helm values (init stage or full stage with ingress)\n- Debugging Auth.js `error=Configuration` or issuer mismatch (`iss` claim)\n- Recovering from bootstrap admin failures (existing database, OOM-kill)\n- Configuring NetworkPolicy for ingress-to-Keycloak traffic\n\n# When NOT to use\n\n- Authoring Helm chart templates or `_helpers.tpl` -- use `helm-chart-expert`\n- Debugging GCP firewall rules or minikube tunnel -- use `kubernetes-deployment`\n- Checking migration safety -- use `migration-check`\n- Detecting IaC config drift -- use `infrastructure-as-code`\n\n# Required environment\n\n- Runtime: `.claude\u002Fskills\u002Fkeycloak\u002FSKILL.md`\n- Tools: `kubectl`, `helm`, `bash`\n- Keycloak version: 26.x (codecentric\u002Fkeycloakx Helm chart)\n- Setup script: the infrastructure repo's `files\u002Fkeycloak\u002Fsetup-keycloak.sh` (or the project's equivalent)\n- Namespace: environment-specific (`\u003Cinfra-namespace>`)\n\n# Inputs\n\n- `operation: enum` -- one of: `realm-setup`, `auth-integration`, `debug-auth`, `bootstrap-recovery`, `helm-values`\n- `environment: string` -- target environment (localdev, `\u003CenvAlias>`, prod)\n- `symptom: string` (optional) -- error message or behavior being debugged\n\n# Outputs\n\n- Format: configuration YAML, Auth.js TypeScript code, or a diagnostic command sequence\n- Length budget: max 150 lines per response; for multi-operation tasks, produce one section per operation\n- For `debug-auth`: ordered diagnosis steps with specific kubectl\u002Fcurl commands\n- For `bootstrap-recovery`: step-by-step recovery procedure with safety warnings\n\n# Procedure\n\n1. **Identify operation and environment** -- Confirm which Keycloak operation is needed and which environment.\n   **Checkpoint:** Operation type determined.\n\n2. **Check prerequisites** -- Verify Keycloak pod is running (`kubectl get pods -n $NAMESPACE | grep keycloak`). For auth debugging, verify both internal DNS and ingress are reachable.\n   **Checkpoint:** Keycloak pod status confirmed.\n\n3. **Apply configuration** -- Use the appropriate pattern (Helm values, setup script, or Auth.js config).\n   **Checkpoint:** Config applied or code change suggested.\n\n4. **Verify** -- For auth integration, confirm the OIDC discovery endpoint is reachable and the issuer URL matches `AUTH_KEYCLOAK_ISSUER`. Run: `curl \u003Cissuer>\u002F.well-known\u002Fopenid-configuration` and verify the JSON `issuer` field.\n   **Checkpoint:** Discovery endpoint returns valid JSON with matching issuer.\n\n# Self-check\n\n- [ ] No plaintext passwords -- used `$KC_ADMIN_PASSWORD` or equivalent placeholder\n- [ ] Issuer URL matches the `AUTH_KEYCLOAK_ISSUER` env var format\n- [ ] Used `kubernetes.io\u002Fmetadata.name` for NetworkPolicy namespace selectors, not custom `name:` labels\n- [ ] Distinguished between `KC_HOSTNAME` (routing) and `KC_HOSTNAME_URL` (token issuer) when both are needed\n- [ ] Verified whether the database is fresh before suggesting bootstrap admin vars will work\n- [ ] Did not suggest running `kc.sh bootstrap-admin user` inside a pod (causes OOM-kill)\n\n# Common mistakes\n\n- DO NOT hardcode admin passwords in values examples -- use `$KC_ADMIN_PASSWORD` placeholder with a `# LOCAL DEV ONLY` comment\n- DO NOT use `name: ingress-nginx` as a namespace selector label -- minikube addon does not add it; use `kubernetes.io\u002Fmetadata.name: ingress-nginx`\n- DO NOT run `\u002Fopt\u002Fkeycloak\u002Fbin\u002Fkc.sh bootstrap-admin user` inside a running pod -- starts a second JVM, causes OOM-kill at 1Gi memory limit\n- DO NOT assume `KC_BOOTSTRAP_ADMIN_*` vars work on an existing database -- they only take effect on first startup with an empty auth database\n- DO NOT rely on client-side auth checks alone -- always re-verify in the route handler or server action\n- DO NOT use `NEXTAUTH_URL` -- this is Auth.js v4 naming. In Auth.js v5, the env var is `AUTH_URL`\n\n# Escalation\n\n- STOP when: the Keycloak pod is in CrashLoopBackOff and logs show a database connection error (may need PostgreSQL debugging)\n- STOP when: the user wants to modify production Keycloak security settings\n- STOP when: the issuer mismatch involves a certificate trust chain issue\n\n# Examples\n\n## Example: Two-stage Helm deployment\n\n**Stage 1 -- Init (bootstrap without ingress):**\n```yaml\n# values.init.localdev.yaml\nkeycloak:\n  enabled: true\n  command: [\"\u002Fopt\u002Fkeycloak\u002Fbin\u002Fkc.sh\"]\n  args: [\"start-dev\"]\n  database:\n    vendor: postgres\n    hostname: \u003Cinfra-release>-postgresql.$NAMESPACE.svc.cluster.local\n    port: 5432\n    database: user_access\n    existingSecret: \u003Cinfra-release>-postgresql\n    existingSecretKey: postgres-password\n  extraEnv: |\n    - name: KC_BOOTSTRAP_ADMIN_USERNAME\n      value: admin\n    - name: KC_BOOTSTRAP_ADMIN_PASSWORD\n      value: \"$KC_ADMIN_PASSWORD\"   # LOCAL DEV ONLY -- never use in staging\u002Fprod\n```\n\n**Stage 2 -- Full (add ingress + hostname):**\n```yaml\n# values.localdev.yaml\nkeycloak:\n  enabled: true\n  extraEnv: |\n    - name: KC_HOSTNAME\n      value: \"keycloak.\u003Clocaldev-host>\"\n    - name: KC_HOSTNAME_STRICT\n      value: \"false\"\n  ingress:\n    enabled: true\n    ingressClassName: nginx\n    rules:\n      - host: \"keycloak.\u003Clocaldev-host>\"\n        paths:\n          - path: \u002F\n            pathType: Prefix\n```\n\n## Example: Auth.js v5 integration in the web portal\n\n```typescript\n\u002F\u002F \u003CmainApp>\u002Fsrc\u002Fauth.ts\nimport NextAuth from \"next-auth\";\nimport Keycloak from \"next-auth\u002Fproviders\u002Fkeycloak\";\n\nexport const { handlers, auth, signIn, signOut } = NextAuth({\n  providers: [\n    Keycloak({\n      clientId: process.env.KEYCLOAK_CLIENT_ID!,\n      clientSecret: process.env.KEYCLOAK_CLIENT_SECRET!,\n      issuer: process.env.KEYCLOAK_ISSUER!,\n    }),\n  ],\n  callbacks: {\n    async jwt({ token, account, profile }) {\n      if (account) {\n        token.accessToken = account.access_token;\n        token.roles = (profile as { realm_access?: { roles?: string[] } })\n          ?.realm_access?.roles ?? [];\n      }\n      return token;\n    },\n    async session({ session, token }) {\n      session.accessToken = token.accessToken as string | undefined;\n      session.roles = (token.roles as string[] | undefined) ?? [];\n      return session;\n    },\n  },\n});\n```\n\nRequired env vars: `AUTH_SECRET`, `AUTH_URL`, `KEYCLOAK_CLIENT_ID`, `KEYCLOAK_CLIENT_SECRET`, `KEYCLOAK_ISSUER`.\n\nNote: `AUTH_URL` replaces the Auth.js v4 `NEXTAUTH_URL`. Do not use `NEXTAUTH_URL` in Auth.js v5 projects.\n\n## Example: Diagnosing issuer mismatch (error=Configuration)\n\n**Symptom:** Auth.js callback returns `error=Configuration`. Browser shows redirect loop.\n\n**Cause:** the web portal pod exchanges tokens via internal cluster DNS (`\u003Cinfra-release>-keycloak-http.$NAMESPACE.svc.cluster.local`). Keycloak embeds that internal URL as the `iss` claim. Auth.js rejects it because `iss` does not match `KEYCLOAK_ISSUER` (the public HTTPS URL).\n\n**Fix:** Add `KC_HOSTNAME_URL` to Keycloak env vars:\n```yaml\nkeycloak:\n  extraEnv: |\n    - name: KC_HOSTNAME\n      value: \"keycloak.staging.example.com\"\n    - name: KC_HOSTNAME_URL\n      value: \"https:\u002F\u002Fkeycloak.staging.example.com\"\n    - name: KC_HOSTNAME_STRICT\n      value: \"true\"\n```\n\n- `KC_HOSTNAME` controls request routing and admin console hostname\n- `KC_HOSTNAME_URL` controls the full base URL in JWT `iss` claims and OIDC discovery\n- Both are needed when internal and external URLs differ\n\n## Example: Bootstrap admin recovery (existing database)\n\n`KC_BOOTSTRAP_ADMIN_*` vars only take effect on first startup with an empty database.\n\n**Recovery procedure:**\n```bash\n# 1. Scale Keycloak to 0\nkubectl scale deployment \u003Cinfra-release>-keycloak -n \"$NAMESPACE\" --replicas=0\n\n# 2. Drop and recreate the auth database\nkubectl exec -n \"$NAMESPACE\" \u003Cinfra-release>-postgresql-0 -- \\\n  psql -U postgres -c \"DROP DATABASE user_access;\"\nkubectl exec -n \"$NAMESPACE\" \u003Cinfra-release>-postgresql-0 -- \\\n  psql -U postgres -c \"CREATE DATABASE user_access;\"\n\n# 3. Scale Keycloak back up (bootstrap vars now take effect)\nkubectl scale deployment \u003Cinfra-release>-keycloak -n \"$NAMESPACE\" --replicas=1\n\n# 4. Re-run setup script to recreate realms, clients, users\n.\u002Ffiles\u002Fkeycloak\u002Fsetup-keycloak.sh local\n```\n\n# Failure modes\n\n| Mode | Symptom | Fix |\n|------|---------|-----|\n| error=Configuration | Redirect loop or error page after login | Decode JWT, check `iss` vs `KEYCLOAK_ISSUER`; add `KC_HOSTNAME_URL` |\n| Bootstrap admin fails | Keycloak starts but admin login fails, no error in logs | Check if the auth DB has existing data; drop\u002Frecreate DB |\n| NetworkPolicy blocks ingress | Keycloak unreachable via ingress but port-forward works | Use `kubernetes.io\u002Fmetadata.name: ingress-nginx` selector |\n| TLS 308 redirect timeout | `ERR_CONNECTION_TIMED_OUT` on HTTPS, HTTP works | Check GCP firewall for `allow-https` rule; see `kubernetes-deployment` |\n\n# Related skills\n\n- `helm-chart-expert` -- defer for Helm template authoring; compose when Keycloak values need template-level changes\n- `kubernetes-deployment` -- defer for GCP firewall, minikube tunnel, and ingress debugging\n- `infrastructure-as-code` -- defer for drift detection; compose when Keycloak Helm values override was applied manually\n- `migration-check` -- no direct overlap; Keycloak manages its own database schema\n\n# How to use\n\n## What it does\n\nThis skill gives you working Keycloak patterns for a Kubernetes platform: realm and client setup, Auth.js v5 OIDC wiring in the web portal, two-stage Helm values (init then full with ingress), bootstrap admin recovery, and the `KC_HOSTNAME` vs `KC_HOSTNAME_URL` distinction that causes most issuer mismatches. It knows the traps — OOM-killed bootstrap commands, NetworkPolicy selectors that silently drop ingress traffic, v4 env var names in a v5 project.\n\n## When to use it\n\n- Login fails with `error=Configuration` or a redirect loop, and you suspect the `iss` claim.\n- You are adding Keycloak sign-in to the web portal with Auth.js v5 and need the provider, callbacks, and env vars.\n- You need Keycloak Helm values for a fresh environment, either the init stage or the full stage with ingress.\n- The admin account no longer works on an existing database and you need a safe recovery path.\n\n## When not to use it\n\n- Authoring Helm chart templates or `_helpers.tpl` — use `helm-chart-expert`.\n- Cloud firewall rules, tunnels, or general ingress debugging — use `kubernetes-deployment`.\n- Checking whether a database migration is safe to run — use `migration-check`.\n- Detecting drift between committed IaC and the live cluster — use `infrastructure-as-code`.\n\n## How to invoke\n\n```\nSkill(skill: \"infra-pack:keycloak\")\n```\n\nInvoke it, then describe the operation and the target environment. The skill picks the matching pattern and walks the four-step procedure: identify the operation, check that the Keycloak pod is up, apply the config, then verify against the OIDC discovery endpoint.\n\n## Inputs\n\n- `operation` — one of `realm-setup`, `auth-integration`, `debug-auth`, `bootstrap-recovery`, `helm-values` — required.\n- `environment` — the target environment, such as localdev, `\u003CenvAlias>`, or prod — required.\n- `symptom` — the error message or observed behavior you are debugging — optional.\n\n## What you get back\n\nConfiguration YAML, Auth.js TypeScript, or an ordered sequence of `kubectl`\u002F`curl` commands — capped at about 150 lines, one section per operation. Debugging answers come as ranked diagnosis steps; recovery answers come as a numbered procedure with safety warnings. Passwords always appear as placeholders such as `$KC_ADMIN_PASSWORD`, never as literals.\n\n## Worked example\n\n```\nSkill(skill: \"infra-pack:keycloak\")\n\n\"Login on \u003CenvAlias> returns error=Configuration after the callback.\n operation: debug-auth, environment: \u003CenvAlias>\"\n```\n\nThe skill has you decode the JWT and compare its `iss` claim against `KEYCLOAK_ISSUER`. The pod exchanges tokens over internal cluster DNS, so Keycloak stamps the internal URL into `iss` and Auth.js rejects it. You get back Helm `extraEnv` adding `KC_HOSTNAME_URL` with the public HTTPS base URL alongside `KC_HOSTNAME`, plus a `curl \u003Cissuer>\u002F.well-known\u002Fopenid-configuration` check to confirm the fix.\n\n## Related\n\n- `helm-chart-expert` — prefer it when the change is in the chart templates, not the Keycloak values.\n- `kubernetes-deployment` — prefer it when Keycloak is unreachable at the network layer rather than misconfigured.\n- `infrastructure-as-code` — prefer it when Helm values were changed by hand and you need to detect the drift.\n",{"docs":24,"name":5,"owner":28,"version":29,"description":7,"allowed-tools":30},{"status":25,"updated":26,"source_sha":27},"reviewed",1785974400000,"47cf71e1a20f","swarmery-infra","1.0.0","Read, Bash, Write, Edit, Grep, Glob, WebFetch, WebSearch","main","2d9e918cc79c9b17b59356780ff0a3da38a3e98a","plugins\u002Finfra-pack\u002Fskills\u002Fkeycloak",5,"https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery","https:\u002F\u002Fatretyak1985.github.io\u002Fswarmery\u002F","https:\u002F\u002Fgithub.com\u002Fatretyak1985","2026-11-11 04:29:12",{"source":8,"skillName":5,"commands":40,"prompt":50,"zipAvailable":51},[41,44,47],{"tool":42,"command":43},"npx","npx skills add atretyak1985\u002Fswarmery --skill keycloak",{"tool":45,"command":46},"bunx","bunx skills add atretyak1985\u002Fswarmery --skill keycloak",{"tool":48,"command":49},"pnpm","pnpm dlx skills add atretyak1985\u002Fswarmery --skill keycloak","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Fplugins\u002Finfra-pack\u002Fskills\u002Fkeycloak\u002FSKILL.md",true,[],[54,61,67,74,81,88],{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":19},"01M78D4T1FFWFW19Z44AHH5BSY","short-desc","Too short.","https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Ftools\u002Fswarmery\u002Ftestdata\u002Fsysconfig\u002Fclaude\u002Fskills\u002Fshort-desc\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M78D4S0TWT42WXFJHC1DBN0R","no-frontmatter","https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Ftools\u002Fswarmery\u002Ftestdata\u002Fsysconfig\u002Fclaude\u002Fskills\u002Fno-frontmatter\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M78D4Q14P8DJ4W78N62F3EG2","global-skill","Fixture global skill (minimal user-scope shape, format doc §2.3).","https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Ftools\u002Fswarmery\u002Ftestdata\u002Fsysconfig\u002Fclaude\u002Fskills\u002Fglobal-skill\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M78D4N1JHGQJQ7EZ43KY5SV3","documented-skill","Fixture skill whose usage guide deliberately omits the Worked example subsection.","https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Ftools\u002Fswarmery\u002Ftestdata\u002Fsysconfig\u002Fclaude\u002Fskills\u002Fdocumented-skill\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M78D4KVNZ03GBKGDFJZWW5FJ","z","NOT auto-discovered — only skills\u002F is scanned for plugins (§2.2).","https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Ftools\u002Fswarmery\u002Ftestdata\u002Fsysconfig\u002Fclaude\u002Fplugins\u002Fcache\u002Fmkt\u002Ftoolpack\u002F1.0.0\u002Fworkflow-skills\u002Fz\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M78D4JMBRZWK51HFE5RZJGHC","y","Plugin skill y from toolpack — stored as \"toolpack:y\".","https:\u002F\u002Fgithub.com\u002Fatretyak1985\u002Fswarmery\u002Fblob\u002Fmain\u002Ftools\u002Fswarmery\u002Ftestdata\u002Fsysconfig\u002Fclaude\u002Fplugins\u002Fcache\u002Fmkt\u002Ftoolpack\u002F1.0.0\u002Fskills\u002Fy\u002FSKILL.md",[],[]]