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",
});
}
},
);

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 });
});
2 changes: 2 additions & 0 deletions apps/api/src/routes/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { activityRoutes } from "./activity";
import { uploadRoutes } from "./upload";
import { pluginsRoutes } from "./plugins";
import { moderationRoutes } from "./moderation";
import { authRoutes } from "./auth";

// Create main API router
export const apiRoutes = new Hono<Env>();
Expand All @@ -36,3 +37,4 @@ apiRoutes.route("/users", usersRoutes);
apiRoutes.route("/activity", activityRoutes);
apiRoutes.route("/upload", uploadRoutes);
apiRoutes.route("/moderate", moderationRoutes);
apiRoutes.route("/auth", authRoutes);
103 changes: 103 additions & 0 deletions apps/api/src/services/auth.service.ts
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",
};
}

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.");
}

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 };
}
}
10 changes: 10 additions & 0 deletions apps/api/src/services/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@ export class UserService implements IBaseService {
return UserProfileSchema.parse(parsedUser);
}

async ensureUserProfile(nearAccountId: string): Promise<UserProfile> {
const existingUser = await this.findUserByNearAccountId(nearAccountId);
if (existingUser) {
return existingUser;
}

const newUser = await this.createUser({ nearAccountId });
return newUser;
}

/**
* Find a user by NEAR account ID and return as API UserProfile
*/
Expand Down
14 changes: 14 additions & 0 deletions apps/api/src/utils/service-provider.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
ActivityRepository,
AuthRequestRepository,
FeedRepository,
LeaderboardRepository,
ModerationRepository,
Expand All @@ -11,6 +12,7 @@ import { SubmissionService } from "services/submission.service";
import { MockTwitterService } from "../__test__/mocks/twitter-service.mock";
import { db } from "../db";
import { ActivityService } from "../services/activity.service";
import { AuthService } from "../services/auth.service";
import { ConfigService, isProduction } from "../services/config.service";
import { DistributionService } from "../services/distribution.service";
import { FeedService } from "../services/feed.service";
Expand Down Expand Up @@ -86,6 +88,10 @@ export class ServiceProvider {
);
this.services.set("userService", userService);

const authRequestRepository = new AuthRequestRepository(db);
const authService = new AuthService(authRequestRepository, userService);
this.services.set("authService", authService);

const feedService = new FeedService(
feedRepository,
processorService,
Expand Down Expand Up @@ -207,6 +213,14 @@ export class ServiceProvider {
return this.getService<UserService>("userService");
}

/**
* Get the auth service
* @returns The auth service
*/
public getAuthService(): AuthService {
return this.getService<AuthService>("authService");
}

/**
* Get the activity service
* @returns The activity service
Expand Down
3 changes: 2 additions & 1 deletion apps/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
},
"dependencies": {
"@crosspost/sdk": "^0.3.0",
"@fastnear/utils": "^0.9.7",
"@hookform/resolvers": "^5.0.1",
"@radix-ui/react-avatar": "^1.1.3",
"@radix-ui/react-checkbox": "^1.1.5",
Expand Down Expand Up @@ -43,7 +44,7 @@
"immer": "^10.1.1",
"lodash": "^4.17.21",
"lucide-react": "^0.483.0",
"near-sign-verify": "^0.3.6",
"near-sign-verify": "^0.4.1",
"pinata-web3": "^0.5.4",
"postcss": "^8.4.49",
"react": "^18.3.1",
Expand Down
Loading