@plinthjs/auth 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.
@@ -0,0 +1,698 @@
1
+ import { Request, Response, HttpException, Middleware } from '@plinthjs/http';
2
+ import { Session } from '@plinthjs/session';
3
+ import { Hasher } from '@plinthjs/encryption';
4
+
5
+ /**
6
+ * Authentication contracts — the Laravel `Illuminate\Contracts\Auth` interfaces. {@link Authenticatable}
7
+ * is a user that can be authenticated; {@link UserProvider} retrieves and validates users from
8
+ * storage; {@link Guard} reads who the current user is; {@link StatefulGuard} also logs them in/out.
9
+ */
10
+ /** A user that can be authenticated. The Laravel `Authenticatable` contract. */
11
+ interface Authenticatable {
12
+ /** The unique identifier (primary key) for the user. */
13
+ getAuthIdentifier(): string | number;
14
+ /** The name of the identifier field (e.g. `id`). */
15
+ getAuthIdentifierName(): string;
16
+ /** The hashed password used to validate credentials. */
17
+ getAuthPassword(): string;
18
+ }
19
+ /** Login credentials — typically `{ email, password }`. */
20
+ type Credentials = Record<string, unknown>;
21
+ /** A user that supports "remember me" persistence (the Laravel remember-token methods). */
22
+ interface Rememberable {
23
+ /** The persisted remember-me token, or `null` if none. */
24
+ getRememberToken(): string | null;
25
+ /** Persist (in memory) a new remember-me token. */
26
+ setRememberToken(token: string): void;
27
+ }
28
+ /**
29
+ * A user whose password hash can be replaced — the persist seam used by
30
+ * {@link UserProvider.rehashPasswordIfRequired} (mirrors how remember tokens are persisted).
31
+ */
32
+ interface PasswordUpdatable {
33
+ /** Persist (in memory) a new password hash. */
34
+ setAuthPassword(hashed: string): void;
35
+ }
36
+ /**
37
+ * A structural event-dispatcher seam — the `Illuminate\Contracts\Events\Dispatcher` shape the auth
38
+ * layer needs. Any object with a `dispatch(event)` method satisfies it (e.g. `@plinthjs/events`),
39
+ * without this package importing an event implementation. When no dispatcher is provided the guards
40
+ * and brokers dispatch nothing, at zero overhead.
41
+ */
42
+ interface AuthEvents {
43
+ /** Dispatch an auth event object to its listeners. */
44
+ dispatch(event: object): void;
45
+ }
46
+ /** Retrieves and validates users from storage. The Laravel `UserProvider` contract. */
47
+ interface UserProvider {
48
+ /** Find a user by primary key, or `null`. */
49
+ retrieveById(identifier: string | number): Promise<Authenticatable | null>;
50
+ /** Find a user by primary key whose remember-me token matches, or `null` (constant-time). */
51
+ retrieveByToken(identifier: string | number, token: string): Promise<Authenticatable | null>;
52
+ /** Persist a new remember-me token for `user`. */
53
+ updateRememberToken(user: Authenticatable, token: string): Promise<void>;
54
+ /** Find a user matching the non-password credentials, or `null`. */
55
+ retrieveByCredentials(credentials: Credentials): Promise<Authenticatable | null>;
56
+ /** Whether `credentials` validate against `user` (constant-time password check). */
57
+ validateCredentials(user: Authenticatable, credentials: Credentials): Promise<boolean>;
58
+ /**
59
+ * Re-hash and persist the user's password when the hash's cost parameters are stale (or always,
60
+ * when `force` is set) — the Laravel 11+ `rehashPasswordIfRequired` provider method. Optional so
61
+ * existing providers keep compiling; guards call it through optional chaining.
62
+ */
63
+ rehashPasswordIfRequired?(user: Authenticatable, credentials: Credentials, force?: boolean): Promise<void>;
64
+ }
65
+ /** A read-only authentication guard. The Laravel `Guard` contract. */
66
+ interface Guard {
67
+ /** Whether a user is authenticated. */
68
+ check(): Promise<boolean>;
69
+ /** Whether no user is authenticated. */
70
+ guest(): Promise<boolean>;
71
+ /** The authenticated user, or `null`. */
72
+ user(): Promise<Authenticatable | null>;
73
+ /** The authenticated user's identifier, or `null`. */
74
+ id(): Promise<string | number | null>;
75
+ /** Whether the credentials are valid, without logging anyone in. */
76
+ validate(credentials: Credentials): Promise<boolean>;
77
+ /** Set the current user explicitly (e.g. after registration). */
78
+ setUser(user: Authenticatable): void;
79
+ }
80
+ /** A guard that can also log users in and out across requests. The Laravel `StatefulGuard`. */
81
+ interface StatefulGuard extends Guard {
82
+ /** Validate credentials and, on success, log the user in. */
83
+ attempt(credentials: Credentials): Promise<boolean>;
84
+ /** Validate credentials and set the user for this request only (no persistence). */
85
+ once(credentials: Credentials): Promise<boolean>;
86
+ /** Log a user in (persist their id). */
87
+ login(user: Authenticatable): void;
88
+ /** Log in by identifier, returning the user (or `null` if unknown). */
89
+ loginUsingId(id: string | number): Promise<Authenticatable | null>;
90
+ /**
91
+ * Log the current user out. Session storage is cleared synchronously; implementations may return
92
+ * a promise for asynchronous teardown (e.g. cycling the remember token through the provider).
93
+ */
94
+ logout(): void | Promise<void>;
95
+ }
96
+
97
+ /** A user whose email address can be verified. The Laravel `MustVerifyEmail` contract. */
98
+ interface MustVerifyEmail {
99
+ /** The email address being verified. */
100
+ getEmailForVerification(): string;
101
+ /** Whether the email has already been verified. */
102
+ hasVerifiedEmail(): boolean;
103
+ /** Mark the email as verified (persist `email_verified_at`). */
104
+ markEmailAsVerified(): void | Promise<void>;
105
+ }
106
+ /** A verifiable user — an {@link Authenticatable} that also implements {@link MustVerifyEmail}. */
107
+ type VerifiableUser = Authenticatable & MustVerifyEmail;
108
+ /** A signed, expiring verification payload — what a verification link carries. */
109
+ interface VerificationSignature {
110
+ /** Expiry as epoch milliseconds. */
111
+ expires: number;
112
+ /** HMAC signature over the user id, email hash, and expiry. */
113
+ signature: string;
114
+ }
115
+ /** Options for {@link EmailVerifier}. */
116
+ interface EmailVerifierOptions {
117
+ /** Secret key the verification payload is HMAC-signed with. */
118
+ secret: string;
119
+ /** Link lifetime in minutes. Default `60`. */
120
+ expireMinutes?: number;
121
+ /** Injected clock for deterministic expiry. Default `() => new Date()`. */
122
+ now?: () => Date;
123
+ /** Optional event dispatcher; `Verified` is dispatched when a user is first verified. */
124
+ events?: AuthEvents;
125
+ }
126
+ /** Mints and checks signed, expiring email-verification payloads. */
127
+ declare class EmailVerifier {
128
+ private readonly secret;
129
+ private readonly expireMinutes;
130
+ private readonly now;
131
+ private readonly events;
132
+ constructor(options: EmailVerifierOptions);
133
+ /** A stable hash of the user's email — proves the link was issued for this exact address. */
134
+ hashFor(user: VerifiableUser): string;
135
+ /** Build a signed, expiring verification payload for `user` (embed it in the verification URL). */
136
+ sign(user: VerifiableUser): VerificationSignature;
137
+ /** Whether `payload` is a valid, unexpired signature for `user`'s current email. */
138
+ isValid(user: VerifiableUser, payload: VerificationSignature): boolean;
139
+ /**
140
+ * Verify a payload and mark the user verified. Returns `false` on a bad or expired signature;
141
+ * idempotent — an already-verified user returns `true` without re-marking.
142
+ */
143
+ verify(user: VerifiableUser, payload: VerificationSignature): Promise<boolean>;
144
+ /** The HMAC binding the user id, email hash, and expiry. */
145
+ private signature;
146
+ }
147
+
148
+ /**
149
+ * Authentication events — the Laravel `Illuminate\Auth\Events` classes. Guards and brokers dispatch
150
+ * these through the optional {@link AuthEvents} seam at the same moments Laravel fires them:
151
+ * {@link Attempting} before a credential attempt, {@link Validated} once credentials check out,
152
+ * {@link Login} + {@link Authenticated} when a user is logged in / set on the guard, {@link Failed}
153
+ * on a bad attempt, {@link Logout} / {@link CurrentDeviceLogout} / {@link OtherDeviceLogout} on the
154
+ * logout variants, and {@link Registered} / {@link Verified} / {@link PasswordReset} /
155
+ * {@link Lockout} around the account lifecycle. Plain classes with readonly data — dispatchable
156
+ * through any dispatcher that takes an object.
157
+ */
158
+
159
+ /** Fired before every credential attempt — the Laravel `Attempting` event. */
160
+ declare class Attempting {
161
+ /** The guard name the attempt runs on. */
162
+ readonly guard: string;
163
+ /** The credentials being attempted (includes the plaintext password — handle with care). */
164
+ readonly credentials: Credentials;
165
+ /** Whether the attempt asked for "remember me" persistence. */
166
+ readonly remember: boolean;
167
+ constructor(
168
+ /** The guard name the attempt runs on. */
169
+ guard: string,
170
+ /** The credentials being attempted (includes the plaintext password — handle with care). */
171
+ credentials: Credentials,
172
+ /** Whether the attempt asked for "remember me" persistence. */
173
+ remember?: boolean);
174
+ }
175
+ /** Fired when credentials validate against a user — the Laravel `Validated` event. */
176
+ declare class Validated {
177
+ /** The guard name the validation ran on. */
178
+ readonly guard: string;
179
+ /** The user the credentials validated against. */
180
+ readonly user: Authenticatable;
181
+ constructor(
182
+ /** The guard name the validation ran on. */
183
+ guard: string,
184
+ /** The user the credentials validated against. */
185
+ user: Authenticatable);
186
+ }
187
+ /** Fired when a user is logged in for the session — the Laravel `Login` event. */
188
+ declare class Login {
189
+ /** The guard name the login happened on. */
190
+ readonly guard: string;
191
+ /** The user that logged in. */
192
+ readonly user: Authenticatable;
193
+ /** Whether the login came from a remember-me recaller. */
194
+ readonly remember: boolean;
195
+ constructor(
196
+ /** The guard name the login happened on. */
197
+ guard: string,
198
+ /** The user that logged in. */
199
+ user: Authenticatable,
200
+ /** Whether the login came from a remember-me recaller. */
201
+ remember: boolean);
202
+ }
203
+ /** Fired whenever a user is set on a guard — the Laravel `Authenticated` event. */
204
+ declare class Authenticated {
205
+ /** The guard name the user was set on. */
206
+ readonly guard: string;
207
+ /** The user that is now authenticated. */
208
+ readonly user: Authenticatable;
209
+ constructor(
210
+ /** The guard name the user was set on. */
211
+ guard: string,
212
+ /** The user that is now authenticated. */
213
+ user: Authenticatable);
214
+ }
215
+ /** Fired when a credential attempt fails — the Laravel `Failed` event. */
216
+ declare class Failed {
217
+ /** The guard name the attempt ran on. */
218
+ readonly guard: string;
219
+ /** The user the credentials matched, or `null` when no user was found. */
220
+ readonly user: Authenticatable | null;
221
+ /** The credentials that failed. */
222
+ readonly credentials: Credentials;
223
+ constructor(
224
+ /** The guard name the attempt ran on. */
225
+ guard: string,
226
+ /** The user the credentials matched, or `null` when no user was found. */
227
+ user: Authenticatable | null,
228
+ /** The credentials that failed. */
229
+ credentials: Credentials);
230
+ }
231
+ /** Fired when the user logs out (remember token cycled) — the Laravel `Logout` event. */
232
+ declare class Logout {
233
+ /** The guard name the logout happened on. */
234
+ readonly guard: string;
235
+ /** The user that logged out. */
236
+ readonly user: Authenticatable;
237
+ constructor(
238
+ /** The guard name the logout happened on. */
239
+ guard: string,
240
+ /** The user that logged out. */
241
+ user: Authenticatable);
242
+ }
243
+ /** Fired on a current-device-only logout — the Laravel `CurrentDeviceLogout` event. */
244
+ declare class CurrentDeviceLogout {
245
+ /** The guard name the logout happened on. */
246
+ readonly guard: string;
247
+ /** The user that logged out on this device. */
248
+ readonly user: Authenticatable;
249
+ constructor(
250
+ /** The guard name the logout happened on. */
251
+ guard: string,
252
+ /** The user that logged out on this device. */
253
+ user: Authenticatable);
254
+ }
255
+ /** Fired when the user's other devices are logged out — the Laravel `OtherDeviceLogout` event. */
256
+ declare class OtherDeviceLogout {
257
+ /** The guard name the logout happened on. */
258
+ readonly guard: string;
259
+ /** The user whose other sessions were invalidated. */
260
+ readonly user: Authenticatable;
261
+ constructor(
262
+ /** The guard name the logout happened on. */
263
+ guard: string,
264
+ /** The user whose other sessions were invalidated. */
265
+ user: Authenticatable);
266
+ }
267
+ /** Fired when a new account is registered (dispatched by application code) — the Laravel `Registered` event. */
268
+ declare class Registered {
269
+ /** The freshly registered user. */
270
+ readonly user: Authenticatable;
271
+ constructor(
272
+ /** The freshly registered user. */
273
+ user: Authenticatable);
274
+ }
275
+ /** Fired when a user's email address is verified — the Laravel `Verified` event. */
276
+ declare class Verified {
277
+ /** The user whose email was just verified. */
278
+ readonly user: Authenticatable;
279
+ constructor(
280
+ /** The user whose email was just verified. */
281
+ user: Authenticatable);
282
+ }
283
+ /** Fired when a password is reset through the broker — the Laravel `PasswordReset` event. */
284
+ declare class PasswordReset {
285
+ /** The user whose password was reset. */
286
+ readonly user: Authenticatable;
287
+ constructor(
288
+ /** The user whose password was reset. */
289
+ user: Authenticatable);
290
+ }
291
+ /**
292
+ * Fired when login attempts are rate-limited — the Laravel `Lockout` event. Laravel carries the
293
+ * HTTP request; Mason carries the credentials that triggered the lockout (dispatched by whatever
294
+ * rate-limiting layer the application wires up).
295
+ */
296
+ declare class Lockout {
297
+ /** The credentials whose attempts were locked out. */
298
+ readonly credentials: Credentials;
299
+ constructor(
300
+ /** The credentials whose attempts were locked out. */
301
+ credentials: Credentials);
302
+ }
303
+
304
+ /**
305
+ * Session key holding the hash of the authenticated user's password — the Laravel
306
+ * `AuthenticateSession` mechanism. The session middleware compares it against the user's current
307
+ * hash each request, so {@link SessionGuard.logoutOtherDevices} (which re-hashes the password)
308
+ * invalidates every other session while this one is kept in step.
309
+ */
310
+ declare const PASSWORD_HASH_SESSION_KEY = "auth.password_hash";
311
+ /** An `attemptWhen` callback — runs after credential validation; all must return `true` to log in. */
312
+ type AttemptCallback = (user: Authenticatable, guard: SessionGuard) => boolean | Promise<boolean>;
313
+ /** Options for {@link SessionGuard}. */
314
+ interface SessionGuardOptions {
315
+ /** Guard name carried on dispatched events. Default `'web'`. */
316
+ name?: string;
317
+ /** The current request — required only for the HTTP Basic helpers. */
318
+ request?: Request;
319
+ /** Optional event dispatcher; when unset no events are dispatched. */
320
+ events?: AuthEvents;
321
+ }
322
+ /** Session-backed, stateful guard. The Laravel `SessionGuard` equivalent. */
323
+ declare class SessionGuard implements StatefulGuard {
324
+ private readonly provider;
325
+ private readonly session;
326
+ private readonly key;
327
+ private cachedUser;
328
+ private resolved;
329
+ private lastAttempted;
330
+ private viaRememberFlag;
331
+ private rememberDuration;
332
+ private request;
333
+ private readonly name;
334
+ private readonly events;
335
+ constructor(provider: UserProvider, session: Session, key?: string, options?: SessionGuardOptions);
336
+ user(): Promise<Authenticatable | null>;
337
+ check(): Promise<boolean>;
338
+ guest(): Promise<boolean>;
339
+ id(): Promise<string | number | null>;
340
+ validate(credentials: Credentials): Promise<boolean>;
341
+ attempt(credentials: Credentials): Promise<boolean>;
342
+ /**
343
+ * Attempt to authenticate with additional callbacks — the Laravel `attemptWhen`. The callbacks
344
+ * run after the credentials validate, receiving the user and this guard; every one must return
345
+ * `true` (a falsy result fails the attempt without logging the user in).
346
+ */
347
+ attemptWhen(credentials: Credentials, callbacks?: AttemptCallback | readonly AttemptCallback[]): Promise<boolean>;
348
+ once(credentials: Credentials): Promise<boolean>;
349
+ login(user: Authenticatable): void;
350
+ loginUsingId(id: string | number): Promise<Authenticatable | null>;
351
+ /**
352
+ * Log the current user out, cycling the remember token so every recaller dies — the Laravel
353
+ * `logout`. The session keys are cleared synchronously; the returned promise resolves once the
354
+ * token has been cycled through the provider and the `Logout` event dispatched.
355
+ */
356
+ logout(): Promise<void>;
357
+ /**
358
+ * Log the current user out on this device only — the Laravel `logoutCurrentDevice`. Unlike
359
+ * {@link SessionGuard.logout} the remember token is *not* cycled, so other remembered devices
360
+ * stay logged in. Dispatches `CurrentDeviceLogout`.
361
+ */
362
+ logoutCurrentDevice(): Promise<void>;
363
+ /**
364
+ * Invalidate the user's sessions on every other device — the Laravel `logoutOtherDevices`.
365
+ * Validates `password` against the current user (throwing when it does not match), then:
366
+ *
367
+ * - force re-hashes the password through {@link UserProvider.rehashPasswordIfRequired} (when the
368
+ * provider supports it) and refreshes this session's stored password hash, so any session
369
+ * checked by `authenticateSession` whose stored hash is now stale is logged out — the same
370
+ * session-password-hash mechanism Laravel's `AuthenticateSession` middleware uses; and
371
+ * - cycles the remember token, killing every previously issued recaller cookie.
372
+ *
373
+ * Returns the fresh recaller value for *this* device (the Laravel `queueRecallerCookie`
374
+ * re-issue), or `null` when nobody is authenticated.
375
+ */
376
+ logoutOtherDevices(password: string): Promise<string | null>;
377
+ setUser(user: Authenticatable): void;
378
+ /** Set the current request (used by the HTTP Basic helpers). The `setRequest` equivalent. */
379
+ setRequest(request: Request): this;
380
+ /** The last user a credential attempt resolved, or `null`. The `getLastAttempted` equivalent. */
381
+ getLastAttempted(): Authenticatable | null;
382
+ /** Whether the current user was authenticated via a remember-me recaller. The `viaRemember` equivalent. */
383
+ viaRemember(): boolean;
384
+ /**
385
+ * Set how long (in minutes) issued recaller cookies should live — the `setRememberDuration`
386
+ * equivalent. The guard does not write cookies itself; read it back via
387
+ * {@link SessionGuard.getRememberDuration} when turning a recaller value into a cookie.
388
+ */
389
+ setRememberDuration(minutes: number): this;
390
+ /** The "remember me" cookie lifetime in minutes. The `getRememberDuration` equivalent. */
391
+ getRememberDuration(): number;
392
+ /**
393
+ * Attempt HTTP Basic authentication, logging the user in for the session — the Laravel `basic`.
394
+ * Resolves to `undefined` when already authenticated or when the `Authorization: Basic` header
395
+ * validates; otherwise resolves to a `401` challenge response (`WWW-Authenticate: Basic`).
396
+ * Requires the request (constructor option or {@link SessionGuard.setRequest}).
397
+ */
398
+ basic(field?: string): Promise<Response | undefined>;
399
+ /**
400
+ * Perform a stateless HTTP Basic attempt (no session persistence) — the Laravel `onceBasic`.
401
+ * Resolves to `undefined` on success, or the `401` challenge response on failure.
402
+ */
403
+ onceBasic(field?: string): Promise<Response | undefined>;
404
+ /**
405
+ * Issue a fresh remember-me token for `user`, persist it through the provider, and return the
406
+ * recaller value (`id|token`) to store in a long-lived cookie. The Laravel "remember me" persist.
407
+ */
408
+ remember(user: Authenticatable): Promise<string>;
409
+ /**
410
+ * Authenticate from a recaller cookie value (`id|token`), logging the user in for the session on a
411
+ * constant-time token match (the Laravel `viaRemember` path). Returns the user, or `null`.
412
+ */
413
+ loginUsingRecaller(value: string): Promise<Authenticatable | null>;
414
+ /** Persist the user's id and current password hash into the session. */
415
+ private updateSession;
416
+ /** Whether `credentials` validate against `user`, dispatching `Validated` when they do. */
417
+ private hasValidCredentials;
418
+ /** Run the `attemptWhen` callbacks; every one must return `true` for the login to proceed. */
419
+ private shouldLogin;
420
+ /** Clear the session synchronously, then finish teardown (token cycling + event) async. */
421
+ private performLogout;
422
+ /** Resolve the user that was logged out, cycle their remember token, and dispatch the event. */
423
+ private finishLogout;
424
+ /** Parse `Authorization: Basic …` from the request into `{ [field], password }`, or `null`. */
425
+ private basicCredentialsFromRequest;
426
+ }
427
+ /** Options for {@link TokenGuard}. */
428
+ interface TokenGuardOptions {
429
+ /** Guard name carried on dispatched events. Default `'api'`. */
430
+ name?: string;
431
+ /** Optional event dispatcher; when unset no events are dispatched. */
432
+ events?: AuthEvents;
433
+ }
434
+ /** Stateless token guard. The Laravel `TokenGuard` equivalent. */
435
+ declare class TokenGuard implements Guard {
436
+ private readonly provider;
437
+ private readonly request;
438
+ private readonly inputKey;
439
+ private cachedUser;
440
+ private resolved;
441
+ private readonly name;
442
+ private readonly events;
443
+ constructor(provider: UserProvider, request: Request, inputKey?: string, options?: TokenGuardOptions);
444
+ user(): Promise<Authenticatable | null>;
445
+ check(): Promise<boolean>;
446
+ guest(): Promise<boolean>;
447
+ id(): Promise<string | number | null>;
448
+ validate(credentials: Credentials): Promise<boolean>;
449
+ setUser(user: Authenticatable): void;
450
+ /** Read the API token from the bearer header, then the query string, then the input bag. */
451
+ private tokenForRequest;
452
+ }
453
+ /**
454
+ * The user-resolver callback behind a {@link RequestGuard} — the closure passed to
455
+ * `Auth::viaRequest`. Receives the request (and the provider, when one was registered) and returns
456
+ * the authenticated user, or `null`/`undefined` for a guest.
457
+ */
458
+ type RequestUserResolver = (request: Request, provider?: UserProvider) => Authenticatable | null | undefined | Promise<Authenticatable | null | undefined>;
459
+ /**
460
+ * Closure-driven guard over the current request — the Laravel `RequestGuard` (the engine behind
461
+ * `Auth::viaRequest`). Resolves the user once per instance through the callback.
462
+ */
463
+ declare class RequestGuard implements Guard {
464
+ private readonly callback;
465
+ private readonly provider?;
466
+ private cachedUser;
467
+ private resolved;
468
+ private request;
469
+ constructor(callback: RequestUserResolver, request?: Request, provider?: UserProvider | undefined);
470
+ user(): Promise<Authenticatable | null>;
471
+ check(): Promise<boolean>;
472
+ guest(): Promise<boolean>;
473
+ id(): Promise<string | number | null>;
474
+ /**
475
+ * Whether the callback resolves a user for `credentials['request']` — the Laravel
476
+ * `RequestGuard::validate`, which runs the resolver against the given request.
477
+ */
478
+ validate(credentials: Credentials): Promise<boolean>;
479
+ setUser(user: Authenticatable): void;
480
+ /** Swap the request and reset the cached user. The `setRequest` equivalent. */
481
+ setRequest(request: Request): this;
482
+ }
483
+
484
+ /**
485
+ * Builds a guard on demand. Request-scoped guards capture per-request state in the closure, or read
486
+ * the request {@link AuthManager.guard} forwards (factories registered before this parameter
487
+ * existed simply ignore it).
488
+ */
489
+ type GuardFactory = (request?: Request) => Guard;
490
+ declare class AuthManager {
491
+ private defaultGuard;
492
+ private readonly guards;
493
+ constructor(defaultGuard?: string);
494
+ /** Register a guard factory under `name`. The `Auth::extend()` equivalent. */
495
+ extend(name: string, factory: GuardFactory): this;
496
+ /**
497
+ * Register a closure-driven guard under `name` — the `Auth::viaRequest()` equivalent. The
498
+ * callback receives the request (and `provider`, when given) and returns the authenticated user
499
+ * or `null`; the manager builds a {@link RequestGuard} around it on every resolve.
500
+ */
501
+ viaRequest(name: string, callback: RequestUserResolver, provider?: UserProvider): this;
502
+ /**
503
+ * Resolve a guard by name (or the default), forwarding `request` to the factory so
504
+ * request-scoped guards (e.g. {@link AuthManager.viaRequest}) can read it. Throws if the guard is
505
+ * not registered.
506
+ */
507
+ guard(name?: string, request?: Request): Guard;
508
+ /** Change the default guard name. The `Auth::shouldUse()` equivalent. */
509
+ setDefaultGuard(name: string): this;
510
+ /** The current default guard name. */
511
+ getDefaultGuard(): string;
512
+ }
513
+
514
+ /**
515
+ * Authentication middleware bridging `@plinthjs/auth` to `@plinthjs/http` — the Laravel `Authenticate`
516
+ * (`auth`) middleware family. {@link authenticateSession} resolves the user from the session
517
+ * (requires the session middleware) and {@link authenticateToken} from a request token; both attach
518
+ * the user to the request (readable via {@link getUser}) or render a `401` via
519
+ * {@link AuthenticationError}. {@link authenticateSession} also keeps a hash of the user's password
520
+ * in the session (the Laravel `AuthenticateSession` middleware) so sessions die when the password
521
+ * changes — e.g. after `SessionGuard.logoutOtherDevices`. {@link redirectIfAuthenticated} is the
522
+ * `guest` middleware, and {@link requirePassword} / {@link confirmPassword} implement the Laravel
523
+ * `password.confirm` flow over an `auth.password_confirmed_at` session timestamp.
524
+ */
525
+
526
+ /** Session key holding the epoch-seconds timestamp of the last password confirmation. */
527
+ declare const PASSWORD_CONFIRMED_AT_SESSION_KEY = "auth.password_confirmed_at";
528
+ /** Raised when authentication is required but the request is unauthenticated (renders `401`). */
529
+ declare class AuthenticationError extends HttpException {
530
+ constructor(message?: string);
531
+ }
532
+ /** The authenticated user attached by an authenticate middleware, or `undefined`. */
533
+ declare function getUser(req: Request): Authenticatable | undefined;
534
+ /**
535
+ * Authenticate via the session — the web `auth` middleware. Requires the session middleware to have
536
+ * run; resolves the user from the session id and attaches it, or throws {@link AuthenticationError}.
537
+ * Also enforces the Laravel `AuthenticateSession` password-hash check: the user's password hash is
538
+ * stored in the session on first sight and compared on every request, so a password change (e.g.
539
+ * `SessionGuard.logoutOtherDevices`) logs every stale session out.
540
+ */
541
+ declare function authenticateSession(provider: UserProvider): Middleware;
542
+ /**
543
+ * Authenticate via a request token — the stateless `auth:api` middleware. Resolves the user from a
544
+ * bearer/query/input token and attaches it, or throws {@link AuthenticationError}.
545
+ */
546
+ declare function authenticateToken(provider: UserProvider, inputKey?: string): Middleware;
547
+ /**
548
+ * Redirect authenticated users away (e.g. from login/register pages) — the Laravel
549
+ * `RedirectIfAuthenticated` (`guest`) middleware. Guests (and requests without a session) pass
550
+ * through; an authenticated session is redirected to `redirectTo`.
551
+ */
552
+ declare function redirectIfAuthenticated(provider: UserProvider, redirectTo?: string): Middleware;
553
+ /**
554
+ * Require a recent password confirmation — the Laravel `RequirePassword` (`password.confirm`)
555
+ * middleware. Passes when the session's `auth.password_confirmed_at` timestamp is within
556
+ * `passwordTimeoutSeconds`; otherwise redirects to `redirectTo` (or renders `423 Locked` for JSON
557
+ * clients). Stamp the timestamp via {@link confirmPassword} after re-validating the password.
558
+ */
559
+ declare function requirePassword(redirectTo?: string, passwordTimeoutSeconds?: number, now?: () => Date): Middleware;
560
+ /**
561
+ * Re-validate the user's password and stamp the session's confirmation timestamp — what Laravel's
562
+ * `ConfirmablePasswordController` does for the `password.confirm` flow. Returns `false` (leaving
563
+ * the session untouched) when the password does not match.
564
+ */
565
+ declare function confirmPassword(provider: UserProvider, session: Session, user: Authenticatable, password: string, now?: () => Date): Promise<boolean>;
566
+
567
+ /** The outcome of a broker operation — the Laravel `Password::*` status constants. */
568
+ declare const PasswordStatus: {
569
+ readonly ResetLinkSent: "passwords.sent";
570
+ readonly PasswordReset: "passwords.reset";
571
+ readonly InvalidUser: "passwords.user";
572
+ readonly InvalidToken: "passwords.token";
573
+ readonly InvalidPassword: "passwords.password";
574
+ readonly ResetThrottled: "passwords.throttled";
575
+ };
576
+ /** A password-broker status value. */
577
+ type PasswordStatus = (typeof PasswordStatus)[keyof typeof PasswordStatus];
578
+ /** Stores, verifies, and expires password-reset tokens. The Laravel `TokenRepositoryInterface`. */
579
+ interface TokenRepository {
580
+ /** Mint, store, and return a fresh plaintext token for `user` (only its hash is kept). */
581
+ create(user: Authenticatable): Promise<string>;
582
+ /** Whether `token` matches a stored, non-expired token for `user`. */
583
+ exists(user: Authenticatable, token: string): Promise<boolean>;
584
+ /** Whether `user` was issued a token within the throttle window (for re-send throttling). */
585
+ recentlyCreatedToken(user: Authenticatable): Promise<boolean>;
586
+ /** Forget `user`'s token (after a successful reset). */
587
+ delete(user: Authenticatable): Promise<void>;
588
+ /** Purge every expired token. */
589
+ deleteExpired(): Promise<void>;
590
+ }
591
+ /** Options for {@link ArrayTokenRepository}. */
592
+ interface ArrayTokenRepositoryOptions {
593
+ /** Hasher used to store token hashes (never the plaintext). */
594
+ hasher: Hasher;
595
+ /** Token lifetime in minutes (the Laravel `expire`). Default `60`. */
596
+ expireMinutes?: number;
597
+ /** Re-send throttle window in seconds (the Laravel `throttle`). Default `60`. */
598
+ throttleSeconds?: number;
599
+ /** Injected clock for deterministic expiry/throttle. Default `() => new Date()`. */
600
+ now?: () => Date;
601
+ /** Plaintext token generator. Default 40 random hex chars; tests may inject a fixed value. */
602
+ createToken?: () => string;
603
+ }
604
+ /** In-memory {@link TokenRepository}, keyed by the user's auth identifier — ideal for tests/small apps. */
605
+ declare class ArrayTokenRepository implements TokenRepository {
606
+ private readonly store;
607
+ private readonly hasher;
608
+ private readonly expireMinutes;
609
+ private readonly throttleSeconds;
610
+ private readonly now;
611
+ private readonly makeToken;
612
+ constructor(options: ArrayTokenRepositoryOptions);
613
+ create(user: Authenticatable): Promise<string>;
614
+ exists(user: Authenticatable, token: string): Promise<boolean>;
615
+ recentlyCreatedToken(user: Authenticatable): Promise<boolean>;
616
+ delete(user: Authenticatable): Promise<void>;
617
+ deleteExpired(): Promise<void>;
618
+ private expired;
619
+ }
620
+ /** Credentials for a reset: the lookup fields plus the `token` and new `password`. */
621
+ type ResetCredentials = Credentials & {
622
+ token: string;
623
+ password: string;
624
+ };
625
+ /** A callback that delivers the reset link/token to the user (email, SMS, …). */
626
+ type ResetLinkSender = (user: Authenticatable, token: string) => void | Promise<void>;
627
+ /** A callback that persists the user's new password. */
628
+ type PasswordResetCallback = (user: Authenticatable, password: string) => void | Promise<void>;
629
+ /** Drives the password-reset flow over a {@link UserProvider} and {@link TokenRepository}. */
630
+ declare class PasswordBroker {
631
+ private readonly users;
632
+ private readonly tokens;
633
+ private readonly events;
634
+ constructor(users: UserProvider, tokens: TokenRepository, events?: AuthEvents);
635
+ /**
636
+ * Send a reset link: resolve the user from `credentials`, throttle repeat requests, mint a token,
637
+ * and hand it to `send`. Returns {@link PasswordStatus.ResetLinkSent} on success.
638
+ */
639
+ sendResetLink(credentials: Credentials, send: ResetLinkSender): Promise<PasswordStatus>;
640
+ /**
641
+ * Reset a password: resolve the user, require a non-empty password, verify the token, then run
642
+ * `reset` to persist and delete the token. Returns {@link PasswordStatus.PasswordReset} on success.
643
+ */
644
+ reset(credentials: ResetCredentials, reset: PasswordResetCallback): Promise<PasswordStatus>;
645
+ /** The user-lookup credentials, with `token`/`password` removed so they don't act as match fields. */
646
+ private lookupOnly;
647
+ }
648
+
649
+ /** A simple record-backed {@link Authenticatable}. The Laravel `GenericUser` equivalent. */
650
+ declare class GenericUser implements Authenticatable, Rememberable, PasswordUpdatable {
651
+ readonly attributes: Record<string, unknown>;
652
+ private readonly identifierName;
653
+ private readonly passwordName;
654
+ constructor(attributes: Record<string, unknown>, identifierName?: string, passwordName?: string);
655
+ getAuthIdentifier(): string | number;
656
+ getAuthIdentifierName(): string;
657
+ getAuthPassword(): string;
658
+ setAuthPassword(hashed: string): void;
659
+ getRememberToken(): string | null;
660
+ setRememberToken(token: string): void;
661
+ /** Read an arbitrary attribute, used by providers to match credentials. */
662
+ getAttribute(key: string): unknown;
663
+ }
664
+ /** An in-memory {@link UserProvider} over a fixed list of users — ideal for tests and small apps. */
665
+ declare class ArrayUserProvider implements UserProvider {
666
+ private readonly users;
667
+ private readonly hasher;
668
+ constructor(users: GenericUser[], hasher: Hasher);
669
+ retrieveById(identifier: string | number): Promise<Authenticatable | null>;
670
+ retrieveByToken(identifier: string | number, token: string): Promise<Authenticatable | null>;
671
+ updateRememberToken(user: Authenticatable, token: string): Promise<void>;
672
+ retrieveByCredentials(credentials: Credentials): Promise<Authenticatable | null>;
673
+ validateCredentials(user: Authenticatable, credentials: Credentials): Promise<boolean>;
674
+ /**
675
+ * Re-hash and persist the user's password when its cost parameters no longer match the hasher's
676
+ * (or always, when `force` is set) — the Laravel `rehashPasswordIfRequired`. Persists through the
677
+ * {@link PasswordUpdatable} seam, mirroring how remember tokens are persisted.
678
+ */
679
+ rehashPasswordIfRequired(user: Authenticatable, credentials: Credentials, force?: boolean): Promise<void>;
680
+ }
681
+
682
+ /**
683
+ * @plinthjs/auth — authentication, the Laravel `Illuminate\Auth` equivalent.
684
+ *
685
+ * The {@link Authenticatable} / {@link UserProvider} / {@link Guard} contracts, an in-memory
686
+ * {@link ArrayUserProvider} over {@link GenericUser}s (passwords verified through `@plinthjs/encryption`,
687
+ * re-hashed on login via {@link UserProvider.rehashPasswordIfRequired}), the {@link SessionGuard}
688
+ * (stateful, web — with `attemptWhen`, HTTP Basic, remember-me, and the logout variants), the
689
+ * {@link TokenGuard} (stateless, API), the {@link RequestGuard} behind
690
+ * {@link AuthManager.viaRequest}, an {@link AuthManager} that resolves named guards, the Laravel
691
+ * auth event classes dispatched through the structural {@link AuthEvents} seam, and the
692
+ * {@link authenticateSession} / {@link authenticateToken} / {@link redirectIfAuthenticated} /
693
+ * {@link requirePassword} HTTP middleware (with {@link getUser} to read the user off the request).
694
+ */
695
+ /** The Mason version this build of `auth` ships with. */
696
+ declare const VERSION = "0.1.0";
697
+
698
+ export { ArrayTokenRepository, type ArrayTokenRepositoryOptions, ArrayUserProvider, type AttemptCallback, Attempting, type AuthEvents, AuthManager, type Authenticatable, Authenticated, AuthenticationError, type Credentials, CurrentDeviceLogout, EmailVerifier, type EmailVerifierOptions, Failed, GenericUser, type Guard, type GuardFactory, Lockout, Login, Logout, type MustVerifyEmail, OtherDeviceLogout, PASSWORD_CONFIRMED_AT_SESSION_KEY, PASSWORD_HASH_SESSION_KEY, PasswordBroker, PasswordReset, type PasswordResetCallback, PasswordStatus, type PasswordUpdatable, Registered, type Rememberable, RequestGuard, type RequestUserResolver, type ResetCredentials, type ResetLinkSender, SessionGuard, type SessionGuardOptions, type StatefulGuard, TokenGuard, type TokenGuardOptions, type TokenRepository, type UserProvider, VERSION, Validated, type VerifiableUser, type VerificationSignature, Verified, authenticateSession, authenticateToken, confirmPassword, getUser, redirectIfAuthenticated, requirePassword };