| 1 | import { ssoClient } from "@g1t/contracts"; |
| 2 | |
| 3 | import { afterSso, errorCookie } from "../app/lib/sso"; |
| 4 | |
| 5 | /** |
| 6 | * A workspace's identity provider posting its SAML response |
| 7 | * (`POST /auth/sso/<slug>/saml`). It comes from the provider's site, so it |
| 8 | * is answered here, before React Router, which refuses cross-site form |
| 9 | * posts; and it carries no session cookie (SameSite=Lax), so identity |
| 10 | * finds the session from the request g1t sent, which the response must |
| 11 | * answer. Either way the browser is sent on with a 303: on to where it was |
| 12 | * going, or back to the page that says what went wrong. |
| 13 | */ |
| 14 | export async function receiveSaml(env: Env, request: Request, slug: string): Promise<Response> { |
| 15 | const back = (message: string) => |
| 16 | new Response(null, { |
| 17 | status: 303, |
| 18 | headers: { location: `/auth/sso/${slug}/saml`, "set-cookie": errorCookie(message), "cache-control": "no-store" }, |
| 19 | }); |
| 20 | let samlResponse = ""; |
| 21 | try { |
| 22 | const form = await request.formData(); |
| 23 | samlResponse = String(form.get("SAMLResponse") ?? ""); |
| 24 | } catch { |
| 25 | return back("The identity provider's response could not be read."); |
| 26 | } |
| 27 | if (!samlResponse) return back("The identity provider sent no SAML response."); |
| 28 | const finished = await ssoClient(env.IDENTITY) |
| 29 | .saml(slug, samlResponse) |
| 30 | .catch(() => null); |
| 31 | if (!finished) return back("g1t could not check the identity provider's response just now. Try again in a minute."); |
| 32 | if (!finished.ok) return back(finished.error.message); |
| 33 | return new Response(null, { status: 303, headers: { location: afterSso(finished.value), "cache-control": "no-store" } }); |
| 34 | } |