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
27 changes: 27 additions & 0 deletions app/api/auth/logout/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { NextRequest, NextResponse } from 'next/server'
import {
clearSessionCookies,
readRefreshToken,
revokeSession,
} from '@/lib/auth/session'

export async function POST(request: NextRequest): Promise<NextResponse> {
try {
const refreshToken = readRefreshToken(request)
if (refreshToken) {
await revokeSession(refreshToken)
}

const response = NextResponse.json({ ok: true }, { status: 200 })
clearSessionCookies(response)
return response
} catch {
return NextResponse.json(
{
error: 'Failed to log out',
code: 'LOGOUT_FAILED',
},
{ status: 500 }
)
}
}
12 changes: 12 additions & 0 deletions app/api/auth/me/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { NextResponse } from 'next/server'
import { withAuth } from '@/lib/auth/middleware'

export const GET = withAuth(async (_request, auth) => {
return NextResponse.json(
{
walletAddress: auth.walletAddress,
authenticated: true,
},
{ status: 200 }
)
})
57 changes: 57 additions & 0 deletions app/api/auth/nonce/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { NextRequest, NextResponse } from 'next/server'
import { NONCE_TTL_SECONDS } from '@/lib/auth/constants'
import { randomNonce, sha256Hex } from '@/lib/auth/crypto'
import { saveNonce } from '@/lib/auth/store'
import {
buildAuthMessage,
isValidStellarAddress,
normalizeWalletAddress,
} from '@/lib/auth/stellar'

interface NonceRequestBody {
walletAddress?: string
}

export async function POST(request: NextRequest): Promise<NextResponse> {
try {
const body: NonceRequestBody = await request.json()
const walletAddress = body.walletAddress?.trim()

if (!walletAddress || !isValidStellarAddress(walletAddress)) {
return NextResponse.json(
{
error: 'Invalid wallet address',
code: 'INVALID_WALLET_ADDRESS',
},
{ status: 400 }
)
}

const normalizedWallet = normalizeWalletAddress(walletAddress)
const nonce = randomNonce()
const expiresAt = new Date(Date.now() + NONCE_TTL_SECONDS * 1000)
await saveNonce({
walletAddress: normalizedWallet,
nonceHash: sha256Hex(nonce),
expiresAt,
})

return NextResponse.json(
{
walletAddress: normalizedWallet,
nonce,
message: buildAuthMessage(normalizedWallet, nonce),
expiresAt: expiresAt.toISOString(),
},
{ status: 200 }
)
} catch {
return NextResponse.json(
{
error: 'Failed to create auth nonce',
code: 'NONCE_ISSUE_FAILED',
},
{ status: 500 }
)
}
}
52 changes: 52 additions & 0 deletions app/api/auth/refresh/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { NextRequest, NextResponse } from 'next/server'
import {
readRefreshToken,
rotateSession,
setSessionCookies,
} from '@/lib/auth/session'

export async function POST(request: NextRequest): Promise<NextResponse> {
try {
const refreshToken = readRefreshToken(request)
if (!refreshToken) {
return NextResponse.json(
{
error: 'Refresh token is required',
code: 'REFRESH_TOKEN_REQUIRED',
},
{ status: 401 }
)
}

const session = await rotateSession(request, refreshToken)
if (!session) {
return NextResponse.json(
{
error: 'Invalid or expired refresh token',
code: 'INVALID_REFRESH_TOKEN',
},
{ status: 401 }
)
}

const response = NextResponse.json(
{
walletAddress: session.walletAddress,
accessTokenExpiresAt: session.accessTokenExpiresAt.toISOString(),
refreshTokenExpiresAt: session.refreshTokenExpiresAt.toISOString(),
},
{ status: 200 }
)
setSessionCookies(response, session)

return response
} catch {
return NextResponse.json(
{
error: 'Failed to refresh session',
code: 'SESSION_REFRESH_FAILED',
},
{ status: 500 }
)
}
}
125 changes: 125 additions & 0 deletions app/api/auth/verify/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { NextRequest, NextResponse } from 'next/server'
import { createSession, setSessionCookies } from '@/lib/auth/session'
import { consumeNonce, hasActiveNonce } from '@/lib/auth/store'
import { sha256Hex } from '@/lib/auth/crypto'
import {
buildAuthMessage,
isValidStellarAddress,
normalizeWalletAddress,
verifyStellarSignature,
} from '@/lib/auth/stellar'

interface VerifyRequestBody {
walletAddress?: string
nonce?: string
signature?: string
message?: string
}

export async function POST(request: NextRequest): Promise<NextResponse> {
try {
const body: VerifyRequestBody = await request.json()

const walletAddress = body.walletAddress?.trim()
const nonce = body.nonce?.trim()
const signature = body.signature?.trim()

if (!walletAddress || !nonce || !signature) {
return NextResponse.json(
{
error: 'Missing walletAddress, nonce, or signature',
code: 'INVALID_AUTH_PAYLOAD',
},
{ status: 400 }
)
}

if (!isValidStellarAddress(walletAddress)) {
return NextResponse.json(
{
error: 'Invalid wallet address',
code: 'INVALID_WALLET_ADDRESS',
},
{ status: 400 }
)
}

const normalizedWallet = normalizeWalletAddress(walletAddress)
const nonceHash = sha256Hex(nonce)
const expectedMessage = buildAuthMessage(normalizedWallet, nonce)

if (body.message && body.message !== expectedMessage) {
return NextResponse.json(
{
error: 'Signed message does not match expected format',
code: 'MESSAGE_MISMATCH',
},
{ status: 400 }
)
}

const nonceIsValid = await hasActiveNonce({
walletAddress: normalizedWallet,
nonceHash,
})
if (!nonceIsValid) {
return NextResponse.json(
{
error: 'Nonce is invalid, expired, or already used',
code: 'INVALID_NONCE',
},
{ status: 401 }
)
}

const signatureIsValid = verifyStellarSignature({
walletAddress: normalizedWallet,
message: expectedMessage,
signature,
})
if (!signatureIsValid) {
return NextResponse.json(
{
error: 'Invalid wallet signature',
code: 'INVALID_SIGNATURE',
},
{ status: 401 }
)
}

const consumed = await consumeNonce({
walletAddress: normalizedWallet,
nonceHash,
})
if (!consumed) {
return NextResponse.json(
{
error: 'Nonce is invalid, expired, or already used',
code: 'INVALID_NONCE',
},
{ status: 401 }
)
}

const session = await createSession(request, normalizedWallet)
const response = NextResponse.json(
{
walletAddress: normalizedWallet,
accessTokenExpiresAt: session.accessTokenExpiresAt.toISOString(),
refreshTokenExpiresAt: session.refreshTokenExpiresAt.toISOString(),
},
{ status: 200 }
)
setSessionCookies(response, session)

return response
} catch {
return NextResponse.json(
{
error: 'Authentication failed',
code: 'AUTH_VERIFICATION_FAILED',
},
{ status: 500 }
)
}
}
4 changes: 0 additions & 4 deletions app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import React from "react"
import type { Metadata } from 'next'
import { Geist, Geist_Mono } from 'next/font/google'
import { Analytics } from '@vercel/analytics/next'
import './globals.css'

const _geist = Geist({ subsets: ["latin"] });
const _geistMono = Geist_Mono({ subsets: ["latin"] });

export const metadata: Metadata = {
title: 'TaskChain',
description: 'Web3-powered freelance marketplace with escrow-based payments on Stellar blockchain. Protect your work and payments with smart contract security.',
Expand Down
Binary file added docs/pr-evidence/build.txt
Binary file not shown.
Binary file added docs/pr-evidence/lint.txt
Binary file not shown.
3 changes: 2 additions & 1 deletion env.example
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
DATABASE_URL=your db url
DATABASE_URL=your db url
JWT_SECRET=replace_with_a_long_random_secret_min_32_chars
6 changes: 6 additions & 0 deletions lib/auth/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const ACCESS_TOKEN_COOKIE = 'tc_access_token'
export const REFRESH_TOKEN_COOKIE = 'tc_refresh_token'

export const ACCESS_TOKEN_TTL_SECONDS = 15 * 60
export const REFRESH_TOKEN_TTL_SECONDS = 7 * 24 * 60 * 60
export const NONCE_TTL_SECONDS = 5 * 60
44 changes: 44 additions & 0 deletions lib/auth/crypto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { createHash, randomBytes, timingSafeEqual } from 'crypto'

function toBase64Url(input: Buffer | string): string {
const buffer = typeof input === 'string' ? Buffer.from(input, 'utf8') : input
return buffer
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/g, '')
}

export function fromBase64Url(value: string): Buffer {
const normalized = value.replace(/-/g, '+').replace(/_/g, '/')
const padding = normalized.length % 4
const padded =
padding === 0 ? normalized : normalized + '='.repeat(4 - padding)
return Buffer.from(padded, 'base64')
}

export function sha256Hex(value: string): string {
return createHash('sha256').update(value, 'utf8').digest('hex')
}

export function randomNonce(bytes = 32): string {
return toBase64Url(randomBytes(bytes))
}

export function randomId(bytes = 24): string {
return toBase64Url(randomBytes(bytes))
}

export function safeEqual(a: string, b: string): boolean {
const left = Buffer.from(a, 'utf8')
const right = Buffer.from(b, 'utf8')
if (left.length !== right.length) {
return false
}

return timingSafeEqual(left, right)
}

export function encodeBase64Url(value: Buffer | string): string {
return toBase64Url(value)
}
Loading