-
Notifications
You must be signed in to change notification settings - Fork 0
feat(api): add PAM auth and token utilities #16
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| .git | ||
| .gitignore | ||
| .gitattributes | ||
| AGENTS.md | ||
| CHANGELOG.md | ||
| CONTRIBUTING.md | ||
| VERSION | ||
| *.md | ||
| node_modules | ||
| apps/web | ||
| apps/docs | ||
| data | ||
| workspace | ||
| infra | ||
| dist | ||
| .env | ||
| __pycache__ | ||
| *.log | ||
| docker-compose.yml | ||
| CLI.md |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import { Elysia } from "elysia"; | ||
| import { signAccessToken, verifyAccessToken, generateRefreshToken, storeRefreshToken, validateRefreshToken, blacklistRefreshToken } from "../../utils/auth"; | ||
| import { config } from "../../utils/config"; | ||
|
|
||
| const PAM_AUTH_URL = "http://pam-auth:4567"; | ||
|
|
||
| const callPam = async (username: string, password: string): Promise<{ ok: boolean; username?: string; error?: string }> => { | ||
| try { | ||
| const res = await fetch(`${PAM_AUTH_URL}/auth`, { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify({ username, password }), | ||
| signal: AbortSignal.timeout(5000), | ||
| }); | ||
| const data = await res.json(); | ||
| return data; | ||
| } catch (err) { | ||
| return { ok: false, error: "Auth service unavailable" }; | ||
| } | ||
| }; | ||
|
|
||
| const SESSION_COOKIE_OPTS = { | ||
| path: "/", | ||
| httpOnly: true, | ||
| sameSite: "strict" as const, | ||
| secure: config.caddyBaseDomain !== "localhost", | ||
| maxAge: 900, | ||
| }; | ||
|
|
||
| const REFRESH_COOKIE_OPTS = { | ||
| path: "/", | ||
| httpOnly: true, | ||
| sameSite: "strict" as const, | ||
| secure: config.caddyBaseDomain !== "localhost", | ||
| maxAge: 7 * 24 * 60 * 60, | ||
| }; | ||
|
|
||
| export const authRoutes = new Elysia() | ||
| .post("/auth/login", async ({ body, cookie: { dequel_session, dequel_refresh }, set }) => { | ||
| const { username, password } = body as { username?: string; password?: string }; | ||
| if (!username || !password) { | ||
| set.status = 400; | ||
| return { error: "Username and password required" }; | ||
| } | ||
| const result = await callPam(username, password); | ||
| if (!result.ok) { | ||
| set.status = 401; | ||
| return { error: result.error || "Authentication failed" }; | ||
| } | ||
| const accessToken = await signAccessToken(username); | ||
| const refreshToken = generateRefreshToken(); | ||
| await storeRefreshToken(username, refreshToken); | ||
| dequel_session.value = accessToken; | ||
| dequel_session.set(SESSION_COOKIE_OPTS); | ||
| dequel_refresh.value = refreshToken; | ||
| dequel_refresh.set(REFRESH_COOKIE_OPTS); | ||
| return { ok: true, username }; | ||
| }) | ||
| .post("/auth/logout", async ({ cookie: { dequel_session, dequel_refresh } }) => { | ||
| const rt = dequel_refresh.value; | ||
| if (rt) { | ||
| try { await blacklistRefreshToken(rt); } catch {} | ||
| } | ||
| dequel_session.remove(); | ||
| dequel_refresh.remove(); | ||
| return { ok: true }; | ||
| }) | ||
| .post("/auth/refresh", async ({ cookie: { dequel_session, dequel_refresh }, set }) => { | ||
| const rt = dequel_refresh.value; | ||
| if (!rt) { | ||
| set.status = 401; | ||
| return { error: "No refresh token" }; | ||
| } | ||
| const username = await validateRefreshToken(rt); | ||
| if (!username) { | ||
| set.status = 401; | ||
| return { error: "Invalid or expired refresh token" }; | ||
| } | ||
| await blacklistRefreshToken(rt); | ||
| const accessToken = await signAccessToken(username); | ||
| const newRefreshToken = generateRefreshToken(); | ||
| await storeRefreshToken(username, newRefreshToken); | ||
| dequel_session.value = accessToken; | ||
| dequel_session.set(SESSION_COOKIE_OPTS); | ||
| dequel_refresh.value = newRefreshToken; | ||
| dequel_refresh.set(REFRESH_COOKIE_OPTS); | ||
| return { ok: true, username }; | ||
| }) | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| .get("/auth/me", async ({ cookie: { dequel_session } }) => { | ||
| const token = dequel_session.value; | ||
| if (!token) return { authenticated: false }; | ||
| const payload = await verifyAccessToken(token); | ||
| if (!payload) return { authenticated: false }; | ||
| return { authenticated: true, username: payload.sub }; | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import { describe, it, expect, mock, beforeAll, beforeEach, afterAll } from 'bun:test'; | ||
| import { Database } from 'bun:sqlite'; | ||
|
|
||
| const TEST_SECRET = 'test-jwt-secret-for-testing-purposes-only'; | ||
|
|
||
| let db: Database; | ||
|
|
||
| const fileUrl = (path: string) => new URL(path, import.meta.url).toString(); | ||
| mock.module(fileUrl('../client.ts'), () => ({ | ||
| getDb: () => db, | ||
| })); | ||
|
|
||
| beforeAll(async () => { | ||
| db = new Database(':memory:'); | ||
| db.run(` | ||
| CREATE TABLE refresh_tokens ( | ||
| id text PRIMARY KEY NOT NULL, | ||
| username text NOT NULL, | ||
| token_hash text NOT NULL UNIQUE, | ||
| expires_at text NOT NULL, | ||
| created_at text NOT NULL, | ||
| blacklisted_at text | ||
| ) | ||
| `); | ||
| const { initAuth } = await import('../../utils/auth'); | ||
| initAuth(TEST_SECRET); | ||
| }); | ||
|
|
||
| beforeEach(() => { | ||
| db.run('DELETE FROM refresh_tokens'); | ||
| }); | ||
|
|
||
| afterAll(() => { | ||
| db.close(); | ||
| }); | ||
|
|
||
| describe('storeRefreshToken / validateRefreshToken', () => { | ||
| it('stores and validates a refresh token', async () => { | ||
| const { generateRefreshToken, storeRefreshToken, validateRefreshToken } = await import('../../utils/auth'); | ||
| const token = generateRefreshToken(); | ||
| await storeRefreshToken('testuser', token); | ||
| const username = await validateRefreshToken(token); | ||
| expect(username).toBe('testuser'); | ||
| }); | ||
|
|
||
| it('returns null for unknown token', async () => { | ||
| const { validateRefreshToken } = await import('../../utils/auth'); | ||
| const result = await validateRefreshToken('dqr_nonexistent'); | ||
| expect(result).toBeNull(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('blacklistRefreshToken', () => { | ||
| it('blacklists a refresh token', async () => { | ||
| const { generateRefreshToken, storeRefreshToken, validateRefreshToken, blacklistRefreshToken } = await import('../../utils/auth'); | ||
| const token = generateRefreshToken(); | ||
| await storeRefreshToken('testuser', token); | ||
| expect(await validateRefreshToken(token)).toBe('testuser'); | ||
| await blacklistRefreshToken(token); | ||
| expect(await validateRefreshToken(token)).toBeNull(); | ||
| }); | ||
|
|
||
| it('does not affect other tokens when blacklisting one', async () => { | ||
| const { generateRefreshToken, storeRefreshToken, validateRefreshToken, blacklistRefreshToken } = await import('../../utils/auth'); | ||
| const tokenA = generateRefreshToken(); | ||
| const tokenB = generateRefreshToken(); | ||
| await storeRefreshToken('user1', tokenA); | ||
| await storeRefreshToken('user2', tokenB); | ||
| await blacklistRefreshToken(tokenA); | ||
| expect(await validateRefreshToken(tokenA)).toBeNull(); | ||
| expect(await validateRefreshToken(tokenB)).toBe('user2'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('cleanupExpiredTokens', () => { | ||
| it('removes expired tokens', async () => { | ||
| const { generateRefreshToken, storeRefreshToken, cleanupExpiredTokens } = await import('../../utils/auth'); | ||
| const token = generateRefreshToken(); | ||
| await storeRefreshToken('testuser', token); | ||
| const row = db.query('SELECT token_hash FROM refresh_tokens ORDER BY created_at DESC LIMIT 1').get() as { token_hash: string }; | ||
| db.run(`UPDATE refresh_tokens SET expires_at = '2000-01-01T00:00:00.000Z' WHERE token_hash = ?`, [row.token_hash]); | ||
| await cleanupExpiredTokens(); | ||
| const remaining = db.query('SELECT COUNT(*) as c FROM refresh_tokens').get() as { c: number }; | ||
| expect(remaining.c).toBe(0); | ||
| }); | ||
|
|
||
| it('keeps non-expired tokens', async () => { | ||
| const { generateRefreshToken, storeRefreshToken, cleanupExpiredTokens } = await import('../../utils/auth'); | ||
| const token = generateRefreshToken(); | ||
| await storeRefreshToken('testuser', token); | ||
| await cleanupExpiredTokens(); | ||
| const remaining = db.query('SELECT COUNT(*) as c FROM refresh_tokens').get() as { c: number }; | ||
| expect(remaining.c).toBe(1); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| CREATE TABLE IF NOT EXISTS refresh_tokens ( | ||
| id text PRIMARY KEY NOT NULL, | ||
| username text NOT NULL, | ||
| token_hash text NOT NULL UNIQUE, | ||
| expires_at text NOT NULL, | ||
| created_at text NOT NULL, | ||
| blacklisted_at text | ||
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.