Skip to content
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

feat: add generic next middleware #52

Merged
merged 1 commit into from
Jan 22, 2025
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: 5 additions & 0 deletions .changeset/brave-steaks-fly.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@cipherstash/nextjs": minor
---

Implemented a generic Next.js jseql middleware.
57 changes: 4 additions & 53 deletions packages/nextjs/src/clerk/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { ClerkMiddlewareAuth } from '@clerk/nextjs/server'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import { CS_COOKIE_NAME, type CtsToken } from '../index'
import { CS_COOKIE_NAME, resetCtsToken } from '../index'
import { setCtsToken } from '../cts'
import { logger } from '../../../utils/logger'

export const jseqlClerkMiddleware = async (
Expand All @@ -22,65 +23,15 @@ export const jseqlClerkMiddleware = async (
return NextResponse.next()
}

const workspaceId = process.env.CS_WORKSPACE_ID

if (!workspaceId) {
logger.error(
'The "CS_WORKSPACE_ID" environment variable is not set, and is required by jseqlClerkMiddleware. No CipherStash session will be set.',
)

return NextResponse.next()
}

const ctsEndoint =
process.env.CS_CTS_ENDPOINT ||
'https://ap-southeast-2.aws.auth.viturhosted.net'

const ctsResponse = await fetch(`${ctsEndoint}/api/authorize`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
workspaceId,
oidcToken,
}),
})

if (!ctsResponse.ok) {
logger.debug(`Failed to fetch CTS token: ${ctsResponse.statusText}`)

logger.error(
'There was an issue communicating with the CipherStash CTS API, the CipherStash session was not set. If the issue persists, please contact support.',
)

return NextResponse.next()
}

const cts_token = (await ctsResponse.json()) as CtsToken

// Setting cookies on the request and response using the `ResponseCookies` API
const response = NextResponse.next()
response.cookies.set({
name: CS_COOKIE_NAME,
value: JSON.stringify(cts_token),
expires: new Date(cts_token.expiry * 1000),
sameSite: 'lax',
path: '/',
})

response.cookies.get(CS_COOKIE_NAME)
return response
return await setCtsToken(oidcToken)
}

if (!userId && ctsSession) {
logger.debug(
'No Clerk token found in the request, so the CipherStash session was reset.',
)

const response = NextResponse.next()
response.cookies.delete(CS_COOKIE_NAME)
return response
return resetCtsToken()
}

logger.debug(
Expand Down
55 changes: 55 additions & 0 deletions packages/nextjs/src/cts/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { NextResponse } from 'next/server'
import { logger } from '../../../utils/logger'
import { CS_COOKIE_NAME, type CtsToken } from '../index'

export const setCtsToken = async (oidcToken: string) => {
const workspaceId = process.env.CS_WORKSPACE_ID

if (!workspaceId) {
logger.error(
'The "CS_WORKSPACE_ID" environment variable is not set, and is required by jseqlClerkMiddleware. No CipherStash session will be set.',
)

return NextResponse.next()
}

const ctsEndoint =
process.env.CS_CTS_ENDPOINT ||
'https://ap-southeast-2.aws.auth.viturhosted.net'

const ctsResponse = await fetch(`${ctsEndoint}/api/authorize`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
workspaceId,
oidcToken,
}),
})

if (!ctsResponse.ok) {
logger.debug(`Failed to fetch CTS token: ${ctsResponse.statusText}`)

logger.error(
'There was an issue communicating with the CipherStash CTS API, the CipherStash session was not set. If the issue persists, please contact support.',
)

return NextResponse.next()
}

const cts_token = (await ctsResponse.json()) as CtsToken

// Setting cookies on the request and response using the `ResponseCookies` API
const response = NextResponse.next()
response.cookies.set({
name: CS_COOKIE_NAME,
value: JSON.stringify(cts_token),
expires: new Date(cts_token.expiry * 1000),
sameSite: 'lax',
path: '/',
})

response.cookies.get(CS_COOKIE_NAME)
return response
}
31 changes: 31 additions & 0 deletions packages/nextjs/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import { setCtsToken } from './cts'
import { logger } from '../../utils/logger'

export const CS_COOKIE_NAME = '__cipherstash_cts_session'
Expand All @@ -20,3 +23,31 @@ export const getCtsToken = async () => {
const cts_token = JSON.parse(cookieData) as CtsToken
return cts_token
}

export const resetCtsToken = () => {
const response = NextResponse.next()
response.cookies.delete(CS_COOKIE_NAME)
return response
}

export const jseqlMiddleware = async (oidcToken: string, req: NextRequest) => {
const ctsSession = req.cookies.has(CS_COOKIE_NAME)

if (oidcToken && !ctsSession) {
return await setCtsToken(oidcToken)
}

if (!oidcToken && ctsSession) {
logger.debug(
'The JWT token was undefined, so the CipherStash session was reset.',
)

return resetCtsToken()
}

logger.debug(
'The JWT token was undefined, so the CipherStash session was not set.',
)

return NextResponse.next()
}
Loading