autosolutions-os 0.2.5 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,408 @@
1
+ /**
2
+ * Sign in with AutoSolutions, for an app that keeps its own Supabase project.
3
+ *
4
+ * Four apps keep their own project, their own people and their own roles: Key
5
+ * Accounts, Asset Portal, Candidate Hub and Ops Hub. Each project adds the
6
+ * core as a custom OpenID Connect provider, `custom:autosolutions`; the core's
7
+ * OAuth 2.1 server sends people to the Hub's consent page
8
+ * (https://autosolutions.app/oauth/consent), and the app's project links them
9
+ * to their existing account by verified email, so their user id there does not
10
+ * change. See docs/CONTRACT.md, "Federated: own project, one sign-in".
11
+ *
12
+ * What this module does in the app's browser:
13
+ *
14
+ * 1. `signInWithAutoSolutions` starts the flow: on a click, or by itself on the
15
+ * sign-in page (`automatic`), only on an autosolutions.app address, only
16
+ * when the core's shared cookie shows a live session, at most once a
17
+ * minute, and never after a sign-out here, a "no access" answer or an
18
+ * attempt that did not come back, until the person clicks.
19
+ * 2. `followCoreSession` marks the session that comes back as one that came
20
+ * through AutoSolutions (`as-sso`, the core user id) and, on an
21
+ * autosolutions.app address, keeps that session in step with the core: on
22
+ * load, on focus, when the tab comes back into view and once a minute it
23
+ * reads the core's cookies on .autosolutions.app, and
24
+ * - the sign-out note is there and no live core session is shared: it signs
25
+ * out here (local scope), so the app shows its sign-in page;
26
+ * - the shared session is another person's: it signs out here, and the
27
+ * sign-in page starts again;
28
+ * - the same person, or no cookie and no note (blocked cookies): nothing.
29
+ * A session that did not come through AutoSolutions (Google, a password, an
30
+ * email link, a partner or a candidate) is never touched.
31
+ * 3. `signOutWithAutoSolutions` signs out here (local scope) and then at the
32
+ * Hub's /sign-out, which signs the person out of the core, so the Hub and
33
+ * every other app follow; `signOutEverywhereUrl` is that address.
34
+ * 4. `coreIdentity` reads the person's AutoSolutions identity from the app's
35
+ * own user: the core user id (`sub`) and the email the core vouched for.
36
+ *
37
+ * Every part is best effort: storage or cookie errors never stop a sign-in or
38
+ * a sign-out. Nothing here imports supabase-js or React; the functions take
39
+ * the app's own client.
40
+ */
41
+ import { coreProjectRef, HUB_URL, PARENT_DOMAIN } from "./config.js";
42
+ import { joinChunks, parseCopy, parseSignedOutNote, sharedSessionCookieName, signedOutCookieName, signedOutCopy, } from "./session.js";
43
+ /** The provider identifier every federated project registers. */
44
+ export const AUTOSOLUTIONS_PROVIDER = "custom:autosolutions";
45
+ /** The Hub's sign-out page. */
46
+ export const SIGN_OUT_PATH = "/sign-out";
47
+ /** localStorage keys on the app's own origin. */
48
+ const PENDING = "as-sso-pending";
49
+ const MARKER = "as-sso";
50
+ const HOLD = "as-sso-hold";
51
+ const AUTO_AT = "as-sso-auto-at";
52
+ /** A started sign-in that has not come back within this long has been abandoned. */
53
+ const PENDING_FOR = 10 * 60_000;
54
+ /** The automatic start runs at most this often. */
55
+ const AUTO_EVERY = 60_000;
56
+ /** The server's clock and the browser's may differ by this much. */
57
+ const CLOCK_SKEW = 5 * 60_000;
58
+ /** followCoreSession looks this often while the page is open. */
59
+ const FOLLOW_EVERY = 60_000;
60
+ const text = (value) => (typeof value === "string" && value.length > 0 ? value : null);
61
+ /**
62
+ * The `custom:autosolutions` identity of a user of the app's project, or null
63
+ * when the person has never come in through AutoSolutions.
64
+ */
65
+ export function coreIdentity(user) {
66
+ const identities = user && Array.isArray(user.identities) ? user.identities : [];
67
+ const identity = identities.find((candidate) => candidate?.provider === AUTOSOLUTIONS_PROVIDER);
68
+ if (!identity)
69
+ return null;
70
+ const data = identity.identity_data && typeof identity.identity_data === "object" ? identity.identity_data : {};
71
+ const sub = text(data["sub"]) ?? text(data["provider_id"]) ?? text(identity.id);
72
+ if (!sub)
73
+ return null;
74
+ const verified = data["email_verified"];
75
+ return {
76
+ sub,
77
+ email: text(data["email"]) ?? text(identity.email),
78
+ emailVerified: verified === true || verified === "true" ? true : verified === false || verified === "false" ? false : null,
79
+ identityId: text(identity.identity_id),
80
+ lastSignInAt: text(identity.last_sign_in_at),
81
+ };
82
+ }
83
+ function browser() {
84
+ return typeof window !== "undefined" && typeof document !== "undefined";
85
+ }
86
+ function onParentDomain() {
87
+ if (!browser())
88
+ return false;
89
+ const host = window.location.hostname;
90
+ return host === PARENT_DOMAIN || host.endsWith(`.${PARENT_DOMAIN}`);
91
+ }
92
+ function read(key) {
93
+ try {
94
+ return window.localStorage.getItem(key);
95
+ }
96
+ catch {
97
+ return null;
98
+ }
99
+ }
100
+ function write(key, value) {
101
+ try {
102
+ window.localStorage.setItem(key, value);
103
+ }
104
+ catch {
105
+ // Storage blocked: the sign-in still works, it is just not followed.
106
+ }
107
+ }
108
+ function remove(key) {
109
+ try {
110
+ window.localStorage.removeItem(key);
111
+ }
112
+ catch {
113
+ // Nothing to remove.
114
+ }
115
+ }
116
+ /** A sign-in started here that has not come back yet, or null. A stale one is forgotten. */
117
+ function pending() {
118
+ const raw = read(PENDING);
119
+ if (raw === null)
120
+ return null;
121
+ const at = Number(raw);
122
+ if (!Number.isFinite(at) || Date.now() - at > PENDING_FOR || at - Date.now() > CLOCK_SKEW) {
123
+ remove(PENDING);
124
+ return null;
125
+ }
126
+ return at;
127
+ }
128
+ function readCoreCookies() {
129
+ try {
130
+ const ref = coreProjectRef();
131
+ const jar = new Map();
132
+ for (const entry of document.cookie ? document.cookie.split("; ") : []) {
133
+ const index = entry.indexOf("=");
134
+ if (index > 0)
135
+ jar.set(entry.slice(0, index), entry.slice(index + 1));
136
+ }
137
+ const note = parseSignedOutNote(jar.get(signedOutCookieName(ref)));
138
+ const key = sharedSessionCookieName(ref);
139
+ if (!jar.has(`${key}.0`))
140
+ return { note: note !== null, shared: "absent", userId: null };
141
+ const copy = parseCopy(joinChunks(key, (name) => jar.get(name)));
142
+ // Another app may be halfway through writing its chunks: that is not "no session".
143
+ if (!copy)
144
+ return { note: note !== null, shared: "unreadable", userId: null };
145
+ return { note: note !== null, shared: signedOutCopy(copy, note) ? "signed-out" : "live", userId: copy.userId };
146
+ }
147
+ catch {
148
+ return null;
149
+ }
150
+ }
151
+ /** The sign-in page has just come back from a provider: let supabase-js finish with it. */
152
+ function returning() {
153
+ try {
154
+ const search = new URLSearchParams(window.location.search ?? "");
155
+ const hash = new URLSearchParams(String(window.location.hash ?? "").replace(/^#/, ""));
156
+ return ["code", "error", "error_code", "error_description"].some((name) => search.has(name))
157
+ || ["access_token", "error", "error_code", "error_description"].some((name) => hash.has(name));
158
+ }
159
+ catch {
160
+ return false;
161
+ }
162
+ }
163
+ /**
164
+ * Start "Sign in with AutoSolutions". On a click, always; with `automatic`,
165
+ * only when the rules above allow it, so a sign-in page can call it as soon as
166
+ * it knows there is no session, and never loops.
167
+ */
168
+ export async function signInWithAutoSolutions(client, options) {
169
+ if (options.automatic) {
170
+ if (!onParentDomain())
171
+ return { started: false, reason: "off-domain" };
172
+ if (returning())
173
+ return { started: false, reason: "returning" };
174
+ if (read(HOLD) !== null)
175
+ return { started: false, reason: "held" };
176
+ if (pending() !== null) {
177
+ // The last attempt went to the Hub and did not come back signed in (it
178
+ // was cancelled, refused, or left): wait for a click.
179
+ holdAutomaticSignIn();
180
+ remove(PENDING);
181
+ return { started: false, reason: "held" };
182
+ }
183
+ const last = Number(read(AUTO_AT));
184
+ if (Number.isFinite(last) && last > 0 && Date.now() - last < AUTO_EVERY)
185
+ return { started: false, reason: "too-soon" };
186
+ if (readCoreCookies()?.shared !== "live")
187
+ return { started: false, reason: "no-core-session" };
188
+ write(AUTO_AT, String(Date.now()));
189
+ }
190
+ else {
191
+ remove(HOLD);
192
+ }
193
+ write(PENDING, String(Date.now()));
194
+ try {
195
+ const { data, error } = await client.auth.signInWithOAuth({
196
+ provider: AUTOSOLUTIONS_PROVIDER,
197
+ options: {
198
+ redirectTo: options.redirectTo,
199
+ ...(options.skipBrowserRedirect ? { skipBrowserRedirect: true } : {}),
200
+ ...(options.scopes ? { scopes: options.scopes } : {}),
201
+ },
202
+ });
203
+ if (error) {
204
+ remove(PENDING);
205
+ return { started: false, reason: "error", error };
206
+ }
207
+ return { started: true, url: text(data?.url) };
208
+ }
209
+ catch (error) {
210
+ remove(PENDING);
211
+ return { started: false, reason: "error", error };
212
+ }
213
+ }
214
+ /**
215
+ * Keep the automatic start from running until the person clicks: after a
216
+ * "no access" answer from the app's own rules, and before a sign-out here
217
+ * (`signOutWithAutoSolutions` does it).
218
+ */
219
+ export function holdAutomaticSignIn() {
220
+ if (browser())
221
+ write(HOLD, String(Date.now()));
222
+ }
223
+ /**
224
+ * Whether this browser's session in the app came through AutoSolutions. With
225
+ * `user`, also that it is that person's (their AutoSolutions identity is the
226
+ * one the marker names). Needs `followCoreSession`, which sets the marker.
227
+ */
228
+ export function cameThroughAutoSolutions(user) {
229
+ if (!browser())
230
+ return false;
231
+ const marker = read(MARKER);
232
+ if (marker === null)
233
+ return false;
234
+ if (user === undefined)
235
+ return true;
236
+ return coreIdentity(user)?.sub === marker;
237
+ }
238
+ /** Record how a session came: through AutoSolutions only when a sign-in started here came back with that identity. */
239
+ function noteAuthEvent(event, session) {
240
+ try {
241
+ if (event === "SIGNED_OUT") {
242
+ remove(MARKER);
243
+ return;
244
+ }
245
+ const user = session?.user;
246
+ if (!user)
247
+ return;
248
+ const identity = coreIdentity(user);
249
+ const startedAt = pending();
250
+ if (startedAt !== null && identity) {
251
+ const last = identity.lastSignInAt ? Date.parse(identity.lastSignInAt) : Number.NaN;
252
+ // A person with the identity already linked who signs in some other way
253
+ // after an abandoned attempt: the identity's last sign-in is the old one.
254
+ if (Number.isNaN(last) || last >= startedAt - CLOCK_SKEW) {
255
+ write(MARKER, identity.sub);
256
+ remove(PENDING);
257
+ remove(HOLD);
258
+ return;
259
+ }
260
+ }
261
+ const marker = read(MARKER);
262
+ if (marker !== null && identity?.sub !== marker)
263
+ remove(MARKER);
264
+ }
265
+ catch {
266
+ // Never let the marker break authentication.
267
+ }
268
+ }
269
+ /**
270
+ * Install once, at the app's root, on every address: it records which
271
+ * sessions came through AutoSolutions everywhere, and on an autosolutions.app
272
+ * address keeps those sessions in step with the core (see the top of this
273
+ * file). Returns a function that stops it.
274
+ */
275
+ export function followCoreSession(client, options = {}) {
276
+ if (!browser())
277
+ return () => { };
278
+ let stopped = false;
279
+ let signingOut = false;
280
+ let user = undefined;
281
+ let unsubscribe = () => { };
282
+ const listeners = [];
283
+ let timer;
284
+ const check = () => {
285
+ if (stopped || signingOut || !onParentDomain())
286
+ return;
287
+ try {
288
+ if (!user)
289
+ return;
290
+ const marker = read(MARKER);
291
+ if (marker === null || coreIdentity(user)?.sub !== marker)
292
+ return;
293
+ const core = readCoreCookies();
294
+ if (!core)
295
+ return;
296
+ let reason = null;
297
+ if (core.note && (core.shared === "absent" || core.shared === "signed-out"))
298
+ reason = "core-signed-out";
299
+ else if (core.shared === "live" && core.userId !== null && core.userId !== marker)
300
+ reason = "different-person";
301
+ if (reason === null)
302
+ return;
303
+ const why = reason;
304
+ signingOut = true;
305
+ remove(MARKER);
306
+ const done = () => {
307
+ signingOut = false;
308
+ try {
309
+ options.onSignedOut?.(why);
310
+ }
311
+ catch {
312
+ // The app's handler is its own business.
313
+ }
314
+ };
315
+ Promise.resolve()
316
+ .then(() => client.auth.signOut({ scope: "local" }))
317
+ .then(done, done);
318
+ }
319
+ catch {
320
+ // Never let following the core break the page.
321
+ }
322
+ };
323
+ try {
324
+ const subscription = client.auth.onAuthStateChange((event, session) => {
325
+ noteAuthEvent(event, session);
326
+ user = event === "SIGNED_OUT" ? null : session?.user ?? null;
327
+ // Outside the callback: supabase-js holds its lock while it runs, and a
328
+ // sign-out from inside it would wait for itself.
329
+ if (user)
330
+ setTimeout(check, 0);
331
+ });
332
+ unsubscribe = () => subscription?.data?.subscription?.unsubscribe?.();
333
+ }
334
+ catch {
335
+ // No auth events: nothing can be followed.
336
+ }
337
+ if (onParentDomain()) {
338
+ const wake = () => {
339
+ if (document.visibilityState === "hidden")
340
+ return;
341
+ check();
342
+ };
343
+ listeners.push([document, "visibilitychange", wake], [window, "focus", wake], [window, "pageshow", wake]);
344
+ for (const [target, type, listener] of listeners) {
345
+ try {
346
+ target.addEventListener(type, listener);
347
+ }
348
+ catch {
349
+ // A part that cannot be installed leaves the others working.
350
+ }
351
+ }
352
+ timer = setInterval(check, options.intervalMs ?? FOLLOW_EVERY);
353
+ }
354
+ return () => {
355
+ stopped = true;
356
+ if (timer !== undefined)
357
+ clearInterval(timer);
358
+ for (const [target, type, listener] of listeners) {
359
+ try {
360
+ target.removeEventListener(type, listener);
361
+ }
362
+ catch {
363
+ // Already gone.
364
+ }
365
+ }
366
+ try {
367
+ unsubscribe();
368
+ }
369
+ catch {
370
+ // Already gone.
371
+ }
372
+ };
373
+ }
374
+ /**
375
+ * The Hub's sign-out page, which signs the person out of the core (so the Hub
376
+ * and every app follow) and then returns to `returnTo`, when the Hub allows
377
+ * that address. A relative `returnTo` is taken from this page's address.
378
+ */
379
+ export function signOutEverywhereUrl(returnTo) {
380
+ let target = returnTo;
381
+ try {
382
+ target = browser() ? new URL(returnTo, window.location.href).toString() : new URL(returnTo).toString();
383
+ }
384
+ catch {
385
+ // Not a URL: the Hub refuses it and stays on its own page.
386
+ }
387
+ return `${HUB_URL}${SIGN_OUT_PATH}?return_to=${encodeURIComponent(target)}`;
388
+ }
389
+ /**
390
+ * The app's sign-out for a session that came through AutoSolutions: hold the
391
+ * automatic start, sign out here (local scope), then go through the Hub's
392
+ * sign-out back to `returnTo` (the app's sign-in page). Returns false, and does
393
+ * nothing, for any other session: the app then signs out as it always has.
394
+ */
395
+ export async function signOutWithAutoSolutions(client, options) {
396
+ if (!cameThroughAutoSolutions(options.user))
397
+ return false;
398
+ holdAutomaticSignIn();
399
+ try {
400
+ await client.auth.signOut({ scope: "local" });
401
+ }
402
+ catch {
403
+ // Local sign-out removes the session whatever the server says.
404
+ }
405
+ remove(MARKER);
406
+ window.location.assign(signOutEverywhereUrl(options.returnTo));
407
+ return true;
408
+ }
package/dist/frame.d.ts CHANGED
@@ -2,10 +2,11 @@
2
2
  * OsWorkspaceFrame: the design system's WorkspaceFrame, wired to the core.
3
3
  *
4
4
  * Every app on the core renders this around its pages. It draws the same rail,
5
- * the same 53-tool menu and the same footer in every app, marks this app's own
6
- * tools live, links the others through the catalogue, and puts the acting
7
- * company's mark on the top bar's plate (its name, when it has no artwork or
8
- * the artwork fails to load), which opens the company menu.
5
+ * the same menu map (Cliff's, 0.3.0), the same Hub panel and the same footer
6
+ * in every app, marks this app's own tools live, links the others through
7
+ * the catalogue (or, for a tool with no app, to its page in the Hub), and
8
+ * puts the acting company's mark on the top bar's plate (its name, when it
9
+ * has no artwork or the artwork fails to load), which opens the company menu.
9
10
  *
10
11
  * It knows nothing about routers. Hand it the current location (pathname plus
11
12
  * query) and an `onNavigate(href)` that pushes an in-app path. Rows for other
@@ -52,7 +53,12 @@ export type OsWorkspaceFrameProps = {
52
53
  appKey: string;
53
54
  /** This app's own tools, with their routes: these rows are live whatever the map says. */
54
55
  tools?: OsAppTool[];
55
- /** The Hub function's menu. The Hub passes its own rows; other apps leave it out and the rail's Hub goes to the Hub. */
56
+ /**
57
+ * The Hub function's menu. Default: the design's Hub panel (OS_HUB_MENU,
58
+ * 0.3.0), every row a link into the Hub, so the rail's Hub opens it in any
59
+ * app. The Hub passes its own rows, to lock what it gates. `[]` for no Hub
60
+ * menu: the rail's Hub then goes to the Hub, as before 0.3.0.
61
+ */
56
62
  hubItems?: OsHubSection[];
57
63
  /** Where the app is: pathname plus query. */
58
64
  location: string;
@@ -87,13 +93,13 @@ export type OsWorkspaceFrameProps = {
87
93
  actions?: ReactNode;
88
94
  /** How the plate switches company. Default "os". */
89
95
  companySwitch?: OsCompanySwitch;
90
- /** Rendered in the panel under the open tool's tabs, in the panel's padding (a session list, say). */
96
+ /** Rendered in the tool's panel under its tabs, in the panel's padding (a session list, say). */
91
97
  panelFooter?: ReactNode;
92
98
  /** Sign out, in whatever order the app needs (clear caches first, and so on). */
93
99
  onSignOut?: () => void;
94
100
  /** This app's settings route. Default: the Hub's settings. */
95
101
  settingsPath?: string;
96
- /** This app's landing. In the Hub it is where Back to hub lands. */
102
+ /** This app's landing. In the Hub it is where the rail's Hub lands from Admin or Settings. */
97
103
  homePath?: string;
98
104
  /** Show Admin in the footer. Default: asked of the core with my_admin_scope(). */
99
105
  admin?: boolean;
package/dist/frame.js CHANGED
@@ -3,10 +3,11 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
3
3
  * OsWorkspaceFrame: the design system's WorkspaceFrame, wired to the core.
4
4
  *
5
5
  * Every app on the core renders this around its pages. It draws the same rail,
6
- * the same 53-tool menu and the same footer in every app, marks this app's own
7
- * tools live, links the others through the catalogue, and puts the acting
8
- * company's mark on the top bar's plate (its name, when it has no artwork or
9
- * the artwork fails to load), which opens the company menu.
6
+ * the same menu map (Cliff's, 0.3.0), the same Hub panel and the same footer
7
+ * in every app, marks this app's own tools live, links the others through
8
+ * the catalogue (or, for a tool with no app, to its page in the Hub), and
9
+ * puts the acting company's mark on the top bar's plate (its name, when it
10
+ * has no artwork or the artwork fails to load), which opens the company menu.
10
11
  *
11
12
  * It knows nothing about routers. Hand it the current location (pathname plus
12
13
  * query) and an `onNavigate(href)` that pushes an in-app path. Rows for other