local-lite 0.1.2 → 0.1.3
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/bin/local-lite.mjs +1 -1
- package/dist/auth/apple.js +6 -2
- package/dist/auth/github.js +6 -2
- package/dist/auth/google.js +6 -2
- package/dist/auth/index.d.ts +1 -0
- package/dist/auth/index.js +1 -0
- package/dist/auth/local/index.d.ts +1 -0
- package/dist/auth/local/index.js +17 -0
- package/dist/auth/local.d.ts +285 -0
- package/dist/auth/local.js +709 -0
- package/dist/auth/microsoft.js +7 -2
- package/dist/backups/onedrive.d.ts +2 -1
- package/dist/backups/onedrive.js +6 -2
- package/dist/config/index.js +1 -0
- package/dist/config/types.d.ts +7 -0
- package/dist/core/client.d.ts +4 -0
- package/dist/core/client.js +6 -1
- package/dist/keys/generator.js +12 -3
- package/dist/react/auth.d.ts +21 -0
- package/dist/react/auth.js +121 -0
- package/dist/utils/dynamic.js +0 -3
- package/dist/utils/uuid.d.ts +3 -4
- package/dist/utils/uuid.js +40 -10
- package/docs/auth.md +85 -2
- package/package.json +6 -1
|
@@ -0,0 +1,709 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LocalAuthEngine = exports.DEFAULT_MIN_PASSWORD_LENGTH = exports.DEFAULT_RESET_TOKEN_EXPIRY_MS = exports.DEFAULT_LOCKOUT_DURATION_MS = exports.DEFAULT_LOCKOUT_ATTEMPTS = exports.DEFAULT_SALT_BYTES = exports.DEFAULT_PASSWORD_ITERATIONS = exports.DEFAULT_PASSWORD_ALGORITHM = exports.DEFAULT_USER_TOKENS_TABLE = exports.DEFAULT_USERS_TABLE = void 0;
|
|
4
|
+
exports.getCryptoRandomBytes = getCryptoRandomBytes;
|
|
5
|
+
exports.derivePbkdf2Key = derivePbkdf2Key;
|
|
6
|
+
exports.hashPassword = hashPassword;
|
|
7
|
+
exports.verifyPassword = verifyPassword;
|
|
8
|
+
exports.generateCryptoToken = generateCryptoToken;
|
|
9
|
+
exports.mapStoredUserRow = mapStoredUserRow;
|
|
10
|
+
const pbkdf2_js_1 = require("@noble/hashes/pbkdf2.js");
|
|
11
|
+
const sha2_js_1 = require("@noble/hashes/sha2.js");
|
|
12
|
+
const utils_js_1 = require("@noble/hashes/utils.js");
|
|
13
|
+
const uuid_js_1 = require("../utils/uuid.js");
|
|
14
|
+
const sql_js_1 = require("../utils/sql.js");
|
|
15
|
+
const generator_js_1 = require("../keys/generator.js");
|
|
16
|
+
const session_js_1 = require("./session.js");
|
|
17
|
+
exports.DEFAULT_USERS_TABLE = '_local_users';
|
|
18
|
+
exports.DEFAULT_USER_TOKENS_TABLE = '_local_user_tokens';
|
|
19
|
+
exports.DEFAULT_PASSWORD_ALGORITHM = 'PBKDF2-SHA256';
|
|
20
|
+
exports.DEFAULT_PASSWORD_ITERATIONS = 1_000;
|
|
21
|
+
exports.DEFAULT_SALT_BYTES = 16;
|
|
22
|
+
exports.DEFAULT_LOCKOUT_ATTEMPTS = 5;
|
|
23
|
+
exports.DEFAULT_LOCKOUT_DURATION_MS = 15 * 60 * 1000; // 15 minutes
|
|
24
|
+
exports.DEFAULT_RESET_TOKEN_EXPIRY_MS = 60 * 60 * 1000; // 1 hour
|
|
25
|
+
exports.DEFAULT_MIN_PASSWORD_LENGTH = 8;
|
|
26
|
+
/**
|
|
27
|
+
* Generates cryptographically secure random bytes across Web, Expo/React Native, and Node.js.
|
|
28
|
+
*/
|
|
29
|
+
function getCryptoRandomBytes(length) {
|
|
30
|
+
const cryptoObj = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
|
|
31
|
+
if (cryptoObj?.getRandomValues) {
|
|
32
|
+
try {
|
|
33
|
+
return cryptoObj.getRandomValues(new Uint8Array(length));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
// Fallback below
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
const nodeCrypto = globalThis.process?.versions?.node
|
|
41
|
+
? globalThis.require('node:crypto')
|
|
42
|
+
: null;
|
|
43
|
+
if (nodeCrypto?.randomBytes) {
|
|
44
|
+
return new Uint8Array(nodeCrypto.randomBytes(length));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
// Fallback ignored
|
|
49
|
+
}
|
|
50
|
+
const fallback = new Uint8Array(length);
|
|
51
|
+
for (let i = 0; i < length; i++) {
|
|
52
|
+
fallback[i] = Math.floor(Math.random() * 256);
|
|
53
|
+
}
|
|
54
|
+
return fallback;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Derives PBKDF2 keys using hardware-accelerated WebCrypto if available,
|
|
58
|
+
* fast 32-bit integer unboxed pure-JS for mobile performance (<=2000 iters),
|
|
59
|
+
* or non-blocking asynchronous pure-JS PBKDF2.
|
|
60
|
+
*/
|
|
61
|
+
async function derivePbkdf2Key(password, salt, iterations, algorithm = exports.DEFAULT_PASSWORD_ALGORITHM) {
|
|
62
|
+
const isSha256 = algorithm.toUpperCase().includes('SHA256');
|
|
63
|
+
const dkLen = isSha256 ? 32 : 64;
|
|
64
|
+
const hashName = isSha256 ? 'SHA-256' : 'SHA-512';
|
|
65
|
+
const hashFn = isSha256 ? sha2_js_1.sha256 : sha2_js_1.sha512;
|
|
66
|
+
// 1. Try hardware-accelerated WebCrypto if supported
|
|
67
|
+
const subtle = typeof globalThis !== 'undefined' ? globalThis.crypto?.subtle : undefined;
|
|
68
|
+
if (subtle?.importKey && subtle?.deriveBits) {
|
|
69
|
+
try {
|
|
70
|
+
const keyMaterial = await subtle.importKey('raw', (0, utils_js_1.utf8ToBytes)(password), { name: 'PBKDF2' }, false, ['deriveBits']);
|
|
71
|
+
const derivedBits = await subtle.deriveBits({
|
|
72
|
+
name: 'PBKDF2',
|
|
73
|
+
salt: salt,
|
|
74
|
+
iterations,
|
|
75
|
+
hash: hashName,
|
|
76
|
+
}, keyMaterial, dkLen * 8);
|
|
77
|
+
return new Uint8Array(derivedBits);
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
// Fallback to noble hashes
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
// 2. Pure-JS execution:
|
|
84
|
+
// With SHA-256 and <=2000 iterations, pbkdf2 uses native 32-bit unboxed integers without BigInt.
|
|
85
|
+
// In Hermes on mobile, this takes ~15-25ms. Running synchronously avoids timer queue latency.
|
|
86
|
+
if (iterations <= 2000 && isSha256) {
|
|
87
|
+
return (0, pbkdf2_js_1.pbkdf2)(hashFn, (0, utils_js_1.utf8ToBytes)(password), salt, {
|
|
88
|
+
c: iterations,
|
|
89
|
+
dkLen,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
// 3. For large iterations or SHA-512, yield to event loop
|
|
93
|
+
return await (0, pbkdf2_js_1.pbkdf2Async)(hashFn, (0, utils_js_1.utf8ToBytes)(password), salt, {
|
|
94
|
+
c: iterations,
|
|
95
|
+
dkLen,
|
|
96
|
+
asyncTick: 50,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Hashes a plaintext password using PBKDF2 with a cryptographically secure random salt.
|
|
101
|
+
*/
|
|
102
|
+
async function hashPassword(password, options = {}) {
|
|
103
|
+
const saltLen = options.saltBytes ?? exports.DEFAULT_SALT_BYTES;
|
|
104
|
+
const iterations = options.iterations ?? exports.DEFAULT_PASSWORD_ITERATIONS;
|
|
105
|
+
const algorithm = options.algorithm ?? exports.DEFAULT_PASSWORD_ALGORITHM;
|
|
106
|
+
const salt = getCryptoRandomBytes(saltLen);
|
|
107
|
+
const derivedKey = await derivePbkdf2Key(password, salt, iterations, algorithm);
|
|
108
|
+
return {
|
|
109
|
+
hash: (0, utils_js_1.bytesToHex)(derivedKey),
|
|
110
|
+
salt: (0, utils_js_1.bytesToHex)(salt),
|
|
111
|
+
iterations,
|
|
112
|
+
algorithm,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Verifies a plaintext password against a stored PBKDF2 hash using constant-time comparison.
|
|
117
|
+
*/
|
|
118
|
+
async function verifyPassword(password, expectedHashHex, saltHex, iterations, algorithm = exports.DEFAULT_PASSWORD_ALGORITHM) {
|
|
119
|
+
try {
|
|
120
|
+
const salt = (0, utils_js_1.hexToBytes)(saltHex);
|
|
121
|
+
const derivedKey = await derivePbkdf2Key(password, salt, iterations, algorithm);
|
|
122
|
+
const actualHashHex = (0, utils_js_1.bytesToHex)(derivedKey);
|
|
123
|
+
return (0, generator_js_1.timingSafeEqual)(actualHashHex.toLowerCase(), expectedHashHex.toLowerCase());
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Generates an opaque random token and its corresponding SHA-256 hash.
|
|
131
|
+
*/
|
|
132
|
+
function generateCryptoToken(lengthBytes = 32) {
|
|
133
|
+
const bytes = getCryptoRandomBytes(lengthBytes);
|
|
134
|
+
const token = (0, utils_js_1.bytesToHex)(bytes);
|
|
135
|
+
const hash = (0, utils_js_1.bytesToHex)((0, sha2_js_1.sha256)((0, utils_js_1.utf8ToBytes)(token)));
|
|
136
|
+
return { token, hash };
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Converts a raw database row into a sanitized user object without secret credentials.
|
|
140
|
+
*/
|
|
141
|
+
function mapStoredUserRow(row) {
|
|
142
|
+
let metadata = null;
|
|
143
|
+
if (row.metadata) {
|
|
144
|
+
try {
|
|
145
|
+
metadata = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata;
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
metadata = row.metadata;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
id: String(row.id),
|
|
153
|
+
email: String(row.email),
|
|
154
|
+
username: row.username ? String(row.username) : null,
|
|
155
|
+
displayName: row.display_name ? String(row.display_name) : null,
|
|
156
|
+
role: String(row.role || 'user'),
|
|
157
|
+
metadata,
|
|
158
|
+
status: row.status || 'active',
|
|
159
|
+
failedLoginAttempts: Number(row.failed_login_attempts || 0),
|
|
160
|
+
lockedUntil: row.locked_until != null ? Number(row.locked_until) : null,
|
|
161
|
+
emailVerified: row.email_verified === 1 || row.email_verified === '1' || row.email_verified === true,
|
|
162
|
+
createdAt: Number(row.created_at || 0),
|
|
163
|
+
updatedAt: Number(row.updated_at || 0),
|
|
164
|
+
lastLoginAt: row.last_login_at != null ? Number(row.last_login_at) : null,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Fully local, zero-backend authentication engine for SQLite.
|
|
169
|
+
* Manages users, PBKDF2-SHA512 crypto credentials, offline sessions, account lockout, and tokens.
|
|
170
|
+
*/
|
|
171
|
+
class LocalAuthEngine {
|
|
172
|
+
db;
|
|
173
|
+
events;
|
|
174
|
+
usersTable;
|
|
175
|
+
tokensTable;
|
|
176
|
+
sqlUsersTable;
|
|
177
|
+
sqlTokensTable;
|
|
178
|
+
algorithm;
|
|
179
|
+
iterations;
|
|
180
|
+
saltBytes;
|
|
181
|
+
maxFailedAttempts;
|
|
182
|
+
lockoutDurationMs;
|
|
183
|
+
resetTokenExpiryMs;
|
|
184
|
+
minPasswordLength;
|
|
185
|
+
customPasswordValidator;
|
|
186
|
+
sessionManager;
|
|
187
|
+
constructor(db, sessionOrManager, events, options = {}) {
|
|
188
|
+
this.db = db;
|
|
189
|
+
this.events = events;
|
|
190
|
+
this.usersTable = options.usersTable || exports.DEFAULT_USERS_TABLE;
|
|
191
|
+
this.tokensTable = options.tokensTable || exports.DEFAULT_USER_TOKENS_TABLE;
|
|
192
|
+
this.sqlUsersTable = (0, sql_js_1.escapeIdentifier)(this.usersTable);
|
|
193
|
+
this.sqlTokensTable = (0, sql_js_1.escapeIdentifier)(this.tokensTable);
|
|
194
|
+
this.algorithm = options.algorithm || exports.DEFAULT_PASSWORD_ALGORITHM;
|
|
195
|
+
this.iterations = options.iterations || exports.DEFAULT_PASSWORD_ITERATIONS;
|
|
196
|
+
this.saltBytes = options.saltBytes || exports.DEFAULT_SALT_BYTES;
|
|
197
|
+
this.maxFailedAttempts = options.maxFailedAttempts ?? exports.DEFAULT_LOCKOUT_ATTEMPTS;
|
|
198
|
+
this.lockoutDurationMs = options.lockoutDurationMs ?? exports.DEFAULT_LOCKOUT_DURATION_MS;
|
|
199
|
+
this.resetTokenExpiryMs = options.resetTokenExpiryMs ?? exports.DEFAULT_RESET_TOKEN_EXPIRY_MS;
|
|
200
|
+
this.minPasswordLength = options.minPasswordLength ?? exports.DEFAULT_MIN_PASSWORD_LENGTH;
|
|
201
|
+
this.customPasswordValidator = options.validatePassword;
|
|
202
|
+
if (sessionOrManager instanceof session_js_1.SessionManager) {
|
|
203
|
+
this.sessionManager = sessionOrManager;
|
|
204
|
+
}
|
|
205
|
+
else {
|
|
206
|
+
this.sessionManager = new session_js_1.SessionManager(this.db, this.events, sessionOrManager);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Retrieves the underlying SessionManager instance.
|
|
211
|
+
*/
|
|
212
|
+
getSessionManager() {
|
|
213
|
+
return this.sessionManager;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Initializes SQLite tables and indexes for users and tokens.
|
|
217
|
+
*/
|
|
218
|
+
async initialize() {
|
|
219
|
+
await this.sessionManager.initialize();
|
|
220
|
+
// 1. Users table
|
|
221
|
+
await this.db.execute(`
|
|
222
|
+
CREATE TABLE IF NOT EXISTS ${this.sqlUsersTable} (
|
|
223
|
+
id TEXT PRIMARY KEY,
|
|
224
|
+
email TEXT NOT NULL,
|
|
225
|
+
username TEXT,
|
|
226
|
+
display_name TEXT,
|
|
227
|
+
password_hash TEXT NOT NULL,
|
|
228
|
+
salt TEXT NOT NULL,
|
|
229
|
+
iterations INTEGER NOT NULL,
|
|
230
|
+
algorithm TEXT NOT NULL,
|
|
231
|
+
role TEXT NOT NULL DEFAULT 'user',
|
|
232
|
+
metadata TEXT,
|
|
233
|
+
status TEXT NOT NULL DEFAULT 'active',
|
|
234
|
+
failed_login_attempts INTEGER NOT NULL DEFAULT 0,
|
|
235
|
+
locked_until INTEGER,
|
|
236
|
+
email_verified INTEGER NOT NULL DEFAULT 0,
|
|
237
|
+
created_at INTEGER NOT NULL,
|
|
238
|
+
updated_at INTEGER NOT NULL,
|
|
239
|
+
last_login_at INTEGER
|
|
240
|
+
);
|
|
241
|
+
`);
|
|
242
|
+
await this.db.execute(`
|
|
243
|
+
CREATE UNIQUE INDEX IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(`idx_${this.usersTable}_email`)} ON ${this.sqlUsersTable} (email);
|
|
244
|
+
`);
|
|
245
|
+
await this.db.execute(`
|
|
246
|
+
CREATE UNIQUE INDEX IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(`idx_${this.usersTable}_username`)} ON ${this.sqlUsersTable} (username);
|
|
247
|
+
`);
|
|
248
|
+
await this.db.execute(`
|
|
249
|
+
CREATE INDEX IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(`idx_${this.usersTable}_status`)} ON ${this.sqlUsersTable} (status);
|
|
250
|
+
`);
|
|
251
|
+
// 2. Tokens table (password resets, email verification, recovery)
|
|
252
|
+
await this.db.execute(`
|
|
253
|
+
CREATE TABLE IF NOT EXISTS ${this.sqlTokensTable} (
|
|
254
|
+
id TEXT PRIMARY KEY,
|
|
255
|
+
user_id TEXT NOT NULL,
|
|
256
|
+
token_hash TEXT NOT NULL,
|
|
257
|
+
type TEXT NOT NULL,
|
|
258
|
+
expires_at INTEGER NOT NULL,
|
|
259
|
+
created_at INTEGER NOT NULL,
|
|
260
|
+
used_at INTEGER
|
|
261
|
+
);
|
|
262
|
+
`);
|
|
263
|
+
await this.db.execute(`
|
|
264
|
+
CREATE INDEX IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(`idx_${this.tokensTable}_hash`)} ON ${this.sqlTokensTable} (token_hash, type);
|
|
265
|
+
`);
|
|
266
|
+
await this.db.execute(`
|
|
267
|
+
CREATE INDEX IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(`idx_${this.tokensTable}_user`)} ON ${this.sqlTokensTable} (user_id);
|
|
268
|
+
`);
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Registers a new user with high-level crypto credentials.
|
|
272
|
+
*/
|
|
273
|
+
async signUp(options) {
|
|
274
|
+
const email = (options.email || '').trim().toLowerCase();
|
|
275
|
+
if (!email || !email.includes('@')) {
|
|
276
|
+
throw new Error('A valid email address is required.');
|
|
277
|
+
}
|
|
278
|
+
const username = options.username ? options.username.trim().toLowerCase() : null;
|
|
279
|
+
this.assertValidPassword(options.password);
|
|
280
|
+
// Uniqueness checks
|
|
281
|
+
const existingEmail = await this.getUserByEmail(email);
|
|
282
|
+
if (existingEmail) {
|
|
283
|
+
throw new Error('An account with this email address already exists.');
|
|
284
|
+
}
|
|
285
|
+
if (username) {
|
|
286
|
+
const existingUsername = await this.getUserByUsername(username);
|
|
287
|
+
if (existingUsername) {
|
|
288
|
+
throw new Error('This username is already taken.');
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
const id = options.id || (0, uuid_js_1.generateUUID)();
|
|
292
|
+
const now = Date.now();
|
|
293
|
+
const creds = await hashPassword(options.password, {
|
|
294
|
+
saltBytes: this.saltBytes,
|
|
295
|
+
iterations: this.iterations,
|
|
296
|
+
algorithm: this.algorithm,
|
|
297
|
+
});
|
|
298
|
+
const metadataStr = options.metadata ? JSON.stringify(options.metadata) : null;
|
|
299
|
+
const role = options.role || 'user';
|
|
300
|
+
const emailVerified = options.emailVerified ? 1 : 0;
|
|
301
|
+
await this.db.execute(`INSERT INTO ${this.sqlUsersTable} (
|
|
302
|
+
id, email, username, display_name, password_hash, salt, iterations, algorithm,
|
|
303
|
+
role, metadata, status, failed_login_attempts, locked_until, email_verified,
|
|
304
|
+
created_at, updated_at, last_login_at
|
|
305
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', 0, NULL, ?, ?, ?, NULL);`, [
|
|
306
|
+
id,
|
|
307
|
+
email,
|
|
308
|
+
username,
|
|
309
|
+
options.displayName || null,
|
|
310
|
+
creds.hash,
|
|
311
|
+
creds.salt,
|
|
312
|
+
creds.iterations,
|
|
313
|
+
creds.algorithm,
|
|
314
|
+
role,
|
|
315
|
+
metadataStr,
|
|
316
|
+
emailVerified,
|
|
317
|
+
now,
|
|
318
|
+
now,
|
|
319
|
+
]);
|
|
320
|
+
const user = {
|
|
321
|
+
id,
|
|
322
|
+
email,
|
|
323
|
+
username,
|
|
324
|
+
displayName: options.displayName || null,
|
|
325
|
+
role,
|
|
326
|
+
metadata: options.metadata || null,
|
|
327
|
+
status: 'active',
|
|
328
|
+
failedLoginAttempts: 0,
|
|
329
|
+
lockedUntil: null,
|
|
330
|
+
emailVerified: options.emailVerified ?? false,
|
|
331
|
+
createdAt: now,
|
|
332
|
+
updatedAt: now,
|
|
333
|
+
lastLoginAt: null,
|
|
334
|
+
};
|
|
335
|
+
let session = null;
|
|
336
|
+
if (options.setActiveSession !== false) {
|
|
337
|
+
session = await this.sessionManager.createSession({
|
|
338
|
+
userId: user.id,
|
|
339
|
+
user,
|
|
340
|
+
provider: 'local',
|
|
341
|
+
offlineDurationMs: options.offlineDurationMs,
|
|
342
|
+
setActive: true,
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
this.events?.emit(this.usersTable, { operation: 'SIGN_UP', user });
|
|
346
|
+
return { user, session };
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Authenticates a user by email or username using constant-time PBKDF2 comparison.
|
|
350
|
+
* Handles brute-force protection, account locking, and session initialization.
|
|
351
|
+
*/
|
|
352
|
+
async signIn(options) {
|
|
353
|
+
const identifier = (options.identifier || '').trim().toLowerCase();
|
|
354
|
+
const password = options.password || '';
|
|
355
|
+
if (!identifier || !password) {
|
|
356
|
+
throw new Error('Identifier and password are required.');
|
|
357
|
+
}
|
|
358
|
+
const rows = await this.db.execute(`SELECT * FROM ${this.sqlUsersTable} WHERE lower(email) = ? OR lower(username) = ? LIMIT 1;`, [identifier, identifier]);
|
|
359
|
+
const row = (rows && rows.length > 0 ? rows[0] : null);
|
|
360
|
+
if (!row) {
|
|
361
|
+
// Dummy verification to mitigate timing attacks against non-existent accounts
|
|
362
|
+
await verifyPassword('dummy_password', '0'.repeat(128), '0'.repeat(32), Math.min(this.iterations, 5_000));
|
|
363
|
+
throw new Error('Invalid email/username or password.');
|
|
364
|
+
}
|
|
365
|
+
const now = Date.now();
|
|
366
|
+
// Check account lockout
|
|
367
|
+
if (row.locked_until && row.locked_until > now) {
|
|
368
|
+
const waitMinutes = Math.ceil((row.locked_until - now) / 60000);
|
|
369
|
+
throw new Error(`Account is temporarily locked due to consecutive failed login attempts. Please try again in ${waitMinutes} minute(s).`);
|
|
370
|
+
}
|
|
371
|
+
// Check suspended status
|
|
372
|
+
if (row.status === 'suspended') {
|
|
373
|
+
throw new Error('Account has been suspended. Please contact support.');
|
|
374
|
+
}
|
|
375
|
+
// Verify password
|
|
376
|
+
const isValid = await verifyPassword(password, row.password_hash, row.salt, row.iterations, row.algorithm);
|
|
377
|
+
if (!isValid) {
|
|
378
|
+
const attempts = (row.failed_login_attempts || 0) + 1;
|
|
379
|
+
let lockedUntil = null;
|
|
380
|
+
let newStatus = row.status;
|
|
381
|
+
if (this.maxFailedAttempts > 0 && attempts >= this.maxFailedAttempts) {
|
|
382
|
+
lockedUntil = now + this.lockoutDurationMs;
|
|
383
|
+
newStatus = 'locked';
|
|
384
|
+
this.events?.emit(this.usersTable, {
|
|
385
|
+
operation: 'ACCOUNT_LOCKED',
|
|
386
|
+
userId: row.id,
|
|
387
|
+
lockedUntil,
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
await this.db.execute(`UPDATE ${this.sqlUsersTable} SET failed_login_attempts = ?, locked_until = ?, status = ?, updated_at = ? WHERE id = ?;`, [attempts, lockedUntil, newStatus, now, row.id]);
|
|
391
|
+
if (lockedUntil) {
|
|
392
|
+
const waitMinutes = Math.ceil(this.lockoutDurationMs / 60000);
|
|
393
|
+
throw new Error(`Account has been locked due to ${attempts} failed attempts. Please try again in ${waitMinutes} minute(s).`);
|
|
394
|
+
}
|
|
395
|
+
throw new Error('Invalid email/username or password.');
|
|
396
|
+
}
|
|
397
|
+
// Reset failed attempts and update last login timestamp
|
|
398
|
+
await this.db.execute(`UPDATE ${this.sqlUsersTable} SET failed_login_attempts = 0, locked_until = NULL, status = 'active', last_login_at = ?, updated_at = ? WHERE id = ?;`, [now, now, row.id]);
|
|
399
|
+
// Auto-upgrade legacy or slower hashes to modern PBKDF2-SHA256 standard
|
|
400
|
+
if (row.algorithm !== this.algorithm || row.iterations !== this.iterations) {
|
|
401
|
+
try {
|
|
402
|
+
const upgraded = await hashPassword(password, {
|
|
403
|
+
saltBytes: this.saltBytes,
|
|
404
|
+
iterations: this.iterations,
|
|
405
|
+
algorithm: this.algorithm,
|
|
406
|
+
});
|
|
407
|
+
await this.db.execute(`UPDATE ${this.sqlUsersTable} SET password_hash = ?, salt = ?, iterations = ?, algorithm = ? WHERE id = ?;`, [upgraded.hash, upgraded.salt, upgraded.iterations, upgraded.algorithm, row.id]);
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
// Non-critical upgrade
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
const user = mapStoredUserRow({
|
|
414
|
+
...row,
|
|
415
|
+
failed_login_attempts: 0,
|
|
416
|
+
locked_until: null,
|
|
417
|
+
status: 'active',
|
|
418
|
+
last_login_at: now,
|
|
419
|
+
});
|
|
420
|
+
let session = null;
|
|
421
|
+
if (options.setActiveSession !== false) {
|
|
422
|
+
session = await this.sessionManager.createSession({
|
|
423
|
+
userId: user.id,
|
|
424
|
+
user,
|
|
425
|
+
provider: 'local',
|
|
426
|
+
offlineDurationMs: options.offlineDurationMs,
|
|
427
|
+
setActive: true,
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
this.events?.emit(this.usersTable, { operation: 'SIGN_IN', user, session });
|
|
431
|
+
return { user, session };
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Signs out the active user and clears the local session.
|
|
435
|
+
*/
|
|
436
|
+
async signOut() {
|
|
437
|
+
const current = await this.sessionManager.getActiveSession();
|
|
438
|
+
await this.sessionManager.clearSession();
|
|
439
|
+
this.events?.emit(this.usersTable, { operation: 'SIGN_OUT', userId: current?.userId });
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Subscribes to authentication state changes (sign in, sign out, user updates).
|
|
443
|
+
*/
|
|
444
|
+
onAuthStateChange(listener) {
|
|
445
|
+
if (!this.events)
|
|
446
|
+
return () => { };
|
|
447
|
+
const unsubs = [
|
|
448
|
+
this.events.on(this.usersTable, () => {
|
|
449
|
+
this.getCurrentUser().then(listener).catch(() => { });
|
|
450
|
+
}),
|
|
451
|
+
this.events.on('_local_sessions', () => {
|
|
452
|
+
this.getCurrentUser().then(listener).catch(() => { });
|
|
453
|
+
}),
|
|
454
|
+
];
|
|
455
|
+
return () => {
|
|
456
|
+
unsubs.forEach((u) => u());
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Retrieves the currently authenticated local user based on the active session.
|
|
461
|
+
*/
|
|
462
|
+
async getCurrentUser() {
|
|
463
|
+
const session = await this.sessionManager.getActiveSession();
|
|
464
|
+
if (!session || !session.userId)
|
|
465
|
+
return null;
|
|
466
|
+
return this.getUserById(session.userId);
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Returns whether a valid user session is currently active.
|
|
470
|
+
*/
|
|
471
|
+
async isAuthenticated() {
|
|
472
|
+
return this.sessionManager.isAuthenticated();
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Finds a user by unique ID.
|
|
476
|
+
*/
|
|
477
|
+
async getUserById(id) {
|
|
478
|
+
const rows = await this.db.execute(`SELECT * FROM ${this.sqlUsersTable} WHERE id = ? LIMIT 1;`, [id]);
|
|
479
|
+
if (!rows || rows.length === 0)
|
|
480
|
+
return null;
|
|
481
|
+
return mapStoredUserRow(rows[0]);
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Finds a user by email address (case-insensitive).
|
|
485
|
+
*/
|
|
486
|
+
async getUserByEmail(email) {
|
|
487
|
+
const rows = await this.db.execute(`SELECT * FROM ${this.sqlUsersTable} WHERE lower(email) = ? LIMIT 1;`, [email.trim().toLowerCase()]);
|
|
488
|
+
if (!rows || rows.length === 0)
|
|
489
|
+
return null;
|
|
490
|
+
return mapStoredUserRow(rows[0]);
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Finds a user by username (case-insensitive).
|
|
494
|
+
*/
|
|
495
|
+
async getUserByUsername(username) {
|
|
496
|
+
const rows = await this.db.execute(`SELECT * FROM ${this.sqlUsersTable} WHERE lower(username) = ? LIMIT 1;`, [username.trim().toLowerCase()]);
|
|
497
|
+
if (!rows || rows.length === 0)
|
|
498
|
+
return null;
|
|
499
|
+
return mapStoredUserRow(rows[0]);
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Changes a user's password after verifying their existing password.
|
|
503
|
+
*/
|
|
504
|
+
async changePassword(options) {
|
|
505
|
+
const rows = await this.db.execute(`SELECT * FROM ${this.sqlUsersTable} WHERE id = ? LIMIT 1;`, [options.userId]);
|
|
506
|
+
const row = (rows && rows.length > 0 ? rows[0] : null);
|
|
507
|
+
if (!row) {
|
|
508
|
+
throw new Error('User not found.');
|
|
509
|
+
}
|
|
510
|
+
const isOldValid = await verifyPassword(options.oldPassword, row.password_hash, row.salt, row.iterations, row.algorithm);
|
|
511
|
+
if (!isOldValid) {
|
|
512
|
+
throw new Error('Current password is incorrect.');
|
|
513
|
+
}
|
|
514
|
+
this.assertValidPassword(options.newPassword);
|
|
515
|
+
const now = Date.now();
|
|
516
|
+
const creds = await hashPassword(options.newPassword, {
|
|
517
|
+
saltBytes: this.saltBytes,
|
|
518
|
+
iterations: this.iterations,
|
|
519
|
+
algorithm: this.algorithm,
|
|
520
|
+
});
|
|
521
|
+
await this.db.execute(`UPDATE ${this.sqlUsersTable} SET password_hash = ?, salt = ?, iterations = ?, algorithm = ?, updated_at = ? WHERE id = ?;`, [creds.hash, creds.salt, creds.iterations, creds.algorithm, now, options.userId]);
|
|
522
|
+
this.events?.emit(this.usersTable, {
|
|
523
|
+
operation: 'PASSWORD_CHANGED',
|
|
524
|
+
userId: options.userId,
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Generates a cryptographically secure, single-use password reset token with expiration.
|
|
529
|
+
*/
|
|
530
|
+
async createPasswordResetToken(emailOrUsername) {
|
|
531
|
+
const identifier = (emailOrUsername || '').trim().toLowerCase();
|
|
532
|
+
const rows = await this.db.execute(`SELECT id FROM ${this.sqlUsersTable} WHERE lower(email) = ? OR lower(username) = ? LIMIT 1;`, [identifier, identifier]);
|
|
533
|
+
if (!rows || rows.length === 0) {
|
|
534
|
+
throw new Error('No account found matching this identifier.');
|
|
535
|
+
}
|
|
536
|
+
const userId = String(rows[0].id);
|
|
537
|
+
const { token, hash } = generateCryptoToken(32);
|
|
538
|
+
const now = Date.now();
|
|
539
|
+
const expiresAt = now + this.resetTokenExpiryMs;
|
|
540
|
+
const tokenId = (0, uuid_js_1.generateUUID)();
|
|
541
|
+
await this.db.execute(`INSERT INTO ${this.sqlTokensTable} (id, user_id, token_hash, type, expires_at, created_at, used_at)
|
|
542
|
+
VALUES (?, ?, ?, 'reset_password', ?, ?, NULL);`, [tokenId, userId, hash, expiresAt, now]);
|
|
543
|
+
return { token, expiresAt };
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Resets a user's password using a valid cryptographic reset token.
|
|
547
|
+
*/
|
|
548
|
+
async resetPasswordWithToken(token, newPassword) {
|
|
549
|
+
if (!token || !token.trim()) {
|
|
550
|
+
throw new Error('A valid reset token is required.');
|
|
551
|
+
}
|
|
552
|
+
this.assertValidPassword(newPassword);
|
|
553
|
+
const tokenHash = (0, utils_js_1.bytesToHex)((0, sha2_js_1.sha256)((0, utils_js_1.utf8ToBytes)(token.trim())));
|
|
554
|
+
const now = Date.now();
|
|
555
|
+
const rows = await this.db.execute(`SELECT * FROM ${this.sqlTokensTable} WHERE token_hash = ? AND type = 'reset_password' AND used_at IS NULL AND expires_at > ? LIMIT 1;`, [tokenHash, now]);
|
|
556
|
+
if (!rows || rows.length === 0) {
|
|
557
|
+
throw new Error('Password reset token is invalid or has expired.');
|
|
558
|
+
}
|
|
559
|
+
const tokenRow = rows[0];
|
|
560
|
+
const userId = String(tokenRow.user_id);
|
|
561
|
+
const creds = await hashPassword(newPassword, {
|
|
562
|
+
saltBytes: this.saltBytes,
|
|
563
|
+
iterations: this.iterations,
|
|
564
|
+
algorithm: this.algorithm,
|
|
565
|
+
});
|
|
566
|
+
// Invalidate token
|
|
567
|
+
await this.db.execute(`UPDATE ${this.sqlTokensTable} SET used_at = ? WHERE id = ?;`, [now, tokenRow.id]);
|
|
568
|
+
// Update password and unlock account
|
|
569
|
+
await this.db.execute(`UPDATE ${this.sqlUsersTable} SET password_hash = ?, salt = ?, iterations = ?, algorithm = ?, failed_login_attempts = 0, locked_until = NULL, status = 'active', updated_at = ? WHERE id = ?;`, [creds.hash, creds.salt, creds.iterations, creds.algorithm, now, userId]);
|
|
570
|
+
this.events?.emit(this.usersTable, {
|
|
571
|
+
operation: 'PASSWORD_RESET',
|
|
572
|
+
userId,
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Updates an existing user's profile, role, or metadata.
|
|
577
|
+
*/
|
|
578
|
+
async updateUser(id, updates) {
|
|
579
|
+
const existing = await this.getUserById(id);
|
|
580
|
+
if (!existing) {
|
|
581
|
+
throw new Error('User not found.');
|
|
582
|
+
}
|
|
583
|
+
const now = Date.now();
|
|
584
|
+
const setClauses = ['updated_at = ?'];
|
|
585
|
+
const params = [now];
|
|
586
|
+
if (updates.email !== undefined) {
|
|
587
|
+
const email = updates.email.trim().toLowerCase();
|
|
588
|
+
if (!email.includes('@'))
|
|
589
|
+
throw new Error('A valid email address is required.');
|
|
590
|
+
if (email !== existing.email) {
|
|
591
|
+
const conflict = await this.getUserByEmail(email);
|
|
592
|
+
if (conflict && conflict.id !== id) {
|
|
593
|
+
throw new Error('Email address is already in use by another account.');
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
setClauses.push('email = ?');
|
|
597
|
+
params.push(email);
|
|
598
|
+
}
|
|
599
|
+
if (updates.username !== undefined) {
|
|
600
|
+
const username = updates.username ? updates.username.trim().toLowerCase() : null;
|
|
601
|
+
if (username && username !== existing.username) {
|
|
602
|
+
const conflict = await this.getUserByUsername(username);
|
|
603
|
+
if (conflict && conflict.id !== id) {
|
|
604
|
+
throw new Error('Username is already in use by another account.');
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
setClauses.push('username = ?');
|
|
608
|
+
params.push(username);
|
|
609
|
+
}
|
|
610
|
+
if (updates.displayName !== undefined) {
|
|
611
|
+
setClauses.push('display_name = ?');
|
|
612
|
+
params.push(updates.displayName);
|
|
613
|
+
}
|
|
614
|
+
if (updates.role !== undefined) {
|
|
615
|
+
setClauses.push('role = ?');
|
|
616
|
+
params.push(updates.role);
|
|
617
|
+
}
|
|
618
|
+
if (updates.status !== undefined) {
|
|
619
|
+
setClauses.push('status = ?');
|
|
620
|
+
params.push(updates.status);
|
|
621
|
+
}
|
|
622
|
+
if (updates.emailVerified !== undefined) {
|
|
623
|
+
setClauses.push('email_verified = ?');
|
|
624
|
+
params.push(updates.emailVerified ? 1 : 0);
|
|
625
|
+
}
|
|
626
|
+
if (updates.metadata !== undefined) {
|
|
627
|
+
setClauses.push('metadata = ?');
|
|
628
|
+
params.push(updates.metadata ? JSON.stringify(updates.metadata) : null);
|
|
629
|
+
}
|
|
630
|
+
params.push(id);
|
|
631
|
+
await this.db.execute(`UPDATE ${this.sqlUsersTable} SET ${setClauses.join(', ')} WHERE id = ?;`, params);
|
|
632
|
+
const updated = (await this.getUserById(id));
|
|
633
|
+
// If active session belongs to this user, update cached user data
|
|
634
|
+
const active = await this.sessionManager.getActiveSession();
|
|
635
|
+
if (active && active.userId === id) {
|
|
636
|
+
await this.sessionManager.updateUser(updated);
|
|
637
|
+
}
|
|
638
|
+
this.events?.emit(this.usersTable, { operation: 'USER_UPDATED', user: updated });
|
|
639
|
+
return updated;
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Permanently deletes a user, their associated tokens, and clears any active session.
|
|
643
|
+
*/
|
|
644
|
+
async deleteUser(id) {
|
|
645
|
+
await this.db.execute(`DELETE FROM ${this.sqlTokensTable} WHERE user_id = ?;`, [id]);
|
|
646
|
+
await this.db.execute(`DELETE FROM ${this.sqlUsersTable} WHERE id = ?;`, [id]);
|
|
647
|
+
const active = await this.sessionManager.getActiveSession();
|
|
648
|
+
if (active && active.userId === id) {
|
|
649
|
+
await this.sessionManager.clearSession();
|
|
650
|
+
}
|
|
651
|
+
this.events?.emit(this.usersTable, { operation: 'USER_DELETED', userId: id });
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Manually locks a user account.
|
|
655
|
+
*/
|
|
656
|
+
async lockAccount(userId, durationMs) {
|
|
657
|
+
const now = Date.now();
|
|
658
|
+
const duration = durationMs ?? this.lockoutDurationMs;
|
|
659
|
+
const lockedUntil = now + duration;
|
|
660
|
+
await this.db.execute(`UPDATE ${this.sqlUsersTable} SET status = 'locked', locked_until = ?, updated_at = ? WHERE id = ?;`, [lockedUntil, now, userId]);
|
|
661
|
+
this.events?.emit(this.usersTable, { operation: 'ACCOUNT_LOCKED', userId, lockedUntil });
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Manually unlocks a user account and clears failed login attempts.
|
|
665
|
+
*/
|
|
666
|
+
async unlockAccount(userId) {
|
|
667
|
+
const now = Date.now();
|
|
668
|
+
await this.db.execute(`UPDATE ${this.sqlUsersTable} SET status = 'active', failed_login_attempts = 0, locked_until = NULL, updated_at = ? WHERE id = ?;`, [now, userId]);
|
|
669
|
+
this.events?.emit(this.usersTable, { operation: 'ACCOUNT_UNLOCKED', userId });
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Lists local users with optional role, status filtering, and pagination.
|
|
673
|
+
*/
|
|
674
|
+
async listUsers(options = {}) {
|
|
675
|
+
const conditions = [];
|
|
676
|
+
const params = [];
|
|
677
|
+
if (options.status) {
|
|
678
|
+
conditions.push('status = ?');
|
|
679
|
+
params.push(options.status);
|
|
680
|
+
}
|
|
681
|
+
if (options.role) {
|
|
682
|
+
conditions.push('role = ?');
|
|
683
|
+
params.push(options.role);
|
|
684
|
+
}
|
|
685
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
|
|
686
|
+
const limit = options.limit ?? 50;
|
|
687
|
+
const offset = options.offset ?? 0;
|
|
688
|
+
const rows = await this.db.execute(`SELECT * FROM ${this.sqlUsersTable} ${whereClause} ORDER BY created_at DESC LIMIT ? OFFSET ?;`, [...params, limit, offset]);
|
|
689
|
+
return (rows || []).map((r) => mapStoredUserRow(r));
|
|
690
|
+
}
|
|
691
|
+
assertValidPassword(password) {
|
|
692
|
+
if (!password || typeof password !== 'string') {
|
|
693
|
+
throw new Error('A password must be provided.');
|
|
694
|
+
}
|
|
695
|
+
if (password.length < this.minPasswordLength) {
|
|
696
|
+
throw new Error(`Password must be at least ${this.minPasswordLength} characters long.`);
|
|
697
|
+
}
|
|
698
|
+
if (this.customPasswordValidator) {
|
|
699
|
+
const res = this.customPasswordValidator(password);
|
|
700
|
+
if (res === false) {
|
|
701
|
+
throw new Error('Password does not meet complexity requirements.');
|
|
702
|
+
}
|
|
703
|
+
if (typeof res === 'string') {
|
|
704
|
+
throw new Error(res);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
exports.LocalAuthEngine = LocalAuthEngine;
|