cursedauth 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/LICENSE +21 -0
- package/README.md +87 -0
- package/dist/account/AccountMenu.d.ts +153 -0
- package/dist/account/AccountMenu.d.ts.map +1 -0
- package/dist/account/AccountMenu.js +388 -0
- package/dist/account/AccountMenu.js.map +1 -0
- package/dist/account/AccountNotice.d.ts +35 -0
- package/dist/account/AccountNotice.d.ts.map +1 -0
- package/dist/account/AccountNotice.js +133 -0
- package/dist/account/AccountNotice.js.map +1 -0
- package/dist/account/accountNotice.state.d.ts +20 -0
- package/dist/account/accountNotice.state.d.ts.map +1 -0
- package/dist/account/accountNotice.state.js +55 -0
- package/dist/account/accountNotice.state.js.map +1 -0
- package/dist/account/avatar.d.ts +37 -0
- package/dist/account/avatar.d.ts.map +1 -0
- package/dist/account/avatar.js +47 -0
- package/dist/account/avatar.js.map +1 -0
- package/dist/accountSlot.client.d.ts +113 -0
- package/dist/accountSlot.client.d.ts.map +1 -0
- package/dist/accountSlot.client.js +330 -0
- package/dist/accountSlot.client.js.map +1 -0
- package/dist/accountSlots.d.ts +192 -0
- package/dist/accountSlots.d.ts.map +1 -0
- package/dist/accountSlots.js +274 -0
- package/dist/accountSlots.js.map +1 -0
- package/dist/auth.d.ts +167 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +310 -0
- package/dist/auth.js.map +1 -0
- package/dist/auth.server.d.ts +35 -0
- package/dist/auth.server.d.ts.map +1 -0
- package/dist/auth.server.js +67 -0
- package/dist/auth.server.js.map +1 -0
- package/dist/clientDescription.d.ts +186 -0
- package/dist/clientDescription.d.ts.map +1 -0
- package/dist/clientDescription.js +278 -0
- package/dist/clientDescription.js.map +1 -0
- package/dist/constantTime.d.ts +35 -0
- package/dist/constantTime.d.ts.map +1 -0
- package/dist/constantTime.js +46 -0
- package/dist/constantTime.js.map +1 -0
- package/dist/contentCensus.d.ts +59 -0
- package/dist/contentCensus.d.ts.map +1 -0
- package/dist/contentCensus.js +55 -0
- package/dist/contentCensus.js.map +1 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +24 -0
- package/dist/index.js.map +1 -0
- package/dist/mountGatedApp.d.ts +128 -0
- package/dist/mountGatedApp.d.ts.map +1 -0
- package/dist/mountGatedApp.js +107 -0
- package/dist/mountGatedApp.js.map +1 -0
- package/dist/runtimeMode.d.ts +28 -0
- package/dist/runtimeMode.d.ts.map +1 -0
- package/dist/runtimeMode.js +37 -0
- package/dist/runtimeMode.js.map +1 -0
- package/dist/secureRequest.d.ts +22 -0
- package/dist/secureRequest.d.ts.map +1 -0
- package/dist/secureRequest.js +27 -0
- package/dist/secureRequest.js.map +1 -0
- package/dist/sso.d.ts +373 -0
- package/dist/sso.d.ts.map +1 -0
- package/dist/sso.js +420 -0
- package/dist/sso.js.map +1 -0
- package/dist/ssoAutoSignIn.d.ts +272 -0
- package/dist/ssoAutoSignIn.d.ts.map +1 -0
- package/dist/ssoAutoSignIn.js +431 -0
- package/dist/ssoAutoSignIn.js.map +1 -0
- package/dist/ssoConsumer.server.d.ts +295 -0
- package/dist/ssoConsumer.server.d.ts.map +1 -0
- package/dist/ssoConsumer.server.js +972 -0
- package/dist/ssoConsumer.server.js.map +1 -0
- package/dist/stageIdentity.d.ts +72 -0
- package/dist/stageIdentity.d.ts.map +1 -0
- package/dist/stageIdentity.js +74 -0
- package/dist/stageIdentity.js.map +1 -0
- package/dist/ui/popover.d.ts +190 -0
- package/dist/ui/popover.d.ts.map +1 -0
- package/dist/ui/popover.js +351 -0
- package/dist/ui/popover.js.map +1 -0
- package/dist/userSessions.d.ts +205 -0
- package/dist/userSessions.d.ts.map +1 -0
- package/dist/userSessions.js +419 -0
- package/dist/userSessions.js.map +1 -0
- package/package.json +115 -0
- package/src/account/AccountMenu.tsx +729 -0
- package/src/account/AccountNotice.tsx +223 -0
- package/src/account/accountNotice.state.ts +66 -0
- package/src/account/avatar.ts +50 -0
- package/src/accountSlot.client.ts +362 -0
- package/src/accountSlots.ts +305 -0
- package/src/auth.server.ts +89 -0
- package/src/auth.ts +515 -0
- package/src/clientDescription.ts +366 -0
- package/src/constantTime.ts +45 -0
- package/src/contentCensus.ts +106 -0
- package/src/index.ts +58 -0
- package/src/mountGatedApp.ts +240 -0
- package/src/runtimeMode.ts +37 -0
- package/src/secureRequest.ts +25 -0
- package/src/sso.ts +767 -0
- package/src/ssoAutoSignIn.ts +544 -0
- package/src/ssoConsumer.server.ts +1260 -0
- package/src/stageIdentity.ts +76 -0
- package/src/ui/popover.ts +390 -0
- package/src/userSessions.ts +678 -0
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// ── The satellite auth boundary (server half) ────────────────────────────────────────
|
|
2
|
+
//
|
|
3
|
+
// The client half — and the full "what replaces this when real auth lands" table — is in
|
|
4
|
+
// `auth.ts`. This file is separate for one reason: the server must not pull React into
|
|
5
|
+
// its bundle. Change them together; they are one boundary.
|
|
6
|
+
import type { Context, MiddlewareHandler, Next } from "hono";
|
|
7
|
+
import { isProductionRuntime } from "./runtimeMode";
|
|
8
|
+
|
|
9
|
+
export interface SessionClaims {
|
|
10
|
+
userId: string;
|
|
11
|
+
tenantId: string;
|
|
12
|
+
scopes: string[];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Hono middleware. Rejects with 401 unless a valid session is present. */
|
|
16
|
+
export type RequireSession = MiddlewareHandler;
|
|
17
|
+
|
|
18
|
+
/** Verifies a bearer token. Rejects (or throws) when the token is not a live session. */
|
|
19
|
+
export type SessionVerifier = (token: string) => Promise<SessionClaims>;
|
|
20
|
+
|
|
21
|
+
/** Context key the middleware stores verified claims under. */
|
|
22
|
+
export const SESSION_CLAIMS_KEY = "satelliteSession";
|
|
23
|
+
|
|
24
|
+
/** Claims for the current request, or null on an unauthenticated one. */
|
|
25
|
+
export function getSessionClaims(c: Context): SessionClaims | null {
|
|
26
|
+
return (c.get(SESSION_CLAIMS_KEY) as SessionClaims | undefined) ?? null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const unauthorized = (c: Context) =>
|
|
30
|
+
c.json({ error: "unauthorized" }, 401, {
|
|
31
|
+
"www-authenticate": 'Bearer realm="satellite"',
|
|
32
|
+
"cache-control": "no-store",
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
/** Extracts a bearer token from an Authorization header, or null. */
|
|
36
|
+
export function bearerToken(header: string | undefined | null): string | null {
|
|
37
|
+
if (!header) return null;
|
|
38
|
+
const match = /^Bearer[ \t]+(\S+)$/i.exec(header.trim());
|
|
39
|
+
return match ? match[1] : null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The real gate: 401 unless the request carries a bearer token `verify` accepts. A
|
|
44
|
+
* verifier that throws is treated as a rejection — a broken verifier must fail closed,
|
|
45
|
+
* never open.
|
|
46
|
+
*/
|
|
47
|
+
export function createRequireSession(verify: SessionVerifier): RequireSession {
|
|
48
|
+
return async (c: Context, next: Next) => {
|
|
49
|
+
const token = bearerToken(c.req.header("authorization"));
|
|
50
|
+
if (!token) return unauthorized(c);
|
|
51
|
+
let claims: SessionClaims;
|
|
52
|
+
try {
|
|
53
|
+
claims = await verify(token);
|
|
54
|
+
} catch {
|
|
55
|
+
return unauthorized(c);
|
|
56
|
+
}
|
|
57
|
+
if (!claims?.userId) return unauthorized(c);
|
|
58
|
+
c.set(SESSION_CLAIMS_KEY, claims);
|
|
59
|
+
await next();
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export const DEV_REQUIRE_SESSION_IN_PRODUCTION =
|
|
64
|
+
"createDevRequireSession() was reached in a production build. " +
|
|
65
|
+
"A satellite that needs auth must not ship the dev pass-through — wire the real " +
|
|
66
|
+
"verifier (createRequireSession) first.";
|
|
67
|
+
|
|
68
|
+
/** Claims the dev pass-through injects, so downstream code always sees a session. */
|
|
69
|
+
export const DEV_SESSION_CLAIMS: SessionClaims = {
|
|
70
|
+
userId: "dev-user",
|
|
71
|
+
tenantId: "dev",
|
|
72
|
+
scopes: ["*"],
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Development pass-through: every request is allowed and carries {@link DEV_SESSION_CLAIMS}.
|
|
77
|
+
*
|
|
78
|
+
* It throws AT CONSTRUCTION in production — i.e. at server boot, loudly, rather than
|
|
79
|
+
* silently serving a private app to the internet. The satellite it guards (`roms`) is
|
|
80
|
+
* additionally kept undeployable by a descriptive-only deploy block; this is the second
|
|
81
|
+
* lock on the same door.
|
|
82
|
+
*/
|
|
83
|
+
export function createDevRequireSession(): RequireSession {
|
|
84
|
+
if (isProductionRuntime()) throw new Error(DEV_REQUIRE_SESSION_IN_PRODUCTION);
|
|
85
|
+
return async (c: Context, next: Next) => {
|
|
86
|
+
c.set(SESSION_CLAIMS_KEY, DEV_SESSION_CLAIMS);
|
|
87
|
+
await next();
|
|
88
|
+
};
|
|
89
|
+
}
|
package/src/auth.ts
ADDED
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
// ── The satellite auth boundary (client half) ────────────────────────────────────────
|
|
2
|
+
//
|
|
3
|
+
// This file and its server twin (`auth.server.ts`) are the ONLY places that know how a
|
|
4
|
+
// satellite authenticates. Application code codes against `useSatelliteAuth()` and never
|
|
5
|
+
// learns which adapter is underneath — so adopting real auth is an adapter swap, not an
|
|
6
|
+
// app rewrite.
|
|
7
|
+
//
|
|
8
|
+
// FORWARD PATH — what replaces each member when real auth is adopted (cc has shipped all
|
|
9
|
+
// of this; see the repo CLAUDE.md and the build spec §12 for the full flip procedure):
|
|
10
|
+
//
|
|
11
|
+
// client adapter `createCcSessionStore` + `CCSessionProvider` + `createAccountClient`,
|
|
12
|
+
// all exported from `cursedbelt/react`. The session store MUST live at
|
|
13
|
+
// module scope and be read through `token()` per request — a token held
|
|
14
|
+
// in React state hands the client a stale closure (a documented cc
|
|
15
|
+
// footgun). That is why `token()` is a function on this interface and
|
|
16
|
+
// not a string field.
|
|
17
|
+
// server middleware cc's guard mixin routes: pass the satellite's EXISTING Hono app to
|
|
18
|
+
// `composeServer({ app, ctx, services })` from
|
|
19
|
+
// `cursedbelt/src/server/mixins`, with `createLocalGuardServices`
|
|
20
|
+
// from `cursedbelt/src/server/runtime/localHost.ts`.
|
|
21
|
+
// user provisioning INVITATION-GATED SIGNUP ONLY — `AccountService.inviteMember` →
|
|
22
|
+
// `POST /api/guard/invitations/accept`, invite token in the
|
|
23
|
+
// `x-cc-invitation` header. Never enable open signup.
|
|
24
|
+
// password reset `POST /api/guard/accounts/:id/password`
|
|
25
|
+
//
|
|
26
|
+
// At that point `@node-rs/argon2` becomes a real dependency, and the app's identity lives
|
|
27
|
+
// in its OWN `<dataRoot>/registry.db` — never the machine-wide `cc-registry.db`.
|
|
28
|
+
//
|
|
29
|
+
// FORBIDDEN, now and then: `cursedbelt/react`'s `AuthGate` and `sessionAuth`, and
|
|
30
|
+
// app-generator's `auth-login*.ts` / `bin/invite.ts`. Those are cc's legacy scaffold,
|
|
31
|
+
// disclosed debt, slated for deletion — never extend them.
|
|
32
|
+
//
|
|
33
|
+
// NOTE: `fractals` has no auth surface of any kind and must never import this module.
|
|
34
|
+
// The boundary exists for `roms`, the private satellite.
|
|
35
|
+
import {
|
|
36
|
+
createContext,
|
|
37
|
+
createElement,
|
|
38
|
+
useCallback,
|
|
39
|
+
useContext,
|
|
40
|
+
useEffect,
|
|
41
|
+
useMemo,
|
|
42
|
+
useRef,
|
|
43
|
+
useState,
|
|
44
|
+
} from "react";
|
|
45
|
+
import { isProductionRuntime } from "./runtimeMode";
|
|
46
|
+
import {
|
|
47
|
+
clearSsoAutoState,
|
|
48
|
+
decideSsoAutoSignIn,
|
|
49
|
+
lastSsoAttemptAt,
|
|
50
|
+
ssoErrorFromLocation,
|
|
51
|
+
ssoSignedOutHere,
|
|
52
|
+
startSsoSignIn,
|
|
53
|
+
startSsoSignOut,
|
|
54
|
+
} from "./ssoAutoSignIn";
|
|
55
|
+
|
|
56
|
+
// Re-exported through THIS subpath on purpose: `cursedauth/auth`
|
|
57
|
+
// is already the one client-side auth import every satellite has, and a second
|
|
58
|
+
// entry point for five lines of the same boundary is how two conventions start.
|
|
59
|
+
export {
|
|
60
|
+
clearSsoAutoState,
|
|
61
|
+
decideSsoAutoSignIn,
|
|
62
|
+
lastSsoAttemptAt,
|
|
63
|
+
markSsoSignedOut,
|
|
64
|
+
SSO_ATTEMPT_COOLDOWN_MS,
|
|
65
|
+
SSO_SIGNOUT_PATH,
|
|
66
|
+
SSO_START_PATH,
|
|
67
|
+
type SsoAutoDecision,
|
|
68
|
+
type SsoAutoSkipReason,
|
|
69
|
+
ssoErrorFromLocation,
|
|
70
|
+
ssoSignedOutHere,
|
|
71
|
+
startSsoSignIn,
|
|
72
|
+
startSsoSignOut,
|
|
73
|
+
type SsoInitScriptTarget,
|
|
74
|
+
suppressSsoAutoSignIn,
|
|
75
|
+
takeSsoError,
|
|
76
|
+
useSsoAutoSignIn,
|
|
77
|
+
useSsoErrorNotice,
|
|
78
|
+
} from "./ssoAutoSignIn";
|
|
79
|
+
|
|
80
|
+
export interface SatelliteUser {
|
|
81
|
+
id: string;
|
|
82
|
+
email: string;
|
|
83
|
+
displayName?: string;
|
|
84
|
+
/** Registry-level admin (SSO apps only) — may manage users at the accounts
|
|
85
|
+
* satellite. Apps gate their own privileged surfaces on their own rules. */
|
|
86
|
+
isAdmin?: boolean;
|
|
87
|
+
/**
|
|
88
|
+
* 🔴 The OWNER, which is a strictly smaller set than `isAdmin` and not a
|
|
89
|
+
* synonym for it. Several apps have a surface that is one person's — a fleet
|
|
90
|
+
* limit everybody else's data lives under, a spend decision — and until
|
|
91
|
+
* 2026-08-12 the client had no way to ask, so those surfaces either showed to
|
|
92
|
+
* every admin or were hidden from everybody.
|
|
93
|
+
*
|
|
94
|
+
* It is a COURTESY, never a boundary: the server refuses the write regardless
|
|
95
|
+
* (`scopes` carries `owner` too — see `ssoConsumer.server.ts`). What this
|
|
96
|
+
* flag decides is whether a control is rendered, not whether it works.
|
|
97
|
+
*/
|
|
98
|
+
isOwner?: boolean;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export type SatelliteAuthStatus = "loading" | "authenticated" | "anonymous";
|
|
102
|
+
|
|
103
|
+
export interface SatelliteAuth {
|
|
104
|
+
status: SatelliteAuthStatus;
|
|
105
|
+
user: SatelliteUser | null;
|
|
106
|
+
signIn(email: string, password: string): Promise<void>;
|
|
107
|
+
/**
|
|
108
|
+
* Leave. At an SSO door this ends the session at BOTH ends — this app's
|
|
109
|
+
* cookie and the accounts satellite's — because ending only the first was
|
|
110
|
+
* never a sign-out: auth's session outlived it and the next hop returned the
|
|
111
|
+
* same person without asking for a password (2026-08-10).
|
|
112
|
+
*/
|
|
113
|
+
signOut(): Promise<void>;
|
|
114
|
+
/**
|
|
115
|
+
* Hand the machine to somebody else: the accounts satellite is asked for the
|
|
116
|
+
* credential form even though it holds a live session (`prompt=login`), and
|
|
117
|
+
* the app is re-entered as whoever signs in.
|
|
118
|
+
*
|
|
119
|
+
* Absent on adapters where the idea does not apply — a single-owner app has
|
|
120
|
+
* exactly one user, so there is nobody to switch to.
|
|
121
|
+
*/
|
|
122
|
+
switchUser?(): Promise<void>;
|
|
123
|
+
/** The accounts satellite's origin, when the server named one — where
|
|
124
|
+
* passwords, 2FA and the user list live. Absent/null on a door that is not
|
|
125
|
+
* an SSO door, which is how a UI knows not to offer any of it. */
|
|
126
|
+
accountsUrl?: string | null;
|
|
127
|
+
/** Bearer token for API calls, or null. Callable per-request — never a captured string. */
|
|
128
|
+
token(): string | null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* An authentication implementation. `useSession` is a React hook: it is called from
|
|
133
|
+
* inside `SatelliteAuthProvider`'s render, so an adapter is free to hold state, subscribe
|
|
134
|
+
* to a store, or fire effects exactly as any hook would.
|
|
135
|
+
*/
|
|
136
|
+
export interface AuthAdapter {
|
|
137
|
+
/** Stable id, for diagnostics ("which adapter is this build running?"). */
|
|
138
|
+
id: string;
|
|
139
|
+
/**
|
|
140
|
+
* What the sign-in surface should ASK for. Added 2026-07-27 with the
|
|
141
|
+
* password-only adapter: `signIn(email, password)` is the shape of a
|
|
142
|
+
* multi-account app, and a single-owner satellite has no email to check. A
|
|
143
|
+
* form that collects one anyway and then discards it is a lie about what the
|
|
144
|
+
* credential is, so the adapter says which fields are real and the UI renders
|
|
145
|
+
* exactly those. Defaults to `"email+password"`, which is what every existing
|
|
146
|
+
* caller already assumed.
|
|
147
|
+
*/
|
|
148
|
+
credential?: "email+password" | "password" | "sso";
|
|
149
|
+
useSession(): SatelliteAuth;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const SatelliteAuthContext = createContext<SatelliteAuth | null>(null);
|
|
153
|
+
|
|
154
|
+
export interface SatelliteAuthProviderProps {
|
|
155
|
+
adapter: AuthAdapter;
|
|
156
|
+
children: React.ReactNode;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function SatelliteAuthProvider({ adapter, children }: SatelliteAuthProviderProps) {
|
|
160
|
+
const auth = adapter.useSession();
|
|
161
|
+
return createElement(SatelliteAuthContext.Provider, { value: auth }, children);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function useSatelliteAuth(): SatelliteAuth {
|
|
165
|
+
const auth = useContext(SatelliteAuthContext);
|
|
166
|
+
if (!auth) {
|
|
167
|
+
throw new Error(
|
|
168
|
+
"useSatelliteAuth() was called outside <SatelliteAuthProvider>. Wrap the app in a " +
|
|
169
|
+
"provider and give it an adapter.",
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
return auth;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* The real adapter for a satellite with ONE owner and one password
|
|
177
|
+
* (`cursedauth`'s `secureRequest` on the server side).
|
|
178
|
+
*
|
|
179
|
+
* ── Why there is no token here ──────────────────────────────────────────────
|
|
180
|
+
* `token()` returns null, always, and that is not a stub. The session is an
|
|
181
|
+
* `HttpOnly` cookie: the browser attaches it to same-origin requests by itself,
|
|
182
|
+
* and JavaScript is not able to read it — which is the point. The SPA and the
|
|
183
|
+
* API are served by the same origin, so nothing has to be threaded through.
|
|
184
|
+
* `token()` stays on the interface because the multi-account adapter (cc's
|
|
185
|
+
* bearer sessions, as `apps/orch` uses) genuinely needs it.
|
|
186
|
+
*
|
|
187
|
+
* ── Why status starts "loading" ─────────────────────────────────────────────
|
|
188
|
+
* A cookie session cannot be read synchronously, so the first render genuinely
|
|
189
|
+
* does not know. Rendering the sign-in form during that gap would flash a login
|
|
190
|
+
* screen at an owner who is already signed in, on every page load; rendering the
|
|
191
|
+
* app would flash private chrome at someone who is not. `"loading"` is the
|
|
192
|
+
* honest third answer and the app shell is expected to handle it.
|
|
193
|
+
*/
|
|
194
|
+
export interface OwnerPasswordAdapterOptions {
|
|
195
|
+
/** Base path of the three auth routes. Defaults to `/api/auth`. */
|
|
196
|
+
basePath?: string;
|
|
197
|
+
/** Injectable for tests. Defaults to the global `fetch`. */
|
|
198
|
+
fetchImpl?: typeof fetch;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** The principal a password-only app is signed in AS. There is exactly one. */
|
|
202
|
+
export const OWNER_USER: SatelliteUser = { id: "owner", email: "", displayName: "Owner" };
|
|
203
|
+
|
|
204
|
+
export function createOwnerPasswordAdapter(options: OwnerPasswordAdapterOptions = {}): AuthAdapter {
|
|
205
|
+
const base = options.basePath ?? "/api/auth";
|
|
206
|
+
const http = options.fetchImpl ?? fetch;
|
|
207
|
+
|
|
208
|
+
return {
|
|
209
|
+
id: "owner-password",
|
|
210
|
+
credential: "password",
|
|
211
|
+
useSession(): SatelliteAuth {
|
|
212
|
+
const [status, setStatus] = useState<SatelliteAuthStatus>("loading");
|
|
213
|
+
|
|
214
|
+
// One probe on mount. `useEffect` rather than a render-time fetch so a
|
|
215
|
+
// double render (StrictMode) cannot fire two logins-worth of requests.
|
|
216
|
+
useEffect(() => {
|
|
217
|
+
let cancelled = false;
|
|
218
|
+
void (async () => {
|
|
219
|
+
try {
|
|
220
|
+
const res = await http(`${base}/session`, { credentials: "same-origin" });
|
|
221
|
+
const body = (await res.json()) as { authenticated?: boolean };
|
|
222
|
+
if (!cancelled) setStatus(body?.authenticated ? "authenticated" : "anonymous");
|
|
223
|
+
} catch {
|
|
224
|
+
// A failed probe is not a session. Treating an unreachable server as
|
|
225
|
+
// "anonymous" shows the sign-in form, which is both the safe default
|
|
226
|
+
// and the screen from which the owner can retry.
|
|
227
|
+
if (!cancelled) setStatus("anonymous");
|
|
228
|
+
}
|
|
229
|
+
})();
|
|
230
|
+
return () => {
|
|
231
|
+
cancelled = true;
|
|
232
|
+
};
|
|
233
|
+
// `base` and `http` are fixed when the adapter is constructed, so this
|
|
234
|
+
// runs exactly once per mount — which is the intent: one session probe,
|
|
235
|
+
// not one per render.
|
|
236
|
+
}, [base, http]);
|
|
237
|
+
|
|
238
|
+
const signIn = useCallback(
|
|
239
|
+
async (_email: string, password: string) => {
|
|
240
|
+
const res = await http(`${base}/login`, {
|
|
241
|
+
method: "POST",
|
|
242
|
+
credentials: "same-origin",
|
|
243
|
+
headers: { "content-type": "application/json" },
|
|
244
|
+
body: JSON.stringify({ password }),
|
|
245
|
+
});
|
|
246
|
+
if (!res.ok) {
|
|
247
|
+
const body = (await res.json().catch(() => null)) as { error?: string } | null;
|
|
248
|
+
throw new Error(body?.error ?? "Could not sign in");
|
|
249
|
+
}
|
|
250
|
+
setStatus("authenticated");
|
|
251
|
+
},
|
|
252
|
+
[base, http],
|
|
253
|
+
);
|
|
254
|
+
|
|
255
|
+
const signOut = useCallback(async () => {
|
|
256
|
+
// The status flips even if the request fails: the cookie is HttpOnly, so
|
|
257
|
+
// a client that believes it is signed in while the server disagrees is
|
|
258
|
+
// strictly worse than the reverse — the next API call simply 401s and
|
|
259
|
+
// the owner sees the sign-in form.
|
|
260
|
+
try {
|
|
261
|
+
await http(`${base}/logout`, { method: "POST", credentials: "same-origin" });
|
|
262
|
+
} finally {
|
|
263
|
+
setStatus("anonymous");
|
|
264
|
+
}
|
|
265
|
+
}, [base, http]);
|
|
266
|
+
|
|
267
|
+
return useMemo(
|
|
268
|
+
() => ({
|
|
269
|
+
status,
|
|
270
|
+
user: status === "authenticated" ? OWNER_USER : null,
|
|
271
|
+
signIn,
|
|
272
|
+
signOut,
|
|
273
|
+
token: () => null,
|
|
274
|
+
}),
|
|
275
|
+
[status, signIn, signOut],
|
|
276
|
+
);
|
|
277
|
+
},
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Deliberately generic (2026-09-14). This is a published package; a mock identity
|
|
282
|
+
// is not the place to put a real person's address, and nothing reads the value.
|
|
283
|
+
const MOCK_USER: SatelliteUser = {
|
|
284
|
+
id: "mock-user",
|
|
285
|
+
email: "dev@example.com",
|
|
286
|
+
displayName: "Dev User",
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
/** Token the mock hands out, so a dev API call carries a recognizably fake credential. */
|
|
290
|
+
export const MOCK_SESSION_TOKEN = "mock-session-token";
|
|
291
|
+
|
|
292
|
+
export const MOCK_ADAPTER_IN_PRODUCTION =
|
|
293
|
+
"createMockAuthAdapter() was reached in a production build. " +
|
|
294
|
+
"A satellite that needs auth must not ship the mock — wire the real adapter first.";
|
|
295
|
+
|
|
296
|
+
export interface MockAuthAdapterOptions {
|
|
297
|
+
user?: SatelliteUser;
|
|
298
|
+
/** Start signed out, to exercise the sign-in surface. Defaults to signed in. */
|
|
299
|
+
initialStatus?: Extract<SatelliteAuthStatus, "authenticated" | "anonymous">;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Development stand-in: authenticated immediately, no server involved.
|
|
304
|
+
*
|
|
305
|
+
* It REFUSES TO EXIST in a production build. This is a hard requirement, not a nicety —
|
|
306
|
+
* an adapter that reports `authenticated` unconditionally on a public subdomain is an
|
|
307
|
+
* open door. In a Vite production bundle `import.meta.env.DEV` is compiled to `false`, so
|
|
308
|
+
* this throw cannot be switched off from the outside.
|
|
309
|
+
*/
|
|
310
|
+
export function createMockAuthAdapter(options: MockAuthAdapterOptions = {}): AuthAdapter {
|
|
311
|
+
if (isProductionRuntime()) throw new Error(MOCK_ADAPTER_IN_PRODUCTION);
|
|
312
|
+
|
|
313
|
+
const user = options.user ?? MOCK_USER;
|
|
314
|
+
const startsSignedIn = options.initialStatus !== "anonymous";
|
|
315
|
+
|
|
316
|
+
return {
|
|
317
|
+
id: "mock",
|
|
318
|
+
useSession(): SatelliteAuth {
|
|
319
|
+
const [signedIn, setSignedIn] = useState(startsSignedIn);
|
|
320
|
+
const signIn = useCallback(async () => {
|
|
321
|
+
setSignedIn(true);
|
|
322
|
+
}, []);
|
|
323
|
+
const signOut = useCallback(async () => {
|
|
324
|
+
setSignedIn(false);
|
|
325
|
+
}, []);
|
|
326
|
+
return useMemo(
|
|
327
|
+
() => ({
|
|
328
|
+
status: signedIn ? "authenticated" : "anonymous",
|
|
329
|
+
user: signedIn ? user : null,
|
|
330
|
+
signIn,
|
|
331
|
+
signOut,
|
|
332
|
+
token: () => (signedIn ? MOCK_SESSION_TOKEN : null),
|
|
333
|
+
}),
|
|
334
|
+
[signedIn, signIn, signOut, user],
|
|
335
|
+
);
|
|
336
|
+
},
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// ── The SSO adapter (2026-07-28) ─────────────────────────────────────────────
|
|
341
|
+
|
|
342
|
+
/** What `/api/auth/session` answers in an SSO app (`cursedauth/sso-consumer`
|
|
343
|
+
* on the server side). Exported so app UIs can read `accountsUrl` for their
|
|
344
|
+
* "Manage account" link without a second shape. */
|
|
345
|
+
export interface SsoSessionInfo {
|
|
346
|
+
authenticated: boolean;
|
|
347
|
+
user?: { id: string; email: string; name: string; isAdmin: boolean; isOwner?: boolean };
|
|
348
|
+
/** The accounts satellite's origin — where passwords live. */
|
|
349
|
+
accountsUrl?: string;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
export async function fetchSsoSession(
|
|
353
|
+
fetchImpl: typeof fetch = fetch,
|
|
354
|
+
basePath = "/api/auth",
|
|
355
|
+
): Promise<SsoSessionInfo> {
|
|
356
|
+
const res = await fetchImpl(`${basePath}/session`, { credentials: "same-origin" });
|
|
357
|
+
if (!res.ok) return { authenticated: false };
|
|
358
|
+
return (await res.json()) as SsoSessionInfo;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
export interface SsoRedirectAdapterOptions extends OwnerPasswordAdapterOptions {
|
|
362
|
+
/**
|
|
363
|
+
* Sign in automatically when the session probe says anonymous and the
|
|
364
|
+
* accounts satellite is the door (2026-08-01, owner ask: "don't show me a
|
|
365
|
+
* button when I'm already authorized"). Defaults to ON.
|
|
366
|
+
*
|
|
367
|
+
* The guards that keep it from becoming a redirect loop — and the four
|
|
368
|
+
* situations that suppress it — live in `ssoAutoSignIn.ts`, shared with the
|
|
369
|
+
* satellites that do not use this adapter. Pass `false` to get the old
|
|
370
|
+
* click-to-start behavior back.
|
|
371
|
+
*/
|
|
372
|
+
autoSignIn?: boolean;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* The adapter for a satellite whose users live at the accounts satellite
|
|
377
|
+
* (`apps/auth`). There is no password form here to render — `credential:
|
|
378
|
+
* "sso"` tells the sign-in surface to draw ONE button, and `signIn()` performs
|
|
379
|
+
* a full-page navigation to `/api/auth/sso/start` (a redirect chain cannot be
|
|
380
|
+
* ridden by `fetch`; the browser itself must carry the auth cookie across
|
|
381
|
+
* origins and follow the grant back). The email/password arguments exist on the
|
|
382
|
+
* interface for the other adapters and are ignored here.
|
|
383
|
+
*
|
|
384
|
+
* Since 2026-08-01 the button usually presses itself: an anonymous probe at an
|
|
385
|
+
* SSO door starts the hop immediately and `status` STAYS `"loading"` across the
|
|
386
|
+
* navigation, so the shell shows its loading view rather than flashing a
|
|
387
|
+
* sign-in screen at someone who is already signed in. `"anonymous"` now means
|
|
388
|
+
* something stronger than it did — the automatic path was tried and declined,
|
|
389
|
+
* so the surface it renders is the one that can actually help.
|
|
390
|
+
*/
|
|
391
|
+
export function createSsoRedirectAdapter(options: SsoRedirectAdapterOptions = {}): AuthAdapter {
|
|
392
|
+
const base = options.basePath ?? "/api/auth";
|
|
393
|
+
const http = options.fetchImpl ?? fetch;
|
|
394
|
+
const autoSignIn = options.autoSignIn !== false;
|
|
395
|
+
|
|
396
|
+
return {
|
|
397
|
+
id: "sso-redirect",
|
|
398
|
+
credential: "sso",
|
|
399
|
+
useSession(): SatelliteAuth {
|
|
400
|
+
const [status, setStatus] = useState<SatelliteAuthStatus>("loading");
|
|
401
|
+
const [user, setUser] = useState<SatelliteUser | null>(null);
|
|
402
|
+
// Set when the automatic hop has been launched. The page is unloading,
|
|
403
|
+
// so the honest status is still "loading" — see `resolvedStatus` below.
|
|
404
|
+
const [redirecting, setRedirecting] = useState(false);
|
|
405
|
+
// An explicit sign-out must not be undone by the automatic path on the
|
|
406
|
+
// very next render. A ref rather than state: it is read inside the
|
|
407
|
+
// effect's async body, and it must never schedule a render of its own.
|
|
408
|
+
const signedOutHere = useRef(false);
|
|
409
|
+
// What the SERVER said its accounts origin is. Kept in state rather than
|
|
410
|
+
// read from a config constant because a door that is NOT an SSO door
|
|
411
|
+
// answers with an empty one on purpose (the local vault daemon), and the
|
|
412
|
+
// UI decides what to offer from that answer alone.
|
|
413
|
+
const [accountsUrl, setAccountsUrl] = useState<string | null>(null);
|
|
414
|
+
|
|
415
|
+
useEffect(() => {
|
|
416
|
+
let cancelled = false;
|
|
417
|
+
void (async () => {
|
|
418
|
+
try {
|
|
419
|
+
const info = await fetchSsoSession(http, base);
|
|
420
|
+
if (cancelled) return;
|
|
421
|
+
setAccountsUrl(info.accountsUrl ?? null);
|
|
422
|
+
if (info.authenticated && info.user) {
|
|
423
|
+
setUser({
|
|
424
|
+
id: info.user.id,
|
|
425
|
+
email: info.user.email,
|
|
426
|
+
displayName: info.user.name || info.user.email,
|
|
427
|
+
isAdmin: info.user.isAdmin,
|
|
428
|
+
isOwner: info.user.isOwner,
|
|
429
|
+
});
|
|
430
|
+
// A confirmed session retires both guards: the attempt worked,
|
|
431
|
+
// and whatever sign-out came before it is over.
|
|
432
|
+
clearSsoAutoState();
|
|
433
|
+
setStatus("authenticated");
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
const decision = decideSsoAutoSignIn({
|
|
437
|
+
authenticated: false,
|
|
438
|
+
accountsUrl: info.accountsUrl,
|
|
439
|
+
ssoError: ssoErrorFromLocation(),
|
|
440
|
+
signedOut: signedOutHere.current || ssoSignedOutHere(),
|
|
441
|
+
lastAttemptAt: lastSsoAttemptAt(),
|
|
442
|
+
now: Date.now(),
|
|
443
|
+
enabled: autoSignIn,
|
|
444
|
+
});
|
|
445
|
+
if (decision.start) {
|
|
446
|
+
setRedirecting(true);
|
|
447
|
+
startSsoSignIn({ startPath: `${base}/sso/start`, automatic: true });
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
setStatus("anonymous");
|
|
451
|
+
} catch {
|
|
452
|
+
// A failed probe is not a session — same posture as the owner
|
|
453
|
+
// adapter: show the sign-in surface, from which retry is one click.
|
|
454
|
+
// Deliberately NOT an auto-start: an unreachable server is exactly
|
|
455
|
+
// the case where bouncing to another origin loses the error.
|
|
456
|
+
if (!cancelled) setStatus("anonymous");
|
|
457
|
+
}
|
|
458
|
+
})();
|
|
459
|
+
return () => {
|
|
460
|
+
cancelled = true;
|
|
461
|
+
};
|
|
462
|
+
}, [base, http, autoSignIn]);
|
|
463
|
+
|
|
464
|
+
const signIn = useCallback(async () => {
|
|
465
|
+
// Deliberately a navigation, not a fetch — and deliberately never
|
|
466
|
+
// resolving: the page is about to unload. An explicit press clears
|
|
467
|
+
// the guards, so it works even after a sign-out or a failed hop.
|
|
468
|
+
signedOutHere.current = false;
|
|
469
|
+
startSsoSignIn({ startPath: `${base}/sso/start` });
|
|
470
|
+
await new Promise<never>(() => {});
|
|
471
|
+
}, [base]);
|
|
472
|
+
|
|
473
|
+
const signOut = useCallback(async () => {
|
|
474
|
+
// A NAVIGATION, not a fetch, and it deliberately never resolves — the
|
|
475
|
+
// page is about to unload. It has to be: this ends auth's session as
|
|
476
|
+
// well as this app's, and a cross-origin cookie cannot be cleared by
|
|
477
|
+
// a same-origin `fetch`. Before 2026-08-10 this posted to `/logout`
|
|
478
|
+
// and stopped there, which ended this app's cookie only — auth's
|
|
479
|
+
// session outlived it, so the next hop signed the same person
|
|
480
|
+
// straight back in with no password asked for, and there was no
|
|
481
|
+
// sequence of clicks that let anybody else use the machine.
|
|
482
|
+
signedOutHere.current = true;
|
|
483
|
+
startSsoSignOut({ signOutPath: `${base}/sso/signout` });
|
|
484
|
+
await new Promise<never>(() => {});
|
|
485
|
+
}, [base]);
|
|
486
|
+
|
|
487
|
+
const switchUser = useCallback(async () => {
|
|
488
|
+
// Same shape as `signIn`, plus the flag that makes accounts show its
|
|
489
|
+
// form instead of re-issuing a grant for the session it already holds.
|
|
490
|
+
signedOutHere.current = false;
|
|
491
|
+
startSsoSignIn({ startPath: `${base}/sso/start`, switchUser: true });
|
|
492
|
+
await new Promise<never>(() => {});
|
|
493
|
+
}, [base]);
|
|
494
|
+
|
|
495
|
+
// The page is on its way to accounts, so "loading" is the honest answer
|
|
496
|
+
// and the shell keeps showing its spinner. Reporting "anonymous" here
|
|
497
|
+
// would flash the sign-in screen for the length of one navigation —
|
|
498
|
+
// which is the entire thing this feature exists to remove.
|
|
499
|
+
const resolvedStatus: SatelliteAuthStatus = redirecting ? "loading" : status;
|
|
500
|
+
|
|
501
|
+
return useMemo(
|
|
502
|
+
() => ({
|
|
503
|
+
status: resolvedStatus,
|
|
504
|
+
user,
|
|
505
|
+
signIn,
|
|
506
|
+
signOut,
|
|
507
|
+
switchUser,
|
|
508
|
+
accountsUrl,
|
|
509
|
+
token: () => null,
|
|
510
|
+
}),
|
|
511
|
+
[resolvedStatus, user, signIn, signOut, switchUser, accountsUrl],
|
|
512
|
+
);
|
|
513
|
+
},
|
|
514
|
+
};
|
|
515
|
+
}
|