local-lite 3.0.1 → 3.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/local.d.ts +23 -4
- package/dist/auth/local.js +143 -16
- 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 +450 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +1 -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;
|
|
@@ -281,13 +300,13 @@ export declare class LocalAuthEngine {
|
|
|
281
300
|
*/
|
|
282
301
|
changePassword(options: ChangePasswordOptions): Promise<void>;
|
|
283
302
|
/**
|
|
284
|
-
* Generates a cryptographically secure, single-use password reset token with expiration.
|
|
303
|
+
* Generates a cryptographically secure, single-use password reset token or 6-digit OTP with expiration.
|
|
285
304
|
*/
|
|
286
|
-
createPasswordResetToken(emailOrUsername: string): Promise<CreateResetTokenResult>;
|
|
305
|
+
createPasswordResetToken(emailOrUsername: string, options?: CreateResetTokenOptions): Promise<CreateResetTokenResult>;
|
|
287
306
|
/**
|
|
288
|
-
* Resets a user's password using a valid cryptographic reset token.
|
|
307
|
+
* Resets a user's password using a valid cryptographic reset token or 6-digit OTP.
|
|
289
308
|
*/
|
|
290
|
-
resetPasswordWithToken(token: string, newPassword: string): Promise<void>;
|
|
309
|
+
resetPasswordWithToken(token: string, newPassword: string, options?: ResetPasswordWithTokenOptions): Promise<void>;
|
|
291
310
|
/**
|
|
292
311
|
* Updates an existing user's profile, role, or metadata.
|
|
293
312
|
*/
|
package/dist/auth/local.js
CHANGED
|
@@ -205,7 +205,50 @@ class LocalAuthEngine {
|
|
|
205
205
|
this.minPasswordLength =
|
|
206
206
|
resolvedOptions.minPasswordLength ?? exports.DEFAULT_MIN_PASSWORD_LENGTH;
|
|
207
207
|
this.customPasswordValidator = resolvedOptions.validatePassword;
|
|
208
|
-
this.remoteAuthHandler =
|
|
208
|
+
this.remoteAuthHandler =
|
|
209
|
+
resolvedOptions.remoteAuthHandler ??
|
|
210
|
+
(resolvedOptions.remote?.url
|
|
211
|
+
? async ({ user, session, mode, password }) => {
|
|
212
|
+
const baseUrl = resolvedOptions.remote.url.replace(/\/+$/, '');
|
|
213
|
+
const fetchFn = resolvedOptions.remote.fetch || globalThis.fetch;
|
|
214
|
+
if (!fetchFn)
|
|
215
|
+
return null;
|
|
216
|
+
const customHeaders = resolvedOptions.remote.headers ?? {};
|
|
217
|
+
if (mode === 'refresh' || !password) {
|
|
218
|
+
if (!session?.token)
|
|
219
|
+
return null;
|
|
220
|
+
const res = await fetchFn(`${baseUrl}/auth/local/refresh`, {
|
|
221
|
+
method: 'POST',
|
|
222
|
+
headers: {
|
|
223
|
+
'Content-Type': 'application/json',
|
|
224
|
+
...customHeaders,
|
|
225
|
+
Authorization: `Bearer ${session.token}`,
|
|
226
|
+
},
|
|
227
|
+
});
|
|
228
|
+
if (!res.ok)
|
|
229
|
+
return null;
|
|
230
|
+
const data = (await res.json());
|
|
231
|
+
return data?.token ? { token: data.token } : null;
|
|
232
|
+
}
|
|
233
|
+
const res = await fetchFn(`${baseUrl}/auth/local`, {
|
|
234
|
+
method: 'POST',
|
|
235
|
+
headers: {
|
|
236
|
+
'Content-Type': 'application/json',
|
|
237
|
+
...customHeaders,
|
|
238
|
+
},
|
|
239
|
+
body: JSON.stringify({
|
|
240
|
+
mode: mode === 'signup' ? 'signup' : 'signin',
|
|
241
|
+
email: user.email,
|
|
242
|
+
password,
|
|
243
|
+
displayName: user.displayName ?? undefined,
|
|
244
|
+
}),
|
|
245
|
+
});
|
|
246
|
+
if (!res.ok)
|
|
247
|
+
return null;
|
|
248
|
+
const data = (await res.json());
|
|
249
|
+
return data?.token ? { token: data.token } : null;
|
|
250
|
+
}
|
|
251
|
+
: undefined);
|
|
209
252
|
if (resolvedSession instanceof session_js_1.SessionManager) {
|
|
210
253
|
this.sessionManager = resolvedSession;
|
|
211
254
|
}
|
|
@@ -237,7 +280,11 @@ class LocalAuthEngine {
|
|
|
237
280
|
const user = await this.getUserById(session.userId);
|
|
238
281
|
if (!user)
|
|
239
282
|
return null;
|
|
240
|
-
const result = await this.remoteAuthHandler({
|
|
283
|
+
const result = await this.remoteAuthHandler({
|
|
284
|
+
user,
|
|
285
|
+
session,
|
|
286
|
+
mode: 'refresh',
|
|
287
|
+
});
|
|
241
288
|
if (result && result.token) {
|
|
242
289
|
await this.sessionManager.updateTokens({ token: result.token });
|
|
243
290
|
session.token = result.token;
|
|
@@ -300,11 +347,26 @@ class LocalAuthEngine {
|
|
|
300
347
|
user_id TEXT NOT NULL,
|
|
301
348
|
token_hash TEXT NOT NULL,
|
|
302
349
|
type TEXT NOT NULL,
|
|
350
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
351
|
+
max_attempts INTEGER NOT NULL DEFAULT 1,
|
|
303
352
|
expires_at INTEGER NOT NULL,
|
|
304
353
|
created_at INTEGER NOT NULL,
|
|
305
354
|
used_at INTEGER
|
|
306
355
|
);
|
|
307
356
|
`);
|
|
357
|
+
// Backfill attempts/max_attempts columns on existing pre-3.x token tables
|
|
358
|
+
try {
|
|
359
|
+
await this.db.execute(`ALTER TABLE ${this.sqlTokensTable} ADD COLUMN attempts INTEGER NOT NULL DEFAULT 0;`);
|
|
360
|
+
}
|
|
361
|
+
catch {
|
|
362
|
+
// Column already exists
|
|
363
|
+
}
|
|
364
|
+
try {
|
|
365
|
+
await this.db.execute(`ALTER TABLE ${this.sqlTokensTable} ADD COLUMN max_attempts INTEGER NOT NULL DEFAULT 1;`);
|
|
366
|
+
}
|
|
367
|
+
catch {
|
|
368
|
+
// Column already exists
|
|
369
|
+
}
|
|
308
370
|
await this.db.execute(`
|
|
309
371
|
CREATE INDEX IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(`idx_${this.tokensTable}_hash`)} ON ${this.sqlTokensTable} (token_hash, type);
|
|
310
372
|
`);
|
|
@@ -392,7 +454,12 @@ class LocalAuthEngine {
|
|
|
392
454
|
});
|
|
393
455
|
if (this.remoteAuthHandler && session) {
|
|
394
456
|
try {
|
|
395
|
-
const remoteRes = await this.remoteAuthHandler({
|
|
457
|
+
const remoteRes = await this.remoteAuthHandler({
|
|
458
|
+
user,
|
|
459
|
+
session,
|
|
460
|
+
mode: 'signup',
|
|
461
|
+
password: options.password,
|
|
462
|
+
});
|
|
396
463
|
if (remoteRes && remoteRes.token) {
|
|
397
464
|
await this.sessionManager.updateTokens({ token: remoteRes.token });
|
|
398
465
|
session.token = remoteRes.token;
|
|
@@ -496,7 +563,12 @@ class LocalAuthEngine {
|
|
|
496
563
|
});
|
|
497
564
|
if (this.remoteAuthHandler && session) {
|
|
498
565
|
try {
|
|
499
|
-
const remoteRes = await this.remoteAuthHandler({
|
|
566
|
+
const remoteRes = await this.remoteAuthHandler({
|
|
567
|
+
user,
|
|
568
|
+
session,
|
|
569
|
+
mode: 'signin',
|
|
570
|
+
password,
|
|
571
|
+
});
|
|
500
572
|
if (remoteRes && remoteRes.token) {
|
|
501
573
|
await this.sessionManager.updateTokens({ token: remoteRes.token });
|
|
502
574
|
session.token = remoteRes.token;
|
|
@@ -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,450 @@
|
|
|
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 uuid_js_1 = require("../utils/uuid.js");
|
|
15
|
+
/**
|
|
16
|
+
* Persistent SQLite-backed ServerAuthStorage using any LocalDBAdapter.
|
|
17
|
+
*/
|
|
18
|
+
class SQLiteServerAuthStorage {
|
|
19
|
+
db;
|
|
20
|
+
initialized = false;
|
|
21
|
+
constructor(db) {
|
|
22
|
+
this.db = db;
|
|
23
|
+
}
|
|
24
|
+
async initialize() {
|
|
25
|
+
if (this.initialized)
|
|
26
|
+
return;
|
|
27
|
+
await this.db.execute(`
|
|
28
|
+
CREATE TABLE IF NOT EXISTS _local_auth_accounts (
|
|
29
|
+
id TEXT PRIMARY KEY,
|
|
30
|
+
email TEXT NOT NULL UNIQUE,
|
|
31
|
+
display_name TEXT,
|
|
32
|
+
password_hash TEXT NOT NULL,
|
|
33
|
+
salt TEXT NOT NULL,
|
|
34
|
+
iterations INTEGER NOT NULL,
|
|
35
|
+
algorithm TEXT NOT NULL,
|
|
36
|
+
failed_login_attempts INTEGER NOT NULL DEFAULT 0,
|
|
37
|
+
locked_until INTEGER,
|
|
38
|
+
token_version INTEGER NOT NULL DEFAULT 1,
|
|
39
|
+
created_at INTEGER NOT NULL,
|
|
40
|
+
updated_at INTEGER NOT NULL
|
|
41
|
+
);
|
|
42
|
+
`);
|
|
43
|
+
try {
|
|
44
|
+
await this.db.execute(`ALTER TABLE _local_auth_accounts ADD COLUMN token_version INTEGER NOT NULL DEFAULT 1;`);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// Column already exists
|
|
48
|
+
}
|
|
49
|
+
await this.db.execute(`
|
|
50
|
+
CREATE TABLE IF NOT EXISTS _local_auth_reset_otps (
|
|
51
|
+
id TEXT PRIMARY KEY,
|
|
52
|
+
user_id TEXT NOT NULL,
|
|
53
|
+
email TEXT NOT NULL,
|
|
54
|
+
otp_hash TEXT NOT NULL,
|
|
55
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
56
|
+
expires_at INTEGER NOT NULL,
|
|
57
|
+
used_at INTEGER,
|
|
58
|
+
created_at INTEGER NOT NULL
|
|
59
|
+
);
|
|
60
|
+
`);
|
|
61
|
+
await this.db.execute(`
|
|
62
|
+
CREATE INDEX IF NOT EXISTS idx_local_auth_otps_email
|
|
63
|
+
ON _local_auth_reset_otps (email, created_at);
|
|
64
|
+
`);
|
|
65
|
+
this.initialized = true;
|
|
66
|
+
}
|
|
67
|
+
async findUserByEmail(email) {
|
|
68
|
+
await this.initialize();
|
|
69
|
+
const rows = await this.db.execute(`SELECT * FROM _local_auth_accounts WHERE email = ? LIMIT 1;`, [email]);
|
|
70
|
+
const r = rows?.[0];
|
|
71
|
+
if (!r)
|
|
72
|
+
return null;
|
|
73
|
+
return {
|
|
74
|
+
id: String(r.id),
|
|
75
|
+
email: String(r.email),
|
|
76
|
+
displayName: r.display_name ?? null,
|
|
77
|
+
passwordHash: String(r.password_hash),
|
|
78
|
+
salt: String(r.salt),
|
|
79
|
+
iterations: Number(r.iterations),
|
|
80
|
+
algorithm: String(r.algorithm),
|
|
81
|
+
failedLoginAttempts: Number(r.failed_login_attempts ?? 0),
|
|
82
|
+
lockedUntil: r.locked_until != null ? Number(r.locked_until) : null,
|
|
83
|
+
tokenVersion: r.token_version != null ? Number(r.token_version) : 1,
|
|
84
|
+
createdAt: Number(r.created_at),
|
|
85
|
+
updatedAt: Number(r.updated_at),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
async createUser(record) {
|
|
89
|
+
await this.initialize();
|
|
90
|
+
await this.db.execute(`INSERT INTO _local_auth_accounts
|
|
91
|
+
(id, email, display_name, password_hash, salt, iterations, algorithm, failed_login_attempts, locked_until, token_version, created_at, updated_at)
|
|
92
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, [
|
|
93
|
+
record.id,
|
|
94
|
+
record.email,
|
|
95
|
+
record.displayName ?? null,
|
|
96
|
+
record.passwordHash,
|
|
97
|
+
record.salt,
|
|
98
|
+
record.iterations,
|
|
99
|
+
record.algorithm,
|
|
100
|
+
record.failedLoginAttempts,
|
|
101
|
+
record.lockedUntil ?? null,
|
|
102
|
+
record.tokenVersion ?? 1,
|
|
103
|
+
record.createdAt,
|
|
104
|
+
record.updatedAt,
|
|
105
|
+
]);
|
|
106
|
+
}
|
|
107
|
+
async recordFailedAttempt(userId, attempts, lockedUntil, updatedAt) {
|
|
108
|
+
await this.initialize();
|
|
109
|
+
await this.db.execute(`UPDATE _local_auth_accounts SET failed_login_attempts = ?, locked_until = ?, updated_at = ? WHERE id = ?;`, [attempts, lockedUntil, updatedAt, userId]);
|
|
110
|
+
}
|
|
111
|
+
async updatePasswordAndResetLockout(userId, patch) {
|
|
112
|
+
await this.initialize();
|
|
113
|
+
await this.db.execute(`UPDATE _local_auth_accounts
|
|
114
|
+
SET password_hash = ?, salt = ?, iterations = ?, algorithm = ?, failed_login_attempts = 0, locked_until = NULL, token_version = COALESCE(token_version, 1) + 1, updated_at = ?
|
|
115
|
+
WHERE id = ?;`, [
|
|
116
|
+
patch.passwordHash,
|
|
117
|
+
patch.salt,
|
|
118
|
+
patch.iterations,
|
|
119
|
+
patch.algorithm,
|
|
120
|
+
patch.updatedAt,
|
|
121
|
+
userId,
|
|
122
|
+
]);
|
|
123
|
+
}
|
|
124
|
+
async invalidateActiveOtps(email, usedAt) {
|
|
125
|
+
await this.initialize();
|
|
126
|
+
await this.db.execute(`UPDATE _local_auth_reset_otps SET used_at = ? WHERE email = ? AND used_at IS NULL;`, [usedAt, email]);
|
|
127
|
+
}
|
|
128
|
+
async createResetOtp(record) {
|
|
129
|
+
await this.initialize();
|
|
130
|
+
await this.db.execute(`INSERT INTO _local_auth_reset_otps
|
|
131
|
+
(id, user_id, email, otp_hash, attempts, expires_at, used_at, created_at)
|
|
132
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?);`, [
|
|
133
|
+
record.id,
|
|
134
|
+
record.userId,
|
|
135
|
+
record.email,
|
|
136
|
+
record.otpHash,
|
|
137
|
+
record.attempts,
|
|
138
|
+
record.expiresAt,
|
|
139
|
+
record.usedAt ?? null,
|
|
140
|
+
record.createdAt,
|
|
141
|
+
]);
|
|
142
|
+
}
|
|
143
|
+
async findLatestActiveOtp(email) {
|
|
144
|
+
await this.initialize();
|
|
145
|
+
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]);
|
|
146
|
+
const r = rows?.[0];
|
|
147
|
+
if (!r)
|
|
148
|
+
return null;
|
|
149
|
+
return {
|
|
150
|
+
id: String(r.id),
|
|
151
|
+
userId: String(r.user_id),
|
|
152
|
+
email: String(r.email),
|
|
153
|
+
otpHash: String(r.otp_hash),
|
|
154
|
+
attempts: Number(r.attempts ?? 0),
|
|
155
|
+
expiresAt: Number(r.expires_at),
|
|
156
|
+
usedAt: r.used_at != null ? Number(r.used_at) : null,
|
|
157
|
+
createdAt: Number(r.created_at),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
async incrementOtpAttempts(id, attempts, usedAt) {
|
|
161
|
+
await this.initialize();
|
|
162
|
+
await this.db.execute(`UPDATE _local_auth_reset_otps SET attempts = ?, used_at = ? WHERE id = ?;`, [attempts, usedAt, id]);
|
|
163
|
+
}
|
|
164
|
+
async markOtpUsed(id, usedAt) {
|
|
165
|
+
await this.initialize();
|
|
166
|
+
await this.db.execute(`UPDATE _local_auth_reset_otps SET used_at = ? WHERE id = ?;`, [usedAt, id]);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
exports.SQLiteServerAuthStorage = SQLiteServerAuthStorage;
|
|
170
|
+
const DEFAULT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
171
|
+
const DEFAULT_SERVER_PASSWORD_ITERATIONS = 100_000;
|
|
172
|
+
const DEFAULT_OTP_TTL_MS = 15 * 60 * 1000;
|
|
173
|
+
function deriveSubSecret(secret, scope) {
|
|
174
|
+
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)));
|
|
175
|
+
}
|
|
176
|
+
function hashServerOtp(secret, email, otp) {
|
|
177
|
+
const key = deriveSubSecret(secret, 'local-sync-otp-v1');
|
|
178
|
+
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()}`)));
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Verifies a Bearer token or Request issued by `createAuthEndpoint()`.
|
|
182
|
+
*/
|
|
183
|
+
function verifyAuthToken(requestOrToken, secret) {
|
|
184
|
+
if (!secret)
|
|
185
|
+
return null;
|
|
186
|
+
let token = '';
|
|
187
|
+
if (typeof requestOrToken === 'string') {
|
|
188
|
+
const trimmed = requestOrToken.trim();
|
|
189
|
+
token = trimmed.startsWith('Bearer ') ? trimmed.slice(7).trim() : trimmed;
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
const authHeader = requestOrToken.headers.get('authorization');
|
|
193
|
+
if (authHeader && authHeader.startsWith('Bearer ')) {
|
|
194
|
+
token = authHeader.slice(7).trim();
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (!token)
|
|
198
|
+
return null;
|
|
199
|
+
const signingSecret = deriveSubSecret(secret, 'local-sync-auth-v1');
|
|
200
|
+
const result = (0, signed_token_js_1.verifySignedToken)(token, signingSecret);
|
|
201
|
+
if (!result.valid ||
|
|
202
|
+
!result.payload ||
|
|
203
|
+
result.payload.purpose !== 'sync-auth' ||
|
|
204
|
+
!result.payload.sub ||
|
|
205
|
+
!result.payload.email) {
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
id: result.payload.sub,
|
|
210
|
+
email: result.payload.email,
|
|
211
|
+
name: result.payload.name ?? null,
|
|
212
|
+
provider: 'local',
|
|
213
|
+
tokenVersion: typeof result.payload.tv === 'number' ? result.payload.tv : 1,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Verifies a Bearer token and checks that its tokenVersion matches the stored user record
|
|
218
|
+
* (revoking tokens issued before a password reset).
|
|
219
|
+
*/
|
|
220
|
+
async function verifyAuthTokenWithStorage(requestOrToken, secret, storage) {
|
|
221
|
+
const verified = verifyAuthToken(requestOrToken, secret);
|
|
222
|
+
if (!verified)
|
|
223
|
+
return null;
|
|
224
|
+
const user = await storage.findUserByEmail(verified.email);
|
|
225
|
+
if (!user || user.id !== verified.id)
|
|
226
|
+
return null;
|
|
227
|
+
if ((user.tokenVersion ?? 1) !== verified.tokenVersion)
|
|
228
|
+
return null;
|
|
229
|
+
return verified;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Creates a turnkey Web Request/Response handler for local email/password auth,
|
|
233
|
+
* token refresh, and 6-digit email OTP password resets.
|
|
234
|
+
*/
|
|
235
|
+
function createAuthEndpoint(options) {
|
|
236
|
+
const { storage, secret, tokenTtlMs = DEFAULT_TOKEN_TTL_MS, passwordIterations = DEFAULT_SERVER_PASSWORD_ITERATIONS, minPasswordLength = 8, maxFailedAttempts = 5, lockoutDurationMs = 15 * 60 * 1000, sendResetOtpEmail, } = options;
|
|
237
|
+
const otpTtlMs = options.otp?.ttlMs ?? DEFAULT_OTP_TTL_MS;
|
|
238
|
+
const maxOtpAttempts = options.otp?.maxAttempts ?? 5;
|
|
239
|
+
if (!secret || !secret.trim()) {
|
|
240
|
+
throw new Error('A non-empty signing secret is required.');
|
|
241
|
+
}
|
|
242
|
+
const signingSecret = deriveSubSecret(secret, 'local-sync-auth-v1');
|
|
243
|
+
const issueToken = (user) => (0, signed_token_js_1.createSignedToken)({
|
|
244
|
+
secret: signingSecret,
|
|
245
|
+
expiresInMs: tokenTtlMs,
|
|
246
|
+
payload: {
|
|
247
|
+
purpose: 'sync-auth',
|
|
248
|
+
sub: user.id,
|
|
249
|
+
email: user.email,
|
|
250
|
+
name: user.displayName ?? null,
|
|
251
|
+
tv: user.tokenVersion ?? 1,
|
|
252
|
+
},
|
|
253
|
+
});
|
|
254
|
+
return async function handleAuthRequest(request) {
|
|
255
|
+
if (request.method.toUpperCase() === 'OPTIONS') {
|
|
256
|
+
return new Response(null, { status: 204 });
|
|
257
|
+
}
|
|
258
|
+
if (request.method.toUpperCase() !== 'POST') {
|
|
259
|
+
return Response.json({ error: 'Method Not Allowed' }, { status: 405 });
|
|
260
|
+
}
|
|
261
|
+
const pathname = new URL(request.url).pathname.replace(/\/+$/, '');
|
|
262
|
+
// 1. Refresh
|
|
263
|
+
if (pathname.endsWith('/refresh')) {
|
|
264
|
+
const verified = await verifyAuthTokenWithStorage(request, secret, storage);
|
|
265
|
+
if (!verified) {
|
|
266
|
+
return Response.json({ error: 'Unauthorized' }, { status: 401 });
|
|
267
|
+
}
|
|
268
|
+
const token = issueToken({
|
|
269
|
+
id: verified.id,
|
|
270
|
+
email: verified.email,
|
|
271
|
+
displayName: verified.name,
|
|
272
|
+
tokenVersion: verified.tokenVersion,
|
|
273
|
+
});
|
|
274
|
+
return Response.json({ token });
|
|
275
|
+
}
|
|
276
|
+
let body;
|
|
277
|
+
try {
|
|
278
|
+
body = (await request.json());
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return Response.json({ error: 'Invalid JSON payload' }, { status: 400 });
|
|
282
|
+
}
|
|
283
|
+
// 2. Forgot Password (6-digit Email OTP)
|
|
284
|
+
if (pathname.endsWith('/forgot-password')) {
|
|
285
|
+
const email = typeof body.email === 'string' ? body.email.trim().toLowerCase() : '';
|
|
286
|
+
if (!email || !email.includes('@')) {
|
|
287
|
+
return Response.json({ error: 'Please enter a valid email address.' }, { status: 400 });
|
|
288
|
+
}
|
|
289
|
+
const existing = await storage.findUserByEmail(email);
|
|
290
|
+
if (existing) {
|
|
291
|
+
const limit = 4_294_800_000;
|
|
292
|
+
let num = limit;
|
|
293
|
+
while (num >= limit) {
|
|
294
|
+
const randomVal = (0, local_js_1.getCryptoRandomBytes)(4);
|
|
295
|
+
num =
|
|
296
|
+
((randomVal[0] << 24) |
|
|
297
|
+
(randomVal[1] << 16) |
|
|
298
|
+
(randomVal[2] << 8) |
|
|
299
|
+
randomVal[3]) >>>
|
|
300
|
+
0;
|
|
301
|
+
}
|
|
302
|
+
const otp = String(100000 + (num % 900000));
|
|
303
|
+
const now = Date.now();
|
|
304
|
+
await storage.invalidateActiveOtps(email, now);
|
|
305
|
+
await storage.createResetOtp({
|
|
306
|
+
id: (0, uuid_js_1.generateUUID)(),
|
|
307
|
+
userId: existing.id,
|
|
308
|
+
email,
|
|
309
|
+
otpHash: hashServerOtp(secret, email, otp),
|
|
310
|
+
attempts: 0,
|
|
311
|
+
expiresAt: now + otpTtlMs,
|
|
312
|
+
usedAt: null,
|
|
313
|
+
createdAt: now,
|
|
314
|
+
});
|
|
315
|
+
if (sendResetOtpEmail) {
|
|
316
|
+
await sendResetOtpEmail({
|
|
317
|
+
to: email,
|
|
318
|
+
otp,
|
|
319
|
+
expiresMinutes: Math.max(1, Math.round(otpTtlMs / 60000)),
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return Response.json({
|
|
324
|
+
success: true,
|
|
325
|
+
message: 'If an account exists for that email, a verification code has been sent.',
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
// 3. Reset Password with OTP
|
|
329
|
+
if (pathname.endsWith('/reset-password')) {
|
|
330
|
+
const email = typeof body.email === 'string' ? body.email.trim().toLowerCase() : '';
|
|
331
|
+
const otp = typeof body.otp === 'string' ? body.otp.trim() : '';
|
|
332
|
+
const newPassword = typeof body.newPassword === 'string' ? body.newPassword : '';
|
|
333
|
+
if (!email || !email.includes('@') || !/^\d{6}$/.test(otp)) {
|
|
334
|
+
return Response.json({ error: 'Valid email and 6-digit verification code are required.' }, { status: 400 });
|
|
335
|
+
}
|
|
336
|
+
if (newPassword.length < minPasswordLength) {
|
|
337
|
+
return Response.json({
|
|
338
|
+
error: `New password must be at least ${minPasswordLength} characters.`,
|
|
339
|
+
}, { status: 400 });
|
|
340
|
+
}
|
|
341
|
+
const now = Date.now();
|
|
342
|
+
const otpRow = await storage.findLatestActiveOtp(email);
|
|
343
|
+
if (!otpRow || otpRow.expiresAt <= now) {
|
|
344
|
+
return Response.json({ error: 'Invalid or expired verification code.' }, { status: 400 });
|
|
345
|
+
}
|
|
346
|
+
if (otpRow.attempts >= maxOtpAttempts) {
|
|
347
|
+
await storage.markOtpUsed(otpRow.id, now);
|
|
348
|
+
return Response.json({ error: 'Too many invalid attempts. Please request a new code.' }, { status: 429 });
|
|
349
|
+
}
|
|
350
|
+
const actualHash = hashServerOtp(secret, email, otp);
|
|
351
|
+
if (!(0, generator_js_1.timingSafeEqual)(actualHash, otpRow.otpHash)) {
|
|
352
|
+
const nextAttempts = otpRow.attempts + 1;
|
|
353
|
+
await storage.incrementOtpAttempts(otpRow.id, nextAttempts, nextAttempts >= maxOtpAttempts ? now : null);
|
|
354
|
+
return Response.json({ error: 'Invalid or expired verification code.' }, { status: 400 });
|
|
355
|
+
}
|
|
356
|
+
const hashed = await (0, local_js_1.hashPassword)(newPassword, {
|
|
357
|
+
iterations: passwordIterations,
|
|
358
|
+
});
|
|
359
|
+
await storage.updatePasswordAndResetLockout(otpRow.userId, {
|
|
360
|
+
passwordHash: hashed.hash,
|
|
361
|
+
salt: hashed.salt,
|
|
362
|
+
iterations: hashed.iterations,
|
|
363
|
+
algorithm: hashed.algorithm,
|
|
364
|
+
updatedAt: now,
|
|
365
|
+
});
|
|
366
|
+
await storage.markOtpUsed(otpRow.id, now);
|
|
367
|
+
return Response.json({ success: true });
|
|
368
|
+
}
|
|
369
|
+
// 4. Sign In / Sign Up
|
|
370
|
+
const mode = body.mode === 'signup' ? 'signup' : 'signin';
|
|
371
|
+
const email = typeof body.email === 'string' ? body.email.trim().toLowerCase() : '';
|
|
372
|
+
const password = typeof body.password === 'string' ? body.password : '';
|
|
373
|
+
const displayName = typeof body.displayName === 'string' && body.displayName.trim()
|
|
374
|
+
? body.displayName.trim()
|
|
375
|
+
: null;
|
|
376
|
+
if (!email || !email.includes('@') || !password) {
|
|
377
|
+
return Response.json({ error: 'Valid email and password are required.' }, { status: 400 });
|
|
378
|
+
}
|
|
379
|
+
const existing = await storage.findUserByEmail(email);
|
|
380
|
+
if (mode === 'signup') {
|
|
381
|
+
if (existing) {
|
|
382
|
+
return Response.json({ error: 'An account with this email already exists.' }, { status: 409 });
|
|
383
|
+
}
|
|
384
|
+
if (password.length < minPasswordLength) {
|
|
385
|
+
return Response.json({
|
|
386
|
+
error: `Password must be at least ${minPasswordLength} characters.`,
|
|
387
|
+
}, { status: 400 });
|
|
388
|
+
}
|
|
389
|
+
const id = (0, identity_js_1.resolveUnifiedUserId)({ id: email, email, emailVerified: false }, 'local');
|
|
390
|
+
const hashed = await (0, local_js_1.hashPassword)(password, {
|
|
391
|
+
iterations: passwordIterations,
|
|
392
|
+
});
|
|
393
|
+
const now = Date.now();
|
|
394
|
+
await storage.createUser({
|
|
395
|
+
id,
|
|
396
|
+
email,
|
|
397
|
+
displayName,
|
|
398
|
+
passwordHash: hashed.hash,
|
|
399
|
+
salt: hashed.salt,
|
|
400
|
+
iterations: hashed.iterations,
|
|
401
|
+
algorithm: hashed.algorithm,
|
|
402
|
+
failedLoginAttempts: 0,
|
|
403
|
+
lockedUntil: null,
|
|
404
|
+
tokenVersion: 1,
|
|
405
|
+
createdAt: now,
|
|
406
|
+
updatedAt: now,
|
|
407
|
+
});
|
|
408
|
+
const token = issueToken({ id, email, displayName, tokenVersion: 1 });
|
|
409
|
+
return Response.json({
|
|
410
|
+
token,
|
|
411
|
+
user: { id, email, displayName },
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
if (!existing) {
|
|
415
|
+
// Constant-time dummy verification mitigates timing-based email enumeration.
|
|
416
|
+
await (0, local_js_1.verifyPassword)('dummy_password', '0'.repeat(64), '0'.repeat(32), Math.min(passwordIterations, 5_000));
|
|
417
|
+
return Response.json({ error: 'Invalid email or password.' }, { status: 401 });
|
|
418
|
+
}
|
|
419
|
+
const now = Date.now();
|
|
420
|
+
if (existing.lockedUntil && existing.lockedUntil > now) {
|
|
421
|
+
return Response.json({ error: 'Account temporarily locked due to too many failed attempts.' }, { status: 429 });
|
|
422
|
+
}
|
|
423
|
+
const valid = await (0, local_js_1.verifyPassword)(password, existing.passwordHash, existing.salt, existing.iterations, existing.algorithm);
|
|
424
|
+
if (!valid) {
|
|
425
|
+
const nextAttempts = existing.failedLoginAttempts + 1;
|
|
426
|
+
const lockedUntil = maxFailedAttempts > 0 && nextAttempts >= maxFailedAttempts
|
|
427
|
+
? now + lockoutDurationMs
|
|
428
|
+
: null;
|
|
429
|
+
await storage.recordFailedAttempt(existing.id, nextAttempts, lockedUntil, now);
|
|
430
|
+
return Response.json({ error: 'Invalid email or password.' }, { status: 401 });
|
|
431
|
+
}
|
|
432
|
+
if (existing.failedLoginAttempts > 0 || existing.lockedUntil) {
|
|
433
|
+
await storage.recordFailedAttempt(existing.id, 0, null, now);
|
|
434
|
+
}
|
|
435
|
+
const token = issueToken({
|
|
436
|
+
id: existing.id,
|
|
437
|
+
email: existing.email,
|
|
438
|
+
displayName: existing.displayName ?? null,
|
|
439
|
+
tokenVersion: existing.tokenVersion ?? 1,
|
|
440
|
+
});
|
|
441
|
+
return Response.json({
|
|
442
|
+
token,
|
|
443
|
+
user: {
|
|
444
|
+
id: existing.id,
|
|
445
|
+
email: existing.email,
|
|
446
|
+
displayName: existing.displayName ?? null,
|
|
447
|
+
},
|
|
448
|
+
});
|
|
449
|
+
};
|
|
450
|
+
}
|
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('/')}`;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "local-lite",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.2",
|
|
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",
|