local-lite 3.0.1 → 3.0.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/dist/auth/local.d.ts +30 -4
- package/dist/auth/local.js +170 -43
- package/dist/config/resolve-remote.js +1 -0
- package/dist/config/types.d.ts +4 -0
- package/dist/core/index.d.ts +1 -1
- package/dist/server/auth.d.ts +113 -0
- package/dist/server/auth.js +452 -0
- package/dist/server/dashboard.js +25 -34
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +1 -0
- package/dist/utils/http.d.ts +8 -0
- package/dist/utils/http.js +26 -0
- package/package.json +6 -1
package/dist/auth/local.d.ts
CHANGED
|
@@ -94,15 +94,34 @@ export interface LocalAuthEngineOptions {
|
|
|
94
94
|
* Optional remote authentication handler to exchange local sessions for remote sync provider tokens.
|
|
95
95
|
*/
|
|
96
96
|
remoteAuthHandler?: RemoteAuthHandler;
|
|
97
|
+
/**
|
|
98
|
+
* Built-in remote auth endpoint configuration (e.g. `{ url: 'https://api.example.com' }`).
|
|
99
|
+
* Auto-wires `remoteAuthHandler` to `POST <url>/auth/local` and `POST <url>/auth/local/refresh`.
|
|
100
|
+
*/
|
|
101
|
+
remote?: {
|
|
102
|
+
url: string;
|
|
103
|
+
fetch?: typeof fetch;
|
|
104
|
+
headers?: Record<string, string>;
|
|
105
|
+
};
|
|
97
106
|
}
|
|
98
107
|
export interface RemoteAuthExchangeContext<TMetadata = any> {
|
|
99
108
|
user: LocalUser<TMetadata>;
|
|
100
109
|
session: SessionRecord<LocalUser<TMetadata>>;
|
|
110
|
+
mode?: 'signin' | 'signup' | 'refresh';
|
|
111
|
+
password?: string;
|
|
101
112
|
}
|
|
102
113
|
export type RemoteAuthHandler<TMetadata = any> = (context: RemoteAuthExchangeContext<TMetadata>) => Promise<{
|
|
103
114
|
token: string;
|
|
104
115
|
[key: string]: any;
|
|
105
116
|
} | null>;
|
|
117
|
+
export interface CreateResetTokenOptions {
|
|
118
|
+
format?: 'hex' | 'otp6';
|
|
119
|
+
expiresInMs?: number;
|
|
120
|
+
maxAttempts?: number;
|
|
121
|
+
}
|
|
122
|
+
export interface ResetPasswordWithTokenOptions {
|
|
123
|
+
identifier?: string;
|
|
124
|
+
}
|
|
106
125
|
export interface SignUpOptions<TMetadata = Record<string, any>> {
|
|
107
126
|
id?: string;
|
|
108
127
|
email: string;
|
|
@@ -179,6 +198,11 @@ export declare function hashPassword(password: string, options?: {
|
|
|
179
198
|
* Verifies a plaintext password against a stored PBKDF2 hash using constant-time comparison.
|
|
180
199
|
*/
|
|
181
200
|
export declare function verifyPassword(password: string, expectedHashHex: string, saltHex: string, iterations: number, algorithm?: string): Promise<boolean>;
|
|
201
|
+
/**
|
|
202
|
+
* Performs a constant-time dummy password verification to mitigate
|
|
203
|
+
* timing-based account enumeration when an account does not exist.
|
|
204
|
+
*/
|
|
205
|
+
export declare function verifyDummyPassword(iterations?: number): Promise<void>;
|
|
182
206
|
/**
|
|
183
207
|
* Generates an opaque random token and its corresponding SHA-256 hash.
|
|
184
208
|
*/
|
|
@@ -220,6 +244,8 @@ export declare class LocalAuthEngine {
|
|
|
220
244
|
* Gets the configured remote authentication exchange handler.
|
|
221
245
|
*/
|
|
222
246
|
getRemoteAuthHandler(): RemoteAuthHandler | undefined;
|
|
247
|
+
private performRemoteAuthExchange;
|
|
248
|
+
private tryRemoteAuthExchange;
|
|
223
249
|
/**
|
|
224
250
|
* Triggers token exchange with the registered remote sync provider for the active session.
|
|
225
251
|
*/
|
|
@@ -281,13 +307,13 @@ export declare class LocalAuthEngine {
|
|
|
281
307
|
*/
|
|
282
308
|
changePassword(options: ChangePasswordOptions): Promise<void>;
|
|
283
309
|
/**
|
|
284
|
-
* Generates a cryptographically secure, single-use password reset token with expiration.
|
|
310
|
+
* Generates a cryptographically secure, single-use password reset token or 6-digit OTP with expiration.
|
|
285
311
|
*/
|
|
286
|
-
createPasswordResetToken(emailOrUsername: string): Promise<CreateResetTokenResult>;
|
|
312
|
+
createPasswordResetToken(emailOrUsername: string, options?: CreateResetTokenOptions): Promise<CreateResetTokenResult>;
|
|
287
313
|
/**
|
|
288
|
-
* Resets a user's password using a valid cryptographic reset token.
|
|
314
|
+
* Resets a user's password using a valid cryptographic reset token or 6-digit OTP.
|
|
289
315
|
*/
|
|
290
|
-
resetPasswordWithToken(token: string, newPassword: string): Promise<void>;
|
|
316
|
+
resetPasswordWithToken(token: string, newPassword: string, options?: ResetPasswordWithTokenOptions): Promise<void>;
|
|
291
317
|
/**
|
|
292
318
|
* Updates an existing user's profile, role, or metadata.
|
|
293
319
|
*/
|
package/dist/auth/local.js
CHANGED
|
@@ -5,6 +5,7 @@ exports.getCryptoRandomBytes = getCryptoRandomBytes;
|
|
|
5
5
|
exports.derivePbkdf2Key = derivePbkdf2Key;
|
|
6
6
|
exports.hashPassword = hashPassword;
|
|
7
7
|
exports.verifyPassword = verifyPassword;
|
|
8
|
+
exports.verifyDummyPassword = verifyDummyPassword;
|
|
8
9
|
exports.generateCryptoToken = generateCryptoToken;
|
|
9
10
|
exports.mapStoredUserRow = mapStoredUserRow;
|
|
10
11
|
const pbkdf2_js_1 = require("@noble/hashes/pbkdf2.js");
|
|
@@ -106,6 +107,13 @@ async function verifyPassword(password, expectedHashHex, saltHex, iterations, al
|
|
|
106
107
|
return false;
|
|
107
108
|
}
|
|
108
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* Performs a constant-time dummy password verification to mitigate
|
|
112
|
+
* timing-based account enumeration when an account does not exist.
|
|
113
|
+
*/
|
|
114
|
+
async function verifyDummyPassword(iterations = exports.DEFAULT_PASSWORD_ITERATIONS) {
|
|
115
|
+
await verifyPassword('dummy_password', '0'.repeat(128), '0'.repeat(32), Math.min(iterations, 5_000));
|
|
116
|
+
}
|
|
109
117
|
/**
|
|
110
118
|
* Generates an opaque random token and its corresponding SHA-256 hash.
|
|
111
119
|
*/
|
|
@@ -205,7 +213,46 @@ class LocalAuthEngine {
|
|
|
205
213
|
this.minPasswordLength =
|
|
206
214
|
resolvedOptions.minPasswordLength ?? exports.DEFAULT_MIN_PASSWORD_LENGTH;
|
|
207
215
|
this.customPasswordValidator = resolvedOptions.validatePassword;
|
|
208
|
-
this.remoteAuthHandler =
|
|
216
|
+
this.remoteAuthHandler =
|
|
217
|
+
resolvedOptions.remoteAuthHandler ??
|
|
218
|
+
(resolvedOptions.remote?.url
|
|
219
|
+
? async ({ user, session, mode, password }) => {
|
|
220
|
+
const baseUrl = resolvedOptions.remote.url.replace(/\/+$/, '');
|
|
221
|
+
const fetchFn = resolvedOptions.remote.fetch || globalThis.fetch;
|
|
222
|
+
if (!fetchFn)
|
|
223
|
+
return null;
|
|
224
|
+
const customHeaders = resolvedOptions.remote.headers ?? {};
|
|
225
|
+
const isRefresh = mode === 'refresh' || !password;
|
|
226
|
+
if (isRefresh && !session?.token)
|
|
227
|
+
return null;
|
|
228
|
+
const endpoint = isRefresh
|
|
229
|
+
? `${baseUrl}/auth/local/refresh`
|
|
230
|
+
: `${baseUrl}/auth/local`;
|
|
231
|
+
const headers = {
|
|
232
|
+
'Content-Type': 'application/json',
|
|
233
|
+
...customHeaders,
|
|
234
|
+
...(isRefresh ? { Authorization: `Bearer ${session.token}` } : {}),
|
|
235
|
+
};
|
|
236
|
+
const res = await fetchFn(endpoint, {
|
|
237
|
+
method: 'POST',
|
|
238
|
+
headers,
|
|
239
|
+
...(isRefresh
|
|
240
|
+
? {}
|
|
241
|
+
: {
|
|
242
|
+
body: JSON.stringify({
|
|
243
|
+
mode: mode === 'signup' ? 'signup' : 'signin',
|
|
244
|
+
email: user.email,
|
|
245
|
+
password,
|
|
246
|
+
displayName: user.displayName ?? undefined,
|
|
247
|
+
}),
|
|
248
|
+
}),
|
|
249
|
+
});
|
|
250
|
+
if (!res.ok)
|
|
251
|
+
return null;
|
|
252
|
+
const data = (await res.json());
|
|
253
|
+
return data?.token ? { token: data.token } : null;
|
|
254
|
+
}
|
|
255
|
+
: undefined);
|
|
209
256
|
if (resolvedSession instanceof session_js_1.SessionManager) {
|
|
210
257
|
this.sessionManager = resolvedSession;
|
|
211
258
|
}
|
|
@@ -225,6 +272,26 @@ class LocalAuthEngine {
|
|
|
225
272
|
getRemoteAuthHandler() {
|
|
226
273
|
return this.remoteAuthHandler;
|
|
227
274
|
}
|
|
275
|
+
async performRemoteAuthExchange(context) {
|
|
276
|
+
if (!this.remoteAuthHandler)
|
|
277
|
+
return null;
|
|
278
|
+
const result = await this.remoteAuthHandler(context);
|
|
279
|
+
if (result && result.token) {
|
|
280
|
+
await this.sessionManager.updateTokens({ token: result.token });
|
|
281
|
+
context.session.token = result.token;
|
|
282
|
+
}
|
|
283
|
+
return result;
|
|
284
|
+
}
|
|
285
|
+
async tryRemoteAuthExchange(context) {
|
|
286
|
+
if (!this.remoteAuthHandler)
|
|
287
|
+
return;
|
|
288
|
+
try {
|
|
289
|
+
await this.performRemoteAuthExchange(context);
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
// Non-fatal if offline
|
|
293
|
+
}
|
|
294
|
+
}
|
|
228
295
|
/**
|
|
229
296
|
* Triggers token exchange with the registered remote sync provider for the active session.
|
|
230
297
|
*/
|
|
@@ -237,12 +304,11 @@ class LocalAuthEngine {
|
|
|
237
304
|
const user = await this.getUserById(session.userId);
|
|
238
305
|
if (!user)
|
|
239
306
|
return null;
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
}
|
|
245
|
-
return result;
|
|
307
|
+
return this.performRemoteAuthExchange({
|
|
308
|
+
user,
|
|
309
|
+
session,
|
|
310
|
+
mode: 'refresh',
|
|
311
|
+
});
|
|
246
312
|
}
|
|
247
313
|
/**
|
|
248
314
|
* Retrieves the cached remote sync authentication token from the active session.
|
|
@@ -300,11 +366,26 @@ class LocalAuthEngine {
|
|
|
300
366
|
user_id TEXT NOT NULL,
|
|
301
367
|
token_hash TEXT NOT NULL,
|
|
302
368
|
type TEXT NOT NULL,
|
|
369
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
370
|
+
max_attempts INTEGER NOT NULL DEFAULT 1,
|
|
303
371
|
expires_at INTEGER NOT NULL,
|
|
304
372
|
created_at INTEGER NOT NULL,
|
|
305
373
|
used_at INTEGER
|
|
306
374
|
);
|
|
307
375
|
`);
|
|
376
|
+
// Backfill attempts/max_attempts columns on existing pre-3.x token tables
|
|
377
|
+
try {
|
|
378
|
+
await this.db.execute(`ALTER TABLE ${this.sqlTokensTable} ADD COLUMN attempts INTEGER NOT NULL DEFAULT 0;`);
|
|
379
|
+
}
|
|
380
|
+
catch {
|
|
381
|
+
// Column already exists
|
|
382
|
+
}
|
|
383
|
+
try {
|
|
384
|
+
await this.db.execute(`ALTER TABLE ${this.sqlTokensTable} ADD COLUMN max_attempts INTEGER NOT NULL DEFAULT 1;`);
|
|
385
|
+
}
|
|
386
|
+
catch {
|
|
387
|
+
// Column already exists
|
|
388
|
+
}
|
|
308
389
|
await this.db.execute(`
|
|
309
390
|
CREATE INDEX IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(`idx_${this.tokensTable}_hash`)} ON ${this.sqlTokensTable} (token_hash, type);
|
|
310
391
|
`);
|
|
@@ -390,17 +471,13 @@ class LocalAuthEngine {
|
|
|
390
471
|
offlineDurationMs: options.offlineDurationMs,
|
|
391
472
|
setActive: true,
|
|
392
473
|
});
|
|
393
|
-
if (
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
}
|
|
401
|
-
catch {
|
|
402
|
-
// Non-fatal if offline
|
|
403
|
-
}
|
|
474
|
+
if (session) {
|
|
475
|
+
await this.tryRemoteAuthExchange({
|
|
476
|
+
user,
|
|
477
|
+
session,
|
|
478
|
+
mode: 'signup',
|
|
479
|
+
password: options.password,
|
|
480
|
+
});
|
|
404
481
|
}
|
|
405
482
|
}
|
|
406
483
|
this.events?.emit(this.usersTable, { operation: 'SIGN_UP', user });
|
|
@@ -419,8 +496,7 @@ class LocalAuthEngine {
|
|
|
419
496
|
const rows = await this.db.execute(`SELECT * FROM ${this.sqlUsersTable} WHERE lower(email) = ? OR lower(username) = ? LIMIT 1;`, [identifier, identifier]);
|
|
420
497
|
const row = (rows && rows.length > 0 ? rows[0] : null);
|
|
421
498
|
if (!row) {
|
|
422
|
-
|
|
423
|
-
await verifyPassword('dummy_password', '0'.repeat(128), '0'.repeat(32), Math.min(this.iterations, 5_000));
|
|
499
|
+
await verifyDummyPassword(this.iterations);
|
|
424
500
|
throw new Error('Invalid email/username or password.');
|
|
425
501
|
}
|
|
426
502
|
const now = Date.now();
|
|
@@ -494,17 +570,13 @@ class LocalAuthEngine {
|
|
|
494
570
|
offlineDurationMs: options.offlineDurationMs,
|
|
495
571
|
setActive: true,
|
|
496
572
|
});
|
|
497
|
-
if (
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
}
|
|
505
|
-
catch {
|
|
506
|
-
// Non-fatal if offline
|
|
507
|
-
}
|
|
573
|
+
if (session) {
|
|
574
|
+
await this.tryRemoteAuthExchange({
|
|
575
|
+
user,
|
|
576
|
+
session,
|
|
577
|
+
mode: 'signin',
|
|
578
|
+
password,
|
|
579
|
+
});
|
|
508
580
|
}
|
|
509
581
|
}
|
|
510
582
|
this.events?.emit(this.usersTable, { operation: 'SIGN_IN', user, session });
|
|
@@ -619,38 +691,93 @@ class LocalAuthEngine {
|
|
|
619
691
|
});
|
|
620
692
|
}
|
|
621
693
|
/**
|
|
622
|
-
* Generates a cryptographically secure, single-use password reset token with expiration.
|
|
694
|
+
* Generates a cryptographically secure, single-use password reset token or 6-digit OTP with expiration.
|
|
623
695
|
*/
|
|
624
|
-
async createPasswordResetToken(emailOrUsername) {
|
|
696
|
+
async createPasswordResetToken(emailOrUsername, options = {}) {
|
|
625
697
|
const identifier = (emailOrUsername || '').trim().toLowerCase();
|
|
626
698
|
const rows = await this.db.execute(`SELECT id FROM ${this.sqlUsersTable} WHERE lower(email) = ? OR lower(username) = ? LIMIT 1;`, [identifier, identifier]);
|
|
627
699
|
if (!rows || rows.length === 0) {
|
|
628
700
|
throw new Error('No account found matching this identifier.');
|
|
629
701
|
}
|
|
630
702
|
const userId = String(rows[0].id);
|
|
631
|
-
const
|
|
703
|
+
const format = options.format ?? 'hex';
|
|
704
|
+
let token;
|
|
705
|
+
let hash;
|
|
706
|
+
if (format === 'otp6') {
|
|
707
|
+
// Rejection sampling avoids modulo bias across [0, 900000)
|
|
708
|
+
const limit = 4_294_800_000;
|
|
709
|
+
let num = limit;
|
|
710
|
+
while (num >= limit) {
|
|
711
|
+
const randomVal = getCryptoRandomBytes(4);
|
|
712
|
+
num =
|
|
713
|
+
((randomVal[0] << 24) |
|
|
714
|
+
(randomVal[1] << 16) |
|
|
715
|
+
(randomVal[2] << 8) |
|
|
716
|
+
randomVal[3]) >>>
|
|
717
|
+
0;
|
|
718
|
+
}
|
|
719
|
+
token = String(100000 + (num % 900000));
|
|
720
|
+
hash = (0, utils_js_1.bytesToHex)((0, sha2_js_1.sha256)((0, utils_js_1.utf8ToBytes)(token)));
|
|
721
|
+
}
|
|
722
|
+
else {
|
|
723
|
+
const generated = generateCryptoToken(32);
|
|
724
|
+
token = generated.token;
|
|
725
|
+
hash = generated.hash;
|
|
726
|
+
}
|
|
632
727
|
const now = Date.now();
|
|
633
|
-
const expiresAt = now + this.resetTokenExpiryMs;
|
|
728
|
+
const expiresAt = now + (options.expiresInMs ?? this.resetTokenExpiryMs);
|
|
729
|
+
const maxAttempts = options.maxAttempts ?? (format === 'otp6' ? 5 : 1);
|
|
634
730
|
const tokenId = (0, uuid_js_1.generateUUID)();
|
|
635
|
-
|
|
636
|
-
|
|
731
|
+
if (format === 'otp6') {
|
|
732
|
+
await this.db.execute(`UPDATE ${this.sqlTokensTable} SET used_at = ? WHERE user_id = ? AND type = 'reset_password' AND used_at IS NULL;`, [now, userId]);
|
|
733
|
+
}
|
|
734
|
+
await this.db.execute(`INSERT INTO ${this.sqlTokensTable} (id, user_id, token_hash, type, attempts, max_attempts, expires_at, created_at, used_at)
|
|
735
|
+
VALUES (?, ?, ?, 'reset_password', 0, ?, ?, ?, NULL);`, [tokenId, userId, hash, maxAttempts, expiresAt, now]);
|
|
637
736
|
return { token, expiresAt };
|
|
638
737
|
}
|
|
639
738
|
/**
|
|
640
|
-
* Resets a user's password using a valid cryptographic reset token.
|
|
739
|
+
* Resets a user's password using a valid cryptographic reset token or 6-digit OTP.
|
|
641
740
|
*/
|
|
642
|
-
async resetPasswordWithToken(token, newPassword) {
|
|
741
|
+
async resetPasswordWithToken(token, newPassword, options = {}) {
|
|
643
742
|
if (!token || !token.trim()) {
|
|
644
743
|
throw new Error('A valid reset token is required.');
|
|
645
744
|
}
|
|
646
745
|
this.assertValidPassword(newPassword);
|
|
647
746
|
const tokenHash = (0, utils_js_1.bytesToHex)((0, sha2_js_1.sha256)((0, utils_js_1.utf8ToBytes)(token.trim())));
|
|
648
747
|
const now = Date.now();
|
|
649
|
-
|
|
650
|
-
if (
|
|
651
|
-
|
|
748
|
+
let tokenRow = null;
|
|
749
|
+
if (options.identifier) {
|
|
750
|
+
const identifier = options.identifier.trim().toLowerCase();
|
|
751
|
+
const userRows = await this.db.execute(`SELECT id FROM ${this.sqlUsersTable} WHERE lower(email) = ? OR lower(username) = ? LIMIT 1;`, [identifier, identifier]);
|
|
752
|
+
if (!userRows || userRows.length === 0) {
|
|
753
|
+
throw new Error('Password reset token is invalid or has expired.');
|
|
754
|
+
}
|
|
755
|
+
const targetUserId = String(userRows[0].id);
|
|
756
|
+
const rows = await this.db.execute(`SELECT * FROM ${this.sqlTokensTable} WHERE user_id = ? AND type = 'reset_password' AND used_at IS NULL AND expires_at > ? ORDER BY created_at DESC LIMIT 1;`, [targetUserId, now]);
|
|
757
|
+
if (!rows || rows.length === 0) {
|
|
758
|
+
throw new Error('Password reset token is invalid or has expired.');
|
|
759
|
+
}
|
|
760
|
+
const candidate = rows[0];
|
|
761
|
+
const maxAttempts = Number(candidate.max_attempts ?? 1);
|
|
762
|
+
const attempts = Number(candidate.attempts ?? 0);
|
|
763
|
+
if (attempts >= maxAttempts) {
|
|
764
|
+
await this.db.execute(`UPDATE ${this.sqlTokensTable} SET used_at = ? WHERE id = ?;`, [now, candidate.id]);
|
|
765
|
+
throw new Error('Too many invalid reset attempts. Request a new code.');
|
|
766
|
+
}
|
|
767
|
+
if (!(0, generator_js_1.timingSafeEqual)(tokenHash, String(candidate.token_hash))) {
|
|
768
|
+
const nextAttempts = attempts + 1;
|
|
769
|
+
await this.db.execute(`UPDATE ${this.sqlTokensTable} SET attempts = ?, used_at = ? WHERE id = ?;`, [nextAttempts, nextAttempts >= maxAttempts ? now : null, candidate.id]);
|
|
770
|
+
throw new Error('Password reset token is invalid or has expired.');
|
|
771
|
+
}
|
|
772
|
+
tokenRow = candidate;
|
|
773
|
+
}
|
|
774
|
+
else {
|
|
775
|
+
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]);
|
|
776
|
+
if (!rows || rows.length === 0) {
|
|
777
|
+
throw new Error('Password reset token is invalid or has expired.');
|
|
778
|
+
}
|
|
779
|
+
tokenRow = rows[0];
|
|
652
780
|
}
|
|
653
|
-
const tokenRow = rows[0];
|
|
654
781
|
const userId = String(tokenRow.user_id);
|
|
655
782
|
const creds = await hashPassword(newPassword, {
|
|
656
783
|
saltBytes: this.saltBytes,
|
|
@@ -46,6 +46,7 @@ async function resolveRemoteAdapter(config) {
|
|
|
46
46
|
url: config.server.url,
|
|
47
47
|
token: config.server.token,
|
|
48
48
|
headers: config.server.headers,
|
|
49
|
+
fetch: config.server.fetch,
|
|
49
50
|
tables: config.tables,
|
|
50
51
|
primaryKey: config.primaryKey,
|
|
51
52
|
pollIntervalMs: config.server.pollIntervalMs,
|
package/dist/config/types.d.ts
CHANGED
|
@@ -124,6 +124,10 @@ export interface SelfHostedServerConfigOptions {
|
|
|
124
124
|
* Custom HTTP request headers.
|
|
125
125
|
*/
|
|
126
126
|
headers?: Record<string, string>;
|
|
127
|
+
/**
|
|
128
|
+
* Custom fetch implementation (defaults to globalThis.fetch).
|
|
129
|
+
*/
|
|
130
|
+
fetch?: typeof fetch;
|
|
127
131
|
/**
|
|
128
132
|
* Polling interval in milliseconds for live change detection. Default: 5000.
|
|
129
133
|
*/
|
package/dist/core/index.d.ts
CHANGED
|
@@ -14,5 +14,5 @@ export * from './audit.js';
|
|
|
14
14
|
export * from '../reactive/event-emitter.js';
|
|
15
15
|
export * from '../adapters/network/index.js';
|
|
16
16
|
export type { LocalDBAdapter, LocalTransaction, } from '../adapters/local/index.js';
|
|
17
|
-
export type { RemoteDBAdapter } from '../adapters/remote/index.js';
|
|
17
|
+
export type { RemoteAutomationJob, RemoteBackupArchive, RemoteDBAdapter, } from '../adapters/remote/index.js';
|
|
18
18
|
export * from '../utils/logger.js';
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { LocalDBAdapter } from '../adapters/local/index.js';
|
|
2
|
+
export interface ServerAuthUserRecord {
|
|
3
|
+
id: string;
|
|
4
|
+
email: string;
|
|
5
|
+
displayName?: string | null;
|
|
6
|
+
passwordHash: string;
|
|
7
|
+
salt: string;
|
|
8
|
+
iterations: number;
|
|
9
|
+
algorithm: string;
|
|
10
|
+
failedLoginAttempts: number;
|
|
11
|
+
lockedUntil?: number | null;
|
|
12
|
+
tokenVersion?: number;
|
|
13
|
+
createdAt: number;
|
|
14
|
+
updatedAt: number;
|
|
15
|
+
}
|
|
16
|
+
export interface ServerAuthOtpRecord {
|
|
17
|
+
id: string;
|
|
18
|
+
userId: string;
|
|
19
|
+
email: string;
|
|
20
|
+
otpHash: string;
|
|
21
|
+
attempts: number;
|
|
22
|
+
expiresAt: number;
|
|
23
|
+
usedAt?: number | null;
|
|
24
|
+
createdAt: number;
|
|
25
|
+
}
|
|
26
|
+
export interface ServerAuthStorage {
|
|
27
|
+
initialize?(): Promise<void>;
|
|
28
|
+
findUserByEmail(email: string): Promise<ServerAuthUserRecord | null>;
|
|
29
|
+
createUser(record: ServerAuthUserRecord): Promise<void>;
|
|
30
|
+
recordFailedAttempt(userId: string, attempts: number, lockedUntil: number | null, updatedAt: number): Promise<void>;
|
|
31
|
+
updatePasswordAndResetLockout(userId: string, patch: {
|
|
32
|
+
passwordHash: string;
|
|
33
|
+
salt: string;
|
|
34
|
+
iterations: number;
|
|
35
|
+
algorithm: string;
|
|
36
|
+
updatedAt: number;
|
|
37
|
+
}): Promise<void>;
|
|
38
|
+
invalidateActiveOtps(email: string, usedAt: number): Promise<void>;
|
|
39
|
+
createResetOtp(record: ServerAuthOtpRecord): Promise<void>;
|
|
40
|
+
findLatestActiveOtp(email: string): Promise<ServerAuthOtpRecord | null>;
|
|
41
|
+
incrementOtpAttempts(id: string, attempts: number, usedAt: number | null): Promise<void>;
|
|
42
|
+
markOtpUsed(id: string, usedAt: number): Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Persistent SQLite-backed ServerAuthStorage using any LocalDBAdapter.
|
|
46
|
+
*/
|
|
47
|
+
export declare class SQLiteServerAuthStorage implements ServerAuthStorage {
|
|
48
|
+
private db;
|
|
49
|
+
private initialized;
|
|
50
|
+
constructor(db: LocalDBAdapter);
|
|
51
|
+
initialize(): Promise<void>;
|
|
52
|
+
findUserByEmail(email: string): Promise<ServerAuthUserRecord | null>;
|
|
53
|
+
createUser(record: ServerAuthUserRecord): Promise<void>;
|
|
54
|
+
recordFailedAttempt(userId: string, attempts: number, lockedUntil: number | null, updatedAt: number): Promise<void>;
|
|
55
|
+
updatePasswordAndResetLockout(userId: string, patch: {
|
|
56
|
+
passwordHash: string;
|
|
57
|
+
salt: string;
|
|
58
|
+
iterations: number;
|
|
59
|
+
algorithm: string;
|
|
60
|
+
updatedAt: number;
|
|
61
|
+
}): Promise<void>;
|
|
62
|
+
invalidateActiveOtps(email: string, usedAt: number): Promise<void>;
|
|
63
|
+
createResetOtp(record: ServerAuthOtpRecord): Promise<void>;
|
|
64
|
+
findLatestActiveOtp(email: string): Promise<ServerAuthOtpRecord | null>;
|
|
65
|
+
incrementOtpAttempts(id: string, attempts: number, usedAt: number | null): Promise<void>;
|
|
66
|
+
markOtpUsed(id: string, usedAt: number): Promise<void>;
|
|
67
|
+
}
|
|
68
|
+
export interface ServerAuthTokenPayload {
|
|
69
|
+
purpose: 'sync-auth';
|
|
70
|
+
sub: string;
|
|
71
|
+
email: string;
|
|
72
|
+
name?: string | null;
|
|
73
|
+
tv?: number;
|
|
74
|
+
}
|
|
75
|
+
export interface VerifiedServerAuthUser {
|
|
76
|
+
id: string;
|
|
77
|
+
email: string;
|
|
78
|
+
name: string | null;
|
|
79
|
+
provider: 'local';
|
|
80
|
+
tokenVersion: number;
|
|
81
|
+
}
|
|
82
|
+
export interface CreateAuthEndpointOptions {
|
|
83
|
+
storage: ServerAuthStorage;
|
|
84
|
+
secret: string;
|
|
85
|
+
tokenTtlMs?: number;
|
|
86
|
+
passwordIterations?: number;
|
|
87
|
+
minPasswordLength?: number;
|
|
88
|
+
maxFailedAttempts?: number;
|
|
89
|
+
lockoutDurationMs?: number;
|
|
90
|
+
otp?: {
|
|
91
|
+
ttlMs?: number;
|
|
92
|
+
maxAttempts?: number;
|
|
93
|
+
};
|
|
94
|
+
sendResetOtpEmail?: (params: {
|
|
95
|
+
to: string;
|
|
96
|
+
otp: string;
|
|
97
|
+
expiresMinutes: number;
|
|
98
|
+
}) => Promise<void>;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Verifies a Bearer token or Request issued by `createAuthEndpoint()`.
|
|
102
|
+
*/
|
|
103
|
+
export declare function verifyAuthToken(requestOrToken: Request | string, secret: string): VerifiedServerAuthUser | null;
|
|
104
|
+
/**
|
|
105
|
+
* Verifies a Bearer token and checks that its tokenVersion matches the stored user record
|
|
106
|
+
* (revoking tokens issued before a password reset).
|
|
107
|
+
*/
|
|
108
|
+
export declare function verifyAuthTokenWithStorage(requestOrToken: Request | string, secret: string, storage: ServerAuthStorage): Promise<VerifiedServerAuthUser | null>;
|
|
109
|
+
/**
|
|
110
|
+
* Creates a turnkey Web Request/Response handler for local email/password auth,
|
|
111
|
+
* token refresh, and 6-digit email OTP password resets.
|
|
112
|
+
*/
|
|
113
|
+
export declare function createAuthEndpoint(options: CreateAuthEndpointOptions): (request: Request) => Promise<Response>;
|
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SQLiteServerAuthStorage = void 0;
|
|
4
|
+
exports.verifyAuthToken = verifyAuthToken;
|
|
5
|
+
exports.verifyAuthTokenWithStorage = verifyAuthTokenWithStorage;
|
|
6
|
+
exports.createAuthEndpoint = createAuthEndpoint;
|
|
7
|
+
const hmac_js_1 = require("@noble/hashes/hmac.js");
|
|
8
|
+
const sha2_js_1 = require("@noble/hashes/sha2.js");
|
|
9
|
+
const utils_js_1 = require("@noble/hashes/utils.js");
|
|
10
|
+
const identity_js_1 = require("../auth/identity.js");
|
|
11
|
+
const local_js_1 = require("../auth/local.js");
|
|
12
|
+
const generator_js_1 = require("../keys/generator.js");
|
|
13
|
+
const signed_token_js_1 = require("../keys/signed-token.js");
|
|
14
|
+
const http_js_1 = require("../utils/http.js");
|
|
15
|
+
const uuid_js_1 = require("../utils/uuid.js");
|
|
16
|
+
/**
|
|
17
|
+
* Persistent SQLite-backed ServerAuthStorage using any LocalDBAdapter.
|
|
18
|
+
*/
|
|
19
|
+
class SQLiteServerAuthStorage {
|
|
20
|
+
db;
|
|
21
|
+
initialized = false;
|
|
22
|
+
constructor(db) {
|
|
23
|
+
this.db = db;
|
|
24
|
+
}
|
|
25
|
+
async initialize() {
|
|
26
|
+
if (this.initialized)
|
|
27
|
+
return;
|
|
28
|
+
await this.db.execute(`
|
|
29
|
+
CREATE TABLE IF NOT EXISTS _local_auth_accounts (
|
|
30
|
+
id TEXT PRIMARY KEY,
|
|
31
|
+
email TEXT NOT NULL UNIQUE,
|
|
32
|
+
display_name TEXT,
|
|
33
|
+
password_hash TEXT NOT NULL,
|
|
34
|
+
salt TEXT NOT NULL,
|
|
35
|
+
iterations INTEGER NOT NULL,
|
|
36
|
+
algorithm TEXT NOT NULL,
|
|
37
|
+
failed_login_attempts INTEGER NOT NULL DEFAULT 0,
|
|
38
|
+
locked_until INTEGER,
|
|
39
|
+
token_version INTEGER NOT NULL DEFAULT 1,
|
|
40
|
+
created_at INTEGER NOT NULL,
|
|
41
|
+
updated_at INTEGER NOT NULL
|
|
42
|
+
);
|
|
43
|
+
`);
|
|
44
|
+
try {
|
|
45
|
+
await this.db.execute(`ALTER TABLE _local_auth_accounts ADD COLUMN token_version INTEGER NOT NULL DEFAULT 1;`);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
// Column already exists
|
|
49
|
+
}
|
|
50
|
+
await this.db.execute(`
|
|
51
|
+
CREATE TABLE IF NOT EXISTS _local_auth_reset_otps (
|
|
52
|
+
id TEXT PRIMARY KEY,
|
|
53
|
+
user_id TEXT NOT NULL,
|
|
54
|
+
email TEXT NOT NULL,
|
|
55
|
+
otp_hash TEXT NOT NULL,
|
|
56
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
57
|
+
expires_at INTEGER NOT NULL,
|
|
58
|
+
used_at INTEGER,
|
|
59
|
+
created_at INTEGER NOT NULL
|
|
60
|
+
);
|
|
61
|
+
`);
|
|
62
|
+
await this.db.execute(`
|
|
63
|
+
CREATE INDEX IF NOT EXISTS idx_local_auth_otps_email
|
|
64
|
+
ON _local_auth_reset_otps (email, created_at);
|
|
65
|
+
`);
|
|
66
|
+
this.initialized = true;
|
|
67
|
+
}
|
|
68
|
+
async findUserByEmail(email) {
|
|
69
|
+
await this.initialize();
|
|
70
|
+
const rows = await this.db.execute(`SELECT * FROM _local_auth_accounts WHERE email = ? LIMIT 1;`, [email]);
|
|
71
|
+
const r = rows?.[0];
|
|
72
|
+
if (!r)
|
|
73
|
+
return null;
|
|
74
|
+
return {
|
|
75
|
+
id: String(r.id),
|
|
76
|
+
email: String(r.email),
|
|
77
|
+
displayName: r.display_name ?? null,
|
|
78
|
+
passwordHash: String(r.password_hash),
|
|
79
|
+
salt: String(r.salt),
|
|
80
|
+
iterations: Number(r.iterations),
|
|
81
|
+
algorithm: String(r.algorithm),
|
|
82
|
+
failedLoginAttempts: Number(r.failed_login_attempts ?? 0),
|
|
83
|
+
lockedUntil: r.locked_until != null ? Number(r.locked_until) : null,
|
|
84
|
+
tokenVersion: r.token_version != null ? Number(r.token_version) : 1,
|
|
85
|
+
createdAt: Number(r.created_at),
|
|
86
|
+
updatedAt: Number(r.updated_at),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
async createUser(record) {
|
|
90
|
+
await this.initialize();
|
|
91
|
+
await this.db.execute(`INSERT INTO _local_auth_accounts
|
|
92
|
+
(id, email, display_name, password_hash, salt, iterations, algorithm, failed_login_attempts, locked_until, token_version, created_at, updated_at)
|
|
93
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, [
|
|
94
|
+
record.id,
|
|
95
|
+
record.email,
|
|
96
|
+
record.displayName ?? null,
|
|
97
|
+
record.passwordHash,
|
|
98
|
+
record.salt,
|
|
99
|
+
record.iterations,
|
|
100
|
+
record.algorithm,
|
|
101
|
+
record.failedLoginAttempts,
|
|
102
|
+
record.lockedUntil ?? null,
|
|
103
|
+
record.tokenVersion ?? 1,
|
|
104
|
+
record.createdAt,
|
|
105
|
+
record.updatedAt,
|
|
106
|
+
]);
|
|
107
|
+
}
|
|
108
|
+
async recordFailedAttempt(userId, attempts, lockedUntil, updatedAt) {
|
|
109
|
+
await this.initialize();
|
|
110
|
+
await this.db.execute(`UPDATE _local_auth_accounts SET failed_login_attempts = ?, locked_until = ?, updated_at = ? WHERE id = ?;`, [attempts, lockedUntil, updatedAt, userId]);
|
|
111
|
+
}
|
|
112
|
+
async updatePasswordAndResetLockout(userId, patch) {
|
|
113
|
+
await this.initialize();
|
|
114
|
+
await this.db.execute(`UPDATE _local_auth_accounts
|
|
115
|
+
SET password_hash = ?, salt = ?, iterations = ?, algorithm = ?, failed_login_attempts = 0, locked_until = NULL, token_version = COALESCE(token_version, 1) + 1, updated_at = ?
|
|
116
|
+
WHERE id = ?;`, [
|
|
117
|
+
patch.passwordHash,
|
|
118
|
+
patch.salt,
|
|
119
|
+
patch.iterations,
|
|
120
|
+
patch.algorithm,
|
|
121
|
+
patch.updatedAt,
|
|
122
|
+
userId,
|
|
123
|
+
]);
|
|
124
|
+
}
|
|
125
|
+
async invalidateActiveOtps(email, usedAt) {
|
|
126
|
+
await this.initialize();
|
|
127
|
+
await this.db.execute(`UPDATE _local_auth_reset_otps SET used_at = ? WHERE email = ? AND used_at IS NULL;`, [usedAt, email]);
|
|
128
|
+
}
|
|
129
|
+
async createResetOtp(record) {
|
|
130
|
+
await this.initialize();
|
|
131
|
+
await this.db.execute(`INSERT INTO _local_auth_reset_otps
|
|
132
|
+
(id, user_id, email, otp_hash, attempts, expires_at, used_at, created_at)
|
|
133
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?);`, [
|
|
134
|
+
record.id,
|
|
135
|
+
record.userId,
|
|
136
|
+
record.email,
|
|
137
|
+
record.otpHash,
|
|
138
|
+
record.attempts,
|
|
139
|
+
record.expiresAt,
|
|
140
|
+
record.usedAt ?? null,
|
|
141
|
+
record.createdAt,
|
|
142
|
+
]);
|
|
143
|
+
}
|
|
144
|
+
async findLatestActiveOtp(email) {
|
|
145
|
+
await this.initialize();
|
|
146
|
+
const rows = await this.db.execute(`SELECT * FROM _local_auth_reset_otps WHERE email = ? AND used_at IS NULL ORDER BY created_at DESC LIMIT 1;`, [email]);
|
|
147
|
+
const r = rows?.[0];
|
|
148
|
+
if (!r)
|
|
149
|
+
return null;
|
|
150
|
+
return {
|
|
151
|
+
id: String(r.id),
|
|
152
|
+
userId: String(r.user_id),
|
|
153
|
+
email: String(r.email),
|
|
154
|
+
otpHash: String(r.otp_hash),
|
|
155
|
+
attempts: Number(r.attempts ?? 0),
|
|
156
|
+
expiresAt: Number(r.expires_at),
|
|
157
|
+
usedAt: r.used_at != null ? Number(r.used_at) : null,
|
|
158
|
+
createdAt: Number(r.created_at),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
async incrementOtpAttempts(id, attempts, usedAt) {
|
|
162
|
+
await this.initialize();
|
|
163
|
+
await this.db.execute(`UPDATE _local_auth_reset_otps SET attempts = ?, used_at = ? WHERE id = ?;`, [attempts, usedAt, id]);
|
|
164
|
+
}
|
|
165
|
+
async markOtpUsed(id, usedAt) {
|
|
166
|
+
await this.initialize();
|
|
167
|
+
await this.db.execute(`UPDATE _local_auth_reset_otps SET used_at = ? WHERE id = ?;`, [usedAt, id]);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
exports.SQLiteServerAuthStorage = SQLiteServerAuthStorage;
|
|
171
|
+
const DEFAULT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
172
|
+
const DEFAULT_SERVER_PASSWORD_ITERATIONS = 100_000;
|
|
173
|
+
const DEFAULT_OTP_TTL_MS = 15 * 60 * 1000;
|
|
174
|
+
function normalizeEmail(raw) {
|
|
175
|
+
return typeof raw === 'string' ? raw.trim().toLowerCase() : '';
|
|
176
|
+
}
|
|
177
|
+
function isValidEmail(email) {
|
|
178
|
+
return Boolean(email && email.includes('@'));
|
|
179
|
+
}
|
|
180
|
+
function deriveSubSecret(secret, scope) {
|
|
181
|
+
return (0, utils_js_1.bytesToHex)((0, hmac_js_1.hmac)(sha2_js_1.sha256, (0, utils_js_1.utf8ToBytes)(secret), (0, utils_js_1.utf8ToBytes)(scope)));
|
|
182
|
+
}
|
|
183
|
+
function hashServerOtp(secret, email, otp) {
|
|
184
|
+
const key = deriveSubSecret(secret, 'local-sync-otp-v1');
|
|
185
|
+
return (0, utils_js_1.bytesToHex)((0, hmac_js_1.hmac)(sha2_js_1.sha256, (0, utils_js_1.utf8ToBytes)(key), (0, utils_js_1.utf8ToBytes)(`otp:${email.trim().toLowerCase()}:${otp.trim()}`)));
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Verifies a Bearer token or Request issued by `createAuthEndpoint()`.
|
|
189
|
+
*/
|
|
190
|
+
function verifyAuthToken(requestOrToken, secret) {
|
|
191
|
+
if (!secret)
|
|
192
|
+
return null;
|
|
193
|
+
let token = '';
|
|
194
|
+
if (typeof requestOrToken === 'string') {
|
|
195
|
+
const trimmed = requestOrToken.trim();
|
|
196
|
+
token = trimmed.startsWith('Bearer ') ? trimmed.slice(7).trim() : trimmed;
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
const authHeader = requestOrToken.headers.get('authorization');
|
|
200
|
+
if (authHeader && authHeader.startsWith('Bearer ')) {
|
|
201
|
+
token = authHeader.slice(7).trim();
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (!token)
|
|
205
|
+
return null;
|
|
206
|
+
const signingSecret = deriveSubSecret(secret, 'local-sync-auth-v1');
|
|
207
|
+
const result = (0, signed_token_js_1.verifySignedToken)(token, signingSecret);
|
|
208
|
+
if (!result.valid ||
|
|
209
|
+
!result.payload ||
|
|
210
|
+
result.payload.purpose !== 'sync-auth' ||
|
|
211
|
+
!result.payload.sub ||
|
|
212
|
+
!result.payload.email) {
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
id: result.payload.sub,
|
|
217
|
+
email: result.payload.email,
|
|
218
|
+
name: result.payload.name ?? null,
|
|
219
|
+
provider: 'local',
|
|
220
|
+
tokenVersion: typeof result.payload.tv === 'number' ? result.payload.tv : 1,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Verifies a Bearer token and checks that its tokenVersion matches the stored user record
|
|
225
|
+
* (revoking tokens issued before a password reset).
|
|
226
|
+
*/
|
|
227
|
+
async function verifyAuthTokenWithStorage(requestOrToken, secret, storage) {
|
|
228
|
+
const verified = verifyAuthToken(requestOrToken, secret);
|
|
229
|
+
if (!verified)
|
|
230
|
+
return null;
|
|
231
|
+
const user = await storage.findUserByEmail(verified.email);
|
|
232
|
+
if (!user || user.id !== verified.id)
|
|
233
|
+
return null;
|
|
234
|
+
if ((user.tokenVersion ?? 1) !== verified.tokenVersion)
|
|
235
|
+
return null;
|
|
236
|
+
return verified;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Creates a turnkey Web Request/Response handler for local email/password auth,
|
|
240
|
+
* token refresh, and 6-digit email OTP password resets.
|
|
241
|
+
*/
|
|
242
|
+
function createAuthEndpoint(options) {
|
|
243
|
+
const { storage, secret, tokenTtlMs = DEFAULT_TOKEN_TTL_MS, passwordIterations = DEFAULT_SERVER_PASSWORD_ITERATIONS, minPasswordLength = 8, maxFailedAttempts = 5, lockoutDurationMs = 15 * 60 * 1000, sendResetOtpEmail, } = options;
|
|
244
|
+
const otpTtlMs = options.otp?.ttlMs ?? DEFAULT_OTP_TTL_MS;
|
|
245
|
+
const maxOtpAttempts = options.otp?.maxAttempts ?? 5;
|
|
246
|
+
if (!secret || !secret.trim()) {
|
|
247
|
+
throw new Error('A non-empty signing secret is required.');
|
|
248
|
+
}
|
|
249
|
+
const signingSecret = deriveSubSecret(secret, 'local-sync-auth-v1');
|
|
250
|
+
const issueToken = (user) => (0, signed_token_js_1.createSignedToken)({
|
|
251
|
+
secret: signingSecret,
|
|
252
|
+
expiresInMs: tokenTtlMs,
|
|
253
|
+
payload: {
|
|
254
|
+
purpose: 'sync-auth',
|
|
255
|
+
sub: user.id,
|
|
256
|
+
email: user.email,
|
|
257
|
+
name: user.displayName ?? null,
|
|
258
|
+
tv: user.tokenVersion ?? 1,
|
|
259
|
+
},
|
|
260
|
+
});
|
|
261
|
+
return async function handleAuthRequest(request) {
|
|
262
|
+
if (request.method.toUpperCase() === 'OPTIONS') {
|
|
263
|
+
return new Response(null, { status: 204 });
|
|
264
|
+
}
|
|
265
|
+
if (request.method.toUpperCase() !== 'POST') {
|
|
266
|
+
return (0, http_js_1.jsonError)('Method Not Allowed', 405);
|
|
267
|
+
}
|
|
268
|
+
const pathname = new URL(request.url).pathname.replace(/\/+$/, '');
|
|
269
|
+
// 1. Refresh
|
|
270
|
+
if (pathname.endsWith('/refresh')) {
|
|
271
|
+
const verified = await verifyAuthTokenWithStorage(request, secret, storage);
|
|
272
|
+
if (!verified) {
|
|
273
|
+
return (0, http_js_1.jsonError)('Unauthorized', 401);
|
|
274
|
+
}
|
|
275
|
+
const token = issueToken({
|
|
276
|
+
id: verified.id,
|
|
277
|
+
email: verified.email,
|
|
278
|
+
displayName: verified.name,
|
|
279
|
+
tokenVersion: verified.tokenVersion,
|
|
280
|
+
});
|
|
281
|
+
return Response.json({ token });
|
|
282
|
+
}
|
|
283
|
+
let body;
|
|
284
|
+
try {
|
|
285
|
+
body = (await request.json());
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
return (0, http_js_1.jsonError)('Invalid JSON payload', 400);
|
|
289
|
+
}
|
|
290
|
+
// 2. Forgot Password (6-digit Email OTP)
|
|
291
|
+
if (pathname.endsWith('/forgot-password')) {
|
|
292
|
+
const email = normalizeEmail(body.email);
|
|
293
|
+
if (!isValidEmail(email)) {
|
|
294
|
+
return (0, http_js_1.jsonError)('Please enter a valid email address.', 400);
|
|
295
|
+
}
|
|
296
|
+
const existing = await storage.findUserByEmail(email);
|
|
297
|
+
if (existing) {
|
|
298
|
+
const limit = 4_294_800_000;
|
|
299
|
+
let num = limit;
|
|
300
|
+
while (num >= limit) {
|
|
301
|
+
const randomVal = (0, local_js_1.getCryptoRandomBytes)(4);
|
|
302
|
+
num =
|
|
303
|
+
((randomVal[0] << 24) |
|
|
304
|
+
(randomVal[1] << 16) |
|
|
305
|
+
(randomVal[2] << 8) |
|
|
306
|
+
randomVal[3]) >>>
|
|
307
|
+
0;
|
|
308
|
+
}
|
|
309
|
+
const otp = String(100000 + (num % 900000));
|
|
310
|
+
const now = Date.now();
|
|
311
|
+
await storage.invalidateActiveOtps(email, now);
|
|
312
|
+
await storage.createResetOtp({
|
|
313
|
+
id: (0, uuid_js_1.generateUUID)(),
|
|
314
|
+
userId: existing.id,
|
|
315
|
+
email,
|
|
316
|
+
otpHash: hashServerOtp(secret, email, otp),
|
|
317
|
+
attempts: 0,
|
|
318
|
+
expiresAt: now + otpTtlMs,
|
|
319
|
+
usedAt: null,
|
|
320
|
+
createdAt: now,
|
|
321
|
+
});
|
|
322
|
+
if (sendResetOtpEmail) {
|
|
323
|
+
await sendResetOtpEmail({
|
|
324
|
+
to: email,
|
|
325
|
+
otp,
|
|
326
|
+
expiresMinutes: Math.max(1, Math.round(otpTtlMs / 60000)),
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
return Response.json({
|
|
331
|
+
success: true,
|
|
332
|
+
message: 'If an account exists for that email, a verification code has been sent.',
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
// 3. Reset Password with OTP
|
|
336
|
+
if (pathname.endsWith('/reset-password')) {
|
|
337
|
+
const email = normalizeEmail(body.email);
|
|
338
|
+
const otp = typeof body.otp === 'string' ? body.otp.trim() : '';
|
|
339
|
+
const newPassword = typeof body.newPassword === 'string' ? body.newPassword : '';
|
|
340
|
+
if (!isValidEmail(email) || !/^\d{6}$/.test(otp)) {
|
|
341
|
+
return (0, http_js_1.jsonError)('Valid email and 6-digit verification code are required.', 400);
|
|
342
|
+
}
|
|
343
|
+
if (newPassword.length < minPasswordLength) {
|
|
344
|
+
return (0, http_js_1.jsonError)(`New password must be at least ${minPasswordLength} characters.`, 400);
|
|
345
|
+
}
|
|
346
|
+
const now = Date.now();
|
|
347
|
+
const otpRow = await storage.findLatestActiveOtp(email);
|
|
348
|
+
if (!otpRow || otpRow.expiresAt <= now) {
|
|
349
|
+
return (0, http_js_1.jsonError)('Invalid or expired verification code.', 400);
|
|
350
|
+
}
|
|
351
|
+
if (otpRow.attempts >= maxOtpAttempts) {
|
|
352
|
+
await storage.markOtpUsed(otpRow.id, now);
|
|
353
|
+
return (0, http_js_1.jsonError)('Too many invalid attempts. Please request a new code.', 429);
|
|
354
|
+
}
|
|
355
|
+
const actualHash = hashServerOtp(secret, email, otp);
|
|
356
|
+
if (!(0, generator_js_1.timingSafeEqual)(actualHash, otpRow.otpHash)) {
|
|
357
|
+
const nextAttempts = otpRow.attempts + 1;
|
|
358
|
+
await storage.incrementOtpAttempts(otpRow.id, nextAttempts, nextAttempts >= maxOtpAttempts ? now : null);
|
|
359
|
+
return (0, http_js_1.jsonError)('Invalid or expired verification code.', 400);
|
|
360
|
+
}
|
|
361
|
+
const hashed = await (0, local_js_1.hashPassword)(newPassword, {
|
|
362
|
+
iterations: passwordIterations,
|
|
363
|
+
});
|
|
364
|
+
await storage.updatePasswordAndResetLockout(otpRow.userId, {
|
|
365
|
+
passwordHash: hashed.hash,
|
|
366
|
+
salt: hashed.salt,
|
|
367
|
+
iterations: hashed.iterations,
|
|
368
|
+
algorithm: hashed.algorithm,
|
|
369
|
+
updatedAt: now,
|
|
370
|
+
});
|
|
371
|
+
await storage.markOtpUsed(otpRow.id, now);
|
|
372
|
+
return Response.json({ success: true });
|
|
373
|
+
}
|
|
374
|
+
// 4. Sign In / Sign Up
|
|
375
|
+
const mode = body.mode === 'signup' ? 'signup' : 'signin';
|
|
376
|
+
const email = normalizeEmail(body.email);
|
|
377
|
+
const password = typeof body.password === 'string' ? body.password : '';
|
|
378
|
+
const displayName = typeof body.displayName === 'string' && body.displayName.trim()
|
|
379
|
+
? body.displayName.trim()
|
|
380
|
+
: null;
|
|
381
|
+
if (!isValidEmail(email) || !password) {
|
|
382
|
+
return (0, http_js_1.jsonError)('Valid email and password are required.', 400);
|
|
383
|
+
}
|
|
384
|
+
const existing = await storage.findUserByEmail(email);
|
|
385
|
+
if (mode === 'signup') {
|
|
386
|
+
if (existing) {
|
|
387
|
+
return (0, http_js_1.jsonError)('An account with this email already exists.', 409);
|
|
388
|
+
}
|
|
389
|
+
if (password.length < minPasswordLength) {
|
|
390
|
+
return (0, http_js_1.jsonError)(`Password must be at least ${minPasswordLength} characters.`, 400);
|
|
391
|
+
}
|
|
392
|
+
const id = (0, identity_js_1.resolveUnifiedUserId)({ id: email, email, emailVerified: false }, 'local');
|
|
393
|
+
const hashed = await (0, local_js_1.hashPassword)(password, {
|
|
394
|
+
iterations: passwordIterations,
|
|
395
|
+
});
|
|
396
|
+
const now = Date.now();
|
|
397
|
+
await storage.createUser({
|
|
398
|
+
id,
|
|
399
|
+
email,
|
|
400
|
+
displayName,
|
|
401
|
+
passwordHash: hashed.hash,
|
|
402
|
+
salt: hashed.salt,
|
|
403
|
+
iterations: hashed.iterations,
|
|
404
|
+
algorithm: hashed.algorithm,
|
|
405
|
+
failedLoginAttempts: 0,
|
|
406
|
+
lockedUntil: null,
|
|
407
|
+
tokenVersion: 1,
|
|
408
|
+
createdAt: now,
|
|
409
|
+
updatedAt: now,
|
|
410
|
+
});
|
|
411
|
+
const token = issueToken({ id, email, displayName, tokenVersion: 1 });
|
|
412
|
+
return Response.json({
|
|
413
|
+
token,
|
|
414
|
+
user: { id, email, displayName },
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
if (!existing) {
|
|
418
|
+
await (0, local_js_1.verifyDummyPassword)(passwordIterations);
|
|
419
|
+
return (0, http_js_1.jsonError)('Invalid email or password.', 401);
|
|
420
|
+
}
|
|
421
|
+
const now = Date.now();
|
|
422
|
+
if (existing.lockedUntil && existing.lockedUntil > now) {
|
|
423
|
+
return (0, http_js_1.jsonError)('Account temporarily locked due to too many failed attempts.', 429);
|
|
424
|
+
}
|
|
425
|
+
const valid = await (0, local_js_1.verifyPassword)(password, existing.passwordHash, existing.salt, existing.iterations, existing.algorithm);
|
|
426
|
+
if (!valid) {
|
|
427
|
+
const nextAttempts = existing.failedLoginAttempts + 1;
|
|
428
|
+
const lockedUntil = maxFailedAttempts > 0 && nextAttempts >= maxFailedAttempts
|
|
429
|
+
? now + lockoutDurationMs
|
|
430
|
+
: null;
|
|
431
|
+
await storage.recordFailedAttempt(existing.id, nextAttempts, lockedUntil, now);
|
|
432
|
+
return (0, http_js_1.jsonError)('Invalid email or password.', 401);
|
|
433
|
+
}
|
|
434
|
+
if (existing.failedLoginAttempts > 0 || existing.lockedUntil) {
|
|
435
|
+
await storage.recordFailedAttempt(existing.id, 0, null, now);
|
|
436
|
+
}
|
|
437
|
+
const token = issueToken({
|
|
438
|
+
id: existing.id,
|
|
439
|
+
email: existing.email,
|
|
440
|
+
displayName: existing.displayName ?? null,
|
|
441
|
+
tokenVersion: existing.tokenVersion ?? 1,
|
|
442
|
+
});
|
|
443
|
+
return Response.json({
|
|
444
|
+
token,
|
|
445
|
+
user: {
|
|
446
|
+
id: existing.id,
|
|
447
|
+
email: existing.email,
|
|
448
|
+
displayName: existing.displayName ?? null,
|
|
449
|
+
},
|
|
450
|
+
});
|
|
451
|
+
};
|
|
452
|
+
}
|
package/dist/server/dashboard.js
CHANGED
|
@@ -2,20 +2,21 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createDashboardHandler = createDashboardHandler;
|
|
4
4
|
const local_js_1 = require("../auth/local.js");
|
|
5
|
+
const http_js_1 = require("../utils/http.js");
|
|
5
6
|
const encryption_js_1 = require("../backups/encryption.js");
|
|
6
7
|
const store_js_1 = require("../kv-store/store.js");
|
|
7
8
|
const sql_js_1 = require("../utils/sql.js");
|
|
8
9
|
function jsonResponse(data, status = 200) {
|
|
9
|
-
return
|
|
10
|
+
return (0, http_js_1.jsonResponse)(data, {
|
|
10
11
|
status,
|
|
11
|
-
headers: {
|
|
12
|
-
'Content-Type': 'application/json; charset=utf-8',
|
|
13
|
-
'Cache-Control': 'no-store',
|
|
14
|
-
},
|
|
12
|
+
headers: { 'Cache-Control': 'no-store' },
|
|
15
13
|
});
|
|
16
14
|
}
|
|
17
15
|
function errorResponse(message, status = 400) {
|
|
18
|
-
return
|
|
16
|
+
return (0, http_js_1.jsonError)(message, {
|
|
17
|
+
status,
|
|
18
|
+
headers: { 'Cache-Control': 'no-store' },
|
|
19
|
+
});
|
|
19
20
|
}
|
|
20
21
|
function isAuthorized(request, url, authToken) {
|
|
21
22
|
if (!authToken)
|
|
@@ -177,6 +178,22 @@ function createDashboardHandler(db, options = {}) {
|
|
|
177
178
|
headers.append('Set-Cookie', `local_lite_session=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}`);
|
|
178
179
|
return new Response(res.body, { status: res.status, headers });
|
|
179
180
|
};
|
|
181
|
+
const buildAuthSessionResponse = async (result, status = 200) => {
|
|
182
|
+
let token = result.session?.token ?? '';
|
|
183
|
+
if (!token && result.session?.id) {
|
|
184
|
+
token = (0, local_js_1.generateCryptoToken)(32).token;
|
|
185
|
+
await db.execute(`UPDATE _local_sessions SET token = ? WHERE id = ?;`, [
|
|
186
|
+
token,
|
|
187
|
+
result.session.id,
|
|
188
|
+
]);
|
|
189
|
+
}
|
|
190
|
+
const res = jsonResponse({
|
|
191
|
+
user: result.user,
|
|
192
|
+
token,
|
|
193
|
+
expiresAt: result.session?.expiresAt ?? null,
|
|
194
|
+
}, status);
|
|
195
|
+
return token ? withSessionCookie(res, token) : res;
|
|
196
|
+
};
|
|
180
197
|
const logs = [];
|
|
181
198
|
let nextLogId = 1;
|
|
182
199
|
const recordLog = (method, path, status, startedAt, detail) => {
|
|
@@ -254,20 +271,7 @@ function createDashboardHandler(db, options = {}) {
|
|
|
254
271
|
displayName: body?.name ? String(body.name) : undefined,
|
|
255
272
|
role: 'admin',
|
|
256
273
|
});
|
|
257
|
-
|
|
258
|
-
if (!token && result.session?.id) {
|
|
259
|
-
token = (0, local_js_1.generateCryptoToken)(32).token;
|
|
260
|
-
await db.execute(`UPDATE _local_sessions SET token = ? WHERE id = ?;`, [
|
|
261
|
-
token,
|
|
262
|
-
result.session.id,
|
|
263
|
-
]);
|
|
264
|
-
}
|
|
265
|
-
const res = jsonResponse({
|
|
266
|
-
user: result.user,
|
|
267
|
-
token,
|
|
268
|
-
expiresAt: result.session?.expiresAt ?? null,
|
|
269
|
-
}, 201);
|
|
270
|
-
return token ? withSessionCookie(res, token) : res;
|
|
274
|
+
return await buildAuthSessionResponse(result, 201);
|
|
271
275
|
}
|
|
272
276
|
catch (err) {
|
|
273
277
|
return errorResponse(err?.message ?? 'Setup failed.', 400);
|
|
@@ -281,20 +285,7 @@ function createDashboardHandler(db, options = {}) {
|
|
|
281
285
|
identifier: String(body?.identifier ?? ''),
|
|
282
286
|
password: String(body?.password ?? ''),
|
|
283
287
|
});
|
|
284
|
-
|
|
285
|
-
if (!token && result.session?.id) {
|
|
286
|
-
token = (0, local_js_1.generateCryptoToken)(32).token;
|
|
287
|
-
await db.execute(`UPDATE _local_sessions SET token = ? WHERE id = ?;`, [
|
|
288
|
-
token,
|
|
289
|
-
result.session.id,
|
|
290
|
-
]);
|
|
291
|
-
}
|
|
292
|
-
const res = jsonResponse({
|
|
293
|
-
user: result.user,
|
|
294
|
-
token,
|
|
295
|
-
expiresAt: result.session?.expiresAt ?? null,
|
|
296
|
-
});
|
|
297
|
-
return token ? withSessionCookie(res, token) : res;
|
|
288
|
+
return await buildAuthSessionResponse(result);
|
|
298
289
|
}
|
|
299
290
|
catch (err) {
|
|
300
291
|
return errorResponse(err?.message ?? 'Invalid credentials.', 401);
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export type ApiMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
|
|
2
2
|
export * from './email.js';
|
|
3
3
|
export * from './sync.js';
|
|
4
|
+
export * from './auth.js';
|
|
4
5
|
export * from './dashboard.js';
|
|
5
6
|
export interface ApiRequestContext<TConfig = unknown> {
|
|
6
7
|
request: Request;
|
package/dist/server/index.js
CHANGED
|
@@ -18,6 +18,7 @@ exports.defineServerConfig = defineServerConfig;
|
|
|
18
18
|
exports.createServer = createServer;
|
|
19
19
|
__exportStar(require("./email.js"), exports);
|
|
20
20
|
__exportStar(require("./sync.js"), exports);
|
|
21
|
+
__exportStar(require("./auth.js"), exports);
|
|
21
22
|
__exportStar(require("./dashboard.js"), exports);
|
|
22
23
|
function normalizePath(path) {
|
|
23
24
|
const normalized = `/${path.split('/').filter(Boolean).join('/')}`;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds a JSON HTTP Response with a UTF-8 `Content-Type` header.
|
|
3
|
+
*/
|
|
4
|
+
export declare function jsonResponse(data: unknown, statusOrInit?: number | ResponseInit): Response;
|
|
5
|
+
/**
|
|
6
|
+
* Builds a standardized `{ error: message }` JSON HTTP Response.
|
|
7
|
+
*/
|
|
8
|
+
export declare function jsonError(message: string, statusOrInit?: number | ResponseInit): Response;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.jsonResponse = jsonResponse;
|
|
4
|
+
exports.jsonError = jsonError;
|
|
5
|
+
/**
|
|
6
|
+
* Builds a JSON HTTP Response with a UTF-8 `Content-Type` header.
|
|
7
|
+
*/
|
|
8
|
+
function jsonResponse(data, statusOrInit = 200) {
|
|
9
|
+
const init = typeof statusOrInit === 'number' ? { status: statusOrInit } : statusOrInit;
|
|
10
|
+
const headers = new Headers(init.headers);
|
|
11
|
+
if (!headers.has('Content-Type')) {
|
|
12
|
+
headers.set('Content-Type', 'application/json; charset=utf-8');
|
|
13
|
+
}
|
|
14
|
+
return new Response(JSON.stringify(data), {
|
|
15
|
+
...init,
|
|
16
|
+
status: init.status ?? 200,
|
|
17
|
+
headers,
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Builds a standardized `{ error: message }` JSON HTTP Response.
|
|
22
|
+
*/
|
|
23
|
+
function jsonError(message, statusOrInit = 400) {
|
|
24
|
+
const init = typeof statusOrInit === 'number' ? { status: statusOrInit } : statusOrInit;
|
|
25
|
+
return jsonResponse({ error: message }, { ...init, status: init.status ?? 400 });
|
|
26
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "local-lite",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.3",
|
|
4
4
|
"description": "Never let a lost connection break a promise. Local-first sync that faithfully keeps data safe until you're back online.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -66,6 +66,11 @@
|
|
|
66
66
|
"import": "./dist/adapters/remote/firestore.js",
|
|
67
67
|
"default": "./dist/adapters/remote/firestore.js"
|
|
68
68
|
},
|
|
69
|
+
"./self-hosted": {
|
|
70
|
+
"types": "./dist/adapters/remote/self-hosted.d.ts",
|
|
71
|
+
"import": "./dist/adapters/remote/self-hosted.js",
|
|
72
|
+
"default": "./dist/adapters/remote/self-hosted.js"
|
|
73
|
+
},
|
|
69
74
|
"./auth": {
|
|
70
75
|
"types": "./dist/auth/index.d.ts",
|
|
71
76
|
"import": "./dist/auth/index.js",
|