|
| 1 | +import { randomBytes } from "node:crypto" |
| 2 | +import express from "express" |
| 3 | +import { and, eq, gt, isNull } from "../db/drizzle.js" |
| 4 | +import { db } from "../db/index.js" |
| 5 | +import { AuthSessionTable, AuthUserTable, DesktopHandoffGrantTable } from "../db/schema.js" |
| 6 | +import { normalizeDenTypeId } from "../db/typeid.js" |
| 7 | +import { asyncRoute } from "./errors.js" |
| 8 | +import { getRequestSession } from "./session.js" |
| 9 | +import { z } from "zod" |
| 10 | + |
| 11 | +const desktopAuthRouter = express.Router() |
| 12 | + |
| 13 | +const createGrantSchema = z.object({ |
| 14 | + next: z.string().trim().max(128).optional(), |
| 15 | + desktopScheme: z.string().trim().max(32).optional(), |
| 16 | +}) |
| 17 | + |
| 18 | +const exchangeGrantSchema = z.object({ |
| 19 | + grant: z.string().trim().min(12).max(128), |
| 20 | +}) |
| 21 | + |
| 22 | +function buildOpenworkDeepLink(input: { |
| 23 | + scheme?: string | null |
| 24 | + grant: string |
| 25 | + denBaseUrl: string |
| 26 | +}) { |
| 27 | + const requestedScheme = input.scheme?.trim() || "openwork" |
| 28 | + const scheme = /^[a-z][a-z0-9+.-]*$/i.test(requestedScheme) |
| 29 | + ? requestedScheme |
| 30 | + : "openwork" |
| 31 | + const url = new URL(`${scheme}://den-auth`) |
| 32 | + url.searchParams.set("grant", input.grant) |
| 33 | + url.searchParams.set("denBaseUrl", input.denBaseUrl) |
| 34 | + return url.toString() |
| 35 | +} |
| 36 | + |
| 37 | +desktopAuthRouter.post( |
| 38 | + "/desktop-handoff", |
| 39 | + asyncRoute(async (req, res) => { |
| 40 | + const session = await getRequestSession(req) |
| 41 | + if (!session?.user?.id || !session.session?.token) { |
| 42 | + res.status(401).json({ error: "unauthorized" }) |
| 43 | + return |
| 44 | + } |
| 45 | + |
| 46 | + const parsed = createGrantSchema.safeParse(req.body ?? {}) |
| 47 | + if (!parsed.success) { |
| 48 | + res.status(400).json({ error: "invalid_request", details: parsed.error.flatten() }) |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + const grant = randomBytes(24).toString("base64url") |
| 53 | + const expiresAt = new Date(Date.now() + 5 * 60 * 1000) |
| 54 | + await db.insert(DesktopHandoffGrantTable).values({ |
| 55 | + id: grant, |
| 56 | + user_id: normalizeDenTypeId("user", session.user.id), |
| 57 | + session_token: session.session.token, |
| 58 | + expires_at: expiresAt, |
| 59 | + consumed_at: null, |
| 60 | + }) |
| 61 | + |
| 62 | + const forwardedProto = |
| 63 | + typeof req.headers["x-forwarded-proto"] === "string" |
| 64 | + ? req.headers["x-forwarded-proto"] |
| 65 | + : null |
| 66 | + const host = typeof req.headers.host === "string" ? req.headers.host : null |
| 67 | + const protocol = forwardedProto ?? req.protocol ?? "https" |
| 68 | + const denBaseUrl = host ? `${protocol}://${host}` : "https://app.openworklabs.com" |
| 69 | + |
| 70 | + res.json({ |
| 71 | + grant, |
| 72 | + expiresAt: expiresAt.toISOString(), |
| 73 | + openworkUrl: buildOpenworkDeepLink({ |
| 74 | + scheme: parsed.data.desktopScheme || "openwork", |
| 75 | + grant, |
| 76 | + denBaseUrl, |
| 77 | + }), |
| 78 | + }) |
| 79 | + }), |
| 80 | +) |
| 81 | + |
| 82 | +desktopAuthRouter.post( |
| 83 | + "/desktop-handoff/exchange", |
| 84 | + asyncRoute(async (req, res) => { |
| 85 | + const parsed = exchangeGrantSchema.safeParse(req.body ?? {}) |
| 86 | + if (!parsed.success) { |
| 87 | + res.status(400).json({ error: "invalid_request", details: parsed.error.flatten() }) |
| 88 | + return |
| 89 | + } |
| 90 | + |
| 91 | + const now = new Date() |
| 92 | + const rows = await db |
| 93 | + .select({ |
| 94 | + grant: DesktopHandoffGrantTable, |
| 95 | + session: AuthSessionTable, |
| 96 | + user: AuthUserTable, |
| 97 | + }) |
| 98 | + .from(DesktopHandoffGrantTable) |
| 99 | + .innerJoin( |
| 100 | + AuthSessionTable, |
| 101 | + eq(DesktopHandoffGrantTable.session_token, AuthSessionTable.token), |
| 102 | + ) |
| 103 | + .innerJoin( |
| 104 | + AuthUserTable, |
| 105 | + eq(DesktopHandoffGrantTable.user_id, AuthUserTable.id), |
| 106 | + ) |
| 107 | + .where( |
| 108 | + and( |
| 109 | + eq(DesktopHandoffGrantTable.id, parsed.data.grant), |
| 110 | + isNull(DesktopHandoffGrantTable.consumed_at), |
| 111 | + gt(DesktopHandoffGrantTable.expires_at, now), |
| 112 | + gt(AuthSessionTable.expiresAt, now), |
| 113 | + ), |
| 114 | + ) |
| 115 | + .limit(1) |
| 116 | + |
| 117 | + const row = rows[0] |
| 118 | + if (!row) { |
| 119 | + res.status(404).json({ |
| 120 | + error: "grant_not_found", |
| 121 | + message: "This desktop sign-in link is missing, expired, or already used.", |
| 122 | + }) |
| 123 | + return |
| 124 | + } |
| 125 | + |
| 126 | + await db |
| 127 | + .update(DesktopHandoffGrantTable) |
| 128 | + .set({ consumed_at: now }) |
| 129 | + .where( |
| 130 | + and( |
| 131 | + eq(DesktopHandoffGrantTable.id, parsed.data.grant), |
| 132 | + isNull(DesktopHandoffGrantTable.consumed_at), |
| 133 | + ), |
| 134 | + ) |
| 135 | + |
| 136 | + res.json({ |
| 137 | + token: row.session.token, |
| 138 | + user: { |
| 139 | + id: row.user.id, |
| 140 | + email: row.user.email, |
| 141 | + name: row.user.name, |
| 142 | + }, |
| 143 | + }) |
| 144 | + }), |
| 145 | +) |
| 146 | + |
| 147 | +export { desktopAuthRouter } |
0 commit comments