|
| 1 | +/** |
| 2 | + * Cookie-based auth helper for the unified auth gate. |
| 3 | + * |
| 4 | + * The deploy is protected by two credential types: |
| 5 | + * |
| 6 | + * 1. `collab_sid` cookie (set by the OAuth flow). Identifies a GitHub |
| 7 | + * org member. Scoped — see `cookieAuthorizesRequest` below. |
| 8 | + * 2. Basic auth (`OPENCODE_SERVER_PASSWORD`). Identifies the server |
| 9 | + * itself. Used for internal self-fetches via `nativeFetch`. |
| 10 | + * |
| 11 | + * `cookieAuthorizesRequest` is the 3-rule decision function called from |
| 12 | + * both auth middlewares (the HttpApi-layer `validateCredential` and the |
| 13 | + * router-layer `validateRawCredential`) and from the `/preview/<port>/*` |
| 14 | + * proxy gate. The middleware checks `isPublicUIPath` first; the cookie |
| 15 | + * helper is consulted next; basic auth is the fallthrough. |
| 16 | + * |
| 17 | + * See CONTEXT.md → "Cookie Authorization Scope" for the design. |
| 18 | + * See docs/adr/0001 (preview proxy auth) for the trigger. |
| 19 | + */ |
| 20 | + |
| 21 | +import { Database } from "@/storage/db" |
| 22 | +import { eq, and, isNull } from "drizzle-orm" |
| 23 | +import { join } from "path" |
| 24 | +import { |
| 25 | + CollabAuthSessionTable, |
| 26 | + CollabSessionTable, |
| 27 | + CollabParticipantTable, |
| 28 | +} from "./schema.sql" |
| 29 | + |
| 30 | +/** |
| 31 | + * Parse a `Cookie:` header into a key→value map. Single source of truth so |
| 32 | + * the WebSocket upgrade path doesn't have to re-implement it. |
| 33 | + */ |
| 34 | +export function parseCookies(header: string): Record<string, string> { |
| 35 | + const out: Record<string, string> = {} |
| 36 | + for (const part of header.split(";")) { |
| 37 | + const [k, ...v] = part.trim().split("=") |
| 38 | + if (k) out[k.trim()] = decodeURIComponent(v.join("=")) |
| 39 | + } |
| 40 | + return out |
| 41 | +} |
| 42 | + |
| 43 | +/** Container workspace root. Mirrors collab/workspace.ts. */ |
| 44 | +function workspaceRoot(): string { |
| 45 | + return process.env["COLLAB_WORKSPACE_ROOT"] ?? "/var/opencode/workspaces" |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Resolve a workspace-addressing string (header `x-opencode-directory` or |
| 50 | + * query `directory=` / `location[directory]=`) to a collab session id. |
| 51 | + * |
| 52 | + * The workspace path is computed as `<root>/<collabSessionId>/<repoName?>/`, |
| 53 | + * so the first path component after the root IS the collab session id. |
| 54 | + * Returns null for paths outside the workspace root (e.g. opencode's |
| 55 | + * own source tree during dev) — those won't pass the participation check |
| 56 | + * by definition. |
| 57 | + */ |
| 58 | +export function directoryToCollabSessionId(dir: string): string | null { |
| 59 | + const root = workspaceRoot() |
| 60 | + // Strip a trailing slash on root once so the prefix check is exact. |
| 61 | + const rootWithSlash = root.endsWith("/") ? root : root + "/" |
| 62 | + if (!dir.startsWith(rootWithSlash)) return null |
| 63 | + const rest = dir.slice(rootWithSlash.length) |
| 64 | + const sessionId = rest.split("/")[0] |
| 65 | + return sessionId || null |
| 66 | +} |
| 67 | + |
| 68 | +/** |
| 69 | + * Minimal info the auth gate needs about the cookie holder. |
| 70 | + */ |
| 71 | +export interface CookieIdentity { |
| 72 | + readonly token: string |
| 73 | + readonly githubId: number |
| 74 | + readonly githubLogin: string |
| 75 | +} |
| 76 | + |
| 77 | +/** |
| 78 | + * Look up the auth session row for a cookie token. Returns null when the |
| 79 | + * cookie is missing, unknown, or expired. Mirrors the opportunistic-delete |
| 80 | + * pattern from getSession() in router.ts. |
| 81 | + */ |
| 82 | +export function lookupCookieIdentity(req: Request): CookieIdentity | null { |
| 83 | + const sid = parseCookies(req.headers.get("cookie") ?? "")["collab_sid"] |
| 84 | + if (!sid) return null |
| 85 | + return Database.use((db) => { |
| 86 | + const row = db |
| 87 | + .select() |
| 88 | + .from(CollabAuthSessionTable) |
| 89 | + .where(eq(CollabAuthSessionTable.token, sid)) |
| 90 | + .get() |
| 91 | + if (!row) return null |
| 92 | + if (row.expires_at < Date.now()) { |
| 93 | + db.delete(CollabAuthSessionTable).where(eq(CollabAuthSessionTable.token, sid)).run() |
| 94 | + return null |
| 95 | + } |
| 96 | + return { token: sid, githubId: row.github_id, githubLogin: row.github_login } |
| 97 | + }) |
| 98 | +} |
| 99 | + |
| 100 | +/** Same lookup but takes a parsed cookies map directly — used by the |
| 101 | + * Node-side WebSocket upgrade path where we don't have a `Request`. */ |
| 102 | +export function lookupCookieIdentityFromHeaders(cookieHeader: string): CookieIdentity | null { |
| 103 | + const sid = parseCookies(cookieHeader)["collab_sid"] |
| 104 | + if (!sid) return null |
| 105 | + return Database.use((db) => { |
| 106 | + const row = db |
| 107 | + .select() |
| 108 | + .from(CollabAuthSessionTable) |
| 109 | + .where(eq(CollabAuthSessionTable.token, sid)) |
| 110 | + .get() |
| 111 | + if (!row) return null |
| 112 | + if (row.expires_at < Date.now()) { |
| 113 | + db.delete(CollabAuthSessionTable).where(eq(CollabAuthSessionTable.token, sid)).run() |
| 114 | + return null |
| 115 | + } |
| 116 | + return { token: sid, githubId: row.github_id, githubLogin: row.github_login } |
| 117 | + }) |
| 118 | +} |
| 119 | + |
| 120 | +/** |
| 121 | + * Is the cookie holder a participant of the collab session with this id? |
| 122 | + * One indexed SQLite read. |
| 123 | + */ |
| 124 | +function participantOfSession(collabSessionId: string, githubId: number): boolean { |
| 125 | + return Database.use((db) => { |
| 126 | + const row = db |
| 127 | + .select({ id: CollabSessionTable.id }) |
| 128 | + .from(CollabSessionTable) |
| 129 | + .innerJoin( |
| 130 | + CollabParticipantTable, |
| 131 | + eq(CollabParticipantTable.collab_session_id, CollabSessionTable.id), |
| 132 | + ) |
| 133 | + .where( |
| 134 | + and( |
| 135 | + eq(CollabSessionTable.id, collabSessionId), |
| 136 | + eq(CollabParticipantTable.github_id, githubId), |
| 137 | + isNull(CollabSessionTable.deleted_at), |
| 138 | + ), |
| 139 | + ) |
| 140 | + .get() |
| 141 | + return !!row |
| 142 | + }) |
| 143 | +} |
| 144 | + |
| 145 | +/** |
| 146 | + * Is the cookie holder a participant of the collab session whose Native |
| 147 | + * Session ID is the given value? |
| 148 | + */ |
| 149 | +function participantOfNativeSession(nativeSessionId: string, githubId: number): boolean { |
| 150 | + return Database.use((db) => { |
| 151 | + const row = db |
| 152 | + .select({ id: CollabSessionTable.id }) |
| 153 | + .from(CollabSessionTable) |
| 154 | + .innerJoin( |
| 155 | + CollabParticipantTable, |
| 156 | + eq(CollabParticipantTable.collab_session_id, CollabSessionTable.id), |
| 157 | + ) |
| 158 | + .where( |
| 159 | + and( |
| 160 | + eq(CollabSessionTable.session_id, nativeSessionId), |
| 161 | + eq(CollabParticipantTable.github_id, githubId), |
| 162 | + isNull(CollabSessionTable.deleted_at), |
| 163 | + ), |
| 164 | + ) |
| 165 | + .get() |
| 166 | + return !!row |
| 167 | + }) |
| 168 | +} |
| 169 | + |
| 170 | +/** Extract a workspace-addressing parameter from a Request. */ |
| 171 | +function workspaceParamFrom(req: Request): string | null { |
| 172 | + const dirHeader = req.headers.get("x-opencode-directory") |
| 173 | + if (dirHeader) return dirHeader |
| 174 | + const url = new URL(req.url, "http://localhost") |
| 175 | + return ( |
| 176 | + url.searchParams.get("directory") || |
| 177 | + url.searchParams.get("location[directory]") || |
| 178 | + null |
| 179 | + ) |
| 180 | +} |
| 181 | + |
| 182 | +/** |
| 183 | + * Extract a native session id from common URL shapes. Currently we only |
| 184 | + * detect the `/event/<sessionId>` and `/session/<sessionId>/...` patterns |
| 185 | + * — those are the routes that don't carry `x-opencode-directory` but DO |
| 186 | + * scope to a specific Native Session. |
| 187 | + */ |
| 188 | +function nativeSessionIdFrom(req: Request): string | null { |
| 189 | + const url = new URL(req.url, "http://localhost") |
| 190 | + const m = url.pathname.match(/^\/(?:event|session)\/([^/]+)/) |
| 191 | + return m ? m[1]! : null |
| 192 | +} |
| 193 | + |
| 194 | +/** Paths for which a valid cookie alone (no scope check) is enough. */ |
| 195 | +function cookieAllowedWithoutScope(pathname: string): boolean { |
| 196 | + // /preview/<port>/* — see ADR-0001 + the inline note in preview-router.ts: |
| 197 | + // participants already have shell-level trust via the iframe terminal, so |
| 198 | + // strict port↔session binding is deferred to v2. |
| 199 | + return pathname.startsWith("/preview/") |
| 200 | +} |
| 201 | + |
| 202 | +export type CookieAuthDecision = "allow" | "deny" | "fallthrough" |
| 203 | + |
| 204 | +/** |
| 205 | + * 3-rule decision function — see CONTEXT.md → Cookie Authorization Scope. |
| 206 | + * |
| 207 | + * - `"allow"` — cookie present, valid, scoped to this resource. Caller |
| 208 | + * serves the request. |
| 209 | + * - `"deny"` — cookie present, valid, but NOT scoped to this resource. |
| 210 | + * Caller MUST 401 immediately; do not fall through to |
| 211 | + * basic-auth (avoids signalling the password's existence |
| 212 | + * in response to a scoped-cookie miss). |
| 213 | + * - `"fallthrough"` — no cookie at all (or invalid/expired). Caller |
| 214 | + * proceeds to basic-auth validation. |
| 215 | + */ |
| 216 | +export function cookieAuthorizesRequest(req: Request): CookieAuthDecision { |
| 217 | + const id = lookupCookieIdentity(req) |
| 218 | + if (!id) return "fallthrough" |
| 219 | + |
| 220 | + const url = new URL(req.url, "http://localhost") |
| 221 | + |
| 222 | + // Rule (a): cookie-only paths (no scope check needed). |
| 223 | + if (cookieAllowedWithoutScope(url.pathname)) return "allow" |
| 224 | + |
| 225 | + // Rule (b): workspace-addressed routes — bind on directory. |
| 226 | + const dir = workspaceParamFrom(req) |
| 227 | + if (dir) { |
| 228 | + const sessionId = directoryToCollabSessionId(dir) |
| 229 | + if (!sessionId) return "deny" |
| 230 | + return participantOfSession(sessionId, id.githubId) ? "allow" : "deny" |
| 231 | + } |
| 232 | + |
| 233 | + // Rule (c): native-session-addressed routes — bind on Native Session ID. |
| 234 | + const nativeSessionId = nativeSessionIdFrom(req) |
| 235 | + if (nativeSessionId) { |
| 236 | + return participantOfNativeSession(nativeSessionId, id.githubId) ? "allow" : "deny" |
| 237 | + } |
| 238 | + |
| 239 | + // Rule (d): no addressing → fall through to basic-auth. /global/event, |
| 240 | + // /global/config, /global/dispose, /global/upgrade etc. land here and |
| 241 | + // require the server credential. |
| 242 | + return "fallthrough" |
| 243 | +} |
0 commit comments