local-lite 3.0.2 → 3.0.4

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.
@@ -198,6 +198,11 @@ export declare function hashPassword(password: string, options?: {
198
198
  * Verifies a plaintext password against a stored PBKDF2 hash using constant-time comparison.
199
199
  */
200
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>;
201
206
  /**
202
207
  * Generates an opaque random token and its corresponding SHA-256 hash.
203
208
  */
@@ -239,6 +244,8 @@ export declare class LocalAuthEngine {
239
244
  * Gets the configured remote authentication exchange handler.
240
245
  */
241
246
  getRemoteAuthHandler(): RemoteAuthHandler | undefined;
247
+ private performRemoteAuthExchange;
248
+ private tryRemoteAuthExchange;
242
249
  /**
243
250
  * Triggers token exchange with the registered remote sync provider for the active session.
244
251
  */
@@ -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
  */
@@ -214,34 +222,30 @@ class LocalAuthEngine {
214
222
  if (!fetchFn)
215
223
  return null;
216
224
  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`, {
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, {
234
237
  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
- }),
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
+ }),
245
249
  });
246
250
  if (!res.ok)
247
251
  return null;
@@ -268,6 +272,26 @@ class LocalAuthEngine {
268
272
  getRemoteAuthHandler() {
269
273
  return this.remoteAuthHandler;
270
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
+ }
271
295
  /**
272
296
  * Triggers token exchange with the registered remote sync provider for the active session.
273
297
  */
@@ -280,16 +304,11 @@ class LocalAuthEngine {
280
304
  const user = await this.getUserById(session.userId);
281
305
  if (!user)
282
306
  return null;
283
- const result = await this.remoteAuthHandler({
307
+ return this.performRemoteAuthExchange({
284
308
  user,
285
309
  session,
286
310
  mode: 'refresh',
287
311
  });
288
- if (result && result.token) {
289
- await this.sessionManager.updateTokens({ token: result.token });
290
- session.token = result.token;
291
- }
292
- return result;
293
312
  }
294
313
  /**
295
314
  * Retrieves the cached remote sync authentication token from the active session.
@@ -452,22 +471,13 @@ class LocalAuthEngine {
452
471
  offlineDurationMs: options.offlineDurationMs,
453
472
  setActive: true,
454
473
  });
455
- if (this.remoteAuthHandler && session) {
456
- try {
457
- const remoteRes = await this.remoteAuthHandler({
458
- user,
459
- session,
460
- mode: 'signup',
461
- password: options.password,
462
- });
463
- if (remoteRes && remoteRes.token) {
464
- await this.sessionManager.updateTokens({ token: remoteRes.token });
465
- session.token = remoteRes.token;
466
- }
467
- }
468
- catch {
469
- // Non-fatal if offline
470
- }
474
+ if (session) {
475
+ await this.tryRemoteAuthExchange({
476
+ user,
477
+ session,
478
+ mode: 'signup',
479
+ password: options.password,
480
+ });
471
481
  }
472
482
  }
473
483
  this.events?.emit(this.usersTable, { operation: 'SIGN_UP', user });
@@ -486,8 +496,7 @@ class LocalAuthEngine {
486
496
  const rows = await this.db.execute(`SELECT * FROM ${this.sqlUsersTable} WHERE lower(email) = ? OR lower(username) = ? LIMIT 1;`, [identifier, identifier]);
487
497
  const row = (rows && rows.length > 0 ? rows[0] : null);
488
498
  if (!row) {
489
- // Dummy verification to mitigate timing attacks against non-existent accounts
490
- await verifyPassword('dummy_password', '0'.repeat(128), '0'.repeat(32), Math.min(this.iterations, 5_000));
499
+ await verifyDummyPassword(this.iterations);
491
500
  throw new Error('Invalid email/username or password.');
492
501
  }
493
502
  const now = Date.now();
@@ -561,22 +570,13 @@ class LocalAuthEngine {
561
570
  offlineDurationMs: options.offlineDurationMs,
562
571
  setActive: true,
563
572
  });
564
- if (this.remoteAuthHandler && session) {
565
- try {
566
- const remoteRes = await this.remoteAuthHandler({
567
- user,
568
- session,
569
- mode: 'signin',
570
- password,
571
- });
572
- if (remoteRes && remoteRes.token) {
573
- await this.sessionManager.updateTokens({ token: remoteRes.token });
574
- session.token = remoteRes.token;
575
- }
576
- }
577
- catch {
578
- // Non-fatal if offline
579
- }
573
+ if (session) {
574
+ await this.tryRemoteAuthExchange({
575
+ user,
576
+ session,
577
+ mode: 'signin',
578
+ password,
579
+ });
580
580
  }
581
581
  }
582
582
  this.events?.emit(this.usersTable, { operation: 'SIGN_IN', user, session });
@@ -273,8 +273,12 @@ function generateSqlDiff(prevSchema, nextSchema, dialect = 'mysql') {
273
273
  const safeCol = !col.nullable && !col.defaultSql
274
274
  ? { ...col, nullable: true, defaultSql: 'NULL' }
275
275
  : col;
276
- up.push(`ALTER TABLE ${qTable} ADD COLUMN ${formatColumnDef(colName, safeCol, dialect)};`);
277
- down.unshift(`ALTER TABLE ${qTable} DROP COLUMN ${quoteIdent(colName, dialect)};`);
276
+ up.push(dialect === 'mysql'
277
+ ? `ALTER TABLE ${qTable} ADD COLUMN IF NOT EXISTS ${formatColumnDef(colName, safeCol, dialect)};`
278
+ : `ALTER TABLE ${qTable} ADD COLUMN ${formatColumnDef(colName, safeCol, dialect)};`);
279
+ down.unshift(dialect === 'mysql'
280
+ ? `ALTER TABLE ${qTable} DROP COLUMN IF EXISTS ${quoteIdent(colName, dialect)};`
281
+ : `ALTER TABLE ${qTable} DROP COLUMN ${quoteIdent(colName, dialect)};`);
278
282
  }
279
283
  else if (prevCol.sqlType !== col.sqlType) {
280
284
  warnings.push(`Column type changed for ${tableName}.${colName} (${prevCol.sqlType} -> ${col.sqlType}); review manually before altering.`);
@@ -454,7 +458,7 @@ function applySqlStatement(tables, stmt) {
454
458
  if (!table)
455
459
  return;
456
460
  for (const clause of splitTopLevel(alterMatch[2], ',')) {
457
- const addCol = clause.match(/^ADD\s+(?:COLUMN\s+)?[`"]?(\w+)[`"]?\s+([\s\S]+)$/i);
461
+ const addCol = clause.match(/^ADD\s+(?:COLUMN\s+)?(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?\s+([\s\S]+)$/i);
458
462
  if (addCol && !/^(?:UNIQUE|INDEX|KEY|CONSTRAINT|PRIMARY|FOREIGN)\b/i.test(addCol[1])) {
459
463
  table.columns[addCol[1]] = {
460
464
  sqlType: parseSqlType(addCol[2]),
@@ -463,7 +467,7 @@ function applySqlStatement(tables, stmt) {
463
467
  };
464
468
  continue;
465
469
  }
466
- const dropCol = clause.match(/^DROP\s+(?:COLUMN\s+)?[`"]?(\w+)[`"]?$/i);
470
+ const dropCol = clause.match(/^DROP\s+(?:COLUMN\s+)?(?:IF\s+EXISTS\s+)?[`"]?(\w+)[`"]?$/i);
467
471
  if (dropCol) {
468
472
  delete table.columns[dropCol[1]];
469
473
  continue;
@@ -11,6 +11,7 @@ const identity_js_1 = require("../auth/identity.js");
11
11
  const local_js_1 = require("../auth/local.js");
12
12
  const generator_js_1 = require("../keys/generator.js");
13
13
  const signed_token_js_1 = require("../keys/signed-token.js");
14
+ const http_js_1 = require("../utils/http.js");
14
15
  const uuid_js_1 = require("../utils/uuid.js");
15
16
  /**
16
17
  * Persistent SQLite-backed ServerAuthStorage using any LocalDBAdapter.
@@ -170,6 +171,12 @@ exports.SQLiteServerAuthStorage = SQLiteServerAuthStorage;
170
171
  const DEFAULT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
171
172
  const DEFAULT_SERVER_PASSWORD_ITERATIONS = 100_000;
172
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
+ }
173
180
  function deriveSubSecret(secret, scope) {
174
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)));
175
182
  }
@@ -256,14 +263,14 @@ function createAuthEndpoint(options) {
256
263
  return new Response(null, { status: 204 });
257
264
  }
258
265
  if (request.method.toUpperCase() !== 'POST') {
259
- return Response.json({ error: 'Method Not Allowed' }, { status: 405 });
266
+ return (0, http_js_1.jsonError)('Method Not Allowed', 405);
260
267
  }
261
268
  const pathname = new URL(request.url).pathname.replace(/\/+$/, '');
262
269
  // 1. Refresh
263
270
  if (pathname.endsWith('/refresh')) {
264
271
  const verified = await verifyAuthTokenWithStorage(request, secret, storage);
265
272
  if (!verified) {
266
- return Response.json({ error: 'Unauthorized' }, { status: 401 });
273
+ return (0, http_js_1.jsonError)('Unauthorized', 401);
267
274
  }
268
275
  const token = issueToken({
269
276
  id: verified.id,
@@ -278,13 +285,13 @@ function createAuthEndpoint(options) {
278
285
  body = (await request.json());
279
286
  }
280
287
  catch {
281
- return Response.json({ error: 'Invalid JSON payload' }, { status: 400 });
288
+ return (0, http_js_1.jsonError)('Invalid JSON payload', 400);
282
289
  }
283
290
  // 2. Forgot Password (6-digit Email OTP)
284
291
  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 });
292
+ const email = normalizeEmail(body.email);
293
+ if (!isValidEmail(email)) {
294
+ return (0, http_js_1.jsonError)('Please enter a valid email address.', 400);
288
295
  }
289
296
  const existing = await storage.findUserByEmail(email);
290
297
  if (existing) {
@@ -327,31 +334,29 @@ function createAuthEndpoint(options) {
327
334
  }
328
335
  // 3. Reset Password with OTP
329
336
  if (pathname.endsWith('/reset-password')) {
330
- const email = typeof body.email === 'string' ? body.email.trim().toLowerCase() : '';
337
+ const email = normalizeEmail(body.email);
331
338
  const otp = typeof body.otp === 'string' ? body.otp.trim() : '';
332
339
  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 });
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);
335
342
  }
336
343
  if (newPassword.length < minPasswordLength) {
337
- return Response.json({
338
- error: `New password must be at least ${minPasswordLength} characters.`,
339
- }, { status: 400 });
344
+ return (0, http_js_1.jsonError)(`New password must be at least ${minPasswordLength} characters.`, 400);
340
345
  }
341
346
  const now = Date.now();
342
347
  const otpRow = await storage.findLatestActiveOtp(email);
343
348
  if (!otpRow || otpRow.expiresAt <= now) {
344
- return Response.json({ error: 'Invalid or expired verification code.' }, { status: 400 });
349
+ return (0, http_js_1.jsonError)('Invalid or expired verification code.', 400);
345
350
  }
346
351
  if (otpRow.attempts >= maxOtpAttempts) {
347
352
  await storage.markOtpUsed(otpRow.id, now);
348
- return Response.json({ error: 'Too many invalid attempts. Please request a new code.' }, { status: 429 });
353
+ return (0, http_js_1.jsonError)('Too many invalid attempts. Please request a new code.', 429);
349
354
  }
350
355
  const actualHash = hashServerOtp(secret, email, otp);
351
356
  if (!(0, generator_js_1.timingSafeEqual)(actualHash, otpRow.otpHash)) {
352
357
  const nextAttempts = otpRow.attempts + 1;
353
358
  await storage.incrementOtpAttempts(otpRow.id, nextAttempts, nextAttempts >= maxOtpAttempts ? now : null);
354
- return Response.json({ error: 'Invalid or expired verification code.' }, { status: 400 });
359
+ return (0, http_js_1.jsonError)('Invalid or expired verification code.', 400);
355
360
  }
356
361
  const hashed = await (0, local_js_1.hashPassword)(newPassword, {
357
362
  iterations: passwordIterations,
@@ -368,23 +373,21 @@ function createAuthEndpoint(options) {
368
373
  }
369
374
  // 4. Sign In / Sign Up
370
375
  const mode = body.mode === 'signup' ? 'signup' : 'signin';
371
- const email = typeof body.email === 'string' ? body.email.trim().toLowerCase() : '';
376
+ const email = normalizeEmail(body.email);
372
377
  const password = typeof body.password === 'string' ? body.password : '';
373
378
  const displayName = typeof body.displayName === 'string' && body.displayName.trim()
374
379
  ? body.displayName.trim()
375
380
  : null;
376
- if (!email || !email.includes('@') || !password) {
377
- return Response.json({ error: 'Valid email and password are required.' }, { status: 400 });
381
+ if (!isValidEmail(email) || !password) {
382
+ return (0, http_js_1.jsonError)('Valid email and password are required.', 400);
378
383
  }
379
384
  const existing = await storage.findUserByEmail(email);
380
385
  if (mode === 'signup') {
381
386
  if (existing) {
382
- return Response.json({ error: 'An account with this email already exists.' }, { status: 409 });
387
+ return (0, http_js_1.jsonError)('An account with this email already exists.', 409);
383
388
  }
384
389
  if (password.length < minPasswordLength) {
385
- return Response.json({
386
- error: `Password must be at least ${minPasswordLength} characters.`,
387
- }, { status: 400 });
390
+ return (0, http_js_1.jsonError)(`Password must be at least ${minPasswordLength} characters.`, 400);
388
391
  }
389
392
  const id = (0, identity_js_1.resolveUnifiedUserId)({ id: email, email, emailVerified: false }, 'local');
390
393
  const hashed = await (0, local_js_1.hashPassword)(password, {
@@ -412,13 +415,12 @@ function createAuthEndpoint(options) {
412
415
  });
413
416
  }
414
417
  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
+ await (0, local_js_1.verifyDummyPassword)(passwordIterations);
419
+ return (0, http_js_1.jsonError)('Invalid email or password.', 401);
418
420
  }
419
421
  const now = Date.now();
420
422
  if (existing.lockedUntil && existing.lockedUntil > now) {
421
- return Response.json({ error: 'Account temporarily locked due to too many failed attempts.' }, { status: 429 });
423
+ return (0, http_js_1.jsonError)('Account temporarily locked due to too many failed attempts.', 429);
422
424
  }
423
425
  const valid = await (0, local_js_1.verifyPassword)(password, existing.passwordHash, existing.salt, existing.iterations, existing.algorithm);
424
426
  if (!valid) {
@@ -427,7 +429,7 @@ function createAuthEndpoint(options) {
427
429
  ? now + lockoutDurationMs
428
430
  : null;
429
431
  await storage.recordFailedAttempt(existing.id, nextAttempts, lockedUntil, now);
430
- return Response.json({ error: 'Invalid email or password.' }, { status: 401 });
432
+ return (0, http_js_1.jsonError)('Invalid email or password.', 401);
431
433
  }
432
434
  if (existing.failedLoginAttempts > 0 || existing.lockedUntil) {
433
435
  await storage.recordFailedAttempt(existing.id, 0, null, now);
@@ -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 new Response(JSON.stringify(data), {
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 jsonResponse({ error: message }, status);
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
- let token = result.session?.token ?? '';
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
- let token = result.session?.token ?? '';
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);
@@ -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.2",
3
+ "version": "3.0.4",
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",