demos for spacedust

put the cookie handling in one place

and put `partitioned` on the cors cookies

+25 -17
+25 -17
server/index.js
··· 146 146 req.on('error', err => reject(err)); 147 147 }); 148 148 149 + const COOKIE_BASE = { httpOnly: true, secure: true, partitioned: true, sameSite: 'None' }; 150 + const setDidCookie = (res, did, appSecret) => res.setHeader('Set-Cookie', cookie.serialize( 151 + 'verified-did', 152 + cookieSig.sign(did, appSecret), 153 + { ...COOKIE_BASE, maxAge: 90 * 86_400 }, 154 + )); 155 + const clearDidCookie = res => res.setHeader('Set-Cookie', cookie.serialize( 156 + 'verified-did', 157 + '', 158 + { ...COOKIE_BASE, expires: new Date(0) }, 159 + )); 160 + const getDidCookie = (req, res, appSecret) => { 161 + const cookies = cookie.parse(req.headers.cookie ?? ''); 162 + const untrusted = cookies['verified-did'] ?? ''; 163 + const did = cookieSig.unsign(untrusted, appSecret); 164 + if (!did) clearDidCookie(res); 165 + return did; 166 + }; 167 + 149 168 const handleFile = (fname, ftype) => async (req, res, replace = {}) => { 150 169 let content 151 170 try { ··· 175 194 const verified = await jose.jwtVerify(token, jwks); 176 195 did = verified.payload.sub; 177 196 } catch (e) { 178 - res.setHeader('Set-Cookie', cookie.serialize('verified-did', '', { expires: new Date(0) })); 179 - return res.writeHead(400).end(JSON.stringify({ reason: 'verification failed' })); 197 + return clearDidCookie(res).writeHead(400).end(JSON.stringify({ reason: 'verification failed' })); 180 198 } 181 - const signed = cookieSig.sign(did, appSecret); 182 - res.setHeader('Set-Cookie', cookie.serialize('verified-did', signed, { 183 - httpOnly: true, 184 - secure: true, 185 - maxAge: 90 * 86_400, 186 - })) 199 + setDidCookie(res, did, appSecret); 187 200 return res.writeHead(200).end('okayyyy'); 188 201 }; 189 202 190 203 const handleSubscribe = async (req, res, appSecret) => { 191 - const rawCookies = req.headers.cookie; 192 - const cookies = cookie.parse(req.headers.cookie ?? ''); 193 - const untrusted = cookies['verified-did'] ?? ''; 194 - const did = cookieSig.unsign(untrusted, appSecret); 195 - if (!did) { 196 - res.setHeader('Set-Cookie', cookie.serialize('verified-did', '', { expires: new Date(0) })); 197 - return res.writeHead(400).end(JSON.stringify({ reason: 'failed to verify cookie signature' })); 198 - } 204 + let did = getDidCookie(req, res, appSecret); 205 + if (!did) return res.writeHead(400).end(JSON.stringify({ reason: 'failed to verify cookie signature' })); 206 + 199 207 const body = await getRequesBody(req); 200 208 const { sub } = JSON.parse(body); 201 - addSub('did:plc:z72i7hdynmk6r22z27h6tvur', sub); // DELETEME @bsky.app (DEBUG) 209 + // addSub('did:plc:z72i7hdynmk6r22z27h6tvur', sub); // DELETEME @bsky.app (DEBUG) 202 210 addSub(did, sub); 203 211 res.setHeader('Content-Type', 'application/json'); 204 212 res.writeHead(201);