|
| 1 | +import { datePivot } from '@/lib/time' |
| 2 | +import * as cookie from 'cookie' |
| 3 | +import { NodeNextRequest } from 'next/dist/server/base-http/node' |
| 4 | +import { encode as encodeJWT, decode as decodeJWT } from 'next-auth/jwt' |
| 5 | + |
| 6 | +const b64Encode = obj => Buffer.from(JSON.stringify(obj)).toString('base64') |
| 7 | +const b64Decode = s => JSON.parse(Buffer.from(s, 'base64')) |
| 8 | + |
| 9 | +const userJwtRegexp = /^multi_auth\.\d+$/ |
| 10 | + |
| 11 | +const HTTPS = process.env.NODE_ENV === 'production' |
| 12 | +const SESSION_COOKIE_NAME = HTTPS ? '__Secure-next-auth.session-token' : 'next-auth.session-token' |
| 13 | + |
| 14 | +const cookieOptions = (args) => ({ |
| 15 | + path: '/', |
| 16 | + secure: process.env.NODE_ENV === 'production', |
| 17 | + // httpOnly cookies by default |
| 18 | + httpOnly: true, |
| 19 | + sameSite: 'lax', |
| 20 | + // default expiration for next-auth JWTs is in 30 days |
| 21 | + expires: datePivot(new Date(), { days: 30 }), |
| 22 | + ...args |
| 23 | +}) |
| 24 | + |
| 25 | +export function setMultiAuthCookies (req, res, { id, jwt, name, photoId }) { |
| 26 | + const httpOnlyOptions = cookieOptions() |
| 27 | + const jsOptions = { ...httpOnlyOptions, httpOnly: false } |
| 28 | + |
| 29 | + // add JWT to **httpOnly** cookie |
| 30 | + res.appendHeader('Set-Cookie', cookie.serialize(`multi_auth.${id}`, jwt, httpOnlyOptions)) |
| 31 | + |
| 32 | + // switch to user we just added |
| 33 | + res.appendHeader('Set-Cookie', cookie.serialize('multi_auth.user-id', id, jsOptions)) |
| 34 | + |
| 35 | + let newMultiAuth = [{ id, name, photoId }] |
| 36 | + if (req.cookies.multi_auth) { |
| 37 | + const oldMultiAuth = b64Decode(req.cookies.multi_auth) |
| 38 | + // make sure we don't add duplicates |
| 39 | + if (oldMultiAuth.some(({ id: id_ }) => id_ === id)) return |
| 40 | + newMultiAuth = [...oldMultiAuth, ...newMultiAuth] |
| 41 | + } |
| 42 | + res.appendHeader('Set-Cookie', cookie.serialize('multi_auth', b64Encode(newMultiAuth), jsOptions)) |
| 43 | +} |
| 44 | + |
| 45 | +export function switchSessionCookie (request) { |
| 46 | + // switch next-auth session cookie with multi_auth cookie if cookie pointer present |
| 47 | + |
| 48 | + // is there a cookie pointer? |
| 49 | + const cookiePointerName = 'multi_auth.user-id' |
| 50 | + const hasCookiePointer = !!request.cookies[cookiePointerName] |
| 51 | + |
| 52 | + // is there a session? |
| 53 | + const hasSession = !!request.cookies[SESSION_COOKIE_NAME] |
| 54 | + |
| 55 | + if (!hasCookiePointer || !hasSession) { |
| 56 | + // no session or no cookie pointer. do nothing. |
| 57 | + return request |
| 58 | + } |
| 59 | + |
| 60 | + const userId = request.cookies[cookiePointerName] |
| 61 | + if (userId === 'anonymous') { |
| 62 | + // user switched to anon. only delete session cookie. |
| 63 | + delete request.cookies[SESSION_COOKIE_NAME] |
| 64 | + return request |
| 65 | + } |
| 66 | + |
| 67 | + const userJWT = request.cookies[`multi_auth.${userId}`] |
| 68 | + if (!userJWT) { |
| 69 | + // no JWT for account switching found |
| 70 | + return request |
| 71 | + } |
| 72 | + |
| 73 | + if (userJWT) { |
| 74 | + // use JWT found in cookie pointed to by cookie pointer |
| 75 | + request.cookies[SESSION_COOKIE_NAME] = userJWT |
| 76 | + return request |
| 77 | + } |
| 78 | + |
| 79 | + return request |
| 80 | +} |
| 81 | + |
| 82 | +export function checkMultiAuthCookies (req, res) { |
| 83 | + if (!req.cookies.multi_auth || !req.cookies['multi_auth.user-id']) { |
| 84 | + return false |
| 85 | + } |
| 86 | + |
| 87 | + const accounts = b64Decode(req.cookies.multi_auth) |
| 88 | + for (const account of accounts) { |
| 89 | + if (!req.cookies[`multi_auth.${account.id}`]) { |
| 90 | + return false |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + return true |
| 95 | +} |
| 96 | + |
| 97 | +export function resetMultiAuthCookies (req, res) { |
| 98 | + const httpOnlyOptions = cookieOptions({ expires: 0, maxAge: 0 }) |
| 99 | + const jsOptions = { ...httpOnlyOptions, httpOnly: false } |
| 100 | + |
| 101 | + if ('multi_auth' in req.cookies) res.appendHeader('Set-Cookie', cookie.serialize('multi_auth', '', jsOptions)) |
| 102 | + if ('multi_auth.user-id' in req.cookies) res.appendHeader('Set-Cookie', cookie.serialize('multi_auth.user-id', '', jsOptions)) |
| 103 | + |
| 104 | + for (const key of Object.keys(req.cookies)) { |
| 105 | + // reset all user JWTs |
| 106 | + if (userJwtRegexp.test(key)) { |
| 107 | + res.appendHeader('Set-Cookie', cookie.serialize(key, '', httpOnlyOptions)) |
| 108 | + } |
| 109 | + } |
| 110 | +} |
| 111 | + |
| 112 | +export async function refreshMultiAuthCookies (req, res) { |
| 113 | + const httpOnlyOptions = cookieOptions() |
| 114 | + const jsOptions = { ...httpOnlyOptions, httpOnly: false } |
| 115 | + |
| 116 | + const refreshCookie = (name) => { |
| 117 | + res.appendHeader('Set-Cookie', cookie.serialize(name, req.cookies[name], jsOptions)) |
| 118 | + } |
| 119 | + |
| 120 | + const refreshToken = async (token) => { |
| 121 | + const secret = process.env.NEXTAUTH_SECRET |
| 122 | + return await encodeJWT({ |
| 123 | + token: await decodeJWT({ token, secret }), |
| 124 | + secret |
| 125 | + }) |
| 126 | + } |
| 127 | + |
| 128 | + const isAnon = req.cookies['multi_auth.user-id'] === 'anonymous' |
| 129 | + |
| 130 | + for (const [key, value] of Object.entries(req.cookies)) { |
| 131 | + // only refresh session cookie manually if we switched to anon since else it's already handled by next-auth |
| 132 | + if (key === SESSION_COOKIE_NAME && !isAnon) continue |
| 133 | + |
| 134 | + if (!key.startsWith('multi_auth') && key !== SESSION_COOKIE_NAME) continue |
| 135 | + |
| 136 | + if (userJwtRegexp.test(key) || key === SESSION_COOKIE_NAME) { |
| 137 | + const oldToken = value |
| 138 | + const newToken = await refreshToken(oldToken) |
| 139 | + res.appendHeader('Set-Cookie', cookie.serialize(key, newToken, httpOnlyOptions)) |
| 140 | + continue |
| 141 | + } |
| 142 | + |
| 143 | + refreshCookie(key) |
| 144 | + } |
| 145 | +} |
| 146 | + |
| 147 | +export async function multiAuthMiddleware (req, res) { |
| 148 | + if (!req.cookies) { |
| 149 | + // required to properly access parsed cookies via req.cookies and not unparsed via req.headers.cookie |
| 150 | + req = new NodeNextRequest(req) |
| 151 | + } |
| 152 | + |
| 153 | + const ok = checkMultiAuthCookies(req, res) |
| 154 | + if (!ok) { |
| 155 | + resetMultiAuthCookies(req, res) |
| 156 | + return switchSessionCookie(req) |
| 157 | + } |
| 158 | + |
| 159 | + await refreshMultiAuthCookies(req, res) |
| 160 | + return switchSessionCookie(req) |
| 161 | +} |
0 commit comments