fix(desktop): retain renderer permissions across shared-session windows (#60458)

This commit is contained in:
Luke Parker
2026-10-30 14:27:35 +10:00
committed by GitHub
Unverified
parent 78f8dffd48
commit f807ffeccb
3 changed files with 171 additions and 16 deletions
+2 -3
View File
@@ -1,5 +1,4 @@
import { protocol } from "electron"
import type { BrowserWindow } from "electron"
import electron, { type BrowserWindow } from "electron"
export const rendererProtocol = "oc"
@@ -34,7 +33,7 @@ export function isRendererUrl(value?: string, html = false) {
// Scheme privileges can only be granted before the app is ready, so the entry module calls this
// before it loads anything else.
export function registerRendererScheme() {
protocol.registerSchemesAsPrivileged([
electron.protocol.registerSchemesAsPrivileged([
{
scheme: rendererProtocol,
privileges: {
@@ -0,0 +1,123 @@
import { expect, test } from "bun:test"
import { EventEmitter } from "node:events"
import type { BrowserWindow, Session, WebContents } from "electron"
import { allowRendererPermissions } from "./security"
type RequestHandler = NonNullable<Parameters<Session["setPermissionRequestHandler"]>[0]>
type CheckHandler = NonNullable<Parameters<Session["setPermissionCheckHandler"]>[0]>
type Permission = Parameters<RequestHandler>[1]
type RequestDetails = Parameters<RequestHandler>[3]
type CheckDetails = Parameters<CheckHandler>[3]
const url = "oc://renderer/index.html"
const origin = "oc://renderer"
function createSession() {
let request: RequestHandler | null = null
let checkHandler: CheckHandler | null = null
// SAFETY: allowRendererPermissions touches only setPermissionRequestHandler and setPermissionCheckHandler.
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
const session = {
setPermissionRequestHandler(handler: RequestHandler | null) {
request = handler
},
setPermissionCheckHandler(handler: CheckHandler | null) {
checkHandler = handler
},
} as unknown as Session
const sender = (id: number) => {
// SAFETY: permission handlers read only `webContents.id`.
return { id } as WebContents
}
const ask = (
id: number,
permission: Permission,
details: RequestDetails = { requestingUrl: url, isMainFrame: true },
) =>
new Promise<boolean>((resolve) => {
if (!request) throw new Error("Missing permission request handler")
request(sender(id), permission, resolve, details)
})
const check = (
id: number | null,
permission: Permission,
details: CheckDetails = { requestingUrl: url, isMainFrame: true },
) => {
if (!checkHandler) throw new Error("Missing permission check handler")
return checkHandler(id === null ? null : sender(id), permission, origin, details)
}
return { session, ask, check }
}
function createWindow(id: number, session: Session) {
let destroyed = false
const winEvents = new EventEmitter()
const contentsEvents = new EventEmitter()
// SAFETY: allowRendererPermissions reads only `isDestroyed`, `once`, and `webContents` (`id`, `session`, `isDestroyed`, `once`).
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
const win = {
isDestroyed: () => destroyed,
once: winEvents.once.bind(winEvents),
webContents: {
id,
session,
isDestroyed: () => destroyed,
once: contentsEvents.once.bind(contentsEvents),
},
} as unknown as BrowserWindow
return {
win,
close() {
destroyed = true
contentsEvents.emit("destroyed")
winEvents.emit("closed")
},
}
}
test("retains permissions across all live windows on a shared session and revokes closed ones", async () => {
const shared = createSession()
const first = createWindow(1, shared.session)
const second = createWindow(2, shared.session)
allowRendererPermissions(first.win)
allowRendererPermissions(second.win)
const audioReq: RequestDetails = { requestingUrl: url, isMainFrame: true, mediaTypes: ["audio"] }
const audioCheck: CheckDetails = { requestingUrl: url, isMainFrame: true, mediaType: "audio" }
expect(await shared.ask(1, "notifications")).toBe(true)
expect(await shared.ask(2, "notifications")).toBe(true)
expect(await shared.ask(99, "notifications")).toBe(false)
expect(shared.check(1, "clipboard-sanitized-write")).toBe(true)
expect(shared.check(2, "clipboard-sanitized-write")).toBe(true)
expect(shared.check(99, "clipboard-sanitized-write")).toBe(false)
expect(await shared.ask(1, "media", audioReq)).toBe(true)
expect(shared.check(1, "media", audioCheck)).toBe(true)
second.close()
expect(await shared.ask(2, "notifications")).toBe(false)
expect(shared.check(2, "clipboard-sanitized-write")).toBe(false)
expect(await shared.ask(1, "notifications")).toBe(true)
expect(shared.check(1, "clipboard-sanitized-write")).toBe(true)
expect(await shared.ask(1, "media", audioReq)).toBe(true)
first.close()
expect(await shared.ask(1, "notifications")).toBe(false)
expect(shared.check(null, "notifications", { isMainFrame: false })).toBe(false)
})
+46 -13
View File
@@ -1,16 +1,42 @@
import type { BrowserWindow } from "electron"
import type { BrowserWindow, Session } from "electron"
import { SidecarCredentials } from "../service/sidecar-credentials"
import { addRendererHeaders, hasHeader, upsertHeader } from "./headers"
import { isRendererUrl } from "./scheme"
const rendererPermissions = new Set(["clipboard-sanitized-write", "notifications"])
const allowedBySession = new WeakMap<Session, Set<number>>()
const wiredHeaderSessions = new WeakSet<Session>()
// App windows share Electron's default session, where setPermission*Handler replaces the previous
// handler. One pair of handlers per session evaluates against the live renderer WebContents set.
export function allowRendererPermissions(win: BrowserWindow) {
const webContentsId = win.webContents.id
win.webContents.session.setPermissionRequestHandler((webContents, permission, callback, details) => {
if (win.isDestroyed() || win.webContents.isDestroyed()) return
const webContents = win.webContents
const session = webContents.session
const allowed = allowedBySession.get(session) ?? registerPermissionHandlers(session)
const id = webContents.id
if (allowed.has(id)) return
allowed.add(id)
const remove = () => {
allowed.delete(id)
}
webContents.once("destroyed", remove)
win.once("closed", remove)
}
function registerPermissionHandlers(session: Session) {
const allowed = new Set<number>()
allowedBySession.set(session, allowed)
session.setPermissionRequestHandler((webContents, permission, callback, details) => {
if (permission === "media") {
callback(
webContents.id === webContentsId &&
allowed.has(webContents.id) &&
isRendererUrl(details.requestingUrl) &&
details.isMainFrame &&
"mediaTypes" in details &&
@@ -21,14 +47,14 @@ export function allowRendererPermissions(win: BrowserWindow) {
return
}
callback(
rendererPermissions.has(permission) && isRendererUrl(details.requestingUrl) && webContents.id === webContentsId,
)
callback(rendererPermissions.has(permission) && isRendererUrl(details.requestingUrl) && allowed.has(webContents.id))
})
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === "media") {
return (
webContents?.id === webContentsId &&
webContents !== null &&
allowed.has(webContents.id) &&
isRendererUrl(details.requestingUrl) &&
details.isMainFrame &&
details.mediaType === "audio"
@@ -37,13 +63,15 @@ export function allowRendererPermissions(win: BrowserWindow) {
if (!rendererPermissions.has(permission)) return false
if (webContents && webContents.id !== webContentsId) return false
if (webContents ? !allowed.has(webContents.id) : allowed.size === 0) return false
return isRendererUrl(details.requestingUrl) || isRendererUrl(requestingOrigin)
})
return allowed
}
export function wireNavigationPolicy(win: BrowserWindow, openExternalURL: (url: string) => unknown) {
export function wireNavigationPolicy(win: BrowserWindow, openExternalURL: (url: string) => void) {
win.webContents.setWindowOpenHandler(({ url }) => {
if (!isRendererUrl(url)) openExternalURL(url)
@@ -57,6 +85,11 @@ export function wireNavigationPolicy(win: BrowserWindow, openExternalURL: (url:
}
export function wireRendererHeaders(win: BrowserWindow) {
const session = win.webContents.session
if (wiredHeaderSessions.has(session)) return
wiredHeaderSessions.add(session)
// The renderer sends sidecar requests without credentials, so its GETs are CORS-simple and need no
// preflight. Electron applies these listeners in Chromium's extraHeaders mode, after the CORS
// decision, so adding Authorization here does not reintroduce one.
@@ -64,7 +97,7 @@ export function wireRendererHeaders(win: BrowserWindow) {
// Only the renderer's own top-level frame is credentialed. Other content in this session (web views,
// embedded pages) can reach the same loopback origin and must not inherit its access. Requests with
// no frame, such as from a service worker, are not credentialed either; the renderer registers none.
win.webContents.session.webRequest.onBeforeSendHeaders(
session.webRequest.onBeforeSendHeaders(
{ urls: ["http://127.0.0.1/*", "http://localhost/*"] },
(details, callback) => {
const frame = details.frame
@@ -78,7 +111,7 @@ export function wireRendererHeaders(win: BrowserWindow) {
callback({ requestHeaders: details.requestHeaders })
},
)
win.webContents.session.webRequest.onHeadersReceived((details, callback) => {
session.webRequest.onHeadersReceived((details, callback) => {
const responseHeaders = details.responseHeaders ?? {}
addRendererHeaders(responseHeaders, { document: isRendererUrl(details.url, true) })
callback({ responseHeaders })