@burdenoff/microfe-auth 2026.704.1 → 2026.708.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/hooks/useContextSwitcherData.js +117 -99
- package/dist/auth/hooks/useContextSwitcherData.js.map +1 -1
- package/dist/auth/pages/SSOClearPage.js +13 -15
- package/dist/auth/pages/SSOClearPage.js.map +1 -1
- package/dist/auth/pages/SSODepositPage.js +16 -18
- package/dist/auth/pages/SSODepositPage.js.map +1 -1
- package/dist/auth/pages/SSORelayCallbackPage.js +12 -14
- package/dist/auth/pages/SSORelayCallbackPage.js.map +1 -1
- package/package.json +2 -2
|
@@ -5,11 +5,11 @@ import { useEventBus as o } from "@burdenoff/fe-libs/shared/events";
|
|
|
5
5
|
import { getStoredAuthToken as s, graphqlFetch as c } from "@burdenoff/fe-libs/shared/graphql";
|
|
6
6
|
import { useActiveContext as l } from "@burdenoff/fe-libs/shared/providers/shell/ActiveContextProvider";
|
|
7
7
|
//#region src/auth/hooks/useContextSwitcherData.ts
|
|
8
|
-
var u = "\n query MyOrganizations {\n myOrganizations {\n total\n items {\n id\n name\n slug\n tenantId\n description\n logo\n website\n status\n type\n createdAt\n updatedAt\n }\n }\n }\n", d = "\n query WorkspacesByOrg {\n workspaces: myWorkspaces(limit: 100) {\n total\n items {\n id\n name\n slug\n tenantId\n organizationId\n type\n status\n region\n createdAt\n updatedAt\n }\n }\n }\n", f = "\n
|
|
9
|
-
async function
|
|
8
|
+
var u = "\n query MyOrganizations {\n myOrganizations {\n total\n items {\n id\n name\n slug\n tenantId\n description\n logo\n website\n status\n type\n createdAt\n updatedAt\n }\n }\n }\n", d = "\n query WorkspacesByOrg {\n workspaces: myWorkspaces(limit: 100) {\n total\n items {\n id\n name\n slug\n tenantId\n organizationId\n type\n status\n region\n createdAt\n updatedAt\n }\n }\n }\n", f = "\n mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {\n issueWorkspaceToken(input: $input) {\n success\n token\n expiresAt\n organizationId\n workspaceId\n projectId\n scopes\n error {\n code\n message\n }\n }\n }\n", p = "\n query MyProjectsForContext {\n projects: myProjects {\n total\n items {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n }\n", m = "\n mutation CreateDefaultProject($input: CreateProjectInput!) {\n createProject(input: $input) {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n";
|
|
9
|
+
async function h({ authToken: e, workspaceBaseUrl: t, workspaceToken: n }) {
|
|
10
10
|
let r = await c({
|
|
11
11
|
gateway: "workspace",
|
|
12
|
-
query:
|
|
12
|
+
query: m,
|
|
13
13
|
variables: { input: { name: "Default Project" } },
|
|
14
14
|
authToken: e,
|
|
15
15
|
workspaceToken: n,
|
|
@@ -17,7 +17,7 @@ async function g({ authToken: e, workspaceBaseUrl: t, workspaceToken: n }) {
|
|
|
17
17
|
});
|
|
18
18
|
return r.errors?.length ? (console.warn("Failed to create default project:", r.errors), null) : r.data?.createProject ?? null;
|
|
19
19
|
}
|
|
20
|
-
function
|
|
20
|
+
function g(e, t = 3e4) {
|
|
21
21
|
try {
|
|
22
22
|
let n = JSON.parse(atob(e.split(".")[1]));
|
|
23
23
|
return n.exp ? n.exp * 1e3 < Date.now() + t : !1;
|
|
@@ -25,7 +25,7 @@ function _(e, t = 3e4) {
|
|
|
25
25
|
return !0;
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
-
function
|
|
28
|
+
function _(e) {
|
|
29
29
|
try {
|
|
30
30
|
let t = JSON.parse(atob(e.split(".")[1]));
|
|
31
31
|
return {
|
|
@@ -38,26 +38,26 @@ function v(e) {
|
|
|
38
38
|
return null;
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
|
-
function
|
|
42
|
-
if (!e ||
|
|
43
|
-
let n =
|
|
41
|
+
function v(e, t) {
|
|
42
|
+
if (!e || g(e)) return !1;
|
|
43
|
+
let n = _(e);
|
|
44
44
|
return !(!n || t.workspaceId && n.workspaceId !== t.workspaceId || t.organizationId && n.organizationId !== t.organizationId || t.projectId && n.projectId !== t.projectId);
|
|
45
45
|
}
|
|
46
|
-
var
|
|
46
|
+
var y = class extends Error {
|
|
47
47
|
constructor(e) {
|
|
48
48
|
super(e), this.name = "AuthError";
|
|
49
49
|
}
|
|
50
50
|
};
|
|
51
|
-
function
|
|
51
|
+
function b(e) {
|
|
52
52
|
return e.some((e) => e.extensions?.code === "UNAUTHENTICATED" || e.message?.toLowerCase().includes("unauthorized") || e.message?.toLowerCase().includes("not authenticated"));
|
|
53
53
|
}
|
|
54
|
-
function
|
|
54
|
+
function x() {
|
|
55
55
|
let t = e.getState().accessToken;
|
|
56
|
-
if (t && !
|
|
56
|
+
if (t && !g(t)) return t;
|
|
57
57
|
let n = s();
|
|
58
|
-
return n && !
|
|
58
|
+
return n && !g(n) ? n : t;
|
|
59
59
|
}
|
|
60
|
-
function
|
|
60
|
+
function S(e) {
|
|
61
61
|
return Array.from(new Set(e.flatMap((e) => e.organizationId ? [e.organizationId] : []))).map((t, n) => ({
|
|
62
62
|
id: t,
|
|
63
63
|
name: e.find((e) => e.organizationId === t)?.name || `Organization ${n + 1}`,
|
|
@@ -65,55 +65,73 @@ function C(e) {
|
|
|
65
65
|
tenantId: e.find((e) => e.organizationId === t)?.tenantId || ""
|
|
66
66
|
}));
|
|
67
67
|
}
|
|
68
|
-
var
|
|
68
|
+
var C = new Set([
|
|
69
69
|
"project.created",
|
|
70
70
|
"project.updated",
|
|
71
71
|
"project.deleted",
|
|
72
72
|
"project.archived",
|
|
73
73
|
"project.unarchived"
|
|
74
|
-
]),
|
|
74
|
+
]), w = new Set([
|
|
75
75
|
"workspace.created",
|
|
76
76
|
"workspace.updated",
|
|
77
77
|
"workspace.deleted",
|
|
78
78
|
"workspace.archived",
|
|
79
79
|
"workspace.reactivated"
|
|
80
80
|
]);
|
|
81
|
-
function
|
|
81
|
+
function T(e) {
|
|
82
82
|
if (e && typeof e == "object" && "workspaceId" in e) {
|
|
83
83
|
let t = e.workspaceId;
|
|
84
84
|
return typeof t == "string" ? t : void 0;
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
|
-
function
|
|
88
|
-
let { organizationId:
|
|
87
|
+
function E(s) {
|
|
88
|
+
let { organizationId: m, workspaceId: _, projectId: E, setContext: D } = l(), O = o(), k = e((e) => e.organizations), A = e((e) => e.currentOrganizationId), j = e((e) => e.isLoadingOrganizations), M = e((e) => e.workspaces), N = e((e) => e.currentWorkspaceId), P = e((e) => e.workspaceToken), F = e((e) => e.isLoadingWorkspaces), I = e((e) => e.projects), L = e((e) => e.currentProjectId), R = e((e) => e.isLoadingProjects), [ee, z] = a(null), B = i(null), V = i(/* @__PURE__ */ new Map()), H = i(_), U = i(m);
|
|
89
89
|
r(() => {
|
|
90
|
-
H.current =
|
|
90
|
+
H.current = _, U.current = m;
|
|
91
91
|
});
|
|
92
92
|
let W = t(), G = s?.globalBaseUrl ?? W.globalBaseUrl, K = s?.workspaceBaseUrl ?? W.workspaceBaseUrl, q = i(null), J = i(null), Y = i(null), X = i(null);
|
|
93
93
|
r(() => {
|
|
94
94
|
let t = e.getState();
|
|
95
|
-
if (
|
|
96
|
-
workspaceId:
|
|
97
|
-
organizationId:
|
|
98
|
-
projectId:
|
|
95
|
+
if (m && m !== t.currentOrganizationId && m !== q.current && (q.current = m, t.setCurrentOrganizationId(m), t.workspaces.length > 0 && !t.workspaces.some((e) => e.organizationId === m) && t.setWorkspaces([])), _ && _ !== t.currentWorkspaceId && _ !== J.current && (J.current = _, t.setCurrentWorkspaceId(_), t.projects.length > 0 && !t.projects.some((e) => e.workspaceId === _) && (t.setProjects([]), t.setCurrentProjectId(null))), E && E !== t.currentProjectId && E !== Y.current && (Y.current = E, t.setCurrentProjectId(E)), t.workspaceToken && !v(t.workspaceToken, {
|
|
96
|
+
workspaceId: _,
|
|
97
|
+
organizationId: m,
|
|
98
|
+
projectId: E
|
|
99
99
|
})) {
|
|
100
|
-
let e = `${
|
|
100
|
+
let e = `${m ?? ""}|${_ ?? ""}|${E ?? ""}`;
|
|
101
101
|
X.current !== e && (X.current = e, t.setWorkspaceToken(null));
|
|
102
102
|
}
|
|
103
103
|
}, [
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
104
|
+
m,
|
|
105
|
+
_,
|
|
106
|
+
E
|
|
107
107
|
]);
|
|
108
|
-
let
|
|
108
|
+
let te = n(async () => {
|
|
109
109
|
if (B.current) return B.current;
|
|
110
|
-
let t = e.getState(), n =
|
|
111
|
-
return !n ||
|
|
110
|
+
let t = e.getState(), n = x();
|
|
111
|
+
return !n || g(n) ? [] : (t.setLoadingOrganizations(!0), z(null), B.current = (async () => {
|
|
112
112
|
try {
|
|
113
|
-
let r = U.current ?? t.currentOrganizationId, i = await
|
|
113
|
+
let r = U.current ?? t.currentOrganizationId, i = r ? await (async () => {
|
|
114
|
+
let [e, t] = await Promise.all([c({
|
|
115
|
+
gateway: "global",
|
|
116
|
+
query: u,
|
|
117
|
+
authToken: n,
|
|
118
|
+
baseUrl: G
|
|
119
|
+
}), c({
|
|
120
|
+
gateway: "global",
|
|
121
|
+
query: d,
|
|
122
|
+
authToken: n,
|
|
123
|
+
baseUrl: G
|
|
124
|
+
})]);
|
|
125
|
+
return {
|
|
126
|
+
data: e.data?.myOrganizations ? {
|
|
127
|
+
myOrganizations: e.data.myOrganizations,
|
|
128
|
+
...t.data?.workspaces ? { workspaces: t.data.workspaces } : {}
|
|
129
|
+
} : null,
|
|
130
|
+
errors: [...e.errors ?? [], ...t.errors ?? []]
|
|
131
|
+
};
|
|
132
|
+
})() : await c({
|
|
114
133
|
gateway: "global",
|
|
115
|
-
query:
|
|
116
|
-
variables: void 0,
|
|
134
|
+
query: u,
|
|
117
135
|
authToken: n,
|
|
118
136
|
baseUrl: G
|
|
119
137
|
});
|
|
@@ -124,7 +142,7 @@ function D(s) {
|
|
|
124
142
|
baseUrl: G
|
|
125
143
|
})), i.errors?.length) {
|
|
126
144
|
let e = i.errors[0]?.message ?? "GraphQL error";
|
|
127
|
-
throw
|
|
145
|
+
throw b(i.errors) ? new y(e) : (t.workspaces.length === 0 && console.error("Failed to fetch organizations:", i.errors), Error(e));
|
|
128
146
|
}
|
|
129
147
|
let a = i.data?.myOrganizations?.items ?? [];
|
|
130
148
|
if (r && a.length === 0 && t.workspaces.length === 0) {
|
|
@@ -142,10 +160,10 @@ function D(s) {
|
|
|
142
160
|
} }
|
|
143
161
|
});
|
|
144
162
|
}
|
|
145
|
-
let o = a.length === 0 && t.workspaces.length > 0 ?
|
|
163
|
+
let o = a.length === 0 && t.workspaces.length > 0 ? S(t.workspaces) : [], s = o.length > 0 ? o : a;
|
|
146
164
|
t.setOrganizations(s);
|
|
147
|
-
let l = r,
|
|
148
|
-
if (l && !
|
|
165
|
+
let l = r, f = l && a.some((e) => e.id === l);
|
|
166
|
+
if (l && !f && a.length > 0 && (l = a[0].id, D({
|
|
149
167
|
organizationId: l,
|
|
150
168
|
workspaceId: null,
|
|
151
169
|
tenantId: null,
|
|
@@ -170,7 +188,7 @@ function D(s) {
|
|
|
170
188
|
tenantId: e[0].tenantId,
|
|
171
189
|
projectId: null
|
|
172
190
|
};
|
|
173
|
-
H.current ? (t.setCurrentWorkspaceId(e[0].id), t.setWorkspaceToken(null),
|
|
191
|
+
H.current ? (t.setCurrentWorkspaceId(e[0].id), t.setWorkspaceToken(null), D(n)) : t.currentWorkspaceId || (t.setCurrentWorkspaceId(e[0].id), D(n));
|
|
174
192
|
}
|
|
175
193
|
}
|
|
176
194
|
} catch {} finally {
|
|
@@ -179,10 +197,10 @@ function D(s) {
|
|
|
179
197
|
}
|
|
180
198
|
return s;
|
|
181
199
|
} catch (e) {
|
|
182
|
-
if (e instanceof
|
|
200
|
+
if (e instanceof y) return [];
|
|
183
201
|
let n = e instanceof Error ? e.message : "Failed to fetch organizations";
|
|
184
202
|
if (t.workspaces.length === 0 && console.error("Failed to fetch organizations:", e), z(n), t.workspaces.length > 0) {
|
|
185
|
-
let e =
|
|
203
|
+
let e = S(t.workspaces);
|
|
186
204
|
if (e.length > 0) return t.setOrganizations(e), t.currentOrganizationId || t.setCurrentOrganizationId(e[0].id), e;
|
|
187
205
|
}
|
|
188
206
|
return [];
|
|
@@ -190,11 +208,11 @@ function D(s) {
|
|
|
190
208
|
t.setLoadingOrganizations(!1), B.current = null;
|
|
191
209
|
}
|
|
192
210
|
})(), B.current);
|
|
193
|
-
}, [G,
|
|
211
|
+
}, [G, D]), Z = n(async (t) => {
|
|
194
212
|
let n = V.current.get(t);
|
|
195
213
|
if (n) return n;
|
|
196
|
-
let r = e.getState(), i =
|
|
197
|
-
if (!i ||
|
|
214
|
+
let r = e.getState(), i = x();
|
|
215
|
+
if (!i || g(i)) return [];
|
|
198
216
|
r.setLoadingWorkspaces(!0), z(null);
|
|
199
217
|
let a = (async () => {
|
|
200
218
|
try {
|
|
@@ -206,12 +224,12 @@ function D(s) {
|
|
|
206
224
|
});
|
|
207
225
|
if (e.data?.workspaces?.items && (e.data.workspaces.items = e.data.workspaces.items.filter((e) => e.organizationId === t)), e.errors?.length) {
|
|
208
226
|
let t = e.errors[0]?.message ?? "GraphQL error";
|
|
209
|
-
throw
|
|
227
|
+
throw b(e.errors) ? new y(t) : (console.error("Failed to fetch workspaces:", e.errors), Error(t));
|
|
210
228
|
}
|
|
211
229
|
let n = (e.data?.workspaces?.items ?? []).filter((e) => e.organizationId === t);
|
|
212
230
|
return r.setWorkspaces(n), n;
|
|
213
231
|
} catch (e) {
|
|
214
|
-
if (e instanceof
|
|
232
|
+
if (e instanceof y) return [];
|
|
215
233
|
let t = e instanceof Error ? e.message : "Failed to fetch workspaces";
|
|
216
234
|
return console.error("Failed to fetch workspaces:", e), z(t), [];
|
|
217
235
|
} finally {
|
|
@@ -220,8 +238,8 @@ function D(s) {
|
|
|
220
238
|
})();
|
|
221
239
|
return V.current.set(t, a), a;
|
|
222
240
|
}, [G]), Q = n(async (t, n, r) => {
|
|
223
|
-
let i = e.getState(), a =
|
|
224
|
-
if (!a ||
|
|
241
|
+
let i = e.getState(), a = x();
|
|
242
|
+
if (!a || g(a)) return {
|
|
225
243
|
success: !1,
|
|
226
244
|
error: "No valid access token available"
|
|
227
245
|
};
|
|
@@ -229,7 +247,7 @@ function D(s) {
|
|
|
229
247
|
try {
|
|
230
248
|
let e = await c({
|
|
231
249
|
gateway: "workspace",
|
|
232
|
-
query:
|
|
250
|
+
query: f,
|
|
233
251
|
variables: { input: {
|
|
234
252
|
organizationId: t,
|
|
235
253
|
...n && { workspaceId: n },
|
|
@@ -240,7 +258,7 @@ function D(s) {
|
|
|
240
258
|
});
|
|
241
259
|
if (e.errors?.length) {
|
|
242
260
|
let t = e.errors[0]?.message ?? "GraphQL error";
|
|
243
|
-
return
|
|
261
|
+
return b(e.errors) || console.error("Failed to issue workspace token:", e.errors), {
|
|
244
262
|
success: !1,
|
|
245
263
|
error: t
|
|
246
264
|
};
|
|
@@ -266,34 +284,34 @@ function D(s) {
|
|
|
266
284
|
};
|
|
267
285
|
}
|
|
268
286
|
}, [K]), $ = n(async () => {
|
|
269
|
-
let t = e.getState(), n =
|
|
270
|
-
if (!n ||
|
|
287
|
+
let t = e.getState(), n = x(), r = t.workspaceToken, i = t.currentWorkspaceId;
|
|
288
|
+
if (!n || g(n) || !r || !i) return [];
|
|
271
289
|
t.setLoadingProjects(!0), z(null);
|
|
272
290
|
try {
|
|
273
291
|
let e = await c({
|
|
274
292
|
gateway: "workspace",
|
|
275
|
-
query:
|
|
293
|
+
query: p,
|
|
276
294
|
authToken: n,
|
|
277
295
|
workspaceToken: r,
|
|
278
296
|
baseUrl: K
|
|
279
297
|
});
|
|
280
298
|
if (e.errors?.length) {
|
|
281
299
|
let t = e.errors[0]?.message ?? "GraphQL error";
|
|
282
|
-
throw
|
|
300
|
+
throw b(e.errors) ? new y(t) : (console.error("Failed to fetch projects:", e.errors), Error(t));
|
|
283
301
|
}
|
|
284
302
|
let i = e.data?.projects?.items ?? [];
|
|
285
303
|
return t.setProjects(i), i;
|
|
286
304
|
} catch (e) {
|
|
287
|
-
if (e instanceof
|
|
305
|
+
if (e instanceof y) return [];
|
|
288
306
|
let t = e instanceof Error ? e.message : "Failed to fetch projects";
|
|
289
307
|
return console.error("Failed to fetch projects:", e), z(t), [];
|
|
290
308
|
} finally {
|
|
291
309
|
t.setLoadingProjects(!1);
|
|
292
310
|
}
|
|
293
|
-
}, [K]),
|
|
311
|
+
}, [K]), ne = n(async (t) => {
|
|
294
312
|
let n = e.getState();
|
|
295
313
|
return n.setCurrentWorkspaceId(null), n.setWorkspaceToken(null), n.setProjects([]), n.setCurrentProjectId(null), n.setCurrentOrganizationId(t.id), await Z(t.id);
|
|
296
|
-
}, [Z]),
|
|
314
|
+
}, [Z]), re = n(async (t) => {
|
|
297
315
|
let n = e.getState();
|
|
298
316
|
if (n.setCurrentProjectId(null), n.setProjects([]), !t.organizationId) return console.error("Workspace missing organizationId:", t), {
|
|
299
317
|
success: !1,
|
|
@@ -306,9 +324,9 @@ function D(s) {
|
|
|
306
324
|
};
|
|
307
325
|
let i = await $();
|
|
308
326
|
if (i.length === 0) {
|
|
309
|
-
let t =
|
|
327
|
+
let t = x(), r = e.getState().workspaceToken;
|
|
310
328
|
if (t && r) {
|
|
311
|
-
let e = await
|
|
329
|
+
let e = await h({
|
|
312
330
|
authToken: t,
|
|
313
331
|
workspaceBaseUrl: K,
|
|
314
332
|
workspaceToken: r
|
|
@@ -324,9 +342,9 @@ function D(s) {
|
|
|
324
342
|
Q,
|
|
325
343
|
$,
|
|
326
344
|
K
|
|
327
|
-
]),
|
|
345
|
+
]), ie = n((t) => {
|
|
328
346
|
let n = e.getState();
|
|
329
|
-
n.setCurrentProjectId(t.id), n.workspaceToken && !
|
|
347
|
+
n.setCurrentProjectId(t.id), n.workspaceToken && !v(n.workspaceToken, {
|
|
330
348
|
workspaceId: n.currentWorkspaceId,
|
|
331
349
|
organizationId: n.currentOrganizationId,
|
|
332
350
|
projectId: t.id
|
|
@@ -349,49 +367,49 @@ function D(s) {
|
|
|
349
367
|
}, r = n(() => $()), i = n(() => {
|
|
350
368
|
let t = e.getState().currentOrganizationId;
|
|
351
369
|
return t ? Z(t) : Promise.resolve();
|
|
352
|
-
}), a =
|
|
370
|
+
}), a = O.onAny((t) => {
|
|
353
371
|
let n = t.name;
|
|
354
|
-
if (
|
|
355
|
-
let n =
|
|
372
|
+
if (C.has(n)) {
|
|
373
|
+
let n = T(t.payload), { currentWorkspaceId: i } = e.getState();
|
|
356
374
|
if (n && i && n !== i) return;
|
|
357
375
|
r();
|
|
358
376
|
return;
|
|
359
377
|
}
|
|
360
|
-
|
|
378
|
+
w.has(n) && i();
|
|
361
379
|
});
|
|
362
380
|
return () => {
|
|
363
381
|
t = !0, a();
|
|
364
382
|
};
|
|
365
383
|
}, [
|
|
366
|
-
|
|
384
|
+
O,
|
|
367
385
|
$,
|
|
368
386
|
Z
|
|
369
387
|
]), {
|
|
370
|
-
organizations:
|
|
371
|
-
workspaces:
|
|
388
|
+
organizations: k,
|
|
389
|
+
workspaces: M,
|
|
372
390
|
projects: I,
|
|
373
|
-
currentOrganizationId:
|
|
374
|
-
currentWorkspaceId:
|
|
391
|
+
currentOrganizationId: A,
|
|
392
|
+
currentWorkspaceId: N,
|
|
375
393
|
currentProjectId: L,
|
|
376
|
-
currentOrganization:
|
|
377
|
-
currentWorkspace:
|
|
394
|
+
currentOrganization: k.find((e) => e.id === A),
|
|
395
|
+
currentWorkspace: M.find((e) => e.id === N),
|
|
378
396
|
currentProject: I.find((e) => e.id === L),
|
|
379
|
-
workspaceToken:
|
|
380
|
-
isLoadingOrganizations:
|
|
397
|
+
workspaceToken: P,
|
|
398
|
+
isLoadingOrganizations: j,
|
|
381
399
|
isLoadingWorkspaces: F,
|
|
382
400
|
isLoadingProjects: R,
|
|
383
|
-
isLoading:
|
|
384
|
-
error:
|
|
385
|
-
fetchOrganizations:
|
|
401
|
+
isLoading: j || F || R,
|
|
402
|
+
error: ee,
|
|
403
|
+
fetchOrganizations: te,
|
|
386
404
|
fetchWorkspacesForOrg: Z,
|
|
387
405
|
issueWorkspaceToken: Q,
|
|
388
406
|
fetchProjects: $,
|
|
389
|
-
selectOrganization:
|
|
390
|
-
selectWorkspace:
|
|
391
|
-
selectProject:
|
|
407
|
+
selectOrganization: ne,
|
|
408
|
+
selectWorkspace: re,
|
|
409
|
+
selectProject: ie
|
|
392
410
|
};
|
|
393
411
|
}
|
|
394
|
-
function
|
|
412
|
+
function D(n) {
|
|
395
413
|
let i = e((e) => e.currentOrganizationId), a = e((e) => e.workspaces), o = e((e) => e.accessToken), s = e((e) => e.isLoadingWorkspaces), l = t(), u = n?.globalBaseUrl ?? l.globalBaseUrl, f = n?.disableWorkspaceSync ?? !1;
|
|
396
414
|
r(() => {
|
|
397
415
|
if (f || !i || !o || s) return;
|
|
@@ -421,10 +439,10 @@ function O(n) {
|
|
|
421
439
|
f
|
|
422
440
|
]);
|
|
423
441
|
}
|
|
424
|
-
function
|
|
425
|
-
let a = e((e) => e.currentWorkspaceId), o = e((e) => e.currentOrganizationId), s = e((e) => e.workspaces), l = e((e) => e.projects), u = e((e) => e.currentProjectId), d = e((e) => e.workspaceToken),
|
|
442
|
+
function O(n) {
|
|
443
|
+
let a = e((e) => e.currentWorkspaceId), o = e((e) => e.currentOrganizationId), s = e((e) => e.workspaces), l = e((e) => e.projects), u = e((e) => e.currentProjectId), d = e((e) => e.workspaceToken), m = e((e) => e.accessToken), _ = t(), y = n?.workspaceBaseUrl ?? _.workspaceBaseUrl, b = n?.disableProjectSync ?? !1, x = n?.skipProjectFetch ?? !1, S = i(!1), C = i(/* @__PURE__ */ new Map()), w = i(/* @__PURE__ */ new Map()), T = 3e4;
|
|
426
444
|
r(() => {
|
|
427
|
-
if (b || !a || !
|
|
445
|
+
if (b || !a || !m || S.current) return;
|
|
428
446
|
let t = w.current.get(a);
|
|
429
447
|
if (t && t.count >= 8 && Date.now() - t.lastFailureAt < T) return;
|
|
430
448
|
t && Date.now() - t.lastFailureAt >= T && w.current.delete(a);
|
|
@@ -432,12 +450,12 @@ function k(n) {
|
|
|
432
450
|
if (n && o && n.organizationId !== o) return;
|
|
433
451
|
let r = n?.organizationId ?? o;
|
|
434
452
|
if (!r) return;
|
|
435
|
-
let i = e.getState(),
|
|
453
|
+
let i = e.getState(), _ = !d || g(d) || !v(d, {
|
|
436
454
|
workspaceId: a,
|
|
437
455
|
organizationId: o,
|
|
438
456
|
projectId: u
|
|
439
457
|
}), E = l.some((e) => e.workspaceId === a);
|
|
440
|
-
if (E && !
|
|
458
|
+
if (E && !_) {
|
|
441
459
|
if (!i.currentProjectId) {
|
|
442
460
|
let e = l.find((e) => e.workspaceId === a);
|
|
443
461
|
e && i.setCurrentProjectId(e.id);
|
|
@@ -449,17 +467,17 @@ function k(n) {
|
|
|
449
467
|
let t = !1;
|
|
450
468
|
try {
|
|
451
469
|
let e = d;
|
|
452
|
-
if (
|
|
470
|
+
if (_) {
|
|
453
471
|
let t = await c({
|
|
454
472
|
gateway: "workspace",
|
|
455
|
-
query:
|
|
473
|
+
query: f,
|
|
456
474
|
variables: { input: {
|
|
457
475
|
organizationId: r,
|
|
458
476
|
workspaceId: a,
|
|
459
477
|
...u ? { projectId: u } : {}
|
|
460
478
|
} },
|
|
461
|
-
authToken:
|
|
462
|
-
baseUrl:
|
|
479
|
+
authToken: m,
|
|
480
|
+
baseUrl: y
|
|
463
481
|
});
|
|
464
482
|
if (t.data?.issueWorkspaceToken?.success && t.data.issueWorkspaceToken.token) e = t.data.issueWorkspaceToken.token, i.setWorkspaceToken(e);
|
|
465
483
|
else return;
|
|
@@ -467,17 +485,17 @@ function k(n) {
|
|
|
467
485
|
if (e && !E && !x) {
|
|
468
486
|
let t = await c({
|
|
469
487
|
gateway: "workspace",
|
|
470
|
-
query:
|
|
471
|
-
authToken:
|
|
488
|
+
query: p,
|
|
489
|
+
authToken: m,
|
|
472
490
|
workspaceToken: e,
|
|
473
|
-
baseUrl:
|
|
491
|
+
baseUrl: y
|
|
474
492
|
});
|
|
475
493
|
if (t.errors?.length) return;
|
|
476
494
|
let n = t.data?.projects?.items ?? [];
|
|
477
495
|
if (n.length === 0) {
|
|
478
|
-
let t = await
|
|
479
|
-
authToken:
|
|
480
|
-
workspaceBaseUrl:
|
|
496
|
+
let t = await h({
|
|
497
|
+
authToken: m,
|
|
498
|
+
workspaceBaseUrl: y,
|
|
481
499
|
workspaceToken: e
|
|
482
500
|
});
|
|
483
501
|
if (t) n = [t];
|
|
@@ -519,8 +537,8 @@ function k(n) {
|
|
|
519
537
|
l,
|
|
520
538
|
u,
|
|
521
539
|
d,
|
|
522
|
-
|
|
523
|
-
|
|
540
|
+
m,
|
|
541
|
+
y,
|
|
524
542
|
b,
|
|
525
543
|
x
|
|
526
544
|
]), r(() => {
|
|
@@ -531,6 +549,6 @@ function k(n) {
|
|
|
531
549
|
}, []);
|
|
532
550
|
}
|
|
533
551
|
//#endregion
|
|
534
|
-
export {
|
|
552
|
+
export { E as useContextSwitcherData, O as useProjectSyncEffect, D as useWorkspaceSyncEffect };
|
|
535
553
|
|
|
536
554
|
//# sourceMappingURL=useContextSwitcherData.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useContextSwitcherData.js","names":[],"sources":["../../../src/auth/hooks/useContextSwitcherData.ts"],"sourcesContent":["import { useCallback, useState, useEffect, useRef } from \"react\";\nimport {\n graphqlFetch,\n getStoredAuthToken,\n} from \"@burdenoff/fe-libs/shared/graphql\";\nimport { useActiveContext } from \"@burdenoff/fe-libs/shared/providers/shell/ActiveContextProvider\";\nimport { useEventBus } from \"@burdenoff/fe-libs/shared/events\";\nimport { useAuthStore } from \"../store/authStore\";\nimport type { Organization, Workspace, Project } from \"../types\";\nimport { resolveGatewayBaseUrls } from \"../utils/gatewayBaseUrls\";\n\n// =============================================================================\n// Hook Options\n// =============================================================================\n\nexport interface UseContextSwitcherDataOptions {\n /**\n * Optional Global API Gateway base URL override.\n * If not provided, uses GATEWAYS config from fe-libs.\n */\n globalBaseUrl?: string;\n /**\n * Optional Workspaces API Gateway base URL override.\n * If not provided, uses GATEWAYS config from fe-libs.\n */\n workspaceBaseUrl?: string;\n /** Disable initial organization/workspace bootstrap fetches */\n disableBootstrap?: boolean;\n /** Disable the workspace sync effect */\n disableWorkspaceSync?: boolean;\n /** Disable the project sync effect */\n disableProjectSync?: boolean;\n /** Only hydrate the workspace token; do not eagerly fetch projects */\n skipProjectFetch?: boolean;\n}\n\n// =============================================================================\n// GraphQL Response Types\n// =============================================================================\n\ninterface MyOrganizationsResponse {\n myOrganizations: {\n total: number;\n items: Organization[];\n };\n}\n\ninterface WorkspacesByOrgResponse {\n workspaces: {\n total: number;\n items: Workspace[];\n };\n}\n\ninterface IssueWorkspaceTokenResult {\n success: boolean;\n token: string | null;\n expiresAt: string | null;\n organizationId: string | null;\n workspaceId: string | null;\n projectId: string | null;\n scopes: string[] | null;\n error: {\n code: string;\n message: string;\n } | null;\n}\n\ninterface ProjectsResponse {\n projects: {\n total: number;\n items: Project[];\n };\n}\n\ninterface CreateProjectResponse {\n createProject: Project;\n}\n\n// =============================================================================\n// GraphQL Query/Mutation Strings\n// =============================================================================\n\nconst MY_ORGANIZATIONS_QUERY = `\n query MyOrganizations {\n myOrganizations {\n total\n items {\n id\n name\n slug\n tenantId\n description\n logo\n website\n status\n type\n createdAt\n updatedAt\n }\n }\n }\n`;\n\n// Both queries below historically used `workspaces(filter: $filter)` with\n// a `WorkspaceFilterInput` to fetch workspaces for a specific organization.\n// That Query field was removed/renamed in the global subgraph; calling it\n// now throws GRAPHQL_VALIDATION_FAILED (\"Cannot query field 'workspaces'\n// on type 'Query'\") which crashes the context switcher and cascades into a\n// \"Verifying workspace access...\" stuck-spinner on every Platform module\n// route (/billing, /support, /notifications, /devportal).\n//\n// The supported field is `myWorkspaces(limit, offset)` on the global\n// subgraph — self-scoped, returns the caller's workspaces across all\n// orgs. It does NOT accept a filter, so we fetch up to 100 of \"my\"\n// workspaces and let the existing downstream auto-pick logic filter by\n// organizationId client-side. The recovery path at line ~624 already\n// uses this exact aliased pattern; we're just promoting it to the\n// primary path.\nconst WORKSPACES_BY_ORG_QUERY = `\n query WorkspacesByOrg {\n workspaces: myWorkspaces(limit: 100) {\n total\n items {\n id\n name\n slug\n tenantId\n organizationId\n type\n status\n region\n createdAt\n updatedAt\n }\n }\n }\n`;\n\nconst CONTEXT_SWITCHER_BOOTSTRAP_QUERY = `\n query ContextSwitcherBootstrap {\n myOrganizations {\n total\n items {\n id\n name\n slug\n tenantId\n description\n logo\n website\n status\n type\n createdAt\n updatedAt\n }\n }\n workspaces: myWorkspaces(limit: 100) {\n total\n items {\n id\n name\n slug\n tenantId\n organizationId\n type\n status\n region\n createdAt\n updatedAt\n }\n }\n }\n`;\n\nconst ISSUE_WORKSPACE_TOKEN_MUTATION = `\n mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {\n issueWorkspaceToken(input: $input) {\n success\n token\n expiresAt\n organizationId\n workspaceId\n projectId\n scopes\n error {\n code\n message\n }\n }\n }\n`;\n\n// The workspace gateway exposes `myProjects` (public RBAC, caller-scoped to\n// the active workspace via x-workspace-id) and the privileged\n// `projects(filter)` (list:project). The header has no `list:project`\n// permission seeded for the typical operator, so the privileged form\n// returns FORBIDDEN even though the caller is a member of the workspace.\n// `myProjects` is the right field for \"give me the projects I can see in\n// this workspace\" — workspace scope is already established by the\n// workspace token + x-workspace-id header that we pass with the request.\nconst PROJECTS_QUERY = `\n query MyProjectsForContext {\n projects: myProjects {\n total\n items {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n }\n`;\n\nconst CREATE_DEFAULT_PROJECT_MUTATION = `\n mutation CreateDefaultProject($input: CreateProjectInput!) {\n createProject(input: $input) {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n`;\n\nasync function createDefaultProject({\n authToken,\n workspaceBaseUrl,\n workspaceToken,\n}: {\n authToken: string;\n workspaceBaseUrl: string;\n workspaceToken: string;\n}): Promise<Project | null> {\n const result = await graphqlFetch<CreateProjectResponse>({\n gateway: \"workspace\",\n query: CREATE_DEFAULT_PROJECT_MUTATION,\n variables: {\n input: {\n name: \"Default Project\",\n },\n },\n authToken,\n workspaceToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (result.errors?.length) {\n console.warn(\"Failed to create default project:\", result.errors);\n return null;\n }\n\n return result.data?.createProject ?? null;\n}\n\n// =============================================================================\n// Auth Helpers\n// =============================================================================\n\n/**\n * Check whether a JWT is expired (or within bufferMs of expiry).\n * Returns true if the token is expired, close to expiry, or malformed.\n */\nfunction isTokenExpired(token: string, bufferMs = 30_000): boolean {\n try {\n const payload = JSON.parse(atob(token.split(\".\")[1]));\n if (!payload.exp) return false;\n return payload.exp * 1000 < Date.now() + bufferMs;\n } catch {\n return true;\n }\n}\n\nfunction getWorkspaceTokenPayload(token: string): {\n workspaceId?: string;\n organizationId?: string;\n projectId?: string;\n exp?: number;\n} | null {\n try {\n const payload = JSON.parse(atob(token.split(\".\")[1]));\n return {\n workspaceId:\n typeof payload.workspaceId === \"string\"\n ? payload.workspaceId\n : undefined,\n organizationId:\n typeof payload.organizationId === \"string\"\n ? payload.organizationId\n : undefined,\n projectId:\n typeof payload.projectId === \"string\" ? payload.projectId : undefined,\n exp: typeof payload.exp === \"number\" ? payload.exp : undefined,\n };\n } catch {\n return null;\n }\n}\n\nfunction isWorkspaceTokenValidForContext(\n token: string | null | undefined,\n expected: {\n workspaceId?: string | null;\n organizationId?: string | null;\n projectId?: string | null;\n },\n): token is string {\n if (!token || isTokenExpired(token)) {\n return false;\n }\n\n const payload = getWorkspaceTokenPayload(token);\n if (!payload) {\n return false;\n }\n\n if (expected.workspaceId && payload.workspaceId !== expected.workspaceId) {\n return false;\n }\n\n if (\n expected.organizationId &&\n payload.organizationId !== expected.organizationId\n ) {\n return false;\n }\n\n if (expected.projectId && payload.projectId !== expected.projectId) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Custom error class for auth-related failures (expired token, unauthorized, etc.).\n * Used to distinguish auth errors in outer catch blocks so they can be\n * suppressed from console.error — they are expected during token refresh cycles\n * and do not indicate application bugs.\n */\nclass AuthError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * Detect whether a set of GraphQL errors are authentication-related.\n */\nfunction isAuthGraphQLError(\n errors: Array<{ message?: string; extensions?: { code?: string } }>,\n): boolean {\n return errors.some(\n (e) =>\n e.extensions?.code === \"UNAUTHENTICATED\" ||\n e.message?.toLowerCase().includes(\"unauthorized\") ||\n e.message?.toLowerCase().includes(\"not authenticated\"),\n );\n}\n\n/**\n * Resolve the best available access token:\n * 1. Try the zustand store token\n * 2. If expired, fall back to profile storage (may have been refreshed)\n * 3. Return null if no valid token is available\n */\nfunction resolveAccessToken(): string | null {\n const storeToken = useAuthStore.getState().accessToken;\n\n // If store token is valid (or has no exp claim), use it\n if (storeToken && !isTokenExpired(storeToken)) {\n return storeToken;\n }\n\n // Store token is expired or missing — try profile storage (may be fresher)\n const profileToken = getStoredAuthToken();\n if (profileToken && !isTokenExpired(profileToken)) {\n return profileToken;\n }\n\n // Both expired or missing — if store token exists at all, return it as a last\n // resort (the gateway will reject it and the useEffect will re-trigger after\n // token refresh). Returning null would silently swallow the first load.\n return storeToken;\n}\n\nfunction buildFallbackOrganizations(workspaces: Workspace[]): Organization[] {\n const uniqueOrgIds = Array.from(\n new Set(\n workspaces.flatMap((workspace) =>\n workspace.organizationId ? [workspace.organizationId] : [],\n ),\n ),\n );\n\n return uniqueOrgIds.map((organizationId, index) => ({\n id: organizationId,\n name:\n workspaces.find(\n (workspace) => workspace.organizationId === organizationId,\n )?.name || `Organization ${index + 1}`,\n slug: organizationId,\n tenantId:\n workspaces.find(\n (workspace) => workspace.organizationId === organizationId,\n )?.tenantId || \"\",\n }));\n}\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Hook for managing the context switcher data (organizations, workspaces, projects)\n *\n * Data flow:\n * 1. fetchOrganizations() - Get all orgs user has access to (Global Gateway)\n * 2. selectOrganization(org) - Set current org & fetch workspaces for that org\n * 3. selectWorkspace(ws) - Issue workspace token & fetch projects\n * 4. selectProject(proj) - Set current project\n *\n * All GraphQL calls go through graphqlFetch from fe-libs which automatically\n * resolves gateway URLs and injects auth + locale headers.\n *\n * @param options - Optional configuration (gateway base URL overrides)\n */\n// Domain events emitted by microfe-workspaces that should refresh the switcher's\n// cached lists. Module-scoped so they aren't reallocated on every effect run.\nconst PROJECT_REFRESH_EVENTS = new Set<string>([\n \"project.created\",\n \"project.updated\",\n \"project.deleted\",\n \"project.archived\",\n \"project.unarchived\",\n]);\nconst WORKSPACE_REFRESH_EVENTS = new Set<string>([\n \"workspace.created\",\n \"workspace.updated\",\n \"workspace.deleted\",\n \"workspace.archived\",\n \"workspace.reactivated\",\n]);\n\n// Safely read a string `workspaceId` off a cross-MFE event payload of unknown\n// shape, rather than trusting a bare cast (the payload is produced by another\n// MFE and could drift). Returns undefined when absent or not a string.\nfunction readEventWorkspaceId(payload: unknown): string | undefined {\n if (payload && typeof payload === \"object\" && \"workspaceId\" in payload) {\n const value = (payload as { workspaceId?: unknown }).workspaceId;\n return typeof value === \"string\" ? value : undefined;\n }\n return undefined;\n}\n\nexport function useContextSwitcherData(\n options?: UseContextSwitcherDataOptions,\n) {\n const {\n organizationId: activeOrganizationId,\n workspaceId: activeWorkspaceId,\n projectId: activeProjectId,\n setContext: setActiveContext,\n } = useActiveContext();\n\n const eventBus = useEventBus();\n\n // Use selectors for reactive state\n const organizations = useAuthStore((state) => state.organizations);\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const isLoadingOrganizations = useAuthStore(\n (state) => state.isLoadingOrganizations,\n );\n\n const workspaces = useAuthStore((state) => state.workspaces);\n const currentWorkspaceId = useAuthStore((state) => state.currentWorkspaceId);\n const workspaceToken = useAuthStore((state) => state.workspaceToken);\n const isLoadingWorkspaces = useAuthStore(\n (state) => state.isLoadingWorkspaces,\n );\n\n const projects = useAuthStore((state) => state.projects);\n const currentProjectId = useAuthStore((state) => state.currentProjectId);\n const isLoadingProjects = useAuthStore((state) => state.isLoadingProjects);\n\n // Local error state\n const [error, setError] = useState<string | null>(null);\n\n // Deduplication refs to prevent duplicate GraphQL calls\n const fetchOrganizationsPromiseRef = useRef<Promise<Organization[]> | null>(\n null,\n );\n const fetchWorkspacesPromisesRef = useRef<Map<string, Promise<Workspace[]>>>(\n new Map(),\n );\n\n // Stable refs for latest context values — avoids stale closures in callbacks\n // without adding them to useCallback dep arrays (which would recreate callbacks\n // on every context change and trigger spurious fetch re-runs).\n const activeWorkspaceIdRef = useRef(activeWorkspaceId);\n const activeOrganizationIdRef = useRef(activeOrganizationId);\n useEffect(() => {\n activeWorkspaceIdRef.current = activeWorkspaceId;\n activeOrganizationIdRef.current = activeOrganizationId;\n });\n\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const globalBaseUrl =\n options?.globalBaseUrl ?? resolvedBaseUrls.globalBaseUrl;\n const workspaceBaseUrl =\n options?.workspaceBaseUrl ?? resolvedBaseUrls.workspaceBaseUrl;\n\n // Refs to break feedback loops with the Header's \"store → URL\" sync effect.\n // Without these the pair can ping-pong: this effect writes (URL → store),\n // Header writes (store → URL), Zustand re-fires our subscribers, and React\n // hits \"Maximum update depth exceeded\" — especially when a downstream call\n // (workspace token issuance) returns 504 and leaves the two halves in\n // disagreement. The refs record the last value we pushed for each axis;\n // identical pushes are skipped so the loop has a hard floor.\n const lastAppliedOrgIdRef = useRef<string | null>(null);\n const lastAppliedWorkspaceIdRef = useRef<string | null>(null);\n const lastAppliedProjectIdRef = useRef<string | null>(null);\n const lastClearedTokenContextRef = useRef<string | null>(null);\n\n useEffect(() => {\n const store = useAuthStore.getState();\n\n if (\n activeOrganizationId &&\n activeOrganizationId !== store.currentOrganizationId &&\n activeOrganizationId !== lastAppliedOrgIdRef.current\n ) {\n lastAppliedOrgIdRef.current = activeOrganizationId;\n store.setCurrentOrganizationId(activeOrganizationId);\n if (\n store.workspaces.length > 0 &&\n !store.workspaces.some(\n (workspace) => workspace.organizationId === activeOrganizationId,\n )\n ) {\n store.setWorkspaces([]);\n }\n }\n\n if (\n activeWorkspaceId &&\n activeWorkspaceId !== store.currentWorkspaceId &&\n activeWorkspaceId !== lastAppliedWorkspaceIdRef.current\n ) {\n lastAppliedWorkspaceIdRef.current = activeWorkspaceId;\n store.setCurrentWorkspaceId(activeWorkspaceId);\n if (\n store.projects.length > 0 &&\n !store.projects.some(\n (project) => project.workspaceId === activeWorkspaceId,\n )\n ) {\n store.setProjects([]);\n store.setCurrentProjectId(null);\n }\n }\n\n if (\n activeProjectId &&\n activeProjectId !== store.currentProjectId &&\n activeProjectId !== lastAppliedProjectIdRef.current\n ) {\n lastAppliedProjectIdRef.current = activeProjectId;\n store.setCurrentProjectId(activeProjectId);\n }\n\n if (\n store.workspaceToken &&\n !isWorkspaceTokenValidForContext(store.workspaceToken, {\n workspaceId: activeWorkspaceId,\n organizationId: activeOrganizationId,\n projectId: activeProjectId,\n })\n ) {\n // Clear-token-once-per-context guard: when the upstream gateway is\n // flaky (504s during workspace token issuance) the surrounding state\n // machine can oscillate between \"got token but invalid\" and \"clearing\n // token\". The downstream re-issue path then loops. Only clear once per\n // (org, ws, proj) tuple — a successful re-issue resets the ref via\n // setWorkspaceToken landing a new token for the same context.\n const ctxKey = `${activeOrganizationId ?? \"\"}|${activeWorkspaceId ?? \"\"}|${activeProjectId ?? \"\"}`;\n if (lastClearedTokenContextRef.current !== ctxKey) {\n lastClearedTokenContextRef.current = ctxKey;\n store.setWorkspaceToken(null);\n }\n }\n }, [activeOrganizationId, activeWorkspaceId, activeProjectId]);\n\n // ===========================================================================\n // Fetch Organizations (Global Gateway)\n // ===========================================================================\n\n const fetchOrganizations = useCallback(async (): Promise<Organization[]> => {\n // Deduplicate: if a fetch is already in progress, return the same promise\n if (fetchOrganizationsPromiseRef.current) {\n return fetchOrganizationsPromiseRef.current;\n }\n\n const store = useAuthStore.getState();\n const token = resolveAccessToken();\n\n if (!token) {\n // Not an error — user may not be authenticated yet (e.g., page load before login).\n // The useEffect in Header.tsx will re-trigger when accessToken becomes available.\n return [];\n }\n\n // If the token is clearly expired and no fresh fallback was found, skip the\n // doomed request. The useEffect in Header.tsx re-triggers when the auth\n // provider refreshes the token and updates accessToken in the store.\n if (isTokenExpired(token)) {\n return [];\n }\n\n store.setLoadingOrganizations(true);\n setError(null);\n\n // Store the promise for deduplication before starting\n fetchOrganizationsPromiseRef.current = (async () => {\n try {\n const initialTargetOrgId =\n activeOrganizationIdRef.current ?? store.currentOrganizationId;\n let result = await graphqlFetch<\n MyOrganizationsResponse & Partial<WorkspacesByOrgResponse>\n >({\n gateway: \"global\",\n query: initialTargetOrgId\n ? CONTEXT_SWITCHER_BOOTSTRAP_QUERY\n : MY_ORGANIZATIONS_QUERY,\n // Both queries are now parameter-less (the legacy `filter` arg\n // was for the removed `workspaces(filter:)` field; `myWorkspaces`\n // doesn't accept it). Downstream code filters by organizationId\n // client-side.\n variables: undefined,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n\n // Self-heal stale-URL case: bootstrap query embeds\n // workspaces(filter: {organizationId: <urlOrg>}) — when the user\n // isn't a member of that org (URL was bookmarked from a different\n // tenant, org was deleted, etc.), the workspaces resolver throws\n // FORBIDDEN which blanks the entire data block, masking\n // myOrganizations as the visible error. Retry with the simpler\n // MY_ORGANIZATIONS_QUERY so the operator sees their actual orgs\n // and the URL params get corrected on next render.\n if (\n initialTargetOrgId &&\n result.errors?.length &&\n result.errors.some(\n (e) =>\n e?.extensions?.code === \"FORBIDDEN\" ||\n /not a member of this organization/i.test(e?.message ?? \"\") ||\n // Public gateway often drops the underlying FORBIDDEN error\n // and replaces it with the schema-level non-null violation\n // (\"Cannot return null for non-nullable field Query.myOrganizations\").\n // That happens when ANY field in the query throws — workspaces\n // here — and data:null cascades up. Treat that pattern as a\n // signal to retry without the workspaces filter.\n /Cannot return null for non-nullable field Query\\.myOrganizations/i.test(\n e?.message ?? \"\",\n ),\n )\n ) {\n // Fetch myOrganizations + ALL workspaces (no filter) so the\n // downstream auto-pick logic still has a workspace list to seed\n // context from. If we only refetched myOrganizations, the page\n // would render but every workspace-scoped query would fail with\n // \"Select a workspace…\".\n result = await graphqlFetch<\n MyOrganizationsResponse & Partial<WorkspacesByOrgResponse>\n >({\n gateway: \"global\",\n query: `\n query ContextSwitcherRecover {\n myOrganizations {\n total\n items { id name slug tenantId description logo website status type createdAt updatedAt }\n }\n workspaces: myWorkspaces {\n total\n items { id name slug tenantId organizationId type status region createdAt updatedAt }\n }\n }\n `,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n }\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n // Auth errors are expected during token refresh cycles — throw AuthError\n // so the outer catch can suppress console.error.\n throw new AuthError(errorMessage);\n }\n if (store.workspaces.length === 0) {\n console.error(\"Failed to fetch organizations:\", result.errors);\n }\n throw new Error(errorMessage);\n }\n\n let orgs: Organization[] = result.data?.myOrganizations?.items ?? [];\n\n // Stale-context recovery: bootstrap query was filtered by\n // initialTargetOrgId, so when the URL/persisted org doesn't belong to\n // this user the response is empty. Re-fetch the unfiltered list of\n // *all* orgs the user can access so the guard below can pick a real\n // default. Skip the recovery when no target was set (already\n // unfiltered) or when workspaces are already in the store (the\n // existing fallback path covers that case).\n if (\n initialTargetOrgId &&\n orgs.length === 0 &&\n store.workspaces.length === 0\n ) {\n const recovery = await graphqlFetch<MyOrganizationsResponse>({\n gateway: \"global\",\n query: MY_ORGANIZATIONS_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n if (!recovery.errors?.length) {\n orgs = recovery.data?.myOrganizations?.items ?? [];\n // discard the filtered workspaces payload — it was for the\n // ghost org and would only mislead the workspace selector below.\n result = {\n ...recovery,\n data: {\n myOrganizations: recovery.data?.myOrganizations ?? {\n items: [],\n total: 0,\n },\n },\n };\n } else {\n // Surface the failure so a user reporting \"blank org list\" has\n // something to grep for in the console. We still fall through —\n // the guard below either picks from a fallback (workspaces in\n // store) or no-ops, leaving the existing error path in place.\n console.warn(\n \"[ContextSwitcher] Stale-context recovery failed:\",\n recovery.errors,\n );\n }\n }\n\n const fallbackOrganizations =\n orgs.length === 0 && store.workspaces.length > 0\n ? buildFallbackOrganizations(store.workspaces)\n : [];\n const effectiveOrganizations =\n fallbackOrganizations.length > 0 ? fallbackOrganizations : orgs;\n\n store.setOrganizations(effectiveOrganizations);\n\n // Determine which organization to use for workspace fetching\n let targetOrgId = initialTargetOrgId;\n\n // Stale-context guard: if the persisted/URL org isn't in the user's\n // accessible orgs, fall back to the first available one and clear the\n // stale workspace/project so they get re-derived. Without this, URL\n // params like ?org=<ghost-id> from a prior session leak into the new\n // user's request headers and cause \"Authentication required\" /\n // \"not a member\" errors at every subgraph.\n //\n // Check against `orgs` (freshly returned from the API in this same\n // closure) rather than `effectiveOrganizations`, which can fall back\n // to ids derived from `store.workspaces` — that fallback path could\n // contain stale ghost orgIds and mask the guard.\n const targetOrgIsAccessible =\n targetOrgId && orgs.some((org) => org.id === targetOrgId);\n if (targetOrgId && !targetOrgIsAccessible && orgs.length > 0) {\n targetOrgId = orgs[0].id;\n setActiveContext({\n organizationId: targetOrgId,\n workspaceId: null,\n tenantId: null,\n projectId: null,\n });\n store.setWorkspaces([]);\n store.setProjects([]);\n store.setCurrentWorkspaceId(null);\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n }\n\n if (targetOrgId && targetOrgId !== store.currentOrganizationId) {\n store.setCurrentOrganizationId(targetOrgId);\n }\n\n // Auto-select first organization if none is selected\n if (effectiveOrganizations.length > 0 && !targetOrgId) {\n store.setCurrentOrganizationId(effectiveOrganizations[0].id);\n targetOrgId = effectiveOrganizations[0].id;\n }\n\n // Fetch workspaces for the selected/auto-selected org if:\n // 1. We have a target org (either auto-selected or persisted from localStorage)\n // 2. AND workspaces array is empty (not persisted, or cleared)\n // This handles both initial login AND page refresh scenarios.\n // Read from useAuthStore.getState() rather than the captured `store`\n // snapshot so we see the post-guard cleared value when the org guard\n // above fired (the local `store.workspaces` ref is stale after\n // setWorkspaces([])).\n if (targetOrgId && useAuthStore.getState().workspaces.length === 0) {\n store.setLoadingWorkspaces(true);\n try {\n // myWorkspaces returns ALL workspaces the user is a member of\n // across every org. Filter to the target org client-side here.\n const bootstrappedWorkspaces =\n initialTargetOrgId === targetOrgId\n ? result.data?.workspaces?.items?.filter(\n (w) => w.organizationId === targetOrgId,\n )\n : undefined;\n const ws = bootstrappedWorkspaces\n ? (bootstrappedWorkspaces as Workspace[])\n : await graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n }).then((wsResult) =>\n wsResult.errors?.length\n ? null\n : (wsResult.data?.workspaces?.items ?? []).filter(\n (w) => w.organizationId === targetOrgId,\n ),\n );\n\n if (ws) {\n store.setWorkspaces(ws);\n const persistedWorkspace = activeWorkspaceIdRef.current\n ? ws.find(\n (workspace) =>\n workspace.id === activeWorkspaceIdRef.current,\n )\n : null;\n\n if (persistedWorkspace) {\n store.setCurrentWorkspaceId(persistedWorkspace.id);\n } else if (ws.length > 0) {\n const nextActiveContext = {\n organizationId: targetOrgId,\n workspaceId: ws[0].id,\n tenantId: ws[0].tenantId,\n projectId: null,\n };\n\n if (activeWorkspaceIdRef.current) {\n // Stale-context guard: URL/persisted workspace ID is not in\n // the user's accessible workspaces for the active org. Fall\n // back to the first workspace and clear the stale URL param\n // so subsequent requests don't carry the ghost ID.\n store.setCurrentWorkspaceId(ws[0].id);\n store.setWorkspaceToken(null);\n setActiveContext(nextActiveContext);\n } else if (!store.currentWorkspaceId) {\n // Auto-select first workspace only if none is currently selected\n // (preserves selection from completeAuthFlow or persistence if applicable)\n store.setCurrentWorkspaceId(ws[0].id);\n setActiveContext(nextActiveContext);\n }\n }\n }\n } catch {\n // Non-critical — user can still select workspace manually\n } finally {\n store.setLoadingWorkspaces(false);\n }\n }\n\n return effectiveOrganizations;\n } catch (err) {\n // Auth errors are expected during token refresh / page load cycles.\n // Suppress from console.error — the useEffect will re-trigger when the\n // auth provider refreshes the token.\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch organizations\";\n if (store.workspaces.length === 0) {\n console.error(\"Failed to fetch organizations:\", err);\n }\n setError(message);\n\n if (store.workspaces.length > 0) {\n const fallbackOrganizations = buildFallbackOrganizations(\n store.workspaces,\n );\n if (fallbackOrganizations.length > 0) {\n store.setOrganizations(fallbackOrganizations);\n if (!store.currentOrganizationId) {\n store.setCurrentOrganizationId(fallbackOrganizations[0].id);\n }\n return fallbackOrganizations;\n }\n }\n\n return [];\n } finally {\n store.setLoadingOrganizations(false);\n fetchOrganizationsPromiseRef.current = null;\n }\n })();\n\n return fetchOrganizationsPromiseRef.current;\n }, [globalBaseUrl, setActiveContext]);\n\n // ===========================================================================\n // Fetch Workspaces for Organization (Global Gateway)\n // ===========================================================================\n\n const fetchWorkspacesForOrg = useCallback(\n async (organizationId: string): Promise<Workspace[]> => {\n // Deduplicate: if a fetch for this org is already in progress, return the same promise\n const existingPromise =\n fetchWorkspacesPromisesRef.current.get(organizationId);\n if (existingPromise) {\n return existingPromise;\n }\n\n const store = useAuthStore.getState();\n const token = resolveAccessToken();\n\n if (!token || isTokenExpired(token)) {\n return [];\n }\n\n store.setLoadingWorkspaces(true);\n setError(null);\n\n // Store the promise for deduplication before starting\n const fetchPromise = (async () => {\n try {\n const result = await graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n // myWorkspaces returns workspaces across all the user's orgs;\n // filter to the requested org before handing to downstream.\n if (result.data?.workspaces?.items) {\n result.data.workspaces.items = result.data.workspaces.items.filter(\n (w) => w.organizationId === organizationId,\n );\n }\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n throw new AuthError(errorMessage);\n }\n console.error(\"Failed to fetch workspaces:\", result.errors);\n throw new Error(errorMessage);\n }\n\n // `myWorkspaces` returns every workspace the caller can see across\n // all of their orgs/tenants. The store key is per-org (selecting\n // org X then opening the dropdown should only show X's workspaces),\n // so we filter down to the requested org here. The dropdown filter\n // in ContextSwitcher.tsx is a defence-in-depth — without this\n // narrowing the store would briefly hold the caller's other-org\n // workspaces and the auto-pick logic (lines below) might select\n // one of them as the default.\n const allWs: Workspace[] = result.data?.workspaces?.items ?? [];\n const ws = allWs.filter((w) => w.organizationId === organizationId);\n store.setWorkspaces(ws);\n return ws;\n } catch (err) {\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch workspaces\";\n console.error(\"Failed to fetch workspaces:\", err);\n setError(message);\n return [];\n } finally {\n store.setLoadingWorkspaces(false);\n fetchWorkspacesPromisesRef.current.delete(organizationId);\n }\n })();\n\n fetchWorkspacesPromisesRef.current.set(organizationId, fetchPromise);\n return fetchPromise;\n },\n [globalBaseUrl],\n );\n\n // ===========================================================================\n // Issue Workspace Token (Workspace Gateway - wspace-auth-svc)\n // ===========================================================================\n\n const issueWorkspaceToken = useCallback(\n async (\n organizationId: string,\n workspaceId?: string,\n projectId?: string | null,\n ): Promise<{\n success: boolean;\n token?: string;\n resolvedWorkspaceId?: string;\n error?: string;\n }> => {\n const store = useAuthStore.getState();\n const authToken = resolveAccessToken();\n\n if (!authToken || isTokenExpired(authToken)) {\n return { success: false, error: \"No valid access token available\" };\n }\n\n setError(null);\n\n try {\n const result = await graphqlFetch<{\n issueWorkspaceToken: IssueWorkspaceTokenResult;\n }>({\n gateway: \"workspace\",\n query: ISSUE_WORKSPACE_TOKEN_MUTATION,\n variables: {\n input: {\n organizationId,\n ...(workspaceId && { workspaceId }),\n ...(projectId && { projectId }),\n },\n },\n authToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (!isAuthGraphQLError(result.errors)) {\n console.error(\"Failed to issue workspace token:\", result.errors);\n }\n return { success: false, error: errorMessage };\n }\n\n const tokenResult = result.data?.issueWorkspaceToken;\n\n if (tokenResult?.success && tokenResult.token) {\n const resolvedWsId = tokenResult.workspaceId || workspaceId;\n if (resolvedWsId) {\n store.setCurrentWorkspaceId(resolvedWsId);\n }\n store.setWorkspaceToken(tokenResult.token);\n return {\n success: true,\n token: tokenResult.token,\n resolvedWorkspaceId: resolvedWsId || undefined,\n };\n }\n\n return {\n success: false,\n error:\n tokenResult?.error?.message ?? \"Failed to issue workspace token\",\n };\n } catch (err) {\n const message =\n err instanceof Error\n ? err.message\n : \"Failed to issue workspace token\";\n console.error(\"Failed to issue workspace token:\", err);\n setError(message);\n return { success: false, error: message };\n }\n },\n [workspaceBaseUrl],\n );\n\n // ===========================================================================\n // Fetch Projects (Workspace Gateway - requires workspace token)\n // ===========================================================================\n\n const fetchProjects = useCallback(async (): Promise<Project[]> => {\n const store = useAuthStore.getState();\n const authToken = resolveAccessToken();\n const wsToken = store.workspaceToken;\n const workspaceId = store.currentWorkspaceId;\n\n if (!authToken || isTokenExpired(authToken)) {\n return [];\n }\n\n if (!wsToken) {\n return [];\n }\n\n if (!workspaceId) {\n return [];\n }\n\n store.setLoadingProjects(true);\n setError(null);\n\n try {\n const result = await graphqlFetch<ProjectsResponse>({\n gateway: \"workspace\",\n query: PROJECTS_QUERY,\n authToken,\n workspaceToken: wsToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n throw new AuthError(errorMessage);\n }\n console.error(\"Failed to fetch projects:\", result.errors);\n throw new Error(errorMessage);\n }\n\n const projs: Project[] = result.data?.projects?.items ?? [];\n store.setProjects(projs);\n return projs;\n } catch (err) {\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch projects\";\n console.error(\"Failed to fetch projects:\", err);\n setError(message);\n return [];\n } finally {\n store.setLoadingProjects(false);\n }\n }, [workspaceBaseUrl]);\n\n // ===========================================================================\n // High-Level Selection Actions\n // ===========================================================================\n\n const selectOrganization = useCallback(\n async (org: Organization): Promise<Workspace[]> => {\n const store = useAuthStore.getState();\n\n store.setCurrentWorkspaceId(null);\n store.setWorkspaceToken(null);\n store.setProjects([]);\n store.setCurrentProjectId(null);\n store.setCurrentOrganizationId(org.id);\n\n const ws = await fetchWorkspacesForOrg(org.id);\n return ws;\n },\n [fetchWorkspacesForOrg],\n );\n\n const selectWorkspace = useCallback(\n async (\n workspace: Workspace,\n ): Promise<{\n success: boolean;\n projects?: Project[];\n error?: string;\n }> => {\n const store = useAuthStore.getState();\n\n store.setCurrentProjectId(null);\n store.setProjects([]);\n\n if (!workspace.organizationId) {\n console.error(\"Workspace missing organizationId:\", workspace);\n return {\n success: false,\n error: \"Workspace is missing organizationId\",\n };\n }\n\n const tokenResult = await issueWorkspaceToken(\n workspace.organizationId,\n workspace.id,\n );\n\n if (!tokenResult.success) {\n return { success: false, error: tokenResult.error };\n }\n\n let projs = await fetchProjects();\n if (projs.length === 0) {\n const authToken = resolveAccessToken();\n const workspaceToken = useAuthStore.getState().workspaceToken;\n if (authToken && workspaceToken) {\n const defaultProject = await createDefaultProject({\n authToken,\n workspaceBaseUrl,\n workspaceToken,\n });\n if (defaultProject) {\n projs = [defaultProject];\n store.setProjects(projs);\n }\n }\n }\n\n if (projs.length > 0) {\n store.setCurrentProjectId(projs[0]!.id);\n }\n\n return { success: true, projects: projs };\n },\n [issueWorkspaceToken, fetchProjects, workspaceBaseUrl],\n );\n\n const selectProject = useCallback((project: Project): void => {\n const store = useAuthStore.getState();\n store.setCurrentProjectId(project.id);\n if (\n store.workspaceToken &&\n !isWorkspaceTokenValidForContext(store.workspaceToken, {\n workspaceId: store.currentWorkspaceId,\n organizationId: store.currentOrganizationId,\n projectId: project.id,\n })\n ) {\n store.setWorkspaceToken(null);\n }\n }, []);\n\n // ===========================================================================\n // Cross-MFE refresh: keep the switcher lists current when another MFE mutates\n // org/workspace/project entities. microfe-workspaces emits these domain events\n // on the shared event bus (e.g. on project rename); without this the switcher\n // keeps showing the stale cached name until a full page reload.\n // ===========================================================================\n\n useEffect(() => {\n let cancelled = false;\n\n // Coalesce a refetch into a single in-flight run with one trailing re-run,\n // so a burst of events collapses to one request (+ one trailing) instead of\n // fanning out or being swallowed by a downstream per-key dedupe. The flag is\n // cleared on cleanup so nothing fires after the subscription is torn down.\n const makeCoalescedRefetch = (run: () => Promise<unknown>) => {\n let running = false;\n let queued = false;\n const trigger = () => {\n if (cancelled) return;\n if (running) {\n queued = true;\n return;\n }\n running = true;\n void run().finally(() => {\n running = false;\n if (!cancelled && queued) {\n queued = false;\n trigger();\n }\n });\n };\n return trigger;\n };\n\n const refreshProjects = makeCoalescedRefetch(() => fetchProjects());\n const refreshWorkspaces = makeCoalescedRefetch(() => {\n const orgId = useAuthStore.getState().currentOrganizationId;\n return orgId ? fetchWorkspacesForOrg(orgId) : Promise.resolve();\n });\n\n // Custom domain events (not in BurdenoffEventName) flow through `onAny`.\n const unsubscribe = eventBus.onAny((event) => {\n // Custom event names aren't in the BurdenoffEventName union; compare as string.\n const eventName: string = event.name;\n\n if (PROJECT_REFRESH_EVENTS.has(eventName)) {\n const eventWorkspaceId = readEventWorkspaceId(event.payload);\n const { currentWorkspaceId } = useAuthStore.getState();\n // Only refetch when the event targets the workspace currently in\n // context (events without a workspace id are treated as relevant).\n if (\n eventWorkspaceId &&\n currentWorkspaceId &&\n eventWorkspaceId !== currentWorkspaceId\n ) {\n return;\n }\n // Refetch only — a deleted project simply drops out of the list, and\n // `currentProject` resolves to undefined for it. Clearing the selection\n // here would race ActiveContext / the project sync effect (the real\n // source of truth), so we leave selection reconciliation to them.\n refreshProjects();\n return;\n }\n\n if (WORKSPACE_REFRESH_EVENTS.has(eventName)) {\n refreshWorkspaces();\n }\n });\n\n return () => {\n cancelled = true;\n unsubscribe();\n };\n }, [eventBus, fetchProjects, fetchWorkspacesForOrg]);\n\n // ===========================================================================\n // Get Current Items\n // ===========================================================================\n\n const currentOrganization = organizations.find(\n (org) => org.id === currentOrganizationId,\n );\n const currentWorkspace = workspaces.find(\n (ws) => ws.id === currentWorkspaceId,\n );\n const currentProject = projects.find((proj) => proj.id === currentProjectId);\n\n // ===========================================================================\n // Return Hook API\n // ===========================================================================\n\n return {\n organizations,\n workspaces,\n projects,\n\n currentOrganizationId,\n currentWorkspaceId,\n currentProjectId,\n\n currentOrganization,\n currentWorkspace,\n currentProject,\n\n workspaceToken,\n\n isLoadingOrganizations,\n isLoadingWorkspaces,\n isLoadingProjects,\n isLoading:\n isLoadingOrganizations || isLoadingWorkspaces || isLoadingProjects,\n\n error,\n\n fetchOrganizations,\n fetchWorkspacesForOrg,\n issueWorkspaceToken,\n fetchProjects,\n\n selectOrganization,\n selectWorkspace,\n selectProject,\n };\n}\n\n/**\n * Hook to reactively ensure workspaces are synced with the current organization.\n *\n * This handles edge cases where the organization changes but workspaces\n * from a different org are still in the store (e.g., stale data, race conditions).\n *\n * Usage:\n * ```tsx\n * import { useWorkspaceSyncEffect } from '@burdenoff/microfe-auth';\n *\n * function MyComponent() {\n * useWorkspaceSyncEffect(); // Ensures workspaces stay in sync\n * // ...\n * }\n * ```\n */\nexport function useWorkspaceSyncEffect(\n options?: UseContextSwitcherDataOptions,\n) {\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const workspaces = useAuthStore((state) => state.workspaces);\n const accessToken = useAuthStore((state) => state.accessToken);\n const isLoadingWorkspaces = useAuthStore(\n (state) => state.isLoadingWorkspaces,\n );\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const globalBaseUrl =\n options?.globalBaseUrl ?? resolvedBaseUrls.globalBaseUrl;\n const disableWorkspaceSync = options?.disableWorkspaceSync ?? false;\n\n useEffect(() => {\n if (disableWorkspaceSync) return;\n // Skip if no org selected, no token, or already loading\n if (!currentOrganizationId || !accessToken || isLoadingWorkspaces) return;\n\n // Check if any workspace matches the current org\n const hasMatchingWorkspaces = workspaces.some(\n (ws) => ws.organizationId === currentOrganizationId,\n );\n\n // If workspaces exist but none match current org, we need to refetch\n // This can happen in edge cases with stale data or race conditions\n if (workspaces.length > 0 && !hasMatchingWorkspaces) {\n const store = useAuthStore.getState();\n store.setLoadingWorkspaces(true);\n\n // Inline fetch to avoid circular dependency with useContextSwitcherData\n graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: accessToken,\n baseUrl: globalBaseUrl,\n })\n .then((result) => {\n // myWorkspaces returns ALL my workspaces; filter to current org\n // client-side (the old server-side filter no longer exists).\n if (result.data?.workspaces?.items) {\n result.data.workspaces.items = result.data.workspaces.items.filter(\n (w) => w.organizationId === currentOrganizationId,\n );\n }\n if (!result.errors?.length) {\n const allWs: Workspace[] = result.data?.workspaces?.items ?? [];\n // Same per-org narrowing as fetchWorkspacesForOrg — see the\n // comment there for why we don't just dump the full caller-\n // visible list into the store.\n const ws = allWs.filter(\n (w) => w.organizationId === currentOrganizationId,\n );\n store.setWorkspaces(ws);\n }\n })\n .catch(() => {\n // Silent fail - user can manually refresh or select org again\n })\n .finally(() => {\n store.setLoadingWorkspaces(false);\n });\n }\n }, [\n currentOrganizationId,\n workspaces,\n accessToken,\n isLoadingWorkspaces,\n globalBaseUrl,\n disableWorkspaceSync,\n ]);\n}\n\n/**\n * Hook to reactively ensure projects are loaded when a workspace is selected.\n *\n * This handles the case where a workspace is auto-selected (from URL/localStorage)\n * but projects haven't been fetched yet. It will:\n * 1. Issue a workspace token if not present\n * 2. Fetch projects for the selected workspace\n *\n * Usage:\n * ```tsx\n * import { useProjectSyncEffect } from '@burdenoff/microfe-auth';\n *\n * function MyComponent() {\n * useProjectSyncEffect(); // Ensures projects are loaded for selected workspace\n * // ...\n * }\n * ```\n */\nexport function useProjectSyncEffect(options?: UseContextSwitcherDataOptions) {\n const currentWorkspaceId = useAuthStore((state) => state.currentWorkspaceId);\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const workspaces = useAuthStore((state) => state.workspaces);\n const projects = useAuthStore((state) => state.projects);\n const currentProjectId = useAuthStore((state) => state.currentProjectId);\n const workspaceToken = useAuthStore((state) => state.workspaceToken);\n const accessToken = useAuthStore((state) => state.accessToken);\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const workspaceBaseUrl =\n options?.workspaceBaseUrl ?? resolvedBaseUrls.workspaceBaseUrl;\n const disableProjectSync = options?.disableProjectSync ?? false;\n const skipProjectFetch = options?.skipProjectFetch ?? false;\n\n // Use refs to prevent the infinite loop caused by including loading/failure\n // state in the dependency array. Without these, the cycle is:\n // setLoadingProjects(true) -> dep change -> effect re-runs (guarded) ->\n // async completes -> setLoadingProjects(false) -> dep change ->\n // effect re-runs -> starts again -> INFINITE LOOP\n const syncInProgressRef = useRef(false);\n // Pending retry timer per workspace, so transient failures (e.g. RBAC lag\n // right after workspace creation) get an automatic second chance even if no\n // dependency change re-triggers the effect.\n const retryTimerRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(\n new Map(),\n );\n // Per-workspace failure tracker — caps retry attempts when project bootstrap\n // (token issue, list, or default-create) fails. Without this, a persistent\n // backend failure (e.g. cross-layer workspace not yet synced) causes the\n // effect to re-fire every render: list returns empty → create-default fails\n // → setProjects([]) → new array reference → effect re-runs → loop.\n //\n // We track both count AND lastFailureAt so we can honour a \"cool-down\" window:\n // after PROJECT_SYNC_FAILURE_COOLDOWN_MS has elapsed since the last failure,\n // the counter is treated as cleared so transient backend hiccups (e.g. RBAC\n // role propagation lag right after signup) don't permanently lock a workspace\n // out of the context dropdown — the original cause of marqueue §729.\n const projectSyncFailuresRef = useRef<\n Map<string, { count: number; lastFailureAt: number }>\n >(new Map());\n const PROJECT_SYNC_MAX_FAILURES = 8;\n const PROJECT_SYNC_FAILURE_COOLDOWN_MS = 30_000;\n useEffect(() => {\n if (disableProjectSync) return;\n // Skip if no workspace selected or no access token\n if (!currentWorkspaceId || !accessToken) return;\n\n // Skip if a sync is already in progress (ref-based guard avoids dep loop)\n if (syncInProgressRef.current) return;\n\n // Stop retrying once this workspace has failed too many times in a row.\n // Counter is reset on success, on workspace switch (different key), by\n // an explicit user retry path (e.g. selectWorkspace), or after the\n // cool-down window has elapsed since the last failure (so transient\n // backend issues don't permanently wedge the dropdown).\n const failureEntry = projectSyncFailuresRef.current.get(currentWorkspaceId);\n if (\n failureEntry &&\n failureEntry.count >= PROJECT_SYNC_MAX_FAILURES &&\n Date.now() - failureEntry.lastFailureAt < PROJECT_SYNC_FAILURE_COOLDOWN_MS\n ) {\n return;\n }\n if (\n failureEntry &&\n Date.now() - failureEntry.lastFailureAt >=\n PROJECT_SYNC_FAILURE_COOLDOWN_MS\n ) {\n // Cool-down elapsed — clear the counter so we get a fresh budget.\n projectSyncFailuresRef.current.delete(currentWorkspaceId);\n }\n\n // Resolve organizationId: prefer the workspace object (if loaded), fall\n // back to the persisted currentOrganizationId. The workspaces array is\n // NOT persisted by zustand, so on page reload it is empty until\n // fetchOrganizations() completes. Using the persisted org ID lets us\n // issue the workspace token immediately instead of waiting.\n const currentWorkspace = workspaces.find(\n (ws) => ws.id === currentWorkspaceId,\n );\n\n // Guard: transient (newOrg, oldWs) divergence during org switches — token issuance always fails.\n if (\n currentWorkspace &&\n currentOrganizationId &&\n currentWorkspace.organizationId !== currentOrganizationId\n ) {\n return;\n }\n\n const organizationId =\n currentWorkspace?.organizationId ?? currentOrganizationId;\n if (!organizationId) return;\n\n const store = useAuthStore.getState();\n\n // If we don't have a workspace token or it's expired, issue one first\n const needsToken =\n !workspaceToken ||\n isTokenExpired(workspaceToken) ||\n !isWorkspaceTokenValidForContext(workspaceToken, {\n workspaceId: currentWorkspaceId,\n organizationId: currentOrganizationId,\n projectId: currentProjectId,\n });\n\n // Skip if projects are already loaded for this workspace AND token is valid\n const hasProjectsForWorkspace = projects.some(\n (p) => p.workspaceId === currentWorkspaceId,\n );\n if (hasProjectsForWorkspace && !needsToken) {\n if (!store.currentProjectId) {\n const firstProject = projects.find(\n (project) => project.workspaceId === currentWorkspaceId,\n );\n if (firstProject) {\n store.setCurrentProjectId(firstProject.id);\n }\n }\n return;\n }\n\n const syncProjects = async () => {\n syncInProgressRef.current = true;\n store.setLoadingProjects(true);\n let succeeded = false;\n\n try {\n let wsToken = workspaceToken;\n\n // Issue workspace token if needed\n if (needsToken) {\n const tokenResult = await graphqlFetch<{\n issueWorkspaceToken: IssueWorkspaceTokenResult;\n }>({\n gateway: \"workspace\",\n query: ISSUE_WORKSPACE_TOKEN_MUTATION,\n variables: {\n input: {\n organizationId,\n workspaceId: currentWorkspaceId,\n ...(currentProjectId ? { projectId: currentProjectId } : {}),\n },\n },\n authToken: accessToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (\n tokenResult.data?.issueWorkspaceToken?.success &&\n tokenResult.data.issueWorkspaceToken.token\n ) {\n wsToken = tokenResult.data.issueWorkspaceToken.token;\n store.setWorkspaceToken(wsToken);\n } else {\n return;\n }\n }\n\n // Fetch projects (skip if already loaded or token-only sync requested)\n if (wsToken && !hasProjectsForWorkspace && !skipProjectFetch) {\n const projectsResult = await graphqlFetch<ProjectsResponse>({\n gateway: \"workspace\",\n query: PROJECTS_QUERY,\n authToken: accessToken,\n workspaceToken: wsToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (projectsResult.errors?.length) {\n return;\n }\n\n let projs: Project[] = projectsResult.data?.projects?.items ?? [];\n if (projs.length === 0) {\n const defaultProject = await createDefaultProject({\n authToken: accessToken,\n workspaceBaseUrl,\n workspaceToken: wsToken,\n });\n if (defaultProject) {\n projs = [defaultProject];\n } else {\n // Default-project creation failed (e.g. workspace not yet\n // propagated to the workspace layer). Do NOT write [] back —\n // that would change the projects reference and re-trigger\n // this effect on the next render.\n return;\n }\n }\n\n store.setProjects(projs);\n\n // Auto-select first project if none selected and projects exist\n if (projs.length > 0 && !store.currentProjectId) {\n store.setCurrentProjectId(projs[0].id);\n }\n }\n\n succeeded = true;\n } catch {\n // A later auth/context update should be able to retry.\n } finally {\n store.setLoadingProjects(false);\n syncInProgressRef.current = false;\n const failures = projectSyncFailuresRef.current;\n if (succeeded) {\n failures.delete(currentWorkspaceId);\n const pending = retryTimerRef.current.get(currentWorkspaceId);\n if (pending) {\n clearTimeout(pending);\n retryTimerRef.current.delete(currentWorkspaceId);\n }\n } else {\n const existing = failures.get(currentWorkspaceId);\n const nextCount = (existing?.count ?? 0) + 1;\n failures.set(currentWorkspaceId, {\n count: nextCount,\n lastFailureAt: Date.now(),\n });\n // Schedule a backoff retry for transient backend lag (e.g. RBAC\n // role propagation right after signup → first projects() call hits\n // permission-denied). Without this, the effect would only re-run on\n // dep change and the user would be stuck staring at an empty\n // project dropdown until something else triggered a re-render.\n if (nextCount < PROJECT_SYNC_MAX_FAILURES) {\n const existingTimer = retryTimerRef.current.get(currentWorkspaceId);\n if (existingTimer) clearTimeout(existingTimer);\n const backoffMs = Math.min(1000 * 2 ** (nextCount - 1), 8000);\n const timer = setTimeout(() => {\n retryTimerRef.current.delete(currentWorkspaceId);\n // Only re-run if the workspace context is still the same and\n // a project hasn't been loaded for it in the meantime.\n const latest = useAuthStore.getState();\n if (\n latest.currentWorkspaceId === currentWorkspaceId &&\n !latest.projects.some(\n (p) => p.workspaceId === currentWorkspaceId,\n ) &&\n !syncInProgressRef.current\n ) {\n // Bump a render by clearing then resetting workspaceToken\n // when valid, OR by re-issuing projects fetch directly. The\n // simplest robust trigger is to clear the in-progress guard\n // and call syncProjects() again with current closure values.\n void syncProjects();\n }\n }, backoffMs);\n retryTimerRef.current.set(currentWorkspaceId, timer);\n }\n }\n }\n };\n\n syncProjects();\n }, [\n currentWorkspaceId,\n currentOrganizationId,\n workspaces,\n projects,\n currentProjectId,\n workspaceToken,\n accessToken,\n workspaceBaseUrl,\n disableProjectSync,\n skipProjectFetch,\n ]);\n\n // Cleanup any pending retry timers on unmount so we don't leak stray\n // setTimeout callbacks running against stale closures.\n useEffect(() => {\n const timers = retryTimerRef.current;\n return () => {\n timers.forEach((timer) => clearTimeout(timer));\n timers.clear();\n };\n }, []);\n}\n// hmr-bust-1778064429\n"],"mappings":";;;;;;;AAmFA,IAAM,IAAyB,2RAoCzB,IAA0B,oSAoB1B,IAAmC,kiBAoCnC,IAAiC,6SA0BjC,IAAiB,uPAkBjB,IAAkC;AAexC,eAAe,EAAqB,EAClC,cACA,qBACA,qBAK0B;CAC1B,IAAM,IAAS,MAAM,EAAoC;EACvD,SAAS;EACT,OAAO;EACP,WAAW,EACT,OAAO,EACL,MAAM,mBACP,EACF;EACD;EACA;EACA,SAAS;EACV,CAAC;AAOF,QALI,EAAO,QAAQ,UACjB,QAAQ,KAAK,qCAAqC,EAAO,OAAO,EACzD,QAGF,EAAO,MAAM,iBAAiB;;AAWvC,SAAS,EAAe,GAAe,IAAW,KAAiB;AACjE,KAAI;EACF,IAAM,IAAU,KAAK,MAAM,KAAK,EAAM,MAAM,IAAI,CAAC,GAAG,CAAC;AAErD,SADK,EAAQ,MACN,EAAQ,MAAM,MAAO,KAAK,KAAK,GAAG,IADhB;SAEnB;AACN,SAAO;;;AAIX,SAAS,EAAyB,GAKzB;AACP,KAAI;EACF,IAAM,IAAU,KAAK,MAAM,KAAK,EAAM,MAAM,IAAI,CAAC,GAAG,CAAC;AACrD,SAAO;GACL,aACE,OAAO,EAAQ,eAAgB,WAC3B,EAAQ,cACR,KAAA;GACN,gBACE,OAAO,EAAQ,kBAAmB,WAC9B,EAAQ,iBACR,KAAA;GACN,WACE,OAAO,EAAQ,aAAc,WAAW,EAAQ,YAAY,KAAA;GAC9D,KAAK,OAAO,EAAQ,OAAQ,WAAW,EAAQ,MAAM,KAAA;GACtD;SACK;AACN,SAAO;;;AAIX,SAAS,EACP,GACA,GAKiB;AACjB,KAAI,CAAC,KA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IAEf,EAAE,CAAC"}
|
|
1
|
+
{"version":3,"file":"useContextSwitcherData.js","names":[],"sources":["../../../src/auth/hooks/useContextSwitcherData.ts"],"sourcesContent":["import { useCallback, useState, useEffect, useRef } from \"react\";\nimport {\n graphqlFetch,\n getStoredAuthToken,\n} from \"@burdenoff/fe-libs/shared/graphql\";\nimport { useActiveContext } from \"@burdenoff/fe-libs/shared/providers/shell/ActiveContextProvider\";\nimport { useEventBus } from \"@burdenoff/fe-libs/shared/events\";\nimport { useAuthStore } from \"../store/authStore\";\nimport type { Organization, Workspace, Project } from \"../types\";\nimport { resolveGatewayBaseUrls } from \"../utils/gatewayBaseUrls\";\n\n// =============================================================================\n// Hook Options\n// =============================================================================\n\nexport interface UseContextSwitcherDataOptions {\n /**\n * Optional Global API Gateway base URL override.\n * If not provided, uses GATEWAYS config from fe-libs.\n */\n globalBaseUrl?: string;\n /**\n * Optional Workspaces API Gateway base URL override.\n * If not provided, uses GATEWAYS config from fe-libs.\n */\n workspaceBaseUrl?: string;\n /** Disable initial organization/workspace bootstrap fetches */\n disableBootstrap?: boolean;\n /** Disable the workspace sync effect */\n disableWorkspaceSync?: boolean;\n /** Disable the project sync effect */\n disableProjectSync?: boolean;\n /** Only hydrate the workspace token; do not eagerly fetch projects */\n skipProjectFetch?: boolean;\n}\n\n// =============================================================================\n// GraphQL Response Types\n// =============================================================================\n\ninterface MyOrganizationsResponse {\n myOrganizations: {\n total: number;\n items: Organization[];\n };\n}\n\ninterface WorkspacesByOrgResponse {\n workspaces: {\n total: number;\n items: Workspace[];\n };\n}\n\ntype GraphQLFetchResult<T> = Awaited<ReturnType<typeof graphqlFetch<T>>>;\n\ninterface IssueWorkspaceTokenResult {\n success: boolean;\n token: string | null;\n expiresAt: string | null;\n organizationId: string | null;\n workspaceId: string | null;\n projectId: string | null;\n scopes: string[] | null;\n error: {\n code: string;\n message: string;\n } | null;\n}\n\ninterface ProjectsResponse {\n projects: {\n total: number;\n items: Project[];\n };\n}\n\ninterface CreateProjectResponse {\n createProject: Project;\n}\n\n// =============================================================================\n// GraphQL Query/Mutation Strings\n// =============================================================================\n\nconst MY_ORGANIZATIONS_QUERY = `\n query MyOrganizations {\n myOrganizations {\n total\n items {\n id\n name\n slug\n tenantId\n description\n logo\n website\n status\n type\n createdAt\n updatedAt\n }\n }\n }\n`;\n\n// Both queries below historically used `workspaces(filter: $filter)` with\n// a `WorkspaceFilterInput` to fetch workspaces for a specific organization.\n// That Query field was removed/renamed in the global subgraph; calling it\n// now throws GRAPHQL_VALIDATION_FAILED (\"Cannot query field 'workspaces'\n// on type 'Query'\") which crashes the context switcher and cascades into a\n// \"Verifying workspace access...\" stuck-spinner on every Platform module\n// route (/billing, /support, /notifications, /devportal).\n//\n// The supported field is `myWorkspaces(limit, offset)` on the global\n// subgraph — self-scoped, returns the caller's workspaces across all\n// orgs. It does NOT accept a filter, so we fetch up to 100 of \"my\"\n// workspaces and let the existing downstream auto-pick logic filter by\n// organizationId client-side. The recovery path at line ~624 already\n// uses this exact aliased pattern; we're just promoting it to the\n// primary path.\nconst WORKSPACES_BY_ORG_QUERY = `\n query WorkspacesByOrg {\n workspaces: myWorkspaces(limit: 100) {\n total\n items {\n id\n name\n slug\n tenantId\n organizationId\n type\n status\n region\n createdAt\n updatedAt\n }\n }\n }\n`;\n\nconst ISSUE_WORKSPACE_TOKEN_MUTATION = `\n mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {\n issueWorkspaceToken(input: $input) {\n success\n token\n expiresAt\n organizationId\n workspaceId\n projectId\n scopes\n error {\n code\n message\n }\n }\n }\n`;\n\n// The workspace gateway exposes `myProjects` (public RBAC, caller-scoped to\n// the active workspace via x-workspace-id) and the privileged\n// `projects(filter)` (list:project). The header has no `list:project`\n// permission seeded for the typical operator, so the privileged form\n// returns FORBIDDEN even though the caller is a member of the workspace.\n// `myProjects` is the right field for \"give me the projects I can see in\n// this workspace\" — workspace scope is already established by the\n// workspace token + x-workspace-id header that we pass with the request.\nconst PROJECTS_QUERY = `\n query MyProjectsForContext {\n projects: myProjects {\n total\n items {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n }\n`;\n\nconst CREATE_DEFAULT_PROJECT_MUTATION = `\n mutation CreateDefaultProject($input: CreateProjectInput!) {\n createProject(input: $input) {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n`;\n\nasync function createDefaultProject({\n authToken,\n workspaceBaseUrl,\n workspaceToken,\n}: {\n authToken: string;\n workspaceBaseUrl: string;\n workspaceToken: string;\n}): Promise<Project | null> {\n const result = await graphqlFetch<CreateProjectResponse>({\n gateway: \"workspace\",\n query: CREATE_DEFAULT_PROJECT_MUTATION,\n variables: {\n input: {\n name: \"Default Project\",\n },\n },\n authToken,\n workspaceToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (result.errors?.length) {\n console.warn(\"Failed to create default project:\", result.errors);\n return null;\n }\n\n return result.data?.createProject ?? null;\n}\n\n// =============================================================================\n// Auth Helpers\n// =============================================================================\n\n/**\n * Check whether a JWT is expired (or within bufferMs of expiry).\n * Returns true if the token is expired, close to expiry, or malformed.\n */\nfunction isTokenExpired(token: string, bufferMs = 30_000): boolean {\n try {\n const payload = JSON.parse(atob(token.split(\".\")[1]));\n if (!payload.exp) return false;\n return payload.exp * 1000 < Date.now() + bufferMs;\n } catch {\n return true;\n }\n}\n\nfunction getWorkspaceTokenPayload(token: string): {\n workspaceId?: string;\n organizationId?: string;\n projectId?: string;\n exp?: number;\n} | null {\n try {\n const payload = JSON.parse(atob(token.split(\".\")[1]));\n return {\n workspaceId:\n typeof payload.workspaceId === \"string\"\n ? payload.workspaceId\n : undefined,\n organizationId:\n typeof payload.organizationId === \"string\"\n ? payload.organizationId\n : undefined,\n projectId:\n typeof payload.projectId === \"string\" ? payload.projectId : undefined,\n exp: typeof payload.exp === \"number\" ? payload.exp : undefined,\n };\n } catch {\n return null;\n }\n}\n\nfunction isWorkspaceTokenValidForContext(\n token: string | null | undefined,\n expected: {\n workspaceId?: string | null;\n organizationId?: string | null;\n projectId?: string | null;\n },\n): token is string {\n if (!token || isTokenExpired(token)) {\n return false;\n }\n\n const payload = getWorkspaceTokenPayload(token);\n if (!payload) {\n return false;\n }\n\n if (expected.workspaceId && payload.workspaceId !== expected.workspaceId) {\n return false;\n }\n\n if (\n expected.organizationId &&\n payload.organizationId !== expected.organizationId\n ) {\n return false;\n }\n\n if (expected.projectId && payload.projectId !== expected.projectId) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Custom error class for auth-related failures (expired token, unauthorized, etc.).\n * Used to distinguish auth errors in outer catch blocks so they can be\n * suppressed from console.error — they are expected during token refresh cycles\n * and do not indicate application bugs.\n */\nclass AuthError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * Detect whether a set of GraphQL errors are authentication-related.\n */\nfunction isAuthGraphQLError(\n errors: Array<{ message?: string; extensions?: { code?: string } }>,\n): boolean {\n return errors.some(\n (e) =>\n e.extensions?.code === \"UNAUTHENTICATED\" ||\n e.message?.toLowerCase().includes(\"unauthorized\") ||\n e.message?.toLowerCase().includes(\"not authenticated\"),\n );\n}\n\n/**\n * Resolve the best available access token:\n * 1. Try the zustand store token\n * 2. If expired, fall back to profile storage (may have been refreshed)\n * 3. Return null if no valid token is available\n */\nfunction resolveAccessToken(): string | null {\n const storeToken = useAuthStore.getState().accessToken;\n\n // If store token is valid (or has no exp claim), use it\n if (storeToken && !isTokenExpired(storeToken)) {\n return storeToken;\n }\n\n // Store token is expired or missing — try profile storage (may be fresher)\n const profileToken = getStoredAuthToken();\n if (profileToken && !isTokenExpired(profileToken)) {\n return profileToken;\n }\n\n // Both expired or missing — if store token exists at all, return it as a last\n // resort (the gateway will reject it and the useEffect will re-trigger after\n // token refresh). Returning null would silently swallow the first load.\n return storeToken;\n}\n\nfunction buildFallbackOrganizations(workspaces: Workspace[]): Organization[] {\n const uniqueOrgIds = Array.from(\n new Set(\n workspaces.flatMap((workspace) =>\n workspace.organizationId ? [workspace.organizationId] : [],\n ),\n ),\n );\n\n return uniqueOrgIds.map((organizationId, index) => ({\n id: organizationId,\n name:\n workspaces.find(\n (workspace) => workspace.organizationId === organizationId,\n )?.name || `Organization ${index + 1}`,\n slug: organizationId,\n tenantId:\n workspaces.find(\n (workspace) => workspace.organizationId === organizationId,\n )?.tenantId || \"\",\n }));\n}\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Hook for managing the context switcher data (organizations, workspaces, projects)\n *\n * Data flow:\n * 1. fetchOrganizations() - Get all orgs user has access to (Global Gateway)\n * 2. selectOrganization(org) - Set current org & fetch workspaces for that org\n * 3. selectWorkspace(ws) - Issue workspace token & fetch projects\n * 4. selectProject(proj) - Set current project\n *\n * All GraphQL calls go through graphqlFetch from fe-libs which automatically\n * resolves gateway URLs and injects auth + locale headers.\n *\n * @param options - Optional configuration (gateway base URL overrides)\n */\n// Domain events emitted by microfe-workspaces that should refresh the switcher's\n// cached lists. Module-scoped so they aren't reallocated on every effect run.\nconst PROJECT_REFRESH_EVENTS = new Set<string>([\n \"project.created\",\n \"project.updated\",\n \"project.deleted\",\n \"project.archived\",\n \"project.unarchived\",\n]);\nconst WORKSPACE_REFRESH_EVENTS = new Set<string>([\n \"workspace.created\",\n \"workspace.updated\",\n \"workspace.deleted\",\n \"workspace.archived\",\n \"workspace.reactivated\",\n]);\n\n// Safely read a string `workspaceId` off a cross-MFE event payload of unknown\n// shape, rather than trusting a bare cast (the payload is produced by another\n// MFE and could drift). Returns undefined when absent or not a string.\nfunction readEventWorkspaceId(payload: unknown): string | undefined {\n if (payload && typeof payload === \"object\" && \"workspaceId\" in payload) {\n const value = (payload as { workspaceId?: unknown }).workspaceId;\n return typeof value === \"string\" ? value : undefined;\n }\n return undefined;\n}\n\nexport function useContextSwitcherData(\n options?: UseContextSwitcherDataOptions,\n) {\n const {\n organizationId: activeOrganizationId,\n workspaceId: activeWorkspaceId,\n projectId: activeProjectId,\n setContext: setActiveContext,\n } = useActiveContext();\n\n const eventBus = useEventBus();\n\n // Use selectors for reactive state\n const organizations = useAuthStore((state) => state.organizations);\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const isLoadingOrganizations = useAuthStore(\n (state) => state.isLoadingOrganizations,\n );\n\n const workspaces = useAuthStore((state) => state.workspaces);\n const currentWorkspaceId = useAuthStore((state) => state.currentWorkspaceId);\n const workspaceToken = useAuthStore((state) => state.workspaceToken);\n const isLoadingWorkspaces = useAuthStore(\n (state) => state.isLoadingWorkspaces,\n );\n\n const projects = useAuthStore((state) => state.projects);\n const currentProjectId = useAuthStore((state) => state.currentProjectId);\n const isLoadingProjects = useAuthStore((state) => state.isLoadingProjects);\n\n // Local error state\n const [error, setError] = useState<string | null>(null);\n\n // Deduplication refs to prevent duplicate GraphQL calls\n const fetchOrganizationsPromiseRef = useRef<Promise<Organization[]> | null>(\n null,\n );\n const fetchWorkspacesPromisesRef = useRef<Map<string, Promise<Workspace[]>>>(\n new Map(),\n );\n\n // Stable refs for latest context values — avoids stale closures in callbacks\n // without adding them to useCallback dep arrays (which would recreate callbacks\n // on every context change and trigger spurious fetch re-runs).\n const activeWorkspaceIdRef = useRef(activeWorkspaceId);\n const activeOrganizationIdRef = useRef(activeOrganizationId);\n useEffect(() => {\n activeWorkspaceIdRef.current = activeWorkspaceId;\n activeOrganizationIdRef.current = activeOrganizationId;\n });\n\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const globalBaseUrl =\n options?.globalBaseUrl ?? resolvedBaseUrls.globalBaseUrl;\n const workspaceBaseUrl =\n options?.workspaceBaseUrl ?? resolvedBaseUrls.workspaceBaseUrl;\n\n // Refs to break feedback loops with the Header's \"store → URL\" sync effect.\n // Without these the pair can ping-pong: this effect writes (URL → store),\n // Header writes (store → URL), Zustand re-fires our subscribers, and React\n // hits \"Maximum update depth exceeded\" — especially when a downstream call\n // (workspace token issuance) returns 504 and leaves the two halves in\n // disagreement. The refs record the last value we pushed for each axis;\n // identical pushes are skipped so the loop has a hard floor.\n const lastAppliedOrgIdRef = useRef<string | null>(null);\n const lastAppliedWorkspaceIdRef = useRef<string | null>(null);\n const lastAppliedProjectIdRef = useRef<string | null>(null);\n const lastClearedTokenContextRef = useRef<string | null>(null);\n\n useEffect(() => {\n const store = useAuthStore.getState();\n\n if (\n activeOrganizationId &&\n activeOrganizationId !== store.currentOrganizationId &&\n activeOrganizationId !== lastAppliedOrgIdRef.current\n ) {\n lastAppliedOrgIdRef.current = activeOrganizationId;\n store.setCurrentOrganizationId(activeOrganizationId);\n if (\n store.workspaces.length > 0 &&\n !store.workspaces.some(\n (workspace) => workspace.organizationId === activeOrganizationId,\n )\n ) {\n store.setWorkspaces([]);\n }\n }\n\n if (\n activeWorkspaceId &&\n activeWorkspaceId !== store.currentWorkspaceId &&\n activeWorkspaceId !== lastAppliedWorkspaceIdRef.current\n ) {\n lastAppliedWorkspaceIdRef.current = activeWorkspaceId;\n store.setCurrentWorkspaceId(activeWorkspaceId);\n if (\n store.projects.length > 0 &&\n !store.projects.some(\n (project) => project.workspaceId === activeWorkspaceId,\n )\n ) {\n store.setProjects([]);\n store.setCurrentProjectId(null);\n }\n }\n\n if (\n activeProjectId &&\n activeProjectId !== store.currentProjectId &&\n activeProjectId !== lastAppliedProjectIdRef.current\n ) {\n lastAppliedProjectIdRef.current = activeProjectId;\n store.setCurrentProjectId(activeProjectId);\n }\n\n if (\n store.workspaceToken &&\n !isWorkspaceTokenValidForContext(store.workspaceToken, {\n workspaceId: activeWorkspaceId,\n organizationId: activeOrganizationId,\n projectId: activeProjectId,\n })\n ) {\n // Clear-token-once-per-context guard: when the upstream gateway is\n // flaky (504s during workspace token issuance) the surrounding state\n // machine can oscillate between \"got token but invalid\" and \"clearing\n // token\". The downstream re-issue path then loops. Only clear once per\n // (org, ws, proj) tuple — a successful re-issue resets the ref via\n // setWorkspaceToken landing a new token for the same context.\n const ctxKey = `${activeOrganizationId ?? \"\"}|${activeWorkspaceId ?? \"\"}|${activeProjectId ?? \"\"}`;\n if (lastClearedTokenContextRef.current !== ctxKey) {\n lastClearedTokenContextRef.current = ctxKey;\n store.setWorkspaceToken(null);\n }\n }\n }, [activeOrganizationId, activeWorkspaceId, activeProjectId]);\n\n // ===========================================================================\n // Fetch Organizations (Global Gateway)\n // ===========================================================================\n\n const fetchOrganizations = useCallback(async (): Promise<Organization[]> => {\n // Deduplicate: if a fetch is already in progress, return the same promise\n if (fetchOrganizationsPromiseRef.current) {\n return fetchOrganizationsPromiseRef.current;\n }\n\n const store = useAuthStore.getState();\n const token = resolveAccessToken();\n\n if (!token) {\n // Not an error — user may not be authenticated yet (e.g., page load before login).\n // The useEffect in Header.tsx will re-trigger when accessToken becomes available.\n return [];\n }\n\n // If the token is clearly expired and no fresh fallback was found, skip the\n // doomed request. The useEffect in Header.tsx re-triggers when the auth\n // provider refreshes the token and updates accessToken in the store.\n if (isTokenExpired(token)) {\n return [];\n }\n\n store.setLoadingOrganizations(true);\n setError(null);\n\n // Store the promise for deduplication before starting\n fetchOrganizationsPromiseRef.current = (async () => {\n try {\n const initialTargetOrgId =\n activeOrganizationIdRef.current ?? store.currentOrganizationId;\n let result: GraphQLFetchResult<\n MyOrganizationsResponse & Partial<WorkspacesByOrgResponse>\n > = initialTargetOrgId\n ? await (async () => {\n const [organizationsResult, workspacesResult] = await Promise.all(\n [\n graphqlFetch<MyOrganizationsResponse>({\n gateway: \"global\",\n query: MY_ORGANIZATIONS_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n }),\n graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n }),\n ],\n );\n\n const data = organizationsResult.data?.myOrganizations\n ? {\n myOrganizations: organizationsResult.data.myOrganizations,\n ...(workspacesResult.data?.workspaces\n ? { workspaces: workspacesResult.data.workspaces }\n : {}),\n }\n : null;\n\n return {\n data,\n errors: [\n ...(organizationsResult.errors ?? []),\n ...(workspacesResult.errors ?? []),\n ],\n };\n })()\n : await graphqlFetch<MyOrganizationsResponse>({\n gateway: \"global\",\n query: MY_ORGANIZATIONS_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n\n // Self-heal stale-URL case: if the workspace side of the bootstrap\n // fails because the URL points at an inaccessible org/workspace, retry\n // with the organization-only query so the operator sees their actual\n // orgs and the URL params get corrected on next render.\n if (\n initialTargetOrgId &&\n result.errors?.length &&\n result.errors.some(\n (e) =>\n e?.extensions?.code === \"FORBIDDEN\" ||\n /not a member of this organization/i.test(e?.message ?? \"\") ||\n // Public gateway often drops the underlying FORBIDDEN error\n // and replaces it with the schema-level non-null violation\n // (\"Cannot return null for non-nullable field Query.myOrganizations\").\n // That happens when ANY field in the query throws — workspaces\n // here — and data:null cascades up. Treat that pattern as a\n // signal to retry without the workspaces filter.\n /Cannot return null for non-nullable field Query\\.myOrganizations/i.test(\n e?.message ?? \"\",\n ),\n )\n ) {\n // Fetch myOrganizations + ALL workspaces (no filter) so the\n // downstream auto-pick logic still has a workspace list to seed\n // context from. If we only refetched myOrganizations, the page\n // would render but every workspace-scoped query would fail with\n // \"Select a workspace…\".\n result = await graphqlFetch<\n MyOrganizationsResponse & Partial<WorkspacesByOrgResponse>\n >({\n gateway: \"global\",\n query: `\n query ContextSwitcherRecover {\n myOrganizations {\n total\n items { id name slug tenantId description logo website status type createdAt updatedAt }\n }\n workspaces: myWorkspaces {\n total\n items { id name slug tenantId organizationId type status region createdAt updatedAt }\n }\n }\n `,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n }\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n // Auth errors are expected during token refresh cycles — throw AuthError\n // so the outer catch can suppress console.error.\n throw new AuthError(errorMessage);\n }\n if (store.workspaces.length === 0) {\n console.error(\"Failed to fetch organizations:\", result.errors);\n }\n throw new Error(errorMessage);\n }\n\n let orgs: Organization[] = result.data?.myOrganizations?.items ?? [];\n\n // Stale-context recovery: bootstrap query was filtered by\n // initialTargetOrgId, so when the URL/persisted org doesn't belong to\n // this user the response is empty. Re-fetch the unfiltered list of\n // *all* orgs the user can access so the guard below can pick a real\n // default. Skip the recovery when no target was set (already\n // unfiltered) or when workspaces are already in the store (the\n // existing fallback path covers that case).\n if (\n initialTargetOrgId &&\n orgs.length === 0 &&\n store.workspaces.length === 0\n ) {\n const recovery = await graphqlFetch<MyOrganizationsResponse>({\n gateway: \"global\",\n query: MY_ORGANIZATIONS_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n if (!recovery.errors?.length) {\n orgs = recovery.data?.myOrganizations?.items ?? [];\n // discard the filtered workspaces payload — it was for the\n // ghost org and would only mislead the workspace selector below.\n result = {\n ...recovery,\n data: {\n myOrganizations: recovery.data?.myOrganizations ?? {\n items: [],\n total: 0,\n },\n },\n };\n } else {\n // Surface the failure so a user reporting \"blank org list\" has\n // something to grep for in the console. We still fall through —\n // the guard below either picks from a fallback (workspaces in\n // store) or no-ops, leaving the existing error path in place.\n console.warn(\n \"[ContextSwitcher] Stale-context recovery failed:\",\n recovery.errors,\n );\n }\n }\n\n const fallbackOrganizations =\n orgs.length === 0 && store.workspaces.length > 0\n ? buildFallbackOrganizations(store.workspaces)\n : [];\n const effectiveOrganizations =\n fallbackOrganizations.length > 0 ? fallbackOrganizations : orgs;\n\n store.setOrganizations(effectiveOrganizations);\n\n // Determine which organization to use for workspace fetching\n let targetOrgId = initialTargetOrgId;\n\n // Stale-context guard: if the persisted/URL org isn't in the user's\n // accessible orgs, fall back to the first available one and clear the\n // stale workspace/project so they get re-derived. Without this, URL\n // params like ?org=<ghost-id> from a prior session leak into the new\n // user's request headers and cause \"Authentication required\" /\n // \"not a member\" errors at every subgraph.\n //\n // Check against `orgs` (freshly returned from the API in this same\n // closure) rather than `effectiveOrganizations`, which can fall back\n // to ids derived from `store.workspaces` — that fallback path could\n // contain stale ghost orgIds and mask the guard.\n const targetOrgIsAccessible =\n targetOrgId && orgs.some((org) => org.id === targetOrgId);\n if (targetOrgId && !targetOrgIsAccessible && orgs.length > 0) {\n targetOrgId = orgs[0].id;\n setActiveContext({\n organizationId: targetOrgId,\n workspaceId: null,\n tenantId: null,\n projectId: null,\n });\n store.setWorkspaces([]);\n store.setProjects([]);\n store.setCurrentWorkspaceId(null);\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n }\n\n if (targetOrgId && targetOrgId !== store.currentOrganizationId) {\n store.setCurrentOrganizationId(targetOrgId);\n }\n\n // Auto-select first organization if none is selected\n if (effectiveOrganizations.length > 0 && !targetOrgId) {\n store.setCurrentOrganizationId(effectiveOrganizations[0].id);\n targetOrgId = effectiveOrganizations[0].id;\n }\n\n // Fetch workspaces for the selected/auto-selected org if:\n // 1. We have a target org (either auto-selected or persisted from localStorage)\n // 2. AND workspaces array is empty (not persisted, or cleared)\n // This handles both initial login AND page refresh scenarios.\n // Read from useAuthStore.getState() rather than the captured `store`\n // snapshot so we see the post-guard cleared value when the org guard\n // above fired (the local `store.workspaces` ref is stale after\n // setWorkspaces([])).\n if (targetOrgId && useAuthStore.getState().workspaces.length === 0) {\n store.setLoadingWorkspaces(true);\n try {\n // myWorkspaces returns ALL workspaces the user is a member of\n // across every org. Filter to the target org client-side here.\n const bootstrappedWorkspaces =\n initialTargetOrgId === targetOrgId\n ? result.data?.workspaces?.items?.filter(\n (w) => w.organizationId === targetOrgId,\n )\n : undefined;\n const ws = bootstrappedWorkspaces\n ? (bootstrappedWorkspaces as Workspace[])\n : await graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n }).then((wsResult) =>\n wsResult.errors?.length\n ? null\n : (wsResult.data?.workspaces?.items ?? []).filter(\n (w) => w.organizationId === targetOrgId,\n ),\n );\n\n if (ws) {\n store.setWorkspaces(ws);\n const persistedWorkspace = activeWorkspaceIdRef.current\n ? ws.find(\n (workspace) =>\n workspace.id === activeWorkspaceIdRef.current,\n )\n : null;\n\n if (persistedWorkspace) {\n store.setCurrentWorkspaceId(persistedWorkspace.id);\n } else if (ws.length > 0) {\n const nextActiveContext = {\n organizationId: targetOrgId,\n workspaceId: ws[0].id,\n tenantId: ws[0].tenantId,\n projectId: null,\n };\n\n if (activeWorkspaceIdRef.current) {\n // Stale-context guard: URL/persisted workspace ID is not in\n // the user's accessible workspaces for the active org. Fall\n // back to the first workspace and clear the stale URL param\n // so subsequent requests don't carry the ghost ID.\n store.setCurrentWorkspaceId(ws[0].id);\n store.setWorkspaceToken(null);\n setActiveContext(nextActiveContext);\n } else if (!store.currentWorkspaceId) {\n // Auto-select first workspace only if none is currently selected\n // (preserves selection from completeAuthFlow or persistence if applicable)\n store.setCurrentWorkspaceId(ws[0].id);\n setActiveContext(nextActiveContext);\n }\n }\n }\n } catch {\n // Non-critical — user can still select workspace manually\n } finally {\n store.setLoadingWorkspaces(false);\n }\n }\n\n return effectiveOrganizations;\n } catch (err) {\n // Auth errors are expected during token refresh / page load cycles.\n // Suppress from console.error — the useEffect will re-trigger when the\n // auth provider refreshes the token.\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch organizations\";\n if (store.workspaces.length === 0) {\n console.error(\"Failed to fetch organizations:\", err);\n }\n setError(message);\n\n if (store.workspaces.length > 0) {\n const fallbackOrganizations = buildFallbackOrganizations(\n store.workspaces,\n );\n if (fallbackOrganizations.length > 0) {\n store.setOrganizations(fallbackOrganizations);\n if (!store.currentOrganizationId) {\n store.setCurrentOrganizationId(fallbackOrganizations[0].id);\n }\n return fallbackOrganizations;\n }\n }\n\n return [];\n } finally {\n store.setLoadingOrganizations(false);\n fetchOrganizationsPromiseRef.current = null;\n }\n })();\n\n return fetchOrganizationsPromiseRef.current;\n }, [globalBaseUrl, setActiveContext]);\n\n // ===========================================================================\n // Fetch Workspaces for Organization (Global Gateway)\n // ===========================================================================\n\n const fetchWorkspacesForOrg = useCallback(\n async (organizationId: string): Promise<Workspace[]> => {\n // Deduplicate: if a fetch for this org is already in progress, return the same promise\n const existingPromise =\n fetchWorkspacesPromisesRef.current.get(organizationId);\n if (existingPromise) {\n return existingPromise;\n }\n\n const store = useAuthStore.getState();\n const token = resolveAccessToken();\n\n if (!token || isTokenExpired(token)) {\n return [];\n }\n\n store.setLoadingWorkspaces(true);\n setError(null);\n\n // Store the promise for deduplication before starting\n const fetchPromise = (async () => {\n try {\n const result = await graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n // myWorkspaces returns workspaces across all the user's orgs;\n // filter to the requested org before handing to downstream.\n if (result.data?.workspaces?.items) {\n result.data.workspaces.items = result.data.workspaces.items.filter(\n (w) => w.organizationId === organizationId,\n );\n }\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n throw new AuthError(errorMessage);\n }\n console.error(\"Failed to fetch workspaces:\", result.errors);\n throw new Error(errorMessage);\n }\n\n // `myWorkspaces` returns every workspace the caller can see across\n // all of their orgs/tenants. The store key is per-org (selecting\n // org X then opening the dropdown should only show X's workspaces),\n // so we filter down to the requested org here. The dropdown filter\n // in ContextSwitcher.tsx is a defence-in-depth — without this\n // narrowing the store would briefly hold the caller's other-org\n // workspaces and the auto-pick logic (lines below) might select\n // one of them as the default.\n const allWs: Workspace[] = result.data?.workspaces?.items ?? [];\n const ws = allWs.filter((w) => w.organizationId === organizationId);\n store.setWorkspaces(ws);\n return ws;\n } catch (err) {\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch workspaces\";\n console.error(\"Failed to fetch workspaces:\", err);\n setError(message);\n return [];\n } finally {\n store.setLoadingWorkspaces(false);\n fetchWorkspacesPromisesRef.current.delete(organizationId);\n }\n })();\n\n fetchWorkspacesPromisesRef.current.set(organizationId, fetchPromise);\n return fetchPromise;\n },\n [globalBaseUrl],\n );\n\n // ===========================================================================\n // Issue Workspace Token (Workspace Gateway - wspace-auth-svc)\n // ===========================================================================\n\n const issueWorkspaceToken = useCallback(\n async (\n organizationId: string,\n workspaceId?: string,\n projectId?: string | null,\n ): Promise<{\n success: boolean;\n token?: string;\n resolvedWorkspaceId?: string;\n error?: string;\n }> => {\n const store = useAuthStore.getState();\n const authToken = resolveAccessToken();\n\n if (!authToken || isTokenExpired(authToken)) {\n return { success: false, error: \"No valid access token available\" };\n }\n\n setError(null);\n\n try {\n const result = await graphqlFetch<{\n issueWorkspaceToken: IssueWorkspaceTokenResult;\n }>({\n gateway: \"workspace\",\n query: ISSUE_WORKSPACE_TOKEN_MUTATION,\n variables: {\n input: {\n organizationId,\n ...(workspaceId && { workspaceId }),\n ...(projectId && { projectId }),\n },\n },\n authToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (!isAuthGraphQLError(result.errors)) {\n console.error(\"Failed to issue workspace token:\", result.errors);\n }\n return { success: false, error: errorMessage };\n }\n\n const tokenResult = result.data?.issueWorkspaceToken;\n\n if (tokenResult?.success && tokenResult.token) {\n const resolvedWsId = tokenResult.workspaceId || workspaceId;\n if (resolvedWsId) {\n store.setCurrentWorkspaceId(resolvedWsId);\n }\n store.setWorkspaceToken(tokenResult.token);\n return {\n success: true,\n token: tokenResult.token,\n resolvedWorkspaceId: resolvedWsId || undefined,\n };\n }\n\n return {\n success: false,\n error:\n tokenResult?.error?.message ?? \"Failed to issue workspace token\",\n };\n } catch (err) {\n const message =\n err instanceof Error\n ? err.message\n : \"Failed to issue workspace token\";\n console.error(\"Failed to issue workspace token:\", err);\n setError(message);\n return { success: false, error: message };\n }\n },\n [workspaceBaseUrl],\n );\n\n // ===========================================================================\n // Fetch Projects (Workspace Gateway - requires workspace token)\n // ===========================================================================\n\n const fetchProjects = useCallback(async (): Promise<Project[]> => {\n const store = useAuthStore.getState();\n const authToken = resolveAccessToken();\n const wsToken = store.workspaceToken;\n const workspaceId = store.currentWorkspaceId;\n\n if (!authToken || isTokenExpired(authToken)) {\n return [];\n }\n\n if (!wsToken) {\n return [];\n }\n\n if (!workspaceId) {\n return [];\n }\n\n store.setLoadingProjects(true);\n setError(null);\n\n try {\n const result = await graphqlFetch<ProjectsResponse>({\n gateway: \"workspace\",\n query: PROJECTS_QUERY,\n authToken,\n workspaceToken: wsToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n throw new AuthError(errorMessage);\n }\n console.error(\"Failed to fetch projects:\", result.errors);\n throw new Error(errorMessage);\n }\n\n const projs: Project[] = result.data?.projects?.items ?? [];\n store.setProjects(projs);\n return projs;\n } catch (err) {\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch projects\";\n console.error(\"Failed to fetch projects:\", err);\n setError(message);\n return [];\n } finally {\n store.setLoadingProjects(false);\n }\n }, [workspaceBaseUrl]);\n\n // ===========================================================================\n // High-Level Selection Actions\n // ===========================================================================\n\n const selectOrganization = useCallback(\n async (org: Organization): Promise<Workspace[]> => {\n const store = useAuthStore.getState();\n\n store.setCurrentWorkspaceId(null);\n store.setWorkspaceToken(null);\n store.setProjects([]);\n store.setCurrentProjectId(null);\n store.setCurrentOrganizationId(org.id);\n\n const ws = await fetchWorkspacesForOrg(org.id);\n return ws;\n },\n [fetchWorkspacesForOrg],\n );\n\n const selectWorkspace = useCallback(\n async (\n workspace: Workspace,\n ): Promise<{\n success: boolean;\n projects?: Project[];\n error?: string;\n }> => {\n const store = useAuthStore.getState();\n\n store.setCurrentProjectId(null);\n store.setProjects([]);\n\n if (!workspace.organizationId) {\n console.error(\"Workspace missing organizationId:\", workspace);\n return {\n success: false,\n error: \"Workspace is missing organizationId\",\n };\n }\n\n const tokenResult = await issueWorkspaceToken(\n workspace.organizationId,\n workspace.id,\n );\n\n if (!tokenResult.success) {\n return { success: false, error: tokenResult.error };\n }\n\n let projs = await fetchProjects();\n if (projs.length === 0) {\n const authToken = resolveAccessToken();\n const workspaceToken = useAuthStore.getState().workspaceToken;\n if (authToken && workspaceToken) {\n const defaultProject = await createDefaultProject({\n authToken,\n workspaceBaseUrl,\n workspaceToken,\n });\n if (defaultProject) {\n projs = [defaultProject];\n store.setProjects(projs);\n }\n }\n }\n\n if (projs.length > 0) {\n store.setCurrentProjectId(projs[0]!.id);\n }\n\n return { success: true, projects: projs };\n },\n [issueWorkspaceToken, fetchProjects, workspaceBaseUrl],\n );\n\n const selectProject = useCallback((project: Project): void => {\n const store = useAuthStore.getState();\n store.setCurrentProjectId(project.id);\n if (\n store.workspaceToken &&\n !isWorkspaceTokenValidForContext(store.workspaceToken, {\n workspaceId: store.currentWorkspaceId,\n organizationId: store.currentOrganizationId,\n projectId: project.id,\n })\n ) {\n store.setWorkspaceToken(null);\n }\n }, []);\n\n // ===========================================================================\n // Cross-MFE refresh: keep the switcher lists current when another MFE mutates\n // org/workspace/project entities. microfe-workspaces emits these domain events\n // on the shared event bus (e.g. on project rename); without this the switcher\n // keeps showing the stale cached name until a full page reload.\n // ===========================================================================\n\n useEffect(() => {\n let cancelled = false;\n\n // Coalesce a refetch into a single in-flight run with one trailing re-run,\n // so a burst of events collapses to one request (+ one trailing) instead of\n // fanning out or being swallowed by a downstream per-key dedupe. The flag is\n // cleared on cleanup so nothing fires after the subscription is torn down.\n const makeCoalescedRefetch = (run: () => Promise<unknown>) => {\n let running = false;\n let queued = false;\n const trigger = () => {\n if (cancelled) return;\n if (running) {\n queued = true;\n return;\n }\n running = true;\n void run().finally(() => {\n running = false;\n if (!cancelled && queued) {\n queued = false;\n trigger();\n }\n });\n };\n return trigger;\n };\n\n const refreshProjects = makeCoalescedRefetch(() => fetchProjects());\n const refreshWorkspaces = makeCoalescedRefetch(() => {\n const orgId = useAuthStore.getState().currentOrganizationId;\n return orgId ? fetchWorkspacesForOrg(orgId) : Promise.resolve();\n });\n\n // Custom domain events (not in BurdenoffEventName) flow through `onAny`.\n const unsubscribe = eventBus.onAny((event) => {\n // Custom event names aren't in the BurdenoffEventName union; compare as string.\n const eventName: string = event.name;\n\n if (PROJECT_REFRESH_EVENTS.has(eventName)) {\n const eventWorkspaceId = readEventWorkspaceId(event.payload);\n const { currentWorkspaceId } = useAuthStore.getState();\n // Only refetch when the event targets the workspace currently in\n // context (events without a workspace id are treated as relevant).\n if (\n eventWorkspaceId &&\n currentWorkspaceId &&\n eventWorkspaceId !== currentWorkspaceId\n ) {\n return;\n }\n // Refetch only — a deleted project simply drops out of the list, and\n // `currentProject` resolves to undefined for it. Clearing the selection\n // here would race ActiveContext / the project sync effect (the real\n // source of truth), so we leave selection reconciliation to them.\n refreshProjects();\n return;\n }\n\n if (WORKSPACE_REFRESH_EVENTS.has(eventName)) {\n refreshWorkspaces();\n }\n });\n\n return () => {\n cancelled = true;\n unsubscribe();\n };\n }, [eventBus, fetchProjects, fetchWorkspacesForOrg]);\n\n // ===========================================================================\n // Get Current Items\n // ===========================================================================\n\n const currentOrganization = organizations.find(\n (org) => org.id === currentOrganizationId,\n );\n const currentWorkspace = workspaces.find(\n (ws) => ws.id === currentWorkspaceId,\n );\n const currentProject = projects.find((proj) => proj.id === currentProjectId);\n\n // ===========================================================================\n // Return Hook API\n // ===========================================================================\n\n return {\n organizations,\n workspaces,\n projects,\n\n currentOrganizationId,\n currentWorkspaceId,\n currentProjectId,\n\n currentOrganization,\n currentWorkspace,\n currentProject,\n\n workspaceToken,\n\n isLoadingOrganizations,\n isLoadingWorkspaces,\n isLoadingProjects,\n isLoading:\n isLoadingOrganizations || isLoadingWorkspaces || isLoadingProjects,\n\n error,\n\n fetchOrganizations,\n fetchWorkspacesForOrg,\n issueWorkspaceToken,\n fetchProjects,\n\n selectOrganization,\n selectWorkspace,\n selectProject,\n };\n}\n\n/**\n * Hook to reactively ensure workspaces are synced with the current organization.\n *\n * This handles edge cases where the organization changes but workspaces\n * from a different org are still in the store (e.g., stale data, race conditions).\n *\n * Usage:\n * ```tsx\n * import { useWorkspaceSyncEffect } from '@burdenoff/microfe-auth';\n *\n * function MyComponent() {\n * useWorkspaceSyncEffect(); // Ensures workspaces stay in sync\n * // ...\n * }\n * ```\n */\nexport function useWorkspaceSyncEffect(\n options?: UseContextSwitcherDataOptions,\n) {\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const workspaces = useAuthStore((state) => state.workspaces);\n const accessToken = useAuthStore((state) => state.accessToken);\n const isLoadingWorkspaces = useAuthStore(\n (state) => state.isLoadingWorkspaces,\n );\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const globalBaseUrl =\n options?.globalBaseUrl ?? resolvedBaseUrls.globalBaseUrl;\n const disableWorkspaceSync = options?.disableWorkspaceSync ?? false;\n\n useEffect(() => {\n if (disableWorkspaceSync) return;\n // Skip if no org selected, no token, or already loading\n if (!currentOrganizationId || !accessToken || isLoadingWorkspaces) return;\n\n // Check if any workspace matches the current org\n const hasMatchingWorkspaces = workspaces.some(\n (ws) => ws.organizationId === currentOrganizationId,\n );\n\n // If workspaces exist but none match current org, we need to refetch\n // This can happen in edge cases with stale data or race conditions\n if (workspaces.length > 0 && !hasMatchingWorkspaces) {\n const store = useAuthStore.getState();\n store.setLoadingWorkspaces(true);\n\n // Inline fetch to avoid circular dependency with useContextSwitcherData\n graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: accessToken,\n baseUrl: globalBaseUrl,\n })\n .then((result) => {\n // myWorkspaces returns ALL my workspaces; filter to current org\n // client-side (the old server-side filter no longer exists).\n if (result.data?.workspaces?.items) {\n result.data.workspaces.items = result.data.workspaces.items.filter(\n (w) => w.organizationId === currentOrganizationId,\n );\n }\n if (!result.errors?.length) {\n const allWs: Workspace[] = result.data?.workspaces?.items ?? [];\n // Same per-org narrowing as fetchWorkspacesForOrg — see the\n // comment there for why we don't just dump the full caller-\n // visible list into the store.\n const ws = allWs.filter(\n (w) => w.organizationId === currentOrganizationId,\n );\n store.setWorkspaces(ws);\n }\n })\n .catch(() => {\n // Silent fail - user can manually refresh or select org again\n })\n .finally(() => {\n store.setLoadingWorkspaces(false);\n });\n }\n }, [\n currentOrganizationId,\n workspaces,\n accessToken,\n isLoadingWorkspaces,\n globalBaseUrl,\n disableWorkspaceSync,\n ]);\n}\n\n/**\n * Hook to reactively ensure projects are loaded when a workspace is selected.\n *\n * This handles the case where a workspace is auto-selected (from URL/localStorage)\n * but projects haven't been fetched yet. It will:\n * 1. Issue a workspace token if not present\n * 2. Fetch projects for the selected workspace\n *\n * Usage:\n * ```tsx\n * import { useProjectSyncEffect } from '@burdenoff/microfe-auth';\n *\n * function MyComponent() {\n * useProjectSyncEffect(); // Ensures projects are loaded for selected workspace\n * // ...\n * }\n * ```\n */\nexport function useProjectSyncEffect(options?: UseContextSwitcherDataOptions) {\n const currentWorkspaceId = useAuthStore((state) => state.currentWorkspaceId);\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const workspaces = useAuthStore((state) => state.workspaces);\n const projects = useAuthStore((state) => state.projects);\n const currentProjectId = useAuthStore((state) => state.currentProjectId);\n const workspaceToken = useAuthStore((state) => state.workspaceToken);\n const accessToken = useAuthStore((state) => state.accessToken);\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const workspaceBaseUrl =\n options?.workspaceBaseUrl ?? resolvedBaseUrls.workspaceBaseUrl;\n const disableProjectSync = options?.disableProjectSync ?? false;\n const skipProjectFetch = options?.skipProjectFetch ?? false;\n\n // Use refs to prevent the infinite loop caused by including loading/failure\n // state in the dependency array. Without these, the cycle is:\n // setLoadingProjects(true) -> dep change -> effect re-runs (guarded) ->\n // async completes -> setLoadingProjects(false) -> dep change ->\n // effect re-runs -> starts again -> INFINITE LOOP\n const syncInProgressRef = useRef(false);\n // Pending retry timer per workspace, so transient failures (e.g. RBAC lag\n // right after workspace creation) get an automatic second chance even if no\n // dependency change re-triggers the effect.\n const retryTimerRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(\n new Map(),\n );\n // Per-workspace failure tracker — caps retry attempts when project bootstrap\n // (token issue, list, or default-create) fails. Without this, a persistent\n // backend failure (e.g. cross-layer workspace not yet synced) causes the\n // effect to re-fire every render: list returns empty → create-default fails\n // → setProjects([]) → new array reference → effect re-runs → loop.\n //\n // We track both count AND lastFailureAt so we can honour a \"cool-down\" window:\n // after PROJECT_SYNC_FAILURE_COOLDOWN_MS has elapsed since the last failure,\n // the counter is treated as cleared so transient backend hiccups (e.g. RBAC\n // role propagation lag right after signup) don't permanently lock a workspace\n // out of the context dropdown — the original cause of marqueue §729.\n const projectSyncFailuresRef = useRef<\n Map<string, { count: number; lastFailureAt: number }>\n >(new Map());\n const PROJECT_SYNC_MAX_FAILURES = 8;\n const PROJECT_SYNC_FAILURE_COOLDOWN_MS = 30_000;\n useEffect(() => {\n if (disableProjectSync) return;\n // Skip if no workspace selected or no access token\n if (!currentWorkspaceId || !accessToken) return;\n\n // Skip if a sync is already in progress (ref-based guard avoids dep loop)\n if (syncInProgressRef.current) return;\n\n // Stop retrying once this workspace has failed too many times in a row.\n // Counter is reset on success, on workspace switch (different key), by\n // an explicit user retry path (e.g. selectWorkspace), or after the\n // cool-down window has elapsed since the last failure (so transient\n // backend issues don't permanently wedge the dropdown).\n const failureEntry = projectSyncFailuresRef.current.get(currentWorkspaceId);\n if (\n failureEntry &&\n failureEntry.count >= PROJECT_SYNC_MAX_FAILURES &&\n Date.now() - failureEntry.lastFailureAt < PROJECT_SYNC_FAILURE_COOLDOWN_MS\n ) {\n return;\n }\n if (\n failureEntry &&\n Date.now() - failureEntry.lastFailureAt >=\n PROJECT_SYNC_FAILURE_COOLDOWN_MS\n ) {\n // Cool-down elapsed — clear the counter so we get a fresh budget.\n projectSyncFailuresRef.current.delete(currentWorkspaceId);\n }\n\n // Resolve organizationId: prefer the workspace object (if loaded), fall\n // back to the persisted currentOrganizationId. The workspaces array is\n // NOT persisted by zustand, so on page reload it is empty until\n // fetchOrganizations() completes. Using the persisted org ID lets us\n // issue the workspace token immediately instead of waiting.\n const currentWorkspace = workspaces.find(\n (ws) => ws.id === currentWorkspaceId,\n );\n\n // Guard: transient (newOrg, oldWs) divergence during org switches — token issuance always fails.\n if (\n currentWorkspace &&\n currentOrganizationId &&\n currentWorkspace.organizationId !== currentOrganizationId\n ) {\n return;\n }\n\n const organizationId =\n currentWorkspace?.organizationId ?? currentOrganizationId;\n if (!organizationId) return;\n\n const store = useAuthStore.getState();\n\n // If we don't have a workspace token or it's expired, issue one first\n const needsToken =\n !workspaceToken ||\n isTokenExpired(workspaceToken) ||\n !isWorkspaceTokenValidForContext(workspaceToken, {\n workspaceId: currentWorkspaceId,\n organizationId: currentOrganizationId,\n projectId: currentProjectId,\n });\n\n // Skip if projects are already loaded for this workspace AND token is valid\n const hasProjectsForWorkspace = projects.some(\n (p) => p.workspaceId === currentWorkspaceId,\n );\n if (hasProjectsForWorkspace && !needsToken) {\n if (!store.currentProjectId) {\n const firstProject = projects.find(\n (project) => project.workspaceId === currentWorkspaceId,\n );\n if (firstProject) {\n store.setCurrentProjectId(firstProject.id);\n }\n }\n return;\n }\n\n const syncProjects = async () => {\n syncInProgressRef.current = true;\n store.setLoadingProjects(true);\n let succeeded = false;\n\n try {\n let wsToken = workspaceToken;\n\n // Issue workspace token if needed\n if (needsToken) {\n const tokenResult = await graphqlFetch<{\n issueWorkspaceToken: IssueWorkspaceTokenResult;\n }>({\n gateway: \"workspace\",\n query: ISSUE_WORKSPACE_TOKEN_MUTATION,\n variables: {\n input: {\n organizationId,\n workspaceId: currentWorkspaceId,\n ...(currentProjectId ? { projectId: currentProjectId } : {}),\n },\n },\n authToken: accessToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (\n tokenResult.data?.issueWorkspaceToken?.success &&\n tokenResult.data.issueWorkspaceToken.token\n ) {\n wsToken = tokenResult.data.issueWorkspaceToken.token;\n store.setWorkspaceToken(wsToken);\n } else {\n return;\n }\n }\n\n // Fetch projects (skip if already loaded or token-only sync requested)\n if (wsToken && !hasProjectsForWorkspace && !skipProjectFetch) {\n const projectsResult = await graphqlFetch<ProjectsResponse>({\n gateway: \"workspace\",\n query: PROJECTS_QUERY,\n authToken: accessToken,\n workspaceToken: wsToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (projectsResult.errors?.length) {\n return;\n }\n\n let projs: Project[] = projectsResult.data?.projects?.items ?? [];\n if (projs.length === 0) {\n const defaultProject = await createDefaultProject({\n authToken: accessToken,\n workspaceBaseUrl,\n workspaceToken: wsToken,\n });\n if (defaultProject) {\n projs = [defaultProject];\n } else {\n // Default-project creation failed (e.g. workspace not yet\n // propagated to the workspace layer). Do NOT write [] back —\n // that would change the projects reference and re-trigger\n // this effect on the next render.\n return;\n }\n }\n\n store.setProjects(projs);\n\n // Auto-select first project if none selected and projects exist\n if (projs.length > 0 && !store.currentProjectId) {\n store.setCurrentProjectId(projs[0].id);\n }\n }\n\n succeeded = true;\n } catch {\n // A later auth/context update should be able to retry.\n } finally {\n store.setLoadingProjects(false);\n syncInProgressRef.current = false;\n const failures = projectSyncFailuresRef.current;\n if (succeeded) {\n failures.delete(currentWorkspaceId);\n const pending = retryTimerRef.current.get(currentWorkspaceId);\n if (pending) {\n clearTimeout(pending);\n retryTimerRef.current.delete(currentWorkspaceId);\n }\n } else {\n const existing = failures.get(currentWorkspaceId);\n const nextCount = (existing?.count ?? 0) + 1;\n failures.set(currentWorkspaceId, {\n count: nextCount,\n lastFailureAt: Date.now(),\n });\n // Schedule a backoff retry for transient backend lag (e.g. RBAC\n // role propagation right after signup → first projects() call hits\n // permission-denied). Without this, the effect would only re-run on\n // dep change and the user would be stuck staring at an empty\n // project dropdown until something else triggered a re-render.\n if (nextCount < PROJECT_SYNC_MAX_FAILURES) {\n const existingTimer = retryTimerRef.current.get(currentWorkspaceId);\n if (existingTimer) clearTimeout(existingTimer);\n const backoffMs = Math.min(1000 * 2 ** (nextCount - 1), 8000);\n const timer = setTimeout(() => {\n retryTimerRef.current.delete(currentWorkspaceId);\n // Only re-run if the workspace context is still the same and\n // a project hasn't been loaded for it in the meantime.\n const latest = useAuthStore.getState();\n if (\n latest.currentWorkspaceId === currentWorkspaceId &&\n !latest.projects.some(\n (p) => p.workspaceId === currentWorkspaceId,\n ) &&\n !syncInProgressRef.current\n ) {\n // Bump a render by clearing then resetting workspaceToken\n // when valid, OR by re-issuing projects fetch directly. The\n // simplest robust trigger is to clear the in-progress guard\n // and call syncProjects() again with current closure values.\n void syncProjects();\n }\n }, backoffMs);\n retryTimerRef.current.set(currentWorkspaceId, timer);\n }\n }\n }\n };\n\n syncProjects();\n }, [\n currentWorkspaceId,\n currentOrganizationId,\n workspaces,\n projects,\n currentProjectId,\n workspaceToken,\n accessToken,\n workspaceBaseUrl,\n disableProjectSync,\n skipProjectFetch,\n ]);\n\n // Cleanup any pending retry timers on unmount so we don't leak stray\n // setTimeout callbacks running against stale closures.\n useEffect(() => {\n const timers = retryTimerRef.current;\n return () => {\n timers.forEach((timer) => clearTimeout(timer));\n timers.clear();\n };\n }, []);\n}\n// hmr-bust-1778064429\n"],"mappings":";;;;;;;AAqFA,IAAM,IAAyB,2RAoCzB,IAA0B,oSAoB1B,IAAiC,6SA0BjC,IAAiB,uPAkBjB,IAAkC;AAexC,eAAe,EAAqB,EAClC,cACA,qBACA,qBAK0B;CAC1B,IAAM,IAAS,MAAM,EAAoC;EACvD,SAAS;EACT,OAAO;EACP,WAAW,EACT,OAAO,EACL,MAAM,mBACP,EACF;EACD;EACA;EACA,SAAS;EACV,CAAC;AAOF,QALI,EAAO,QAAQ,UACjB,QAAQ,KAAK,qCAAqC,EAAO,OAAO,EACzD,QAGF,EAAO,MAAM,iBAAiB;;AAWvC,SAAS,EAAe,GAAe,IAAW,KAAiB;AACjE,KAAI;EACF,IAAM,IAAU,KAAK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AAI1C,QAAY;WACN,WAEE;AAER,IADA,EAAM,mBAAmB,GAAM,EAC/B,EAAkB,UAAU;IAC5B,IAAM,IAAW,EAAuB;AACxC,QAAI,GAAW;AACb,OAAS,OAAO,EAAmB;KACnC,IAAM,IAAU,EAAc,QAAQ,IAAI,EAAmB;AAC7D,KAAI,MACF,aAAa,EAAQ,EACrB,EAAc,QAAQ,OAAO,EAAmB;WAE7C;KAEL,IAAM,KADW,EAAS,IAAI,EAAmB,EACpB,SAAS,KAAK;AAU3C,SATA,EAAS,IAAI,GAAoB;MAC/B,OAAO;MACP,eAAe,KAAK,KAAK;MAC1B,CAAC,EAME,IAAY,GAA2B;MACzC,IAAM,IAAgB,EAAc,QAAQ,IAAI,EAAmB;AACnE,MAAI,KAAe,aAAa,EAAc;MAC9C,IAAM,IAAY,KAAK,IAAI,MAAO,MAAM,IAAY,IAAI,IAAK,EACvD,IAAQ,iBAAiB;AAC7B,SAAc,QAAQ,OAAO,EAAmB;OAGhD,IAAM,IAAS,EAAa,UAAU;AACtC,OACE,EAAO,uBAAuB,KAC9B,CAAC,EAAO,SAAS,MACd,MAAM,EAAE,gBAAgB,EAC1B,IACD,CAAC,EAAkB,WAMd,GAAc;SAEpB,EAAU;AACb,QAAc,QAAQ,IAAI,GAAoB,EAAM;;;;;AAM5D,KAAc;IACb;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,EAIF,QAAgB;EACd,IAAM,IAAS,EAAc;AAC7B,eAAa;AAEX,GADA,EAAO,SAAS,MAAU,aAAa,EAAM,CAAC,EAC9C,EAAO,OAAO;;IAEf,EAAE,CAAC"}
|
|
@@ -3,37 +3,35 @@ import { clearLocalAuthState as t } from "@burdenoff/fe-libs/shared/components";
|
|
|
3
3
|
import { useSearchParams as n } from "react-router-dom";
|
|
4
4
|
import { jsx as r } from "react/jsx-runtime";
|
|
5
5
|
import { clearShellSsoCookies as i } from "@burdenoff/fe-libs/shared/utils";
|
|
6
|
-
import {
|
|
6
|
+
import { BrandedSplash as a } from "@burdenoff/fe-libs/ui";
|
|
7
|
+
import { getAuthBridge as o } from "@burdenoff/fe-libs/shared/providers/shell/AuthBridgeClient";
|
|
7
8
|
//#region src/auth/pages/SSOClearPage.tsx
|
|
8
|
-
var
|
|
9
|
-
function
|
|
9
|
+
var s = new Set(/* @__PURE__ */ "burdenoff.com,vibecontrols.com,fluidgrids.com,botlit.ai,bigconsole.com,gethealthybowl.com,headshotmarketing.com,timecampus.com,ggnomad.com,movethewheels.com,crewfoundry.com,planmagnet.com,eventfullymanaged.com,kadaikodi.com,assethandler.com,technospam.com,semanticfed.com,manufacturedops.com,theglobalfuel.com,housingvista.com,proserviceworld.com,mybodyshield.com,artistrybase.com,collabkin.com,brainyrich.com,theculturepost.com,comradecircle.com,cosmicintersection.com,govcitizenhub.com,intelwatchtower.com,ecoimpacthub.com,buildmyiq.com,fluidgrids.ai,atheletebridge.com,adaptercloud.com,coolandlovely.com,subscriberbot.com,labsofscience.com,hookmovies.com".split(","));
|
|
10
|
+
function c(e) {
|
|
10
11
|
if (e.hostname === "localhost" || e.hostname === "127.0.0.1" || e.hostname.endsWith(".local.burdenoff.com")) return !0;
|
|
11
12
|
if (e.protocol !== "https:") return !1;
|
|
12
|
-
for (let t of
|
|
13
|
+
for (let t of s) if (e.hostname === t || e.hostname === `app.${t}` || e.hostname === `alphaapp.${t}` || e.hostname === `www.${t}`) return !0;
|
|
13
14
|
return !1;
|
|
14
15
|
}
|
|
15
|
-
function
|
|
16
|
+
function l(e) {
|
|
16
17
|
if (!e) return "/auth/login?reason=logout";
|
|
17
18
|
try {
|
|
18
19
|
let t = new URL(e, window.location.origin);
|
|
19
|
-
if (t.origin === window.location.origin ||
|
|
20
|
+
if (t.origin === window.location.origin || c(t)) return t.href;
|
|
20
21
|
} catch {}
|
|
21
22
|
return "/auth/login?reason=logout";
|
|
22
23
|
}
|
|
23
|
-
function
|
|
24
|
-
let [
|
|
24
|
+
function u() {
|
|
25
|
+
let [s] = n();
|
|
25
26
|
return e(() => {
|
|
26
|
-
let e =
|
|
27
|
+
let e = l(s.get("returnTo"));
|
|
27
28
|
try {
|
|
28
|
-
t(), i(),
|
|
29
|
+
t(), i(), o()?.notifyLogoutAll();
|
|
29
30
|
} catch {}
|
|
30
31
|
window.location.replace(e);
|
|
31
|
-
}, [
|
|
32
|
-
className: "flex items-center justify-center min-h-screen bg-bg-canvas",
|
|
33
|
-
children: /* @__PURE__ */ r("div", { className: "animate-spin rounded-full size-8 border-2 border-action-primary-bg border-t-transparent" })
|
|
34
|
-
});
|
|
32
|
+
}, [s]), /* @__PURE__ */ r(a, { label: "Signing you out…" });
|
|
35
33
|
}
|
|
36
34
|
//#endregion
|
|
37
|
-
export {
|
|
35
|
+
export { u as SSOClearPage };
|
|
38
36
|
|
|
39
37
|
//# sourceMappingURL=SSOClearPage.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SSOClearPage.js","names":[],"sources":["../../../src/auth/pages/SSOClearPage.tsx"],"sourcesContent":["/**\n * SSOClearPage — Cross-Domain Logout at the Central Bridge Host\n *\n * Companion to SSODepositPage. When a user signs out on a product origin,\n * the product app cleared its own localStorage / cookies but the bridge\n * host (alphaapp/app.burdenoff.com) still held the deposited session in\n * first-party (unpartitioned) localStorage. A later visit to any product\n * would then bridge-host-relay that stale session back, effectively\n * undoing the logout.\n *\n * AuthProvider.logout() / logoutAll() on a non-bridge-host origin redirect\n * here via a top-level navigation:\n *\n * product.com (logout)\n * → app.burdenoff.com/auth/sso-clear?returnTo=<encoded-return-url>\n * — wipes bridge-host localStorage + bf-sso cookie\n * → <returnTo>\n *\n * URL: /auth/sso-clear\n */\n\nimport { useEffect } from \"react\";\nimport { useSearchParams } from \"react-router-dom\";\nimport { clearShellSsoCookies } from \"@burdenoff/fe-libs/shared/utils\";\nimport { clearLocalAuthState } from \"@burdenoff/fe-libs/shared/components\";\nimport { getAuthBridge } from \"@burdenoff/fe-libs/shared/providers/shell/AuthBridgeClient\";\n\nconst ALLOWED_RETURN_DOMAINS = new Set([\n \"burdenoff.com\",\n \"vibecontrols.com\",\n \"fluidgrids.com\",\n \"botlit.ai\",\n \"bigconsole.com\",\n \"gethealthybowl.com\",\n \"headshotmarketing.com\",\n \"timecampus.com\",\n \"ggnomad.com\",\n \"movethewheels.com\",\n \"crewfoundry.com\",\n \"planmagnet.com\",\n \"eventfullymanaged.com\",\n \"kadaikodi.com\",\n \"assethandler.com\",\n \"technospam.com\",\n \"semanticfed.com\",\n \"manufacturedops.com\",\n \"theglobalfuel.com\",\n \"housingvista.com\",\n \"proserviceworld.com\",\n \"mybodyshield.com\",\n \"artistrybase.com\",\n \"collabkin.com\",\n \"brainyrich.com\",\n \"theculturepost.com\",\n \"comradecircle.com\",\n \"cosmicintersection.com\",\n \"govcitizenhub.com\",\n \"intelwatchtower.com\",\n \"ecoimpacthub.com\",\n \"buildmyiq.com\",\n \"fluidgrids.ai\",\n \"atheletebridge.com\",\n \"adaptercloud.com\",\n \"coolandlovely.com\",\n \"subscriberbot.com\",\n \"labsofscience.com\",\n \"hookmovies.com\",\n]);\n\nfunction isAllowedReturnUrl(url: URL): boolean {\n if (url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\") return true;\n if (url.hostname.endsWith(\".local.burdenoff.com\")) return true;\n if (url.protocol !== \"https:\") return false;\n for (const domain of ALLOWED_RETURN_DOMAINS) {\n if (\n url.hostname === domain ||\n url.hostname === `app.${domain}` ||\n url.hostname === `alphaapp.${domain}` ||\n url.hostname === `www.${domain}`\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction resolveSafeReturn(returnTo: string | null): string {\n if (!returnTo) return \"/auth/login?reason=logout\";\n try {\n const url = new URL(returnTo, window.location.origin);\n if (url.origin === window.location.origin || isAllowedReturnUrl(url)) {\n return url.href;\n }\n } catch {\n /* ignore */\n }\n return \"/auth/login?reason=logout\";\n}\n\nexport function SSOClearPage() {\n const [searchParams] = useSearchParams();\n\n useEffect(() => {\n const returnTo = resolveSafeReturn(searchParams.get(\"returnTo\"));\n\n try {\n clearLocalAuthState();\n clearShellSsoCookies();\n // Broadcast to any same-origin shells still listening so they drop the\n // session immediately too (best-effort — only fires on the bridge\n // host's origin, which is the only place where iframe storage isn't\n // partitioned cross-product).\n getAuthBridge()?.notifyLogoutAll();\n } catch {\n /* ignore — proceed with the redirect regardless */\n }\n\n window.location.replace(returnTo);\n }, [searchParams]);\n\n return
|
|
1
|
+
{"version":3,"file":"SSOClearPage.js","names":[],"sources":["../../../src/auth/pages/SSOClearPage.tsx"],"sourcesContent":["/**\n * SSOClearPage — Cross-Domain Logout at the Central Bridge Host\n *\n * Companion to SSODepositPage. When a user signs out on a product origin,\n * the product app cleared its own localStorage / cookies but the bridge\n * host (alphaapp/app.burdenoff.com) still held the deposited session in\n * first-party (unpartitioned) localStorage. A later visit to any product\n * would then bridge-host-relay that stale session back, effectively\n * undoing the logout.\n *\n * AuthProvider.logout() / logoutAll() on a non-bridge-host origin redirect\n * here via a top-level navigation:\n *\n * product.com (logout)\n * → app.burdenoff.com/auth/sso-clear?returnTo=<encoded-return-url>\n * — wipes bridge-host localStorage + bf-sso cookie\n * → <returnTo>\n *\n * URL: /auth/sso-clear\n */\n\nimport { useEffect } from \"react\";\nimport { BrandedSplash } from \"@burdenoff/fe-libs/ui\";\nimport { useSearchParams } from \"react-router-dom\";\nimport { clearShellSsoCookies } from \"@burdenoff/fe-libs/shared/utils\";\nimport { clearLocalAuthState } from \"@burdenoff/fe-libs/shared/components\";\nimport { getAuthBridge } from \"@burdenoff/fe-libs/shared/providers/shell/AuthBridgeClient\";\n\nconst ALLOWED_RETURN_DOMAINS = new Set([\n \"burdenoff.com\",\n \"vibecontrols.com\",\n \"fluidgrids.com\",\n \"botlit.ai\",\n \"bigconsole.com\",\n \"gethealthybowl.com\",\n \"headshotmarketing.com\",\n \"timecampus.com\",\n \"ggnomad.com\",\n \"movethewheels.com\",\n \"crewfoundry.com\",\n \"planmagnet.com\",\n \"eventfullymanaged.com\",\n \"kadaikodi.com\",\n \"assethandler.com\",\n \"technospam.com\",\n \"semanticfed.com\",\n \"manufacturedops.com\",\n \"theglobalfuel.com\",\n \"housingvista.com\",\n \"proserviceworld.com\",\n \"mybodyshield.com\",\n \"artistrybase.com\",\n \"collabkin.com\",\n \"brainyrich.com\",\n \"theculturepost.com\",\n \"comradecircle.com\",\n \"cosmicintersection.com\",\n \"govcitizenhub.com\",\n \"intelwatchtower.com\",\n \"ecoimpacthub.com\",\n \"buildmyiq.com\",\n \"fluidgrids.ai\",\n \"atheletebridge.com\",\n \"adaptercloud.com\",\n \"coolandlovely.com\",\n \"subscriberbot.com\",\n \"labsofscience.com\",\n \"hookmovies.com\",\n]);\n\nfunction isAllowedReturnUrl(url: URL): boolean {\n if (url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\") return true;\n if (url.hostname.endsWith(\".local.burdenoff.com\")) return true;\n if (url.protocol !== \"https:\") return false;\n for (const domain of ALLOWED_RETURN_DOMAINS) {\n if (\n url.hostname === domain ||\n url.hostname === `app.${domain}` ||\n url.hostname === `alphaapp.${domain}` ||\n url.hostname === `www.${domain}`\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction resolveSafeReturn(returnTo: string | null): string {\n if (!returnTo) return \"/auth/login?reason=logout\";\n try {\n const url = new URL(returnTo, window.location.origin);\n if (url.origin === window.location.origin || isAllowedReturnUrl(url)) {\n return url.href;\n }\n } catch {\n /* ignore */\n }\n return \"/auth/login?reason=logout\";\n}\n\nexport function SSOClearPage() {\n const [searchParams] = useSearchParams();\n\n useEffect(() => {\n const returnTo = resolveSafeReturn(searchParams.get(\"returnTo\"));\n\n try {\n clearLocalAuthState();\n clearShellSsoCookies();\n // Broadcast to any same-origin shells still listening so they drop the\n // session immediately too (best-effort — only fires on the bridge\n // host's origin, which is the only place where iframe storage isn't\n // partitioned cross-product).\n getAuthBridge()?.notifyLogoutAll();\n } catch {\n /* ignore — proceed with the redirect regardless */\n }\n\n window.location.replace(returnTo);\n }, [searchParams]);\n\n return <BrandedSplash label=\"Signing you out…\" />;\n}\n"],"mappings":";;;;;;;;AA4BA,IAAM,IAAyB,IAAI,IAAI,8qBAwCtC,CAAC;AAEF,SAAS,EAAmB,GAAmB;AAE7C,KADI,EAAI,aAAa,eAAe,EAAI,aAAa,eACjD,EAAI,SAAS,SAAS,uBAAuB,CAAE,QAAO;AAC1D,KAAI,EAAI,aAAa,SAAU,QAAO;AACtC,MAAK,IAAM,KAAU,EACnB,KACE,EAAI,aAAa,KACjB,EAAI,aAAa,OAAO,OACxB,EAAI,aAAa,YAAY,OAC7B,EAAI,aAAa,OAAO,IAExB,QAAO;AAGX,QAAO;;AAGT,SAAS,EAAkB,GAAiC;AAC1D,KAAI,CAAC,EAAU,QAAO;AACtB,KAAI;EACF,IAAM,IAAM,IAAI,IAAI,GAAU,OAAO,SAAS,OAAO;AACrD,MAAI,EAAI,WAAW,OAAO,SAAS,UAAU,EAAmB,EAAI,CAClE,QAAO,EAAI;SAEP;AAGR,QAAO;;AAGT,SAAgB,IAAe;CAC7B,IAAM,CAAC,KAAgB,GAAiB;AAoBxC,QAlBA,QAAgB;EACd,IAAM,IAAW,EAAkB,EAAa,IAAI,WAAW,CAAC;AAEhE,MAAI;AAOF,GANA,GAAqB,EACrB,GAAsB,EAKtB,GAAe,EAAE,iBAAiB;UAC5B;AAIR,SAAO,SAAS,QAAQ,EAAS;IAChC,CAAC,EAAa,CAAC,EAEX,kBAAC,GAAD,EAAe,OAAM,oBAAqB,CAAA"}
|
|
@@ -3,52 +3,50 @@ import { useEffect as t } from "react";
|
|
|
3
3
|
import { useSearchParams as n } from "react-router-dom";
|
|
4
4
|
import { jsx as r } from "react/jsx-runtime";
|
|
5
5
|
import { setSSoCookie as i } from "@burdenoff/fe-libs/shared/utils";
|
|
6
|
-
import {
|
|
6
|
+
import { BrandedSplash as a } from "@burdenoff/fe-libs/ui";
|
|
7
|
+
import { getAuthBridge as o } from "@burdenoff/fe-libs/shared/providers/shell/AuthBridgeClient";
|
|
7
8
|
//#region src/auth/pages/SSODepositPage.tsx
|
|
8
|
-
var
|
|
9
|
-
function
|
|
9
|
+
var s = new Set(/* @__PURE__ */ "burdenoff.com,vibecontrols.com,fluidgrids.com,botlit.ai,bigconsole.com,gethealthybowl.com,headshotmarketing.com,timecampus.com,ggnomad.com,movethewheels.com,crewfoundry.com,planmagnet.com,eventfullymanaged.com,kadaikodi.com,assethandler.com,technospam.com,semanticfed.com,manufacturedops.com,theglobalfuel.com,housingvista.com,proserviceworld.com,mybodyshield.com,artistrybase.com,collabkin.com,brainyrich.com,theculturepost.com,comradecircle.com,cosmicintersection.com,govcitizenhub.com,intelwatchtower.com,ecoimpacthub.com,buildmyiq.com,fluidgrids.ai,atheletebridge.com,adaptercloud.com,coolandlovely.com,subscriberbot.com,labsofscience.com,hookmovies.com".split(","));
|
|
10
|
+
function c(e) {
|
|
10
11
|
if (e.hostname === "localhost" || e.hostname === "127.0.0.1" || e.hostname.endsWith(".local.burdenoff.com")) return !0;
|
|
11
12
|
if (e.protocol !== "https:") return !1;
|
|
12
|
-
for (let t of
|
|
13
|
+
for (let t of s) if (e.hostname === t || e.hostname === `app.${t}` || e.hostname === `alphaapp.${t}` || e.hostname === `admin.${t}` || e.hostname === `alphaadmin.${t}` || e.hostname === `www.${t}`) return !0;
|
|
13
14
|
return !1;
|
|
14
15
|
}
|
|
15
|
-
function
|
|
16
|
+
function l(e) {
|
|
16
17
|
if (!e) return "/";
|
|
17
18
|
try {
|
|
18
19
|
let t = new URL(e, window.location.origin);
|
|
19
|
-
if (t.origin === window.location.origin ||
|
|
20
|
+
if (t.origin === window.location.origin || c(t)) return t.href;
|
|
20
21
|
} catch {}
|
|
21
22
|
return "/";
|
|
22
23
|
}
|
|
23
|
-
function
|
|
24
|
-
let [
|
|
24
|
+
function u() {
|
|
25
|
+
let [s] = n();
|
|
25
26
|
return t(() => {
|
|
26
|
-
let t =
|
|
27
|
+
let t = l(s.get("returnTo")), n = window.location.hash;
|
|
27
28
|
if (!n.startsWith("#sso=")) {
|
|
28
29
|
window.location.replace(t);
|
|
29
30
|
return;
|
|
30
31
|
}
|
|
31
32
|
try {
|
|
32
|
-
let r = n.slice(5), { profileId:
|
|
33
|
-
if (!
|
|
33
|
+
let r = n.slice(5), { profileId: a, tokens: s, user: c, profiles: l } = JSON.parse(atob(r));
|
|
34
|
+
if (!a || !s) {
|
|
34
35
|
window.location.replace(t);
|
|
35
36
|
return;
|
|
36
37
|
}
|
|
37
|
-
localStorage.setItem(`bf-p-${
|
|
38
|
+
localStorage.setItem(`bf-p-${a}-tokens`, s), c && localStorage.setItem(`bf-p-${a}-user`, c), l && localStorage.setItem("bf-profiles", l), sessionStorage.setItem("bf-active-profile", a), i(a), e.getState().loadFromProfile(a), window.dispatchEvent(new Event("bf-profile-storage-change")), o()?.notifyLogin({
|
|
38
39
|
user: c ? JSON.parse(c) : null,
|
|
39
40
|
tokens: s ? JSON.parse(s) : null,
|
|
40
|
-
activeProfileId:
|
|
41
|
+
activeProfileId: a,
|
|
41
42
|
profiles: l ? JSON.parse(l) : []
|
|
42
43
|
}), window.location.replace(t);
|
|
43
44
|
} catch {
|
|
44
45
|
window.location.replace(t);
|
|
45
46
|
}
|
|
46
|
-
}, [
|
|
47
|
-
className: "flex items-center justify-center min-h-screen bg-bg-canvas",
|
|
48
|
-
children: /* @__PURE__ */ r("div", { className: "animate-spin rounded-full size-8 border-2 border-action-primary-bg border-t-transparent" })
|
|
49
|
-
});
|
|
47
|
+
}, [s]), /* @__PURE__ */ r(a, { label: "Signing you in…" });
|
|
50
48
|
}
|
|
51
49
|
//#endregion
|
|
52
|
-
export {
|
|
50
|
+
export { u as SSODepositPage };
|
|
53
51
|
|
|
54
52
|
//# sourceMappingURL=SSODepositPage.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SSODepositPage.js","names":[],"sources":["../../../src/auth/pages/SSODepositPage.tsx"],"sourcesContent":["/**\n * SSODepositPage — Cross-Domain Token Deposit at the Central Bridge Host\n *\n * Loaded as a top-level navigation (NOT an iframe) on the bridge host\n * (alphaapp/app.burdenoff.com) right after a user signs in on any other\n * product origin. It receives the freshly-issued tokens in the URL fragment\n * (`#sso=<base64>` — fragments are never sent to servers) and stores them\n * in this origin's first-party (unpartitioned) localStorage so that:\n *\n * 1. A later top-level visit to the bridge host renders authenticated.\n * 2. Other product origins can discover the session via\n * `/auth/sso-relay?returnTo=...` against this host.\n *\n * Flow:\n * product.com/auth/login → user signs in\n * product.com → POST-success redirect to:\n * app.burdenoff.com/auth/sso-deposit?returnTo=<encoded-return-url>#sso=<base64>\n * → writes tokens here, sets bf-sso cookie\n * <returnTo> → user lands back at intended dashboard\n *\n * URL: /auth/sso-deposit\n */\n\nimport { useEffect } from \"react\";\nimport { useSearchParams } from \"react-router-dom\";\nimport { getAuthBridge } from \"@burdenoff/fe-libs/shared/providers/shell/AuthBridgeClient\";\nimport { setSSoCookie } from \"@burdenoff/fe-libs/shared/utils\";\nimport { useAuthStore } from \"../store/authStore\";\n\nconst ALLOWED_RETURN_DOMAINS = new Set([\n \"burdenoff.com\",\n \"vibecontrols.com\",\n \"fluidgrids.com\",\n \"botlit.ai\",\n \"bigconsole.com\",\n \"gethealthybowl.com\",\n \"headshotmarketing.com\",\n \"timecampus.com\",\n \"ggnomad.com\",\n \"movethewheels.com\",\n \"crewfoundry.com\",\n \"planmagnet.com\",\n \"eventfullymanaged.com\",\n \"kadaikodi.com\",\n \"assethandler.com\",\n \"technospam.com\",\n \"semanticfed.com\",\n \"manufacturedops.com\",\n \"theglobalfuel.com\",\n \"housingvista.com\",\n \"proserviceworld.com\",\n \"mybodyshield.com\",\n \"artistrybase.com\",\n \"collabkin.com\",\n \"brainyrich.com\",\n \"theculturepost.com\",\n \"comradecircle.com\",\n \"cosmicintersection.com\",\n \"govcitizenhub.com\",\n \"intelwatchtower.com\",\n \"ecoimpacthub.com\",\n \"buildmyiq.com\",\n \"fluidgrids.ai\",\n \"atheletebridge.com\",\n \"adaptercloud.com\",\n \"coolandlovely.com\",\n \"subscriberbot.com\",\n \"labsofscience.com\",\n \"hookmovies.com\",\n]);\n\nfunction isAllowedReturnUrl(url: URL): boolean {\n if (url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\") return true;\n if (url.hostname.endsWith(\".local.burdenoff.com\")) return true;\n if (url.protocol !== \"https:\") return false;\n for (const domain of ALLOWED_RETURN_DOMAINS) {\n if (\n url.hostname === domain ||\n url.hostname === `app.${domain}` ||\n url.hostname === `alphaapp.${domain}` ||\n // Admin app shells (admin.burdenoff.com / alphaadmin.burdenoff.com) are\n // valid post-deposit return targets. Without these, a login that lands on\n // the bridge host falls back to \"/\" instead of returning to the admin app.\n url.hostname === `admin.${domain}` ||\n url.hostname === `alphaadmin.${domain}` ||\n url.hostname === `www.${domain}`\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction resolveSafeReturn(returnTo: string | null): string {\n if (!returnTo) return \"/\";\n try {\n const url = new URL(returnTo, window.location.origin);\n if (url.origin === window.location.origin || isAllowedReturnUrl(url)) {\n return url.href;\n }\n } catch {\n /* ignore */\n }\n return \"/\";\n}\n\nexport function SSODepositPage() {\n const [searchParams] = useSearchParams();\n\n useEffect(() => {\n const returnTo = resolveSafeReturn(searchParams.get(\"returnTo\"));\n const hash = window.location.hash;\n\n if (!hash.startsWith(\"#sso=\")) {\n window.location.replace(returnTo);\n return;\n }\n\n try {\n const encoded = hash.slice(5);\n const payload = JSON.parse(atob(encoded)) as {\n profileId?: string;\n tokens?: string;\n user?: string;\n profiles?: string;\n };\n const { profileId, tokens, user, profiles } = payload;\n\n if (!profileId || !tokens) {\n window.location.replace(returnTo);\n return;\n }\n\n // First-party (unpartitioned) writes on the bridge host origin —\n // future top-level visits here see the session.\n localStorage.setItem(`bf-p-${profileId}-tokens`, tokens);\n if (user) {\n localStorage.setItem(`bf-p-${profileId}-user`, user);\n }\n if (profiles) {\n localStorage.setItem(\"bf-profiles\", profiles);\n }\n sessionStorage.setItem(\"bf-active-profile\", profileId);\n setSSoCookie(profileId);\n useAuthStore.getState().loadFromProfile(profileId);\n window.dispatchEvent(new Event(\"bf-profile-storage-change\"));\n\n // Notify the same-origin auth bridge so any other open shells on\n // this origin pick up the new session immediately.\n getAuthBridge()?.notifyLogin({\n user: user ? (JSON.parse(user) as Record<string, unknown>) : null,\n tokens: tokens ? (JSON.parse(tokens) as { accessToken: string }) : null,\n activeProfileId: profileId,\n profiles: profiles\n ? (JSON.parse(profiles) as Array<Record<string, unknown>>)\n : [],\n });\n\n window.location.replace(returnTo);\n } catch {\n window.location.replace(returnTo);\n }\n }, [searchParams]);\n\n return
|
|
1
|
+
{"version":3,"file":"SSODepositPage.js","names":[],"sources":["../../../src/auth/pages/SSODepositPage.tsx"],"sourcesContent":["/**\n * SSODepositPage — Cross-Domain Token Deposit at the Central Bridge Host\n *\n * Loaded as a top-level navigation (NOT an iframe) on the bridge host\n * (alphaapp/app.burdenoff.com) right after a user signs in on any other\n * product origin. It receives the freshly-issued tokens in the URL fragment\n * (`#sso=<base64>` — fragments are never sent to servers) and stores them\n * in this origin's first-party (unpartitioned) localStorage so that:\n *\n * 1. A later top-level visit to the bridge host renders authenticated.\n * 2. Other product origins can discover the session via\n * `/auth/sso-relay?returnTo=...` against this host.\n *\n * Flow:\n * product.com/auth/login → user signs in\n * product.com → POST-success redirect to:\n * app.burdenoff.com/auth/sso-deposit?returnTo=<encoded-return-url>#sso=<base64>\n * → writes tokens here, sets bf-sso cookie\n * <returnTo> → user lands back at intended dashboard\n *\n * URL: /auth/sso-deposit\n */\n\nimport { useEffect } from \"react\";\nimport { BrandedSplash } from \"@burdenoff/fe-libs/ui\";\nimport { useSearchParams } from \"react-router-dom\";\nimport { getAuthBridge } from \"@burdenoff/fe-libs/shared/providers/shell/AuthBridgeClient\";\nimport { setSSoCookie } from \"@burdenoff/fe-libs/shared/utils\";\nimport { useAuthStore } from \"../store/authStore\";\n\nconst ALLOWED_RETURN_DOMAINS = new Set([\n \"burdenoff.com\",\n \"vibecontrols.com\",\n \"fluidgrids.com\",\n \"botlit.ai\",\n \"bigconsole.com\",\n \"gethealthybowl.com\",\n \"headshotmarketing.com\",\n \"timecampus.com\",\n \"ggnomad.com\",\n \"movethewheels.com\",\n \"crewfoundry.com\",\n \"planmagnet.com\",\n \"eventfullymanaged.com\",\n \"kadaikodi.com\",\n \"assethandler.com\",\n \"technospam.com\",\n \"semanticfed.com\",\n \"manufacturedops.com\",\n \"theglobalfuel.com\",\n \"housingvista.com\",\n \"proserviceworld.com\",\n \"mybodyshield.com\",\n \"artistrybase.com\",\n \"collabkin.com\",\n \"brainyrich.com\",\n \"theculturepost.com\",\n \"comradecircle.com\",\n \"cosmicintersection.com\",\n \"govcitizenhub.com\",\n \"intelwatchtower.com\",\n \"ecoimpacthub.com\",\n \"buildmyiq.com\",\n \"fluidgrids.ai\",\n \"atheletebridge.com\",\n \"adaptercloud.com\",\n \"coolandlovely.com\",\n \"subscriberbot.com\",\n \"labsofscience.com\",\n \"hookmovies.com\",\n]);\n\nfunction isAllowedReturnUrl(url: URL): boolean {\n if (url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\") return true;\n if (url.hostname.endsWith(\".local.burdenoff.com\")) return true;\n if (url.protocol !== \"https:\") return false;\n for (const domain of ALLOWED_RETURN_DOMAINS) {\n if (\n url.hostname === domain ||\n url.hostname === `app.${domain}` ||\n url.hostname === `alphaapp.${domain}` ||\n // Admin app shells (admin.burdenoff.com / alphaadmin.burdenoff.com) are\n // valid post-deposit return targets. Without these, a login that lands on\n // the bridge host falls back to \"/\" instead of returning to the admin app.\n url.hostname === `admin.${domain}` ||\n url.hostname === `alphaadmin.${domain}` ||\n url.hostname === `www.${domain}`\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction resolveSafeReturn(returnTo: string | null): string {\n if (!returnTo) return \"/\";\n try {\n const url = new URL(returnTo, window.location.origin);\n if (url.origin === window.location.origin || isAllowedReturnUrl(url)) {\n return url.href;\n }\n } catch {\n /* ignore */\n }\n return \"/\";\n}\n\nexport function SSODepositPage() {\n const [searchParams] = useSearchParams();\n\n useEffect(() => {\n const returnTo = resolveSafeReturn(searchParams.get(\"returnTo\"));\n const hash = window.location.hash;\n\n if (!hash.startsWith(\"#sso=\")) {\n window.location.replace(returnTo);\n return;\n }\n\n try {\n const encoded = hash.slice(5);\n const payload = JSON.parse(atob(encoded)) as {\n profileId?: string;\n tokens?: string;\n user?: string;\n profiles?: string;\n };\n const { profileId, tokens, user, profiles } = payload;\n\n if (!profileId || !tokens) {\n window.location.replace(returnTo);\n return;\n }\n\n // First-party (unpartitioned) writes on the bridge host origin —\n // future top-level visits here see the session.\n localStorage.setItem(`bf-p-${profileId}-tokens`, tokens);\n if (user) {\n localStorage.setItem(`bf-p-${profileId}-user`, user);\n }\n if (profiles) {\n localStorage.setItem(\"bf-profiles\", profiles);\n }\n sessionStorage.setItem(\"bf-active-profile\", profileId);\n setSSoCookie(profileId);\n useAuthStore.getState().loadFromProfile(profileId);\n window.dispatchEvent(new Event(\"bf-profile-storage-change\"));\n\n // Notify the same-origin auth bridge so any other open shells on\n // this origin pick up the new session immediately.\n getAuthBridge()?.notifyLogin({\n user: user ? (JSON.parse(user) as Record<string, unknown>) : null,\n tokens: tokens ? (JSON.parse(tokens) as { accessToken: string }) : null,\n activeProfileId: profileId,\n profiles: profiles\n ? (JSON.parse(profiles) as Array<Record<string, unknown>>)\n : [],\n });\n\n window.location.replace(returnTo);\n } catch {\n window.location.replace(returnTo);\n }\n }, [searchParams]);\n\n return <BrandedSplash label=\"Signing you in…\" />;\n}\n"],"mappings":";;;;;;;;AA8BA,IAAM,IAAyB,IAAI,IAAI,8qBAwCtC,CAAC;AAEF,SAAS,EAAmB,GAAmB;AAE7C,KADI,EAAI,aAAa,eAAe,EAAI,aAAa,eACjD,EAAI,SAAS,SAAS,uBAAuB,CAAE,QAAO;AAC1D,KAAI,EAAI,aAAa,SAAU,QAAO;AACtC,MAAK,IAAM,KAAU,EACnB,KACE,EAAI,aA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,EAAS,GACrB,EAAE;IACP,CAAC,EAEF,OAAO,SAAS,QAAQ,EAAS;UAC3B;AACN,UAAO,SAAS,QAAQ,EAAS;;IAElC,CAAC,EAAa,CAAC,EAEX,kBAAC,GAAD,EAAe,OAAM,mBAAoB,CAAA"}
|
|
@@ -3,9 +3,10 @@ import { useEffect as t } from "react";
|
|
|
3
3
|
import { useSearchParams as n } from "react-router-dom";
|
|
4
4
|
import { jsx as r } from "react/jsx-runtime";
|
|
5
5
|
import { setSSoCookie as i } from "@burdenoff/fe-libs/shared/utils";
|
|
6
|
-
import {
|
|
6
|
+
import { BrandedSplash as a } from "@burdenoff/fe-libs/ui";
|
|
7
|
+
import { getAuthBridge as o } from "@burdenoff/fe-libs/shared/providers/shell/AuthBridgeClient";
|
|
7
8
|
//#region src/auth/pages/SSORelayCallbackPage.tsx
|
|
8
|
-
function
|
|
9
|
+
function s(e) {
|
|
9
10
|
if (!e) return "/dashboard";
|
|
10
11
|
try {
|
|
11
12
|
let t = new URL(e, window.location.origin);
|
|
@@ -14,35 +15,32 @@ function o(e) {
|
|
|
14
15
|
return "/dashboard";
|
|
15
16
|
}
|
|
16
17
|
}
|
|
17
|
-
function
|
|
18
|
-
let [
|
|
18
|
+
function c() {
|
|
19
|
+
let [c] = n();
|
|
19
20
|
return t(() => {
|
|
20
|
-
let t =
|
|
21
|
+
let t = s(c.get("returnTo")), n = window.location.hash;
|
|
21
22
|
if (!n.startsWith("#sso=")) {
|
|
22
23
|
window.location.replace("/auth/login");
|
|
23
24
|
return;
|
|
24
25
|
}
|
|
25
26
|
try {
|
|
26
|
-
let r = n.slice(5), { profileId:
|
|
27
|
-
if (!
|
|
27
|
+
let r = n.slice(5), { profileId: a, tokens: s, user: c, profiles: l } = JSON.parse(atob(r));
|
|
28
|
+
if (!a || !s) {
|
|
28
29
|
window.location.replace("/auth/login");
|
|
29
30
|
return;
|
|
30
31
|
}
|
|
31
|
-
localStorage.setItem(`bf-p-${
|
|
32
|
+
localStorage.setItem(`bf-p-${a}-tokens`, s), c && localStorage.setItem(`bf-p-${a}-user`, c), l && localStorage.setItem("bf-profiles", l), sessionStorage.setItem("bf-active-profile", a), i(a), e.getState().loadFromProfile(a), window.dispatchEvent(new Event("bf-profile-storage-change")), o()?.notifyLogin({
|
|
32
33
|
user: c ? JSON.parse(c) : null,
|
|
33
34
|
tokens: s ? JSON.parse(s) : null,
|
|
34
|
-
activeProfileId:
|
|
35
|
+
activeProfileId: a,
|
|
35
36
|
profiles: l ? JSON.parse(l) : []
|
|
36
37
|
}), window.location.replace(t);
|
|
37
38
|
} catch {
|
|
38
39
|
window.location.replace("/auth/login");
|
|
39
40
|
}
|
|
40
|
-
}, [
|
|
41
|
-
className: "flex items-center justify-center min-h-screen bg-bg-canvas",
|
|
42
|
-
children: /* @__PURE__ */ r("div", { className: "animate-spin rounded-full size-8 border-2 border-action-primary-bg border-t-transparent" })
|
|
43
|
-
});
|
|
41
|
+
}, [c]), /* @__PURE__ */ r(a, { label: "Signing you in…" });
|
|
44
42
|
}
|
|
45
43
|
//#endregion
|
|
46
|
-
export {
|
|
44
|
+
export { c as SSORelayCallbackPage };
|
|
47
45
|
|
|
48
46
|
//# sourceMappingURL=SSORelayCallbackPage.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SSORelayCallbackPage.js","names":[],"sources":["../../../src/auth/pages/SSORelayCallbackPage.tsx"],"sourcesContent":["/**\n * SSORelayCallbackPage — Receives tokens from the SSO relay and stores them locally.\n *\n * Tokens arrive in the URL fragment (#sso=<base64>) which is never sent to servers.\n * After storing in localStorage, redirects to the returnTo path.\n */\n\nimport { useEffect } from \"react\";\nimport { useSearchParams } from \"react-router-dom\";\nimport { getAuthBridge } from \"@burdenoff/fe-libs/shared/providers/shell/AuthBridgeClient\";\nimport { setSSoCookie } from \"@burdenoff/fe-libs/shared/utils\";\nimport { useAuthStore } from \"../store/authStore\";\n\nfunction getSafeReturnTo(returnTo: string | null): string {\n if (!returnTo) return \"/dashboard\";\n\n try {\n const url = new URL(returnTo, window.location.origin);\n if (url.origin !== window.location.origin) return \"/dashboard\";\n return `${url.pathname}${url.search}${url.hash}`;\n } catch {\n return \"/dashboard\";\n }\n}\n\nexport function SSORelayCallbackPage() {\n const [searchParams] = useSearchParams();\n\n useEffect(() => {\n const returnTo = getSafeReturnTo(searchParams.get(\"returnTo\"));\n const hash = window.location.hash;\n\n if (!hash.startsWith(\"#sso=\")) {\n // No SSO data — redirect to login\n window.location.replace(\"/auth/login\");\n return;\n }\n\n try {\n const encoded = hash.slice(5); // Remove \"#sso=\"\n const payload = JSON.parse(atob(encoded));\n const { profileId, tokens, user, profiles } = payload;\n\n if (!profileId || !tokens) {\n window.location.replace(\"/auth/login\");\n return;\n }\n\n // Store tokens in localStorage\n localStorage.setItem(`bf-p-${profileId}-tokens`, tokens);\n if (user) {\n localStorage.setItem(`bf-p-${profileId}-user`, user);\n }\n if (profiles) {\n localStorage.setItem(\"bf-profiles\", profiles);\n }\n sessionStorage.setItem(\"bf-active-profile\", profileId);\n setSSoCookie(profileId);\n useAuthStore.getState().loadFromProfile(profileId);\n\n // Dispatch event so AuthProvider picks up the new state\n window.dispatchEvent(new Event(\"bf-profile-storage-change\"));\n\n // Notify the auth bridge so other open shells can pick up the new session\n getAuthBridge()?.notifyLogin({\n user: user ? JSON.parse(user) : null,\n tokens: tokens ? JSON.parse(tokens) : null,\n activeProfileId: profileId,\n profiles: profiles ? JSON.parse(profiles) : [],\n });\n\n // Clear the hash and redirect\n window.location.replace(returnTo);\n } catch {\n window.location.replace(\"/auth/login\");\n }\n }, [searchParams]);\n\n return
|
|
1
|
+
{"version":3,"file":"SSORelayCallbackPage.js","names":[],"sources":["../../../src/auth/pages/SSORelayCallbackPage.tsx"],"sourcesContent":["/**\n * SSORelayCallbackPage — Receives tokens from the SSO relay and stores them locally.\n *\n * Tokens arrive in the URL fragment (#sso=<base64>) which is never sent to servers.\n * After storing in localStorage, redirects to the returnTo path.\n */\n\nimport { useEffect } from \"react\";\nimport { BrandedSplash } from \"@burdenoff/fe-libs/ui\";\nimport { useSearchParams } from \"react-router-dom\";\nimport { getAuthBridge } from \"@burdenoff/fe-libs/shared/providers/shell/AuthBridgeClient\";\nimport { setSSoCookie } from \"@burdenoff/fe-libs/shared/utils\";\nimport { useAuthStore } from \"../store/authStore\";\n\nfunction getSafeReturnTo(returnTo: string | null): string {\n if (!returnTo) return \"/dashboard\";\n\n try {\n const url = new URL(returnTo, window.location.origin);\n if (url.origin !== window.location.origin) return \"/dashboard\";\n return `${url.pathname}${url.search}${url.hash}`;\n } catch {\n return \"/dashboard\";\n }\n}\n\nexport function SSORelayCallbackPage() {\n const [searchParams] = useSearchParams();\n\n useEffect(() => {\n const returnTo = getSafeReturnTo(searchParams.get(\"returnTo\"));\n const hash = window.location.hash;\n\n if (!hash.startsWith(\"#sso=\")) {\n // No SSO data — redirect to login\n window.location.replace(\"/auth/login\");\n return;\n }\n\n try {\n const encoded = hash.slice(5); // Remove \"#sso=\"\n const payload = JSON.parse(atob(encoded));\n const { profileId, tokens, user, profiles } = payload;\n\n if (!profileId || !tokens) {\n window.location.replace(\"/auth/login\");\n return;\n }\n\n // Store tokens in localStorage\n localStorage.setItem(`bf-p-${profileId}-tokens`, tokens);\n if (user) {\n localStorage.setItem(`bf-p-${profileId}-user`, user);\n }\n if (profiles) {\n localStorage.setItem(\"bf-profiles\", profiles);\n }\n sessionStorage.setItem(\"bf-active-profile\", profileId);\n setSSoCookie(profileId);\n useAuthStore.getState().loadFromProfile(profileId);\n\n // Dispatch event so AuthProvider picks up the new state\n window.dispatchEvent(new Event(\"bf-profile-storage-change\"));\n\n // Notify the auth bridge so other open shells can pick up the new session\n getAuthBridge()?.notifyLogin({\n user: user ? JSON.parse(user) : null,\n tokens: tokens ? JSON.parse(tokens) : null,\n activeProfileId: profileId,\n profiles: profiles ? JSON.parse(profiles) : [],\n });\n\n // Clear the hash and redirect\n window.location.replace(returnTo);\n } catch {\n window.location.replace(\"/auth/login\");\n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,UAAO,SAAS,QAAQ,cAAc;;IAEvC,CAAC,EAAa,CAAC,EAEX,kBAAC,GAAD,EAAe,OAAM,mBAAoB,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@burdenoff/microfe-auth",
|
|
3
|
-
"version": "2026.
|
|
3
|
+
"version": "2026.708.1",
|
|
4
4
|
"description": "Auth microfrontend for Burdenoff products",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"imports": {
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"@apollo/client": "^4.0.9",
|
|
47
|
-
"@burdenoff/fe-libs": "2026.
|
|
47
|
+
"@burdenoff/fe-libs": "2026.704.2",
|
|
48
48
|
"@types/qrcode.react": "^3.0.0",
|
|
49
49
|
"clsx": "^2.1.1",
|
|
50
50
|
"graphql": "^16.12.0",
|