|
| 1 | +import { randomBytes } from "node:crypto"; |
| 2 | +import { z } from "zod"; |
| 3 | +import { env } from "~/env.server"; |
| 4 | +import { createRedisClient, type RedisClient } from "~/redis.server"; |
| 5 | +import { commitSession, getUserSession } from "~/services/sessionStorage.server"; |
| 6 | +import { singleton } from "~/utils/singleton"; |
| 7 | + |
| 8 | +const STATE_TTL_SECONDS = 10 * 60; |
| 9 | +const CREATE_ATTEMPTS = 2; |
| 10 | +const KEY_PREFIX = "oauth:slack:state:"; |
| 11 | +const SLACK_OAUTH_SESSION_BINDING_KEY = "slack-oauth-session-binding"; |
| 12 | + |
| 13 | +const SlackOAuthStateSchema = z.object({ |
| 14 | + userId: z.string(), |
| 15 | + sessionBinding: z.string(), |
| 16 | + organizationId: z.string(), |
| 17 | + service: z.literal("slack"), |
| 18 | + redirectTo: z.string().regex(/^\/(?!\/)/), |
| 19 | +}); |
| 20 | + |
| 21 | +export type SlackOAuthState = z.infer<typeof SlackOAuthStateSchema>; |
| 22 | + |
| 23 | +type CreateSlackOAuthState = SlackOAuthState; |
| 24 | +type StartSlackOAuthState = Omit<CreateSlackOAuthState, "sessionBinding">; |
| 25 | +type ConsumeSlackOAuthState = Pick<SlackOAuthState, "userId" | "sessionBinding" | "service">; |
| 26 | + |
| 27 | +const consumeScript = ` |
| 28 | +local raw = redis.call("GET", KEYS[1]) |
| 29 | +if not raw then return nil end |
| 30 | +local decoded, state = pcall(cjson.decode, raw) |
| 31 | +if not decoded or type(state) ~= "table" then return nil end |
| 32 | +if state.userId ~= ARGV[1] or state.sessionBinding ~= ARGV[2] or state.service ~= ARGV[3] then |
| 33 | + return nil |
| 34 | +end |
| 35 | +redis.call("DEL", KEYS[1]) |
| 36 | +return raw |
| 37 | +`; |
| 38 | + |
| 39 | +export class SlackOAuthStateStore { |
| 40 | + constructor(private readonly redis: Pick<RedisClient, "set" | "eval">) {} |
| 41 | + |
| 42 | + async create(state: CreateSlackOAuthState): Promise<string> { |
| 43 | + const parsedState = SlackOAuthStateSchema.parse(state); |
| 44 | + |
| 45 | + for (let attempt = 0; attempt < CREATE_ATTEMPTS; attempt++) { |
| 46 | + const nonce = randomBytes(32).toString("base64url"); |
| 47 | + const created = await this.redis.set( |
| 48 | + this.#key(nonce), |
| 49 | + JSON.stringify(parsedState), |
| 50 | + "EX", |
| 51 | + STATE_TTL_SECONDS, |
| 52 | + "NX" |
| 53 | + ); |
| 54 | + if (created === "OK") return nonce; |
| 55 | + } |
| 56 | + |
| 57 | + throw new Error("Failed to create a unique Slack OAuth state"); |
| 58 | + } |
| 59 | + |
| 60 | + async consume( |
| 61 | + nonce: string, |
| 62 | + expected: ConsumeSlackOAuthState |
| 63 | + ): Promise<SlackOAuthState | undefined> { |
| 64 | + if (!/^[A-Za-z0-9_-]{43}$/.test(nonce)) return undefined; |
| 65 | + |
| 66 | + const raw = await this.redis.eval( |
| 67 | + consumeScript, |
| 68 | + 1, |
| 69 | + this.#key(nonce), |
| 70 | + expected.userId, |
| 71 | + expected.sessionBinding, |
| 72 | + expected.service |
| 73 | + ); |
| 74 | + if (typeof raw !== "string") return undefined; |
| 75 | + |
| 76 | + try { |
| 77 | + return SlackOAuthStateSchema.safeParse(JSON.parse(raw)).data; |
| 78 | + } catch { |
| 79 | + return undefined; |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + #key(nonce: string): string { |
| 84 | + return `${KEY_PREFIX}{${nonce}}`; |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +export async function createSlackOAuthStateForSession( |
| 89 | + request: Request, |
| 90 | + state: StartSlackOAuthState, |
| 91 | + stateStore: SlackOAuthStateStore = getSlackOAuthStateStore() |
| 92 | +): Promise<{ nonce: string; sessionCookie: string }> { |
| 93 | + const session = await getUserSession(request); |
| 94 | + const sessionBinding = randomBytes(32).toString("base64url"); |
| 95 | + const nonce = await stateStore.create({ ...state, sessionBinding }); |
| 96 | + session.set(SLACK_OAUTH_SESSION_BINDING_KEY, sessionBinding); |
| 97 | + |
| 98 | + return { nonce, sessionCookie: await commitSession(session) }; |
| 99 | +} |
| 100 | + |
| 101 | +export async function consumeSlackOAuthStateForSession( |
| 102 | + request: Request, |
| 103 | + nonce: string, |
| 104 | + userId: string, |
| 105 | + stateStore: SlackOAuthStateStore = getSlackOAuthStateStore() |
| 106 | +): Promise<SlackOAuthState | undefined> { |
| 107 | + const session = await getUserSession(request); |
| 108 | + const sessionBinding = session.get(SLACK_OAUTH_SESSION_BINDING_KEY); |
| 109 | + if (typeof sessionBinding !== "string") return undefined; |
| 110 | + |
| 111 | + return stateStore.consume(nonce, { userId, sessionBinding, service: "slack" }); |
| 112 | +} |
| 113 | + |
| 114 | +export async function clearSlackOAuthSessionBinding(request: Request): Promise<string> { |
| 115 | + const session = await getUserSession(request); |
| 116 | + session.unset(SLACK_OAUTH_SESSION_BINDING_KEY); |
| 117 | + return commitSession(session); |
| 118 | +} |
| 119 | + |
| 120 | +function getSlackOAuthStateStore(): SlackOAuthStateStore { |
| 121 | + if (!env.CACHE_REDIS_HOST) { |
| 122 | + throw new Error("Cache Redis is required for Slack OAuth state"); |
| 123 | + } |
| 124 | + |
| 125 | + return singleton( |
| 126 | + "slackOAuthStateStore", |
| 127 | + () => |
| 128 | + new SlackOAuthStateStore( |
| 129 | + createRedisClient("trigger:slack-oauth-state", { |
| 130 | + host: env.CACHE_REDIS_HOST, |
| 131 | + port: env.CACHE_REDIS_PORT, |
| 132 | + username: env.CACHE_REDIS_USERNAME, |
| 133 | + password: env.CACHE_REDIS_PASSWORD, |
| 134 | + tlsDisabled: env.CACHE_REDIS_TLS_DISABLED === "true", |
| 135 | + clusterMode: env.CACHE_REDIS_CLUSTER_MODE_ENABLED === "1", |
| 136 | + }) |
| 137 | + ) |
| 138 | + ); |
| 139 | +} |
0 commit comments