@basaltkit/auth 1.6.0 → 1.6.1

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,45 @@
1
+ import { BasaltError } from '@basaltkit/core';
2
+ /** Raised when an identifier has exceeded the failed-login budget. */
3
+ export class AccountLockedError extends BasaltError {
4
+ retryAfterMs;
5
+ status = 429;
6
+ constructor(retryAfterMs) {
7
+ super('AUTH_LOCKED', `Too many failed login attempts. Try again in ${Math.ceil(retryAfterMs / 1000)}s.`);
8
+ this.retryAfterMs = retryAfterMs;
9
+ }
10
+ }
11
+ /**
12
+ * Brute-force guard: counts failed logins per identifier (email) within a
13
+ * rolling window and locks the account once the budget is spent. A successful
14
+ * login clears the counter. In-memory per process; back it with Redis for a
15
+ * cluster by supplying the same behavior.
16
+ */
17
+ export class LoginThrottle {
18
+ failures = new Map();
19
+ maxAttempts;
20
+ windowMs;
21
+ clock;
22
+ constructor(options = {}) {
23
+ this.maxAttempts = options.maxAttempts ?? 5;
24
+ this.windowMs = options.windowMs ?? 15 * 60_000;
25
+ this.clock = options.clock ?? (() => Date.now());
26
+ }
27
+ /** Throws {@link AccountLockedError} when the key is currently locked. */
28
+ assertAllowed(key) {
29
+ const entry = this.failures.get(key);
30
+ if (entry && this.clock() < entry.resetAt && entry.count >= this.maxAttempts) {
31
+ throw new AccountLockedError(entry.resetAt - this.clock());
32
+ }
33
+ }
34
+ recordFailure(key) {
35
+ const now = this.clock();
36
+ let entry = this.failures.get(key);
37
+ if (!entry || now >= entry.resetAt)
38
+ entry = { count: 0, resetAt: now + this.windowMs };
39
+ entry.count += 1;
40
+ this.failures.set(key, entry);
41
+ }
42
+ reset(key) {
43
+ this.failures.delete(key);
44
+ }
45
+ }
package/dist/totp.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ /** RFC 4648 base32 encode (no padding, uppercase) — the format authenticator apps expect. */
2
+ export declare function base32Encode(bytes: Uint8Array): string;
3
+ /** RFC 4648 base32 decode — tolerant of lowercase, spaces, and `=` padding. */
4
+ export declare function base32Decode(input: string): Buffer;
5
+ /** A fresh, random base32 TOTP secret (default 20 bytes = 160 bits). */
6
+ export declare function generateTotpSecret(bytes?: number): string;
7
+ export interface TotpOptions {
8
+ /** Seconds per code. Default 30. */
9
+ period?: number;
10
+ /** Code length. Default 6. */
11
+ digits?: number;
12
+ /** Milliseconds since epoch. Default Date.now(). */
13
+ now?: number;
14
+ }
15
+ /** The current TOTP code (RFC 6238) for a base32 secret. */
16
+ export declare function totp(secret: string, options?: TotpOptions): string;
17
+ export interface VerifyTotpOptions extends TotpOptions {
18
+ /** Accept codes ±`window` steps to absorb clock drift. Default 1. */
19
+ window?: number;
20
+ }
21
+ /**
22
+ * The TOTP step (counter) that `token` matches within the allowed window, or
23
+ * null. Constant-time over the window (no early exit → no timing side channel).
24
+ * The step is what enables replay prevention: persist the last-accepted step and
25
+ * reject any code whose step is ≤ it (RFC 6238 §5.2).
26
+ */
27
+ export declare function matchTotpStep(secret: string, token: string, options?: VerifyTotpOptions): number | null;
28
+ /** True when `token` matches the TOTP within the allowed time window (constant-time). */
29
+ export declare function verifyTotp(secret: string, token: string, options?: VerifyTotpOptions): boolean;
30
+ export interface OtpauthUriInput {
31
+ secret: string;
32
+ /** The account label, typically the user's email. */
33
+ account: string;
34
+ /** The issuer shown in the authenticator app. */
35
+ issuer: string;
36
+ digits?: number;
37
+ period?: number;
38
+ }
39
+ /** Builds an `otpauth://totp/...` URI to render as a QR code. */
40
+ export declare function otpauthUri(input: OtpauthUriInput): string;
package/dist/totp.js ADDED
@@ -0,0 +1,108 @@
1
+ import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
2
+ const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
3
+ /** RFC 4648 base32 encode (no padding, uppercase) — the format authenticator apps expect. */
4
+ export function base32Encode(bytes) {
5
+ let bits = 0;
6
+ let value = 0;
7
+ let out = '';
8
+ for (const byte of bytes) {
9
+ value = (value << 8) | byte;
10
+ bits += 8;
11
+ while (bits >= 5) {
12
+ out += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
13
+ bits -= 5;
14
+ }
15
+ }
16
+ if (bits > 0)
17
+ out += BASE32_ALPHABET[(value << (5 - bits)) & 31];
18
+ return out;
19
+ }
20
+ /** RFC 4648 base32 decode — tolerant of lowercase, spaces, and `=` padding. */
21
+ export function base32Decode(input) {
22
+ const clean = input.toUpperCase().replace(/[\s=]/g, '');
23
+ let bits = 0;
24
+ let value = 0;
25
+ const out = [];
26
+ for (const char of clean) {
27
+ const idx = BASE32_ALPHABET.indexOf(char);
28
+ if (idx === -1)
29
+ throw new Error('Invalid base32 character');
30
+ value = (value << 5) | idx;
31
+ bits += 5;
32
+ if (bits >= 8) {
33
+ out.push((value >>> (bits - 8)) & 0xff);
34
+ bits -= 8;
35
+ }
36
+ }
37
+ return Buffer.from(out);
38
+ }
39
+ /** A fresh, random base32 TOTP secret (default 20 bytes = 160 bits). */
40
+ export function generateTotpSecret(bytes = 20) {
41
+ return base32Encode(randomBytes(bytes));
42
+ }
43
+ /** HOTP (RFC 4226) for an explicit counter. */
44
+ function hotp(secret, counter, digits) {
45
+ const buf = Buffer.alloc(8);
46
+ // 53-bit safe: counter never exceeds Number.MAX_SAFE_INTEGER for realistic times.
47
+ buf.writeUInt32BE(Math.floor(counter / 0x100000000), 0);
48
+ buf.writeUInt32BE(counter >>> 0, 4);
49
+ const digest = createHmac('sha1', secret).update(buf).digest();
50
+ const offset = digest[digest.length - 1] & 0x0f;
51
+ const binary = ((digest[offset] & 0x7f) << 24) |
52
+ ((digest[offset + 1] & 0xff) << 16) |
53
+ ((digest[offset + 2] & 0xff) << 8) |
54
+ (digest[offset + 3] & 0xff);
55
+ return (binary % 10 ** digits).toString().padStart(digits, '0');
56
+ }
57
+ /** The current TOTP code (RFC 6238) for a base32 secret. */
58
+ export function totp(secret, options = {}) {
59
+ const period = options.period ?? 30;
60
+ const digits = options.digits ?? 6;
61
+ const now = options.now ?? Date.now();
62
+ const counter = Math.floor(now / 1000 / period);
63
+ return hotp(base32Decode(secret), counter, digits);
64
+ }
65
+ /**
66
+ * The TOTP step (counter) that `token` matches within the allowed window, or
67
+ * null. Constant-time over the window (no early exit → no timing side channel).
68
+ * The step is what enables replay prevention: persist the last-accepted step and
69
+ * reject any code whose step is ≤ it (RFC 6238 §5.2).
70
+ */
71
+ export function matchTotpStep(secret, token, options = {}) {
72
+ const period = options.period ?? 30;
73
+ const digits = options.digits ?? 6;
74
+ const now = options.now ?? Date.now();
75
+ const window = options.window ?? 1;
76
+ const cleaned = token.replace(/\s/g, '');
77
+ if (cleaned.length !== digits)
78
+ return null;
79
+ const key = base32Decode(secret);
80
+ const base = Math.floor(now / 1000 / period);
81
+ let matched = -1;
82
+ // Loop the whole window regardless of an early hit — no timing side channel.
83
+ for (let error = -window; error <= window; error++) {
84
+ const step = base + error;
85
+ const candidate = hotp(key, step, digits);
86
+ if (candidate.length === cleaned.length && timingSafeEqual(Buffer.from(candidate), Buffer.from(cleaned))) {
87
+ matched = step;
88
+ }
89
+ }
90
+ return matched === -1 ? null : matched;
91
+ }
92
+ /** True when `token` matches the TOTP within the allowed time window (constant-time). */
93
+ export function verifyTotp(secret, token, options = {}) {
94
+ return matchTotpStep(secret, token, options) !== null;
95
+ }
96
+ /** Builds an `otpauth://totp/...` URI to render as a QR code. */
97
+ export function otpauthUri(input) {
98
+ // Label is `issuer:account`, each component encoded but the `:` kept literal.
99
+ const label = `${encodeURIComponent(input.issuer)}:${encodeURIComponent(input.account)}`;
100
+ const params = new URLSearchParams({
101
+ secret: input.secret,
102
+ issuer: input.issuer,
103
+ algorithm: 'SHA1',
104
+ digits: String(input.digits ?? 6),
105
+ period: String(input.period ?? 30),
106
+ });
107
+ return `otpauth://totp/${label}?${params.toString()}`;
108
+ }
@@ -0,0 +1,13 @@
1
+ import { WebAuthnService, type PasskeyStore, type WebAuthnChallengeStore, type WebAuthnConfig, type WebAuthnVerifier } from './webauthn.js';
2
+ export declare const WEBAUTHN: import("@basaltkit/core").Token<WebAuthnService>;
3
+ export interface WebAuthnPluginOptions {
4
+ config: WebAuthnConfig;
5
+ /** The crypto boundary — implement over `@simplewebauthn/server`. Required. */
6
+ verifier: WebAuthnVerifier;
7
+ /** Passkey storage. Default: in-memory (swap for a durable store). */
8
+ credentials?: PasskeyStore;
9
+ /** Challenge storage. Default: in-memory. */
10
+ challenges?: WebAuthnChallengeStore;
11
+ }
12
+ /** Registers a {@link WebAuthnService} under the {@link WEBAUTHN} token. */
13
+ export declare function webauthnPlugin(options: WebAuthnPluginOptions): import("@basaltkit/core").BasaltPlugin<unknown>;
@@ -0,0 +1,17 @@
1
+ import { createToken, definePlugin } from '@basaltkit/core';
2
+ import { WebAuthnService, MemoryPasskeyStore, MemoryWebAuthnChallengeStore, } from './webauthn.js';
3
+ export const WEBAUTHN = createToken('auth:webauthn');
4
+ /** Registers a {@link WebAuthnService} under the {@link WEBAUTHN} token. */
5
+ export function webauthnPlugin(options) {
6
+ return definePlugin({
7
+ name: 'basalt:auth-webauthn',
8
+ register({ container }) {
9
+ container.singleton(WEBAUTHN, () => new WebAuthnService({
10
+ config: options.config,
11
+ verifier: options.verifier,
12
+ credentials: options.credentials ?? new MemoryPasskeyStore(),
13
+ challenges: options.challenges ?? new MemoryWebAuthnChallengeStore(),
14
+ }));
15
+ },
16
+ });
17
+ }
@@ -0,0 +1,219 @@
1
+ import { BasaltError } from '@basaltkit/core';
2
+ /**
3
+ * WebAuthn / passkeys ceremony orchestration. The framework owns everything that
4
+ * is NOT cryptography — issuing challenges, assembling the browser options,
5
+ * storing credentials, and the counter/clone check — and delegates the actual
6
+ * attestation/assertion verification to a pluggable {@link WebAuthnVerifier}
7
+ * (implement it over `@simplewebauthn/server` or similar). This keeps the
8
+ * framework free of a crypto dependency while still driving the full flow.
9
+ */
10
+ export interface PasskeyCredential {
11
+ /** base64url credential id. */
12
+ id: string;
13
+ userId: string;
14
+ /** base64url COSE public key (opaque to the framework; the verifier reads it). */
15
+ publicKey: string;
16
+ /** Signature counter for clone detection. */
17
+ counter: number;
18
+ transports?: string[];
19
+ deviceName?: string;
20
+ createdAt: number;
21
+ lastUsedAt?: number;
22
+ }
23
+ export interface PasskeyStore {
24
+ add(credential: PasskeyCredential): Promise<void>;
25
+ get(credentialId: string): Promise<PasskeyCredential | null>;
26
+ forUser(userId: string): Promise<PasskeyCredential[]>;
27
+ updateCounter(credentialId: string, counter: number, lastUsedAt: number): Promise<void>;
28
+ remove(credentialId: string): Promise<void>;
29
+ }
30
+ export declare class MemoryPasskeyStore implements PasskeyStore {
31
+ private readonly byId;
32
+ add(credential: PasskeyCredential): Promise<void>;
33
+ get(credentialId: string): Promise<PasskeyCredential | null>;
34
+ forUser(userId: string): Promise<PasskeyCredential[]>;
35
+ updateCounter(credentialId: string, counter: number, lastUsedAt: number): Promise<void>;
36
+ remove(credentialId: string): Promise<void>;
37
+ }
38
+ /** A stored challenge plus the subject (user id) it was issued for, if any. */
39
+ export interface StoredChallenge {
40
+ challenge: string;
41
+ /** The user the registration challenge is bound to — enforced at finish. */
42
+ userId?: string;
43
+ }
44
+ export interface WebAuthnChallengeStore {
45
+ save(key: string, value: StoredChallenge, expiresAt: number): Promise<void>;
46
+ /** Return AND consume the challenge (single-use), or null if missing/expired. */
47
+ take(key: string): Promise<StoredChallenge | null>;
48
+ }
49
+ export declare class MemoryWebAuthnChallengeStore implements WebAuthnChallengeStore {
50
+ private readonly entries;
51
+ private readonly now;
52
+ private readonly maxEntries;
53
+ constructor(options?: {
54
+ now?: () => number;
55
+ maxEntries?: number;
56
+ });
57
+ save(key: string, value: StoredChallenge, expiresAt: number): Promise<void>;
58
+ take(key: string): Promise<StoredChallenge | null>;
59
+ }
60
+ export interface VerifyRegistrationInput {
61
+ /** The `RegistrationResponseJSON` from `@simplewebauthn/browser`. */
62
+ response: unknown;
63
+ expectedChallenge: string;
64
+ expectedOrigin: string | string[];
65
+ expectedRpId: string;
66
+ requireUserVerification: boolean;
67
+ }
68
+ export interface VerifiedRegistration {
69
+ verified: boolean;
70
+ credential?: {
71
+ id: string;
72
+ publicKey: string;
73
+ counter: number;
74
+ transports?: string[];
75
+ };
76
+ }
77
+ export interface VerifyAuthenticationInput {
78
+ /** The `AuthenticationResponseJSON` from `@simplewebauthn/browser`. */
79
+ response: unknown;
80
+ expectedChallenge: string;
81
+ expectedOrigin: string | string[];
82
+ expectedRpId: string;
83
+ requireUserVerification: boolean;
84
+ credential: {
85
+ id: string;
86
+ publicKey: string;
87
+ counter: number;
88
+ };
89
+ }
90
+ export interface VerifiedAuthentication {
91
+ verified: boolean;
92
+ newCounter: number;
93
+ }
94
+ /** The cryptographic boundary — implement over a WebAuthn library. */
95
+ export interface WebAuthnVerifier {
96
+ verifyRegistration(input: VerifyRegistrationInput): Promise<VerifiedRegistration>;
97
+ verifyAuthentication(input: VerifyAuthenticationInput): Promise<VerifiedAuthentication>;
98
+ }
99
+ export interface PublicKeyParam {
100
+ type: 'public-key';
101
+ alg: number;
102
+ }
103
+ export interface CredentialDescriptor {
104
+ type: 'public-key';
105
+ id: string;
106
+ transports?: string[];
107
+ }
108
+ export interface RegistrationOptions {
109
+ challenge: string;
110
+ rp: {
111
+ id: string;
112
+ name: string;
113
+ };
114
+ user: {
115
+ id: string;
116
+ name: string;
117
+ displayName: string;
118
+ };
119
+ pubKeyCredParams: PublicKeyParam[];
120
+ timeout: number;
121
+ attestation: 'none';
122
+ excludeCredentials: CredentialDescriptor[];
123
+ authenticatorSelection: {
124
+ userVerification: string;
125
+ residentKey: 'preferred';
126
+ };
127
+ }
128
+ export interface AuthenticationOptions {
129
+ challenge: string;
130
+ timeout: number;
131
+ rpId: string;
132
+ userVerification: string;
133
+ allowCredentials: CredentialDescriptor[];
134
+ }
135
+ export declare class WebAuthnChallengeError extends BasaltError {
136
+ readonly status = 400;
137
+ constructor();
138
+ }
139
+ export declare class WebAuthnVerificationError extends BasaltError {
140
+ readonly status = 400;
141
+ constructor();
142
+ }
143
+ export declare class PasskeyNotFoundError extends BasaltError {
144
+ readonly status = 404;
145
+ constructor();
146
+ }
147
+ export declare class PasskeyClonedError extends BasaltError {
148
+ readonly status = 401;
149
+ constructor();
150
+ }
151
+ export declare class PasskeyExistsError extends BasaltError {
152
+ readonly status = 409;
153
+ constructor();
154
+ }
155
+ export declare class WebAuthnSubjectMismatchError extends BasaltError {
156
+ readonly status = 403;
157
+ constructor();
158
+ }
159
+ export interface WebAuthnConfig {
160
+ /** Relying Party ID — your registrable domain, e.g. 'example.com'. */
161
+ rpId: string;
162
+ /** Human-readable RP name shown in the OS prompt. */
163
+ rpName: string;
164
+ /** Expected origin(s), e.g. 'https://example.com'. */
165
+ origin: string | string[];
166
+ /** Challenge TTL in ms. Default 5 minutes. */
167
+ challengeTtlMs?: number;
168
+ /** User-verification requirement. Default 'preferred'. */
169
+ userVerification?: 'required' | 'preferred' | 'discouraged';
170
+ /** Ceremony timeout advertised to the browser, ms. Default 60s. */
171
+ timeoutMs?: number;
172
+ /** Override the accepted algorithms. Default ES256 + RS256. */
173
+ pubKeyCredParams?: PublicKeyParam[];
174
+ }
175
+ export interface WebAuthnServiceOptions {
176
+ config: WebAuthnConfig;
177
+ credentials: PasskeyStore;
178
+ challenges: WebAuthnChallengeStore;
179
+ verifier: WebAuthnVerifier;
180
+ now?: () => number;
181
+ /** Challenge generator (tests). Default: 32 random bytes, base64url. */
182
+ randomChallenge?: () => string;
183
+ }
184
+ export declare class WebAuthnService {
185
+ private readonly config;
186
+ private readonly credentials;
187
+ private readonly challenges;
188
+ private readonly verifier;
189
+ private readonly now;
190
+ private readonly randomChallenge;
191
+ constructor(options: WebAuthnServiceOptions);
192
+ private get uv();
193
+ private get timeout();
194
+ private challengeKey;
195
+ private issueChallenge;
196
+ /** Registration options for a known user; stores the challenge bound to `user.id`. */
197
+ startRegistration(sessionKey: string, user: {
198
+ id: string;
199
+ name: string;
200
+ displayName?: string;
201
+ }): Promise<RegistrationOptions>;
202
+ /** Verify a registration response and store the new passkey. Throws on failure. */
203
+ finishRegistration(sessionKey: string, userId: string, response: unknown, deviceName?: string): Promise<PasskeyCredential>;
204
+ /** Authentication options; `userId` narrows allowCredentials, omit it for discoverable login. */
205
+ startAuthentication(sessionKey: string, userId?: string): Promise<AuthenticationOptions>;
206
+ /**
207
+ * Verify an authentication response. Looks the credential up by its id, checks
208
+ * the signature counter increased (clone detection), persists the new counter,
209
+ * and returns whose passkey authenticated. Throws on any failure.
210
+ */
211
+ finishAuthentication(sessionKey: string, response: unknown): Promise<{
212
+ userId: string;
213
+ credentialId: string;
214
+ }>;
215
+ /** A user's registered passkeys (for a "manage devices" screen). */
216
+ list(userId: string): Promise<PasskeyCredential[]>;
217
+ /** Remove a passkey (revoke a device). */
218
+ remove(credentialId: string): Promise<void>;
219
+ }