@superintelligentfamily/key-react 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Seth Shoultes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/lib/index.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { type Profile } from "@superintelligentfamily/key-js/doorman";
2
+ import { type ReactNode } from "react";
3
+ export declare const PACKAGE_NAME = "@superintelligentfamily/key-react";
4
+ export type { Profile };
5
+ /** getToken() couldn't get an answer: Key or the handler is out of reach, or a refresh lost its race twice. The session
6
+ * is kept; try again later. A signed-out session is not this: getToken() returns null for it. */
7
+ export declare class DoormanUnavailable extends Error {
8
+ readonly status: number;
9
+ constructor(status: number);
10
+ }
11
+ export declare function DoormanProvider({ mount, children }: {
12
+ mount?: string;
13
+ children?: ReactNode;
14
+ }): import("react/jsx-runtime").JSX.Element;
15
+ /** Who the page shows as signed in: cosmetic, so never the reason to show something only a member may see. */
16
+ export declare function useUser(): {
17
+ isSignedIn: boolean;
18
+ user: Profile | null;
19
+ };
20
+ export declare function useAuth(): {
21
+ isSignedIn: boolean;
22
+ getToken: () => Promise<string | null>;
23
+ signOut: () => void;
24
+ };
25
+ export declare function SignedIn({ children }: {
26
+ children?: ReactNode;
27
+ }): import("react/jsx-runtime").JSX.Element | null;
28
+ export declare function SignedOut({ children }: {
29
+ children?: ReactNode;
30
+ }): import("react/jsx-runtime").JSX.Element | null;
31
+ /** Goes to the handler's sign-in, coming back to this page or to `returnTo`, a path on this site (anything else is "/"). */
32
+ export declare function SignInButton({ children, returnTo }: {
33
+ children?: ReactNode;
34
+ returnTo?: string;
35
+ }): import("react/jsx-runtime").JSX.Element;
36
+ /** The signed-in person's picture and name, opening a menu with Sign out; nothing when signed out. */
37
+ export declare function UserButton(): import("react/jsx-runtime").JSX.Element | null;
package/lib/index.js ADDED
@@ -0,0 +1,137 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // @superintelligentfamily/key-react (DESIGN §6.2, doorman#55 PR 5): Key sign-in for a React app whose server mounts @superintelligentfamily/key-handler. The
3
+ // names match Clerk's. Who is shown comes from dm_profile, the cosmetic cookie the handler's callback sets (a visitor can
4
+ // forge it, so it only decides what the page shows); what grants access is the access token getToken() gets from the
5
+ // handler's POST <mount>/token, which the app's server checks with @superintelligentfamily/key-verify.
6
+ import { PROFILE_COOKIE, readProfile, returnPath } from "@superintelligentfamily/key-js/doorman";
7
+ import { createContext, useCallback, useContext, useMemo, useRef, useState, useSyncExternalStore } from "react";
8
+ export const PACKAGE_NAME = "@superintelligentfamily/key-react";
9
+ /** getToken() couldn't get an answer: Key or the handler is out of reach, or a refresh lost its race twice. The session
10
+ * is kept; try again later. A signed-out session is not this: getToken() returns null for it. */
11
+ export class DoormanUnavailable extends Error {
12
+ status;
13
+ constructor(status) {
14
+ super(`the sign-in service didn't answer (${status})`);
15
+ this.status = status;
16
+ }
17
+ }
18
+ /** A token is reused while more than this many seconds are left, as the handler does (its EARLY). */
19
+ const EARLY = 60;
20
+ /** Times getToken asks again because the signed-in cookie changed while a request was out; then it gives up. */
21
+ const MOVES = 2;
22
+ const Ctx = createContext(null);
23
+ // The page's cookies, re-read when the page may have changed hands (back, focus, another tab), as doorman.js does.
24
+ const EVENTS = ["focus", "pageshow"];
25
+ function subscribe(changed) {
26
+ for (const e of EVENTS)
27
+ window.addEventListener(e, changed);
28
+ document.addEventListener("visibilitychange", changed);
29
+ return () => {
30
+ for (const e of EVENTS)
31
+ window.removeEventListener(e, changed);
32
+ document.removeEventListener("visibilitychange", changed);
33
+ };
34
+ }
35
+ const cookies = () => document.cookie;
36
+ const noCookies = () => "";
37
+ /** The cache key: dm_profile exactly as set, which carries a value random per sign-in; "" when no one is signed in. */
38
+ const who = () => readProfile(document.cookie)
39
+ ? document.cookie.split(";").map((s) => s.trim()).find((s) => s.startsWith(`${PROFILE_COOKIE}=`)) ?? ""
40
+ : ""; // on the server, and in the first render that hydrates it: signed out until the browser says
41
+ export function DoormanProvider({ mount = "/api/doorman", children }) {
42
+ // A render after a getToken() that ended the session reads the cookies again: the handler's 401 cleared dm_profile.
43
+ const [, rerender] = useState(0);
44
+ const jar = useSyncExternalStore(subscribe, cookies, noCookies);
45
+ const user = useMemo(() => readProfile(jar), [jar]);
46
+ // The token is tied to the profile it was got under: a sign-out (or another person's sign-in) in another tab changes
47
+ // dm_profile, and this tab then asks the handler again instead of handing out the old session's token.
48
+ const cached = useRef(null);
49
+ const pending = useRef(null);
50
+ const getToken = useCallback(() => {
51
+ const c = cached.current, now = who();
52
+ if (c && now !== "" && c.who === now && c.exp - Date.now() / 1000 > EARLY)
53
+ return Promise.resolve(c.token);
54
+ // One request at a time: two at once would race for the handler's refresh lease.
55
+ return (pending.current ??= (async () => {
56
+ try {
57
+ for (let attempt = 0, moved = 0;;) {
58
+ // The cookie as the request leaves (Fable on #75): if another tab signs someone else in or out while it is out,
59
+ // the answer may be the old session's, so it is dropped and the handler asked again under the new cookie.
60
+ const sent = who();
61
+ const res = await fetch(`${mount}/token`, { method: "POST", credentials: "same-origin" });
62
+ if (res.ok) {
63
+ const body = (await res.json());
64
+ if (who() !== sent) {
65
+ if (++moved > MOVES)
66
+ throw new DoormanUnavailable(409);
67
+ continue;
68
+ }
69
+ cached.current = { token: body.access_token, exp: body.expires_at, who: sent };
70
+ return body.access_token;
71
+ }
72
+ if (res.status === 401) {
73
+ cached.current = null;
74
+ rerender((n) => n + 1);
75
+ return null;
76
+ }
77
+ // 409: another tab's refresh held the lease; the handler says to retry once.
78
+ if (res.status !== 409 || attempt++ > 0)
79
+ throw new DoormanUnavailable(res.status);
80
+ }
81
+ }
82
+ finally {
83
+ pending.current = null;
84
+ }
85
+ })());
86
+ }, [mount]);
87
+ const value = useMemo(() => ({
88
+ user,
89
+ getToken,
90
+ signIn: (o = {}) => window.location.assign(`${mount}/sign-in?return_to=${encodeURIComponent(returnPath(o.returnTo, window.location))}`),
91
+ // A real form POST, so the handler's 303 to Key's end_session navigates the page (DESIGN §5.2).
92
+ signOut: () => {
93
+ cached.current = null;
94
+ const f = document.createElement("form");
95
+ f.method = "post";
96
+ f.action = `${mount}/signout`;
97
+ f.hidden = true;
98
+ document.body.appendChild(f);
99
+ f.submit();
100
+ },
101
+ }), [user, getToken, mount]);
102
+ return _jsx(Ctx.Provider, { value: value, children: children });
103
+ }
104
+ function useDoorman() {
105
+ const d = useContext(Ctx);
106
+ if (!d)
107
+ throw new Error("@superintelligentfamily/key-react: wrap the app in <DoormanProvider>");
108
+ return d;
109
+ }
110
+ /** Who the page shows as signed in: cosmetic, so never the reason to show something only a member may see. */
111
+ export function useUser() {
112
+ const { user } = useDoorman();
113
+ return { isSignedIn: !!user, user };
114
+ }
115
+ export function useAuth() {
116
+ const { user, getToken, signOut } = useDoorman();
117
+ return { isSignedIn: !!user, getToken, signOut };
118
+ }
119
+ export function SignedIn({ children }) {
120
+ return useDoorman().user ? _jsx(_Fragment, { children: children }) : null;
121
+ }
122
+ export function SignedOut({ children }) {
123
+ return useDoorman().user ? null : _jsx(_Fragment, { children: children });
124
+ }
125
+ /** Goes to the handler's sign-in, coming back to this page or to `returnTo`, a path on this site (anything else is "/"). */
126
+ export function SignInButton({ children = "Sign in", returnTo }) {
127
+ const { signIn } = useDoorman();
128
+ return _jsx("button", { type: "button", onClick: () => signIn(returnTo === undefined ? {} : { returnTo }), children: children });
129
+ }
130
+ /** The signed-in person's picture and name, opening a menu with Sign out; nothing when signed out. */
131
+ export function UserButton() {
132
+ const { user, signOut } = useDoorman();
133
+ const [open, setOpen] = useState(false);
134
+ if (!user)
135
+ return null;
136
+ return (_jsxs(_Fragment, { children: [_jsxs("button", { type: "button", "aria-haspopup": "menu", "aria-expanded": open, onClick: () => setOpen(!open), children: [user.picture ? _jsx("img", { src: user.picture, alt: "", width: 32, height: 32, referrerPolicy: "no-referrer" }) : null, _jsx("span", { children: user.name || "Account" })] }), _jsx("div", { role: "menu", hidden: !open, children: _jsx("button", { type: "button", role: "menuitem", onClick: signOut, children: "Sign out" }) })] }));
137
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@superintelligentfamily/key-react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "license": "MIT",
5
+ "description": "Key sign-in for a React app whose server mounts @superintelligentfamily/key-handler: a provider, a sign-in button, and signed-in and signed-out components.",
6
+ "homepage": "https://superintelligentkey.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/sethshoultes/doorman.git",
10
+ "directory": "packages/react"
11
+ },
12
+ "type": "module",
13
+ "files": [
14
+ "lib",
15
+ "LICENSE"
16
+ ],
17
+ "exports": {
18
+ ".": {
19
+ "types": "./lib/index.d.ts",
20
+ "import": "./lib/index.js"
21
+ }
22
+ },
23
+ "dependencies": {
24
+ "@superintelligentfamily/key-js": "1.0.1"
25
+ },
26
+ "peerDependencies": {
27
+ "react": ">=18"
28
+ },
29
+ "devDependencies": {
30
+ "@types/react": "19.1.8",
31
+ "@types/react-dom": "19.1.6",
32
+ "happy-dom": "21.0.4",
33
+ "react": "19.1.0",
34
+ "react-dom": "19.1.0",
35
+ "@superintelligentfamily/key-handler": "0.1.1"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "scripts": {
41
+ "typecheck": "tsc --noEmit -p .",
42
+ "lint": "eslint .",
43
+ "test": "vitest run",
44
+ "check": "pnpm run typecheck && pnpm run lint && pnpm run test",
45
+ "build:npm": "tsc -p tsconfig.build.json"
46
+ }
6
47
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.