11import type { ClerkMiddlewareAuth } from '@clerk/nextjs/server'
22import type { NextRequest } from 'next/server'
33import { NextResponse } from 'next/server'
4- import { CS_COOKIE_NAME , type CtsToken } from '../index'
4+ import { CS_COOKIE_NAME , resetCtsToken } from '../index'
5+ import { setCtsToken } from '../cts'
56import { logger } from '../../../utils/logger'
67
78export const jseqlClerkMiddleware = async (
@@ -22,65 +23,15 @@ export const jseqlClerkMiddleware = async (
2223 return NextResponse . next ( )
2324 }
2425
25- const workspaceId = process . env . CS_WORKSPACE_ID
26-
27- if ( ! workspaceId ) {
28- logger . error (
29- 'The "CS_WORKSPACE_ID" environment variable is not set, and is required by jseqlClerkMiddleware. No CipherStash session will be set.' ,
30- )
31-
32- return NextResponse . next ( )
33- }
34-
35- const ctsEndoint =
36- process . env . CS_CTS_ENDPOINT ||
37- 'https://ap-southeast-2.aws.auth.viturhosted.net'
38-
39- const ctsResponse = await fetch ( `${ ctsEndoint } /api/authorize` , {
40- method : 'POST' ,
41- headers : {
42- 'Content-Type' : 'application/json' ,
43- } ,
44- body : JSON . stringify ( {
45- workspaceId,
46- oidcToken,
47- } ) ,
48- } )
49-
50- if ( ! ctsResponse . ok ) {
51- logger . debug ( `Failed to fetch CTS token: ${ ctsResponse . statusText } ` )
52-
53- logger . error (
54- 'There was an issue communicating with the CipherStash CTS API, the CipherStash session was not set. If the issue persists, please contact support.' ,
55- )
56-
57- return NextResponse . next ( )
58- }
59-
60- const cts_token = ( await ctsResponse . json ( ) ) as CtsToken
61-
62- // Setting cookies on the request and response using the `ResponseCookies` API
63- const response = NextResponse . next ( )
64- response . cookies . set ( {
65- name : CS_COOKIE_NAME ,
66- value : JSON . stringify ( cts_token ) ,
67- expires : new Date ( cts_token . expiry * 1000 ) ,
68- sameSite : 'lax' ,
69- path : '/' ,
70- } )
71-
72- response . cookies . get ( CS_COOKIE_NAME )
73- return response
26+ return await setCtsToken ( oidcToken )
7427 }
7528
7629 if ( ! userId && ctsSession ) {
7730 logger . debug (
7831 'No Clerk token found in the request, so the CipherStash session was reset.' ,
7932 )
8033
81- const response = NextResponse . next ( )
82- response . cookies . delete ( CS_COOKIE_NAME )
83- return response
34+ return resetCtsToken ( )
8435 }
8536
8637 logger . debug (
0 commit comments