|
1 | 1 | import { createCookieSessionStorage, type Session } from "@remix-run/node"; |
| 2 | +import { SignJWT, jwtVerify, errors } from "jose"; |
| 3 | +import { singleton } from "~/utils/singleton"; |
| 4 | +import { createRedisClient, type RedisClient } from "~/redis.server"; |
2 | 5 | import { env } from "~/env.server"; |
| 6 | +import { logger } from "~/services/logger.server"; |
3 | 7 |
|
4 | 8 | export const impersonationSessionStorage = createCookieSessionStorage({ |
5 | 9 | cookie: { |
@@ -42,3 +46,89 @@ export async function clearImpersonationId(request: Request) { |
42 | 46 |
|
43 | 47 | return session; |
44 | 48 | } |
| 49 | + |
| 50 | +// Impersonation token utilities for CSRF protection |
| 51 | +const IMPERSONATION_TOKEN_EXPIRY_SECONDS = 5 * 60; // 5 minutes |
| 52 | + |
| 53 | +function getImpersonationTokenSecret(): Uint8Array { |
| 54 | + return new TextEncoder().encode(env.SESSION_SECRET); |
| 55 | +} |
| 56 | + |
| 57 | +function getImpersonationTokenRedisClient(): RedisClient { |
| 58 | + return singleton( |
| 59 | + "impersonationTokenRedis", |
| 60 | + () => |
| 61 | + createRedisClient("impersonation:token", { |
| 62 | + host: env.CACHE_REDIS_HOST, |
| 63 | + port: env.CACHE_REDIS_PORT, |
| 64 | + username: env.CACHE_REDIS_USERNAME, |
| 65 | + password: env.CACHE_REDIS_PASSWORD, |
| 66 | + tlsDisabled: env.CACHE_REDIS_TLS_DISABLED === "true", |
| 67 | + clusterMode: env.CACHE_REDIS_CLUSTER_MODE_ENABLED === "1", |
| 68 | + keyPrefix: "impersonation:token:", |
| 69 | + }) |
| 70 | + ); |
| 71 | +} |
| 72 | + |
| 73 | +/** |
| 74 | + * Generate a signed one-time impersonation token for a user |
| 75 | + */ |
| 76 | +export async function generateImpersonationToken(userId: string): Promise<string> { |
| 77 | + const secret = getImpersonationTokenSecret(); |
| 78 | + const now = Math.floor(Date.now() / 1000); |
| 79 | + |
| 80 | + const token = await new SignJWT({ userId }) |
| 81 | + .setProtectedHeader({ alg: "HS256" }) |
| 82 | + .setIssuedAt(now) |
| 83 | + .setExpirationTime(now + IMPERSONATION_TOKEN_EXPIRY_SECONDS) |
| 84 | + .setIssuer("https://trigger.dev") |
| 85 | + .setAudience("https://trigger.dev/admin") |
| 86 | + .sign(secret); |
| 87 | + |
| 88 | + return token; |
| 89 | +} |
| 90 | + |
| 91 | +/** |
| 92 | + * Validate and consume an impersonation token (prevents replay attacks) |
| 93 | + */ |
| 94 | +export async function validateAndConsumeImpersonationToken( |
| 95 | + token: string |
| 96 | +): Promise<string | undefined> { |
| 97 | + try { |
| 98 | + const secret = getImpersonationTokenSecret(); |
| 99 | + |
| 100 | + // Verify the token signature and expiration |
| 101 | + const { payload } = await jwtVerify(token, secret, { |
| 102 | + issuer: "https://trigger.dev", |
| 103 | + audience: "https://trigger.dev/admin", |
| 104 | + }); |
| 105 | + |
| 106 | + const userId = payload.userId as string | undefined; |
| 107 | + if (!userId || typeof userId !== "string") { |
| 108 | + return undefined; |
| 109 | + } |
| 110 | + |
| 111 | + // Check if token has already been used (prevent replay attacks) |
| 112 | + const redis = getImpersonationTokenRedisClient(); |
| 113 | + const tokenKey = token; |
| 114 | + |
| 115 | + // Try to set the key with NX (only if not exists) and expiration |
| 116 | + // This atomically marks the token as used |
| 117 | + const result = await redis.set(tokenKey, "1", "EX", IMPERSONATION_TOKEN_EXPIRY_SECONDS, "NX"); |
| 118 | + |
| 119 | + if (result !== "OK") { |
| 120 | + // Token was already used |
| 121 | + return undefined; |
| 122 | + } |
| 123 | + |
| 124 | + return userId; |
| 125 | + } catch (error) { |
| 126 | + if (error instanceof errors.JWTExpired || error instanceof errors.JWTInvalid) { |
| 127 | + return undefined; |
| 128 | + } |
| 129 | + logger.error("Error validating impersonation token", { |
| 130 | + error: error instanceof Error ? error.message : String(error), |
| 131 | + }); |
| 132 | + return undefined; |
| 133 | + } |
| 134 | +} |
0 commit comments