@basaltkit/auth 1.6.0 → 1.6.2
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 +6 -0
- package/dist/apikeys-plugin.d.ts +37 -0
- package/dist/apikeys-plugin.js +56 -0
- package/dist/apikeys.d.ts +54 -0
- package/dist/apikeys.js +86 -0
- package/dist/auth.d.ts +279 -0
- package/dist/auth.js +535 -0
- package/dist/hashing.d.ts +23 -0
- package/dist/hashing.js +42 -0
- package/dist/index.d.ts +14 -1140
- package/dist/index.js +14 -1798
- package/dist/jwt.d.ts +26 -0
- package/dist/jwt.js +57 -0
- package/dist/oauth-plugin.d.ts +32 -0
- package/dist/oauth-plugin.js +63 -0
- package/dist/oauth.d.ts +115 -0
- package/dist/oauth.js +242 -0
- package/dist/plugin.d.ts +56 -0
- package/dist/plugin.js +44 -0
- package/dist/routes.d.ts +23 -0
- package/dist/routes.js +223 -0
- package/dist/secret-box.d.ts +10 -0
- package/dist/secret-box.js +38 -0
- package/dist/stores.d.ts +196 -0
- package/dist/stores.js +169 -0
- package/dist/throttle.d.ts +32 -0
- package/dist/throttle.js +45 -0
- package/dist/totp.d.ts +40 -0
- package/dist/totp.js +108 -0
- package/dist/webauthn-plugin.d.ts +13 -0
- package/dist/webauthn-plugin.js +17 -0
- package/dist/webauthn.d.ts +219 -0
- package/dist/webauthn.js +248 -0
- package/package.json +11 -12
package/README.md
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://basaltkit-docs.pages.dev">
|
|
3
|
+
<img src="https://basaltkit-docs.pages.dev/social-card.png" alt="Basalt" width="440">
|
|
4
|
+
</a>
|
|
5
|
+
</p>
|
|
6
|
+
|
|
1
7
|
# @basaltkit/auth
|
|
2
8
|
|
|
3
9
|
Complete authentication for Basalt applications: user registration and login, JWT tokens with secure renewal, sessions, email verification, password recovery, two-factor authentication (MFA/TOTP), social login (Google, GitHub, or any OpenID Connect provider), and API keys — all with ready-to-use HTTP routes.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { ApiKeys, type ApiKeyContext, type ApiKeysOptions } from './apikeys.js';
|
|
2
|
+
import type { UserSource } from './stores.js';
|
|
3
|
+
declare module '@basaltkit/core' {
|
|
4
|
+
interface RequestContext {
|
|
5
|
+
/** Set when the request authenticated with an API key instead of a session. */
|
|
6
|
+
apiKey?: ApiKeyContext;
|
|
7
|
+
}
|
|
8
|
+
interface BasaltHooks {
|
|
9
|
+
'auth:apikey_issued': {
|
|
10
|
+
id: string;
|
|
11
|
+
tenantId?: string;
|
|
12
|
+
userId?: string;
|
|
13
|
+
};
|
|
14
|
+
'auth:apikey_revoked': {
|
|
15
|
+
id: string;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export declare const API_KEYS: import("@basaltkit/core").Token<ApiKeys>;
|
|
20
|
+
export interface ApiKeysPluginOptions extends ApiKeysOptions {
|
|
21
|
+
/**
|
|
22
|
+
* Header carrying the key, besides `Authorization: Bearer mk_...`.
|
|
23
|
+
* Default `x-api-key`.
|
|
24
|
+
*/
|
|
25
|
+
header?: string;
|
|
26
|
+
/**
|
|
27
|
+
* When provided, a key that carries a `userId` also populates `ctx().user`,
|
|
28
|
+
* so scope-guarded routes can read the acting user.
|
|
29
|
+
*/
|
|
30
|
+
users?: UserSource;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Programmatic access via API keys. Registers an enricher that authenticates
|
|
34
|
+
* `mk_`-prefixed bearers (or the configured header) and a guard that enforces
|
|
35
|
+
* `meta.scopes` on routes. Pair with {@link apiKeyRoutes} for CRUD endpoints.
|
|
36
|
+
*/
|
|
37
|
+
export declare function apiKeysPlugin(options?: ApiKeysPluginOptions): import("@basaltkit/core").BasaltPlugin<unknown>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
|
|
2
|
+
import { ApiKeys, ScopeRequiredError, scopesSatisfy } from './apikeys.js';
|
|
3
|
+
import { publicUser } from './auth.js';
|
|
4
|
+
export const API_KEYS = createToken('auth:apikeys');
|
|
5
|
+
/**
|
|
6
|
+
* Programmatic access via API keys. Registers an enricher that authenticates
|
|
7
|
+
* `mk_`-prefixed bearers (or the configured header) and a guard that enforces
|
|
8
|
+
* `meta.scopes` on routes. Pair with {@link apiKeyRoutes} for CRUD endpoints.
|
|
9
|
+
*/
|
|
10
|
+
export function apiKeysPlugin(options = {}) {
|
|
11
|
+
const header = options.header ?? 'x-api-key';
|
|
12
|
+
return definePlugin({
|
|
13
|
+
name: 'basalt:apikeys',
|
|
14
|
+
register({ container, hooks }) {
|
|
15
|
+
container.singleton(API_KEYS, () => new ApiKeys({ ...options, hooks }));
|
|
16
|
+
const metadata = ensureMetadata(container);
|
|
17
|
+
const enricher = async ({ request, context, container: c }) => {
|
|
18
|
+
const authHeader = request.headers.authorization;
|
|
19
|
+
const bearer = typeof authHeader === 'string' && authHeader.startsWith('Bearer mk_')
|
|
20
|
+
? authHeader.slice('Bearer '.length)
|
|
21
|
+
: undefined;
|
|
22
|
+
const custom = request.headers[header];
|
|
23
|
+
const presented = bearer ?? (typeof custom === 'string' ? custom : undefined);
|
|
24
|
+
if (!presented)
|
|
25
|
+
return;
|
|
26
|
+
const record = await c.get(API_KEYS).verify(presented);
|
|
27
|
+
if (!record)
|
|
28
|
+
return;
|
|
29
|
+
context.apiKey = {
|
|
30
|
+
id: record.id,
|
|
31
|
+
scopes: record.scopes,
|
|
32
|
+
...(record.tenantId !== undefined ? { tenantId: record.tenantId } : {}),
|
|
33
|
+
...(record.userId !== undefined ? { userId: record.userId } : {}),
|
|
34
|
+
};
|
|
35
|
+
if (record.userId && options.users) {
|
|
36
|
+
const user = await options.users.findById(record.userId);
|
|
37
|
+
if (user)
|
|
38
|
+
context.user = publicUser(user);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
metadata.add('http:enrichers', enricher);
|
|
42
|
+
// Guard: a route declaring meta.scopes needs an API key holding them all.
|
|
43
|
+
const guard = ({ route, context }) => {
|
|
44
|
+
const required = route.meta?.['scopes'];
|
|
45
|
+
if (!Array.isArray(required) || required.length === 0)
|
|
46
|
+
return;
|
|
47
|
+
const granted = context.apiKey?.scopes ?? [];
|
|
48
|
+
for (const scope of required) {
|
|
49
|
+
if (!scopesSatisfy(granted, [scope]))
|
|
50
|
+
throw new ScopeRequiredError(scope);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
metadata.add('http:guards', guard);
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { BasaltError, type HookBus } from '@basaltkit/core';
|
|
2
|
+
import { type ApiKeyFilter, type ApiKeyInfo, type ApiKeyRecord, type ApiKeyStore } from './stores.js';
|
|
3
|
+
/** A route required a scope the presented key does not hold. */
|
|
4
|
+
export declare class ScopeRequiredError extends BasaltError {
|
|
5
|
+
readonly status = 403;
|
|
6
|
+
constructor(scope: string);
|
|
7
|
+
}
|
|
8
|
+
/** True when `granted` covers `required` (an exact match or the `*` wildcard). */
|
|
9
|
+
export declare const scopesSatisfy: (granted: readonly string[], required: readonly string[]) => boolean;
|
|
10
|
+
export interface IssueApiKeyInput {
|
|
11
|
+
name: string;
|
|
12
|
+
scopes?: string[] | undefined;
|
|
13
|
+
tenantId?: string;
|
|
14
|
+
userId?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface ApiKeysOptions {
|
|
17
|
+
store?: ApiKeyStore;
|
|
18
|
+
hooks?: HookBus;
|
|
19
|
+
/** Injectable clock — tests and deterministic runs override it. */
|
|
20
|
+
now?: () => number;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Issues and verifies API keys. The plaintext key is returned exactly once by
|
|
24
|
+
* {@link issue}; only its SHA-256 hash is stored, so a leaked database never
|
|
25
|
+
* yields usable keys.
|
|
26
|
+
*/
|
|
27
|
+
export declare class ApiKeys {
|
|
28
|
+
private readonly store;
|
|
29
|
+
private readonly hooks;
|
|
30
|
+
private readonly now;
|
|
31
|
+
constructor(options?: ApiKeysOptions);
|
|
32
|
+
/** Mints a key. Returns the record plus the plaintext `key` (shown once). */
|
|
33
|
+
issue(input: IssueApiKeyInput): Promise<{
|
|
34
|
+
record: ApiKeyInfo;
|
|
35
|
+
key: string;
|
|
36
|
+
}>;
|
|
37
|
+
/**
|
|
38
|
+
* Resolves a presented key to its record, or null if it's malformed,
|
|
39
|
+
* unknown, or revoked. Updates `lastUsedAt` on a hit.
|
|
40
|
+
*/
|
|
41
|
+
verify(presented: string): Promise<ApiKeyRecord | null>;
|
|
42
|
+
list(filter: ApiKeyFilter): Promise<ApiKeyInfo[]>;
|
|
43
|
+
/** Revokes a key by id. No-op if unknown or already revoked. */
|
|
44
|
+
revoke(id: string): Promise<void>;
|
|
45
|
+
/** Reads a single key's public info (used to authorize a revoke). */
|
|
46
|
+
get(id: string): Promise<ApiKeyInfo | null>;
|
|
47
|
+
}
|
|
48
|
+
/** The value stashed on `ctx().apiKey` after a request authenticates with a key. */
|
|
49
|
+
export interface ApiKeyContext {
|
|
50
|
+
id: string;
|
|
51
|
+
scopes: string[];
|
|
52
|
+
tenantId?: string;
|
|
53
|
+
userId?: string;
|
|
54
|
+
}
|
package/dist/apikeys.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
+
import { BasaltError } from '@basaltkit/core';
|
|
3
|
+
import { MemoryApiKeyStore, } from './stores.js';
|
|
4
|
+
/** A route required a scope the presented key does not hold. */
|
|
5
|
+
export class ScopeRequiredError extends BasaltError {
|
|
6
|
+
status = 403;
|
|
7
|
+
constructor(scope) {
|
|
8
|
+
super('AUTH_SCOPE_REQUIRED', `This action requires the "${scope}" scope.`);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/** The prefix on every key. `mk` = Basalt key, `live` = environment. */
|
|
12
|
+
const KEY_PREFIX = 'mk_live_';
|
|
13
|
+
/** SHA-256 is safe here: API keys are high-entropy, so no slow hash is needed. */
|
|
14
|
+
const hashKey = (key) => createHash('sha256').update(key).digest('hex');
|
|
15
|
+
const strip = (record) => {
|
|
16
|
+
const { hash: _hash, ...info } = record;
|
|
17
|
+
return info;
|
|
18
|
+
};
|
|
19
|
+
/** True when `granted` covers `required` (an exact match or the `*` wildcard). */
|
|
20
|
+
export const scopesSatisfy = (granted, required) => granted.includes('*') || required.every((scope) => granted.includes(scope));
|
|
21
|
+
/**
|
|
22
|
+
* Issues and verifies API keys. The plaintext key is returned exactly once by
|
|
23
|
+
* {@link issue}; only its SHA-256 hash is stored, so a leaked database never
|
|
24
|
+
* yields usable keys.
|
|
25
|
+
*/
|
|
26
|
+
export class ApiKeys {
|
|
27
|
+
store;
|
|
28
|
+
hooks;
|
|
29
|
+
now;
|
|
30
|
+
constructor(options = {}) {
|
|
31
|
+
this.store = options.store ?? new MemoryApiKeyStore();
|
|
32
|
+
this.hooks = options.hooks;
|
|
33
|
+
this.now = options.now ?? Date.now;
|
|
34
|
+
}
|
|
35
|
+
/** Mints a key. Returns the record plus the plaintext `key` (shown once). */
|
|
36
|
+
async issue(input) {
|
|
37
|
+
const secret = randomBytes(24).toString('base64url');
|
|
38
|
+
const key = `${KEY_PREFIX}${secret}`;
|
|
39
|
+
const record = {
|
|
40
|
+
id: randomUUID(),
|
|
41
|
+
name: input.name,
|
|
42
|
+
prefix: `${KEY_PREFIX}${secret.slice(0, 6)}`,
|
|
43
|
+
hash: hashKey(key),
|
|
44
|
+
scopes: input.scopes ?? ['*'],
|
|
45
|
+
createdAt: this.now(),
|
|
46
|
+
...(input.tenantId !== undefined ? { tenantId: input.tenantId } : {}),
|
|
47
|
+
...(input.userId !== undefined ? { userId: input.userId } : {}),
|
|
48
|
+
};
|
|
49
|
+
await this.store.create(record);
|
|
50
|
+
await this.hooks?.emit('auth:apikey_issued', {
|
|
51
|
+
id: record.id,
|
|
52
|
+
...(record.tenantId !== undefined ? { tenantId: record.tenantId } : {}),
|
|
53
|
+
...(record.userId !== undefined ? { userId: record.userId } : {}),
|
|
54
|
+
});
|
|
55
|
+
return { record: strip(record), key };
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Resolves a presented key to its record, or null if it's malformed,
|
|
59
|
+
* unknown, or revoked. Updates `lastUsedAt` on a hit.
|
|
60
|
+
*/
|
|
61
|
+
async verify(presented) {
|
|
62
|
+
if (!presented.startsWith(KEY_PREFIX))
|
|
63
|
+
return null;
|
|
64
|
+
const record = await this.store.findByHash(hashKey(presented));
|
|
65
|
+
if (!record || record.revokedAt !== undefined)
|
|
66
|
+
return null;
|
|
67
|
+
await this.store.touch(record.id, this.now());
|
|
68
|
+
return record;
|
|
69
|
+
}
|
|
70
|
+
async list(filter) {
|
|
71
|
+
return (await this.store.list(filter)).map(strip);
|
|
72
|
+
}
|
|
73
|
+
/** Revokes a key by id. No-op if unknown or already revoked. */
|
|
74
|
+
async revoke(id) {
|
|
75
|
+
const record = await this.store.findById(id);
|
|
76
|
+
if (record && record.revokedAt === undefined) {
|
|
77
|
+
await this.store.revoke(id, this.now());
|
|
78
|
+
await this.hooks?.emit('auth:apikey_revoked', { id });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/** Reads a single key's public info (used to authorize a revoke). */
|
|
82
|
+
async get(id) {
|
|
83
|
+
const record = await this.store.findById(id);
|
|
84
|
+
return record ? strip(record) : null;
|
|
85
|
+
}
|
|
86
|
+
}
|
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { BasaltError, type DurationInput, type HookBus } from '@basaltkit/core';
|
|
2
|
+
import { type PasswordHasher } from './hashing.js';
|
|
3
|
+
import { LoginThrottle } from './throttle.js';
|
|
4
|
+
import { type JwtClaims } from './jwt.js';
|
|
5
|
+
import { type AuthTokenStore, type AuthUser, type MfaStore, type PublicUser, type RefreshTokenStore, type SessionRecord, type SessionStore, type TokenVersionStore, type UserSource } from './stores.js';
|
|
6
|
+
export declare class InvalidCredentialsError extends BasaltError {
|
|
7
|
+
readonly status = 401;
|
|
8
|
+
constructor();
|
|
9
|
+
}
|
|
10
|
+
export declare class EmailTakenError extends BasaltError {
|
|
11
|
+
readonly status = 409;
|
|
12
|
+
constructor();
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Thrown at construction when the JWT signing secret is missing or too weak. A
|
|
16
|
+
* short/low-entropy HS256 key can be brute-forced offline, letting an attacker
|
|
17
|
+
* forge access tokens for any account — so this fails closed rather than boot
|
|
18
|
+
* with a guessable key. Use `@basaltkit/env`'s `secret({ minLength: 32 })`.
|
|
19
|
+
*/
|
|
20
|
+
export declare class WeakJwtSecretError extends BasaltError {
|
|
21
|
+
constructor(reason: string);
|
|
22
|
+
}
|
|
23
|
+
export declare class RefreshInvalidError extends BasaltError {
|
|
24
|
+
readonly status = 401;
|
|
25
|
+
constructor();
|
|
26
|
+
}
|
|
27
|
+
/** A used refresh token came back — the whole family is revoked. */
|
|
28
|
+
export declare class RefreshReusedError extends BasaltError {
|
|
29
|
+
readonly status = 401;
|
|
30
|
+
constructor();
|
|
31
|
+
}
|
|
32
|
+
export declare class AuthRequiredError extends BasaltError {
|
|
33
|
+
readonly status = 401;
|
|
34
|
+
constructor();
|
|
35
|
+
}
|
|
36
|
+
/** A verification / reset token was unknown, already used, or expired. */
|
|
37
|
+
export declare class AuthTokenInvalidError extends BasaltError {
|
|
38
|
+
readonly status = 400;
|
|
39
|
+
constructor();
|
|
40
|
+
}
|
|
41
|
+
/** The configured UserSource can't be updated (needed for verification/reset). */
|
|
42
|
+
export declare class UserUpdateUnsupportedError extends BasaltError {
|
|
43
|
+
readonly status = 500;
|
|
44
|
+
constructor();
|
|
45
|
+
}
|
|
46
|
+
/** Credentials were correct but the account has MFA — a code is required. */
|
|
47
|
+
export declare class MfaRequiredError extends BasaltError {
|
|
48
|
+
readonly status = 401;
|
|
49
|
+
constructor();
|
|
50
|
+
}
|
|
51
|
+
/** The supplied MFA (or recovery) code was wrong. */
|
|
52
|
+
export declare class MfaInvalidCodeError extends BasaltError {
|
|
53
|
+
readonly status = 401;
|
|
54
|
+
constructor();
|
|
55
|
+
}
|
|
56
|
+
/** An MFA action needed an enrollment that doesn't exist. */
|
|
57
|
+
export declare class MfaNotEnrolledError extends BasaltError {
|
|
58
|
+
readonly status = 400;
|
|
59
|
+
constructor();
|
|
60
|
+
}
|
|
61
|
+
export interface TokenPair {
|
|
62
|
+
accessToken: string;
|
|
63
|
+
refreshToken: string;
|
|
64
|
+
}
|
|
65
|
+
export interface AuthOptions {
|
|
66
|
+
users: UserSource;
|
|
67
|
+
secret: string;
|
|
68
|
+
hasher?: PasswordHasher;
|
|
69
|
+
sessions?: SessionStore;
|
|
70
|
+
refreshTokens?: RefreshTokenStore;
|
|
71
|
+
accessTtl?: DurationInput;
|
|
72
|
+
refreshTtl?: DurationInput;
|
|
73
|
+
sessionTtl?: DurationInput;
|
|
74
|
+
hooks?: HookBus;
|
|
75
|
+
/** Brute-force lockout (per email). Enabled by default; pass `false` to disable. */
|
|
76
|
+
loginThrottle?: LoginThrottle | false;
|
|
77
|
+
/**
|
|
78
|
+
* Per-IP login throttle — blunts password spraying (1 attempt across many
|
|
79
|
+
* accounts) and lockout-DoS that a per-email counter alone misses. Enabled by
|
|
80
|
+
* default with a higher budget than the per-email one; pass `false` to disable.
|
|
81
|
+
* Only applies when the caller passes the client ip to `login`.
|
|
82
|
+
*/
|
|
83
|
+
ipLoginThrottle?: LoginThrottle | false;
|
|
84
|
+
/**
|
|
85
|
+
* Make the public registration endpoint enumeration-safe: a request for an
|
|
86
|
+
* email that already exists returns the same response (and does equivalent
|
|
87
|
+
* work) as a fresh signup, instead of a 409 that reveals the account exists.
|
|
88
|
+
* Applies to {@link Auth.registerSafely} (used by the register route); the
|
|
89
|
+
* lower-level {@link Auth.register} always throws on a duplicate. Default true.
|
|
90
|
+
*/
|
|
91
|
+
enumerationSafeRegister?: boolean;
|
|
92
|
+
/** Store for verification/reset tokens. Default: in-memory. */
|
|
93
|
+
tokens?: AuthTokenStore;
|
|
94
|
+
/** Email-verification link lifetime. Default 24h. */
|
|
95
|
+
verificationTtl?: DurationInput;
|
|
96
|
+
/** Password-reset link lifetime. Default 1h. */
|
|
97
|
+
resetTtl?: DurationInput;
|
|
98
|
+
/** Store for MFA (TOTP) enrollment state. Default: in-memory. */
|
|
99
|
+
mfa?: MfaStore;
|
|
100
|
+
/**
|
|
101
|
+
* Enables access-token revocation. When set, access tokens carry a version
|
|
102
|
+
* (`tv`) and `resetPassword`/`revokeAllTokens` bump it — invalidating every
|
|
103
|
+
* token issued before the bump, even before its TTL expires. Opt-in; access
|
|
104
|
+
* verification then costs one store read per request. Default: off.
|
|
105
|
+
*/
|
|
106
|
+
tokenVersions?: TokenVersionStore;
|
|
107
|
+
/**
|
|
108
|
+
* Key for encrypting TOTP secrets at rest (AES-256-GCM). When set, secrets are
|
|
109
|
+
* stored as `v1:` envelopes so a database leak can't recover a live second
|
|
110
|
+
* factor; existing plaintext records keep working and are encrypted on next
|
|
111
|
+
* write. Any length — derived to 32 bytes. Omit to store secrets in plaintext.
|
|
112
|
+
*/
|
|
113
|
+
mfaEncryptionKey?: string | Buffer;
|
|
114
|
+
/** Issuer name shown in authenticator apps. Default 'Basalt'. */
|
|
115
|
+
mfaIssuer?: string;
|
|
116
|
+
}
|
|
117
|
+
export declare const publicUser: (user: AuthUser) => PublicUser;
|
|
118
|
+
export declare class Auth {
|
|
119
|
+
readonly users: UserSource;
|
|
120
|
+
private readonly hasher;
|
|
121
|
+
private readonly sessions;
|
|
122
|
+
private readonly refreshTokens;
|
|
123
|
+
private readonly secret;
|
|
124
|
+
private readonly accessTtl;
|
|
125
|
+
private readonly refreshTtl;
|
|
126
|
+
private readonly sessionTtl;
|
|
127
|
+
private readonly hooks;
|
|
128
|
+
private readonly throttle;
|
|
129
|
+
private readonly ipThrottle;
|
|
130
|
+
private readonly tokens;
|
|
131
|
+
private readonly verificationTtl;
|
|
132
|
+
private readonly resetTtl;
|
|
133
|
+
private readonly mfa;
|
|
134
|
+
private readonly mfaIssuer;
|
|
135
|
+
private readonly mfaKey;
|
|
136
|
+
private readonly tokenVersions;
|
|
137
|
+
private readonly enumerationSafeRegister;
|
|
138
|
+
constructor(options: AuthOptions);
|
|
139
|
+
register(email: string, password: string): Promise<PublicUser>;
|
|
140
|
+
/**
|
|
141
|
+
* Logs in an externally-authenticated user (e.g. from an OAuth provider),
|
|
142
|
+
* matched by email — find-or-create. A new account is created **passwordless**
|
|
143
|
+
* (a random, unusable password hash), so password login won't work for it
|
|
144
|
+
* until a password is set. A provider-verified email flips `emailVerified`.
|
|
145
|
+
* Returns the tokens and whether the account was just created.
|
|
146
|
+
*/
|
|
147
|
+
socialLogin(email: string, options?: {
|
|
148
|
+
emailVerified?: boolean;
|
|
149
|
+
}): Promise<{
|
|
150
|
+
user: PublicUser;
|
|
151
|
+
tokens: TokenPair;
|
|
152
|
+
created: boolean;
|
|
153
|
+
}>;
|
|
154
|
+
/**
|
|
155
|
+
* Enumeration-safe registration for the public endpoint: creates the account
|
|
156
|
+
* for a new email, or — when the email is already taken — does equivalent work
|
|
157
|
+
* (so timing doesn't leak) and emits `auth:register_existing_email` so the app
|
|
158
|
+
* can send an out-of-band "you already have an account" email. Returns nothing
|
|
159
|
+
* either way, so the response can't reveal whether the account existed.
|
|
160
|
+
*
|
|
161
|
+
* With `enumerationSafeRegister: false` it throws {@link EmailTakenError} on a
|
|
162
|
+
* duplicate instead (the classic, enumerable behavior).
|
|
163
|
+
*/
|
|
164
|
+
registerSafely(email: string, password: string): Promise<void>;
|
|
165
|
+
/** Verifies credentials without side effects. Null on failure. */
|
|
166
|
+
attempt(email: string, password: string): Promise<AuthUser | null>;
|
|
167
|
+
private dummyHashPromise?;
|
|
168
|
+
/** A valid hash of a throwaway secret, produced once by the configured hasher. */
|
|
169
|
+
private dummyHash;
|
|
170
|
+
/**
|
|
171
|
+
* Credentials → token pair. Emits auth:login / auth:login_failed. Locks the
|
|
172
|
+
* account after too many failures (see {@link LoginThrottle}); a success
|
|
173
|
+
* clears the counter.
|
|
174
|
+
*
|
|
175
|
+
* When the account has MFA enabled, `mfaCode` (a TOTP or recovery code) is
|
|
176
|
+
* required: a correct password with a missing code throws
|
|
177
|
+
* {@link MfaRequiredError} (without counting as a failed attempt), and a
|
|
178
|
+
* wrong code throws {@link MfaInvalidCodeError}.
|
|
179
|
+
*/
|
|
180
|
+
login(email: string, password: string, mfaCode?: string, context?: {
|
|
181
|
+
ip?: string;
|
|
182
|
+
}): Promise<{
|
|
183
|
+
user: PublicUser;
|
|
184
|
+
tokens: TokenPair;
|
|
185
|
+
}>;
|
|
186
|
+
/**
|
|
187
|
+
* Refresh rotation with reuse detection: every refresh consumes the token
|
|
188
|
+
* and issues a new one in the same family. If a consumed token comes back
|
|
189
|
+
* (theft indicator), the whole family is revoked.
|
|
190
|
+
*/
|
|
191
|
+
refresh(refreshToken: string): Promise<TokenPair>;
|
|
192
|
+
/** Revokes a refresh family — logout for token-based clients. */
|
|
193
|
+
revoke(refreshToken: string): Promise<void>;
|
|
194
|
+
/** Structural JWT verification only (signature + expiry). */
|
|
195
|
+
verifyAccess(accessToken: string): JwtClaims;
|
|
196
|
+
/**
|
|
197
|
+
* Verifies the access token AND, when token-version revocation is enabled,
|
|
198
|
+
* rejects a token minted before the user's version was last bumped (i.e.
|
|
199
|
+
* revoked by a password reset / `revokeAllTokens`). Prefer this over
|
|
200
|
+
* {@link verifyAccess} on the request path.
|
|
201
|
+
*/
|
|
202
|
+
verifyAccessToken(accessToken: string): Promise<JwtClaims>;
|
|
203
|
+
/**
|
|
204
|
+
* Revokes every access token issued so far for the user (logout-everywhere),
|
|
205
|
+
* by bumping the token version. No-op unless a {@link TokenVersionStore} is
|
|
206
|
+
* configured. Pair with refresh/session revocation for a full logout.
|
|
207
|
+
*/
|
|
208
|
+
revokeAllTokens(userId: string): Promise<void>;
|
|
209
|
+
createSession(userId: string): Promise<SessionRecord>;
|
|
210
|
+
sessionUser(sessionId: string): Promise<AuthUser | null>;
|
|
211
|
+
logout(sessionId: string): Promise<void>;
|
|
212
|
+
/**
|
|
213
|
+
* Starts email verification: mints a single-use token and emits
|
|
214
|
+
* `auth:verify_requested` for the app to email. Returns the token (so a
|
|
215
|
+
* caller can build the link) or null if no account matches — never reveals
|
|
216
|
+
* whether the email exists.
|
|
217
|
+
*/
|
|
218
|
+
requestEmailVerification(email: string): Promise<{
|
|
219
|
+
user: PublicUser;
|
|
220
|
+
token: string;
|
|
221
|
+
} | null>;
|
|
222
|
+
/** Consumes a verification token and marks the user's email verified. */
|
|
223
|
+
verifyEmail(token: string): Promise<PublicUser>;
|
|
224
|
+
/**
|
|
225
|
+
* Starts a password reset: mints a single-use token and emits
|
|
226
|
+
* `auth:password_reset_requested`. Returns null when no account matches, so
|
|
227
|
+
* the caller always responds 200 (no account enumeration).
|
|
228
|
+
*/
|
|
229
|
+
requestPasswordReset(email: string): Promise<{
|
|
230
|
+
user: PublicUser;
|
|
231
|
+
token: string;
|
|
232
|
+
} | null>;
|
|
233
|
+
/**
|
|
234
|
+
* Consumes a reset token, sets the new password, and revokes every existing
|
|
235
|
+
* session/refresh token for the user (a reset logs everyone else out).
|
|
236
|
+
*/
|
|
237
|
+
resetPassword(token: string, newPassword: string): Promise<PublicUser>;
|
|
238
|
+
isMfaEnabled(userId: string): Promise<boolean>;
|
|
239
|
+
mfaStatus(userId: string): Promise<{
|
|
240
|
+
enabled: boolean;
|
|
241
|
+
pending: boolean;
|
|
242
|
+
}>;
|
|
243
|
+
/**
|
|
244
|
+
* Begins MFA enrollment: generates a fresh secret (not yet active) and
|
|
245
|
+
* returns it plus an `otpauth://` URI to render as a QR code. Call
|
|
246
|
+
* {@link activateMfa} with a code from the app to switch it on.
|
|
247
|
+
*/
|
|
248
|
+
/** Encrypt a TOTP secret for storage (no-op when no key is configured). */
|
|
249
|
+
private encryptMfaSecret;
|
|
250
|
+
/** Decrypt a stored TOTP secret (passes plaintext/legacy values through). */
|
|
251
|
+
private decryptMfaSecret;
|
|
252
|
+
enrollMfa(userId: string): Promise<{
|
|
253
|
+
secret: string;
|
|
254
|
+
otpauthUri: string;
|
|
255
|
+
}>;
|
|
256
|
+
/**
|
|
257
|
+
* Confirms enrollment by checking a code against the pending secret, enables
|
|
258
|
+
* MFA, and returns freshly generated single-use recovery codes (shown once).
|
|
259
|
+
*/
|
|
260
|
+
activateMfa(userId: string, code: string): Promise<{
|
|
261
|
+
recoveryCodes: string[];
|
|
262
|
+
}>;
|
|
263
|
+
/** Turns MFA off. Requires a valid current code (or recovery code). */
|
|
264
|
+
disableMfa(userId: string, code: string): Promise<void>;
|
|
265
|
+
/**
|
|
266
|
+
* Verifies a TOTP code or, failing that, a single-use recovery code (which
|
|
267
|
+
* is consumed on success). Returns false unless MFA is enabled.
|
|
268
|
+
*/
|
|
269
|
+
verifyMfaCode(userId: string, code: string): Promise<boolean>;
|
|
270
|
+
private generateRecoveryCode;
|
|
271
|
+
private hashRecoveryCode;
|
|
272
|
+
/** SHA-256 of a bearer secret (one-time token, refresh token) — only this is
|
|
273
|
+
* persisted, so a leak of the token/session table can't be replayed. */
|
|
274
|
+
private hashToken;
|
|
275
|
+
private issueOneTimeToken;
|
|
276
|
+
private consumeToken;
|
|
277
|
+
private updateUser;
|
|
278
|
+
private issueTokens;
|
|
279
|
+
}
|