Line data Source code
1 : import type { AccountCredential, CrossTabRefreshPort } from '#/core/session'
2 : import type { VisibilityPort } from '#/core/webSessionIdentity'
3 :
4 : /**
5 : * Web Locks + BroadcastChannel implementation of the cross-tab refresh port.
6 : * The coordination key names both the lock and the channel. Resolves to
7 : * undefined where either API is missing (older browsers, non-browser and
8 : * unit-test environments), so hosts fall back to uncoordinated per-tab
9 : * refresh.
10 : *
11 : * Trust boundary, decided rather than assumed: the workspace JWT travels on
12 : * a same-origin BroadcastChannel whose name any script in the page can
13 : * derive from the uid and workspace id, and an inbound message is accepted
14 : * on shape, uid, workspace and a newer expiry, all of which a script in the
15 : * realm can read and forge. Same-origin script already holds the token and
16 : * the session client's storage adapter, so this widens what such a script
17 : * can do to siblings (hand them a token), not what it can reach. Hosts that
18 : * load third-party script into the realm accept that when they opt in.
19 : */
20 2355 : export function createWebCrossTabRefreshPort<Message = AccountCredential>():
21 : | CrossTabRefreshPort<Message>
22 : | undefined {
23 : // Feature-detect defensively: test DOMs ship these piecemeal (happy-dom
24 : // has a BroadcastChannel but a null navigator.locks), and either gap must
25 : // resolve to undefined.
26 2355 : if (typeof BroadcastChannel === 'undefined') return undefined
27 2355 : if (typeof navigator === 'undefined') return undefined
28 2355 : const locks = (navigator as Partial<Navigator>).locks
29 2355 : if (!locks) return undefined
30 : // A present BroadcastChannel can still throw on construction (policy,
31 : // sandbox, privacy mode, partial impl); probe once so the port is either
32 : // fully usable or absent, never interrupted mid-commit.
33 2355 : try {
34 : const probe = new BroadcastChannel('@comfyorg/account-core cross-tab probe')
35 2355 : probe.close()
36 : } catch {
37 0 : return undefined
38 : }
39 : // One refcounted channel per subscribed key, shared by subscribe and
40 : // publish. A channel never delivers a message back to itself, so
41 : // publishing on the subscription channel keeps a tab from hearing its own
42 : // broadcasts.
43 2355 : const channels = new Map<
44 : string,
45 : { channel: BroadcastChannel; subscribers: number }
46 : >()
47 2355 : return {
48 : requestLeadership(key, onAcquired) {
49 0 : const controller = new AbortController()
50 0 : let disposed = false
51 0 : let releaseHeld: (() => void) | undefined
52 0 : void locks
53 : .request(key, { signal: controller.signal }, () => {
54 : // A grant can win the race against our own abandon; returning
55 : // without holding releases the lock straight to the next tab.
56 0 : if (disposed) return
57 0 : onAcquired()
58 : // onAcquired may dispose synchronously, and neither abort() (a
59 : // no-op on a granted lock) nor releaseHeld (not wired yet) can
60 : // observe that — re-check before committing to the hold.
61 : // oxlint-disable-next-line typescript/no-unnecessary-condition -- the narrowing is not call-aware; onAcquired() can flip this
62 0 : if (disposed) return
63 : // Hold the lock until released; the browser releases it for us
64 : // when the tab dies, which is what promotes the next tab.
65 0 : return new Promise<void>((resolve) => {
66 0 : releaseHeld = resolve
67 : })
68 : })
69 : .catch((error: unknown) => {
70 : // Abandoning the request aborts it; anything else means this tab
71 : // silently never leads, which deserves a trace.
72 0 : if (error instanceof DOMException && error.name === 'AbortError') {
73 0 : return
74 : }
75 0 : console.warn('Cross-tab refresh leadership request failed:', error)
76 : })
77 0 : return () => {
78 0 : disposed = true
79 0 : controller.abort()
80 0 : releaseHeld?.()
81 : }
82 : },
83 : publishCredential(key, credential) {
84 0 : const entry = channels.get(key)
85 0 : if (entry !== undefined) {
86 0 : entry.channel.postMessage(credential)
87 0 : return
88 : }
89 : // No subscriber on this key here: publish on an ephemeral channel so
90 : // nothing is left open with no owner to close it.
91 0 : const channel = new BroadcastChannel(key)
92 0 : channel.postMessage(credential)
93 0 : channel.close()
94 : },
95 : onCredential(key, callback) {
96 0 : let entry = channels.get(key)
97 0 : if (entry === undefined) {
98 0 : entry = { channel: new BroadcastChannel(key), subscribers: 0 }
99 0 : channels.set(key, entry)
100 : }
101 0 : entry.subscribers += 1
102 0 : const subscribed = entry
103 0 : const handler = (event: MessageEvent) => {
104 0 : const message: unknown = event.data
105 0 : callback(message)
106 : }
107 0 : subscribed.channel.addEventListener('message', handler)
108 0 : let active = true
109 0 : return () => {
110 0 : if (!active) return
111 0 : active = false
112 0 : subscribed.channel.removeEventListener('message', handler)
113 0 : subscribed.subscribers -= 1
114 0 : if (subscribed.subscribers === 0) {
115 0 : subscribed.channel.close()
116 0 : if (channels.get(key) === subscribed) channels.delete(key)
117 : }
118 : }
119 : }
120 : }
121 : }
122 :
123 0 : export function createWebVisibilityPort(): VisibilityPort | undefined {
124 0 : if (typeof document === 'undefined') return undefined
125 0 : const isVisible = () => document.visibilityState === 'visible'
126 0 : return {
127 : isVisible,
128 : onChange: (listener) => {
129 0 : const handler = () => listener(isVisible())
130 0 : document.addEventListener('visibilitychange', handler)
131 0 : return () => document.removeEventListener('visibilitychange', handler)
132 : }
133 : }
134 : }
|