forked from elliotBraem/efizzybot
-
Notifications
You must be signed in to change notification settings - Fork 7
Implements JWT auth flow with 7 day tokens #187
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
5 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
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 |
|---|---|---|
| @@ -1,54 +1,31 @@ | ||
| import { Context, MiddlewareHandler, Next } from "hono"; | ||
| import { verify } from "near-sign-verify"; | ||
| import { verify } from "hono/jwt"; | ||
| import { getCookie } from "hono/cookie"; | ||
|
|
||
| export function createAuthMiddleware(): MiddlewareHandler { | ||
| return async (c: Context, next: Next) => { | ||
| const method = c.req.method; | ||
| const token = getCookie(c, "token"); | ||
| let accountId: string | null = null; | ||
|
|
||
| if (method === "GET") { | ||
| const nearAccountHeader = c.req.header("X-Near-Account"); | ||
| if ( | ||
| nearAccountHeader && | ||
| nearAccountHeader.toLowerCase() !== "anonymous" | ||
| ) { | ||
| accountId = nearAccountHeader; | ||
| if (token) { | ||
| const secret = process.env.JWT_SECRET; | ||
| if (!secret) { | ||
| console.error("JWT_SECRET is not set."); | ||
| c.status(500); | ||
| return c.json({ error: "Internal Server Error" }); | ||
| } | ||
| try { | ||
| const decodedPayload = await verify(token, secret); | ||
| if (decodedPayload && typeof decodedPayload.sub === "string") { | ||
| accountId = decodedPayload.sub; | ||
| } | ||
| } catch (error) { | ||
| // Invalid token, proceed as anonymous | ||
| console.warn("JWT verification failed:", error); | ||
| } | ||
| // If header is missing or "anonymous", accountId remains null | ||
| c.set("accountId", accountId); | ||
| await next(); | ||
| return; | ||
| } | ||
|
|
||
| // For non-GET requests (POST, PUT, DELETE, PATCH, etc.) | ||
| const authHeader = c.req.header("Authorization"); | ||
| if (!authHeader || !authHeader.startsWith("Bearer ")) { | ||
| c.status(401); | ||
| return c.json({ | ||
| error: "Unauthorized", | ||
| details: "Missing or malformed Authorization header.", | ||
| }); | ||
| } | ||
|
|
||
| const token = authHeader.substring(7); // Remove "Bearer " | ||
|
|
||
| try { | ||
| const verificationResult = await verify(token, { | ||
| expectedRecipient: "curatefun.near", | ||
| requireFullAccessKey: false, | ||
| nonceMaxAge: 300000, // 5 mins | ||
| }); | ||
|
|
||
| accountId = verificationResult.accountId; | ||
| c.set("accountId", accountId); | ||
| await next(); | ||
| } catch (error) { | ||
| console.error("Token verification error:", error); | ||
| c.status(401); | ||
| return c.json({ | ||
| error: "Unauthorized", | ||
| details: "Invalid token signature or recipient.", | ||
| }); | ||
| } | ||
| c.set("accountId", accountId); | ||
| await next(); | ||
| }; | ||
| } | ||
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,67 @@ | ||
| import { Hono } from "hono"; | ||
| import { zValidator } from "@hono/zod-validator"; | ||
| import { z } from "zod"; | ||
| import { AuthService } from "../../services/auth.service"; | ||
| import { Env } from "../../types/app"; | ||
| import { setCookie } from "hono/cookie"; | ||
|
|
||
| export const authRoutes = new Hono<Env>(); | ||
|
|
||
| const CreateAuthRequestSchema = z.object({ | ||
| accountId: z.string(), | ||
| }); | ||
|
|
||
| const VerifyAuthRequestSchema = z.object({ | ||
| token: z.string(), | ||
| accountId: z.string(), | ||
| }); | ||
|
|
||
| authRoutes.post( | ||
| "/initiate-login", | ||
| zValidator("json", CreateAuthRequestSchema), | ||
| async (c) => { | ||
| const payload = c.req.valid("json"); | ||
| const sp = c.var.sp; | ||
| const authService = sp.getService<AuthService>("authService"); | ||
| const result = await authService.createAuthRequest(payload); | ||
| return c.json(result); | ||
| }, | ||
| ); | ||
|
|
||
| authRoutes.post( | ||
| "/verify-login", | ||
| zValidator("json", VerifyAuthRequestSchema), | ||
| async (c) => { | ||
| const payload = c.req.valid("json"); | ||
| const sp = c.var.sp; | ||
| const authService = sp.getService<AuthService>("authService"); | ||
| try { | ||
| const { jwt } = await authService.verifyAuthRequest(payload); | ||
| setCookie(c, "token", jwt, { | ||
| httpOnly: true, | ||
| secure: process.env.NODE_ENV === "production", | ||
| sameSite: "Strict", | ||
| path: "/", | ||
| maxAge: 60 * 60 * 24 * 7, // 7 days | ||
| }); | ||
| return c.json({ success: true }); | ||
| } catch (error: unknown) { | ||
| c.status(401); | ||
| return c.json({ | ||
| success: false, | ||
| error: error instanceof Error ? error.message : "Authentication failed", | ||
| }); | ||
| } | ||
| }, | ||
| ); | ||
|
|
||
| authRoutes.post("/logout", async (c) => { | ||
| setCookie(c, "token", "", { | ||
| httpOnly: true, | ||
| secure: process.env.NODE_ENV === "production", | ||
| sameSite: "Strict", | ||
| path: "/", | ||
| maxAge: 0, | ||
| }); | ||
| return c.json({ success: true }); | ||
| }); |
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,103 @@ | ||
| import { | ||
| AuthRequestRepository, | ||
| InsertAuthRequest, | ||
| } from "@curatedotfun/shared-db"; | ||
| import { toHex } from "@fastnear/utils"; | ||
| import { randomBytes } from "crypto"; | ||
| import { sign } from "hono/jwt"; | ||
| import { verify } from "near-sign-verify"; | ||
| import { z } from "zod"; | ||
| import { UserService } from "./users.service"; | ||
|
|
||
| const AUTH_REQUEST_EXPIRY_MS = 5 * 60 * 1000; // 5 minutes | ||
| const JWT_EXPIRY_SECONDS = 60 * 60 * 24 * 7; // 7 days | ||
|
|
||
| const CreateAuthRequestSchema = z.object({ | ||
| accountId: z.string(), | ||
| }); | ||
|
|
||
| const VerifyAuthRequestSchema = z.object({ | ||
| token: z.string(), | ||
| accountId: z.string(), | ||
| }); | ||
|
|
||
| export class AuthService { | ||
| private userService: UserService; | ||
| private authRequestRepository: AuthRequestRepository; | ||
|
|
||
| constructor( | ||
| authRequestRepository: AuthRequestRepository, | ||
| userService: UserService, | ||
| ) { | ||
| this.authRequestRepository = authRequestRepository; | ||
| this.userService = userService; | ||
| } | ||
|
|
||
| async createAuthRequest(payload: z.infer<typeof CreateAuthRequestSchema>) { | ||
| const { accountId } = payload; | ||
| await this.userService.ensureUserProfile(accountId); | ||
|
|
||
| const nonce = randomBytes(32).toString("hex"); | ||
|
|
||
| const expiresAt = new Date(Date.now() + AUTH_REQUEST_EXPIRY_MS); | ||
|
|
||
| const newAuthRequest: InsertAuthRequest = { | ||
| nonce, | ||
| accountId, | ||
| expiresAt, | ||
| }; | ||
|
|
||
| await this.authRequestRepository.create(newAuthRequest); | ||
|
|
||
| return { | ||
| nonce, | ||
| recipient: "curatefun.near", | ||
elliotBraem marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }; | ||
| } | ||
|
|
||
| async verifyAuthRequest(payload: z.infer<typeof VerifyAuthRequestSchema>) { | ||
| const { token, accountId } = payload; | ||
|
|
||
| const latestRequest = | ||
| await this.authRequestRepository.findLatestByAccountId(accountId); | ||
|
|
||
| if (!latestRequest) { | ||
| throw new Error("No recent auth request found for this account."); | ||
| } | ||
elliotBraem marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if (latestRequest.expiresAt < new Date()) { | ||
| await this.authRequestRepository.deleteById(latestRequest.id); | ||
| throw new Error("Auth request has expired."); | ||
| } | ||
|
|
||
| const message = `Authorize Curate.fun`; | ||
|
|
||
| const verificationResult = await verify(token, { | ||
| expectedRecipient: "curatefun.near", | ||
| expectedMessage: message, | ||
| validateNonce: (nonceFromToken) => { | ||
| const receivedNonceHex = toHex(nonceFromToken); | ||
| return receivedNonceHex === latestRequest.nonce; | ||
| }, | ||
| }); | ||
|
|
||
| if (verificationResult.accountId !== accountId) { | ||
| throw new Error("Account ID mismatch."); | ||
| } | ||
|
|
||
| await this.authRequestRepository.deleteById(latestRequest.id); | ||
|
|
||
| const jwtPayload = { | ||
| sub: accountId, | ||
| exp: Math.floor(Date.now() / 1000) + JWT_EXPIRY_SECONDS, | ||
| }; | ||
|
|
||
| const secret = process.env.JWT_SECRET; | ||
| if (!secret) { | ||
| throw new Error("JWT_SECRET is not set."); | ||
| } | ||
|
|
||
| const jwt = await sign(jwtPayload, secret); | ||
| return { jwt }; | ||
| } | ||
| } | ||
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.
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.