autosolutions-os 0.2.4 → 0.2.5
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/CHANGELOG.md +95 -0
- package/README.md +22 -0
- package/dist/client.js +4 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/session.d.ts +33 -6
- package/dist/session.js +443 -25
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,100 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.5 - 2026-10-15
|
|
4
|
+
|
|
5
|
+
Single sign-on fix. Signed in at the Hub, people opening an app were asked to
|
|
6
|
+
sign in with Google again (reported on 2026-10-14 for Artificial Design
|
|
7
|
+
Studio), and the Hub itself was often signed out an hour later.
|
|
8
|
+
|
|
9
|
+
- **The newest session wins.** `adoptSharedSession` copied the shared session
|
|
10
|
+
in only when the app had none of its own; when both existed it wrote the
|
|
11
|
+
app's own copy over the shared cookie. Supabase rotates refresh tokens and
|
|
12
|
+
accepts a retired one only one step behind or within 10 seconds; anything
|
|
13
|
+
older ends the session for every app (`refresh_token_already_used`). An app
|
|
14
|
+
opened again after the Hub had refreshed twice therefore wrote its old copy
|
|
15
|
+
over the Hub's, refreshed with a retired token and was signed out, and the
|
|
16
|
+
Hub with it. Now, wherever the two copies meet, the one that expires later is
|
|
17
|
+
kept (on a tie, the shared one): on load, and with `followSharedSession`
|
|
18
|
+
(below) when a tab becomes visible or gets focus and whenever supabase-js
|
|
19
|
+
reads its session, which it does before every refresh. An auth event no
|
|
20
|
+
longer writes over a newer shared copy.
|
|
21
|
+
- **A refresh on the wire keeps its result.** supabase-js (2.112 and later)
|
|
22
|
+
reads its stored session before and after a token request and throws the
|
|
23
|
+
rotated tokens away when the copy changed in between. While the page's own
|
|
24
|
+
refresh is in flight, a newer copy of the same person shared by another app
|
|
25
|
+
therefore waits for the next read; taken at once, it made supabase-js
|
|
26
|
+
discard a valid refresh (on supabase-js 2.112.3 a `getSession()` that
|
|
27
|
+
refreshed answered once with no session, and an explicit `refreshSession()`
|
|
28
|
+
reported "Refresh result discarded"). A different person signing in
|
|
29
|
+
elsewhere is still taken at once (the page reloads), so the refreshing
|
|
30
|
+
page's copy of the previous person cannot replace that sign-in.
|
|
31
|
+
- **Only an explicit sign-out clears the shared session, and it clears it
|
|
32
|
+
everywhere.** `client.auth.signOut()` (any scope but `"others"`) now leaves
|
|
33
|
+
a note, `sb-<ref>-auth-token-signed-out`, then clears the cookie and signs
|
|
34
|
+
out as before. The note holds the expiry of the newest copy it knew and the
|
|
35
|
+
`session_id` of each session the sign-out ended (`<expiry>|<id>.<id>`, the
|
|
36
|
+
last 8), a claim every refresh of one sign-in keeps. Every app drops a copy
|
|
37
|
+
that expires at or before the note, or of a session it names, instead of
|
|
38
|
+
sharing it again; until now an app still holding a copy put it back, and the
|
|
39
|
+
Hub took it on its next load. A failed refresh, another tab's `SIGNED_OUT`,
|
|
40
|
+
a missing local copy or blocked storage no longer clear anything.
|
|
41
|
+
- **A sign-out after an idle hour, or during a refresh, stays signed out.**
|
|
42
|
+
supabase-js refreshes an expired copy inside `signOut`, and waits for a
|
|
43
|
+
refresh already in flight, so a rotated copy can be saved and announced
|
|
44
|
+
after the note. It expires later than the note, so without more the Hub and
|
|
45
|
+
every app would load a session the server had just ended (its access token
|
|
46
|
+
stays valid for about an hour). The note's session ids keep such a copy
|
|
47
|
+
out, and `client.auth.signOut()` also leaves the note and clears the cookie
|
|
48
|
+
again once supabase-js has finished, so the note covers it by its expiry as
|
|
49
|
+
well, including a copy whose access token names no session.
|
|
50
|
+
- **A sign-out that does not happen changes nothing.** When supabase-js
|
|
51
|
+
reports a failed sign-out and still holds the session,
|
|
52
|
+
`client.auth.signOut()` puts the note back as it was before (none, or an
|
|
53
|
+
earlier sign-out's) and shares this page's copy again, so the person stays
|
|
54
|
+
signed in everywhere and can sign out again. Left in place, the note made
|
|
55
|
+
the next focus drop this page's copy and every other app's without a
|
|
56
|
+
logout, a second sign-out found no session and called nothing, and the
|
|
57
|
+
session stayed live on the server. supabase-js 2.106 (Smart LeadGen CRM's)
|
|
58
|
+
keeps the session when the server's logout fails (a 500 or a network error;
|
|
59
|
+
a 401, 403 or 404 still signs out), and every version keeps it when the
|
|
60
|
+
refresh it makes first fails on the network. supabase-js 2.112 and later
|
|
61
|
+
remove the session even when the logout fails: that is a sign-out on this
|
|
62
|
+
device, and it stays one everywhere. Two sign-outs at once (a double click)
|
|
63
|
+
count as one: the note goes back only when neither signed out.
|
|
64
|
+
- **Someone else signing in elsewhere replaces the session.** An open page
|
|
65
|
+
that was showing another person reloads, and so does a page on its sign-in
|
|
66
|
+
screen when a session arrives, so it shows that person: when the window
|
|
67
|
+
only gets focus (a click back into a window already in view, with no tab
|
|
68
|
+
switch) nothing tells supabase-js, and such a page would keep asking for
|
|
69
|
+
Google with a valid session stored. A page that has had no auth event yet
|
|
70
|
+
takes the session without reloading (its own first read shows it), and a
|
|
71
|
+
page on its sign-in screen does not reload when a copy that a sign-out
|
|
72
|
+
ended is dropped.
|
|
73
|
+
- **Storage and cookie errors never break sign-in.** The auth callback is now
|
|
74
|
+
guarded too: with cookies blocked, signing in threw a `SecurityError` to the
|
|
75
|
+
caller. A shared cookie read halfway through another app's write is left
|
|
76
|
+
alone instead of being taken for no session.
|
|
77
|
+
- **New: `followSharedSession(client, projectRef)`.** `createOsClient` calls
|
|
78
|
+
it; an app that builds its own client calls it once, right after
|
|
79
|
+
`publishSessionChanges`. It listens for the tab coming back, guards the
|
|
80
|
+
client's session reads (`client.auth.storage`, an internal of supabase-js:
|
|
81
|
+
feature-detected, and the tests fail if a supabase-js update moves it) and
|
|
82
|
+
makes `client.auth.signOut()` the explicit sign-out. `adoptSharedSession`
|
|
83
|
+
and `publishSessionChanges` keep their signatures.
|
|
84
|
+
|
|
85
|
+
### Upgrading
|
|
86
|
+
|
|
87
|
+
- An app on `createOsClient` (the Hub) takes 0.2.5 and changes nothing else.
|
|
88
|
+
From 0.2.4 nothing else is needed: the design-system peer range stays
|
|
89
|
+
`>=6.4.0 <7`.
|
|
90
|
+
- An app with its own copy of the session code replaces it with the 0.2.5
|
|
91
|
+
copy and adds the one `followSharedSession` call where it creates its
|
|
92
|
+
client. Until then it can still sign everyone out with a stale refresh, so
|
|
93
|
+
every app on the core needs one or the other.
|
|
94
|
+
- The Hub takes 0.2.5 before, or together with, the first app that takes the
|
|
95
|
+
copy: a Hub on an older version still lets its own copy win, and its
|
|
96
|
+
sign-out leaves no note.
|
|
97
|
+
|
|
3
98
|
## 0.2.4 - 2026-10-14
|
|
4
99
|
|
|
5
100
|
Released with `autosolutions-design-system` 6.4.0: the workspace frame in the
|
package/README.md
CHANGED
|
@@ -29,6 +29,28 @@ export function App() {
|
|
|
29
29
|
`supabase` is bound to your schema, so `.from("your_table")` works unchanged.
|
|
30
30
|
`os` is the same connection bound to `public`, for the platform's own functions.
|
|
31
31
|
|
|
32
|
+
## One sign-in across the apps
|
|
33
|
+
|
|
34
|
+
`createOsClient` keeps every app on one session: Supabase stores it in each
|
|
35
|
+
origin's localStorage, and the package mirrors it into a cookie on
|
|
36
|
+
`.autosolutions.app`. The newest copy always wins (on load, when a tab comes
|
|
37
|
+
back, and before supabase-js refreshes), only `supabase.auth.signOut()` clears
|
|
38
|
+
it, and it clears it in every app. A sign-out that does not happen (supabase-js
|
|
39
|
+
reports a failure and keeps the session) clears nothing, so the person can sign
|
|
40
|
+
out again. An app that builds its own Supabase client wires the same three calls
|
|
41
|
+
itself, in this order, at module scope:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { createClient } from "@supabase/supabase-js";
|
|
45
|
+
import { adoptSharedSession, followSharedSession, publishSessionChanges, coreProjectRef } from "autosolutions-os";
|
|
46
|
+
|
|
47
|
+
const ref = coreProjectRef();
|
|
48
|
+
adoptSharedSession(ref); // before the client reads its storage
|
|
49
|
+
const supabase = createClient(url, key, { auth: { persistSession: true, autoRefreshToken: true } });
|
|
50
|
+
publishSessionChanges(supabase, ref);
|
|
51
|
+
followSharedSession(supabase, ref);
|
|
52
|
+
```
|
|
53
|
+
|
|
32
54
|
## The workspace frame
|
|
33
55
|
|
|
34
56
|
`OsWorkspaceFrame` is the frame every app on the core renders around its pages:
|
package/dist/client.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { createClient } from "@supabase/supabase-js";
|
|
9
9
|
import { coreProjectRef, corePublishableKey, coreUrl } from "./config.js";
|
|
10
|
-
import { adoptSharedSession, publishSessionChanges } from "./session.js";
|
|
10
|
+
import { adoptSharedSession, followSharedSession, publishSessionChanges } from "./session.js";
|
|
11
11
|
let cached;
|
|
12
12
|
export function createOsClient(options) {
|
|
13
13
|
// One client per page. A second would keep its own session state and the two
|
|
@@ -24,6 +24,9 @@ export function createOsClient(options) {
|
|
|
24
24
|
});
|
|
25
25
|
// Signing in or out here carries to every other AutoSolutions app.
|
|
26
26
|
publishSessionChanges(supabase, ref);
|
|
27
|
+
// While the page is open the newest session wins: when the tab comes back,
|
|
28
|
+
// and before supabase-js refreshes, so it never refreshes with an older token.
|
|
29
|
+
followSharedSession(supabase, ref);
|
|
27
30
|
const client = {
|
|
28
31
|
supabase,
|
|
29
32
|
// Always take the explicit `public` view, so the type is the same whether or
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { coreUrl, corePublishableKey, coreProjectRef, companyMarkUrl, appLabelUrl, HUB_URL, PARENT_DOMAIN } from "./config.js";
|
|
2
2
|
export { createOsClient, resetOsClient, type OsClient } from "./client.js";
|
|
3
|
-
export { adoptSharedSession, publishSessionChanges, sharedSessionCookieName, joinChunks } from "./session.js";
|
|
3
|
+
export { adoptSharedSession, followSharedSession, publishSessionChanges, sharedSessionCookieName, joinChunks } from "./session.js";
|
|
4
4
|
export { loadOsContext, invalidateOsContext, refreshOsContext, retryOsContext, watchOsAuth, useOsContext, useOsContextState, useTenant, useApps, groupApps, markFor, labelFor, withTenantHint, type OsContext, type OsContextStatus, type OsTenant, type OsApp, } from "./context.js";
|
|
5
5
|
export { isEntitled, isActiveMember, appRole, appVariant, currentTenant, toolAllowed, myAdminScope, canManageCurrentCompany, type AdminScope, } from "./identity.js";
|
|
6
6
|
export { OsAppSwitcher, OsAppSwitcherPlate, OsCompanySwitcher, OsBar, useCompanySwitch } from "./chrome.js";
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { coreUrl, corePublishableKey, coreProjectRef, companyMarkUrl, appLabelUrl, HUB_URL, PARENT_DOMAIN } from "./config.js";
|
|
2
2
|
export { createOsClient, resetOsClient } from "./client.js";
|
|
3
|
-
export { adoptSharedSession, publishSessionChanges, sharedSessionCookieName, joinChunks } from "./session.js";
|
|
3
|
+
export { adoptSharedSession, followSharedSession, publishSessionChanges, sharedSessionCookieName, joinChunks } from "./session.js";
|
|
4
4
|
export { loadOsContext, invalidateOsContext, refreshOsContext, retryOsContext, watchOsAuth, useOsContext, useOsContextState, useTenant, useApps, groupApps, markFor, labelFor, withTenantHint, } from "./context.js";
|
|
5
5
|
export { isEntitled, isActiveMember, appRole, appVariant, currentTenant, toolAllowed, myAdminScope, canManageCurrentCompany, } from "./identity.js";
|
|
6
6
|
export { OsAppSwitcher, OsAppSwitcherPlate, OsCompanySwitcher, OsBar, useCompanySwitch } from "./chrome.js";
|
package/dist/session.d.ts
CHANGED
|
@@ -1,16 +1,43 @@
|
|
|
1
1
|
/** Reassemble a chunked value from any source of name/value pairs. */
|
|
2
2
|
export declare function joinChunks(key: string, read: (name: string) => string | undefined): string | null;
|
|
3
3
|
/**
|
|
4
|
-
* Copy a session that arrived from another app into this origin's storage
|
|
5
|
-
*
|
|
6
|
-
* calls it at module
|
|
4
|
+
* Copy a session that arrived from another app into this origin's storage,
|
|
5
|
+
* or share this origin's when it is the newer one. Must run before the
|
|
6
|
+
* Supabase client reads its storage, so `createOsClient` calls it at module
|
|
7
|
+
* scope.
|
|
7
8
|
*/
|
|
8
9
|
export declare function adoptSharedSession(projectRef: string): void;
|
|
9
|
-
|
|
10
|
-
export declare function publishSessionChanges(client: {
|
|
10
|
+
type AuthEvents = {
|
|
11
11
|
auth: {
|
|
12
|
-
onAuthStateChange: (cb: (event: string
|
|
12
|
+
onAuthStateChange: (cb: (event: string, session: {
|
|
13
|
+
user?: {
|
|
14
|
+
id?: string;
|
|
15
|
+
} | null;
|
|
16
|
+
} | null) => void) => unknown;
|
|
13
17
|
};
|
|
18
|
+
};
|
|
19
|
+
/** Keep the shared cookie in step with this app's session. */
|
|
20
|
+
export declare function publishSessionChanges(client: AuthEvents, projectRef: string): void;
|
|
21
|
+
/**
|
|
22
|
+
* Keep a running page on the newest session. Call it once, right after
|
|
23
|
+
* creating the client and calling `publishSessionChanges`; `createOsClient`
|
|
24
|
+
* does. It:
|
|
25
|
+
*
|
|
26
|
+
* - takes the newest session whenever the tab comes back into view or to
|
|
27
|
+
* focus, before supabase-js's own wake-up (which refreshes) reads it;
|
|
28
|
+
* - takes it whenever supabase-js reads its session, which it does before
|
|
29
|
+
* every refresh, so a refresh never uses a token older than the shared one
|
|
30
|
+
* (while one is in flight, a newer copy of the same person waits for the
|
|
31
|
+
* next read, so supabase-js keeps that refresh);
|
|
32
|
+
* - makes `client.auth.signOut()` (any scope but "others") the sign-out that
|
|
33
|
+
* clears the shared session everywhere.
|
|
34
|
+
*
|
|
35
|
+
* Every part is best effort: where a part cannot be installed, the others
|
|
36
|
+
* still work, and nothing here can stop the client from signing in.
|
|
37
|
+
*/
|
|
38
|
+
export declare function followSharedSession(client: {
|
|
39
|
+
auth: object;
|
|
14
40
|
}, projectRef: string): void;
|
|
15
41
|
/** The storage key, for server code that needs to find the cookie by name. */
|
|
16
42
|
export declare function sharedSessionCookieName(projectRef: string): string;
|
|
43
|
+
export {};
|
package/dist/session.js
CHANGED
|
@@ -12,21 +12,48 @@
|
|
|
12
12
|
* Off that domain (localhost, preview hosts) nothing happens and each app
|
|
13
13
|
* signs in normally.
|
|
14
14
|
*
|
|
15
|
-
* The
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
15
|
+
* The rules that matter:
|
|
16
|
+
*
|
|
17
|
+
* 1. The newest copy wins. Supabase rotates refresh tokens: a refresh retires
|
|
18
|
+
* the token it used, and a retired token used again is accepted only one
|
|
19
|
+
* step behind or within 10 seconds. Anything older is taken as theft and
|
|
20
|
+
* ends the session for every app at once. So an app must never refresh with
|
|
21
|
+
* a copy older than the shared one. Wherever the two copies meet (on load,
|
|
22
|
+
* when a tab comes back to focus or into view, and whenever supabase-js reads
|
|
23
|
+
* its session, which it does before every refresh), the one that expires
|
|
24
|
+
* later is kept; on a tie, the shared one. While the page's own refresh is
|
|
25
|
+
* in flight, a newer copy of the same person waits for the next read, as
|
|
26
|
+
* supabase-js throws a refresh away when its copy changes under it. Until
|
|
27
|
+
* 0.2.5 the app's own copy always won, so an app opened after the Hub had
|
|
28
|
+
* refreshed refreshed with a retired token, was signed out, and took the
|
|
29
|
+
* Hub's session with it.
|
|
30
|
+
* 2. Only an explicit sign-out (`client.auth.signOut()`) clears the shared
|
|
31
|
+
* session, and it clears it everywhere: it leaves a note in the cookie jar
|
|
32
|
+
* so every app drops any copy at least as old as the one signed out, or of
|
|
33
|
+
* a session it ended, rather than putting it back. A missing local session,
|
|
34
|
+
* a failed refresh or blocked storage clears nothing, and neither does a
|
|
35
|
+
* sign-out that does not happen (supabase-js reports a failure and keeps
|
|
36
|
+
* the session): the note goes back to what it was.
|
|
37
|
+
* 3. A different person signing in elsewhere replaces the session here. A page
|
|
38
|
+
* that was showing someone else reloads, and so does a page on its sign-in
|
|
39
|
+
* screen when a session arrives, so it shows that person.
|
|
40
|
+
* 4. Storage or cookie errors never break sign-in: each app then simply signs
|
|
41
|
+
* in on its own.
|
|
20
42
|
*/
|
|
21
43
|
import { PARENT_DOMAIN } from "./config.js";
|
|
22
44
|
/** Cookies cap around 4KB each, and sessions can exceed that, so they chunk. */
|
|
23
45
|
const CHUNK = 3200;
|
|
24
46
|
const MAX_CHUNKS = 8;
|
|
47
|
+
const MAX_AGE = 60 * 60 * 24 * 30;
|
|
25
48
|
function storageKey(projectRef) {
|
|
26
49
|
return `sb-${projectRef}-auth-token`;
|
|
27
50
|
}
|
|
51
|
+
/** The note an explicit sign-out leaves: copies expiring at or before its watermark, or of a session it names, are signed out. */
|
|
52
|
+
function signedOutName(key) {
|
|
53
|
+
return `${key}-signed-out`;
|
|
54
|
+
}
|
|
28
55
|
function sharingEnabled() {
|
|
29
|
-
if (typeof window === "undefined")
|
|
56
|
+
if (typeof window === "undefined" || typeof document === "undefined")
|
|
30
57
|
return false;
|
|
31
58
|
const host = window.location.hostname;
|
|
32
59
|
return host === PARENT_DOMAIN || host.endsWith(`.${PARENT_DOMAIN}`);
|
|
@@ -49,14 +76,14 @@ export function joinChunks(key, read) {
|
|
|
49
76
|
return null;
|
|
50
77
|
}
|
|
51
78
|
}
|
|
52
|
-
function
|
|
79
|
+
function cookieJar() {
|
|
53
80
|
const jar = new Map();
|
|
54
81
|
for (const entry of document.cookie ? document.cookie.split("; ") : []) {
|
|
55
82
|
const index = entry.indexOf("=");
|
|
56
83
|
if (index > 0)
|
|
57
84
|
jar.set(entry.slice(0, index), entry.slice(index + 1));
|
|
58
85
|
}
|
|
59
|
-
return
|
|
86
|
+
return jar;
|
|
60
87
|
}
|
|
61
88
|
function writeCookieChunks(key, value) {
|
|
62
89
|
const encoded = encodeURIComponent(value);
|
|
@@ -65,7 +92,7 @@ function writeCookieChunks(key, value) {
|
|
|
65
92
|
parts.push(encoded.slice(i, i + CHUNK));
|
|
66
93
|
if (parts.length > MAX_CHUNKS)
|
|
67
94
|
return; // implausibly large: leave the cookie alone
|
|
68
|
-
const attributes = `Domain=.${PARENT_DOMAIN}; Path=/; Max-Age=${
|
|
95
|
+
const attributes = `Domain=.${PARENT_DOMAIN}; Path=/; Max-Age=${MAX_AGE}; SameSite=Lax; Secure`;
|
|
69
96
|
parts.forEach((part, index) => {
|
|
70
97
|
document.cookie = `${key}.${index}=${part}; ${attributes}`;
|
|
71
98
|
});
|
|
@@ -79,22 +106,179 @@ function clearCookieChunks(key) {
|
|
|
79
106
|
document.cookie = `${key}.${index}=; Domain=.${PARENT_DOMAIN}; Path=/; Max-Age=0; SameSite=Lax; Secure`;
|
|
80
107
|
}
|
|
81
108
|
}
|
|
109
|
+
function readSignedOut(jar, key) {
|
|
110
|
+
const raw = jar.get(signedOutName(key));
|
|
111
|
+
if (raw === undefined || raw === "")
|
|
112
|
+
return null;
|
|
113
|
+
const [watermark = "", sessions = ""] = raw.split("|");
|
|
114
|
+
const expiresAt = Number(watermark);
|
|
115
|
+
if (!Number.isFinite(expiresAt))
|
|
116
|
+
return null;
|
|
117
|
+
return { expiresAt, sessions: sessions ? sessions.split(".") : [] };
|
|
118
|
+
}
|
|
119
|
+
function writeSignedOut(key, expiresAt, sessionIds) {
|
|
120
|
+
const prior = readSignedOut(cookieJar(), key);
|
|
121
|
+
const watermark = prior === null ? expiresAt : Math.max(prior.expiresAt, expiresAt);
|
|
122
|
+
const sessions = [...new Set([...(prior?.sessions ?? []), ...sessionIds])].slice(-8);
|
|
123
|
+
const value = sessions.length > 0 ? `${watermark}|${sessions.join(".")}` : `${watermark}`;
|
|
124
|
+
document.cookie = `${signedOutName(key)}=${value}; Domain=.${PARENT_DOMAIN}; Path=/; Max-Age=${MAX_AGE}; SameSite=Lax; Secure`;
|
|
125
|
+
}
|
|
126
|
+
/** A copy the sign-out ended: it expires no later than the sign-out's watermark, or it is one of the sessions it ended (a refresh of that session expires later). */
|
|
127
|
+
function signedOutCopy(copy, note) {
|
|
128
|
+
if (note === null)
|
|
129
|
+
return false;
|
|
130
|
+
return copy.expiresAt <= note.expiresAt || (copy.sessionId !== null && note.sessions.includes(copy.sessionId));
|
|
131
|
+
}
|
|
132
|
+
/** The `session_id` claim of an access token: one sign-in keeps it through every refresh. */
|
|
133
|
+
function sessionIdOf(accessToken) {
|
|
134
|
+
const payload = accessToken.split(".")[1];
|
|
135
|
+
if (!payload)
|
|
136
|
+
return null;
|
|
137
|
+
try {
|
|
138
|
+
const claims = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
|
|
139
|
+
return typeof claims.session_id === "string" && claims.session_id.length > 0 ? claims.session_id : null;
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function parseCopy(raw) {
|
|
146
|
+
if (!raw)
|
|
147
|
+
return null;
|
|
148
|
+
try {
|
|
149
|
+
const value = JSON.parse(raw);
|
|
150
|
+
if (!value || typeof value !== "object")
|
|
151
|
+
return null;
|
|
152
|
+
const session = value;
|
|
153
|
+
if (typeof session.access_token !== "string" || typeof session.refresh_token !== "string")
|
|
154
|
+
return null;
|
|
155
|
+
const expiresAt = Number(session.expires_at);
|
|
156
|
+
if (!Number.isFinite(expiresAt))
|
|
157
|
+
return null;
|
|
158
|
+
const user = session.user;
|
|
159
|
+
return {
|
|
160
|
+
raw,
|
|
161
|
+
expiresAt,
|
|
162
|
+
refreshToken: session.refresh_token,
|
|
163
|
+
userId: typeof user?.id === "string" ? user.id : null,
|
|
164
|
+
sessionId: sessionIdOf(session.access_token),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function readShared(jar, key) {
|
|
172
|
+
if (!jar.has(`${key}.0`))
|
|
173
|
+
return { state: "absent" };
|
|
174
|
+
const copy = parseCopy(joinChunks(key, (name) => jar.get(name)));
|
|
175
|
+
return copy ? { state: "present", copy } : { state: "unreadable" };
|
|
176
|
+
}
|
|
177
|
+
const pages = new WeakMap();
|
|
178
|
+
function pageFor(key) {
|
|
179
|
+
let byKey = pages.get(window);
|
|
180
|
+
if (!byKey) {
|
|
181
|
+
byKey = new Map();
|
|
182
|
+
pages.set(window, byKey);
|
|
183
|
+
}
|
|
184
|
+
let page = byKey.get(key);
|
|
185
|
+
if (!page) {
|
|
186
|
+
page = { dead: new Set(), user: undefined, following: false, signingOut: false, reloading: false, refreshing: () => false };
|
|
187
|
+
byKey.set(key, page);
|
|
188
|
+
}
|
|
189
|
+
return page;
|
|
190
|
+
}
|
|
191
|
+
/** Bring this origin's copy and the shared one in step: the newest wins. */
|
|
192
|
+
function reconcile(key, page) {
|
|
193
|
+
const jar = cookieJar();
|
|
194
|
+
const signedOut = readSignedOut(jar, key);
|
|
195
|
+
const isSignedOut = (copy) => signedOutCopy(copy, signedOut);
|
|
196
|
+
const shared = readShared(jar, key);
|
|
197
|
+
if (shared.state === "unreadable")
|
|
198
|
+
return "none";
|
|
199
|
+
let theirs = shared.state === "present" ? shared.copy : null;
|
|
200
|
+
if (theirs && (isSignedOut(theirs) || page.dead.has(theirs.refreshToken)))
|
|
201
|
+
theirs = null;
|
|
202
|
+
const local = parseCopy(window.localStorage.getItem(key));
|
|
203
|
+
if (local && isSignedOut(local)) {
|
|
204
|
+
// Signed out on purpose somewhere after this copy was made.
|
|
205
|
+
if (theirs) {
|
|
206
|
+
window.localStorage.setItem(key, theirs.raw);
|
|
207
|
+
return "adopted";
|
|
208
|
+
}
|
|
209
|
+
window.localStorage.removeItem(key);
|
|
210
|
+
return "dropped";
|
|
211
|
+
}
|
|
212
|
+
if (!theirs) {
|
|
213
|
+
if (!local)
|
|
214
|
+
return "none";
|
|
215
|
+
// No shared session is not evidence of a sign-out: share this one.
|
|
216
|
+
writeCookieChunks(key, local.raw);
|
|
217
|
+
return "published";
|
|
218
|
+
}
|
|
219
|
+
if (!local) {
|
|
220
|
+
window.localStorage.setItem(key, theirs.raw);
|
|
221
|
+
return "adopted";
|
|
222
|
+
}
|
|
223
|
+
if (local.raw === theirs.raw)
|
|
224
|
+
return "same";
|
|
225
|
+
if (theirs.expiresAt >= local.expiresAt) {
|
|
226
|
+
// supabase-js reads its storage before and after a token request and throws
|
|
227
|
+
// a valid refresh away when the copy changed in between. While one is in
|
|
228
|
+
// flight, a newer copy of the same person waits for the next read; another
|
|
229
|
+
// person is taken at once (the page reloads), so this page's refresh of the
|
|
230
|
+
// previous person cannot replace that sign-in.
|
|
231
|
+
if (page.refreshing() && theirs.userId !== null && theirs.userId === local.userId)
|
|
232
|
+
return "later";
|
|
233
|
+
window.localStorage.setItem(key, theirs.raw);
|
|
234
|
+
return "adopted";
|
|
235
|
+
}
|
|
236
|
+
writeCookieChunks(key, local.raw);
|
|
237
|
+
return "published";
|
|
238
|
+
}
|
|
82
239
|
/**
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
240
|
+
* The same, in a page that is already running: when the person behind the
|
|
241
|
+
* session changed (someone else signed in elsewhere, or signed out), a page
|
|
242
|
+
* that was showing someone reloads, so nobody sees the previous person's
|
|
243
|
+
* screen. A newer token for the same person changes nothing on screen.
|
|
244
|
+
*/
|
|
245
|
+
function reconcileInPage(key, page) {
|
|
246
|
+
if (page.signingOut || page.reloading)
|
|
247
|
+
return;
|
|
248
|
+
try {
|
|
249
|
+
const shown = page.user;
|
|
250
|
+
const outcome = reconcile(key, page);
|
|
251
|
+
if (outcome !== "adopted" && outcome !== "dropped")
|
|
252
|
+
return;
|
|
253
|
+
// undefined: the page has not been told who it shows yet; its own first read picks the session up.
|
|
254
|
+
if (shown === undefined)
|
|
255
|
+
return;
|
|
256
|
+
const now = parseCopy(window.localStorage.getItem(key));
|
|
257
|
+
const nowUser = now ? now.userId : null;
|
|
258
|
+
if (outcome === "adopted" && (nowUser === null || nowUser === shown))
|
|
259
|
+
return;
|
|
260
|
+
// A page on its sign-in screen (shown === null) reloads for a session that arrives, so it shows that person.
|
|
261
|
+
if (outcome === "dropped" && shown === null)
|
|
262
|
+
return;
|
|
263
|
+
page.reloading = true;
|
|
264
|
+
setTimeout(() => window.location.reload(), 0);
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
// Never let session mirroring break the page.
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Copy a session that arrived from another app into this origin's storage,
|
|
272
|
+
* or share this origin's when it is the newer one. Must run before the
|
|
273
|
+
* Supabase client reads its storage, so `createOsClient` calls it at module
|
|
274
|
+
* scope.
|
|
86
275
|
*/
|
|
87
276
|
export function adoptSharedSession(projectRef) {
|
|
88
277
|
if (!sharingEnabled())
|
|
89
278
|
return;
|
|
90
279
|
const key = storageKey(projectRef);
|
|
91
280
|
try {
|
|
92
|
-
|
|
93
|
-
const shared = readCookieChunks(key);
|
|
94
|
-
if (shared && !local)
|
|
95
|
-
window.localStorage.setItem(key, shared);
|
|
96
|
-
else if (local && local !== shared)
|
|
97
|
-
writeCookieChunks(key, local);
|
|
281
|
+
reconcile(key, pageFor(key));
|
|
98
282
|
}
|
|
99
283
|
catch {
|
|
100
284
|
// Storage blocked (private window, blocked cookies): fall back to a normal
|
|
@@ -107,20 +291,254 @@ export function publishSessionChanges(client, projectRef) {
|
|
|
107
291
|
return;
|
|
108
292
|
const key = storageKey(projectRef);
|
|
109
293
|
try {
|
|
110
|
-
client.auth.onAuthStateChange((event) => {
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
294
|
+
client.auth.onAuthStateChange((event, session) => {
|
|
295
|
+
try {
|
|
296
|
+
const page = pageFor(key);
|
|
297
|
+
if (event === "SIGNED_OUT") {
|
|
298
|
+
page.user = null;
|
|
299
|
+
// Only an explicit sign-out clears the shared session. With
|
|
300
|
+
// followSharedSession installed it already has, inside
|
|
301
|
+
// client.auth.signOut; any other SIGNED_OUT (a failed refresh,
|
|
302
|
+
// another tab of this app) leaves the shared session alone.
|
|
303
|
+
if (!page.following)
|
|
304
|
+
clearCookieChunks(key);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
if (session?.user?.id)
|
|
308
|
+
page.user = session.user.id;
|
|
309
|
+
else if (!session)
|
|
310
|
+
page.user = null;
|
|
311
|
+
publishLocal(key);
|
|
312
|
+
}
|
|
313
|
+
catch {
|
|
314
|
+
// Never let session mirroring break authentication itself.
|
|
114
315
|
}
|
|
115
|
-
const local = window.localStorage.getItem(key);
|
|
116
|
-
if (local)
|
|
117
|
-
writeCookieChunks(key, local);
|
|
118
316
|
});
|
|
119
317
|
}
|
|
120
318
|
catch {
|
|
121
319
|
// Never let session mirroring break authentication itself.
|
|
122
320
|
}
|
|
123
321
|
}
|
|
322
|
+
/** Share this origin's session unless the shared one is newer. */
|
|
323
|
+
function publishLocal(key) {
|
|
324
|
+
const local = parseCopy(window.localStorage.getItem(key));
|
|
325
|
+
if (!local)
|
|
326
|
+
return;
|
|
327
|
+
const jar = cookieJar();
|
|
328
|
+
const signedOut = readSignedOut(jar, key);
|
|
329
|
+
if (signedOutCopy(local, signedOut))
|
|
330
|
+
return;
|
|
331
|
+
const shared = readShared(jar, key);
|
|
332
|
+
if (shared.state === "present" && shared.copy.raw !== local.raw) {
|
|
333
|
+
const theirs = shared.copy;
|
|
334
|
+
const theirsSignedOut = signedOutCopy(theirs, signedOut);
|
|
335
|
+
if (!theirsSignedOut && theirs.expiresAt > local.expiresAt)
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
writeCookieChunks(key, local.raw);
|
|
339
|
+
}
|
|
340
|
+
const GUARDED = Symbol.for("autosolutions-os.sharedSession.guarded");
|
|
341
|
+
/**
|
|
342
|
+
* Keep a running page on the newest session. Call it once, right after
|
|
343
|
+
* creating the client and calling `publishSessionChanges`; `createOsClient`
|
|
344
|
+
* does. It:
|
|
345
|
+
*
|
|
346
|
+
* - takes the newest session whenever the tab comes back into view or to
|
|
347
|
+
* focus, before supabase-js's own wake-up (which refreshes) reads it;
|
|
348
|
+
* - takes it whenever supabase-js reads its session, which it does before
|
|
349
|
+
* every refresh, so a refresh never uses a token older than the shared one
|
|
350
|
+
* (while one is in flight, a newer copy of the same person waits for the
|
|
351
|
+
* next read, so supabase-js keeps that refresh);
|
|
352
|
+
* - makes `client.auth.signOut()` (any scope but "others") the sign-out that
|
|
353
|
+
* clears the shared session everywhere.
|
|
354
|
+
*
|
|
355
|
+
* Every part is best effort: where a part cannot be installed, the others
|
|
356
|
+
* still work, and nothing here can stop the client from signing in.
|
|
357
|
+
*/
|
|
358
|
+
export function followSharedSession(client, projectRef) {
|
|
359
|
+
if (!sharingEnabled())
|
|
360
|
+
return;
|
|
361
|
+
const key = storageKey(projectRef);
|
|
362
|
+
try {
|
|
363
|
+
const page = pageFor(key);
|
|
364
|
+
if (page.following)
|
|
365
|
+
return;
|
|
366
|
+
page.following = true;
|
|
367
|
+
const auth = client.auth;
|
|
368
|
+
// supabase-js holds a token request in flight in refreshingDeferred (internal, like storage).
|
|
369
|
+
page.refreshing = () => auth.refreshingDeferred != null;
|
|
370
|
+
guardReads(auth, key, page);
|
|
371
|
+
signOutEverywhere(auth, key, page);
|
|
372
|
+
const wake = () => {
|
|
373
|
+
if (document.visibilityState === "hidden")
|
|
374
|
+
return;
|
|
375
|
+
reconcileInPage(key, page);
|
|
376
|
+
};
|
|
377
|
+
// On the document, so it runs before supabase-js's own listener on window.
|
|
378
|
+
document.addEventListener("visibilitychange", wake);
|
|
379
|
+
window.addEventListener("focus", wake);
|
|
380
|
+
window.addEventListener("pageshow", wake);
|
|
381
|
+
}
|
|
382
|
+
catch {
|
|
383
|
+
// Never let session mirroring break authentication itself.
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
/** supabase-js reads its session through `auth.storage`; take the newest first. */
|
|
387
|
+
function guardReads(auth, key, page) {
|
|
388
|
+
const inner = auth.storage;
|
|
389
|
+
if (!inner || typeof inner.getItem !== "function" || typeof inner.setItem !== "function")
|
|
390
|
+
return;
|
|
391
|
+
if (typeof inner.removeItem !== "function" || inner[GUARDED])
|
|
392
|
+
return;
|
|
393
|
+
const guarded = {
|
|
394
|
+
getItem(name) {
|
|
395
|
+
if (name === key)
|
|
396
|
+
reconcileInPage(key, page);
|
|
397
|
+
return inner.getItem(name);
|
|
398
|
+
},
|
|
399
|
+
setItem(name, value) {
|
|
400
|
+
return inner.setItem(name, value);
|
|
401
|
+
},
|
|
402
|
+
removeItem(name) {
|
|
403
|
+
if (name === key)
|
|
404
|
+
rememberDead(key, page);
|
|
405
|
+
return inner.removeItem(name);
|
|
406
|
+
},
|
|
407
|
+
};
|
|
408
|
+
if (inner.isServer !== undefined)
|
|
409
|
+
guarded.isServer = inner.isServer;
|
|
410
|
+
Object.defineProperty(guarded, GUARDED, { value: true });
|
|
411
|
+
auth.storage = guarded;
|
|
412
|
+
}
|
|
413
|
+
/** supabase-js removes a session it can no longer use: never take it back. */
|
|
414
|
+
function rememberDead(key, page) {
|
|
415
|
+
try {
|
|
416
|
+
const copy = parseCopy(window.localStorage.getItem(key));
|
|
417
|
+
if (copy)
|
|
418
|
+
page.dead.add(copy.refreshToken);
|
|
419
|
+
}
|
|
420
|
+
catch {
|
|
421
|
+
// Nothing to remember.
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* An explicit sign-out signs out every app: clear the cookie and leave the note
|
|
426
|
+
* first, and again once supabase-js has finished signing out. A sign-out that
|
|
427
|
+
* does not happen changes nothing: when supabase-js reports a failure and still
|
|
428
|
+
* holds the session here, the note goes back to what it was and the session is
|
|
429
|
+
* shared again, so a retry can still end it on the server. supabase-js 2.106
|
|
430
|
+
* keeps the session when the server's logout fails, and every version keeps it
|
|
431
|
+
* when the refresh it makes first fails on the network. 2.112 and later remove
|
|
432
|
+
* it even when the logout fails: that is a sign-out here, so it is one
|
|
433
|
+
* everywhere.
|
|
434
|
+
*/
|
|
435
|
+
function signOutEverywhere(auth, key, page) {
|
|
436
|
+
const original = auth.signOut;
|
|
437
|
+
if (typeof original !== "function")
|
|
438
|
+
return;
|
|
439
|
+
/**
|
|
440
|
+
* Leave the note for the copies this origin and the shared cookie hold right
|
|
441
|
+
* now (the latest expiry, and their sessions), then drop the shared copy.
|
|
442
|
+
*/
|
|
443
|
+
const seal = () => {
|
|
444
|
+
try {
|
|
445
|
+
const local = parseCopy(window.localStorage.getItem(key));
|
|
446
|
+
const shared = readShared(cookieJar(), key);
|
|
447
|
+
const copies = [local, shared.state === "present" ? shared.copy : null].filter((c) => c !== null);
|
|
448
|
+
if (copies.length > 0) {
|
|
449
|
+
writeSignedOut(key, Math.max(...copies.map((c) => c.expiresAt)), copies.flatMap((c) => (c.sessionId ? [c.sessionId] : [])));
|
|
450
|
+
}
|
|
451
|
+
clearCookieChunks(key);
|
|
452
|
+
}
|
|
453
|
+
catch {
|
|
454
|
+
// The sign-out itself still runs.
|
|
455
|
+
}
|
|
456
|
+
};
|
|
457
|
+
/**
|
|
458
|
+
* The sign-outs in flight here (a double click starts two; supabase-js runs
|
|
459
|
+
* them one after the other), the note's raw value before the first of them
|
|
460
|
+
* (null when there was none), and whether one of them signed out.
|
|
461
|
+
*/
|
|
462
|
+
let inFlight = 0;
|
|
463
|
+
let noteBefore = null;
|
|
464
|
+
let ended = false;
|
|
465
|
+
/** supabase-js still holds a session here. */
|
|
466
|
+
const stillHere = () => {
|
|
467
|
+
try {
|
|
468
|
+
return parseCopy(window.localStorage.getItem(key)) !== null;
|
|
469
|
+
}
|
|
470
|
+
catch {
|
|
471
|
+
return false;
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
/** None of them signed out, and supabase-js kept the session: undo the seal. */
|
|
475
|
+
const restore = () => {
|
|
476
|
+
try {
|
|
477
|
+
document.cookie = noteBefore === null
|
|
478
|
+
? `${signedOutName(key)}=; Domain=.${PARENT_DOMAIN}; Path=/; Max-Age=0; SameSite=Lax; Secure`
|
|
479
|
+
: `${signedOutName(key)}=${noteBefore}; Domain=.${PARENT_DOMAIN}; Path=/; Max-Age=${MAX_AGE}; SameSite=Lax; Secure`;
|
|
480
|
+
// The seal cleared the cookie: share this origin's copy again, unless the
|
|
481
|
+
// shared one is newer by now (a sign-in elsewhere meanwhile).
|
|
482
|
+
publishLocal(key);
|
|
483
|
+
}
|
|
484
|
+
catch {
|
|
485
|
+
// Nothing more to put back.
|
|
486
|
+
}
|
|
487
|
+
};
|
|
488
|
+
const finish = (failed) => {
|
|
489
|
+
inFlight -= 1;
|
|
490
|
+
if (!failed || !stillHere()) {
|
|
491
|
+
ended = true;
|
|
492
|
+
// When this origin's copy is due, supabase-js's signOut first waits for a
|
|
493
|
+
// refresh already in flight, or refreshes itself, and that refresh saves
|
|
494
|
+
// a rotated copy that expires after the note above. The note's session
|
|
495
|
+
// ids keep that copy out of the cookie only when its access token names
|
|
496
|
+
// its session, so seal again once the sign-out has finished: the note
|
|
497
|
+
// then covers the copy by its expiry too, and the cookie ends empty.
|
|
498
|
+
seal();
|
|
499
|
+
}
|
|
500
|
+
if (inFlight > 0)
|
|
501
|
+
return;
|
|
502
|
+
if (!ended)
|
|
503
|
+
restore();
|
|
504
|
+
page.signingOut = false;
|
|
505
|
+
};
|
|
506
|
+
auth.signOut = (...args) => {
|
|
507
|
+
const scope = args[0]?.scope;
|
|
508
|
+
// "others" signs out other devices only: this browser keeps its session.
|
|
509
|
+
if (scope === "others")
|
|
510
|
+
return Promise.resolve(original.apply(auth, args));
|
|
511
|
+
if (inFlight === 0) {
|
|
512
|
+
ended = false;
|
|
513
|
+
try {
|
|
514
|
+
noteBefore = cookieJar().get(signedOutName(key)) ?? null;
|
|
515
|
+
}
|
|
516
|
+
catch {
|
|
517
|
+
noteBefore = null;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
inFlight += 1;
|
|
521
|
+
page.signingOut = true;
|
|
522
|
+
seal();
|
|
523
|
+
let pending;
|
|
524
|
+
try {
|
|
525
|
+
pending = original.apply(auth, args);
|
|
526
|
+
}
|
|
527
|
+
catch (error) {
|
|
528
|
+
finish(true);
|
|
529
|
+
throw error;
|
|
530
|
+
}
|
|
531
|
+
// supabase-js answers a failed sign-out with { error }, or throws.
|
|
532
|
+
return Promise.resolve(pending).then((result) => {
|
|
533
|
+
const error = result?.error;
|
|
534
|
+
finish(error !== null && error !== undefined);
|
|
535
|
+
return result;
|
|
536
|
+
}, (error) => {
|
|
537
|
+
finish(true);
|
|
538
|
+
throw error;
|
|
539
|
+
});
|
|
540
|
+
};
|
|
541
|
+
}
|
|
124
542
|
/** The storage key, for server code that needs to find the cookie by name. */
|
|
125
543
|
export function sharedSessionCookieName(projectRef) {
|
|
126
544
|
return storageKey(projectRef);
|
package/package.json
CHANGED