mirror of
https://github.com/Chewbaccalakis/rfid-database.git
synced 2026-09-09 16:01:56 -07:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96c6df2fff | ||
|
|
c33f651cfe | ||
|
|
443dba5bba | ||
|
|
3bcdc14106 | ||
|
|
f2de0e3892 | ||
|
|
cd1a2fe808 |
@@ -22,11 +22,3 @@ jobs:
|
||||
- run: npm run build
|
||||
env:
|
||||
AUTH_SECRET: ci-build-secret-at-least-32-characters
|
||||
|
||||
docker:
|
||||
name: docker-build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build production image
|
||||
run: docker build -t rfid-database:ci .
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
name: Docker
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
# GHCR requires lowercase image names
|
||||
IMAGE_NAME: ghcr.io/chewbaccalakis/rfid-database
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
name: build-and-push
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
attestations: write
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels)
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
type=sha,prefix=sha-,format=short
|
||||
type=ref,event=branch
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
@@ -39,28 +39,56 @@ Open http://localhost:3000 and sign in.
|
||||
|
||||
### Enabling OIDC
|
||||
|
||||
1. In your IdP, create a **confidential** OIDC application.
|
||||
2. Set the redirect / callback URI to:
|
||||
1. **Pull latest and rebuild** (OIDC button detection changed recently):
|
||||
```bash
|
||||
git pull
|
||||
docker compose up -d --build
|
||||
```
|
||||
2. In your IdP, create a **confidential** OIDC application.
|
||||
3. Set the redirect / callback URI to **exactly**:
|
||||
```
|
||||
{AUTH_URL}/api/auth/callback/oidc
|
||||
```
|
||||
Example: `http://localhost:3000/api/auth/callback/oidc`
|
||||
3. Put these in `.env` (Docker Compose reads `.env` automatically):
|
||||
Example: `https://rfid.atlashorizon.net/api/auth/callback/oidc`
|
||||
4. Put these in `.env`:
|
||||
```bash
|
||||
AUTH_URL=http://localhost:3000
|
||||
AUTH_URL=https://rfid.atlashorizon.net
|
||||
AUTH_SECRET=...long random...
|
||||
AUTH_OIDC_ISSUER=https://sso.example.com/application/o/rfid/
|
||||
AUTH_OIDC_CLIENT_ID=...
|
||||
AUTH_OIDC_ISSUER=https://auth.atlashorizon.net
|
||||
AUTH_OIDC_CLIENT_ID=rfiddb
|
||||
AUTH_OIDC_CLIENT_SECRET=...
|
||||
AUTH_OIDC_NAME=Authentik
|
||||
AUTH_OIDC_NAME=AtlasHorizon
|
||||
```
|
||||
4. Restart the app (`docker compose up -d` or restart `npm run dev`).
|
||||
5. Open `/login` — you should see **Sign in with Authentik** (or your `AUTH_OIDC_NAME`).
|
||||
5. Restart, then verify the running app sees config (no secrets returned):
|
||||
```bash
|
||||
curl -s https://rfid.atlashorizon.net/api/v1/auth/config | jq
|
||||
```
|
||||
You want `"oidcEnabled": true` and `"callbackUrl"` matching your IdP.
|
||||
6. Open `/login` — you should see **Sign in with AtlasHorizon**.
|
||||
|
||||
Notes:
|
||||
- `AUTH_OIDC_ISSUER` must be exactly the issuer value from discovery (trailing slash matters for some IdPs).
|
||||
- The IdP must return an **email** claim; accounts are created/linked by email.
|
||||
- `AUTH_OIDC_ISSUER` must match discovery (`{issuer}/.well-known/openid-configuration`).
|
||||
- The app requests `openid email profile` and loads profile from **UserInfo** (Authelia puts `email` there by default).
|
||||
- Optional Authelia hardening — also put email on the ID token:
|
||||
|
||||
```yaml
|
||||
identity_providers:
|
||||
oidc:
|
||||
claims_policies:
|
||||
rfiddb:
|
||||
id_token:
|
||||
- 'email'
|
||||
- 'email_verified'
|
||||
- 'preferred_username'
|
||||
- 'name'
|
||||
clients:
|
||||
- client_id: 'rfiddb'
|
||||
claims_policy: 'rfiddb'
|
||||
# ...rest of client...
|
||||
```
|
||||
|
||||
- Local password login stays available alongside SSO.
|
||||
- If the button is missing, you are almost certainly on an old image — rebuild.
|
||||
|
||||
## REST API (`/api/v1`)
|
||||
|
||||
@@ -107,10 +135,26 @@ npm run typecheck
|
||||
npm run build
|
||||
```
|
||||
|
||||
GitHub Actions runs on every pull request and push to `main`:
|
||||
GitHub Actions on every pull request and push to `main`:
|
||||
|
||||
1. **lint / typecheck / test / Next.js build**
|
||||
2. **`docker build`** — catches Dockerfile parse/build failures (the class of break that conflict markers previously caused)
|
||||
2. **Docker image** — build on PRs; on `main` (and `v*` tags) push to GHCR:
|
||||
`ghcr.io/chewbaccalakis/rfid-database`
|
||||
|
||||
### Pull the published image
|
||||
|
||||
```bash
|
||||
docker pull ghcr.io/chewbaccalakis/rfid-database:latest
|
||||
# or a specific commit: ghcr.io/chewbaccalakis/rfid-database:sha-<shortsha>
|
||||
```
|
||||
|
||||
If the package is private, authenticate first:
|
||||
|
||||
```bash
|
||||
echo $GITHUB_TOKEN | docker login ghcr.io -u USERNAME --password-stdin
|
||||
```
|
||||
|
||||
Or in Compose, set `image: ghcr.io/chewbaccalakis/rfid-database:latest` and comment out `build:`.
|
||||
|
||||
## Docker
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
services:
|
||||
rfid-database:
|
||||
# Local build (default):
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: rfid-database:local
|
||||
# Or pull from GHCR instead of building:
|
||||
# image: ghcr.io/chewbaccalakis/rfid-database:latest
|
||||
# pull_policy: always
|
||||
container_name: rfid-database
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { jsonOk } from "@/lib/api/errors";
|
||||
import { isOidcConfigured } from "@/lib/auth/oidc";
|
||||
|
||||
/**
|
||||
* Public auth diagnostics (no secrets).
|
||||
* Useful to verify the running container sees OIDC env vars.
|
||||
*/
|
||||
export async function GET() {
|
||||
const authUrl = (process.env.AUTH_URL || "").replace(/\/$/, "");
|
||||
const oidcEnabled = isOidcConfigured();
|
||||
|
||||
return jsonOk({
|
||||
oidcEnabled,
|
||||
oidcName: process.env.AUTH_OIDC_NAME || "SSO",
|
||||
issuer: process.env.AUTH_OIDC_ISSUER || null,
|
||||
clientIdSet: Boolean(process.env.AUTH_OIDC_CLIENT_ID?.trim()),
|
||||
clientSecretSet: Boolean(process.env.AUTH_OIDC_CLIENT_SECRET?.trim()),
|
||||
authUrl: authUrl || null,
|
||||
authSecretSet: Boolean(
|
||||
process.env.AUTH_SECRET?.trim() &&
|
||||
process.env.AUTH_SECRET !== "change-me-to-a-long-random-string"
|
||||
),
|
||||
callbackUrl: authUrl
|
||||
? `${authUrl}/api/auth/callback/oidc`
|
||||
: "/api/auth/callback/oidc",
|
||||
hint: oidcEnabled
|
||||
? "OIDC looks configured. Register callbackUrl exactly in your IdP."
|
||||
: "Set AUTH_OIDC_ISSUER, AUTH_OIDC_CLIENT_ID, and AUTH_OIDC_CLIENT_SECRET, then restart.",
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import { isOidcConfigured } from "@/lib/auth/oidc";
|
||||
import { LoginPageClient } from "@/components/LoginPageClient";
|
||||
|
||||
// OIDC env is only available at runtime (Docker). Never prerender this page
|
||||
// at build time or the SSO button stays permanently hidden.
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<LoginPageClient
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { FormEvent, useState } from "react";
|
||||
import { FormEvent, useEffect, useState } from "react";
|
||||
import { signIn } from "next-auth/react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { Suspense } from "react";
|
||||
@@ -10,14 +10,56 @@ type Props = {
|
||||
oidcName: string;
|
||||
};
|
||||
|
||||
type AuthConfig = {
|
||||
oidcEnabled: boolean;
|
||||
oidcName: string;
|
||||
};
|
||||
|
||||
function authErrorMessage(code: string | null): string | null {
|
||||
if (!code) return null;
|
||||
switch (code) {
|
||||
case "EmailRequired":
|
||||
return "Your IdP did not return an email claim. Enable the email scope/claim for this OIDC client.";
|
||||
case "OAuthCallbackError":
|
||||
case "Callback":
|
||||
return "OIDC callback failed. Check redirect URI, client secret, and container logs.";
|
||||
case "OAuthSignin":
|
||||
return "Could not start OIDC login. Check AUTH_OIDC_ISSUER discovery and client id.";
|
||||
case "Configuration":
|
||||
return "Auth configuration error. Verify AUTH_SECRET, AUTH_URL, and OIDC env vars.";
|
||||
case "AccessDenied":
|
||||
return "Access denied by the identity provider.";
|
||||
default:
|
||||
return `Sign-in error: ${code}`;
|
||||
}
|
||||
}
|
||||
|
||||
function LoginForm({ oidcEnabled, oidcName }: Props) {
|
||||
const router = useRouter();
|
||||
const params = useSearchParams();
|
||||
const callbackUrl = params.get("callbackUrl") || "/";
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(
|
||||
authErrorMessage(params.get("error"))
|
||||
);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [runtimeOidc, setRuntimeOidc] = useState<AuthConfig | null>(null);
|
||||
|
||||
// Belt-and-suspenders: ask the live API so a stale static shell can't hide SSO
|
||||
useEffect(() => {
|
||||
fetch("/api/v1/auth/config")
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((data: AuthConfig | null) => {
|
||||
if (data) setRuntimeOidc(data);
|
||||
})
|
||||
.catch(() => {
|
||||
/* ignore */
|
||||
});
|
||||
}, []);
|
||||
|
||||
const showOidc = runtimeOidc?.oidcEnabled ?? oidcEnabled;
|
||||
const displayName = runtimeOidc?.oidcName || oidcName;
|
||||
|
||||
async function onSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
@@ -75,13 +117,13 @@ function LoginForm({ oidcEnabled, oidcName }: Props) {
|
||||
<button className="btn" type="submit" disabled={loading}>
|
||||
{loading ? "Signing in…" : "Sign in"}
|
||||
</button>
|
||||
{oidcEnabled && (
|
||||
{showOidc && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => signIn("oidc", { callbackUrl })}
|
||||
>
|
||||
Sign in with {oidcName}
|
||||
Sign in with {displayName}
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
|
||||
+47
-6
@@ -6,9 +6,9 @@ import { eq } from "drizzle-orm";
|
||||
import { getDb } from "@/db/client";
|
||||
import { users } from "@/db/schema";
|
||||
import { authConfig } from "@/lib/auth/auth.config";
|
||||
import { isOidcConfigured } from "@/lib/auth/oidc";
|
||||
import { emailFromOidcProfile, isOidcConfigured } from "@/lib/auth/oidc";
|
||||
|
||||
export { isOidcConfigured } from "@/lib/auth/oidc";
|
||||
export { emailFromOidcProfile, isOidcConfigured } from "@/lib/auth/oidc";
|
||||
|
||||
function buildProviders(): Provider[] {
|
||||
const providers: Provider[] = [
|
||||
@@ -36,15 +36,44 @@ function buildProviders(): Provider[] {
|
||||
];
|
||||
|
||||
if (isOidcConfigured()) {
|
||||
const issuer = process.env.AUTH_OIDC_ISSUER!.replace(/\/$/, "");
|
||||
providers.push({
|
||||
id: "oidc",
|
||||
name: process.env.AUTH_OIDC_NAME || "SSO",
|
||||
type: "oidc",
|
||||
issuer: process.env.AUTH_OIDC_ISSUER!,
|
||||
issuer,
|
||||
wellKnown: `${issuer}/.well-known/openid-configuration`,
|
||||
clientId: process.env.AUTH_OIDC_CLIENT_ID!,
|
||||
clientSecret: process.env.AUTH_OIDC_CLIENT_SECRET!,
|
||||
// Auth.js OIDC defaults to PKCE-only; Authelia requires a strong `state`
|
||||
checks: ["pkce", "state"],
|
||||
// Authelia (and many IdPs) put `email` on UserInfo, not the ID token.
|
||||
// Auth.js OIDC otherwise only reads ID-token claims.
|
||||
idToken: false,
|
||||
authorization: {
|
||||
params: {
|
||||
scope: "openid email profile",
|
||||
},
|
||||
},
|
||||
client: {
|
||||
token_endpoint_auth_method: "client_secret_post",
|
||||
},
|
||||
// Link OIDC logins to existing local users by email
|
||||
allowDangerousEmailAccountLinking: true,
|
||||
profile(profile: Record<string, unknown>) {
|
||||
const email = emailFromOidcProfile(profile);
|
||||
return {
|
||||
id: String(profile.sub ?? email ?? crypto.randomUUID()),
|
||||
name:
|
||||
(typeof profile.name === "string" && profile.name) ||
|
||||
(typeof profile.preferred_username === "string" &&
|
||||
profile.preferred_username) ||
|
||||
email ||
|
||||
"OIDC user",
|
||||
email: email ?? undefined,
|
||||
image: typeof profile.picture === "string" ? profile.picture : null,
|
||||
};
|
||||
},
|
||||
} as Provider);
|
||||
}
|
||||
|
||||
@@ -56,12 +85,24 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
providers: buildProviders(),
|
||||
callbacks: {
|
||||
...authConfig.callbacks,
|
||||
async signIn({ user, account }) {
|
||||
async signIn({ user, account, profile }) {
|
||||
if (account?.provider === "credentials") return true;
|
||||
if (!user.email) return false;
|
||||
|
||||
const email =
|
||||
user.email?.trim().toLowerCase() ||
|
||||
emailFromOidcProfile((profile ?? {}) as Record<string, unknown>);
|
||||
|
||||
if (!email) {
|
||||
console.error(
|
||||
"[auth] OIDC sign-in rejected: no email in profile. Claim keys:",
|
||||
profile ? Object.keys(profile) : []
|
||||
);
|
||||
return "/login?error=EmailRequired";
|
||||
}
|
||||
|
||||
user.email = email;
|
||||
|
||||
const db = getDb();
|
||||
const email = user.email.toLowerCase();
|
||||
let existing = db.select().from(users).where(eq(users.email, email)).get();
|
||||
if (!existing) {
|
||||
const id = crypto.randomUUID();
|
||||
|
||||
@@ -5,3 +5,23 @@ export function isOidcConfigured(): boolean {
|
||||
process.env.AUTH_OIDC_CLIENT_SECRET?.trim()
|
||||
);
|
||||
}
|
||||
|
||||
/** Pull an email out of common OIDC claim shapes (Authelia, Keycloak, etc.). */
|
||||
export function emailFromOidcProfile(
|
||||
profile: Record<string, unknown>
|
||||
): string | null {
|
||||
const candidates = [
|
||||
profile.email,
|
||||
profile.preferred_username,
|
||||
profile.upn,
|
||||
profile.mail,
|
||||
(profile.user as { email?: unknown } | undefined)?.email,
|
||||
];
|
||||
|
||||
for (const value of candidates) {
|
||||
if (typeof value !== "string") continue;
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.includes("@")) return trimmed.toLowerCase();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { emailFromOidcProfile } from "@/lib/auth/oidc";
|
||||
|
||||
describe("emailFromOidcProfile", () => {
|
||||
it("reads email claim", () => {
|
||||
expect(emailFromOidcProfile({ email: "[email protected]" })).toBe(
|
||||
"[email protected]"
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to preferred_username when it looks like an email", () => {
|
||||
expect(
|
||||
emailFromOidcProfile({ preferred_username: "[email protected]" })
|
||||
).toBe("[email protected]");
|
||||
});
|
||||
|
||||
it("ignores non-email preferred_username", () => {
|
||||
expect(emailFromOidcProfile({ preferred_username: "nick" })).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when nothing usable is present", () => {
|
||||
expect(emailFromOidcProfile({ sub: "abc", name: "Nick" })).toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user