@whity/api-client 0.0.0-stage → 0.2.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 CHANGED
@@ -1,3 +1,133 @@
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.
1
+ # @whity/api-client
2
+
3
+ The typed client for the **Whity** API — build your own frontend or integration
4
+ against the same OpenAPI contract the reference web app uses.
5
+
6
+ Types are generated from the backend's OpenAPI spec (`public/openapi.json`), so
7
+ request/response shapes stay in lock-step with the server.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @whity/api-client openapi-fetch
13
+ ```
14
+
15
+ (`openapi-fetch` is a peer at runtime; `@whity/api-client` ships TypeScript
16
+ source, so your bundler compiles it.)
17
+
18
+ ## Use
19
+
20
+ ```ts
21
+ import { createApiClient } from '@whity/api-client';
22
+
23
+ // Standalone frontend: point at the backend origin.
24
+ const api = createApiClient({ baseUrl: 'https://your-whity-host' });
25
+
26
+ const { data, error, response } = await api.GET('/api/v1/settings/global');
27
+ if (error) {
28
+ // typed error body
29
+ } else {
30
+ // typed data
31
+ }
32
+ ```
33
+
34
+ Responses are never thrown — branch on `{ data, error, response }`.
35
+
36
+ ### Auth
37
+
38
+ Two modes. Pick the one that matches where your frontend runs.
39
+
40
+ **Cookie mode** (default): the same flow as the Whity web app. Every request sends
41
+ `credentials: 'include'` (httpOnly cookies) plus the `X-Requested-With:
42
+ XMLHttpRequest` CSRF header. The cookies are host-only and SameSite=Lax, so this
43
+ only works when the frontend and the API share a site: same origin, a reverse
44
+ proxy that forwards `/api/*` (leave `baseUrl` empty, the default), or sibling
45
+ subdomains such as `app.example.com` and `api.example.com`.
46
+
47
+ **Token mode**: for a frontend on another site, a native app or a server. Every
48
+ request sends `X-Auth-Mode: token` and `Authorization: Bearer <access token>`,
49
+ never cookies.
50
+
51
+ ```ts
52
+ import { createApiClient, createMemoryTokenStore } from '@whity/api-client';
53
+
54
+ const api = createApiClient({
55
+ baseUrl: 'https://api.example.net', // the backend's origin
56
+ auth: 'token',
57
+ tokenStore: createMemoryTokenStore(), // the default; see "Token storage"
58
+ });
59
+
60
+ const { data, error } = await api.POST('/api/v1/login', {
61
+ body: { email: 'jane@example.com', password },
62
+ });
63
+
64
+ if (data && 'requires_2fa' in data) {
65
+ // 202: finish with the code the user types
66
+ await api.POST('/api/v1/login/2fa', { body: { temp_token: data.temp_token, code } });
67
+ } else if (data && 'requires_tenant_selection' in data) {
68
+ // the user belongs to several tenants: let them pick one
69
+ await api.POST('/api/v1/auth/select-tenant', {
70
+ body: { selection_token: data.selection_token, tenant_id: chosen.tenant_id },
71
+ });
72
+ }
73
+
74
+ const me = await api.GET('/api/v1/me'); // carries the bearer automatically
75
+ await api.POST('/api/v1/auth/logout'); // revokes both tokens, clears the store
76
+ ```
77
+
78
+ The client captures the token pair from login, 2FA, `select-tenant`,
79
+ `switch-tenant`, `refresh` and `PATCH /api/v1/me` responses into the store (a
80
+ changed email or password re-issues the pair), and clears it on logout.
81
+ You never handle the tokens yourself. A request that sets its own
82
+ `Authorization` header is sent as-is.
83
+
84
+ For a browser frontend on another origin, the backend must list that origin in
85
+ `CORS_ALLOWED_ORIGINS` (for example `CORS_ALLOWED_ORIGINS=https://portal.example.com`).
86
+ Native apps and servers send no `Origin` and need nothing extra.
87
+
88
+ #### Token storage
89
+
90
+ `tokenStore` is any object with `get()` and `set(tokens | null)`, either of which
91
+ may be async. The default keeps tokens in memory, so the session ends with the
92
+ page or process. The refresh token lasts days, so store it like a password: the
93
+ platform keychain on mobile, a server-side session for a web frontend. Never
94
+ `localStorage`, where any script on the page can read it.
95
+
96
+ ```ts
97
+ const tokenStore: TokenStore = {
98
+ get: () => SecureStore.getItemAsync('whity').then((v) => (v ? JSON.parse(v) : null)),
99
+ set: (t) => (t ? SecureStore.setItemAsync('whity', JSON.stringify(t)) : SecureStore.deleteItemAsync('whity')),
100
+ };
101
+ ```
102
+
103
+ #### Refresh
104
+
105
+ Access tokens last 15 minutes. On a `401` the client calls `/api/v1/auth/refresh`
106
+ once and replays the original request once; a second `401` is returned as-is, so
107
+ refresh loops are impossible. Requests that hit a `401` together share a single
108
+ refresh, because the refresh token rotates on every use and a second, parallel
109
+ refresh would present one the first just revoked. In token mode, a refresh the
110
+ server refuses clears the store (the session is over); a network failure leaves
111
+ it alone. A `401` from the sign-in endpoints themselves (a wrong password) is
112
+ never treated as an expired session.
113
+
114
+ ## Types
115
+
116
+ ```ts
117
+ import type { paths, components, operations } from '@whity/api-client';
118
+ ```
119
+
120
+ ## Tests
121
+
122
+ ```bash
123
+ npm test # node:test, no extra tooling
124
+ npm run typecheck # src, then src + tests
125
+ ```
126
+
127
+ ## Regenerating the schema
128
+
129
+ From this package (after the backend regenerates `public/openapi.json`):
130
+
131
+ ```bash
132
+ npm run generate
133
+ ```
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
- {
2
- "name": "@whity/api-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@whity/api-client",
3
+ "version": "0.2.0",
4
+ "description": "Typed client for the Whity API, generated from its OpenAPI spec.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/whity-org/whity-core.git",
9
+ "directory": "packages/api-client"
10
+ },
11
+ "type": "module",
12
+ "exports": {
13
+ ".": "./src/index.ts",
14
+ "./schema": "./src/schema.d.ts"
15
+ },
16
+ "types": "./src/index.ts",
17
+ "files": [
18
+ "src"
19
+ ],
20
+ "scripts": {
21
+ "generate": "openapi-typescript ../../public/openapi.json -o src/schema.d.ts",
22
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
23
+ "test": "node --experimental-strip-types --test \"test/*.test.ts\""
24
+ },
25
+ "dependencies": {
26
+ "openapi-fetch": "^0.17.0"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^26.6.5",
30
+ "openapi-typescript": "^7.13.0",
31
+ "typescript": "^5"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public",
35
+ "registry": "https://registry.npmjs.org"
36
+ }
37
+ }
package/src/index.ts ADDED
@@ -0,0 +1,286 @@
1
+ /**
2
+ * `@whity/api-client` — the typed client for the Whity API.
3
+ *
4
+ * The types are generated from the backend's OpenAPI spec (`public/openapi.json`)
5
+ * via `npm run generate`. Build a client with {@link createApiClient} and branch
6
+ * on `{ data, error, response }` — responses are never thrown; the shapes are
7
+ * derived from the spec.
8
+ *
9
+ * Two auth modes:
10
+ *
11
+ * - `'cookie'` (default, same as the Whity web app): every request carries
12
+ * `credentials: 'include'` (httpOnly cookies) and the `X-Requested-With` CSRF
13
+ * header. Needs the frontend and the API on the same site.
14
+ * - `'token'` (headless frontends on another site, native apps, servers): every
15
+ * request carries `X-Auth-Mode: token` and `Authorization: Bearer <access>`,
16
+ * never cookies. Tokens returned by the sign-in endpoints (and by `PATCH
17
+ * /me`, which re-issues them) are captured into a {@link TokenStore}
18
+ * automatically; logout clears it.
19
+ *
20
+ * In both modes a 401 triggers one POST to `/api/v1/auth/refresh` — shared by
21
+ * every request that hit the 401 at the same time — and the original request is
22
+ * replayed once (the replay bypasses the middleware, so refresh loops are
23
+ * structurally impossible).
24
+ *
25
+ * The default `baseUrl` is `''` — same-origin `/api/*`, e.g. behind a reverse
26
+ * proxy. A standalone frontend sets `baseUrl` to the backend's origin.
27
+ */
28
+ import createClient, { type Middleware } from 'openapi-fetch';
29
+ import type { paths } from './schema';
30
+
31
+ export type { paths, components, operations, webhooks } from './schema';
32
+
33
+ /** The access + refresh pair a token-mode sign-in returns. */
34
+ export interface AuthTokens {
35
+ accessToken: string;
36
+ refreshToken: string;
37
+ }
38
+
39
+ /**
40
+ * Where token mode keeps the session. Implement it over the platform keychain
41
+ * on mobile, or a server-side session for a web frontend — refresh tokens last
42
+ * days, so never over `localStorage`.
43
+ */
44
+ export interface TokenStore {
45
+ get(): AuthTokens | null | Promise<AuthTokens | null>;
46
+ /** `null` signs out (logout, or a refresh the server refused). */
47
+ set(tokens: AuthTokens | null): void | Promise<void>;
48
+ }
49
+
50
+ /** In-memory {@link TokenStore}: the session ends with the page or process. */
51
+ export function createMemoryTokenStore(initial: AuthTokens | null = null): TokenStore {
52
+ let tokens = initial;
53
+ return {
54
+ get: () => tokens,
55
+ set: (next) => {
56
+ tokens = next;
57
+ },
58
+ };
59
+ }
60
+
61
+ export interface CreateApiClientOptions {
62
+ /**
63
+ * Base URL prepended to the spec paths. Default `''` keeps `/api/*` requests
64
+ * same-origin (relative) so they can flow through a proxy that forwards
65
+ * cookies. A standalone frontend points this at the backend origin.
66
+ */
67
+ baseUrl?: string;
68
+ /** Injectable fetch (for tests / custom transports); defaults to global fetch. */
69
+ fetch?: (request: Request) => Promise<Response>;
70
+ /** `'cookie'` (default) or `'token'`; see the module docs. */
71
+ auth?: 'cookie' | 'token';
72
+ /** Token mode only: where tokens live. Defaults to {@link createMemoryTokenStore}. */
73
+ tokenStore?: TokenStore;
74
+ }
75
+
76
+ /** Endpoints that start or renew a session without an existing bearer. */
77
+ const SIGN_IN_PATHS = [
78
+ '/api/v1/login',
79
+ '/api/v1/login/2fa',
80
+ '/api/v1/auth/select-tenant',
81
+ '/api/v1/auth/refresh',
82
+ ];
83
+
84
+ /**
85
+ * Endpoints whose token-mode success body can carry a fresh token pair.
86
+ * `PATCH /me` is one: changing the email or password bumps the token epoch,
87
+ * so the pair the caller held stops working the moment it succeeds.
88
+ */
89
+ const ISSUING_PATHS = [...SIGN_IN_PATHS, '/api/v1/auth/switch-tenant', '/api/v1/me'];
90
+
91
+ const LOGOUT_PATH = '/api/v1/auth/logout';
92
+
93
+ /**
94
+ * Endpoints whose 401 means "wrong credentials", not "expired session" — a
95
+ * refresh cannot fix them, and refreshing on a refresh's own 401 would loop.
96
+ */
97
+ const NO_REFRESH_PATHS = [...SIGN_IN_PATHS, LOGOUT_PATH];
98
+
99
+ const pathOf = (request: Request): string => new URL(request.url, 'http://x').pathname;
100
+ const endsWithAny = (path: string, candidates: string[]): boolean =>
101
+ candidates.some((candidate) => path.endsWith(candidate));
102
+
103
+ /** The token pair in a token-mode response body, or null when it has none. */
104
+ async function readTokens(response: Response): Promise<AuthTokens | null> {
105
+ try {
106
+ const body: unknown = await response.clone().json();
107
+ if (typeof body !== 'object' || body === null) return null;
108
+ const { access_token: accessToken, refresh_token: refreshToken } = body as Record<string, unknown>;
109
+ return typeof accessToken === 'string' && typeof refreshToken === 'string'
110
+ ? { accessToken, refreshToken }
111
+ : null;
112
+ } catch {
113
+ return null;
114
+ }
115
+ }
116
+
117
+ export function createApiClient(options: CreateApiClientOptions = {}) {
118
+ const baseUrl = options.baseUrl ?? '';
119
+ const fetchFn =
120
+ options.fetch ?? ((request: Request) => globalThis.fetch(request));
121
+ const tokenMode = options.auth === 'token';
122
+ const store = options.tokenStore ?? createMemoryTokenStore();
123
+
124
+ /**
125
+ * Pristine clones of each in-flight request, keyed by openapi-fetch's
126
+ * per-request id — cloned BEFORE the first send so the body is replayable on
127
+ * the post-refresh retry; deleted on every response/error path so the map
128
+ * never outlives a request. Keep this middleware FIRST: if another middleware
129
+ * short-circuits onRequest before it, the clone for that id would leak.
130
+ * `sentToken` is the bearer the request went out with (token mode, and only
131
+ * when this client attached it) — `null` means the caller owns auth.
132
+ */
133
+ const pristine = new Map<string, { request: Request; sentToken: string | null }>();
134
+
135
+ /** The one refresh currently running, shared by every 401 that wants it. */
136
+ let refreshing: Promise<boolean> | null = null;
137
+
138
+ /** POST /api/v1/auth/refresh — true when the backend renewed the session. */
139
+ const refreshOnce = async (): Promise<boolean> => {
140
+ if (!tokenMode) {
141
+ try {
142
+ const response = await fetchFn(
143
+ new Request(`${baseUrl}/api/v1/auth/refresh`, {
144
+ method: 'POST',
145
+ credentials: 'include',
146
+ headers: { 'X-Requested-With': 'XMLHttpRequest' },
147
+ })
148
+ );
149
+ return response.ok;
150
+ } catch {
151
+ return false;
152
+ }
153
+ }
154
+
155
+ const current = await store.get();
156
+ if (current === null) return false;
157
+ let response: Response;
158
+ try {
159
+ response = await fetchFn(
160
+ new Request(`${baseUrl}/api/v1/auth/refresh`, {
161
+ method: 'POST',
162
+ credentials: 'omit',
163
+ headers: { 'Content-Type': 'application/json', 'X-Auth-Mode': 'token' },
164
+ body: JSON.stringify({ refresh_token: current.refreshToken }),
165
+ })
166
+ );
167
+ } catch {
168
+ // A network failure says nothing about the refresh token; keep it.
169
+ return false;
170
+ }
171
+ const renewed = response.ok ? await readTokens(response) : null;
172
+ if (renewed === null) {
173
+ // Refused (expired, revoked, rotated away): the session is over.
174
+ if (response.status === 401 || response.status === 403) await store.set(null);
175
+ return false;
176
+ }
177
+ await store.set(renewed);
178
+ return true;
179
+ };
180
+
181
+ const refresh = (): Promise<boolean> => {
182
+ refreshing ??= refreshOnce().finally(() => {
183
+ refreshing = null;
184
+ });
185
+ return refreshing;
186
+ };
187
+
188
+ const authMiddleware: Middleware = {
189
+ async onRequest({ request, id }) {
190
+ if (!request.headers.has('X-Requested-With')) {
191
+ request.headers.set('X-Requested-With', 'XMLHttpRequest');
192
+ }
193
+
194
+ let sentToken: string | null = null;
195
+ if (tokenMode) {
196
+ request.headers.set('X-Auth-Mode', 'token');
197
+ const tokens = await store.get();
198
+ if (!request.headers.has('Authorization') && tokens !== null) {
199
+ request.headers.set('Authorization', `Bearer ${tokens.accessToken}`);
200
+ sentToken = tokens.accessToken;
201
+ }
202
+ // Logout revokes only what it is shown. Without the refresh token in
203
+ // the body the bearer session ends but the refresh token stays usable
204
+ // for days, so hand it over unless the caller sent a body of their own.
205
+ if (
206
+ tokens !== null &&
207
+ request.method === 'POST' &&
208
+ request.body === null &&
209
+ pathOf(request).endsWith(LOGOUT_PATH)
210
+ ) {
211
+ const headers = new Headers(request.headers);
212
+ headers.set('Content-Type', 'application/json');
213
+ request = new Request(request, {
214
+ headers,
215
+ body: JSON.stringify({ refresh_token: tokens.refreshToken }),
216
+ });
217
+ }
218
+ }
219
+
220
+ pristine.set(id, { request: request.clone(), sentToken });
221
+ return request;
222
+ },
223
+ async onResponse({ request, response, id }) {
224
+ const entry = pristine.get(id);
225
+ pristine.delete(id);
226
+
227
+ const path = pathOf(request);
228
+ if (tokenMode) {
229
+ if (path.endsWith(LOGOUT_PATH)) {
230
+ await store.set(null);
231
+ return response;
232
+ }
233
+ if (response.ok && endsWithAny(path, ISSUING_PATHS)) {
234
+ const issued = await readTokens(response);
235
+ if (issued !== null) await store.set(issued);
236
+ return response;
237
+ }
238
+ }
239
+
240
+ if (response.status !== 401 || entry === undefined || endsWithAny(path, NO_REFRESH_PATHS)) {
241
+ return response;
242
+ }
243
+ if (tokenMode && entry.sentToken === null) {
244
+ // The caller supplied its own Authorization (or there was no session):
245
+ // a refresh of ours would not change what this request carries.
246
+ return response;
247
+ }
248
+
249
+ if (tokenMode) {
250
+ // Another request may have refreshed while this one was in flight;
251
+ // then the token it went out with is simply stale — replay, don't
252
+ // rotate the refresh token a second time.
253
+ const current = await store.get();
254
+ if (current === null || current.accessToken === entry.sentToken) {
255
+ if (!(await refresh())) return response;
256
+ }
257
+ } else if (!(await refresh())) {
258
+ return response;
259
+ }
260
+
261
+ // Replay the pristine original directly through fetch — NOT the client —
262
+ // so this middleware never sees it and cannot refresh twice.
263
+ const replay = entry.request;
264
+ if (tokenMode) {
265
+ const current = await store.get();
266
+ if (current === null) return response;
267
+ replay.headers.set('Authorization', `Bearer ${current.accessToken}`);
268
+ }
269
+ return fetchFn(replay);
270
+ },
271
+ async onError({ id }) {
272
+ pristine.delete(id);
273
+ },
274
+ };
275
+
276
+ const client = createClient<paths>({
277
+ baseUrl,
278
+ credentials: tokenMode ? 'omit' : 'include',
279
+ fetch: fetchFn,
280
+ });
281
+ client.use(authMiddleware);
282
+
283
+ return client;
284
+ }
285
+
286
+ export type ApiClient = ReturnType<typeof createApiClient>;