autosolutions-os 0.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/README.md +55 -0
- package/dist/chrome.css +130 -0
- package/dist/chrome.d.ts +39 -0
- package/dist/chrome.js +135 -0
- package/dist/client.d.ts +26 -0
- package/dist/client.js +42 -0
- package/dist/config.d.ts +17 -0
- package/dist/config.js +53 -0
- package/dist/context.d.ts +49 -0
- package/dist/context.js +98 -0
- package/dist/gate.d.ts +53 -0
- package/dist/gate.js +137 -0
- package/dist/identity.d.ts +30 -0
- package/dist/identity.js +62 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/server.d.ts +34 -0
- package/dist/server.js +82 -0
- package/dist/session.d.ts +16 -0
- package/dist/session.js +127 -0
- package/package.json +30 -0
package/README.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# autosolutions-os
|
|
2
|
+
|
|
3
|
+
One sign-in, one company switcher, one app grid. Import this instead of copying
|
|
4
|
+
files between apps.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
bun add autosolutions-os @supabase/supabase-js
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```tsx
|
|
11
|
+
import { createOsClient, OsAuthGate, OsCompanySwitcher, OsAppSwitcher } from "autosolutions-os";
|
|
12
|
+
import "autosolutions-os/chrome.css";
|
|
13
|
+
|
|
14
|
+
const { supabase, os } = createOsClient({ appKey: "my_app", schema: "my_app" });
|
|
15
|
+
|
|
16
|
+
export function App() {
|
|
17
|
+
return (
|
|
18
|
+
<OsAuthGate os={os} auth={supabase.auth} appKey="my_app">
|
|
19
|
+
<header>
|
|
20
|
+
<OsAppSwitcher os={os} appKey="my_app" />
|
|
21
|
+
<OsCompanySwitcher os={os} appKey="my_app" />
|
|
22
|
+
</header>
|
|
23
|
+
{/* your app */}
|
|
24
|
+
</OsAuthGate>
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`supabase` is bound to your schema, so `.from("your_table")` works unchanged.
|
|
30
|
+
`os` is the same connection bound to `public`, for the platform's own functions.
|
|
31
|
+
|
|
32
|
+
## On the server
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { authenticate, tokenFromRequest } from "autosolutions-os/server";
|
|
36
|
+
|
|
37
|
+
const token = tokenFromRequest(request);
|
|
38
|
+
if (!token) throw new Error("Unauthorized");
|
|
39
|
+
const { userId, supabase } = await authenticate(token, "my_app");
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`authenticate` validates the token against the core and returns a client that
|
|
43
|
+
carries it, so row-level security still decides what the caller can read.
|
|
44
|
+
|
|
45
|
+
## What it deliberately does not do
|
|
46
|
+
|
|
47
|
+
- It does not read `SUPABASE_URL` from the environment. The core is pinned, because
|
|
48
|
+
a host that injects its own project makes every query return empty with no error.
|
|
49
|
+
- It does not keep a list of apps or companies. Both come from `os_context()`, so
|
|
50
|
+
registering an app in the catalogue is enough to make it appear everywhere.
|
|
51
|
+
- It does not clear the shared session unless someone explicitly signs out. An
|
|
52
|
+
empty local session is not evidence of a sign-out, and treating it as one signs
|
|
53
|
+
the person out of every other app.
|
|
54
|
+
|
|
55
|
+
See [`docs/CONTRACT.md`](../../docs/CONTRACT.md) for the rest of what an app owes the OS.
|
package/dist/chrome.css
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chrome styling.
|
|
3
|
+
*
|
|
4
|
+
* Colours and spacing come from the design system's tokens where an app loads
|
|
5
|
+
* it, with plain fallbacks so the chrome is still legible in an app that has
|
|
6
|
+
* not adopted the package yet.
|
|
7
|
+
*
|
|
8
|
+
* The company switcher is deliberately unplated: the design bible's rule is
|
|
9
|
+
* "the mark on its own with a disclosure chevron, transparent at rest, never
|
|
10
|
+
* put a plate behind it". The old vendored chrome drew a white rounded box with
|
|
11
|
+
* a border, which is what made every app's top bar look subtly wrong.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
.os-root { position: relative; display: inline-flex; align-items: center; }
|
|
15
|
+
|
|
16
|
+
/* Company switcher --------------------------------------------------- */
|
|
17
|
+
.os-company {
|
|
18
|
+
display: inline-flex; align-items: center; gap: 8px;
|
|
19
|
+
background: transparent; border: 0; padding: 4px 6px; margin: 0;
|
|
20
|
+
border-radius: var(--radius-200, 6px); cursor: pointer; color: inherit;
|
|
21
|
+
}
|
|
22
|
+
.os-company.is-static { cursor: default; }
|
|
23
|
+
.os-company:hover:not(.is-static) { background: rgb(255 255 255 / 8%); }
|
|
24
|
+
.os-company[aria-expanded="true"] { background: rgb(255 255 255 / 12%); }
|
|
25
|
+
.os-company__mark { display: block; height: 24px; width: auto; }
|
|
26
|
+
.os-company__name { font-size: 14px; font-weight: 500; white-space: nowrap; }
|
|
27
|
+
|
|
28
|
+
.os-chevron {
|
|
29
|
+
width: 0; height: 0; flex: none;
|
|
30
|
+
border-left: 4px solid transparent; border-right: 4px solid transparent;
|
|
31
|
+
border-top: 5px solid currentColor; opacity: 0.6;
|
|
32
|
+
transition: transform var(--duration-100, 120ms) var(--easing-standard, ease);
|
|
33
|
+
}
|
|
34
|
+
[aria-expanded="true"] > .os-chevron { transform: rotate(180deg); }
|
|
35
|
+
|
|
36
|
+
/* Menus --------------------------------------------------------------- */
|
|
37
|
+
.os-menu {
|
|
38
|
+
position: absolute; top: calc(100% + 6px); left: 0; z-index: 400;
|
|
39
|
+
min-width: 260px; padding: 6px;
|
|
40
|
+
background: var(--color-bg-surface, #ffffff);
|
|
41
|
+
color: var(--color-text, #14171f);
|
|
42
|
+
border: 1px solid var(--color-border, rgb(0 0 0 / 10%));
|
|
43
|
+
border-radius: var(--radius-300, 10px);
|
|
44
|
+
box-shadow: var(--shadow-300, 0 8px 24px rgb(0 0 0 / 12%));
|
|
45
|
+
}
|
|
46
|
+
.os-menu--right { left: auto; right: 0; }
|
|
47
|
+
.os-menu__label {
|
|
48
|
+
display: block; padding: 6px 10px;
|
|
49
|
+
font-size: 11px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase;
|
|
50
|
+
color: var(--color-text-secondary, #6b7280);
|
|
51
|
+
}
|
|
52
|
+
.os-menu__label--error { color: var(--color-text-critical, #be3a2e); text-transform: none; letter-spacing: 0; }
|
|
53
|
+
|
|
54
|
+
.os-item {
|
|
55
|
+
display: flex; align-items: center; gap: 10px; width: 100%;
|
|
56
|
+
padding: 8px 10px; background: transparent; border: 0; border-radius: var(--radius-200, 6px);
|
|
57
|
+
font: inherit; color: inherit; text-align: left; cursor: pointer;
|
|
58
|
+
}
|
|
59
|
+
.os-item:hover:not(:disabled) { background: var(--color-bg-surface-hover, rgb(0 0 0 / 4%)); }
|
|
60
|
+
.os-item:disabled { opacity: 0.6; cursor: default; }
|
|
61
|
+
.os-item__mark { height: 20px; width: auto; flex: none; }
|
|
62
|
+
.os-item__name { flex: 1; font-size: 14px; }
|
|
63
|
+
.os-check { width: 14px; height: 14px; flex: none; position: relative; }
|
|
64
|
+
.os-check::after {
|
|
65
|
+
content: ""; position: absolute; inset: 2px 3px 4px 2px;
|
|
66
|
+
border-right: 2px solid currentColor; border-bottom: 2px solid currentColor;
|
|
67
|
+
transform: rotate(45deg);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/* App grid ------------------------------------------------------------ */
|
|
71
|
+
.os-cols { display: grid; grid-template-columns: repeat(4, minmax(160px, 1fr)); gap: 4px 20px; padding: 6px; }
|
|
72
|
+
.os-cols--menu { grid-template-columns: 1fr; gap: 2px; padding: 0; }
|
|
73
|
+
.os-grp {
|
|
74
|
+
padding: 8px 10px 4px; font-size: 11px; font-weight: 700;
|
|
75
|
+
letter-spacing: 0.06em; text-transform: uppercase;
|
|
76
|
+
color: var(--color-text-secondary, #6b7280);
|
|
77
|
+
}
|
|
78
|
+
.os-sec {
|
|
79
|
+
padding: 6px 10px 2px; font-size: 11px; font-weight: 500;
|
|
80
|
+
color: var(--color-text-secondary, #6b7280);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
.os-plate {
|
|
84
|
+
display: flex; align-items: center; gap: 8px;
|
|
85
|
+
padding: 6px 10px; border-radius: var(--radius-200, 6px);
|
|
86
|
+
text-decoration: none; color: inherit;
|
|
87
|
+
}
|
|
88
|
+
.os-plate:hover { background: var(--color-bg-surface-hover, rgb(0 0 0 / 4%)); }
|
|
89
|
+
.os-plate.is-current { background: var(--color-bg-surface-selected, rgb(0 0 0 / 6%)); }
|
|
90
|
+
.os-plate.is-disabled { opacity: 0.4; cursor: not-allowed; }
|
|
91
|
+
.os-plate--button { background: transparent; border: 0; font: inherit; cursor: pointer; }
|
|
92
|
+
.os-plate__name { font-size: 14px; font-weight: 500; }
|
|
93
|
+
.os-label { display: block; height: 20px; width: auto; }
|
|
94
|
+
.os-label-text { font-size: 14px; font-weight: 500; }
|
|
95
|
+
.os-pipe { width: 1px; height: 16px; background: currentColor; opacity: 0.25; }
|
|
96
|
+
|
|
97
|
+
.os-empty {
|
|
98
|
+
padding: 12px 14px; margin: 0; max-width: 34ch;
|
|
99
|
+
font-size: 13px; line-height: 1.5; color: var(--color-text-secondary, #6b7280);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/* Bar ----------------------------------------------------------------- */
|
|
103
|
+
.os-bar {
|
|
104
|
+
display: flex; align-items: center; gap: 12px;
|
|
105
|
+
height: var(--topbar-height, 56px); padding: 0 16px;
|
|
106
|
+
background: var(--color-topbar-bg, #14171f); color: var(--color-text-inverse, #ffffff);
|
|
107
|
+
}
|
|
108
|
+
.os-bar__spacer { flex: 1; }
|
|
109
|
+
|
|
110
|
+
/* Gate ---------------------------------------------------------------- */
|
|
111
|
+
.os-gate { display: flex; min-height: 100vh; align-items: center; justify-content: center; padding: 24px; }
|
|
112
|
+
.os-gate__card {
|
|
113
|
+
max-width: 34rem; text-align: center;
|
|
114
|
+
display: flex; flex-direction: column; align-items: center; gap: 12px;
|
|
115
|
+
}
|
|
116
|
+
.os-gate__title { margin: 0; font-size: 20px; font-weight: 600; }
|
|
117
|
+
.os-gate__body { margin: 0; font-size: 14px; line-height: 1.6; color: var(--color-text-secondary, #6b7280); }
|
|
118
|
+
.os-gate__button {
|
|
119
|
+
margin-top: 4px; padding: 10px 18px; border-radius: 999px; border: 0; cursor: pointer;
|
|
120
|
+
background: var(--color-bg-fill-brand, #14171f); color: var(--color-text-inverse, #ffffff);
|
|
121
|
+
font: inherit; font-weight: 500;
|
|
122
|
+
}
|
|
123
|
+
.os-gate__link {
|
|
124
|
+
background: none; border: 0; padding: 0; cursor: pointer; font: inherit;
|
|
125
|
+
color: var(--color-text-secondary, #6b7280); text-decoration: underline;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
@media (prefers-reduced-motion: reduce) {
|
|
129
|
+
.os-chevron { transition: none; }
|
|
130
|
+
}
|
package/dist/chrome.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The OS chrome: the company switcher and the app grid.
|
|
3
|
+
*
|
|
4
|
+
* These two menus are the same object in every app, which is why they live here
|
|
5
|
+
* rather than in each app's repo. Everything they render comes from one
|
|
6
|
+
* `os_context()` call; nothing is hardcoded, so registering an app in the
|
|
7
|
+
* catalogue is enough to make it appear in the grid everywhere.
|
|
8
|
+
*
|
|
9
|
+
* The company switcher follows the design bible: the mark on its own with a
|
|
10
|
+
* disclosure chevron, transparent at rest, never a plate behind it.
|
|
11
|
+
*/
|
|
12
|
+
import { type ReactNode } from "react";
|
|
13
|
+
/** The app grid. `variant="menu"` is one column for a popover; `grid` is wide. */
|
|
14
|
+
export declare function OsAppSwitcher({ os, appKey, variant, onOpen }: {
|
|
15
|
+
os: unknown;
|
|
16
|
+
appKey: string;
|
|
17
|
+
variant?: "grid" | "menu";
|
|
18
|
+
onOpen?: () => void;
|
|
19
|
+
}): import("react").JSX.Element;
|
|
20
|
+
/**
|
|
21
|
+
* The company switcher. Switching changes the acting company server-side and
|
|
22
|
+
* then lands on that company's deployment of this app, a different front end
|
|
23
|
+
* when the company runs its own, or the hub when it does not hold this app.
|
|
24
|
+
*/
|
|
25
|
+
export declare function OsCompanySwitcher({ os, appKey }: {
|
|
26
|
+
os: unknown;
|
|
27
|
+
appKey: string;
|
|
28
|
+
}): import("react").JSX.Element | null;
|
|
29
|
+
/** App plate plus popover, for apps whose shell has no nav slot of its own. */
|
|
30
|
+
export declare function OsAppSwitcherPlate({ os, appKey }: {
|
|
31
|
+
os: unknown;
|
|
32
|
+
appKey: string;
|
|
33
|
+
}): import("react").JSX.Element | null;
|
|
34
|
+
/** A slim OS bar for apps with no top chrome of their own. */
|
|
35
|
+
export declare function OsBar({ os, appKey, children }: {
|
|
36
|
+
os: unknown;
|
|
37
|
+
appKey: string;
|
|
38
|
+
children?: ReactNode;
|
|
39
|
+
}): import("react").JSX.Element;
|
package/dist/chrome.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
/**
|
|
3
|
+
* The OS chrome: the company switcher and the app grid.
|
|
4
|
+
*
|
|
5
|
+
* These two menus are the same object in every app, which is why they live here
|
|
6
|
+
* rather than in each app's repo. Everything they render comes from one
|
|
7
|
+
* `os_context()` call; nothing is hardcoded, so registering an app in the
|
|
8
|
+
* catalogue is enough to make it appear in the grid everywhere.
|
|
9
|
+
*
|
|
10
|
+
* The company switcher follows the design bible: the mark on its own with a
|
|
11
|
+
* disclosure chevron, transparent at rest, never a plate behind it.
|
|
12
|
+
*/
|
|
13
|
+
import { useEffect, useRef, useState } from "react";
|
|
14
|
+
import { HUB_URL } from "./config";
|
|
15
|
+
import { groupApps, invalidateOsContext, labelFor, markFor, useOsContext, withTenantHint, } from "./context";
|
|
16
|
+
function useDismiss(open, close, ref) {
|
|
17
|
+
useEffect(() => {
|
|
18
|
+
if (!open)
|
|
19
|
+
return;
|
|
20
|
+
const onClick = (event) => {
|
|
21
|
+
if (ref.current && !ref.current.contains(event.target))
|
|
22
|
+
close();
|
|
23
|
+
};
|
|
24
|
+
const onKey = (event) => {
|
|
25
|
+
if (event.key === "Escape")
|
|
26
|
+
close();
|
|
27
|
+
};
|
|
28
|
+
window.addEventListener("mousedown", onClick);
|
|
29
|
+
window.addEventListener("keydown", onKey);
|
|
30
|
+
return () => {
|
|
31
|
+
window.removeEventListener("mousedown", onClick);
|
|
32
|
+
window.removeEventListener("keydown", onKey);
|
|
33
|
+
};
|
|
34
|
+
}, [open, close, ref]);
|
|
35
|
+
}
|
|
36
|
+
function AppPlate({ app, tenantSlug, current, onOpen }) {
|
|
37
|
+
const label = labelFor(app);
|
|
38
|
+
const mark = label ? (_jsx("img", { className: "os-label", src: label, alt: app.name, onError: (event) => {
|
|
39
|
+
// A catalogue entry can outrun its artwork. Say the name rather than
|
|
40
|
+
// show a broken image.
|
|
41
|
+
event.target.outerHTML =
|
|
42
|
+
`<span class="os-label-text">${app.name}</span>`;
|
|
43
|
+
} })) : (_jsx("span", { className: "os-label-text", children: app.name }));
|
|
44
|
+
if (!app.url) {
|
|
45
|
+
return (_jsx("div", { className: "os-plate is-disabled", "aria-disabled": "true", title: "No deployment yet", children: mark }));
|
|
46
|
+
}
|
|
47
|
+
return (_jsx("a", { className: "os-plate" + (current ? " is-current" : ""), href: withTenantHint(app.url, tenantSlug), ...(current ? {} : { target: "_blank", rel: "noreferrer noopener" }), "aria-label": `Open ${app.name}`, onClick: onOpen, children: mark }));
|
|
48
|
+
}
|
|
49
|
+
/** The app grid. `variant="menu"` is one column for a popover; `grid` is wide. */
|
|
50
|
+
export function OsAppSwitcher({ os, appKey, variant = "menu", onOpen }) {
|
|
51
|
+
const context = useOsContext(os);
|
|
52
|
+
if (!context)
|
|
53
|
+
return _jsx("p", { className: "os-empty", children: "Loading\u2026" });
|
|
54
|
+
const tenantSlug = context.tenant?.slug ?? null;
|
|
55
|
+
const columns = groupApps(context.apps);
|
|
56
|
+
if (columns.length === 0) {
|
|
57
|
+
return (_jsx("p", { className: "os-empty", children: "You are not entitled to any apps in this workspace. Ask your AutoSolutions administrator." }));
|
|
58
|
+
}
|
|
59
|
+
return (_jsxs("div", { className: "os-cols" + (variant === "menu" ? " os-cols--menu" : ""), children: [columns.map((column) => (_jsxs("div", { children: [_jsx("div", { className: "os-grp", children: column.group }), column.sections.map((section, index) => (_jsxs("div", { children: [section.title ? _jsx("div", { className: "os-sec", children: section.title }) : null, section.apps.map((app) => (_jsx(AppPlate, { app: app, tenantSlug: tenantSlug, current: app.key === appKey, onOpen: onOpen }, app.key)))] }, section.title ?? `section-${index}`)))] }, column.group))), _jsxs("div", { children: [_jsx("div", { className: "os-grp", children: "\u00A0" }), _jsx(AppPlate, { app: {
|
|
60
|
+
key: "hub", name: "Hub", iconUrl: null, url: HUB_URL, sortOrder: 0,
|
|
61
|
+
groupKey: null, sectionKey: null, designKey: "hub", labelUrl: null,
|
|
62
|
+
}, tenantSlug: tenantSlug, current: appKey === "hub", onOpen: onOpen })] })] }));
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The company switcher. Switching changes the acting company server-side and
|
|
66
|
+
* then lands on that company's deployment of this app, a different front end
|
|
67
|
+
* when the company runs its own, or the hub when it does not hold this app.
|
|
68
|
+
*/
|
|
69
|
+
export function OsCompanySwitcher({ os, appKey }) {
|
|
70
|
+
const context = useOsContext(os);
|
|
71
|
+
const [open, setOpen] = useState(false);
|
|
72
|
+
const [busy, setBusy] = useState(false);
|
|
73
|
+
const [error, setError] = useState(null);
|
|
74
|
+
const root = useRef(null);
|
|
75
|
+
useDismiss(open, () => setOpen(false), root);
|
|
76
|
+
if (!context?.tenant)
|
|
77
|
+
return null;
|
|
78
|
+
const current = context.tenant;
|
|
79
|
+
const single = context.tenants.length <= 1;
|
|
80
|
+
const choose = async (tenantId) => {
|
|
81
|
+
if (busy || tenantId === current.id) {
|
|
82
|
+
setOpen(false);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
setBusy(true);
|
|
86
|
+
setError(null);
|
|
87
|
+
const { data, error: rpcError } = await os.rpc("switch_company_for_app", {
|
|
88
|
+
t: tenantId,
|
|
89
|
+
app_key: appKey === "hub" ? null : appKey,
|
|
90
|
+
});
|
|
91
|
+
if (rpcError) {
|
|
92
|
+
// Say so. A menu that closes in silence after a failed switch reads as a
|
|
93
|
+
// broken switcher, and the only recovery anyone finds is a full refresh.
|
|
94
|
+
setBusy(false);
|
|
95
|
+
setError("Couldn't switch. Please try again.");
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
invalidateOsContext();
|
|
99
|
+
const result = (data ?? {});
|
|
100
|
+
if (appKey === "hub" || !result.appUrl) {
|
|
101
|
+
window.location.reload();
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const destination = withTenantHint(result.appUrl, result.tenantSlug ?? null);
|
|
105
|
+
try {
|
|
106
|
+
if (new URL(destination).origin === window.location.origin) {
|
|
107
|
+
window.location.reload();
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
/* malformed destination: fall through and let the browser report it */
|
|
113
|
+
}
|
|
114
|
+
window.location.assign(destination);
|
|
115
|
+
};
|
|
116
|
+
return (_jsxs("div", { className: "os-root", ref: root, children: [_jsxs("button", { type: "button", className: "os-company" + (single ? " is-static" : ""), onClick: () => !single && setOpen(!open), "aria-haspopup": !single, "aria-expanded": open, "aria-label": `Company: ${current.name}${single ? "" : ". Switch company"}`, children: [_jsx("img", { className: "os-company__mark", src: markFor(current), alt: current.name, title: current.name, onError: (event) => {
|
|
117
|
+
event.target.outerHTML =
|
|
118
|
+
`<span class="os-company__name">${current.name}</span>`;
|
|
119
|
+
} }), !single && _jsx("span", { className: "os-chevron", "aria-hidden": "true" })] }), open && (_jsxs("div", { className: "os-menu os-menu--right", role: "menu", children: [_jsx("span", { className: "os-menu__label", children: "Your companies" }), context.tenants.map((tenant) => (_jsxs("button", { type: "button", role: "menuitem", disabled: busy, className: "os-item" + (tenant.id === current.id ? " is-current" : ""), onClick: () => void choose(tenant.id), children: [_jsx("img", { className: "os-item__mark", src: markFor(tenant, "plain"), alt: "" }), _jsx("span", { className: "os-item__name", children: tenant.name }), tenant.id === current.id && _jsx("span", { className: "os-check", "aria-hidden": "true" })] }, tenant.id))), busy && _jsx("span", { className: "os-menu__label", children: "Switching\u2026" }), error && (_jsx("span", { className: "os-menu__label os-menu__label--error", role: "alert", children: error }))] }))] }));
|
|
120
|
+
}
|
|
121
|
+
/** App plate plus popover, for apps whose shell has no nav slot of its own. */
|
|
122
|
+
export function OsAppSwitcherPlate({ os, appKey }) {
|
|
123
|
+
const context = useOsContext(os);
|
|
124
|
+
const [open, setOpen] = useState(false);
|
|
125
|
+
const root = useRef(null);
|
|
126
|
+
useDismiss(open, () => setOpen(false), root);
|
|
127
|
+
if (!context)
|
|
128
|
+
return null;
|
|
129
|
+
const current = context.apps.find((app) => app.key === appKey);
|
|
130
|
+
return (_jsxs("div", { className: "os-root", ref: root, children: [_jsxs("button", { type: "button", className: "os-plate os-plate--button", onClick: () => setOpen(!open), "aria-haspopup": "true", "aria-expanded": open, children: [_jsx("span", { className: "os-pipe", "aria-hidden": "true" }), _jsx("span", { className: "os-plate__name", children: current?.name ?? (appKey === "hub" ? "Hub" : appKey) }), _jsx("span", { className: "os-chevron", "aria-hidden": "true" })] }), open && (_jsx("div", { className: "os-menu", role: "menu", children: _jsx(OsAppSwitcher, { os: os, appKey: appKey, variant: "menu", onOpen: () => setOpen(false) }) }))] }));
|
|
131
|
+
}
|
|
132
|
+
/** A slim OS bar for apps with no top chrome of their own. */
|
|
133
|
+
export function OsBar({ os, appKey, children }) {
|
|
134
|
+
return (_jsxs("div", { className: "os-bar", children: [_jsx(OsAppSwitcherPlate, { os: os, appKey: appKey }), children, _jsx("span", { className: "os-bar__spacer" }), _jsx(OsCompanySwitcher, { os: os, appKey: appKey })] }));
|
|
135
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one way an AutoSolutions app talks to the core.
|
|
3
|
+
*
|
|
4
|
+
* `supabase` is bound to the app's own schema, so existing calls such as
|
|
5
|
+
* `.from("prompt_chats")` keep working. `os` is the same connection bound to
|
|
6
|
+
* `public`, for the platform's own tables and functions.
|
|
7
|
+
*/
|
|
8
|
+
import { type SupabaseClient } from "@supabase/supabase-js";
|
|
9
|
+
type AnyClient = SupabaseClient<any, any, any>;
|
|
10
|
+
/** What `.schema()` hands back: `from`, `rpc`, and nothing that needs auth. */
|
|
11
|
+
export type SchemaClient = ReturnType<AnyClient["schema"]>;
|
|
12
|
+
export type OsClient = {
|
|
13
|
+
/** Bound to the app's schema (or `public` when the app has no tables). */
|
|
14
|
+
supabase: AnyClient;
|
|
15
|
+
/** The same connection bound to `public`: entitlements, tenants, catalogue. */
|
|
16
|
+
os: SchemaClient;
|
|
17
|
+
/** Ends the session here and, through the shared cookie, everywhere. */
|
|
18
|
+
signOut: () => Promise<void>;
|
|
19
|
+
};
|
|
20
|
+
export declare function createOsClient(options: {
|
|
21
|
+
appKey: string;
|
|
22
|
+
schema?: string;
|
|
23
|
+
}): OsClient;
|
|
24
|
+
/** Test seam: forget the cached client. */
|
|
25
|
+
export declare function resetOsClient(): void;
|
|
26
|
+
export {};
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one way an AutoSolutions app talks to the core.
|
|
3
|
+
*
|
|
4
|
+
* `supabase` is bound to the app's own schema, so existing calls such as
|
|
5
|
+
* `.from("prompt_chats")` keep working. `os` is the same connection bound to
|
|
6
|
+
* `public`, for the platform's own tables and functions.
|
|
7
|
+
*/
|
|
8
|
+
import { createClient } from "@supabase/supabase-js";
|
|
9
|
+
import { coreProjectRef, corePublishableKey, coreUrl } from "./config";
|
|
10
|
+
import { adoptSharedSession, publishSessionChanges } from "./session";
|
|
11
|
+
let cached;
|
|
12
|
+
export function createOsClient(options) {
|
|
13
|
+
// One client per page. A second would keep its own session state and the two
|
|
14
|
+
// would race each other's token refresh.
|
|
15
|
+
if (cached)
|
|
16
|
+
return cached;
|
|
17
|
+
const ref = coreProjectRef();
|
|
18
|
+
// Someone who signed in at the hub arrives here already authenticated. This
|
|
19
|
+
// has to run before the client below reads its storage.
|
|
20
|
+
adoptSharedSession(ref);
|
|
21
|
+
const supabase = createClient(coreUrl(), corePublishableKey(), {
|
|
22
|
+
...(options.schema ? { db: { schema: options.schema } } : {}),
|
|
23
|
+
auth: { persistSession: true, autoRefreshToken: true, detectSessionInUrl: true },
|
|
24
|
+
});
|
|
25
|
+
// Signing in or out here carries to every other AutoSolutions app.
|
|
26
|
+
publishSessionChanges(supabase, ref);
|
|
27
|
+
const client = {
|
|
28
|
+
supabase,
|
|
29
|
+
// Always take the explicit `public` view, so the type is the same whether or
|
|
30
|
+
// not the app bound itself to a schema.
|
|
31
|
+
os: supabase.schema("public"),
|
|
32
|
+
signOut: async () => {
|
|
33
|
+
await supabase.auth.signOut();
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
cached = client;
|
|
37
|
+
return client;
|
|
38
|
+
}
|
|
39
|
+
/** Test seam: forget the cached client. */
|
|
40
|
+
export function resetOsClient() {
|
|
41
|
+
cached = undefined;
|
|
42
|
+
}
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Core project URL. Override with CORE_SUPABASE_URL only if the core moves. */
|
|
2
|
+
export declare function coreUrl(): string;
|
|
3
|
+
/** Core publishable (anon) key, a public value, safe in the bundle. */
|
|
4
|
+
export declare function corePublishableKey(): string;
|
|
5
|
+
/**
|
|
6
|
+
* supabase-js keys its stored session by the project ref in its URL, so the ref
|
|
7
|
+
* is derived from the same resolved URL rather than pinned separately. A pinned
|
|
8
|
+
* copy can drift from the configured URL and then silently reads nothing.
|
|
9
|
+
*/
|
|
10
|
+
export declare function coreProjectRef(): string;
|
|
11
|
+
/** The artwork for one company, in the cut the surface calls for. */
|
|
12
|
+
export declare function companyMarkUrl(slug: string, cut?: "full" | "plain"): string;
|
|
13
|
+
/** The wordmark plate for one app. `designKey` comes from os_context(). */
|
|
14
|
+
export declare function appLabelUrl(designKey: string): string;
|
|
15
|
+
/** The hub itself: always present in the app grid, never in the catalogue. */
|
|
16
|
+
export declare const HUB_URL = "https://autosolutions.app";
|
|
17
|
+
export declare const PARENT_DOMAIN = "autosolutions.app";
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The core is one Supabase project, and its URL and publishable key are public
|
|
3
|
+
* values that already ship inside every browser bundle. They are pinned here
|
|
4
|
+
* rather than read from the environment, because the failure they prevent is
|
|
5
|
+
* expensive and silent: a host that injects its own SUPABASE_URL points an app
|
|
6
|
+
* at a project that never issued the user's token, and every read comes back
|
|
7
|
+
* empty with no error a developer can see.
|
|
8
|
+
*
|
|
9
|
+
* Secrets are never in this file. The service-role key is server-only and read
|
|
10
|
+
* from the environment where it is used.
|
|
11
|
+
*/
|
|
12
|
+
const CORE_URL = "https://allzlfxbemhhhihdpxfv.supabase.co";
|
|
13
|
+
const CORE_PUBLISHABLE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImFsbHpsZnhiZW1oaGhpaGRweGZ2Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODcwODE0ODksImV4cCI6MjEwMjY1NzQ4OX0.uGWNGg9onAFF88OZ6A_N3bacv805VLea1H_uKSH2LAI";
|
|
14
|
+
/** Where shared artwork lives: company marks, app labels, icons. */
|
|
15
|
+
const BRAND_BUCKET = `${CORE_URL}/storage/v1/object/public/brand`;
|
|
16
|
+
function fromEnv(name) {
|
|
17
|
+
if (typeof process === "undefined")
|
|
18
|
+
return undefined;
|
|
19
|
+
const value = process.env?.[name];
|
|
20
|
+
return value && value.length > 0 ? value : undefined;
|
|
21
|
+
}
|
|
22
|
+
/** Core project URL. Override with CORE_SUPABASE_URL only if the core moves. */
|
|
23
|
+
export function coreUrl() {
|
|
24
|
+
return fromEnv("CORE_SUPABASE_URL") ?? CORE_URL;
|
|
25
|
+
}
|
|
26
|
+
/** Core publishable (anon) key, a public value, safe in the bundle. */
|
|
27
|
+
export function corePublishableKey() {
|
|
28
|
+
return fromEnv("CORE_SUPABASE_ANON_KEY") ?? CORE_PUBLISHABLE_KEY;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* supabase-js keys its stored session by the project ref in its URL, so the ref
|
|
32
|
+
* is derived from the same resolved URL rather than pinned separately. A pinned
|
|
33
|
+
* copy can drift from the configured URL and then silently reads nothing.
|
|
34
|
+
*/
|
|
35
|
+
export function coreProjectRef() {
|
|
36
|
+
try {
|
|
37
|
+
return new URL(coreUrl()).hostname.split(".")[0] ?? "";
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return "";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** The artwork for one company, in the cut the surface calls for. */
|
|
44
|
+
export function companyMarkUrl(slug, cut = "full") {
|
|
45
|
+
return `${BRAND_BUCKET}/companies/${slug}${cut === "plain" ? "-plain" : ""}.png`;
|
|
46
|
+
}
|
|
47
|
+
/** The wordmark plate for one app. `designKey` comes from os_context(). */
|
|
48
|
+
export function appLabelUrl(designKey) {
|
|
49
|
+
return `${BRAND_BUCKET}/app-labels/${designKey}-label.png`;
|
|
50
|
+
}
|
|
51
|
+
/** The hub itself: always present in the app grid, never in the catalogue. */
|
|
52
|
+
export const HUB_URL = "https://autosolutions.app";
|
|
53
|
+
export const PARENT_DOMAIN = "autosolutions.app";
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export type OsTenant = {
|
|
2
|
+
id: string;
|
|
3
|
+
slug: string;
|
|
4
|
+
name: string;
|
|
5
|
+
logoUrl: string | null;
|
|
6
|
+
logoPlainUrl: string | null;
|
|
7
|
+
osRole?: string;
|
|
8
|
+
};
|
|
9
|
+
export type OsApp = {
|
|
10
|
+
key: string;
|
|
11
|
+
name: string;
|
|
12
|
+
iconUrl: string | null;
|
|
13
|
+
url: string | null;
|
|
14
|
+
sortOrder: number;
|
|
15
|
+
/** Switcher column, e.g. Marketing. Comes from the catalogue, not from code. */
|
|
16
|
+
groupKey: string | null;
|
|
17
|
+
/** Sub-heading inside the column; null means the untitled first block. */
|
|
18
|
+
sectionKey: string | null;
|
|
19
|
+
designKey: string | null;
|
|
20
|
+
labelUrl: string | null;
|
|
21
|
+
};
|
|
22
|
+
export type OsContext = {
|
|
23
|
+
tenant: OsTenant | null;
|
|
24
|
+
tenants: OsTenant[];
|
|
25
|
+
apps: OsApp[];
|
|
26
|
+
};
|
|
27
|
+
export declare function loadOsContext(os: unknown): Promise<OsContext | null>;
|
|
28
|
+
/** Forget the cached answer, so the next read reflects a company switch. */
|
|
29
|
+
export declare function invalidateOsContext(): void;
|
|
30
|
+
export declare function useOsContext(os: unknown): OsContext | null;
|
|
31
|
+
export declare function useTenant(os: unknown): OsTenant | null;
|
|
32
|
+
export declare function useApps(os: unknown): OsApp[];
|
|
33
|
+
/** The mark for a company, preferring the catalogue's own artwork. */
|
|
34
|
+
export declare function markFor(tenant: OsTenant, cut?: "full" | "plain"): string;
|
|
35
|
+
/** The wordmark plate for an app, falling back to the CDN convention. */
|
|
36
|
+
export declare function labelFor(app: OsApp): string | null;
|
|
37
|
+
/** Apps grouped for the switcher, in catalogue order. No hardcoded taxonomy. */
|
|
38
|
+
export declare function groupApps(apps: OsApp[]): Array<{
|
|
39
|
+
group: string;
|
|
40
|
+
sections: Array<{
|
|
41
|
+
title: string | null;
|
|
42
|
+
apps: OsApp[];
|
|
43
|
+
}>;
|
|
44
|
+
}>;
|
|
45
|
+
/**
|
|
46
|
+
* Apps show the acting company's branding, so a link carries it as a hint.
|
|
47
|
+
* Access is still decided by the core; this only saves a round trip.
|
|
48
|
+
*/
|
|
49
|
+
export declare function withTenantHint(url: string, slug: string | null): string;
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `os_context()` is the one call every app's chrome makes: who you are acting
|
|
3
|
+
* as, which companies you can act as, and which apps you hold. One round trip,
|
|
4
|
+
* cached for the page.
|
|
5
|
+
*/
|
|
6
|
+
import { useEffect, useState } from "react";
|
|
7
|
+
import { appLabelUrl, companyMarkUrl } from "./config";
|
|
8
|
+
/**
|
|
9
|
+
* One fetch per page, but a FAILURE is never cached. A call that races a token
|
|
10
|
+
* refresh would otherwise blank both switchers until a full reload.
|
|
11
|
+
*/
|
|
12
|
+
let pending = null;
|
|
13
|
+
export function loadOsContext(os) {
|
|
14
|
+
if (!pending) {
|
|
15
|
+
pending = Promise.resolve(os.rpc("os_context"))
|
|
16
|
+
.then(({ data, error }) => {
|
|
17
|
+
if (error || !data) {
|
|
18
|
+
pending = null;
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
return data;
|
|
22
|
+
})
|
|
23
|
+
.catch(() => {
|
|
24
|
+
pending = null;
|
|
25
|
+
return null;
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
return pending;
|
|
29
|
+
}
|
|
30
|
+
/** Forget the cached answer, so the next read reflects a company switch. */
|
|
31
|
+
export function invalidateOsContext() {
|
|
32
|
+
pending = null;
|
|
33
|
+
}
|
|
34
|
+
export function useOsContext(os) {
|
|
35
|
+
const [context, setContext] = useState(null);
|
|
36
|
+
useEffect(() => {
|
|
37
|
+
let live = true;
|
|
38
|
+
void loadOsContext(os).then((value) => {
|
|
39
|
+
if (live)
|
|
40
|
+
setContext(value);
|
|
41
|
+
});
|
|
42
|
+
return () => {
|
|
43
|
+
live = false;
|
|
44
|
+
};
|
|
45
|
+
}, [os]);
|
|
46
|
+
return context;
|
|
47
|
+
}
|
|
48
|
+
export function useTenant(os) {
|
|
49
|
+
return useOsContext(os)?.tenant ?? null;
|
|
50
|
+
}
|
|
51
|
+
export function useApps(os) {
|
|
52
|
+
return useOsContext(os)?.apps ?? [];
|
|
53
|
+
}
|
|
54
|
+
/** The mark for a company, preferring the catalogue's own artwork. */
|
|
55
|
+
export function markFor(tenant, cut = "full") {
|
|
56
|
+
const stored = cut === "plain" ? tenant.logoPlainUrl : tenant.logoUrl;
|
|
57
|
+
return stored ?? companyMarkUrl(tenant.slug, cut);
|
|
58
|
+
}
|
|
59
|
+
/** The wordmark plate for an app, falling back to the CDN convention. */
|
|
60
|
+
export function labelFor(app) {
|
|
61
|
+
if (app.labelUrl)
|
|
62
|
+
return app.labelUrl;
|
|
63
|
+
return app.designKey ? appLabelUrl(app.designKey) : null;
|
|
64
|
+
}
|
|
65
|
+
/** Apps grouped for the switcher, in catalogue order. No hardcoded taxonomy. */
|
|
66
|
+
export function groupApps(apps) {
|
|
67
|
+
const groups = new Map();
|
|
68
|
+
for (const app of [...apps].sort((a, b) => a.sortOrder - b.sortOrder)) {
|
|
69
|
+
const group = app.groupKey ?? "Other";
|
|
70
|
+
const section = app.sectionKey ?? "";
|
|
71
|
+
if (!groups.has(group))
|
|
72
|
+
groups.set(group, new Map());
|
|
73
|
+
const sections = groups.get(group);
|
|
74
|
+
if (!sections.has(section))
|
|
75
|
+
sections.set(section, []);
|
|
76
|
+
sections.get(section).push(app);
|
|
77
|
+
}
|
|
78
|
+
return [...groups.entries()].map(([group, sections]) => ({
|
|
79
|
+
group,
|
|
80
|
+
sections: [...sections.entries()].map(([title, list]) => ({ title: title || null, apps: list })),
|
|
81
|
+
}));
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Apps show the acting company's branding, so a link carries it as a hint.
|
|
85
|
+
* Access is still decided by the core; this only saves a round trip.
|
|
86
|
+
*/
|
|
87
|
+
export function withTenantHint(url, slug) {
|
|
88
|
+
if (!slug)
|
|
89
|
+
return url;
|
|
90
|
+
try {
|
|
91
|
+
const parsed = new URL(url);
|
|
92
|
+
parsed.searchParams.set("tenant", slug);
|
|
93
|
+
return parsed.toString();
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return url;
|
|
97
|
+
}
|
|
98
|
+
}
|
package/dist/gate.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The door every AutoSolutions app opens through.
|
|
3
|
+
*
|
|
4
|
+
* It answers four questions in order, and each has one honest screen:
|
|
5
|
+
* is the session still arriving? → nothing, briefly
|
|
6
|
+
* is anyone signed in? → sign in with Google
|
|
7
|
+
* do they belong to a company? → ask your administrator
|
|
8
|
+
* does this company hold this app? → ask your administrator
|
|
9
|
+
*
|
|
10
|
+
* It fails closed. If the core cannot be reached, nobody gets in, because the
|
|
11
|
+
* alternative, showing the app and letting row-level security return empty
|
|
12
|
+
* lists, reads to the user as "the product is broken".
|
|
13
|
+
*/
|
|
14
|
+
import { type ReactNode } from "react";
|
|
15
|
+
/**
|
|
16
|
+
* Only the parts of a Supabase auth client this gate touches.
|
|
17
|
+
*
|
|
18
|
+
* The parameters are deliberately `any`. A narrower type reads better but sits
|
|
19
|
+
* in contravariant position, so `signInWithOAuth: (o: unknown) => ...` demands
|
|
20
|
+
* a function accepting ANYTHING and the real client's own typed signature is
|
|
21
|
+
* then rejected. Every app would have to cast at the call site.
|
|
22
|
+
*/
|
|
23
|
+
type Auth = {
|
|
24
|
+
getSession: () => Promise<{
|
|
25
|
+
data: {
|
|
26
|
+
session: any;
|
|
27
|
+
};
|
|
28
|
+
}>;
|
|
29
|
+
onAuthStateChange: (cb: (event: any, session: any) => void) => {
|
|
30
|
+
data: {
|
|
31
|
+
subscription: {
|
|
32
|
+
unsubscribe: () => void;
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
signInWithOAuth: (options: any) => Promise<{
|
|
37
|
+
error: any;
|
|
38
|
+
}>;
|
|
39
|
+
signOut: () => Promise<any>;
|
|
40
|
+
};
|
|
41
|
+
export type OsAuthGateProps = {
|
|
42
|
+
os: unknown;
|
|
43
|
+
auth: Auth;
|
|
44
|
+
appKey: string;
|
|
45
|
+
children: ReactNode;
|
|
46
|
+
/** Optional second gate, e.g. an app that also requires approval. */
|
|
47
|
+
extraCheck?: () => Promise<boolean>;
|
|
48
|
+
/** Shown instead of the default screens, for an app with its own look. */
|
|
49
|
+
renderSignedOut?: (signIn: () => void) => ReactNode;
|
|
50
|
+
renderDenied?: (signOut: () => void) => ReactNode;
|
|
51
|
+
};
|
|
52
|
+
export declare function OsAuthGate({ os, auth, appKey, children, extraCheck, renderSignedOut, renderDenied, }: OsAuthGateProps): import("react").JSX.Element;
|
|
53
|
+
export {};
|
package/dist/gate.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
/**
|
|
3
|
+
* The door every AutoSolutions app opens through.
|
|
4
|
+
*
|
|
5
|
+
* It answers four questions in order, and each has one honest screen:
|
|
6
|
+
* is the session still arriving? → nothing, briefly
|
|
7
|
+
* is anyone signed in? → sign in with Google
|
|
8
|
+
* do they belong to a company? → ask your administrator
|
|
9
|
+
* does this company hold this app? → ask your administrator
|
|
10
|
+
*
|
|
11
|
+
* It fails closed. If the core cannot be reached, nobody gets in, because the
|
|
12
|
+
* alternative, showing the app and letting row-level security return empty
|
|
13
|
+
* lists, reads to the user as "the product is broken".
|
|
14
|
+
*/
|
|
15
|
+
import { useCallback, useEffect, useState } from "react";
|
|
16
|
+
import { isActiveMember, isEntitled } from "./identity";
|
|
17
|
+
import { invalidateOsContext, loadOsContext } from "./context";
|
|
18
|
+
/* eslint-enable @typescript-eslint/no-explicit-any */
|
|
19
|
+
/** The session is restored from storage asynchronously; give it one beat. */
|
|
20
|
+
const RESTORE_GRACE_MS = 1500;
|
|
21
|
+
async function resolveSession(auth) {
|
|
22
|
+
const { data } = await auth.getSession();
|
|
23
|
+
if (data.session)
|
|
24
|
+
return true;
|
|
25
|
+
return new Promise((resolve) => {
|
|
26
|
+
const listener = auth.onAuthStateChange((_event, session) => {
|
|
27
|
+
if (!session)
|
|
28
|
+
return;
|
|
29
|
+
clearTimeout(timer);
|
|
30
|
+
listener.data.subscription.unsubscribe();
|
|
31
|
+
resolve(true);
|
|
32
|
+
});
|
|
33
|
+
const timer = setTimeout(() => {
|
|
34
|
+
listener.data.subscription.unsubscribe();
|
|
35
|
+
resolve(false);
|
|
36
|
+
}, RESTORE_GRACE_MS);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* A link into an app can name the company to open it in. Honour it once, then
|
|
41
|
+
* strip it, so a reload does not keep forcing the same company on someone who
|
|
42
|
+
* has since switched.
|
|
43
|
+
*/
|
|
44
|
+
async function applyTenantHint(os, appKey) {
|
|
45
|
+
if (typeof window === "undefined")
|
|
46
|
+
return false;
|
|
47
|
+
const url = new URL(window.location.href);
|
|
48
|
+
const wanted = url.searchParams.get("tenant");
|
|
49
|
+
if (!wanted)
|
|
50
|
+
return false;
|
|
51
|
+
url.searchParams.delete("tenant");
|
|
52
|
+
const context = await loadOsContext(os);
|
|
53
|
+
const target = context?.tenants.find((tenant) => tenant.slug === wanted);
|
|
54
|
+
// Unknown or not viewable: drop the hint silently rather than explain a
|
|
55
|
+
// company the person may not be allowed to know exists.
|
|
56
|
+
if (!target || target.id === context?.tenant?.id) {
|
|
57
|
+
window.history.replaceState({}, "", url.toString());
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
const { error } = await os.rpc("switch_company_for_app", { t: target.id, app_key: appKey === "hub" ? null : appKey });
|
|
61
|
+
if (error) {
|
|
62
|
+
window.history.replaceState({}, "", url.toString());
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
invalidateOsContext();
|
|
66
|
+
window.location.replace(url.toString());
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
export function OsAuthGate({ os, auth, appKey, children, extraCheck, renderSignedOut, renderDenied, }) {
|
|
70
|
+
const [phase, setPhase] = useState("loading");
|
|
71
|
+
const signIn = useCallback(() => {
|
|
72
|
+
void auth.signInWithOAuth({
|
|
73
|
+
provider: "google",
|
|
74
|
+
options: { redirectTo: window.location.origin },
|
|
75
|
+
});
|
|
76
|
+
}, [auth]);
|
|
77
|
+
const signOut = useCallback(() => {
|
|
78
|
+
void auth.signOut().then(() => window.location.reload());
|
|
79
|
+
}, [auth]);
|
|
80
|
+
useEffect(() => {
|
|
81
|
+
let live = true;
|
|
82
|
+
async function decide() {
|
|
83
|
+
if (!(await resolveSession(auth))) {
|
|
84
|
+
if (live)
|
|
85
|
+
setPhase("signed-out");
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (await applyTenantHint(os, appKey))
|
|
89
|
+
return; // navigating away
|
|
90
|
+
try {
|
|
91
|
+
// The Hub is the roof: any active member may open it. Every other app
|
|
92
|
+
// asks whether this company bought it.
|
|
93
|
+
const allowed = appKey === "hub" ? await isActiveMember(os) : await isEntitled(os, appKey);
|
|
94
|
+
if (!allowed) {
|
|
95
|
+
const member = appKey === "hub" ? false : await isActiveMember(os);
|
|
96
|
+
if (live)
|
|
97
|
+
setPhase(member || appKey === "hub" ? "denied" : "no-company");
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (extraCheck && !(await extraCheck())) {
|
|
101
|
+
if (live)
|
|
102
|
+
setPhase("denied");
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (live)
|
|
106
|
+
setPhase("ready");
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
if (live)
|
|
110
|
+
setPhase("denied");
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
void decide();
|
|
114
|
+
const listener = auth.onAuthStateChange((event) => {
|
|
115
|
+
if (event === "SIGNED_IN" || event === "SIGNED_OUT")
|
|
116
|
+
void decide();
|
|
117
|
+
});
|
|
118
|
+
return () => {
|
|
119
|
+
live = false;
|
|
120
|
+
listener.data.subscription.unsubscribe();
|
|
121
|
+
};
|
|
122
|
+
}, [os, auth, appKey, extraCheck]);
|
|
123
|
+
if (phase === "ready")
|
|
124
|
+
return _jsx(_Fragment, { children: children });
|
|
125
|
+
if (phase === "loading")
|
|
126
|
+
return _jsx("div", { className: "os-gate", "aria-busy": "true" });
|
|
127
|
+
if (phase === "signed-out") {
|
|
128
|
+
if (renderSignedOut)
|
|
129
|
+
return _jsx(_Fragment, { children: renderSignedOut(signIn) });
|
|
130
|
+
return (_jsx("div", { className: "os-gate", children: _jsxs("div", { className: "os-gate__card", children: [_jsx("h1", { className: "os-gate__title", children: "Sign in" }), _jsx("p", { className: "os-gate__body", children: "Use your work Google account." }), _jsx("button", { type: "button", className: "os-gate__button", onClick: signIn, children: "Sign in with Google" })] }) }));
|
|
131
|
+
}
|
|
132
|
+
if (renderDenied)
|
|
133
|
+
return _jsx(_Fragment, { children: renderDenied(signOut) });
|
|
134
|
+
return (_jsx("div", { className: "os-gate", children: _jsxs("div", { className: "os-gate__card", children: [_jsx("h1", { className: "os-gate__title", children: phase === "no-company" ? "No workspace yet" : "No access yet" }), _jsx("p", { className: "os-gate__body", children: phase === "no-company"
|
|
135
|
+
? "Your account is not part of a company yet. Ask your AutoSolutions administrator to add you."
|
|
136
|
+
: "This company does not have this app. Ask your AutoSolutions administrator for access." }), _jsx("button", { type: "button", className: "os-gate__link", onClick: signOut, children: "Use a different account" })] }) }));
|
|
137
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who the caller is, according to the core. Every answer is the core's, never a
|
|
3
|
+
* guess made in the browser: these are thin wrappers over functions that already
|
|
4
|
+
* exist, so an app cannot drift from the platform's idea of permission.
|
|
5
|
+
*/
|
|
6
|
+
/** Does this company hold this app? */
|
|
7
|
+
export declare function isEntitled(os: unknown, appKey: string): Promise<boolean>;
|
|
8
|
+
/** Is the caller an active member of any company? The Hub's own gate. */
|
|
9
|
+
export declare function isActiveMember(os: unknown): Promise<boolean>;
|
|
10
|
+
/** The caller's level inside one app, in the company they are acting in. */
|
|
11
|
+
export declare function appRole(os: unknown, appKey: string): Promise<string | null>;
|
|
12
|
+
/**
|
|
13
|
+
* Which flavour of an app this company bought. Two companies can hold the same
|
|
14
|
+
* app and see different products; the CRM is Enxgy's candidate search and Frank
|
|
15
|
+
* Body's buyer search from one deployment.
|
|
16
|
+
*/
|
|
17
|
+
export declare function appVariant(os: unknown, appKey: string): Promise<string | null>;
|
|
18
|
+
/** The company the caller is acting in. */
|
|
19
|
+
export declare function currentTenant(os: unknown): Promise<string | null>;
|
|
20
|
+
/** Whether one named view inside an app is open to the caller. */
|
|
21
|
+
export declare function toolAllowed(os: unknown, appKey: string, toolKey: string): Promise<boolean>;
|
|
22
|
+
export type AdminScope = {
|
|
23
|
+
isPlatformAdmin: boolean;
|
|
24
|
+
managesTenants: string[];
|
|
25
|
+
groupAdminOf: string[];
|
|
26
|
+
};
|
|
27
|
+
/** What the caller administers. Platform admins are included here already. */
|
|
28
|
+
export declare function myAdminScope(os: unknown): Promise<AdminScope>;
|
|
29
|
+
/** Does the caller administer the platform, or the company they are acting in? */
|
|
30
|
+
export declare function canManageCurrentCompany(os: unknown): Promise<boolean>;
|
package/dist/identity.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who the caller is, according to the core. Every answer is the core's, never a
|
|
3
|
+
* guess made in the browser: these are thin wrappers over functions that already
|
|
4
|
+
* exist, so an app cannot drift from the platform's idea of permission.
|
|
5
|
+
*/
|
|
6
|
+
function first(data) {
|
|
7
|
+
const value = Array.isArray(data) ? data[0] : data;
|
|
8
|
+
return (value ?? null);
|
|
9
|
+
}
|
|
10
|
+
async function call(client, fn, args) {
|
|
11
|
+
const { data, error } = await client.rpc(fn, args);
|
|
12
|
+
if (error)
|
|
13
|
+
throw new Error(`${fn}: ${error.message}`);
|
|
14
|
+
return first(data);
|
|
15
|
+
}
|
|
16
|
+
/** Does this company hold this app? */
|
|
17
|
+
export async function isEntitled(os, appKey) {
|
|
18
|
+
return (await call(os, "is_entitled", { app_key: appKey })) === true;
|
|
19
|
+
}
|
|
20
|
+
/** Is the caller an active member of any company? The Hub's own gate. */
|
|
21
|
+
export async function isActiveMember(os) {
|
|
22
|
+
return (await call(os, "is_active_member")) === true;
|
|
23
|
+
}
|
|
24
|
+
/** The caller's level inside one app, in the company they are acting in. */
|
|
25
|
+
export async function appRole(os, appKey) {
|
|
26
|
+
const role = await call(os, "app_role", { app_key: appKey });
|
|
27
|
+
return typeof role === "string" && role.length > 0 ? role : null;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Which flavour of an app this company bought. Two companies can hold the same
|
|
31
|
+
* app and see different products; the CRM is Enxgy's candidate search and Frank
|
|
32
|
+
* Body's buyer search from one deployment.
|
|
33
|
+
*/
|
|
34
|
+
export async function appVariant(os, appKey) {
|
|
35
|
+
const variant = await call(os, "app_variant", { app_key: appKey });
|
|
36
|
+
return typeof variant === "string" && variant.length > 0 ? variant : null;
|
|
37
|
+
}
|
|
38
|
+
/** The company the caller is acting in. */
|
|
39
|
+
export async function currentTenant(os) {
|
|
40
|
+
const id = await call(os, "current_tenant");
|
|
41
|
+
return typeof id === "string" && id.length > 0 ? id : null;
|
|
42
|
+
}
|
|
43
|
+
/** Whether one named view inside an app is open to the caller. */
|
|
44
|
+
export async function toolAllowed(os, appKey, toolKey) {
|
|
45
|
+
return (await call(os, "tool_allowed", { app_key: appKey, tool_key: toolKey })) === true;
|
|
46
|
+
}
|
|
47
|
+
/** What the caller administers. Platform admins are included here already. */
|
|
48
|
+
export async function myAdminScope(os) {
|
|
49
|
+
const row = await call(os, "my_admin_scope");
|
|
50
|
+
return {
|
|
51
|
+
isPlatformAdmin: Boolean(row?.["is_platform_admin"]),
|
|
52
|
+
managesTenants: row?.["manages_tenants"] ?? [],
|
|
53
|
+
groupAdminOf: row?.["group_admin_of"] ?? [],
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/** Does the caller administer the platform, or the company they are acting in? */
|
|
57
|
+
export async function canManageCurrentCompany(os) {
|
|
58
|
+
const [scope, tenantId] = await Promise.all([myAdminScope(os), currentTenant(os)]);
|
|
59
|
+
if (scope.isPlatformAdmin)
|
|
60
|
+
return true;
|
|
61
|
+
return tenantId !== null && scope.managesTenants.includes(tenantId);
|
|
62
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { coreUrl, corePublishableKey, coreProjectRef, companyMarkUrl, appLabelUrl, HUB_URL, PARENT_DOMAIN } from "./config";
|
|
2
|
+
export { createOsClient, resetOsClient, type OsClient } from "./client";
|
|
3
|
+
export { adoptSharedSession, publishSessionChanges, sharedSessionCookieName, joinChunks } from "./session";
|
|
4
|
+
export { loadOsContext, invalidateOsContext, useOsContext, useTenant, useApps, groupApps, markFor, labelFor, withTenantHint, type OsContext, type OsTenant, type OsApp, } from "./context";
|
|
5
|
+
export { isEntitled, isActiveMember, appRole, appVariant, currentTenant, toolAllowed, myAdminScope, canManageCurrentCompany, type AdminScope, } from "./identity";
|
|
6
|
+
export { OsAppSwitcher, OsAppSwitcherPlate, OsCompanySwitcher, OsBar } from "./chrome";
|
|
7
|
+
export { OsAuthGate, type OsAuthGateProps } from "./gate";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { coreUrl, corePublishableKey, coreProjectRef, companyMarkUrl, appLabelUrl, HUB_URL, PARENT_DOMAIN } from "./config";
|
|
2
|
+
export { createOsClient, resetOsClient } from "./client";
|
|
3
|
+
export { adoptSharedSession, publishSessionChanges, sharedSessionCookieName, joinChunks } from "./session";
|
|
4
|
+
export { loadOsContext, invalidateOsContext, useOsContext, useTenant, useApps, groupApps, markFor, labelFor, withTenantHint, } from "./context";
|
|
5
|
+
export { isEntitled, isActiveMember, appRole, appVariant, currentTenant, toolAllowed, myAdminScope, canManageCurrentCompany, } from "./identity";
|
|
6
|
+
export { OsAppSwitcher, OsAppSwitcherPlate, OsCompanySwitcher, OsBar } from "./chrome";
|
|
7
|
+
export { OsAuthGate } from "./gate";
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-side auth for apps built on TanStack Start.
|
|
3
|
+
*
|
|
4
|
+
* Every server function validates the caller's bearer token against the core
|
|
5
|
+
* before it does anything. The client that comes back carries the caller's own
|
|
6
|
+
* token, so the core's row-level security is still the boundary: this only
|
|
7
|
+
* guarantees the request is talking to the right project with a key that
|
|
8
|
+
* project accepts.
|
|
9
|
+
*/
|
|
10
|
+
import { type SupabaseClient } from "@supabase/supabase-js";
|
|
11
|
+
export type CoreAuth = {
|
|
12
|
+
userId: string;
|
|
13
|
+
claims: Record<string, unknown>;
|
|
14
|
+
/** RLS-scoped client carrying the caller's token. */
|
|
15
|
+
supabase: SupabaseClient<any, any, any>;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Validate a bearer token and return a client scoped to its owner.
|
|
19
|
+
* Throws on anything short of a valid token, so a handler cannot accidentally
|
|
20
|
+
* run unauthenticated.
|
|
21
|
+
*/
|
|
22
|
+
export declare function authenticate(token: string, schema?: string): Promise<CoreAuth>;
|
|
23
|
+
/** Pull the bearer token out of a request, from the header or the shared cookie. */
|
|
24
|
+
export declare function tokenFromRequest(request: {
|
|
25
|
+
headers: {
|
|
26
|
+
get: (name: string) => string | null;
|
|
27
|
+
};
|
|
28
|
+
}): string | null;
|
|
29
|
+
/**
|
|
30
|
+
* A client that bypasses row-level security, for the few operations that must:
|
|
31
|
+
* provisioning, cross-user admin reads, cleanup. Server-only, and never
|
|
32
|
+
* constructed from a value that reached the browser.
|
|
33
|
+
*/
|
|
34
|
+
export declare function serviceClient(schema?: string): SupabaseClient<any, any, any>;
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-side auth for apps built on TanStack Start.
|
|
3
|
+
*
|
|
4
|
+
* Every server function validates the caller's bearer token against the core
|
|
5
|
+
* before it does anything. The client that comes back carries the caller's own
|
|
6
|
+
* token, so the core's row-level security is still the boundary: this only
|
|
7
|
+
* guarantees the request is talking to the right project with a key that
|
|
8
|
+
* project accepts.
|
|
9
|
+
*/
|
|
10
|
+
import { createClient } from "@supabase/supabase-js";
|
|
11
|
+
import { corePublishableKey, coreProjectRef, coreUrl } from "./config";
|
|
12
|
+
import { joinChunks, sharedSessionCookieName } from "./session";
|
|
13
|
+
function clientForToken(token, schema) {
|
|
14
|
+
return createClient(coreUrl(), corePublishableKey(), {
|
|
15
|
+
...(schema ? { db: { schema } } : {}),
|
|
16
|
+
global: { headers: { Authorization: `Bearer ${token}` } },
|
|
17
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Validate a bearer token and return a client scoped to its owner.
|
|
22
|
+
* Throws on anything short of a valid token, so a handler cannot accidentally
|
|
23
|
+
* run unauthenticated.
|
|
24
|
+
*/
|
|
25
|
+
export async function authenticate(token, schema) {
|
|
26
|
+
if (!token || token.split(".").length !== 3)
|
|
27
|
+
throw new Error("Unauthorized: invalid token");
|
|
28
|
+
const supabase = clientForToken(token, schema);
|
|
29
|
+
const { data, error } = await supabase.auth.getClaims(token);
|
|
30
|
+
if (error || !data?.claims?.sub)
|
|
31
|
+
throw new Error("Unauthorized: invalid token");
|
|
32
|
+
return {
|
|
33
|
+
userId: String(data.claims.sub),
|
|
34
|
+
claims: data.claims,
|
|
35
|
+
supabase,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** Pull the bearer token out of a request, from the header or the shared cookie. */
|
|
39
|
+
export function tokenFromRequest(request) {
|
|
40
|
+
const header = request.headers.get("authorization");
|
|
41
|
+
if (header?.startsWith("Bearer ")) {
|
|
42
|
+
const token = header.slice("Bearer ".length);
|
|
43
|
+
if (token)
|
|
44
|
+
return token;
|
|
45
|
+
}
|
|
46
|
+
// During SSR there is no Authorization header, but the shared session cookie
|
|
47
|
+
// is on the request because it is scoped to the parent domain.
|
|
48
|
+
const cookieHeader = request.headers.get("cookie");
|
|
49
|
+
if (!cookieHeader)
|
|
50
|
+
return null;
|
|
51
|
+
const jar = new Map();
|
|
52
|
+
for (const entry of cookieHeader.split("; ")) {
|
|
53
|
+
const index = entry.indexOf("=");
|
|
54
|
+
if (index > 0)
|
|
55
|
+
jar.set(entry.slice(0, index), entry.slice(index + 1));
|
|
56
|
+
}
|
|
57
|
+
const raw = joinChunks(sharedSessionCookieName(coreProjectRef()), (name) => jar.get(name));
|
|
58
|
+
if (!raw)
|
|
59
|
+
return null;
|
|
60
|
+
try {
|
|
61
|
+
const parsed = JSON.parse(raw);
|
|
62
|
+
return parsed.access_token ?? null;
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* A client that bypasses row-level security, for the few operations that must:
|
|
70
|
+
* provisioning, cross-user admin reads, cleanup. Server-only, and never
|
|
71
|
+
* constructed from a value that reached the browser.
|
|
72
|
+
*/
|
|
73
|
+
export function serviceClient(schema) {
|
|
74
|
+
const env = typeof process === "undefined" ? undefined : process?.env;
|
|
75
|
+
const key = env?.["CORE_SUPABASE_SERVICE_ROLE_KEY"] ?? env?.["SUPABASE_SERVICE_ROLE_KEY"];
|
|
76
|
+
if (!key)
|
|
77
|
+
throw new Error("Missing CORE_SUPABASE_SERVICE_ROLE_KEY");
|
|
78
|
+
return createClient(coreUrl(), key, {
|
|
79
|
+
...(schema ? { db: { schema } } : {}),
|
|
80
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
81
|
+
});
|
|
82
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Reassemble a chunked value from any source of name/value pairs. */
|
|
2
|
+
export declare function joinChunks(key: string, read: (name: string) => string | undefined): string | null;
|
|
3
|
+
/**
|
|
4
|
+
* Copy a session that arrived from another app into this origin's storage.
|
|
5
|
+
* Must run before the Supabase client reads its storage, so `createOsClient`
|
|
6
|
+
* calls it at module scope.
|
|
7
|
+
*/
|
|
8
|
+
export declare function adoptSharedSession(projectRef: string): void;
|
|
9
|
+
/** Keep the shared cookie in step with this app's session. */
|
|
10
|
+
export declare function publishSessionChanges(client: {
|
|
11
|
+
auth: {
|
|
12
|
+
onAuthStateChange: (cb: (event: string) => void) => unknown;
|
|
13
|
+
};
|
|
14
|
+
}, projectRef: string): void;
|
|
15
|
+
/** The storage key, for server code that needs to find the cookie by name. */
|
|
16
|
+
export declare function sharedSessionCookieName(projectRef: string): string;
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One sign-in across every AutoSolutions app.
|
|
3
|
+
*
|
|
4
|
+
* Supabase keeps the session in localStorage, which browsers scope to a single
|
|
5
|
+
* origin. The hub (autosolutions.app) and the apps (design-studio.autosolutions.app,
|
|
6
|
+
* e-crm.autosolutions.app…) are different origins, so a session created in one is
|
|
7
|
+
* invisible to the others. Cookies can be scoped to a parent domain, so the
|
|
8
|
+
* session is mirrored into a cookie on .autosolutions.app that every app reads.
|
|
9
|
+
* Each app still uses its own localStorage as the working copy; this keeps them
|
|
10
|
+
* in step.
|
|
11
|
+
*
|
|
12
|
+
* Off that domain (localhost, preview hosts) nothing happens and each app
|
|
13
|
+
* signs in normally.
|
|
14
|
+
*
|
|
15
|
+
* The rule that matters: ONLY an explicit sign-out clears the shared cookie. An
|
|
16
|
+
* absent local session is not evidence of anything. The hub used to clear the
|
|
17
|
+
* cookie whenever localStorage was empty at an auth event, which fires on every
|
|
18
|
+
* cold load, so opening the hub in a fresh tab silently signed the user out of
|
|
19
|
+
* every other app.
|
|
20
|
+
*/
|
|
21
|
+
import { PARENT_DOMAIN } from "./config";
|
|
22
|
+
/** Cookies cap around 4KB each, and sessions can exceed that, so they chunk. */
|
|
23
|
+
const CHUNK = 3200;
|
|
24
|
+
const MAX_CHUNKS = 8;
|
|
25
|
+
function storageKey(projectRef) {
|
|
26
|
+
return `sb-${projectRef}-auth-token`;
|
|
27
|
+
}
|
|
28
|
+
function sharingEnabled() {
|
|
29
|
+
if (typeof window === "undefined")
|
|
30
|
+
return false;
|
|
31
|
+
const host = window.location.hostname;
|
|
32
|
+
return host === PARENT_DOMAIN || host.endsWith(`.${PARENT_DOMAIN}`);
|
|
33
|
+
}
|
|
34
|
+
/** Reassemble a chunked value from any source of name/value pairs. */
|
|
35
|
+
export function joinChunks(key, read) {
|
|
36
|
+
const parts = [];
|
|
37
|
+
for (let index = 0; index < MAX_CHUNKS; index += 1) {
|
|
38
|
+
const part = read(`${key}.${index}`);
|
|
39
|
+
if (part === undefined)
|
|
40
|
+
break;
|
|
41
|
+
parts.push(part);
|
|
42
|
+
}
|
|
43
|
+
if (parts.length === 0)
|
|
44
|
+
return null;
|
|
45
|
+
try {
|
|
46
|
+
return decodeURIComponent(parts.join(""));
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function readCookieChunks(key) {
|
|
53
|
+
const jar = new Map();
|
|
54
|
+
for (const entry of document.cookie ? document.cookie.split("; ") : []) {
|
|
55
|
+
const index = entry.indexOf("=");
|
|
56
|
+
if (index > 0)
|
|
57
|
+
jar.set(entry.slice(0, index), entry.slice(index + 1));
|
|
58
|
+
}
|
|
59
|
+
return joinChunks(key, (name) => jar.get(name));
|
|
60
|
+
}
|
|
61
|
+
function writeCookieChunks(key, value) {
|
|
62
|
+
const encoded = encodeURIComponent(value);
|
|
63
|
+
const parts = [];
|
|
64
|
+
for (let i = 0; i < encoded.length; i += CHUNK)
|
|
65
|
+
parts.push(encoded.slice(i, i + CHUNK));
|
|
66
|
+
if (parts.length > MAX_CHUNKS)
|
|
67
|
+
return; // implausibly large: leave the cookie alone
|
|
68
|
+
const attributes = `Domain=.${PARENT_DOMAIN}; Path=/; Max-Age=${60 * 60 * 24 * 30}; SameSite=Lax; Secure`;
|
|
69
|
+
parts.forEach((part, index) => {
|
|
70
|
+
document.cookie = `${key}.${index}=${part}; ${attributes}`;
|
|
71
|
+
});
|
|
72
|
+
// Clear leftovers from a previously longer session.
|
|
73
|
+
for (let index = parts.length; index < MAX_CHUNKS; index += 1) {
|
|
74
|
+
document.cookie = `${key}.${index}=; Domain=.${PARENT_DOMAIN}; Path=/; Max-Age=0; SameSite=Lax; Secure`;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function clearCookieChunks(key) {
|
|
78
|
+
for (let index = 0; index < MAX_CHUNKS; index += 1) {
|
|
79
|
+
document.cookie = `${key}.${index}=; Domain=.${PARENT_DOMAIN}; Path=/; Max-Age=0; SameSite=Lax; Secure`;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Copy a session that arrived from another app into this origin's storage.
|
|
84
|
+
* Must run before the Supabase client reads its storage, so `createOsClient`
|
|
85
|
+
* calls it at module scope.
|
|
86
|
+
*/
|
|
87
|
+
export function adoptSharedSession(projectRef) {
|
|
88
|
+
if (!sharingEnabled())
|
|
89
|
+
return;
|
|
90
|
+
const key = storageKey(projectRef);
|
|
91
|
+
try {
|
|
92
|
+
const local = window.localStorage.getItem(key);
|
|
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);
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
// Storage blocked (private window, blocked cookies): fall back to a normal
|
|
101
|
+
// per-app sign-in rather than breaking the page.
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** Keep the shared cookie in step with this app's session. */
|
|
105
|
+
export function publishSessionChanges(client, projectRef) {
|
|
106
|
+
if (!sharingEnabled())
|
|
107
|
+
return;
|
|
108
|
+
const key = storageKey(projectRef);
|
|
109
|
+
try {
|
|
110
|
+
client.auth.onAuthStateChange((event) => {
|
|
111
|
+
if (event === "SIGNED_OUT") {
|
|
112
|
+
clearCookieChunks(key);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const local = window.localStorage.getItem(key);
|
|
116
|
+
if (local)
|
|
117
|
+
writeCookieChunks(key, local);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
// Never let session mirroring break authentication itself.
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** The storage key, for server code that needs to find the cookie by name. */
|
|
125
|
+
export function sharedSessionCookieName(projectRef) {
|
|
126
|
+
return storageKey(projectRef);
|
|
127
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "autosolutions-os",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "One sign-in, one company switcher, one app grid. What every AutoSolutions app imports instead of copying.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "UNLICENSED",
|
|
7
|
+
"repository": { "type": "git", "url": "https://github.com/autosolutionsai-didac/autosolutions-core", "directory": "packages/os" },
|
|
8
|
+
"sideEffects": ["*.css"],
|
|
9
|
+
"exports": {
|
|
10
|
+
".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
|
|
11
|
+
"./server": { "types": "./dist/server.d.ts", "import": "./dist/server.js" },
|
|
12
|
+
"./chrome.css": "./dist/chrome.css"
|
|
13
|
+
},
|
|
14
|
+
"files": ["dist"],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "tsc -p tsconfig.build.json && cp src/chrome.css dist/chrome.css",
|
|
17
|
+
"typecheck": "tsc --noEmit"
|
|
18
|
+
},
|
|
19
|
+
"peerDependencies": {
|
|
20
|
+
"@supabase/supabase-js": ">=2.40.0",
|
|
21
|
+
"react": ">=18"
|
|
22
|
+
},
|
|
23
|
+
"peerDependenciesMeta": {
|
|
24
|
+
"react": { "optional": true }
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@types/react": "^19.2.0",
|
|
28
|
+
"typescript": "^5.8.3"
|
|
29
|
+
}
|
|
30
|
+
}
|