@stacksjs/auth 0.70.86 → 0.70.88

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/dist/tokens.d.ts DELETED
@@ -1,284 +0,0 @@
1
- import type { AccessToken, CreateClientOptions, CreateClientResult, DatabaseDriver, OAuthClient, PersonalAccessTokenResult, RefreshTokenResult, TokenScopes } from '@stacksjs/types';
2
- /**
3
- * Read `users.password_changed_at` for a user.
4
- *
5
- * Binds a token's validity to the account's credential state: a token
6
- * issued before the user last changed their password is no longer
7
- * trusted, regardless of its own `revoked`/`expires_at` flags. This is
8
- * the durable, use-time backstop behind the post-reset revocation sweep
9
- * (#1947) — even a freshly minted pair that the sweep never saw is
10
- * rejected on first use.
11
- *
12
- * Returns `null` on ANY error (missing column / missing table) so a
13
- * not-yet-migrated database degrades to legacy-allow rather than locking
14
- * everyone out. Accepts an optional query runner so the refresh exchange
15
- * can read the stamp inside its own transaction.
16
- */
17
- export declare function getPasswordChangedAt(userId: unknown, q?: { unsafe: (sql: string, params?: any[]) => any }): Promise<Date | null>;
18
- /**
19
- * True when a credential issued at `createdAt` predates the user's last
20
- * password change (`changedAt`) and must therefore be rejected.
21
- *
22
- * Legacy-allow semantics:
23
- * - `changedAt` null (no stamp / un-migrated) => never reject.
24
- * - `createdAt` missing/unparseable => never reject.
25
- *
26
- * Strict `<` so a token minted in the SAME second as (or after) the
27
- * reset — e.g. the victim's immediate post-reset login — is NOT bricked
28
- * by CURRENT_TIMESTAMP's one-second granularity.
29
- */
30
- export declare function isIssuedBeforePasswordChange(createdAt: unknown, changedAt: Date | null): boolean;
31
- /**
32
- * Get all access tokens for a user
33
- *
34
- * @example
35
- * import { tokens } from '@stacksjs/auth'
36
- * const userTokens = await tokens(user.id)
37
- */
38
- export declare function tokens(userId: number): Promise<AccessToken[]>;
39
- /**
40
- * Get a specific token by its plain text value
41
- * Uses hash comparison for security
42
- *
43
- * @example
44
- * import { findToken } from '@stacksjs/auth'
45
- * const token = await findToken('abc123...')
46
- */
47
- export declare function findToken(plainTextToken: string): Promise<AccessToken | null>;
48
- /**
49
- * Get the current access token from the request context
50
- *
51
- * @example
52
- * import { currentAccessToken } from '@stacksjs/auth'
53
- * const token = await currentAccessToken()
54
- */
55
- export declare function currentAccessToken(): Promise<AccessToken | null>;
56
- /**
57
- * Check if the current token has a given scope/ability
58
- *
59
- * @example
60
- * import { tokenCan } from '@stacksjs/auth'
61
- * if (await tokenCan('posts:create')) {
62
- * // user can create posts
63
- * }
64
- */
65
- export declare function tokenCan(scope: string): Promise<boolean>;
66
- /**
67
- * Check if the current token does NOT have a given scope/ability
68
- *
69
- * @example
70
- * import { tokenCant } from '@stacksjs/auth'
71
- * if (await tokenCant('admin')) {
72
- * throw new Error('Admin access required')
73
- * }
74
- */
75
- export declare function tokenCant(scope: string): Promise<boolean>;
76
- /**
77
- * Check if token has ALL of the given scopes
78
- *
79
- * @example
80
- * import { tokenCanAll } from '@stacksjs/auth'
81
- * if (await tokenCanAll(['posts:read', 'posts:write'])) {
82
- * // user has both scopes
83
- * }
84
- */
85
- export declare function tokenCanAll(scopes: string[]): Promise<boolean>;
86
- /**
87
- * Check if token has ANY of the given scopes
88
- *
89
- * @example
90
- * import { tokenCanAny } from '@stacksjs/auth'
91
- * if (await tokenCanAny(['admin', 'moderator'])) {
92
- * // user has at least one of the scopes
93
- * }
94
- */
95
- export declare function tokenCanAny(scopes: string[]): Promise<boolean>;
96
- /**
97
- * Get all scopes/abilities for the current token
98
- *
99
- * @example
100
- * import { tokenAbilities } from '@stacksjs/auth'
101
- * const abilities = await tokenAbilities()
102
- * // ['read', 'write', 'posts:create']
103
- */
104
- export declare function tokenAbilities(): Promise<string[]>;
105
- /**
106
- * Create a new personal access token for a user
107
- * Tokens are hashed before storage for security
108
- *
109
- * @param userId - The user ID to create the token for
110
- * @param name - A name/description for the token
111
- * @param scopes - Array of scopes/abilities for the token
112
- * @param options - Additional options
113
- * @param options.expiresInMinutes - Token expiry in minutes (default: 60)
114
- * @param options.withRefreshToken - Whether to create a refresh token (default: true)
115
- * @param options.refreshExpiresInDays - Refresh token expiry in days (default: 30)
116
- *
117
- * @example
118
- * import { createToken } from '@stacksjs/auth'
119
- * const result = await createToken(user.id, 'My API Token', ['read', 'write'])
120
- * console.log(result.plainTextToken) // Save this - it won't be shown again!
121
- * console.log(result.refreshToken) // Use this to get new access tokens
122
- */
123
- export declare function createToken(userId: number, name?: string, scopes?: string[], options?: {
124
- expiresInMinutes?: number
125
- withRefreshToken?: boolean
126
- refreshExpiresInDays?: number
127
- }): Promise<PersonalAccessTokenResult>;
128
- /**
129
- * Exchange a refresh token for a new access token
130
- *
131
- * @param refreshTokenPlain - The plain text refresh token
132
- * @param options - Additional options
133
- * @param options.expiresInMinutes - New access token expiry in minutes (default: 60)
134
- * @param options.refreshExpiresInDays - New refresh token expiry in days (default: 30)
135
- *
136
- * @example
137
- * import { refreshToken } from '@stacksjs/auth'
138
- * const result = await refreshToken('your-refresh-token')
139
- * // Use result.plainTextToken as new access token
140
- * // Use result.refreshToken as new refresh token (old one is revoked)
141
- */
142
- export declare function refreshToken(refreshTokenPlain: string, options?: {
143
- expiresInMinutes?: number
144
- refreshExpiresInDays?: number
145
- }): Promise<RefreshTokenResult>;
146
- /**
147
- * Validate a refresh token without exchanging it
148
- *
149
- * @example
150
- * import { validateRefreshToken } from '@stacksjs/auth'
151
- * const isValid = await validateRefreshToken('your-refresh-token')
152
- */
153
- export declare function validateRefreshToken(refreshTokenPlain: string): Promise<boolean>;
154
- /**
155
- * Revoke a specific refresh token
156
- *
157
- * @example
158
- * import { revokeRefreshToken } from '@stacksjs/auth'
159
- * await revokeRefreshToken('your-refresh-token')
160
- */
161
- export declare function revokeRefreshToken(refreshTokenPlain: string): Promise<void>;
162
- /**
163
- * Revoke all refresh tokens for a user
164
- *
165
- * @example
166
- * import { revokeAllRefreshTokens } from '@stacksjs/auth'
167
- * await revokeAllRefreshTokens(user.id)
168
- */
169
- export declare function revokeAllRefreshTokens(userId: number): Promise<void>;
170
- /**
171
- * Delete expired refresh tokens (cleanup)
172
- *
173
- * @example
174
- * import { deleteExpiredRefreshTokens } from '@stacksjs/auth'
175
- * const count = await deleteExpiredRefreshTokens()
176
- */
177
- export declare function deleteExpiredRefreshTokens(): Promise<number>;
178
- /**
179
- * Delete revoked refresh tokens older than specified days
180
- *
181
- * @example
182
- * import { deleteRevokedRefreshTokens } from '@stacksjs/auth'
183
- * const count = await deleteRevokedRefreshTokens(7)
184
- */
185
- export declare function deleteRevokedRefreshTokens(daysOld?: number): Promise<number>;
186
- /**
187
- * Revoke a specific access token
188
- *
189
- * @example
190
- * import { revokeToken } from '@stacksjs/auth'
191
- * await revokeToken('abc123...')
192
- */
193
- export declare function revokeToken(plainTextToken: string): Promise<void>;
194
- /**
195
- * Revoke a token by its ID
196
- *
197
- * @example
198
- * import { revokeTokenById } from '@stacksjs/auth'
199
- * await revokeTokenById(123)
200
- */
201
- export declare function revokeTokenById(tokenId: number): Promise<void>;
202
- /**
203
- * Revoke all tokens for a user
204
- *
205
- * @example
206
- * import { revokeAllTokens } from '@stacksjs/auth'
207
- * await revokeAllTokens(user.id)
208
- */
209
- export declare function revokeAllTokens(userId: number): Promise<void>;
210
- /**
211
- * Revoke all tokens except the current one
212
- *
213
- * @example
214
- * import { revokeOtherTokens } from '@stacksjs/auth'
215
- * await revokeOtherTokens(user.id)
216
- */
217
- export declare function revokeOtherTokens(userId: number): Promise<void>;
218
- /**
219
- * Delete expired tokens (cleanup)
220
- *
221
- * @example
222
- * import { deleteExpiredTokens } from '@stacksjs/auth'
223
- * const count = await deleteExpiredTokens()
224
- */
225
- export declare function deleteExpiredTokens(): Promise<number>;
226
- /**
227
- * Delete revoked tokens older than specified days
228
- *
229
- * @example
230
- * import { deleteRevokedTokens } from '@stacksjs/auth'
231
- * const count = await deleteRevokedTokens(30) // older than 30 days
232
- */
233
- export declare function deleteRevokedTokens(daysOld?: number): Promise<number>;
234
- /**
235
- * Get all OAuth clients for a user
236
- *
237
- * @example
238
- * import { clients } from '@stacksjs/auth'
239
- * const userClients = await clients(user.id)
240
- */
241
- export declare function clients(userId: number): Promise<OAuthClient[]>;
242
- /**
243
- * Get a specific OAuth client by ID
244
- *
245
- * @example
246
- * import { findClient } from '@stacksjs/auth'
247
- * const client = await findClient(1)
248
- */
249
- export declare function findClient(clientId: number): Promise<OAuthClient | null>;
250
- /**
251
- * Create a new OAuth client
252
- *
253
- * @example
254
- * import { createClient } from '@stacksjs/auth'
255
- * const client = await createClient({
256
- * name: 'My App',
257
- * redirect: 'https://myapp.com/callback'
258
- * })
259
- */
260
- export declare function createClient(options: CreateClientOptions): Promise<CreateClientResult>;
261
- /**
262
- * Revoke an OAuth client
263
- *
264
- * @example
265
- * import { revokeClient } from '@stacksjs/auth'
266
- * await revokeClient(1)
267
- */
268
- export declare function revokeClient(clientId: number): Promise<void>;
269
- // ============================================================================
270
- // HELPER FUNCTIONS
271
- // ============================================================================
272
- export declare function parseScopes(scopes: string | string[] | null | undefined): TokenScopes;
273
- /** Current database driver */
274
- declare const dbDriver: DatabaseDriver;
275
- /** Cross-database SQL helpers */
276
- declare const sql: unknown;
277
- /**
278
- * Alias for currentAccessToken
279
- *
280
- * @example
281
- * import { token } from '@stacksjs/auth'
282
- * const t = await token()
283
- */
284
- export declare const token: unknown;
@@ -1,67 +0,0 @@
1
- /**
2
- * Reads `two_factor_secret`/`two_factor_enabled` directly — these are
3
- * guarantee-ALTER columns (see ensureUsersAuthColumns), not part of
4
- * the User model's typed `attributes`, so callers query them the same
5
- * way email-verification.ts reads email_verified_at: raw db access,
6
- * not the ORM model.
7
- */
8
- export declare function getTwoFactorState(userId: number): Promise<{ secret: string | null, enabled: boolean }>;
9
- export declare function isTwoFactorEnabled(user: TwoFactorUser): boolean;
10
- /**
11
- * Generate a new (unpersisted) secret + otpauth:// URI for setup.
12
- */
13
- export declare function generateTwoFactorSetup(email: string, serviceName?: string): { secret: string, uri: string };
14
- /**
15
- * Stash a freshly generated secret server-side while the user goes
16
- * scan/enter it into their authenticator app. Single pending secret
17
- * per user — generating a new one invalidates any prior unconfirmed
18
- * attempt, same delete-then-insert shape as storeWebAuthnChallenge.
19
- */
20
- export declare function stashPendingTwoFactorSecret(userId: number, secret: string, ttlSeconds?: number): Promise<void>;
21
- /**
22
- * Consume (delete-on-read) the pending secret stashed for a user, or
23
- * null if none exists / it expired.
24
- */
25
- export declare function consumePendingTwoFactorSecret(userId: number): Promise<string | null>;
26
- /**
27
- * Verify the setup code against the not-yet-persisted secret and, if
28
- * valid, persist it + flip `two_factor_enabled` on.
29
- */
30
- export declare function enableTwoFactor(userId: number, secret: string, code: string): Promise<boolean>;
31
- export declare function disableTwoFactor(userId: number): Promise<void>;
32
- /**
33
- * Verify a live login/dashboard-reauth code against the user's
34
- * already-persisted secret.
35
- */
36
- export declare function verifyTwoFactorLoginCode(userId: number, code: string): Promise<boolean>;
37
- /**
38
- * Create a single-use, short-lived login challenge for a user whose
39
- * password just verified but who still needs to supply a TOTP code.
40
- * Mirrors storeWebAuthnChallenge's delete-then-insert shape, keyed by
41
- * an opaque random id instead of (user_id, purpose) since a user can
42
- * only have one login attempt in flight that matters here.
43
- */
44
- export declare function createTwoFactorChallenge(userId: number, ttlSeconds?: number): Promise<string>;
45
- /**
46
- * Consume (delete-on-read) a login challenge and return the user id it
47
- * was issued for, or null if missing/expired.
48
- */
49
- export declare function consumeTwoFactorChallenge(challengeToken: string): Promise<number | null>;
50
- export declare const TwoFactor: {
51
- isEnabled: unknown;
52
- getState: unknown;
53
- generateSetup: unknown;
54
- stashPendingSecret: unknown;
55
- consumePendingSecret: unknown;
56
- enable: unknown;
57
- disable: unknown;
58
- verifyLoginCode: unknown;
59
- createChallenge: unknown;
60
- consumeChallenge: unknown
61
- };
62
- export declare interface TwoFactorUser {
63
- id: number
64
- email?: string
65
- two_factor_secret?: string | null
66
- two_factor_enabled?: boolean | number | null
67
- }
package/dist/user.d.ts DELETED
@@ -1,34 +0,0 @@
1
- import type { UserModel as OrmUserModel } from '@stacksjs/orm';
2
- /**
3
- * Get the currently authenticated user
4
- *
5
- * This is the primary way to get the authenticated user in your application.
6
- * It first checks if the user was already set by the auth middleware,
7
- * then falls back to validating the bearer token.
8
- *
9
- * @example
10
- * import { authUser } from '@stacksjs/auth'
11
- *
12
- * const user = await authUser()
13
- * if (user) {
14
- * console.log('Logged in as:', user.email)
15
- * }
16
- */
17
- export declare function authUser(): Promise<UserModel | undefined>;
18
- /**
19
- * Alias for authUser() - for backwards compatibility
20
- * @deprecated Use authUser() instead
21
- */
22
- export declare function getCurrentUser(): Promise<UserModel | undefined>;
23
- export declare function check(): Promise<boolean>;
24
- export declare function id(): Promise<number | undefined>;
25
- export declare function email(): Promise<string | undefined>;
26
- export declare function name(): Promise<string | undefined>;
27
- export declare function isAuthenticated(): Promise<boolean>;
28
- export declare function logout(): Promise<void>;
29
- export declare function refresh(): Promise<void>;
30
- // Local aliases — keep the existing `UserModel` / `UserJsonResponse` symbols
31
- // in this module while sourcing the underlying type from the ORM.
32
- declare type UserModel = OrmUserModel;
33
- declare type UserJsonResponse = OrmUserModel;
34
- export type AuthUser = UserJsonResponse;