From 325ac47a35827036026d84b9807a6bb39453bc8b Mon Sep 17 00:00:00 2001 From: Yuki MIZUNO Date: Sat, 24 Feb 2024 00:37:37 +0900 Subject: [PATCH] Add iat check on API request --- src/api/bookmark.ts | 14 +++++++++----- src/api/register.ts | 9 ++++++--- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/api/bookmark.ts b/src/api/bookmark.ts index 5aeac52..c87218a 100644 --- a/src/api/bookmark.ts +++ b/src/api/bookmark.ts @@ -75,7 +75,7 @@ export const postBookmarkHandlers = factory.createHandlers( const form = c.req.valid('form'); const url = new URL(form.url); - const { sub: user } = c.get('jwtPayload'); + const { sub: user, iat } = c.get('jwtPayload'); const { DB } = env<{ DB: D1Database }>(c); const db = drizzle(DB); @@ -85,12 +85,16 @@ export const postBookmarkHandlers = factory.createHandlers( } const { repo, rkey, uri, cid } = record; - const count = await db - .select({ value: users.bookmarkCount }) + const userdata = await db + .select({ count: users.bookmarkCount, iat: users.issuedAt }) .from(users) .where(eq(users.user, user)) .get(); - if (!count || count.value > 200) { + + if (!userdata || (userdata.iat !== 0 && iat !== userdata.iat)) { + return c.text('unauthorized', 401); + } + if (userdata.count > 200) { // bookmark limit reached. only DELETE request is allowed for this user at this momen. return c.json({ error: 'bookmark limit reached', params: { url } }, 405); } @@ -111,7 +115,7 @@ export const postBookmarkHandlers = factory.createHandlers( db.insert(operations).values({ opcode: 'add', ...result }), db .update(users) - .set({ bookmarkCount: count.value + 1 }) + .set({ bookmarkCount: userdata.count + 1 }) .where(eq(users.user, user)), ]); return c.json({ status: 'created', params: { url } }, 201); diff --git a/src/api/register.ts b/src/api/register.ts index 567edb8..9d35509 100644 --- a/src/api/register.ts +++ b/src/api/register.ts @@ -62,16 +62,19 @@ export const registerAccount = factory.createHandlers( } } + const now = Math.floor(Date.now() / 1000); + const db = drizzle(DB); await db .insert(users) .values({ handle: handleName, user: did }) - .onConflictDoNothing(); - + .onConflictDoUpdate({ + target: users.user, + set: { handle: handleName, issuedAt: now }, + }); await savePubkey(c, didDoc.id, findPubkey(didDoc) ?? ''); const { JWT_SECRET } = env<{ JWT_SECRET: string }>(c); - const now = Math.floor(Date.now() / 1000); const token = await sign( { sub: did, iat: now, exp: now + 30 * 24 * 60 * 60 }, JWT_SECRET,