@userbox/react 0.0.0-bootstrap.0 → 1.0.0-alpha.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/CHANGELOG.md ADDED
@@ -0,0 +1,39 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@userbox/react` are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/).
7
+
8
+ ## [1.0.0-alpha.0] — 2026-05-18
9
+
10
+ Initial alpha. Public surface frozen for the V1 scope.
11
+
12
+ ### Added
13
+ - `UserboxProvider` — bootstraps the session, owns the proactive 12-minute
14
+ refresh timer, exposes session + permission state to descendants.
15
+ - Hooks: `useSession`, `usePermissions`, `usePermission`, `useSignIn`,
16
+ `useSignUp`, `useSignOut`.
17
+ - `<UserboxCallback>` — consumes `access_token` / `refresh_token` from the
18
+ URL fragment, validates state nonce, scrubs the URL.
19
+ - Next.js App Router subpath `@userbox/react/nextjs`:
20
+ - `userboxMiddleware(config)` — Edge middleware that refreshes the access
21
+ token and rotates the refresh cookie.
22
+ - `getSession()` — Server Components helper.
23
+ - Storage strategies: `memory` (closure-scoped) and `cookie` (httpOnly,
24
+ managed by tenant backend).
25
+ - Cross-tab refresh coordination via `BroadcastChannel` with 200ms claim
26
+ window.
27
+ - Single-flight refresh coalescing + permanent-fail latch + transient
28
+ retry policy (1s/3s/9s).
29
+ - `UserboxError` tagged union with type guard.
30
+ - Architectural tests enforcing: no React/Next imports from `core/`, no
31
+ `localStorage`/`sessionStorage` writes for credentials, no
32
+ `accessToken` in the React entry's `.d.ts`, `usePermission` JSDoc
33
+ carries the literal "UI HINTS ONLY" disclaimer.
34
+
35
+ ### Known limitations
36
+ - Refresh-token rotation race on browser crash (documented).
37
+ - External-tenant `<UserboxCallback>` depends on an auth-surface
38
+ prerequisite tracked separately.
39
+ - No Vue / Svelte adapters in V1.
package/README.md CHANGED
@@ -1,7 +1,150 @@
1
1
  # @userbox/react
2
2
 
3
- Placeholder release. Install the real package with:
3
+ > **Alpha.** The API may change before 1.0.0. Install the alpha channel explicitly:
4
+ >
5
+ > npm install @userbox/react@alpha
6
+ >
7
+ > Docs: https://docs.userbox.dev · Source: https://github.com/osbxtech/userbox-js/tree/main/react
4
8
 
5
- npm install @userbox/react@alpha
9
+ The official TypeScript/React frontend SDK for Userbox. Provides session
10
+ management, permission-gated UI hooks, and a thin Next.js App Router
11
+ integration.
6
12
 
7
- Source: https://github.com/osbxtech/userbox-js
13
+ > **Frontend permission checks are UI hints only.** Every destructive action
14
+ > MUST be authorised server-side. The SDK exposes no primitive that grants
15
+ > authoritative access; it surfaces what the server told it the user could
16
+ > see. Treat `usePermission` output strictly as "should I render this
17
+ > button?" — never as "is this safe to do?".
18
+
19
+ ---
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pnpm add @userbox/react@alpha
25
+ # Peer deps (already required by your app)
26
+ pnpm add react react-dom
27
+ # Optional: only if you use the Next.js integration
28
+ pnpm add next
29
+ ```
30
+
31
+ ## Quick start (React)
32
+
33
+ ```tsx
34
+ import { UserboxProvider, useSession, usePermission } from "@userbox/react";
35
+
36
+ function App() {
37
+ return (
38
+ <UserboxProvider
39
+ tenantSlug="acme"
40
+ baseUrl="https://api.userbox.app"
41
+ tokenStorage="cookie" // recommended; see decision matrix below
42
+ refreshUrl="/api/auth/refresh" // your tenant backend proxy
43
+ >
44
+ <Dashboard />
45
+ </UserboxProvider>
46
+ );
47
+ }
48
+
49
+ function Dashboard() {
50
+ const session = useSession();
51
+ if (!session.isLoaded) return <p>Loading…</p>;
52
+ if (!session.isSignedIn) return <SignInButton />;
53
+ return <SignedInDashboard userId={session.user.id} />;
54
+ }
55
+
56
+ function DeleteButton({ workspaceId }: { workspaceId: string }) {
57
+ const { allowed, isLoaded } = usePermission(workspaceId, "items.delete");
58
+ if (!isLoaded) return null; // fail-closed
59
+ if (!allowed) return null; // hide — but the API still enforces
60
+ return <button onClick={...}>Delete</button>;
61
+ }
62
+ ```
63
+
64
+ ## Storage-strategy decision matrix
65
+
66
+ | Strategy | Where refresh token lives | Requires tenant backend? | Survives hard refresh? | Recommended for |
67
+ |---|---|---|---|---|
68
+ | `cookie` (default-ish) | httpOnly cookie set by your tenant backend | Yes — a `refreshUrl` proxy | ✅ | Full-stack apps with Next.js / Express / Django |
69
+ | `memory` | JS closure (`MemoryStore`) | No | ❌ | Pure SPAs with no backend; demo/dogfood |
70
+
71
+ **Pick `cookie` unless you literally have no server.** The memory strategy
72
+ trades survival across reloads for zero-backend deploys.
73
+
74
+ **Configuration consistency — do not mix:**
75
+ - Under `tokenStorage: "memory"`, do NOT install `userboxMiddleware`. The
76
+ middleware looks for a refresh cookie, finds none, and warns.
77
+ - Under `tokenStorage: "cookie"` in Next.js, the middleware is REQUIRED for
78
+ Server Components to see a signed-in session.
79
+
80
+ ## Quick start (Next.js App Router)
81
+
82
+ ```ts
83
+ // middleware.ts
84
+ export { userboxMiddleware as middleware } from "@userbox/react/nextjs";
85
+
86
+ // app/dashboard/page.tsx — Server Component
87
+ import { getSession } from "@userbox/react/nextjs";
88
+ export default async function Page() {
89
+ const session = await getSession();
90
+ if (!session) return <RedirectToSignIn />;
91
+ return <h1>Hello {session.user.id}</h1>;
92
+ }
93
+ ```
94
+
95
+ ⚠️ **`ServerSession` carries the bearer `accessToken`.** Do NOT pass the
96
+ returned `session` as a prop to a Client Component — Next.js will serialise
97
+ the token into the client bundle. Pass `session.user` instead.
98
+
99
+ ## API surface
100
+
101
+ The exported TypeScript types are the authoritative reference. Quick
102
+ reference:
103
+
104
+ - `<UserboxProvider>` — mount once at the root; configures the SDK.
105
+ - `useSession()` — discriminated union; `{ isLoaded, isSignedIn, user }`.
106
+ - `usePermissions(workspaceId)` — `ReadonlySet<string>`, one fetch per workspace.
107
+ - `usePermission(workspaceId, key)` — synchronous boolean derivation. **UI hints only.**
108
+ - `useSignIn() / useSignUp()` — navigate to the hosted auth surface.
109
+ - `useSignOut()` — clears in-memory state + calls `/v1/auth/logout`.
110
+ - `<UserboxCallback>` — consumes credentials from the URL fragment.
111
+ - `userboxMiddleware()` + `getSession()` from `@userbox/react/nextjs`.
112
+
113
+ ## Auth-surface assumptions
114
+
115
+ Sign-in/sign-up navigation defaults to `https://{slug}.userbox.app/{login,signup}?return_to=<url>&state=<nonce>&flow_id=<flow>`.
116
+
117
+ - Override the host with the `baseAuthUrl` provider prop for local dev (e.g.
118
+ `http://acme.userbox.localhost:3000`).
119
+ - `return_to` is validated to be same-origin with the calling app **on the
120
+ client**. Defence-in-depth: the auth surface itself MUST also allowlist
121
+ return URLs server-side before redirecting. The SDK's check is a UX
122
+ safeguard, not the authoritative boundary.
123
+
124
+ ## Known limitations
125
+
126
+ - **Refresh-token rotation race on crash**: if the browser
127
+ crashes between the refresh server having rotated the token and the SDK
128
+ receiving the response, the in-memory rotated token is lost. The user
129
+ needs to sign in again. The window is small but real.
130
+ - **External-tenant `<UserboxCallback>`** depends on the auth surface
131
+ emitting credentials via URL fragment to external return URLs — a
132
+ prerequisite tracked separately (see plan Complexity Tracking). The
133
+ parser in this package is built against the future contract; same-origin
134
+ `*.userbox.app` flows work today.
135
+ - **No `<UserboxGate>` declarative wrapper.** Use `usePermission` directly.
136
+ - **No Vue / Svelte adapters in V1.** `core/` is framework-agnostic and
137
+ could host them later (no commitment).
138
+ - **API slug regex parity**: the SDK rejects 1-2 char slugs
139
+ that the API accepts; this is the safe direction (SDK stricter) but a
140
+ consumer using a single-char slug will see `misconfigured` errors.
141
+
142
+ ## Versioning
143
+
144
+ Strict semver post-GA. See `CHANGELOG.md`. The shapes documented in the
145
+ contract are the public surface; any breaking change is a major release.
146
+
147
+ ## Security
148
+
149
+ See [`SECURITY.md`](./SECURITY.md) for the security model, threat coverage,
150
+ and the responsible-disclosure email.
package/SECURITY.md ADDED
@@ -0,0 +1,62 @@
1
+ # Security policy — `@userbox/react`
2
+
3
+ ## Threat model summary
4
+
5
+ - **Access token storage**: memory-only. The SDK never writes the access
6
+ token to `localStorage`, `sessionStorage`, IndexedDB, or `document.cookie`.
7
+ An architectural test (`tests/architectural/no-localstorage-writes.test.ts`)
8
+ scans the built bundle and fails the build if these writes appear.
9
+ - **Refresh token storage** (two strategies):
10
+ - `cookie` (recommended): httpOnly + Secure + SameSite=Lax cookie managed
11
+ by the tenant backend; the SDK never reads `document.cookie`.
12
+ - `memory`: closure-scoped, lost on reload — by design.
13
+ - **Server authority**: permission decisions are made by the API on every
14
+ request that performs an action. The SDK's `usePermission` is a UI hint;
15
+ a `true` value does NOT authorize a destructive action.
16
+ - **JWT verification**: the SDK decodes JWT claims for routing/timer use
17
+ (`sub`, `tid`, `exp`) without signature verification — the server is the
18
+ sole authority on token validity.
19
+ - **No credentials in logs**: error messages, `console.warn`, and `Error`
20
+ objects produced by the SDK MUST NOT contain access or refresh tokens.
21
+ Enforced by `tests/architectural/no-credential-logs.test.ts` against the
22
+ built bundle.
23
+
24
+ ## CSRF / replay protection on sign-in
25
+
26
+ Each `signIn()` / `signUp()` call generates a cryptographic random state
27
+ nonce, stored in `sessionStorage` under `ub.auth.state` keyed by a
28
+ per-flow `flowId`. The callback verifies the returned `state` matches the
29
+ stored value. Mismatch → `UserboxError { kind: "auth_failed", code: "STATE_MISMATCH" }`.
30
+
31
+ Multi-flow safety: starting multiple concurrent sign-in flows is supported;
32
+ each is keyed independently and consuming one does not affect others.
33
+
34
+ ## Cross-tab coordination
35
+
36
+ When `BroadcastChannel` is available, refresh requests are coordinated so
37
+ exactly one tab issues the outbound HTTP call per refresh cycle. The other tabs adopt the broadcast session.
38
+
39
+ ## Cookie attributes (Next.js middleware)
40
+
41
+ The middleware sets the rotated refresh cookie with:
42
+
43
+ - `HttpOnly` — non-negotiable.
44
+ - `Secure` — required in production builds, optional in dev.
45
+ - `SameSite=Lax` — default; overridable to `Strict` or `None`.
46
+ - `Domain` — defaults to the request host; configurable for cookie-domain
47
+ sharing (e.g. `.acme.com`).
48
+ - `Max-Age` — derived from the refresh-token TTL the server returned.
49
+
50
+ Silent regression of these attributes is a release-blocker.
51
+
52
+ ## Failure-mode preservation (Next.js middleware)
53
+
54
+ A 5xx or network failure from the refresh endpoint does NOT clear the
55
+ refresh cookie. Only HTTP 400/401/403 (genuine credential rejection) clears
56
+ the cookie. This prevents a Userbox-side outage from mass-logging-out users.
57
+
58
+ ## Reporting a vulnerability
59
+
60
+ See the repository [security policy](../SECURITY.md). Report privately through
61
+ GitHub private vulnerability reporting or **security@osbxtech.nl**, never in a
62
+ public issue.
@@ -0,0 +1,161 @@
1
+ import * as React from 'react';
2
+
3
+ /**
4
+ * Userbox error tagged-union. Used by every layer of the SDK as the single
5
+ * error shape callers may inspect. Tokens (access / refresh) MUST NEVER appear
6
+ * in any `message` produced by these constructors — security invariant S-2.
7
+ */
8
+ type MisconfiguredField = "tenantSlug" | "baseUrl" | "tokenStorage" | "refreshUrl" | "callbackUrl";
9
+ type UserboxError = {
10
+ kind: "missing_credentials";
11
+ message: string;
12
+ requestId?: string;
13
+ } | {
14
+ kind: "auth_failed";
15
+ message: string;
16
+ httpStatus: number;
17
+ code: string;
18
+ requestId?: string;
19
+ } | {
20
+ kind: "refresh_failed";
21
+ message: string;
22
+ httpStatus: number;
23
+ code: string;
24
+ requestId?: string;
25
+ } | {
26
+ kind: "permission_fetch_failed";
27
+ message: string;
28
+ httpStatus: number;
29
+ code: string;
30
+ workspaceId: string;
31
+ requestId?: string;
32
+ } | {
33
+ kind: "network";
34
+ message: string;
35
+ } | {
36
+ kind: "misconfigured";
37
+ message: string;
38
+ field: MisconfiguredField;
39
+ };
40
+ /** Type guard verifying a value is a `UserboxError`. */
41
+ declare function isUserboxError(value: unknown): value is UserboxError;
42
+
43
+ type UserboxProviderProps = {
44
+ tenantSlug: string;
45
+ baseUrl: string;
46
+ baseAuthUrl?: string;
47
+ tokenStorage: "cookie" | "memory";
48
+ refreshUrl?: string;
49
+ refreshThresholdPct?: number;
50
+ proactiveSkewMs?: number;
51
+ onSessionExpired?: () => void;
52
+ onError?: (err: UserboxError) => void;
53
+ children: React.ReactNode;
54
+ };
55
+ declare const UserboxProvider: React.FC<UserboxProviderProps>;
56
+
57
+ type SessionUser = {
58
+ id: string;
59
+ tenantId: string;
60
+ email: string | null;
61
+ fullName: string | null;
62
+ };
63
+
64
+ type PublicSession = {
65
+ user: SessionUser;
66
+ };
67
+ type SessionResult = {
68
+ isLoaded: false;
69
+ isSignedIn: false;
70
+ user: null;
71
+ } | {
72
+ isLoaded: true;
73
+ isSignedIn: false;
74
+ user: null;
75
+ } | {
76
+ isLoaded: true;
77
+ isSignedIn: true;
78
+ user: SessionUser;
79
+ };
80
+ type PermissionsResult = {
81
+ permissions: ReadonlySet<string>;
82
+ isLoaded: boolean;
83
+ error: UserboxError | null;
84
+ };
85
+ type PermissionResult = {
86
+ allowed: boolean;
87
+ isLoaded: boolean;
88
+ };
89
+
90
+ /**
91
+ * Returns the session state as a discriminated union. Never throws.
92
+ *
93
+ * Must be called inside a `<UserboxProvider>`. Throws if used outside one
94
+ * (misconfigured error) — that throw is a developer-time signal, not a runtime
95
+ * error to handle in production code.
96
+ */
97
+ declare function useSession(): SessionResult;
98
+
99
+ /**
100
+ * Returns the current access token (or `null` when not signed in).
101
+ *
102
+ * Use this to authenticate calls from tenant frontend code to the tenant's
103
+ * own backend (which validates the token via the Python SDK's `require_auth`
104
+ * dependency or equivalent). The value comes from the in-memory session
105
+ * managed by `<UserboxProvider>` — same source as the `Authorization`
106
+ * header used internally by `useSignOut()` / refresh / `usePermissions`.
107
+ *
108
+ * Security note: the access token has the same exposure surface as any
109
+ * JavaScript variable in the page. If your threat model requires the token
110
+ * never to be reachable from user code, use a backend-cookie strategy
111
+ * (`tokenStorage="cookie"` + a refresh proxy) instead.
112
+ */
113
+ declare function useAccessToken(): string | null;
114
+
115
+ /**
116
+ * Returns the cached permission set for `workspaceId`. Issues at most one
117
+ * outbound `GET /v1/access/permissions` per workspace (cached for the
118
+ * lifetime of the provider).
119
+ *
120
+ * IMPORTANT — UI HINTS ONLY: the returned set is for show/hide rendering only.
121
+ * The server enforces permissions on every request that performs an action.
122
+ */
123
+ declare function usePermissions(workspaceId: string): PermissionsResult;
124
+
125
+ /**
126
+ * Returns whether the current user holds `permissionKey` in `workspaceId`,
127
+ * as a synchronous derivation from `usePermissions`.
128
+ *
129
+ * IMPORTANT — UI HINTS ONLY: this result is for show/hide rendering decisions
130
+ * only. The server must always enforce permissions on the request that
131
+ * performs the operation. A frontend `allowed: true` does NOT authorize a
132
+ * destructive action — that is the responsibility of the API the action
133
+ * targets.
134
+ */
135
+ declare function usePermission(workspaceId: string, permissionKey: string): PermissionResult;
136
+
137
+ type SignInOptions = {
138
+ returnTo?: string;
139
+ };
140
+ declare function useSignIn(): {
141
+ signIn: (opts?: SignInOptions) => void;
142
+ };
143
+
144
+ declare function useSignUp(): {
145
+ signUp: (opts?: SignInOptions) => void;
146
+ };
147
+
148
+ type SignOutOptions = {
149
+ redirectUri?: string;
150
+ };
151
+ declare function useSignOut(): {
152
+ signOut: (opts?: SignOutOptions) => Promise<void>;
153
+ };
154
+
155
+ type UserboxCallbackProps = {
156
+ onSuccess?: (session: PublicSession) => void;
157
+ onError?: (err: UserboxError) => void;
158
+ };
159
+ declare const UserboxCallback: React.FC<UserboxCallbackProps>;
160
+
161
+ export { type PermissionResult, type PermissionsResult, type PublicSession, type SessionResult, type SessionUser, type SignInOptions, type SignOutOptions, UserboxCallback, type UserboxCallbackProps, type UserboxError, UserboxProvider, type UserboxProviderProps, isUserboxError, useAccessToken, usePermission, usePermissions, useSession, useSignIn, useSignOut, useSignUp };