Skip to content

Commit

Permalink
fix eslint stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
AssafKr committed Aug 1, 2023
1 parent cd38969 commit bbfa410
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 40 deletions.
6 changes: 3 additions & 3 deletions tunnel-server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { appLoggerFromEnv } from './src/logging'
import { tunnelsGauge, runMetricsServer } from './src/metrics'
import { numberFromEnv, requiredEnv } from './src/env'
import { replaceHostname } from './src/url'
import { sessionManager } from './src/seesion'
import { session } from './src/seesion'
import { claimsSchema } from './src/auth'

const __dirname = url.fileURLToPath(new URL('.', import.meta.url))
Expand All @@ -37,10 +37,10 @@ const BASE_URL = (() => {
})()

const envStore = inMemoryPreviewEnvStore()
const appSessionManager = sessionManager({ domain: BASE_URL.hostname, schema: claimsSchema, keys: process.env.COOKIE_SECRETS?.split(' ') })
const appSessionManager = session({ domain: BASE_URL.hostname, schema: claimsSchema, keys: process.env.COOKIE_SECRETS?.split(' ') })
const loginUrl = new URL('/login', replaceHostname(BASE_URL, `auth.${BASE_URL.hostname}`)).toString()
const app = createApp({
sessionManager: appSessionManager,
session: appSessionManager,
envStore,
baseUrl: BASE_URL,
isProxyRequest: isProxyRequest(BASE_URL.hostname),
Expand Down
6 changes: 3 additions & 3 deletions tunnel-server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@ import http from 'http'
import internal from 'stream'
import { Logger } from 'pino'
import { match } from 'ts-pattern'
import { SessionManager } from './seesion'
import { Session } from './seesion'
import { Claims, JwtAuthenticator, authenticator, getIssuerToKeyDataFromEnv, unauthorized } from './auth'
import { PreviewEnvStore } from './preview-env'
import { replaceHostname } from './url'

export const app = ({ isProxyRequest, proxyHandlers, sessionManager, baseUrl, envStore, logger }: {
export const app = ({ isProxyRequest, proxyHandlers, session: sessionManager, baseUrl, envStore, logger }: {
isProxyRequest: (req: http.IncomingMessage) => boolean
logger: Logger
baseUrl: URL
sessionManager: SessionManager<Claims>
session: Session<Claims>
envStore: PreviewEnvStore
proxyHandlers: {
wsHandler: (req: http.IncomingMessage, socket: internal.Duplex, head: Buffer) => void
Expand Down
22 changes: 14 additions & 8 deletions tunnel-server/src/preview-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,27 @@ export type PreviewEnv = {

export type PreviewEnvStore = {
get: (key: string) => Promise<PreviewEnv | undefined>
getByPkThumbprint: (pkThumbprint: string) => Promise<PreviewEnv[] | undefined>
set: (key: string, env: PreviewEnv) => Promise<void>
has: (key: string) => Promise<boolean>
delete: (key: string) => Promise<boolean>
getAll: () => Promise<{[key: string]: PreviewEnv}>
}

export const inMemoryPreviewEnvStore = (initial?: Record<string, PreviewEnv>): PreviewEnvStore => {
const map = new Map<string, PreviewEnv>(Object.entries(initial ?? {}))
export const inMemoryPreviewEnvStore = (): PreviewEnvStore => {
const tunnelNameToEnv = new Map<string, PreviewEnv>()
const pkThumbprintToEnv = new Map<string, PreviewEnv[]>()

return {
get: async key => map.get(key),
get: async key => tunnelNameToEnv.get(key),
getByPkThumbprint: async pkThumbprint => pkThumbprintToEnv.get(pkThumbprint),
set: async (key, value) => {
map.set(key, value)
tunnelNameToEnv.set(key, value)
pkThumbprintToEnv.set(
value.publicKeyThumbprint,
[...pkThumbprintToEnv.get(value.publicKeyThumbprint) ?? [], value]
)
},
has: async key => map.has(key),
delete: async key => map.delete(key),
getAll: async () => Object.fromEntries< PreviewEnv>(map),
has: async key => tunnelNameToEnv.has(key),
delete: async key => tunnelNameToEnv.delete(key),
}
}
8 changes: 4 additions & 4 deletions tunnel-server/src/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import internal from 'stream'
import type { Logger } from 'pino'
import { PreviewEnvStore } from './preview-env'
import { requestsCounter } from './metrics'
import { Claims, authenticator, JwtAuthenticator, unauthorized, envToIssuerToKeyData } from './auth'
import { SessionManager } from './seesion'
import { Claims, authenticator, JwtAuthenticator, unauthorized, getIssuerToKeyDataFromEnv } from './auth'
import { Session } from './seesion'

export const isProxyRequest = (
hostname: string,
Expand Down Expand Up @@ -44,7 +44,7 @@ export function proxyHandlers({
sessionManager,
logger,
}: {
sessionManager: SessionManager<Claims>
sessionManager: Session<Claims>
envStore: PreviewEnvStore
loginUrl: string
logger: Logger
Expand Down Expand Up @@ -74,7 +74,7 @@ export function proxyHandlers({
const session = sessionManager(req, res, env.publicKeyThumbprint)
if (env.access === 'private') {
if (!session.user) {
const authenticate = authenticator([JwtAuthenticator(envToIssuerToKeyData(env))])
const authenticate = authenticator([JwtAuthenticator(getIssuerToKeyDataFromEnv(env))])
try {
const authResult = await authenticate(req)
if (!authResult.isAuthenticated) {
Expand Down
44 changes: 22 additions & 22 deletions tunnel-server/src/seesion.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
import { IncomingMessage, ServerResponse } from 'http'
import Cookies from 'cookies'
import { randomBytes } from 'crypto'
import * as z from "zod"
import * as z from 'zod'

// for testing, for production workload use the env var COOKIE_SECRETS
function generateSecret(){
function generateSecret() {
return randomBytes(32)
.toString('base64')
.slice(0, 32)
}

export function sessionManager<T>(opts: {domain: string, schema: z.ZodSchema<T>, keys?: string[] }){
const keys = opts.keys ?? [generateSecret()]
return function session(req: IncomingMessage, res: ServerResponse<IncomingMessage>, thumbprint: string){
const cookies = new Cookies(req, res, {
secure: true,
keys
})
const data = cookies.get(`preevy-${thumbprint}`, {signed: true});
let currentUser = data ? opts.schema.parse(JSON.parse(data)) : undefined
const session = {
get user(){ return currentUser},
set(user: T){
currentUser = user
},
save: ()=> {
cookies.set(`preevy-${thumbprint}`, JSON.stringify(currentUser), {domain: opts.domain, signed: true})
}
}
return session
export function session<T>(opts: {domain: string; schema: z.ZodSchema<T>; keys?: string[] }) {
const keys = opts.keys ?? [generateSecret()]
return function getSession(req: IncomingMessage, res: ServerResponse<IncomingMessage>, thumbprint: string) {
const cookies = new Cookies(req, res, {
secure: true,
keys,
})
const data = cookies.get(`preevy-${thumbprint}`, { signed: true })
let currentUser = data ? opts.schema.parse(JSON.parse(data)) : undefined

return {
get user() { return currentUser },
set(user: T) {
currentUser = user
},
save: () => {
cookies.set(`preevy-${thumbprint}`, JSON.stringify(currentUser), { domain: opts.domain, signed: true })
},
}
}
}

export type SessionManager<T> = ReturnType<typeof sessionManager<T>>
export type Session<T> = ReturnType<typeof session<T>>

0 comments on commit bbfa410

Please sign in to comment.