Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,13 @@
"zod": "^3.25.62"
},
"dependencies": {
"@crosspost/scheduler-sdk": "^0.1.1",
"@crosspost/sdk": "^0.3.0",
"@crosspost/types": "^0.3.0",
"@crosspost/scheduler-sdk": "^0.1.1",
"@curatedotfun/shared-db": "workspace:*",
"@curatedotfun/types": "workspace:*",
"@curatedotfun/utils": "workspace:*",
"@fastnear/utils": "^0.9.7",
"@hono/node-server": "^1.8.2",
"@hono/zod-openapi": "^0.9.5",
"@hono/zod-validator": "^0.5.0",
Expand All @@ -60,7 +61,7 @@
"lodash": "^4.17.21",
"mustache": "^4.2.0",
"near-api-js": "^5.1.1",
"near-sign-verify": "^0.3.6",
"near-sign-verify": "^0.4.1",
"ora": "^8.1.1",
"pg": "^8.15.6",
"pinata-web3": "^0.5.4",
Expand Down
63 changes: 20 additions & 43 deletions apps/api/src/middlewares/auth.middleware.ts
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();
};
}
67 changes: 67 additions & 0 deletions apps/api/src/routes/api/auth.ts
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",
});
}
Comment on lines +48 to +54
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid exposing internal error details in authentication responses.

For security reasons, authentication endpoints should return generic error messages to prevent information leakage about the system's internal state.

Apply this diff to return a generic error message:

    } catch (error: unknown) {
      c.status(401);
      return c.json({
        success: false,
-       error: error instanceof Error ? error.message : "Authentication failed",
+       error: "Authentication failed",
      });
    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (error: unknown) {
c.status(401);
return c.json({
success: false,
error: error instanceof Error ? error.message : "Authentication failed",
});
}
} catch (error: unknown) {
c.status(401);
return c.json({
success: false,
error: "Authentication failed",
});
}
🤖 Prompt for AI Agents
In apps/api/src/routes/api/auth.ts around lines 48 to 54, the current error
response returns the actual error message which may expose internal details.
Modify the catch block to always return a generic error message like
"Authentication failed" instead of the specific error.message, ensuring no
internal error details are leaked in the response.

},
);

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 });
});
Loading