Line data Source code
1 : import type { OAuthTokens } from '@comfyorg/account-core/oauthPkce'
2 : import { omit } from 'es-toolkit'
3 : import { z } from 'zod'
4 :
5 : /** Where this page keeps its OAuth tokens; swapping it changes the policy. */
6 : export interface LocalWebTokenStore {
7 : read(): OAuthTokens | undefined
8 : /** False when the storage refused the write, so nothing was persisted. */
9 : write(tokens: OAuthTokens): boolean
10 : /** Tokens kept for a workspace this page signed in to before, if any. */
11 : readWorkspace(workspaceId: string): OAuthTokens | undefined
12 : /** False when the storage refused the write, so nothing was persisted. */
13 : writeWorkspace(workspaceId: string, tokens: OAuthTokens): boolean
14 : /** Forgets one workspace's kept tokens, only if they are still `stale`. */
15 : forgetWorkspace(workspaceId: string, stale: OAuthTokens): void
16 : /** Forgets the active tokens and every workspace's tokens, returning them. */
17 : clear(): OAuthTokens[]
18 : /** Calls back when another tab changes the stored or kept tokens. */
19 : subscribe(listener: () => void): () => void
20 : }
21 :
22 2352 : export const LOCAL_WEB_TOKENS_KEY = 'Comfy.LocalWebSignIn.Tokens'
23 2352 : const LOCAL_WEB_WORKSPACE_TOKENS_KEY = 'Comfy.LocalWebSignIn.WorkspaceTokens'
24 :
25 : type TokenStorage = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>
26 :
27 2352 : const zStoredTokens = z.object({
28 : accessToken: z.string(),
29 : refreshToken: z.string(),
30 : expiresAt: z.number(),
31 : scope: z.string()
32 : })
33 :
34 2352 : const zStoredWorkspaceTokens = z.record(z.string(), zStoredTokens)
35 :
36 : export function createMemoryTokenStore(): LocalWebTokenStore {
37 : let tokens: OAuthTokens | undefined
38 : const byWorkspace = new Map<string, OAuthTokens>()
39 : return {
40 : read: () => tokens,
41 : write: (next) => {
42 : tokens = next
43 : return true
44 : },
45 : readWorkspace: (workspaceId) => byWorkspace.get(workspaceId),
46 : writeWorkspace: (workspaceId, next) => {
47 : byWorkspace.set(workspaceId, next)
48 : return true
49 : },
50 : forgetWorkspace: (workspaceId, stale) => {
51 : if (byWorkspace.get(workspaceId)?.refreshToken === stale.refreshToken)
52 : byWorkspace.delete(workspaceId)
53 : },
54 : clear: () => {
55 : const forgotten = [...(tokens ? [tokens] : []), ...byWorkspace.values()]
56 : tokens = undefined
57 : byWorkspace.clear()
58 : return forgotten
59 : },
60 : subscribe: () => () => {}
61 : }
62 : }
63 :
64 10 : function parseStoredTokens(raw: string | null): OAuthTokens | undefined {
65 10 : if (raw === null) return undefined
66 10 : try {
67 10 : const parsed = zStoredTokens.safeParse(JSON.parse(raw))
68 10 : return parsed.success ? parsed.data : undefined
69 : } catch {
70 0 : return undefined
71 : }
72 : }
73 :
74 117 : function parseStoredWorkspaceTokens(
75 : raw: string | null
76 : ): Record<string, OAuthTokens> {
77 117 : if (raw === null) return {}
78 117 : try {
79 97 : const parsed = zStoredWorkspaceTokens.safeParse(JSON.parse(raw))
80 117 : return parsed.success ? parsed.data : {}
81 : } catch {
82 0 : return {}
83 : }
84 : }
85 :
86 137 : function ignoringStorageErrors<T>(access: () => T, fallback: T): T {
87 137 : try {
88 137 : return access()
89 : } catch {
90 0 : return fallback
91 : }
92 : }
93 :
94 : /**
95 : * Keeps the tokens in origin storage so a reload or a new tab stays signed
96 : * in, the same persistence Firebase sign-in already uses on this origin.
97 : */
98 2352 : export function createStorageTokenStore(
99 : storage: TokenStorage,
100 : storageEvents: Pick<EventTarget, 'addEventListener' | 'removeEventListener'>
101 : ): LocalWebTokenStore {
102 2352 : const readWorkspaces = () =>
103 : parseStoredWorkspaceTokens(
104 : ignoringStorageErrors(
105 : () => storage.getItem(LOCAL_WEB_WORKSPACE_TOKENS_KEY),
106 : null
107 : )
108 : )
109 2352 : const readActive = () =>
110 : parseStoredTokens(
111 : ignoringStorageErrors(() => storage.getItem(LOCAL_WEB_TOKENS_KEY), null)
112 : )
113 2352 : return {
114 : read: readActive,
115 : write: (tokens) =>
116 : ignoringStorageErrors(() => {
117 0 : storage.setItem(LOCAL_WEB_TOKENS_KEY, JSON.stringify(tokens))
118 0 : return true
119 : }, false),
120 : readWorkspace: (workspaceId) => readWorkspaces()[workspaceId],
121 : writeWorkspace: (workspaceId, tokens) =>
122 : ignoringStorageErrors(() => {
123 10 : storage.setItem(
124 : LOCAL_WEB_WORKSPACE_TOKENS_KEY,
125 : JSON.stringify({ ...readWorkspaces(), [workspaceId]: tokens })
126 : )
127 10 : return true
128 : }, false),
129 : forgetWorkspace(workspaceId, stale) {
130 0 : ignoringStorageErrors(() => {
131 0 : const workspaces = readWorkspaces()
132 0 : if (workspaces[workspaceId]?.refreshToken !== stale.refreshToken) return
133 0 : storage.setItem(
134 : LOCAL_WEB_WORKSPACE_TOKENS_KEY,
135 : JSON.stringify(omit(workspaces, [workspaceId]))
136 : )
137 : }, undefined)
138 : },
139 : clear() {
140 0 : const active = readActive()
141 0 : const forgotten = [
142 : ...(active ? [active] : []),
143 : ...Object.values(readWorkspaces())
144 : ]
145 0 : ignoringStorageErrors(() => {
146 0 : storage.removeItem(LOCAL_WEB_TOKENS_KEY)
147 0 : storage.removeItem(LOCAL_WEB_WORKSPACE_TOKENS_KEY)
148 : }, undefined)
149 0 : return forgotten
150 : },
151 : subscribe(listener) {
152 10 : const onStorage = (event: Event) => {
153 10 : const key = 'key' in event ? event.key : undefined
154 10 : if (
155 : key === LOCAL_WEB_TOKENS_KEY ||
156 : key === LOCAL_WEB_WORKSPACE_TOKENS_KEY ||
157 : key === null
158 : )
159 0 : listener()
160 : }
161 10 : storageEvents.addEventListener('storage', onStorage)
162 10 : return () => storageEvents.removeEventListener('storage', onStorage)
163 : }
164 : }
165 : }
|