@basaltkit/auth 1.0.0 → 1.1.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,8 @@ 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 one-time token — only this is persisted, never the raw value. */
439
+ private hashOneTimeToken;
424
440
  private issueOneTimeToken;
425
441
  private consumeToken;
426
442
  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);
@@ -188,6 +190,11 @@ var MemorySessionStore = class {
188
190
  async delete(id) {
189
191
  return this.sessions.delete(id);
190
192
  }
193
+ async deleteAllForUser(userId) {
194
+ for (const [id, record] of this.sessions) {
195
+ if (record.userId === userId) this.sessions.delete(id);
196
+ }
197
+ }
191
198
  };
192
199
  var MemoryRefreshTokenStore = class {
193
200
  records = /* @__PURE__ */ new Map();
@@ -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
@@ -571,6 +586,7 @@ var Auth = class {
571
586
  passwordHash: await this.hasher.hash(newPassword)
572
587
  });
573
588
  await this.refreshTokens.revokeAllForUser?.(user.id);
589
+ await this.sessions.deleteAllForUser?.(user.id);
574
590
  await this.hooks?.emit("auth:password_reset", { user: publicUser(user) });
575
591
  return publicUser(user);
576
592
  }
@@ -646,18 +662,28 @@ var Auth = class {
646
662
  return createHash("sha256").update(code.replace(/-/g, "").toLowerCase()).digest("hex");
647
663
  }
648
664
  // --- token helpers -------------------------------------------------------
665
+ /** SHA-256 of a one-time token — only this is persisted, never the raw value. */
666
+ hashOneTimeToken(token) {
667
+ return createHash("sha256").update(token).digest("hex");
668
+ }
649
669
  async issueOneTimeToken(userId, purpose, ttl) {
650
670
  await this.tokens.deleteForUser(userId, purpose);
651
671
  const token = randomBytes4(32).toString("base64url");
652
- await this.tokens.create({ token, userId, purpose, expiresAt: Date.now() + parseDuration2(ttl) });
672
+ await this.tokens.create({
673
+ token: this.hashOneTimeToken(token),
674
+ userId,
675
+ purpose,
676
+ expiresAt: Date.now() + parseDuration2(ttl)
677
+ });
653
678
  return token;
654
679
  }
655
680
  async consumeToken(token, purpose) {
656
- const record = await this.tokens.find(token);
681
+ const hashed = this.hashOneTimeToken(token);
682
+ const record = await this.tokens.find(hashed);
657
683
  if (!record || record.purpose !== purpose || record.usedAt !== void 0 || Date.now() >= record.expiresAt) {
658
684
  throw new AuthTokenInvalidError();
659
685
  }
660
- await this.tokens.markUsed(token);
686
+ await this.tokens.markUsed(hashed);
661
687
  return record;
662
688
  }
663
689
  async updateUser(id, patch) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/auth",
3
- "version": "1.0.0",
3
+ "version": "1.1.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"