@bymax-one/nest-auth 1.0.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.
@@ -0,0 +1,347 @@
1
+ 'use strict';
2
+
3
+ var shared = require('@bymax-one/nest-auth/shared');
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var DEFAULT_HEADERS = Object.freeze({
8
+ "Content-Type": "application/json"
9
+ });
10
+ function shouldSkipRefreshOnUrl(url, suffixes) {
11
+ let pathname;
12
+ try {
13
+ pathname = new URL(url, "http://_placeholder").pathname;
14
+ } catch {
15
+ return false;
16
+ }
17
+ for (const suffix of suffixes) {
18
+ if (pathname.endsWith(suffix)) {
19
+ return true;
20
+ }
21
+ }
22
+ return false;
23
+ }
24
+ __name(shouldSkipRefreshOnUrl, "shouldSkipRefreshOnUrl");
25
+ function resolveRequestUrl(input, baseUrl) {
26
+ if (typeof input === "string") {
27
+ return baseUrl !== void 0 && !/^https?:\/\//i.test(input) ? `${baseUrl}${input}` : input;
28
+ }
29
+ if (input instanceof URL) {
30
+ return input.toString();
31
+ }
32
+ return input.url;
33
+ }
34
+ __name(resolveRequestUrl, "resolveRequestUrl");
35
+ function mergeHeaders(defaults, perRequest) {
36
+ const merged = {
37
+ ...defaults
38
+ };
39
+ if (perRequest === void 0) {
40
+ return merged;
41
+ }
42
+ const isUnsafeName = /* @__PURE__ */ __name((name) => name === "__proto__" || name === "constructor" || name === "prototype", "isUnsafeName");
43
+ if (Array.isArray(perRequest)) {
44
+ for (const [name, value] of perRequest) {
45
+ if (isUnsafeName(name)) continue;
46
+ merged[name] = value;
47
+ }
48
+ return merged;
49
+ }
50
+ if (typeof Headers !== "undefined" && perRequest instanceof Headers) {
51
+ perRequest.forEach((value, name) => {
52
+ if (isUnsafeName(name)) return;
53
+ merged[name] = value;
54
+ });
55
+ return merged;
56
+ }
57
+ for (const [name, value] of Object.entries(perRequest)) {
58
+ if (isUnsafeName(name) || typeof value !== "string") continue;
59
+ merged[name] = value;
60
+ }
61
+ return merged;
62
+ }
63
+ __name(mergeHeaders, "mergeHeaders");
64
+ function attachTimeout(init, timeoutMs) {
65
+ if (timeoutMs <= 0) {
66
+ return {
67
+ init,
68
+ cleanup: /* @__PURE__ */ __name(() => {
69
+ }, "cleanup")
70
+ };
71
+ }
72
+ const controller = new AbortController();
73
+ const timer = setTimeout(() => {
74
+ controller.abort();
75
+ }, timeoutMs);
76
+ const userSignal = init.signal;
77
+ if (userSignal != null) {
78
+ if (userSignal.aborted) {
79
+ controller.abort();
80
+ } else {
81
+ userSignal.addEventListener("abort", () => controller.abort(), {
82
+ once: true
83
+ });
84
+ }
85
+ }
86
+ return {
87
+ init: {
88
+ ...init,
89
+ signal: controller.signal
90
+ },
91
+ cleanup: /* @__PURE__ */ __name(() => clearTimeout(timer), "cleanup")
92
+ };
93
+ }
94
+ __name(attachTimeout, "attachTimeout");
95
+ async function performRefresh(endpoint, credentials) {
96
+ try {
97
+ const response = await fetch(endpoint, {
98
+ method: "POST",
99
+ credentials,
100
+ headers: {
101
+ "Content-Type": "application/json"
102
+ }
103
+ });
104
+ const ok = response.ok;
105
+ await response.body?.cancel().catch(
106
+ /* istanbul ignore next */
107
+ () => void 0
108
+ );
109
+ return ok;
110
+ } catch {
111
+ return false;
112
+ }
113
+ }
114
+ __name(performRefresh, "performRefresh");
115
+ function createAuthFetch(config = {}) {
116
+ const baseUrl = config.baseUrl;
117
+ const refreshEndpoint = config.refreshEndpoint ?? shared.AUTH_PROXY_ROUTES.clientRefresh;
118
+ const credentials = config.credentials ?? "include";
119
+ const defaultHeaders = config.defaultHeaders ? {
120
+ ...DEFAULT_HEADERS,
121
+ ...config.defaultHeaders
122
+ } : DEFAULT_HEADERS;
123
+ const onSessionExpired = config.onSessionExpired;
124
+ const timeoutMs = config.timeout ?? 3e4;
125
+ const skipRefreshSuffixes = shared.buildAuthRefreshSkipSuffixes(config.routePrefix);
126
+ let inFlightRefresh = null;
127
+ function getOrStartRefresh() {
128
+ if (inFlightRefresh !== null) {
129
+ return inFlightRefresh;
130
+ }
131
+ const attempt = performRefresh(refreshEndpoint, credentials).finally(() => {
132
+ inFlightRefresh = null;
133
+ });
134
+ inFlightRefresh = attempt;
135
+ return attempt;
136
+ }
137
+ __name(getOrStartRefresh, "getOrStartRefresh");
138
+ return /* @__PURE__ */ __name(async function authFetch(input, init) {
139
+ const initBase = {
140
+ ...init ?? {},
141
+ credentials,
142
+ headers: mergeHeaders(defaultHeaders, init?.headers)
143
+ };
144
+ const url = resolveRequestUrl(input, baseUrl);
145
+ const targetForFetch = (
146
+ // Stryker disable next-line ConditionalExpression: when baseUrl is undefined the ternary returns `input` regardless, so the guard's boolean is unobservable
147
+ baseUrl !== void 0 && typeof input === "string" ? url : input
148
+ );
149
+ const firstAttempt = attachTimeout(initBase, timeoutMs);
150
+ let response;
151
+ try {
152
+ response = await fetch(targetForFetch, firstAttempt.init);
153
+ } finally {
154
+ firstAttempt.cleanup();
155
+ }
156
+ if (response.status !== 401 || shouldSkipRefreshOnUrl(url, skipRefreshSuffixes)) {
157
+ return response;
158
+ }
159
+ const refreshed = await getOrStartRefresh();
160
+ if (!refreshed) {
161
+ try {
162
+ onSessionExpired?.();
163
+ } catch (err) {
164
+ console.warn("[nest-auth] onSessionExpired callback threw:", err);
165
+ }
166
+ return response;
167
+ }
168
+ const retryAttempt = attachTimeout(initBase, timeoutMs);
169
+ try {
170
+ return await fetch(targetForFetch, retryAttempt.init);
171
+ } finally {
172
+ retryAttempt.cleanup();
173
+ }
174
+ }, "authFetch");
175
+ }
176
+ __name(createAuthFetch, "createAuthFetch");
177
+ function normalizeBaseUrl(baseUrl) {
178
+ return baseUrl.replace(/\/+$/, "");
179
+ }
180
+ __name(normalizeBaseUrl, "normalizeBaseUrl");
181
+ function normalizeRoutePrefix(prefix) {
182
+ return prefix.replace(/^\/+|\/+$/g, "");
183
+ }
184
+ __name(normalizeRoutePrefix, "normalizeRoutePrefix");
185
+ function jsonBody(value) {
186
+ return JSON.stringify(value);
187
+ }
188
+ __name(jsonBody, "jsonBody");
189
+ function extractErrorBody(text) {
190
+ if (text.length === 0) return void 0;
191
+ try {
192
+ const parsed = JSON.parse(text);
193
+ return isAuthErrorBody(parsed) ? parsed : void 0;
194
+ } catch {
195
+ return void 0;
196
+ }
197
+ }
198
+ __name(extractErrorBody, "extractErrorBody");
199
+ function throwAuthError(response, text) {
200
+ const body = extractErrorBody(text);
201
+ const message = body?.message ?? `Request failed with status ${response.status}`;
202
+ throw new shared.AuthClientError(message, response.status, body);
203
+ }
204
+ __name(throwAuthError, "throwAuthError");
205
+ async function parseJsonOrThrow(response) {
206
+ const text = await response.text();
207
+ if (!response.ok) {
208
+ throwAuthError(response, text);
209
+ }
210
+ if (text.length === 0) {
211
+ throw new shared.AuthClientError(`Response from ${response.url} was empty \u2014 expected a JSON body`, response.status);
212
+ }
213
+ try {
214
+ return JSON.parse(text);
215
+ } catch {
216
+ throw new shared.AuthClientError(`Response from ${response.url} is not valid JSON`, response.status);
217
+ }
218
+ }
219
+ __name(parseJsonOrThrow, "parseJsonOrThrow");
220
+ async function expectNoContent(response) {
221
+ if (!response.ok) {
222
+ const text = await response.text();
223
+ throwAuthError(response, text);
224
+ }
225
+ await response.body?.cancel().catch(
226
+ /* istanbul ignore next */
227
+ () => void 0
228
+ );
229
+ }
230
+ __name(expectNoContent, "expectNoContent");
231
+ function isAuthErrorBody(value) {
232
+ if (typeof value !== "object" || value === null) return false;
233
+ const candidate = value;
234
+ return typeof candidate["message"] === "string" && typeof candidate["error"] === "string" && typeof candidate["statusCode"] === "number";
235
+ }
236
+ __name(isAuthErrorBody, "isAuthErrorBody");
237
+ function buildUrl(baseUrl, routePrefix, path) {
238
+ if (path.startsWith("/")) {
239
+ return `${baseUrl}${path}`;
240
+ }
241
+ return routePrefix.length > 0 ? `${baseUrl}/${routePrefix}/${path}` : `${baseUrl}/${path}`;
242
+ }
243
+ __name(buildUrl, "buildUrl");
244
+ function createAuthClient(config) {
245
+ const baseUrl = normalizeBaseUrl(config.baseUrl);
246
+ const routePrefix = normalizeRoutePrefix(config.routePrefix ?? "auth");
247
+ const authFetch = config.authFetch ?? createAuthFetch({
248
+ baseUrl,
249
+ routePrefix,
250
+ // Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — createAuthFetch coalesces each option with `??`/falsy checks downstream
251
+ ...config.refreshEndpoint !== void 0 ? {
252
+ refreshEndpoint: config.refreshEndpoint
253
+ } : {},
254
+ // Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
255
+ ...config.credentials !== void 0 ? {
256
+ credentials: config.credentials
257
+ } : {},
258
+ // Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
259
+ ...config.defaultHeaders !== void 0 ? {
260
+ defaultHeaders: config.defaultHeaders
261
+ } : {},
262
+ // Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
263
+ ...config.onSessionExpired !== void 0 ? {
264
+ onSessionExpired: config.onSessionExpired
265
+ } : {},
266
+ // Stryker disable next-line ConditionalExpression: spreading `{ key: undefined }` vs omitting the key is identical — the consumer coalesces this option downstream
267
+ ...config.timeout !== void 0 ? {
268
+ timeout: config.timeout
269
+ } : {}
270
+ });
271
+ const url = /* @__PURE__ */ __name((path) => buildUrl(baseUrl, routePrefix, path), "url");
272
+ async function post(path, body) {
273
+ const response = await authFetch(url(path), {
274
+ method: "POST",
275
+ body: jsonBody(body)
276
+ });
277
+ return parseJsonOrThrow(response);
278
+ }
279
+ __name(post, "post");
280
+ async function postNoContent(path, body) {
281
+ const response = await authFetch(url(path), {
282
+ method: "POST",
283
+ body: jsonBody(body)
284
+ });
285
+ await expectNoContent(response);
286
+ }
287
+ __name(postNoContent, "postNoContent");
288
+ async function get(path) {
289
+ const response = await authFetch(url(path), {
290
+ method: "GET"
291
+ });
292
+ return parseJsonOrThrow(response);
293
+ }
294
+ __name(get, "get");
295
+ return {
296
+ async login(input) {
297
+ return post(shared.AUTH_ROUTES.dashboard.login, input);
298
+ },
299
+ async register(data) {
300
+ return post(shared.AUTH_ROUTES.dashboard.register, data);
301
+ },
302
+ async logout() {
303
+ return postNoContent(shared.AUTH_ROUTES.dashboard.logout, {});
304
+ },
305
+ async refresh() {
306
+ return post(shared.AUTH_ROUTES.dashboard.refresh, {});
307
+ },
308
+ async getMe() {
309
+ return get(shared.AUTH_ROUTES.dashboard.me);
310
+ },
311
+ async mfaChallenge(tempToken, code) {
312
+ const result = await post(shared.AUTH_ROUTES.mfa.challenge, {
313
+ mfaTempToken: tempToken,
314
+ code
315
+ });
316
+ if ("mfaRequired" in result) {
317
+ throw new shared.AuthClientError("MFA challenge endpoint returned another challenge \u2014 server contract mismatch", 502);
318
+ }
319
+ return result;
320
+ },
321
+ async forgotPassword(email, tenantId) {
322
+ return postNoContent(shared.AUTH_ROUTES.password.forgotPassword, {
323
+ email,
324
+ tenantId
325
+ });
326
+ },
327
+ async resetPassword(input) {
328
+ const payload = {
329
+ email: input.email,
330
+ tenantId: input.tenantId,
331
+ newPassword: input.newPassword
332
+ };
333
+ if (input.token !== void 0) payload["token"] = input.token;
334
+ if (input.otp !== void 0) payload["otp"] = input.otp;
335
+ if (input.verifiedToken !== void 0) payload["verifiedToken"] = input.verifiedToken;
336
+ return postNoContent(shared.AUTH_ROUTES.password.resetPassword, payload);
337
+ }
338
+ };
339
+ }
340
+ __name(createAuthClient, "createAuthClient");
341
+
342
+ Object.defineProperty(exports, "AuthClientError", {
343
+ enumerable: true,
344
+ get: function () { return shared.AuthClientError; }
345
+ });
346
+ exports.createAuthClient = createAuthClient;
347
+ exports.createAuthFetch = createAuthFetch;
@@ -0,0 +1,301 @@
1
+ import { LoginResult, AuthResult, AuthUserClient } from '@bymax-one/nest-auth/shared';
2
+ export { AuthClientError, AuthErrorCode, AuthErrorResponse } from '@bymax-one/nest-auth/shared';
3
+
4
+ /**
5
+ * Fetch wrapper for the @bymax-one/nest-auth client subpath.
6
+ *
7
+ * Wraps the platform's native `fetch` so that consumer code can issue
8
+ * authenticated requests without manually:
9
+ *
10
+ * - attaching `credentials: 'include'` on every call,
11
+ * - intercepting 401 responses to attempt a transparent refresh,
12
+ * - retrying the original request after a successful refresh,
13
+ * - de-duplicating concurrent refresh attempts (single-flight),
14
+ * - or notifying the application when the session is irrecoverable.
15
+ *
16
+ * Zero runtime dependencies: relies only on the global `fetch` and the
17
+ * stable constants exported from `@bymax-one/nest-auth/shared`.
18
+ */
19
+ /**
20
+ * Configuration options for {@link createAuthFetch}.
21
+ *
22
+ * Every field is optional so that the default factory output works
23
+ * out-of-the-box against a same-domain Next.js proxy. Override only
24
+ * what your deployment actually needs to change.
25
+ */
26
+ interface AuthFetchConfig {
27
+ /**
28
+ * Optional base URL prepended to relative request URLs.
29
+ *
30
+ * When omitted, relative URLs (`/api/users`) are passed to `fetch`
31
+ * verbatim — appropriate for browser environments where the request
32
+ * is naturally same-origin. Provide this in non-browser contexts
33
+ * (Node-side server components, tests, mobile apps) so that the
34
+ * URL parsing in the skip-list logic can operate on a full URL.
35
+ */
36
+ baseUrl?: string;
37
+ /**
38
+ * Pathname or full URL of the refresh endpoint.
39
+ *
40
+ * Default: {@link AUTH_PROXY_ROUTES.clientRefresh}
41
+ * (`/api/auth/client-refresh`). Replace this when your application
42
+ * exposes the refresh endpoint at a non-default path.
43
+ */
44
+ refreshEndpoint?: string;
45
+ /**
46
+ * Credentials policy for every issued request.
47
+ *
48
+ * Default: `'include'`. Set to `'same-origin'` for same-origin
49
+ * deployments that want to avoid CORS preflights, or to `'omit'`
50
+ * when working with bearer-only deployments that do not use cookies.
51
+ */
52
+ credentials?: RequestCredentials;
53
+ /**
54
+ * Headers merged into every request.
55
+ *
56
+ * Default: `{ 'Content-Type': 'application/json' }`. Headers passed
57
+ * per-request in `fetch(..., { headers })` override these.
58
+ */
59
+ defaultHeaders?: Record<string, string>;
60
+ /**
61
+ * Callback invoked when a refresh attempt fails irrecoverably.
62
+ *
63
+ * Wire this to a UI redirect, a state-store reset, or a logout
64
+ * helper. The callback runs before the auth-fetched promise
65
+ * rejects, so consumers can rely on side effects having happened.
66
+ */
67
+ onSessionExpired?: () => void;
68
+ /**
69
+ * Per-request timeout in milliseconds.
70
+ *
71
+ * Default: `30_000` (30s). Pass `0` to disable the timeout.
72
+ * Disabling is appropriate for long-poll endpoints; for normal
73
+ * requests keep the default to avoid hanging UIs on slow networks.
74
+ */
75
+ timeout?: number;
76
+ /**
77
+ * NestJS `routePrefix` the upstream auth server is mounted under.
78
+ *
79
+ * Used to compose the pathname-suffix skip list so that 401s from
80
+ * credential-issuing endpoints (login, refresh, mfa/challenge, …)
81
+ * are NOT retried after a refresh attempt. Default: `'auth'`.
82
+ * Set this explicitly when the server uses a non-default prefix
83
+ * (e.g. `'authentication'`, `'api/v1/auth'`) or 401 retries will
84
+ * misfire on those endpoints.
85
+ */
86
+ routePrefix?: string;
87
+ }
88
+ /**
89
+ * The fetch-compatible function returned by {@link createAuthFetch}.
90
+ *
91
+ * Has the same signature as the native `fetch` but applies the
92
+ * configured credentials, headers, refresh interception, and retry.
93
+ *
94
+ * @remarks
95
+ * Passing a {@link Request} object whose body is a stream is not
96
+ * supported when the request may be retried after a refresh —
97
+ * `Request` body streams can only be read once, and the retry will
98
+ * fail with `TypeError: body already used`. Prefer passing a URL
99
+ * string plus an `init` with a string/`FormData`/`URLSearchParams`
100
+ * body, which can be re-sent safely. This restriction does not
101
+ * apply to GET/HEAD requests or to requests that do not receive a
102
+ * 401 response.
103
+ */
104
+ type AuthFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
105
+ /**
106
+ * Create a configured fetch wrapper with cookie- and refresh-aware
107
+ * behavior baked in.
108
+ *
109
+ * @example
110
+ * ```ts
111
+ * const authFetch = createAuthFetch({
112
+ * baseUrl: 'https://api.example.com',
113
+ * onSessionExpired: () => router.push('/sign-in')
114
+ * })
115
+ *
116
+ * const response = await authFetch('/api/users')
117
+ * ```
118
+ */
119
+ declare function createAuthFetch(config?: AuthFetchConfig): AuthFetch;
120
+
121
+ /**
122
+ * Typed authentication client for the @bymax-one/nest-auth library.
123
+ *
124
+ * Wraps {@link createAuthFetch} with method-shaped helpers for every
125
+ * standard auth flow (login, register, logout, refresh, getMe, MFA
126
+ * challenge, password reset). Designed for the cookie-mode default —
127
+ * HttpOnly cookies do the actual authentication, the methods just
128
+ * compose the right URL, body, and method verb.
129
+ *
130
+ * Zero runtime dependencies beyond `fetch` and the shared subpath.
131
+ */
132
+
133
+ /**
134
+ * Configuration accepted by {@link createAuthClient}.
135
+ *
136
+ * Same surface as {@link AuthFetchConfig} plus a required `baseUrl` —
137
+ * the typed client always issues requests to a known server origin so
138
+ * the per-method URL composition is unambiguous.
139
+ */
140
+ interface AuthClientConfig extends Omit<AuthFetchConfig, 'baseUrl'> {
141
+ /**
142
+ * Absolute base URL of the @bymax-one/nest-auth server
143
+ * (e.g. `'https://api.example.com'`). The trailing slash is
144
+ * optional; both forms are normalized internally.
145
+ */
146
+ baseUrl: string;
147
+ /**
148
+ * Optional route prefix mounted by the consumer's NestJS app. When
149
+ * the server uses a non-default `routePrefix`, mirror it here so
150
+ * that the client targets the right URLs. Default: `'auth'`.
151
+ */
152
+ routePrefix?: string;
153
+ /**
154
+ * Optional pre-built fetch wrapper. When provided, the client uses
155
+ * this wrapper instead of building one from `baseUrl`/`credentials`/
156
+ * `defaultHeaders`. Useful for tests or for sharing a single
157
+ * wrapper across multiple clients (dashboard + platform).
158
+ */
159
+ authFetch?: AuthFetch;
160
+ }
161
+ /**
162
+ * Payload accepted by {@link AuthClient.register}.
163
+ *
164
+ * Mirrors the `RegisterDto` exposed by the server controller. Field
165
+ * names match exactly so consumers can spread an existing form state
166
+ * into the call without renaming.
167
+ */
168
+ interface RegisterInput {
169
+ /** User's primary email address. */
170
+ email: string;
171
+ /** Plaintext password — server hashes immediately on receipt. */
172
+ password: string;
173
+ /** Display name. */
174
+ name: string;
175
+ /** Tenant identifier scoping the new account. */
176
+ tenantId: string;
177
+ }
178
+ /**
179
+ * Payload accepted by {@link AuthClient.login}.
180
+ *
181
+ * `tenantId` is required because the server-side `LoginDto` enforces it
182
+ * with `@IsNotEmpty()`. Multi-tenant deployments use it to scope the
183
+ * credential lookup; single-tenant deployments must still supply a
184
+ * stable identifier (commonly `'default'`).
185
+ */
186
+ interface LoginInput {
187
+ /** User's primary email address. */
188
+ email: string;
189
+ /** Plaintext password — server hashes immediately on receipt. */
190
+ password: string;
191
+ /** Tenant identifier the login attempt is scoped to. */
192
+ tenantId: string;
193
+ }
194
+ /**
195
+ * Fields shared by every reset-password flow.
196
+ *
197
+ * The wire-shape variants below extend this and add exactly one of
198
+ * `token`, `otp`, or `verifiedToken` — TypeScript then rejects calls
199
+ * that try to combine them.
200
+ */
201
+ interface ResetPasswordBase {
202
+ /** Email address of the account being reset. */
203
+ email: string;
204
+ /** Tenant the account belongs to. */
205
+ tenantId: string;
206
+ /** New plaintext password — server hashes immediately. Min 8 chars, max 128. */
207
+ newPassword: string;
208
+ }
209
+ /**
210
+ * Payload accepted by {@link AuthClient.resetPassword}.
211
+ *
212
+ * Discriminated union: callers must supply exactly one of `token`,
213
+ * `otp`, or `verifiedToken`. The server's `ResetPasswordDto`
214
+ * cross-validates the choice; the union shape lifts that constraint
215
+ * into the type system so misuse is caught at compile time rather
216
+ * than as a runtime 400.
217
+ */
218
+ type ResetPasswordInput = (ResetPasswordBase & {
219
+ token: string;
220
+ otp?: never;
221
+ verifiedToken?: never;
222
+ }) | (ResetPasswordBase & {
223
+ otp: string;
224
+ token?: never;
225
+ verifiedToken?: never;
226
+ }) | (ResetPasswordBase & {
227
+ verifiedToken: string;
228
+ token?: never;
229
+ otp?: never;
230
+ });
231
+ /**
232
+ * Public method surface of the typed auth client.
233
+ */
234
+ interface AuthClient {
235
+ /**
236
+ * Submit credentials and receive either a full {@link AuthResult}
237
+ * or an {@link MfaChallengeResult} when the account requires MFA.
238
+ *
239
+ * @returns A discriminated {@link LoginResult} — branch on
240
+ * `'mfaRequired' in result` to handle the MFA case.
241
+ */
242
+ login(input: LoginInput): Promise<LoginResult>;
243
+ /**
244
+ * Register a new local account. The server may auto-login on
245
+ * success or require email verification before login is permitted,
246
+ * depending on `emailVerification.required`.
247
+ */
248
+ register(data: RegisterInput): Promise<AuthResult>;
249
+ /** Revoke the current session and clear the auth cookies server-side. */
250
+ logout(): Promise<void>;
251
+ /**
252
+ * Manually rotate the refresh token. The auto-refresh in
253
+ * {@link createAuthFetch} handles this automatically on 401, so
254
+ * call this only for explicit refresh flows.
255
+ */
256
+ refresh(): Promise<AuthResult>;
257
+ /** Fetch the currently authenticated user. */
258
+ getMe(): Promise<AuthUserClient>;
259
+ /**
260
+ * Complete an MFA challenge by submitting the temp token returned
261
+ * from `login` together with either a 6-digit TOTP code or a
262
+ * recovery code in `xxxx-xxxx-xxxx` format.
263
+ */
264
+ mfaChallenge(tempToken: string, code: string): Promise<AuthResult>;
265
+ /**
266
+ * Initiate a password reset. The server returns 200 regardless of
267
+ * whether the email is registered — the response carries no signal
268
+ * either way (anti-enumeration design). Both `email` and `tenantId`
269
+ * are required by the server DTO.
270
+ */
271
+ forgotPassword(email: string, tenantId: string): Promise<void>;
272
+ /**
273
+ * Submit a new password using one of the three reset flows:
274
+ * token, OTP, or verified-token. See {@link ResetPasswordInput}
275
+ * for the mutual-exclusivity rule.
276
+ */
277
+ resetPassword(input: ResetPasswordInput): Promise<void>;
278
+ }
279
+ /**
280
+ * Build a typed {@link AuthClient} bound to a specific server.
281
+ *
282
+ * @example
283
+ * ```ts
284
+ * const auth = createAuthClient({
285
+ * baseUrl: 'https://api.example.com',
286
+ * onSessionExpired: () => router.push('/sign-in')
287
+ * })
288
+ *
289
+ * const result = await auth.login({
290
+ * email: 'user@example.com',
291
+ * password: 'pw',
292
+ * tenantId: 'default'
293
+ * })
294
+ * if ('mfaRequired' in result) {
295
+ * const final = await auth.mfaChallenge(result.mfaTempToken, '123456')
296
+ * }
297
+ * ```
298
+ */
299
+ declare function createAuthClient(config: AuthClientConfig): AuthClient;
300
+
301
+ export { type AuthClient, type AuthClientConfig, type AuthFetch, type AuthFetchConfig, type LoginInput, type RegisterInput, type ResetPasswordInput, createAuthClient, createAuthFetch };