@basaltkit/auth 1.0.0 → 1.2.0

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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Machize Contributors
3
+ Copyright (c) 2026 Basalt Contributors
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/dist/index.d.ts CHANGED
@@ -10,6 +10,10 @@ interface PasswordHasher {
10
10
  * Default hasher: scrypt from node:crypto — memory-hard, zero dependencies.
11
11
  * An argon2id driver can be swapped in via the same contract (native module,
12
12
  * left out of the core install).
13
+ *
14
+ * The default cost is N=2^16 (r=8, p=1) — ~64 MiB per hash. The parameters are
15
+ * embedded in every hash, so raising them here never breaks verification of
16
+ * older, cheaper hashes; those simply verify at their stored cost.
13
17
  */
14
18
  declare class ScryptPasswordHasher implements PasswordHasher {
15
19
  private readonly params;
@@ -181,12 +185,19 @@ interface SessionStore {
181
185
  /** Returns null for unknown or expired sessions. */
182
186
  find(id: string): Promise<SessionRecord | null>;
183
187
  delete(id: string): Promise<boolean>;
188
+ /**
189
+ * Deletes every session for a user — fired on password reset so a reset logs
190
+ * out all of the user's active sessions, not just token-based clients.
191
+ * Optional so existing stores keep compiling; implement it to close the gap.
192
+ */
193
+ deleteAllForUser?(userId: string): Promise<void>;
184
194
  }
185
195
  declare class MemorySessionStore implements SessionStore {
186
196
  private readonly sessions;
187
197
  create(userId: string, ttlMs: number): Promise<SessionRecord>;
188
198
  find(id: string): Promise<SessionRecord | null>;
189
199
  delete(id: string): Promise<boolean>;
200
+ deleteAllForUser(userId: string): Promise<void>;
190
201
  }
191
202
  interface RefreshRecord {
192
203
  token: string;
@@ -339,6 +350,9 @@ declare class Auth {
339
350
  register(email: string, password: string): Promise<PublicUser>;
340
351
  /** Verifies credentials without side effects. Null on failure. */
341
352
  attempt(email: string, password: string): Promise<AuthUser | null>;
353
+ private dummyHashPromise?;
354
+ /** A valid hash of a throwaway secret, produced once by the configured hasher. */
355
+ private dummyHash;
342
356
  /**
343
357
  * Credentials → token pair. Emits auth:login / auth:login_failed. Locks the
344
358
  * account after too many failures (see {@link LoginThrottle}); a success
@@ -421,6 +435,9 @@ declare class Auth {
421
435
  verifyMfaCode(userId: string, code: string): Promise<boolean>;
422
436
  private generateRecoveryCode;
423
437
  private hashRecoveryCode;
438
+ /** SHA-256 of a bearer secret (one-time token, refresh token) — only this is
439
+ * persisted, so a leak of the token/session table can't be replayed. */
440
+ private hashToken;
424
441
  private issueOneTimeToken;
425
442
  private consumeToken;
426
443
  private updateUser;
package/dist/index.js CHANGED
@@ -2,14 +2,15 @@
2
2
  import { randomBytes, scrypt, timingSafeEqual } from "crypto";
3
3
  import { promisify } from "util";
4
4
  var scryptAsync = promisify(scrypt);
5
+ var MAXMEM = 512 * 1024 * 1024;
5
6
  var ScryptPasswordHasher = class {
6
- constructor(params = { N: 16384, r: 8, p: 1 }) {
7
+ constructor(params = { N: 65536, r: 8, p: 1 }) {
7
8
  this.params = params;
8
9
  }
9
10
  params;
10
11
  async hash(plain) {
11
12
  const salt = randomBytes(16);
12
- const derived = await scryptAsync(plain, salt, 32, this.params);
13
+ const derived = await scryptAsync(plain, salt, 32, { ...this.params, maxmem: MAXMEM });
13
14
  const { N, r, p } = this.params;
14
15
  return `scrypt$${N}$${r}$${p}$${salt.toString("base64url")}$${derived.toString("base64url")}`;
15
16
  }
@@ -20,7 +21,8 @@ var ScryptPasswordHasher = class {
20
21
  const derived = await scryptAsync(plain, Buffer.from(salt, "base64url"), 32, {
21
22
  N: Number(n),
22
23
  r: Number(r),
23
- p: Number(p)
24
+ p: Number(p),
25
+ maxmem: MAXMEM
24
26
  });
25
27
  const expectedBuffer = Buffer.from(expected, "base64url");
26
28
  return derived.length === expectedBuffer.length && timingSafeEqual(derived, expectedBuffer);
@@ -78,7 +80,8 @@ function verifyJwt(token, secret) {
78
80
  }
79
81
 
80
82
  // src/stores.ts
81
- import { randomBytes as randomBytes2, randomUUID } from "crypto";
83
+ import { createHash, randomBytes as randomBytes2, randomUUID } from "crypto";
84
+ var hashSessionId = (id) => createHash("sha256").update(id).digest("hex");
82
85
  var MemoryUserSource = class {
83
86
  users = /* @__PURE__ */ new Map();
84
87
  async findByEmail(email) {
@@ -168,25 +171,29 @@ var MemoryMfaStore = class {
168
171
  var MemorySessionStore = class {
169
172
  sessions = /* @__PURE__ */ new Map();
170
173
  async create(userId, ttlMs) {
171
- const record = {
172
- id: randomBytes2(32).toString("base64url"),
173
- userId,
174
- expiresAt: Date.now() + ttlMs
175
- };
176
- this.sessions.set(record.id, record);
177
- return record;
174
+ const rawId = randomBytes2(32).toString("base64url");
175
+ const hashed = hashSessionId(rawId);
176
+ const expiresAt = Date.now() + ttlMs;
177
+ this.sessions.set(hashed, { id: hashed, userId, expiresAt });
178
+ return { id: rawId, userId, expiresAt };
178
179
  }
179
180
  async find(id) {
180
- const record = this.sessions.get(id);
181
+ const hashed = hashSessionId(id);
182
+ const record = this.sessions.get(hashed);
181
183
  if (!record) return null;
182
184
  if (Date.now() >= record.expiresAt) {
183
- this.sessions.delete(id);
185
+ this.sessions.delete(hashed);
184
186
  return null;
185
187
  }
186
- return record;
188
+ return { id, userId: record.userId, expiresAt: record.expiresAt };
187
189
  }
188
190
  async delete(id) {
189
- return this.sessions.delete(id);
191
+ return this.sessions.delete(hashSessionId(id));
192
+ }
193
+ async deleteAllForUser(userId) {
194
+ for (const [key, record] of this.sessions) {
195
+ if (record.userId === userId) this.sessions.delete(key);
196
+ }
190
197
  }
191
198
  };
192
199
  var MemoryRefreshTokenStore = class {
@@ -214,7 +221,7 @@ var MemoryRefreshTokenStore = class {
214
221
  };
215
222
 
216
223
  // src/auth.ts
217
- import { createHash, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
224
+ import { createHash as createHash2, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
218
225
  import { BasaltError as BasaltError3, parseDuration as parseDuration2 } from "@basaltkit/core";
219
226
 
220
227
  // src/throttle.ts
@@ -454,9 +461,17 @@ var Auth = class {
454
461
  /** Verifies credentials without side effects. Null on failure. */
455
462
  async attempt(email, password) {
456
463
  const user = await this.users.findByEmail(email);
457
- if (!user) return null;
464
+ if (!user) {
465
+ await this.hasher.verify(password, await this.dummyHash());
466
+ return null;
467
+ }
458
468
  return await this.hasher.verify(password, user.passwordHash) ? user : null;
459
469
  }
470
+ dummyHashPromise;
471
+ /** A valid hash of a throwaway secret, produced once by the configured hasher. */
472
+ dummyHash() {
473
+ return this.dummyHashPromise ??= this.hasher.hash("basalt-timing-equalizer");
474
+ }
460
475
  /**
461
476
  * Credentials → token pair. Emits auth:login / auth:login_failed. Locks the
462
477
  * account after too many failures (see {@link LoginThrottle}); a success
@@ -494,19 +509,20 @@ var Auth = class {
494
509
  * (theft indicator), the whole family is revoked.
495
510
  */
496
511
  async refresh(refreshToken) {
497
- const record = await this.refreshTokens.find(refreshToken);
512
+ const hashed = this.hashToken(refreshToken);
513
+ const record = await this.refreshTokens.find(hashed);
498
514
  if (!record) throw new RefreshInvalidError();
499
515
  if (record.usedAt !== void 0) {
500
516
  await this.refreshTokens.revokeFamily(record.familyId);
501
517
  throw new RefreshReusedError();
502
518
  }
503
519
  if (Date.now() >= record.expiresAt) throw new RefreshInvalidError();
504
- await this.refreshTokens.markUsed(refreshToken);
520
+ await this.refreshTokens.markUsed(hashed);
505
521
  return this.issueTokens(record.userId, record.familyId);
506
522
  }
507
523
  /** Revokes a refresh family — logout for token-based clients. */
508
524
  async revoke(refreshToken) {
509
- const record = await this.refreshTokens.find(refreshToken);
525
+ const record = await this.refreshTokens.find(this.hashToken(refreshToken));
510
526
  if (record) await this.refreshTokens.revokeFamily(record.familyId);
511
527
  }
512
528
  verifyAccess(accessToken) {
@@ -571,6 +587,7 @@ var Auth = class {
571
587
  passwordHash: await this.hasher.hash(newPassword)
572
588
  });
573
589
  await this.refreshTokens.revokeAllForUser?.(user.id);
590
+ await this.sessions.deleteAllForUser?.(user.id);
574
591
  await this.hooks?.emit("auth:password_reset", { user: publicUser(user) });
575
592
  return publicUser(user);
576
593
  }
@@ -643,21 +660,32 @@ var Auth = class {
643
660
  return `${raw.slice(0, 5)}-${raw.slice(5)}`;
644
661
  }
645
662
  hashRecoveryCode(code) {
646
- return createHash("sha256").update(code.replace(/-/g, "").toLowerCase()).digest("hex");
663
+ return createHash2("sha256").update(code.replace(/-/g, "").toLowerCase()).digest("hex");
647
664
  }
648
665
  // --- token helpers -------------------------------------------------------
666
+ /** SHA-256 of a bearer secret (one-time token, refresh token) — only this is
667
+ * persisted, so a leak of the token/session table can't be replayed. */
668
+ hashToken(token) {
669
+ return createHash2("sha256").update(token).digest("hex");
670
+ }
649
671
  async issueOneTimeToken(userId, purpose, ttl) {
650
672
  await this.tokens.deleteForUser(userId, purpose);
651
673
  const token = randomBytes4(32).toString("base64url");
652
- await this.tokens.create({ token, userId, purpose, expiresAt: Date.now() + parseDuration2(ttl) });
674
+ await this.tokens.create({
675
+ token: this.hashToken(token),
676
+ userId,
677
+ purpose,
678
+ expiresAt: Date.now() + parseDuration2(ttl)
679
+ });
653
680
  return token;
654
681
  }
655
682
  async consumeToken(token, purpose) {
656
- const record = await this.tokens.find(token);
683
+ const hashed = this.hashToken(token);
684
+ const record = await this.tokens.find(hashed);
657
685
  if (!record || record.purpose !== purpose || record.usedAt !== void 0 || Date.now() >= record.expiresAt) {
658
686
  throw new AuthTokenInvalidError();
659
687
  }
660
- await this.tokens.markUsed(token);
688
+ await this.tokens.markUsed(hashed);
661
689
  return record;
662
690
  }
663
691
  async updateUser(id, patch) {
@@ -669,7 +697,8 @@ var Auth = class {
669
697
  async issueTokens(userId, familyId = randomUUID2()) {
670
698
  const refreshToken = randomBytes4(32).toString("base64url");
671
699
  await this.refreshTokens.create({
672
- token: refreshToken,
700
+ // Persist only the hash; the raw token is returned to the client below.
701
+ token: this.hashToken(refreshToken),
673
702
  familyId,
674
703
  userId,
675
704
  expiresAt: Date.now() + parseDuration2(this.refreshTtl)
@@ -716,7 +745,7 @@ function authPlugin(options) {
716
745
  }
717
746
 
718
747
  // src/apikeys.ts
719
- import { createHash as createHash2, randomBytes as randomBytes5, randomUUID as randomUUID3 } from "crypto";
748
+ import { createHash as createHash3, randomBytes as randomBytes5, randomUUID as randomUUID3 } from "crypto";
720
749
  import { BasaltError as BasaltError4 } from "@basaltkit/core";
721
750
  var ScopeRequiredError = class extends BasaltError4 {
722
751
  status = 403;
@@ -725,7 +754,7 @@ var ScopeRequiredError = class extends BasaltError4 {
725
754
  }
726
755
  };
727
756
  var KEY_PREFIX = "mk_live_";
728
- var hashKey = (key) => createHash2("sha256").update(key).digest("hex");
757
+ var hashKey = (key) => createHash3("sha256").update(key).digest("hex");
729
758
  var strip = (record) => {
730
759
  const { hash: _hash, ...info } = record;
731
760
  return info;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/auth",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Authentication for Basalt: password hashing, JWT with refresh rotation and reuse detection, sessions, ready-made /auth routes and route guards.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -15,7 +15,7 @@
15
15
  ],
16
16
  "dependencies": {
17
17
  "@basaltkit/core": "^1.0.0",
18
- "@basaltkit/fastify": "^1.0.0"
18
+ "@basaltkit/fastify": "^1.1.0"
19
19
  },
20
20
  "peerDependencies": {
21
21
  "zod": "^3.24.0 || ^4.0.0"