Author SHA1 Message Date
Nick Trochalakis 21e2592f92 Merge pull request #10 from Chewbaccalakis/cursor/fix-oidc-email-userinfo-e593
Fix OIDC email: use Authelia UserInfo (not just ID token)
2026-08-23 21:28:25 -07:00
Cursor Agent 96c6df2fff Fix OIDC email: load Authelia profile from UserInfo
Auth.js OIDC only reads ID-token claims by default; Authelia puts
email on UserInfo. Set idToken:false, harden claim extraction, and
document an optional Authelia claims_policy.
2026-08-24 04:25:50 +00:00
Nick TrochalakisandCursor Agent c33f651cfe Fix Authelia OIDC: send state (+ remove login redirect hint) (#9)
Auth.js OIDC defaults to PKCE-only, so no `state` was sent; Authelia
rejects that. Enable checks: pkce + state. Remove the public redirect
URI hint from the login page.

Co-authored-by: Cursor Agent <[email protected]>
2026-08-24 04:19:29 +00:00
Nick TrochalakisandCursor Agent 443dba5bba Publish Docker image to GHCR on each main build (#8)
Add a Docker workflow that builds on PRs and pushes to
ghcr.io/chewbaccalakis/rfid-database on main (latest + sha) and v* tags.
Drop the redundant docker-build job from CI.

Co-authored-by: Cursor Agent <[email protected]>
2026-08-24 04:10:58 +00:00
Nick Trochalakis 3bcdc14106 Merge pull request #7 from Chewbaccalakis/cursor/fix-login-dynamic-oidc-e593
Fix OIDC button: force dynamic /login (was prerendered at build)
2026-08-23 21:05:12 -07:00
Cursor Agent f2de0e3892 Fix missing OIDC button: stop static-prerendering /login
/login was prerendered at Docker build time when AUTH_OIDC_* were
unset, baking oidcEnabled=false into the page. Force dynamic render
and also read /api/v1/auth/config on the client as a fallback.
2026-08-24 04:02:37 +00:00
Nick TrochalakisandCursor Agent cd1a2fe808 Harden OIDC + auth config diagnostics endpoint (#6)
Request openid email profile, use client_secret_post, surface OIDC
errors on /login, and expose a no-auth diagnostics endpoint so operators
can verify the running container sees AUTH_OIDC_* and the callback URL.

Co-authored-by: Cursor Agent <[email protected]>
2026-08-24 03:57:29 +00:00
Nick TrochalakisandCursor Agent 6d76fecde9 Fix OIDC: enable from runtime AUTH_OIDC_* (no NEXT_PUBLIC flag) (#5)
The SSO button required NEXT_PUBLIC_AUTH_OIDC_ENABLED, which is baked
at build time and silently fails under Docker runtime env. Drive the
login button from server-side AUTH_OIDC_* instead, and document IdP
redirect URI + AUTH_URL setup.

Co-authored-by: Cursor Agent <[email protected]>
2026-08-24 00:13:51 +00:00
Nick TrochalakisandCursor Agent 0e50c537ee Strengthen CI (Next + Docker build) and expand tests (#4)
Add docker-build and next build jobs so Dockerfile/image failures fail
CI. Expand unit coverage for exporters/Zod and integration coverage for
search, MCT import, backup, and token revoke.

Co-authored-by: Cursor Agent <[email protected]>
2026-08-23 23:37:09 +00:00
Nick TrochalakisandCursor Agent 5aa5fef9af Fix Dockerfile conflict markers broken on main (#3)
* Fix conflict markers on main and guard CI against them

PR #2 merged before the Dockerfile cleanup landed, leaving <<<<<<<
markers that break docker compose build. Restore clean Docker files
and fail CI if conflict markers appear in the tree.

* Add CI check that fails on merge conflict markers

* Narrow conflict-marker CI check to <<<<<<< and >>>>>>>

---------

Co-authored-by: Cursor Agent <[email protected]>
2026-08-23 23:32:54 +00:00
Nick TrochalakisandCursor Agent d3ed4566b7 RFID tag dump PWA + REST API (with Docker Compose) (#2)
* Implement RFID tag dump PWA with REST API, auth, and CI

Add Next.js app with SQLite/Drizzle storage for sites and LF/HF tag
dumps, multi-user Auth.js (credentials + optional OIDC), personal API
tokens in Settings, versioned /api/v1 for UI and future CLI use,
MCT/Proxmark/JSON import-export, PWA offline shell, Vitest tests, and
GitHub Actions CI.

* Add Docker Compose setup with persistent volume

Improve the production Dockerfile (healthcheck, entrypoint bootstrap
user, pruned deps) and add docker-compose.yml plus .dockerignore for
one-command deploy with a named SQLite volume.

---------

Co-authored-by: Cursor Agent <[email protected]>
2026-08-23 16:10:30 -07:00
14 changed files with 658 additions and 122 deletions
+20 -4
View File
@@ -1,4 +1,10 @@
AUTH_SECRET=change-me-to-a-long-random-string
# Public URL of this app (important behind reverse proxies / Docker)
# Example: http://localhost:3000 or https://rfid.example.com
# AUTH_URL=http://localhost:3000
# AUTH_TRUST_HOST=true
# Optional: path to SQLite file (default ./data/rfid.db)
# RFID_DB_PATH=./data/rfid.db
@@ -10,10 +16,20 @@ AUTH_SECRET=change-me-to-a-long-random-string
# CREATE_USER_PASSWORD=changeme
# CREATE_USER_NAME=Admin
# Optional OIDC (Authentik, Keycloak, Authelia, etc.)
# Optional OIDC (Authentik, Keycloak, Authelia, Google, etc.)
# Setting these three enables the "Sign in with SSO" button automatically
# (no NEXT_PUBLIC_* flag needed).
#
# In your IdP, create a confidential OIDC client with redirect URI:
# {AUTH_URL}/api/auth/callback/oidc
# e.g. http://localhost:3000/api/auth/callback/oidc
#
# AUTH_OIDC_ISSUER must be the issuer that serves
# {issuer}/.well-known/openid-configuration
# Authentik example: https://sso.example.com/application/o/rfid/
# Keycloak example: https://sso.example.com/realms/myrealm
#
# AUTH_OIDC_ISSUER=https://sso.example.com/application/o/rfid/
# AUTH_OIDC_CLIENT_ID=
# AUTH_OIDC_CLIENT_SECRET=
# AUTH_OIDC_NAME=SSO
# NEXT_PUBLIC_AUTH_OIDC_ENABLED=1
# NEXT_PUBLIC_AUTH_OIDC_NAME=SSO
# AUTH_OIDC_NAME=Authentik
+4
View File
@@ -7,6 +7,7 @@ on:
jobs:
check:
name: lint-typecheck-test-build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -18,3 +19,6 @@ jobs:
- run: npm run lint
- run: npm run typecheck
- run: npm test
- run: npm run build
env:
AUTH_SECRET: ci-build-secret-at-least-32-characters
+60
View File
@@ -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
+79 -7
View File
@@ -30,13 +30,65 @@ Open http://localhost:3000 and sign in.
| Variable | Required | Description |
|----------|----------|-------------|
| `AUTH_SECRET` | yes | NextAuth secret |
| `AUTH_URL` | recommended | Public app URL (e.g. `https://rfid.example.com`) |
| `RFID_DB_PATH` | no | SQLite path (default `./data/rfid.db`) |
| `AUTH_OIDC_ISSUER` | no | OIDC issuer URL |
| `AUTH_OIDC_CLIENT_ID` | no | OIDC client id |
| `AUTH_OIDC_CLIENT_SECRET` | no | OIDC client secret |
| `AUTH_OIDC_NAME` | no | Button label (default `SSO`) |
| `NEXT_PUBLIC_AUTH_OIDC_ENABLED` | no | Set `1` to show SSO button |
| `NEXT_PUBLIC_AUTH_OIDC_NAME` | no | Public SSO button label |
| `AUTH_OIDC_ISSUER` | for OIDC | Issuer URL (must expose `/.well-known/openid-configuration`) |
| `AUTH_OIDC_CLIENT_ID` | for OIDC | OIDC client id |
| `AUTH_OIDC_CLIENT_SECRET` | for OIDC | OIDC client secret |
| `AUTH_OIDC_NAME` | no | SSO button label (default `SSO`) |
### Enabling OIDC
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: `https://rfid.atlashorizon.net/api/auth/callback/oidc`
4. Put these in `.env`:
```bash
AUTH_URL=https://rfid.atlashorizon.net
AUTH_SECRET=...long random...
AUTH_OIDC_ISSUER=https://auth.atlashorizon.net
AUTH_OIDC_CLIENT_ID=rfiddb
AUTH_OIDC_CLIENT_SECRET=...
AUTH_OIDC_NAME=AtlasHorizon
```
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 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`)
@@ -80,9 +132,29 @@ curl -sH "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
npm test
npm run lint
npm run typecheck
npm run build
```
GitHub Actions runs lint, typecheck, and tests 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 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
+6 -5
View File
@@ -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:
@@ -16,15 +20,12 @@ services:
PORT: "3000"
HOSTNAME: 0.0.0.0
AUTH_TRUST_HOST: "true"
# OIDC: set AUTH_OIDC_ISSUER / CLIENT_ID / CLIENT_SECRET (and AUTH_URL)
# in .env — the login page picks them up at runtime.
# Optional bootstrap (only creates if missing):
# CREATE_USER_EMAIL: [email protected]
# CREATE_USER_PASSWORD: change-me
# CREATE_USER_NAME: Admin
# Optional OIDC — also set NEXT_PUBLIC_* in .env if using SSO button
# AUTH_OIDC_ISSUER: ${AUTH_OIDC_ISSUER:-}
# AUTH_OIDC_CLIENT_ID: ${AUTH_OIDC_CLIENT_ID:-}
# AUTH_OIDC_CLIENT_SECRET: ${AUTH_OIDC_CLIENT_SECRET:-}
# AUTH_OIDC_NAME: ${AUTH_OIDC_NAME:-SSO}
volumes:
- rfid-data:/data
healthcheck:
+30
View File
@@ -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.",
});
}
+9 -89
View File
@@ -1,95 +1,15 @@
"use client";
import { isOidcConfigured } from "@/lib/auth/oidc";
import { LoginPageClient } from "@/components/LoginPageClient";
import { FormEvent, useState } from "react";
import { signIn } from "next-auth/react";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense } from "react";
function LoginForm() {
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 [loading, setLoading] = useState(false);
const oidcName = process.env.NEXT_PUBLIC_AUTH_OIDC_NAME || "SSO";
const oidcEnabled = process.env.NEXT_PUBLIC_AUTH_OIDC_ENABLED === "1";
async function onSubmit(e: FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);
const res = await signIn("credentials", {
email,
password,
redirect: false,
callbackUrl,
});
setLoading(false);
if (res?.error) {
setError("Invalid email or password");
return;
}
router.push(callbackUrl);
router.refresh();
}
return (
<div style={{ maxWidth: 400, margin: "3rem auto" }}>
<h1 className="page-title">RFID Database</h1>
<p className="page-sub">Sign in to manage site tag dumps</p>
{error && <div className="error-banner">{error}</div>}
<form className="panel stack" onSubmit={onSubmit}>
<div className="field">
<label className="label" htmlFor="email">
Email
</label>
<input
id="email"
className="input"
type="email"
autoComplete="username"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div className="field">
<label className="label" htmlFor="password">
Password
</label>
<input
id="password"
className="input"
type="password"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<button className="btn" type="submit" disabled={loading}>
{loading ? "Signing in…" : "Sign in"}
</button>
{oidcEnabled && (
<button
type="button"
className="btn btn-secondary"
onClick={() => signIn("oidc", { callbackUrl })}
>
Sign in with {oidcName}
</button>
)}
</form>
</div>
);
}
// 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 (
<Suspense>
<LoginForm />
</Suspense>
<LoginPageClient
oidcEnabled={isOidcConfigured()}
oidcName={process.env.AUTH_OIDC_NAME || "SSO"}
/>
);
}
+140
View File
@@ -0,0 +1,140 @@
"use client";
import { FormEvent, useEffect, useState } from "react";
import { signIn } from "next-auth/react";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense } from "react";
type Props = {
oidcEnabled: boolean;
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>(
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();
setLoading(true);
setError(null);
const res = await signIn("credentials", {
email,
password,
redirect: false,
callbackUrl,
});
setLoading(false);
if (res?.error) {
setError("Invalid email or password");
return;
}
router.push(callbackUrl);
router.refresh();
}
return (
<div style={{ maxWidth: 400, margin: "3rem auto" }}>
<h1 className="page-title">RFID Database</h1>
<p className="page-sub">Sign in to manage site tag dumps</p>
{error && <div className="error-banner">{error}</div>}
<form className="panel stack" onSubmit={onSubmit}>
<div className="field">
<label className="label" htmlFor="email">
Email
</label>
<input
id="email"
className="input"
type="email"
autoComplete="username"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div className="field">
<label className="label" htmlFor="password">
Password
</label>
<input
id="password"
className="input"
type="password"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<button className="btn" type="submit" disabled={loading}>
{loading ? "Signing in…" : "Sign in"}
</button>
{showOidc && (
<button
type="button"
className="btn btn-secondary"
onClick={() => signIn("oidc", { callbackUrl })}
>
Sign in with {displayName}
</button>
)}
</form>
</div>
);
}
export function LoginPageClient(props: Props) {
return (
<Suspense>
<LoginForm {...props} />
</Suspense>
);
}
+51 -17
View File
@@ -6,6 +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 { emailFromOidcProfile, isOidcConfigured } from "@/lib/auth/oidc";
export { emailFromOidcProfile, isOidcConfigured } from "@/lib/auth/oidc";
function buildProviders(): Provider[] {
const providers: Provider[] = [
@@ -32,18 +35,45 @@ function buildProviders(): Provider[] {
}),
];
const issuer = process.env.AUTH_OIDC_ISSUER;
const clientId = process.env.AUTH_OIDC_CLIENT_ID;
const clientSecret = process.env.AUTH_OIDC_CLIENT_SECRET;
if (issuer && clientId && clientSecret) {
if (isOidcConfigured()) {
const issuer = process.env.AUTH_OIDC_ISSUER!.replace(/\/$/, "");
providers.push({
id: "oidc",
name: process.env.AUTH_OIDC_NAME || "SSO",
type: "oidc",
issuer,
clientId,
clientSecret,
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);
}
@@ -55,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();
@@ -82,11 +124,3 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
},
},
});
export function isOidcConfigured(): boolean {
return Boolean(
process.env.AUTH_OIDC_ISSUER &&
process.env.AUTH_OIDC_CLIENT_ID &&
process.env.AUTH_OIDC_CLIENT_SECRET
);
}
+27
View File
@@ -0,0 +1,27 @@
export function isOidcConfigured(): boolean {
return Boolean(
process.env.AUTH_OIDC_ISSUER?.trim() &&
process.env.AUTH_OIDC_CLIENT_ID?.trim() &&
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;
}
+76
View File
@@ -21,6 +21,10 @@ import { GET as getTags, POST as postTag } from "@/app/api/v1/tags/route";
import { PUT as putByUid } from "@/app/api/v1/tags/by-uid/[uid]/route";
import { GET as getExport } from "@/app/api/v1/tags/[id]/export/route";
import { GET as listTokens, POST as createToken } from "@/app/api/v1/tokens/route";
import { DELETE as deleteToken } from "@/app/api/v1/tokens/[id]/route";
import { GET as search } from "@/app/api/v1/search/route";
import { GET as getBackup, POST as postBackup } from "@/app/api/v1/backup/route";
import { POST as importTag } from "@/app/api/v1/tags/import/route";
import { NextRequest } from "next/server";
function req(url: string, init?: ConstructorParameters<typeof NextRequest>[1]) {
@@ -189,9 +193,81 @@ describe("API v1 integration", () => {
true
);
const revoked = await deleteToken(
req(`http://localhost/api/v1/tokens/${data.id}`, {
method: "DELETE",
headers: auth,
}),
{ params: Promise.resolve({ id: data.id }) }
);
expect(revoked.status).toBe(200);
const db = getDb();
const user = db.select().from(users).where(eq(users.id, userId)).get();
expect(user?.email).toBe("[email protected]");
expect(db.select().from(sites).all().length).toBeGreaterThanOrEqual(0);
});
it("searches, imports MCT, and backs up", async () => {
const auth = { Authorization: `Bearer ${bearer}` };
const siteRes = await postSite(
req("http://localhost/api/v1/sites", {
method: "POST",
headers: { ...auth, "Content-Type": "application/json" },
body: JSON.stringify({ code: "C", name: "Lab" }),
})
);
const site = await siteRes.json();
const mct = `+UID: AABBCCDD
+Sector: 0
AABBCCDD00112233445566778899AABB
00000000000000000000000000000000
00000000000000000000000000000000
FFFFFFFFFFFFFF078069FFFFFFFFFFFF
`;
const imported = await importTag(
req("http://localhost/api/v1/tags/import", {
method: "POST",
headers: { ...auth, "Content-Type": "application/json" },
body: JSON.stringify({
siteId: site.id,
label: "Imported fob",
content: mct,
filename: "sample.mct",
}),
})
);
expect(imported.status).toBe(201);
const tag = await imported.json();
expect(tag.uid).toBe("AABBCCDD");
const searchRes = await search(
req("http://localhost/api/v1/search?q=Imported", { headers: auth })
);
expect(searchRes.status).toBe(200);
const found = await searchRes.json();
expect(found.tags.some((t: { label: string }) => t.label === "Imported fob")).toBe(
true
);
const backupRes = await getBackup(
req("http://localhost/api/v1/backup", { headers: auth })
);
expect(backupRes.status).toBe(200);
const backup = await backupRes.json();
expect(backup.sites.length).toBeGreaterThanOrEqual(1);
expect(backup.tags.length).toBeGreaterThanOrEqual(1);
const restore = await postBackup(
req("http://localhost/api/v1/backup", {
method: "POST",
headers: { ...auth, "Content-Type": "application/json" },
body: JSON.stringify({ ...backup, mode: "merge" }),
})
);
expect(restore.status).toBe(200);
});
});
+90
View File
@@ -0,0 +1,90 @@
import { describe, expect, it } from "vitest";
import { exportTag } from "@/lib/rfid/exporters";
import {
dumpDataSchema,
mifareClassicDumpSchema,
siteCreateSchema,
tagCreateSchema,
} from "@/lib/validation/rfid";
const classicDump = {
size: "1K" as const,
sectors: [
{
index: 0,
blocks: [
"04A1B2C304A1B2C304A1B2C304A1B2C3",
"00000000000000000000000000000000",
"00000000000000000000000000000000",
"FFFFFFFFFFFFFF078069FFFFFFFFFFFF",
],
},
],
};
const sampleTag = {
id: "00000000-0000-4000-8000-000000000001",
label: "Dock fob",
frequency: "HF",
protocol: "MIFARE_CLASSIC_1K",
uid: "04A1B2C3",
dumpData: classicDump,
keys: { A: ["FFFFFFFFFFFF"], B: [] },
notes: null as string | null,
};
describe("exporters", () => {
it("exports canonical JSON", () => {
const out = exportTag(sampleTag, "json");
expect(out.contentType).toBe("application/json");
const parsed = JSON.parse(out.body);
expect(parsed.uid).toBe("04A1B2C3");
expect(parsed.dumpData.size).toBe("1K");
});
it("exports proxmark JSON with blocks", () => {
const out = exportTag(sampleTag, "proxmark");
const parsed = JSON.parse(out.body);
expect(parsed.FileType).toBe("mfcard");
expect(parsed.blocks).toHaveLength(4);
expect(parsed.Card.UID).toBe("04A1B2C3");
});
it("exports MCT text", () => {
const out = exportTag(sampleTag, "mct");
expect(out.body).toContain("+UID: 04A1B2C3");
expect(out.body).toContain("+Sector: 0");
});
it("exports hex listing", () => {
const out = exportTag(sampleTag, "hex");
expect(out.body).toContain("# UID 04A1B2C3");
expect(out.body).toContain("S0B0");
});
});
describe("validation schemas", () => {
it("accepts valid classic dump", () => {
expect(mifareClassicDumpSchema.safeParse(classicDump).success).toBe(true);
expect(dumpDataSchema.safeParse(classicDump).success).toBe(true);
});
it("rejects invalid site codes", () => {
expect(
siteCreateSchema.safeParse({ name: "Lab", code: "bad code!" }).success
).toBe(false);
});
it("accepts valid tag create payload", () => {
const parsed = tagCreateSchema.safeParse({
siteId: "00000000-0000-4000-8000-000000000099",
label: "Dock",
frequency: "HF",
protocol: "MIFARE_CLASSIC_1K",
uid: "04:A1:B2:C3",
dumpData: classicDump,
keys: { A: ["FFFFFFFFFFFF"] },
});
expect(parsed.success).toBe(true);
});
});
+42
View File
@@ -0,0 +1,42 @@
import { afterEach, describe, expect, it } from "vitest";
import { isOidcConfigured } from "@/lib/auth/oidc";
describe("isOidcConfigured", () => {
const keys = [
"AUTH_OIDC_ISSUER",
"AUTH_OIDC_CLIENT_ID",
"AUTH_OIDC_CLIENT_SECRET",
] as const;
const previous: Record<string, string | undefined> = {};
afterEach(() => {
for (const key of keys) {
if (previous[key] === undefined) delete process.env[key];
else process.env[key] = previous[key];
}
});
function save() {
for (const key of keys) previous[key] = process.env[key];
}
it("is false when any var is missing", () => {
save();
delete process.env.AUTH_OIDC_ISSUER;
delete process.env.AUTH_OIDC_CLIENT_ID;
delete process.env.AUTH_OIDC_CLIENT_SECRET;
expect(isOidcConfigured()).toBe(false);
process.env.AUTH_OIDC_ISSUER = "https://sso.example.com/";
process.env.AUTH_OIDC_CLIENT_ID = "id";
expect(isOidcConfigured()).toBe(false);
});
it("is true when all three are set", () => {
save();
process.env.AUTH_OIDC_ISSUER = "https://sso.example.com/";
process.env.AUTH_OIDC_CLIENT_ID = "id";
process.env.AUTH_OIDC_CLIENT_SECRET = "secret";
expect(isOidcConfigured()).toBe(true);
});
});
+24
View File
@@ -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();
});
});