@lumoauth/client 0.0.0-stage → 1.1.0

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/index.js ADDED
@@ -0,0 +1,462 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ EMPTY_TOKENS: () => EMPTY_TOKENS,
25
+ LumoAuth: () => LumoAuth,
26
+ LumoAuthSession: () => LumoAuthSession,
27
+ cookieStorageAdapter: () => cookieStorageAdapter,
28
+ defaultStorage: () => defaultStorage,
29
+ localStorageAdapter: () => localStorageAdapter,
30
+ memoryStorageAdapter: () => memoryStorageAdapter,
31
+ sessionStorageAdapter: () => sessionStorageAdapter
32
+ });
33
+ module.exports = __toCommonJS(index_exports);
34
+
35
+ // src/client.ts
36
+ var import_shared2 = require("@lumoauth/shared");
37
+
38
+ // src/guard.ts
39
+ var import_shared = require("@lumoauth/shared");
40
+ var TENANT_API_KEY_PREFIX = "lmk_";
41
+ function inBrowser() {
42
+ return typeof window !== "undefined" && typeof window.document !== "undefined";
43
+ }
44
+ function assertBrowserSafeCredential(token) {
45
+ if (typeof token !== "string" || token === "") return;
46
+ if (!token.startsWith(TENANT_API_KEY_PREFIX)) return;
47
+ if (!inBrowser()) return;
48
+ throw new import_shared.LumoAuthConfigError(
49
+ "Refusing to use a LumoAuth tenant API key (lmk_\u2026) in @lumoauth/client. This package runs in the browser, where the key would be readable by anyone using the app, and it authenticates as your entire organization. Use a per-user access token here, and move any code that needs the API key to the server with @lumoauth/backend."
50
+ );
51
+ }
52
+
53
+ // src/client.ts
54
+ var LumoAuth = class {
55
+ constructor(config) {
56
+ if (!config.baseUrl) {
57
+ throw new import_shared2.LumoAuthConfigError("baseUrl is required");
58
+ }
59
+ assertBrowserSafeCredential(config.token);
60
+ const tokenProvider = config.token ?? (() => "");
61
+ const httpConfig = {
62
+ baseUrl: config.baseUrl,
63
+ token: tokenProvider,
64
+ timeout: config.timeout,
65
+ fetch: config.fetch,
66
+ headers: config.headers
67
+ };
68
+ this.http = new import_shared2.HttpClient(httpConfig);
69
+ this.permissions = new import_shared2.PermissionsModule(this.http, {
70
+ cache: config.cache
71
+ });
72
+ this.zanzibar = new import_shared2.ZanzibarModule(this.http);
73
+ this.abac = new import_shared2.AbacModule(this.http, config.orgId ?? "");
74
+ const authConfig = {
75
+ baseUrl: config.baseUrl,
76
+ orgId: config.orgId ?? "",
77
+ clientId: config.clientId ?? "",
78
+ fetch: config.fetch
79
+ };
80
+ this.auth = new import_shared2.AuthModule(authConfig);
81
+ this.agents = new import_shared2.AgentsModule(this.http, config.orgId ?? "");
82
+ const approvals = new import_shared2.ApprovalsModule(this.http, config.orgId ?? "");
83
+ this.approvals = {
84
+ getStatus: approvals.getStatus.bind(approvals),
85
+ wait: approvals.wait.bind(approvals)
86
+ };
87
+ }
88
+ /**
89
+ * @deprecated Renamed to {@link agents}. This alias will be removed
90
+ * before 2.0.
91
+ */
92
+ get agent() {
93
+ return this.agents;
94
+ }
95
+ /**
96
+ * Clear all client-side caches.
97
+ * Call after the user's roles, groups, or attributes change.
98
+ */
99
+ clearCache() {
100
+ this.permissions.clearCache();
101
+ }
102
+ };
103
+
104
+ // src/storage.ts
105
+ var EMPTY_TOKENS = {
106
+ accessToken: null,
107
+ refreshToken: null,
108
+ idToken: null,
109
+ expiresAt: null
110
+ };
111
+ var TOKEN_KEY = "lumoauth_tokens";
112
+ function hasWindow() {
113
+ return typeof window !== "undefined";
114
+ }
115
+ function parse(raw) {
116
+ if (!raw) return EMPTY_TOKENS;
117
+ try {
118
+ const v = JSON.parse(raw);
119
+ return {
120
+ accessToken: v.accessToken ?? null,
121
+ refreshToken: v.refreshToken ?? null,
122
+ idToken: v.idToken ?? null,
123
+ expiresAt: typeof v.expiresAt === "number" ? v.expiresAt : null
124
+ };
125
+ } catch {
126
+ return EMPTY_TOKENS;
127
+ }
128
+ }
129
+ function webStorageAdapter(name, pick, crossTab) {
130
+ const store = () => {
131
+ if (!hasWindow()) return null;
132
+ try {
133
+ return pick();
134
+ } catch {
135
+ return null;
136
+ }
137
+ };
138
+ return {
139
+ name,
140
+ get() {
141
+ try {
142
+ return parse(store()?.getItem(TOKEN_KEY) ?? null);
143
+ } catch {
144
+ return EMPTY_TOKENS;
145
+ }
146
+ },
147
+ set(tokens) {
148
+ try {
149
+ const s = store();
150
+ if (!s) return;
151
+ if (tokens.accessToken) s.setItem(TOKEN_KEY, JSON.stringify(tokens));
152
+ else s.removeItem(TOKEN_KEY);
153
+ } catch {
154
+ }
155
+ },
156
+ clear() {
157
+ try {
158
+ store()?.removeItem(TOKEN_KEY);
159
+ } catch {
160
+ }
161
+ },
162
+ // Only localStorage raises `storage` in other tabs. sessionStorage is
163
+ // per-tab by definition, so there is nothing to subscribe to.
164
+ subscribe: crossTab ? (onExternalChange) => {
165
+ if (!hasWindow()) return () => {
166
+ };
167
+ const handler = (e) => {
168
+ if (e.key === TOKEN_KEY || e.key === null) onExternalChange();
169
+ };
170
+ window.addEventListener("storage", handler);
171
+ return () => window.removeEventListener("storage", handler);
172
+ } : void 0
173
+ };
174
+ }
175
+ function sessionStorageAdapter() {
176
+ return webStorageAdapter("sessionStorage", () => window.sessionStorage, false);
177
+ }
178
+ function localStorageAdapter() {
179
+ return webStorageAdapter("localStorage", () => window.localStorage, true);
180
+ }
181
+ function memoryStorageAdapter() {
182
+ let tokens = EMPTY_TOKENS;
183
+ return {
184
+ name: "memory",
185
+ get: () => tokens,
186
+ set: (t) => {
187
+ tokens = t;
188
+ },
189
+ clear: () => {
190
+ tokens = EMPTY_TOKENS;
191
+ }
192
+ };
193
+ }
194
+ function cookieStorageAdapter(options = {}) {
195
+ const sessionEndpoint = options.sessionEndpoint ?? "/auth/session";
196
+ const logoutEndpoint = options.logoutEndpoint ?? "/auth/logout";
197
+ const doFetch = options.fetch ?? ((...a) => globalThis.fetch(...a));
198
+ return {
199
+ name: "cookie",
200
+ async get() {
201
+ if (!hasWindow()) return EMPTY_TOKENS;
202
+ try {
203
+ const res = await doFetch(sessionEndpoint, {
204
+ credentials: "include",
205
+ headers: { Accept: "application/json" }
206
+ });
207
+ if (!res.ok) return EMPTY_TOKENS;
208
+ const data = await res.json();
209
+ return {
210
+ accessToken: data.accessToken ?? null,
211
+ refreshToken: null,
212
+ // never leaves the server
213
+ idToken: data.idToken ?? null,
214
+ expiresAt: typeof data.expiresAt === "number" ? data.expiresAt : null
215
+ };
216
+ } catch {
217
+ return EMPTY_TOKENS;
218
+ }
219
+ },
220
+ set() {
221
+ },
222
+ async clear() {
223
+ if (!hasWindow()) return;
224
+ try {
225
+ await doFetch(logoutEndpoint, { method: "POST", credentials: "include" });
226
+ } catch {
227
+ }
228
+ }
229
+ };
230
+ }
231
+ function defaultStorage() {
232
+ return hasWindow() ? sessionStorageAdapter() : memoryStorageAdapter();
233
+ }
234
+
235
+ // src/session.ts
236
+ var INITIAL = {
237
+ status: "loading",
238
+ isLoaded: false,
239
+ isSignedIn: false,
240
+ error: null
241
+ };
242
+ var REFRESH_MARGIN_MS = 6e4;
243
+ var PROACTIVE_WINDOW_MS = 3e4;
244
+ var MIN_TIMER_MS = 5e3;
245
+ var CHANNEL = "lumoauth.session";
246
+ var LumoAuthSession = class _LumoAuthSession {
247
+ constructor(opts) {
248
+ this.state = INITIAL;
249
+ this.tokens = EMPTY_TOKENS;
250
+ this.listeners = /* @__PURE__ */ new Set();
251
+ this.timer = null;
252
+ this.channel = null;
253
+ this.unsubscribeStorage = null;
254
+ this.inflightRefresh = null;
255
+ // ── Store interface ──────────────────────────────────────────────
256
+ this.subscribe = (fn) => {
257
+ this.listeners.add(fn);
258
+ return () => this.listeners.delete(fn);
259
+ };
260
+ this.getSnapshot = () => this.state;
261
+ /** Server snapshot for `useSyncExternalStore` — always the loading state. */
262
+ this.getServerSnapshot = () => INITIAL;
263
+ this.auth = opts.auth;
264
+ this.storage = opts.storage ?? defaultStorage();
265
+ this.redirectUri = opts.redirectUri;
266
+ this.scope = opts.scope ?? "openid profile email";
267
+ this.onTokens = opts.onTokens;
268
+ if (opts.crossTab !== false && typeof BroadcastChannel !== "undefined") {
269
+ this.channel = new BroadcastChannel(CHANNEL);
270
+ this.channel.onmessage = (e) => this.onBroadcast(e.data);
271
+ }
272
+ this.unsubscribeStorage = this.storage.subscribe?.(() => {
273
+ void this.hydrate();
274
+ }) ?? null;
275
+ }
276
+ emit(next) {
277
+ this.state = { ...this.state, ...next };
278
+ this.listeners.forEach((l) => l());
279
+ }
280
+ // ── Lifecycle ────────────────────────────────────────────────────
281
+ /** Load persisted tokens and settle into signed-in or signed-out. */
282
+ async hydrate() {
283
+ const tokens = await this.storage.get();
284
+ this.tokens = tokens;
285
+ if (!tokens.accessToken) {
286
+ this.emit({ status: "unauthenticated", isLoaded: true, isSignedIn: false });
287
+ return;
288
+ }
289
+ if (tokens.expiresAt && tokens.expiresAt <= Date.now()) {
290
+ const refreshed = await this.refresh();
291
+ if (!refreshed) return;
292
+ }
293
+ this.scheduleRefresh();
294
+ this.emit({ status: "authenticated", isLoaded: true, isSignedIn: true, error: null });
295
+ this.onTokens?.(this.tokens);
296
+ }
297
+ dispose() {
298
+ if (this.timer) clearTimeout(this.timer);
299
+ this.timer = null;
300
+ this.channel?.close();
301
+ this.channel = null;
302
+ this.unsubscribeStorage?.();
303
+ this.unsubscribeStorage = null;
304
+ this.listeners.clear();
305
+ }
306
+ // ── Tokens ───────────────────────────────────────────────────────
307
+ getTokens() {
308
+ return this.tokens;
309
+ }
310
+ async persist(tokens, broadcast = true) {
311
+ this.tokens = tokens;
312
+ await this.storage.set(tokens);
313
+ if (broadcast) this.channel?.postMessage({ type: "tokens", tokens });
314
+ this.onTokens?.(tokens);
315
+ }
316
+ static tokensFrom(res, previous) {
317
+ return {
318
+ accessToken: res.access_token,
319
+ // A refresh response may omit the refresh token when it is not
320
+ // rotated; keep the existing one rather than losing the session.
321
+ refreshToken: res.refresh_token ?? previous?.refreshToken ?? null,
322
+ idToken: res.id_token ?? previous?.idToken ?? null,
323
+ expiresAt: Date.now() + res.expires_in * 1e3
324
+ };
325
+ }
326
+ /**
327
+ * A valid access token, refreshing first if it is about to expire.
328
+ * Returns null when there is no session.
329
+ */
330
+ async getToken() {
331
+ const { accessToken, expiresAt } = this.tokens;
332
+ if (!accessToken) return null;
333
+ if (expiresAt && expiresAt - Date.now() < PROACTIVE_WINDOW_MS) {
334
+ return this.refresh();
335
+ }
336
+ return accessToken;
337
+ }
338
+ /**
339
+ * Refresh the access token.
340
+ *
341
+ * Concurrent callers share one in-flight request. Across tabs, a Web Lock
342
+ * elects a single refresher — without it, every tab refreshes on its own
343
+ * timer and they race on a rotated refresh token, so all but the winner
344
+ * are signed out.
345
+ */
346
+ async refresh() {
347
+ if (this.inflightRefresh) return this.inflightRefresh;
348
+ this.inflightRefresh = this.doRefresh().finally(() => {
349
+ this.inflightRefresh = null;
350
+ });
351
+ return this.inflightRefresh;
352
+ }
353
+ async doRefresh() {
354
+ if (!this.tokens.refreshToken) {
355
+ await this.clearSession("no_refresh_token");
356
+ return null;
357
+ }
358
+ const run = async () => {
359
+ const stored = await this.storage.get();
360
+ const fresher = [stored, this.tokens].filter((t) => t.accessToken && t.expiresAt).sort((a, b) => (b.expiresAt ?? 0) - (a.expiresAt ?? 0))[0];
361
+ if (fresher && (fresher.expiresAt ?? 0) - Date.now() > PROACTIVE_WINDOW_MS) {
362
+ this.tokens = fresher;
363
+ this.scheduleRefresh();
364
+ return fresher.accessToken;
365
+ }
366
+ const refreshToken = this.tokens.refreshToken;
367
+ if (!refreshToken) {
368
+ await this.clearSession("no_refresh_token");
369
+ return null;
370
+ }
371
+ try {
372
+ const res = await this.auth.refreshToken(refreshToken);
373
+ await this.persist(_LumoAuthSession.tokensFrom(res, this.tokens));
374
+ this.scheduleRefresh();
375
+ this.emit({ status: "authenticated", isLoaded: true, isSignedIn: true, error: null });
376
+ return this.tokens.accessToken;
377
+ } catch {
378
+ await this.clearSession("refresh_failed");
379
+ return null;
380
+ }
381
+ };
382
+ const locks = globalThis.navigator?.locks;
383
+ if (locks?.request) {
384
+ return locks.request(CHANNEL + ".refresh", run);
385
+ }
386
+ return run();
387
+ }
388
+ scheduleRefresh() {
389
+ if (this.timer) clearTimeout(this.timer);
390
+ this.timer = null;
391
+ const { expiresAt, refreshToken } = this.tokens;
392
+ if (!expiresAt || !refreshToken) return;
393
+ const delay = Math.max(expiresAt - Date.now() - REFRESH_MARGIN_MS, MIN_TIMER_MS);
394
+ this.timer = setTimeout(() => void this.refresh(), delay);
395
+ }
396
+ // ── Flows ────────────────────────────────────────────────────────
397
+ /** Adopt tokens obtained elsewhere (e.g. a completed code exchange). */
398
+ async adopt(res) {
399
+ await this.persist(_LumoAuthSession.tokensFrom(res, this.tokens));
400
+ this.scheduleRefresh();
401
+ this.emit({ status: "authenticated", isLoaded: true, isSignedIn: true, error: null });
402
+ }
403
+ /** Build the PKCE authorization URL; the caller persists verifier + state. */
404
+ buildAuthorizationUrl(extraParams) {
405
+ return this.auth.buildAuthorizationUrl({
406
+ redirectUri: this.redirectUri,
407
+ scope: this.scope,
408
+ ...extraParams ? { extraParams } : {}
409
+ });
410
+ }
411
+ /**
412
+ * Drop the session.
413
+ *
414
+ * `emit: false` clears tokens and storage without notifying subscribers.
415
+ * That is required during sign-out: emitting re-renders the tree, which
416
+ * mounts any `<SignedOut><RedirectToSignIn/></SignedOut>` guard, whose
417
+ * effect then races the pending logout navigation and sends the user back
418
+ * to /authorize — where the IdP session is still alive and silently
419
+ * re-issues a code, defeating logout entirely.
420
+ */
421
+ async clearSession(error = null, opts = {}) {
422
+ const { broadcast = true, emit = true } = opts;
423
+ if (this.timer) clearTimeout(this.timer);
424
+ this.timer = null;
425
+ this.tokens = EMPTY_TOKENS;
426
+ await this.storage.clear();
427
+ if (broadcast) this.channel?.postMessage({ type: "signout" });
428
+ if (emit) {
429
+ this.emit({ status: "unauthenticated", isLoaded: true, isSignedIn: false, error });
430
+ }
431
+ }
432
+ // ── Cross-tab ────────────────────────────────────────────────────
433
+ onBroadcast(msg) {
434
+ if (!msg) return;
435
+ if (msg.type === "signout") {
436
+ void this.clearSession(null, { broadcast: false });
437
+ return;
438
+ }
439
+ if (msg.type === "tokens" && msg.tokens) {
440
+ this.tokens = msg.tokens;
441
+ this.scheduleRefresh();
442
+ this.emit({ status: "authenticated", isLoaded: true, isSignedIn: true, error: null });
443
+ this.onTokens?.(msg.tokens);
444
+ }
445
+ }
446
+ };
447
+
448
+ // src/index.ts
449
+ __reExport(index_exports, require("@lumoauth/shared"), module.exports);
450
+ // Annotate the CommonJS export names for ESM import in node:
451
+ 0 && (module.exports = {
452
+ EMPTY_TOKENS,
453
+ LumoAuth,
454
+ LumoAuthSession,
455
+ cookieStorageAdapter,
456
+ defaultStorage,
457
+ localStorageAdapter,
458
+ memoryStorageAdapter,
459
+ sessionStorageAdapter,
460
+ ...require("@lumoauth/shared")
461
+ });
462
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/guard.ts","../src/storage.ts","../src/session.ts"],"sourcesContent":["// @lumoauth/client — the browser SDK.\n//\n// This is the package application code imports. It re-exports all of\n// @lumoauth/shared so callers need a single dependency, and adds the\n// `LumoAuth` client itself.\n//\n// It is browser-safe by construction: constructing it with a tenant API key\n// (`lmk_…`) in a browser is a hard error. Server-only surfaces live in\n// @lumoauth/backend (token verification, admin) and @lumoauth/agent (AAuth,\n// which needs `node:crypto`).\n\nexport { LumoAuth, type LumoAuthConfig, type ClientApprovals } from './client';\n\n// ─── Session runtime (framework-agnostic) ─────────────────────────────\n// The store @lumoauth/react binds to. Exported so a Vue/Svelte binding can\n// use the same runtime instead of reimplementing refresh and cross-tab logic.\nexport {\n LumoAuthSession,\n type SessionState,\n type SessionStatus,\n type SessionOptions,\n} from './session';\n\n// ─── Token storage ────────────────────────────────────────────────────\nexport {\n type TokenStorage,\n type StoredTokens,\n type CookieStorageOptions,\n EMPTY_TOKENS,\n sessionStorageAdapter,\n localStorageAdapter,\n memoryStorageAdapter,\n cookieStorageAdapter,\n defaultStorage,\n} from './storage';\n\n// The full isomorphic surface: authorization modules, OAuth/PKCE helpers,\n// schemas, errors, and the HTTP client.\nexport * from '@lumoauth/shared';\n","import {\n HttpClient,\n type HttpClientConfig,\n PermissionsModule,\n type PermissionsModuleOptions,\n ZanzibarModule,\n AbacModule,\n AuthModule,\n type AuthModuleConfig,\n AgentsModule,\n ApprovalsModule,\n LumoAuthConfigError,\n} from '@lumoauth/shared';\nimport { assertBrowserSafeCredential } from './guard';\n\n// ─── Config ───────────────────────────────────────────────────────────\n\nexport interface LumoAuthConfig {\n /**\n * Base URL of your LumoAuth instance.\n * @example \"https://auth.example.com\"\n */\n baseUrl: string;\n\n /**\n * Access token for the authenticated user.\n * Can be a static string or an async function that returns a fresh token.\n *\n * Optional — not needed before first sign-in when using PKCE flow.\n *\n * @example\n * // Static token\n * token: 'eyJhbGciOi...'\n *\n * // Dynamic token (recommended for SPAs & server-side)\n * token: () => getAccessTokenFromSession()\n */\n token?: string | (() => string | Promise<string>);\n\n /**\n * Authentication strategy.\n * - `'pkce'` — OAuth 2.0 Authorization Code + PKCE (default, recommended for SPAs)\n * - `'password'` — Resource Owner Password Credentials grant (legacy)\n *\n * @default 'pkce'\n */\n authStrategy?: 'pkce' | 'password';\n\n /**\n * Your organization ID (e.g. \"acme-corp\").\n * Required for building authorization URLs.\n */\n orgId?: string;\n\n /**\n * OAuth client ID.\n * Required when using the auth module.\n */\n clientId?: string;\n\n /** Request timeout in milliseconds. Default: 30 000 ms. */\n timeout?: number;\n\n /**\n * Custom `fetch` implementation.\n * Defaults to the global `fetch`. Useful for testing or\n * environments without a global `fetch` (e.g. older Node.js).\n */\n fetch?: typeof globalThis.fetch;\n\n /** Additional headers sent with every request. */\n headers?: Record<string, string>;\n\n /** Options for the permissions module cache. */\n cache?: boolean | PermissionsModuleOptions['cache'];\n}\n\n/**\n * Browser-safe subset of the approvals surface: status polling only.\n * Creating approvals lives on the server/agent SDKs.\n */\nexport type ClientApprovals = Pick<ApprovalsModule, 'getStatus' | 'wait'>;\n\n// ─── Client ───────────────────────────────────────────────────────────\n\n/**\n * The main LumoAuth client. Provides access to all authorization and\n * authentication modules.\n *\n * @example\n * ```ts\n * import { LumoAuth } from '@lumoauth/client';\n *\n * // PKCE mode (recommended)\n * const client = new LumoAuth({\n * baseUrl: 'https://auth.example.com',\n * orgId: 'acme-corp',\n * clientId: 'my-client-id',\n * });\n *\n * // Build authorization URL and redirect\n * const { url, codeVerifier, state } = await client.auth.buildAuthorizationUrl({\n * redirectUri: 'http://localhost:3000/callback',\n * });\n *\n * // Legacy mode with token\n * const authedClient = new LumoAuth({\n * baseUrl: 'https://auth.example.com',\n * token: () => getAccessToken(),\n * });\n *\n * // Permission checks (RBAC)\n * const canEdit = await authedClient.permissions.check('document.edit');\n * ```\n */\nexport class LumoAuth {\n /** RBAC permission checks. */\n public readonly permissions: PermissionsModule;\n /** Zanzibar-style (ReBAC) relationship checks. */\n public readonly zanzibar: ZanzibarModule;\n /** ABAC policy evaluation and attribute management. */\n public readonly abac: AbacModule;\n /** OAuth 2.0 authentication — PKCE flow, token exchange, refresh. */\n public readonly auth: AuthModule;\n /** Agent identity — ask/isAllowed and self-inspection. */\n public readonly agents: AgentsModule;\n /**\n * Approval status polling — the browser-safe subset of the approvals\n * surface. Creating approvals (`require()`) is an agent/server action;\n * use `@lumoauth/backend` or `@lumoauth/agent` for that.\n */\n public readonly approvals: ClientApprovals;\n\n private readonly http: HttpClient;\n\n constructor(config: LumoAuthConfig) {\n if (!config.baseUrl) {\n throw new LumoAuthConfigError('baseUrl is required');\n }\n\n // Refuse a server credential in a client that ships to browsers.\n // See ./guard for why this is a hard error rather than a warning.\n assertBrowserSafeCredential(config.token);\n\n // Token is optional when using PKCE flow (no token before first sign-in)\n const tokenProvider = config.token ?? (() => '');\n\n const httpConfig: HttpClientConfig = {\n baseUrl: config.baseUrl,\n token: tokenProvider,\n timeout: config.timeout,\n fetch: config.fetch,\n headers: config.headers,\n };\n\n this.http = new HttpClient(httpConfig);\n\n this.permissions = new PermissionsModule(this.http, {\n cache: config.cache,\n });\n this.zanzibar = new ZanzibarModule(this.http);\n this.abac = new AbacModule(this.http, config.orgId ?? '');\n\n // Auth module\n const authConfig: AuthModuleConfig = {\n baseUrl: config.baseUrl,\n orgId: config.orgId ?? '',\n clientId: config.clientId ?? '',\n fetch: config.fetch,\n };\n this.auth = new AuthModule(authConfig);\n\n // Agents module — org-scoped, so it needs `orgId`; the guard fires\n // lazily when a method is called.\n this.agents = new AgentsModule(this.http, config.orgId ?? '');\n\n // Approvals — browser-safe subset (status polling only).\n const approvals = new ApprovalsModule(this.http, config.orgId ?? '');\n this.approvals = {\n getStatus: approvals.getStatus.bind(approvals),\n wait: approvals.wait.bind(approvals),\n };\n }\n\n /**\n * @deprecated Renamed to {@link agents}. This alias will be removed\n * before 2.0.\n */\n get agent(): AgentsModule {\n return this.agents;\n }\n\n /**\n * Clear all client-side caches.\n * Call after the user's roles, groups, or attributes change.\n */\n clearCache(): void {\n this.permissions.clearCache();\n }\n}\n","import { LumoAuthConfigError } from '@lumoauth/shared';\n\n/**\n * Prefix of a LumoAuth tenant API key (`TenantApiKeyService::KEY_PREFIX`).\n * These are server credentials: they authenticate as the tenant, not as a\n * user, and they do not expire on their own.\n */\nconst TENANT_API_KEY_PREFIX = 'lmk_';\n\n/** True when this code is executing in something that looks like a browser. */\nfunction inBrowser(): boolean {\n return typeof window !== 'undefined' && typeof window.document !== 'undefined';\n}\n\n/**\n * Reject server credentials in `@lumoauth/client`.\n *\n * `@lumoauth/client` is designed to ship to browsers, where anything it holds\n * is readable by the user and by any script on the origin. A user access token\n * is fine there — it is short-lived and scoped to one person. A tenant API key\n * (`lmk_…`) is not: it authenticates as the whole organization.\n *\n * This is a hard error rather than a warning because the failure is silent\n * otherwise. The mistake it prevents is the easy one: copying a server-side\n * setup (`token: process.env.LUMOAUTH_AGENT_TOKEN`) into a component that ends\n * up in the client bundle. Nothing else catches that — bundlers happily inline\n * the value, and the request succeeds, so it looks like it works.\n *\n * Server-side code should import `@lumoauth/backend` instead, which accepts\n * these credentials and refuses to construct in a browser.\n *\n * Only static string tokens can be checked here. A `() => string` provider is\n * resolved per-request and may legitimately return a user token, so it is left\n * alone — the guard cannot tell the two apart without calling it.\n */\nexport function assertBrowserSafeCredential(\n token: string | (() => string | Promise<string>) | undefined,\n): void {\n if (typeof token !== 'string' || token === '') return;\n if (!token.startsWith(TENANT_API_KEY_PREFIX)) return;\n if (!inBrowser()) return;\n\n throw new LumoAuthConfigError(\n 'Refusing to use a LumoAuth tenant API key (lmk_…) in @lumoauth/client. ' +\n 'This package runs in the browser, where the key would be readable by ' +\n 'anyone using the app, and it authenticates as your entire organization. ' +\n 'Use a per-user access token here, and move any code that needs the API ' +\n 'key to the server with @lumoauth/backend.',\n );\n}\n","/**\n * Token storage adapters.\n *\n * Where tokens live is the single most consequential security decision in a\n * browser SDK, and the right answer depends on the app. This module makes it a\n * choice rather than a hardcoded default.\n *\n * The trade-off:\n *\n * | Adapter | XSS-readable | Survives reload | Cross-tab | SSR |\n * |------------------|--------------|-----------------|-----------|-----|\n * | `sessionStorage` | yes | per tab | no | no |\n * | `localStorage` | yes | yes | yes | no |\n * | `memory` | no* | no | no | yes |\n * | `cookie` (BFF) | no | yes | yes | yes |\n *\n * \\* memory is not readable from another origin's script, but it is still in\n * the JS heap; it is \"safe\" only in the sense that nothing persists.\n *\n * `cookie` is the strongest option: tokens live in an httpOnly cookie your\n * server sets, and never enter JavaScript at all. It requires a same-origin\n * backend to exchange and refresh on the browser's behalf, which is what\n * @lumoauth/express and (Phase 3) @lumoauth/nextjs provide.\n */\n\nexport interface StoredTokens {\n accessToken: string | null;\n refreshToken: string | null;\n idToken: string | null;\n /** Absolute expiry, epoch milliseconds. */\n expiresAt: number | null;\n}\n\nexport const EMPTY_TOKENS: StoredTokens = {\n accessToken: null,\n refreshToken: null,\n idToken: null,\n expiresAt: null,\n};\n\nexport interface TokenStorage {\n /** Identifies the adapter in errors and diagnostics. */\n readonly name: string;\n get(): StoredTokens | Promise<StoredTokens>;\n set(tokens: StoredTokens): void | Promise<void>;\n clear(): void | Promise<void>;\n /**\n * Optional. Called when the store changes outside this tab; return an\n * unsubscribe function. Adapters backed by a shared medium (localStorage,\n * cookies) can implement this so other tabs stay in sync.\n */\n subscribe?(onExternalChange: () => void): () => void;\n}\n\nconst TOKEN_KEY = 'lumoauth_tokens';\n\nfunction hasWindow(): boolean {\n return typeof window !== 'undefined';\n}\n\n/** Parse without throwing — corrupt storage should sign the user out, not crash. */\nfunction parse(raw: string | null): StoredTokens {\n if (!raw) return EMPTY_TOKENS;\n try {\n const v = JSON.parse(raw) as Partial<StoredTokens>;\n return {\n accessToken: v.accessToken ?? null,\n refreshToken: v.refreshToken ?? null,\n idToken: v.idToken ?? null,\n expiresAt: typeof v.expiresAt === 'number' ? v.expiresAt : null,\n };\n } catch {\n return EMPTY_TOKENS;\n }\n}\n\nfunction webStorageAdapter(\n name: string,\n pick: () => Storage | null,\n crossTab: boolean,\n): TokenStorage {\n const store = (): Storage | null => {\n if (!hasWindow()) return null;\n try {\n return pick();\n } catch {\n // Private browsing and some embedded webviews throw on access.\n return null;\n }\n };\n\n return {\n name,\n get() {\n try {\n return parse(store()?.getItem(TOKEN_KEY) ?? null);\n } catch {\n return EMPTY_TOKENS;\n }\n },\n set(tokens) {\n try {\n const s = store();\n if (!s) return;\n if (tokens.accessToken) s.setItem(TOKEN_KEY, JSON.stringify(tokens));\n else s.removeItem(TOKEN_KEY);\n } catch {\n // Quota or private-browsing failure: the session degrades to\n // in-memory for this tab rather than breaking sign-in.\n }\n },\n clear() {\n try {\n store()?.removeItem(TOKEN_KEY);\n } catch {\n /* ignore */\n }\n },\n // Only localStorage raises `storage` in other tabs. sessionStorage is\n // per-tab by definition, so there is nothing to subscribe to.\n subscribe: crossTab\n ? (onExternalChange) => {\n if (!hasWindow()) return () => {};\n const handler = (e: StorageEvent) => {\n if (e.key === TOKEN_KEY || e.key === null) onExternalChange();\n };\n window.addEventListener('storage', handler);\n return () => window.removeEventListener('storage', handler);\n }\n : undefined,\n };\n}\n\n/**\n * Default. Per-tab, cleared when the tab closes.\n *\n * Note this means a new tab starts signed out and must complete a redirect\n * round-trip. Use {@link localStorageAdapter} to share the session across tabs,\n * or {@link cookieStorageAdapter} to keep tokens out of JavaScript entirely.\n */\nexport function sessionStorageAdapter(): TokenStorage {\n return webStorageAdapter('sessionStorage', () => window.sessionStorage, false);\n}\n\n/** Shared across tabs and survives a browser restart. Still XSS-readable. */\nexport function localStorageAdapter(): TokenStorage {\n return webStorageAdapter('localStorage', () => window.localStorage, true);\n}\n\n/**\n * In-memory only. Nothing persists, so a reload signs the user out.\n *\n * This is the correct default on the server: it is inert during SSR instead of\n * touching a `window` that does not exist.\n */\nexport function memoryStorageAdapter(): TokenStorage {\n let tokens: StoredTokens = EMPTY_TOKENS;\n return {\n name: 'memory',\n get: () => tokens,\n set: (t) => {\n tokens = t;\n },\n clear: () => {\n tokens = EMPTY_TOKENS;\n },\n };\n}\n\nexport interface CookieStorageOptions {\n /**\n * Same-origin endpoint that returns the current session as JSON\n * (`{accessToken, expiresAt, ...}`) reading it from an httpOnly cookie.\n * @default '/auth/session'\n */\n sessionEndpoint?: string;\n /**\n * Same-origin endpoint that clears the session cookie.\n * @default '/auth/logout'\n */\n logoutEndpoint?: string;\n fetch?: typeof globalThis.fetch;\n}\n\n/**\n * Backend-for-frontend adapter: tokens live in an httpOnly cookie and are never\n * exposed to JavaScript.\n *\n * This is the only option here that survives XSS. The cost is that a\n * same-origin server must own the OAuth exchange and refresh —\n * @lumoauth/express already provides those routes.\n *\n * `set()` is intentionally a no-op: the browser cannot write an httpOnly\n * cookie, so only the server may establish the session. Reads go over the\n * network, so the session store caches them rather than calling per request.\n */\nexport function cookieStorageAdapter(options: CookieStorageOptions = {}): TokenStorage {\n const sessionEndpoint = options.sessionEndpoint ?? '/auth/session';\n const logoutEndpoint = options.logoutEndpoint ?? '/auth/logout';\n const doFetch = options.fetch ?? ((...a: Parameters<typeof fetch>) => globalThis.fetch(...a));\n\n return {\n name: 'cookie',\n async get() {\n if (!hasWindow()) return EMPTY_TOKENS;\n try {\n const res = await doFetch(sessionEndpoint, {\n credentials: 'include',\n headers: { Accept: 'application/json' },\n });\n if (!res.ok) return EMPTY_TOKENS;\n const data = (await res.json()) as Partial<StoredTokens>;\n return {\n accessToken: data.accessToken ?? null,\n refreshToken: null, // never leaves the server\n idToken: data.idToken ?? null,\n expiresAt: typeof data.expiresAt === 'number' ? data.expiresAt : null,\n };\n } catch {\n return EMPTY_TOKENS;\n }\n },\n set() {\n // No-op by design — see the note above.\n },\n async clear() {\n if (!hasWindow()) return;\n try {\n await doFetch(logoutEndpoint, { method: 'POST', credentials: 'include' });\n } catch {\n /* best-effort */\n }\n },\n };\n}\n\n/**\n * The default: `sessionStorage` in a browser, memory on the server.\n *\n * Chosen so that importing the SDK into an SSR framework does not blow up on a\n * missing `window`, while browser behaviour is unchanged.\n */\nexport function defaultStorage(): TokenStorage {\n return hasWindow() ? sessionStorageAdapter() : memoryStorageAdapter();\n}\n","import { AuthModule, type TokenResponse } from '@lumoauth/shared';\nimport {\n defaultStorage,\n EMPTY_TOKENS,\n type StoredTokens,\n type TokenStorage,\n} from './storage';\n\n/**\n * Framework-agnostic session runtime.\n *\n * This owns everything that is not React: token persistence, the refresh\n * schedule, the PKCE handshake, and cross-tab coordination. `@lumoauth/react`\n * is a thin binding over it, and a Vue or Svelte binding would be the same\n * shape — which is the reason this exists as a standalone class rather than\n * living inside a provider component.\n *\n * Subscribe/getSnapshot are deliberately shaped for React's\n * `useSyncExternalStore`, but they are plain functions with no React\n * dependency.\n */\n\nexport type SessionStatus = 'loading' | 'authenticated' | 'unauthenticated';\n\nexport interface SessionState {\n status: SessionStatus;\n isLoaded: boolean;\n isSignedIn: boolean;\n /**\n * Why the last operation failed, if it did. The previous implementation\n * discarded this — an ERROR action collapsed to `unauthenticated` and the\n * message was dropped, so callers could not tell \"signed out\" from\n * \"refresh failed\".\n */\n error: string | null;\n}\n\nconst INITIAL: SessionState = {\n status: 'loading',\n isLoaded: false,\n isSignedIn: false,\n error: null,\n};\n\n/** Refresh this long before expiry rather than at it. */\nconst REFRESH_MARGIN_MS = 60_000;\n/** `getToken()` refreshes proactively inside this window. */\nconst PROACTIVE_WINDOW_MS = 30_000;\n/** Never schedule a timer shorter than this, to avoid a refresh storm. */\nconst MIN_TIMER_MS = 5_000;\n\n/** Cross-tab channel name. Also used as the leader-election lock name. */\nconst CHANNEL = 'lumoauth.session';\n\nexport interface SessionOptions {\n auth: AuthModule;\n redirectUri: string;\n scope?: string;\n storage?: TokenStorage;\n /**\n * Share the session across tabs. When enabled, a token refresh in one tab\n * is broadcast to the others, and only one tab performs the refresh.\n *\n * Independent of the storage adapter: `sessionStorage` is per-tab, so\n * broadcasting keeps siblings live for the current session even though\n * nothing is shared on disk.\n * @default true\n */\n crossTab?: boolean;\n /** Called after tokens change, so the host can refetch the user. */\n onTokens?: (tokens: StoredTokens) => void;\n}\n\ninterface Broadcast {\n type: 'tokens' | 'signout';\n tokens?: StoredTokens;\n}\n\nexport class LumoAuthSession {\n private state: SessionState = INITIAL;\n private tokens: StoredTokens = EMPTY_TOKENS;\n private listeners = new Set<() => void>();\n private timer: ReturnType<typeof setTimeout> | null = null;\n private channel: BroadcastChannel | null = null;\n private unsubscribeStorage: (() => void) | null = null;\n private inflightRefresh: Promise<string | null> | null = null;\n\n private readonly auth: AuthModule;\n private readonly storage: TokenStorage;\n private readonly redirectUri: string;\n private readonly scope: string;\n private readonly onTokens?: (t: StoredTokens) => void;\n\n constructor(opts: SessionOptions) {\n this.auth = opts.auth;\n this.storage = opts.storage ?? defaultStorage();\n this.redirectUri = opts.redirectUri;\n this.scope = opts.scope ?? 'openid profile email';\n this.onTokens = opts.onTokens;\n\n if (opts.crossTab !== false && typeof BroadcastChannel !== 'undefined') {\n this.channel = new BroadcastChannel(CHANNEL);\n this.channel.onmessage = (e: MessageEvent<Broadcast>) => this.onBroadcast(e.data);\n }\n this.unsubscribeStorage =\n this.storage.subscribe?.(() => {\n void this.hydrate();\n }) ?? null;\n }\n\n // ── Store interface ──────────────────────────────────────────────\n\n subscribe = (fn: () => void): (() => void) => {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n };\n\n getSnapshot = (): SessionState => this.state;\n\n /** Server snapshot for `useSyncExternalStore` — always the loading state. */\n getServerSnapshot = (): SessionState => INITIAL;\n\n private emit(next: Partial<SessionState>): void {\n this.state = { ...this.state, ...next };\n this.listeners.forEach((l) => l());\n }\n\n // ── Lifecycle ────────────────────────────────────────────────────\n\n /** Load persisted tokens and settle into signed-in or signed-out. */\n async hydrate(): Promise<void> {\n const tokens = await this.storage.get();\n this.tokens = tokens;\n\n if (!tokens.accessToken) {\n this.emit({ status: 'unauthenticated', isLoaded: true, isSignedIn: false });\n return;\n }\n if (tokens.expiresAt && tokens.expiresAt <= Date.now()) {\n const refreshed = await this.refresh();\n if (!refreshed) return; // refresh() already emitted signed-out\n }\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n this.onTokens?.(this.tokens);\n }\n\n dispose(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.channel?.close();\n this.channel = null;\n this.unsubscribeStorage?.();\n this.unsubscribeStorage = null;\n this.listeners.clear();\n }\n\n // ── Tokens ───────────────────────────────────────────────────────\n\n getTokens(): Readonly<StoredTokens> {\n return this.tokens;\n }\n\n private async persist(tokens: StoredTokens, broadcast = true): Promise<void> {\n this.tokens = tokens;\n await this.storage.set(tokens);\n if (broadcast) this.channel?.postMessage({ type: 'tokens', tokens } satisfies Broadcast);\n this.onTokens?.(tokens);\n }\n\n static tokensFrom(res: TokenResponse, previous?: StoredTokens): StoredTokens {\n return {\n accessToken: res.access_token,\n // A refresh response may omit the refresh token when it is not\n // rotated; keep the existing one rather than losing the session.\n refreshToken: res.refresh_token ?? previous?.refreshToken ?? null,\n idToken: res.id_token ?? previous?.idToken ?? null,\n expiresAt: Date.now() + res.expires_in * 1000,\n };\n }\n\n /**\n * A valid access token, refreshing first if it is about to expire.\n * Returns null when there is no session.\n */\n async getToken(): Promise<string | null> {\n const { accessToken, expiresAt } = this.tokens;\n if (!accessToken) return null;\n if (expiresAt && expiresAt - Date.now() < PROACTIVE_WINDOW_MS) {\n return this.refresh();\n }\n return accessToken;\n }\n\n /**\n * Refresh the access token.\n *\n * Concurrent callers share one in-flight request. Across tabs, a Web Lock\n * elects a single refresher — without it, every tab refreshes on its own\n * timer and they race on a rotated refresh token, so all but the winner\n * are signed out.\n */\n async refresh(): Promise<string | null> {\n if (this.inflightRefresh) return this.inflightRefresh;\n this.inflightRefresh = this.doRefresh().finally(() => {\n this.inflightRefresh = null;\n });\n return this.inflightRefresh;\n }\n\n private async doRefresh(): Promise<string | null> {\n if (!this.tokens.refreshToken) {\n await this.clearSession('no_refresh_token');\n return null;\n }\n\n const run = async (): Promise<string | null> => {\n // Another tab may have refreshed while we waited for the lock.\n //\n // Check BOTH the shared store and our own in-memory tokens. Storage\n // alone is not enough: with a per-tab adapter (the default,\n // sessionStorage) `storage.get()` returns this tab's private copy\n // and never sees the winner's rotated token — but the winner also\n // broadcasts, and onBroadcast() updates `this.tokens`. Consulting\n // both makes the check work for shared and per-tab adapters alike.\n const stored = await this.storage.get();\n const fresher = [stored, this.tokens]\n .filter((t) => t.accessToken && t.expiresAt)\n .sort((a, b) => (b.expiresAt ?? 0) - (a.expiresAt ?? 0))[0];\n\n if (fresher && (fresher.expiresAt ?? 0) - Date.now() > PROACTIVE_WINDOW_MS) {\n this.tokens = fresher;\n this.scheduleRefresh();\n return fresher.accessToken;\n }\n\n // Read the refresh token HERE, inside the lock, not before waiting\n // for it. The server rotates and revokes on use, so a value\n // captured before the lock is already spent by the time the loser\n // acquires it — the request 400s and the tab is signed out.\n const refreshToken = this.tokens.refreshToken;\n if (!refreshToken) {\n await this.clearSession('no_refresh_token');\n return null;\n }\n\n try {\n const res = await this.auth.refreshToken(refreshToken);\n await this.persist(LumoAuthSession.tokensFrom(res, this.tokens));\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n return this.tokens.accessToken;\n } catch {\n await this.clearSession('refresh_failed');\n return null;\n }\n };\n\n const locks = (globalThis as { navigator?: { locks?: LockManager } }).navigator?.locks;\n if (locks?.request) {\n return locks.request(CHANNEL + '.refresh', run) as Promise<string | null>;\n }\n return run();\n }\n\n private scheduleRefresh(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n const { expiresAt, refreshToken } = this.tokens;\n if (!expiresAt || !refreshToken) return;\n const delay = Math.max(expiresAt - Date.now() - REFRESH_MARGIN_MS, MIN_TIMER_MS);\n this.timer = setTimeout(() => void this.refresh(), delay);\n }\n\n // ── Flows ────────────────────────────────────────────────────────\n\n /** Adopt tokens obtained elsewhere (e.g. a completed code exchange). */\n async adopt(res: TokenResponse): Promise<void> {\n await this.persist(LumoAuthSession.tokensFrom(res, this.tokens));\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n }\n\n /** Build the PKCE authorization URL; the caller persists verifier + state. */\n buildAuthorizationUrl(extraParams?: Record<string, string>) {\n return this.auth.buildAuthorizationUrl({\n redirectUri: this.redirectUri,\n scope: this.scope,\n ...(extraParams ? { extraParams } : {}),\n });\n }\n\n /**\n * Drop the session.\n *\n * `emit: false` clears tokens and storage without notifying subscribers.\n * That is required during sign-out: emitting re-renders the tree, which\n * mounts any `<SignedOut><RedirectToSignIn/></SignedOut>` guard, whose\n * effect then races the pending logout navigation and sends the user back\n * to /authorize — where the IdP session is still alive and silently\n * re-issues a code, defeating logout entirely.\n */\n async clearSession(\n error: string | null = null,\n opts: { broadcast?: boolean; emit?: boolean } = {},\n ): Promise<void> {\n const { broadcast = true, emit = true } = opts;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.tokens = EMPTY_TOKENS;\n await this.storage.clear();\n if (broadcast) this.channel?.postMessage({ type: 'signout' } satisfies Broadcast);\n if (emit) {\n this.emit({ status: 'unauthenticated', isLoaded: true, isSignedIn: false, error });\n }\n }\n\n // ── Cross-tab ────────────────────────────────────────────────────\n\n private onBroadcast(msg: Broadcast): void {\n if (!msg) return;\n if (msg.type === 'signout') {\n // Do not re-broadcast: that would ping-pong between tabs.\n void this.clearSession(null, { broadcast: false });\n return;\n }\n if (msg.type === 'tokens' && msg.tokens) {\n this.tokens = msg.tokens;\n this.scheduleRefresh();\n this.emit({ status: 'authenticated', isLoaded: true, isSignedIn: true, error: null });\n this.onTokens?.(msg.tokens);\n }\n }\n}\n\n/** Minimal shape of the Web Locks API; not in every lib.dom version. */\ninterface LockManager {\n request<T>(name: string, cb: () => Promise<T>): Promise<T>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAYO;;;ACZP,oBAAoC;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