Line data Source code
1 : import { computed, readonly, ref, shallowRef } from 'vue'
2 :
3 : import { z } from 'zod'
4 :
5 : import type {
6 : DesktopHostAuthBridge,
7 : DesktopHostAuthState,
8 : DesktopHostBillingHandoff,
9 : DesktopHostBillingIntent,
10 : DesktopHostBillingReceiver
11 : } from '@/platform/auth/desktopHost/desktopHostAuthBridge'
12 :
13 : interface DesktopHostUser {
14 : id: string
15 : email?: string
16 : name?: string
17 : workspaceId?: string
18 : }
19 :
20 : /** `inactive`: Desktop does not share its session, so Firebase owns identity as before. */
21 : type DesktopHostSession =
22 : | { status: 'inactive' }
23 : | { status: 'signed_out' }
24 : | { status: 'signed_in'; user: DesktopHostUser }
25 :
26 2356 : const session = shallowRef<DesktopHostSession>({ status: 'inactive' })
27 2356 : let bridge: DesktopHostAuthBridge | undefined
28 2356 : let bridgeReportsSignInFailures = false
29 2356 : let unsubscribe: (() => void) | undefined
30 : /** Bumped on every session change, so a reply that raced one is dropped. */
31 2356 : let revision = 0
32 2356 : let lastTokenReadFailed = false
33 2356 : const recoveredTokenReads = ref(0)
34 :
35 : /** Counts credential reads that succeeded right after a failed one. */
36 2356 : export const desktopHostTokenRecoveries = readonly(recoveredTokenReads)
37 :
38 14 : function toSession(state: DesktopHostAuthState): DesktopHostSession {
39 14 : if (state.status === 'disabled') return { status: 'inactive' }
40 14 : if (state.status === 'signed_out') return { status: 'signed_out' }
41 13 : const { userId, email, name, workspaceId } = state
42 13 : return { status: 'signed_in', user: { id: userId, email, name, workspaceId } }
43 : }
44 :
45 14 : function apply(state: DesktopHostAuthState): void {
46 14 : const next = toSession(state)
47 14 : if (next.status === 'inactive') {
48 0 : stopDesktopHostSession()
49 0 : return
50 : }
51 14 : const current = session.value
52 : const sameAccount =
53 : next.status === 'signed_in' &&
54 : current.status === 'signed_in' &&
55 : next.user.id === current.user.id &&
56 : next.user.workspaceId === current.user.workspaceId
57 14 : if (!sameAccount) revision++
58 14 : session.value = next
59 : }
60 :
61 : /** The Desktop account signed in to this view, or null. */
62 2356 : export const desktopHostUser = computed(() =>
63 : session.value.status === 'signed_in' ? session.value.user : null
64 : )
65 :
66 : /** True while Desktop shares its session with this view, signed in or not. */
67 13 : export function isDesktopHostSessionActive(): boolean {
68 13 : return session.value.status !== 'inactive'
69 : }
70 :
71 : /** Changes whenever the Desktop account or workspace changes. */
72 9 : export function desktopHostSessionRevision(): number {
73 9 : return revision
74 : }
75 :
76 : /** True while a Desktop account is signed in; only then does it own auth. */
77 5525 : export function isDesktopHostSignedIn(): boolean {
78 5525 : return desktopHostUser.value !== null
79 : }
80 :
81 : /**
82 : * Makes the Desktop account the identity for this page when Desktop shares
83 : * its session. Stays inactive, leaving Firebase in charge, when Desktop
84 : * answers `disabled` or the bridge fails.
85 : */
86 13 : export async function startDesktopHostSession(
87 : hostBridge: DesktopHostAuthBridge,
88 : { reportsSignInFailures = false }: { reportsSignInFailures?: boolean } = {}
89 : ): Promise<void> {
90 13 : stopDesktopHostSession()
91 13 : bridge = hostBridge
92 13 : bridgeReportsSignInFailures = reportsSignInFailures
93 13 : try {
94 13 : unsubscribe = hostBridge.onChanged(apply)
95 13 : const before = revision
96 13 : const initial = await hostBridge.getState()
97 13 : if (bridge === hostBridge && revision === before) apply(initial)
98 : } catch {
99 0 : if (bridge === hostBridge) stopDesktopHostSession()
100 : }
101 : }
102 :
103 : /** True when the session tells the person itself why a sign-in did not finish. */
104 0 : export function desktopHostReportsSignInFailures(): boolean {
105 0 : return bridgeReportsSignInFailures
106 : }
107 :
108 13 : export function stopDesktopHostSession(): void {
109 13 : unsubscribe?.()
110 13 : bridgeReportsSignInFailures = false
111 13 : lastTokenReadFailed = false
112 13 : unsubscribe = undefined
113 13 : bridge = undefined
114 13 : revision++
115 13 : session.value = { status: 'inactive' }
116 : }
117 :
118 : /**
119 : * Desktop's credential for `workspaceId`, released only when its session is
120 : * scoped to exactly that workspace. This is the API-node credential.
121 : */
122 121 : export function desktopHostWorkspaceToken(
123 : workspaceId: string
124 : ): Promise<string | undefined> {
125 121 : return fetchToken((current) => current.getWorkspaceToken(workspaceId), {
126 : tracksRecovery: true
127 : })
128 : }
129 :
130 : /**
131 : * The partner-node token Desktop minted and renews for `workspaceId`, under
132 : * the same rules as {@link desktopHostWorkspaceToken}. Resolves undefined when
133 : * Desktop has none or its build cannot mint one.
134 : */
135 3 : export function desktopHostPartnerNodeToken(
136 : workspaceId: string
137 : ): Promise<string | undefined> {
138 3 : return fetchToken(
139 : async (current) =>
140 : (await current.getPartnerNodeToken?.(workspaceId)) ?? null
141 : )
142 : }
143 :
144 124 : async function fetchToken(
145 : read: (current: DesktopHostAuthBridge) => Promise<string | null>,
146 : { tracksRecovery = false }: { tracksRecovery?: boolean } = {}
147 : ): Promise<string | undefined> {
148 124 : const current = bridge
149 124 : if (!current || session.value.status !== 'signed_in') return undefined
150 124 : const before = revision
151 124 : const token = await read(current).catch(() => null)
152 124 : if (revision !== before) return undefined
153 124 : if (tracksRecovery) {
154 121 : if (token && lastTokenReadFailed) recoveredTokenReads.value++
155 121 : lastTokenReadFailed = !token
156 : }
157 124 : return token ?? undefined
158 : }
159 :
160 : /** Runs Desktop's browser sign-in. Resolves true when it ends signed in. */
161 0 : export async function requestDesktopHostSignIn(): Promise<boolean> {
162 0 : const current = bridge
163 0 : if (!current) return false
164 0 : const before = revision
165 0 : const next = await current.requestSignIn().catch(() => undefined)
166 0 : if (next && bridge === current && revision === before) apply(next)
167 0 : return desktopHostUser.value !== null
168 : }
169 :
170 : /** Signs Desktop out of its account. Resolves true once no Desktop user remains. */
171 0 : export async function requestDesktopHostSignOut(): Promise<boolean> {
172 0 : const current = bridge
173 0 : if (!current) return true
174 0 : const before = revision
175 0 : const next = await current.signOut().catch(() => undefined)
176 0 : if (next && bridge === current && revision === before) apply(next)
177 0 : return desktopHostUser.value === null
178 : }
179 :
180 2356 : const zDesktopHostBillingHandoff = z.discriminatedUnion('status', [
181 : z.object({
182 : status: z.literal('issued'),
183 : entryUrl: z.url({ protocol: /^https$/ })
184 : }),
185 : z.object({ status: z.literal('sign_in_again') }),
186 : z.object({
187 : status: z.literal('refused'),
188 : code: z.string().optional(),
189 : message: z.string().optional()
190 : }),
191 : z.object({ status: z.literal('disabled') })
192 : ])
193 :
194 2356 : const UNEXPLAINED_REFUSAL: DesktopHostBillingHandoff = { status: 'refused' }
195 :
196 2356 : const BILLING_HANDOFF_TIMEOUT_MS = 40_000
197 :
198 0 : function refusedAfter(ms: number): {
199 : refusal: Promise<DesktopHostBillingHandoff>
200 : cancel: () => void
201 : } {
202 0 : let timer: ReturnType<typeof setTimeout> | undefined
203 : const refusal = new Promise<DesktopHostBillingHandoff>((resolve) => {
204 0 : timer = setTimeout(() => resolve(UNEXPLAINED_REFUSAL), ms)
205 : })
206 0 : return { refusal, cancel: () => clearTimeout(timer) }
207 : }
208 :
209 0 : export function canDesktopHostIssueBillingHandoff(): boolean {
210 0 : return isDesktopHostSignedIn() && bridge?.issueBillingHandoff !== undefined
211 : }
212 :
213 : /** Asks Desktop to issue a billing handoff with its own credential; only the entry URL comes back. */
214 0 : export async function issueDesktopHostBillingHandoff(
215 : workspaceId: string,
216 : receiver: DesktopHostBillingReceiver,
217 : intent?: DesktopHostBillingIntent,
218 : amountCents?: number
219 : ): Promise<DesktopHostBillingHandoff> {
220 0 : const current = bridge
221 0 : if (!current?.issueBillingHandoff || !isDesktopHostSignedIn())
222 0 : return { status: 'disabled' }
223 0 : const deadline = refusedAfter(BILLING_HANDOFF_TIMEOUT_MS)
224 0 : const answer = await Promise.race([
225 : Promise.resolve()
226 : .then(() =>
227 : current.issueBillingHandoff?.(
228 : workspaceId,
229 : receiver,
230 : intent,
231 : amountCents
232 : )
233 : )
234 : .catch(() => UNEXPLAINED_REFUSAL),
235 : deadline.refusal
236 : ]).finally(deadline.cancel)
237 0 : const parsed = zDesktopHostBillingHandoff.safeParse(answer)
238 0 : return parsed.success ? parsed.data : UNEXPLAINED_REFUSAL
239 : }
240 :
241 : /** True when this Desktop can re-scope its session to another workspace. */
242 5 : export function canDesktopHostSwitchWorkspace(): boolean {
243 5 : return isDesktopHostSignedIn() && bridge?.switchWorkspace !== undefined
244 : }
245 :
246 : /**
247 : * Asks Desktop to re-scope its session to `workspaceId`, which may run browser
248 : * consent. Resolves true once the session is on that workspace.
249 : */
250 0 : export async function requestDesktopHostWorkspaceSwitch(
251 : workspaceId: string
252 : ): Promise<boolean> {
253 0 : const current = bridge
254 0 : if (!current?.switchWorkspace || !isDesktopHostSignedIn()) return false
255 0 : const before = revision
256 0 : const next = await current.switchWorkspace(workspaceId).catch(() => undefined)
257 0 : if (next && bridge === current && revision === before) apply(next)
258 0 : return desktopHostUser.value?.workspaceId === workspaceId
259 : }
|