@basaltkit/auth 5.0.0 → 5.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/README.md CHANGED
@@ -212,6 +212,20 @@ await auth.revoke(renewed.refreshToken) // logout: invalidates the token family
212
212
 
213
213
  A request with no credentials stays anonymous (no error); an explicit invalid token returns 401.
214
214
 
215
+ ### Custom token claims and tenant-bound tokens
216
+
217
+ `tokenClaims` adds your own claims to every access token (login, MFA completion, social login, every refresh — re-derived on each refresh); `verifyClaims` (plugin) checks them on each bearer request, before the user lookup — `false` answers `401 AUTH_TOKEN_CLAIMS_REJECTED`. Reserved names (`sub`, `tv`, `amr`, `iat`, `exp`, `nbf`, `iss`, `aud`, `jti`) fail the sign-in with `AUTH_TOKEN_CLAIM_RESERVED`.
218
+
219
+ With schema-per-tenant and one secret, a token is otherwise kept out of another tenant only because its `sub` is missing there. `tenantBoundTokens()` binds it to its plane: tokens carry `tid` (the `ctx().tenant` id, `null` on the central plane) and are refused wherever the resolved tenant differs. Auth reads `ctx().tenant` structurally — no dependency on `@basaltkit/tenancy`; register `tenancyPlugin` first.
220
+
221
+ ```ts
222
+ import { authPlugin, tenantBoundTokens } from '@basaltkit/auth'
223
+
224
+ authPlugin({ users, secret, ...tenantBoundTokens() })
225
+ // or with claims of your own:
226
+ authPlugin({ users, secret, ...tenantBoundTokens({ tokenClaims: (user) => ({ org: orgOf(user) }) }) })
227
+ ```
228
+
215
229
  ### Password recovery
216
230
 
217
231
  The flow has two steps. The module generates a **single-use token** (valid for 1 hour by default) and emits a hook — your application sends the email with the link:
@@ -614,6 +628,8 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
614
628
  | `mfaEncryptionKey` | `string \| Buffer` | No | — | Shorthand for a one-key ring (`id: 'default'`, ≥ 32 bytes). |
615
629
  | `mfaIssuer` | `string` | No | `'Basalt'` | Name shown in the authenticator app. |
616
630
  | `registerPolicy` | `RegisterPolicy` (`({ email, tenantId? }) => boolean \| Promise<boolean>`) | No | — (open) | Who may create a NEW account through `POST /auth/register` (refusal = same `202`, `auth:register_refused`) and the create branch of `socialLogin` (refusal = `RegistrationClosedError`). Logins into existing accounts and `register()` are never gated. `@basaltkit/teams`' `teamsInviteGate(teams)` = invite-only on tenant hosts. |
631
+ | `tokenClaims` | `(user, { reason, amr?, request? }) => Record<string, unknown> \| Promise<…>` | No | — | Extra access-token claims on every sign-in and refresh (re-derived). Reserved names throw `ReservedTokenClaimError`. |
632
+ | `verifyClaims` | `(claims, context) => boolean \| Promise<boolean>` | No | — | Plugin only. Checks a bearer token's claims before the user lookup; `false` → `401 AUTH_TOKEN_CLAIMS_REJECTED`. `tenantBoundTokens()` supplies it with `tokenClaims`. |
617
633
  | `hooks` | `HookBus` | No | — | Only on the `Auth` class; the plugin injects it. |
618
634
 
619
635
  `Auth` class methods:
package/dist/auth.d.ts CHANGED
@@ -2,6 +2,7 @@ import { BasaltError, type DurationInput, type HookBus } from '@basaltkit/core';
2
2
  import { type PasswordHasher } from './hashing.js';
3
3
  import { LoginThrottle, type ThrottleStore } from './throttle.js';
4
4
  import { type JwtClaims } from './jwt.js';
5
+ import { type TokenClaimsFn } from './token-claims.js';
5
6
  import { type SecretBoxKey, type SecretBoxLegacyOptions } from './secret-box.js';
6
7
  import { type AccountLinkStore, type AuthTokenStore, type AuthUser, type MfaStore, type PublicUser, type RefreshTokenStore, type SessionRecord, type SessionStore, type TokenVersionStore, type UserSource } from './stores.js';
7
8
  export declare class InvalidCredentialsError extends BasaltError {
@@ -303,6 +304,16 @@ export interface AuthOptions {
303
304
  mfaEncryptionKey?: string | Buffer;
304
305
  /** Issuer name shown in authenticator apps. Default 'Basalt'. */
305
306
  mfaIssuer?: string;
307
+ /**
308
+ * Extra claims for every access token: login, MFA completion (login /
309
+ * social login with a code), social login and every refresh — re-derived on
310
+ * each refresh, so a rotated token keeps them. Reserved names
311
+ * ({@link RESERVED_TOKEN_CLAIMS}: `sub`, `tv`, `amr`, `exp`, `iat`, …) throw
312
+ * `AUTH_TOKEN_CLAIM_RESERVED`. Check them on the request path with
313
+ * `authPlugin({ verifyClaims })`; `tenantBoundTokens()` is the ready-made
314
+ * tenant binding. Default: none (tokens carry only `sub`, `tv`, `amr`).
315
+ */
316
+ tokenClaims?: TokenClaimsFn;
306
317
  }
307
318
  export declare const publicUser: (user: AuthUser) => PublicUser;
308
319
  export declare class Auth {
@@ -331,6 +342,7 @@ export declare class Auth {
331
342
  private readonly tokenVersions;
332
343
  private readonly enumerationSafeRegister;
333
344
  private readonly registerPolicy;
345
+ private readonly tokenClaims;
334
346
  constructor(options: AuthOptions);
335
347
  /**
336
348
  * Trusted, server-side account creation (seeding, a back-office, a flow that
@@ -619,5 +631,7 @@ export declare class Auth {
619
631
  private issueOneTimeToken;
620
632
  private consumeToken;
621
633
  private updateUser;
634
+ /** The app's {@link AuthOptions.tokenClaims} for this sign-in, validated. */
635
+ private customClaims;
622
636
  private issueTokens;
623
637
  }
package/dist/auth.js CHANGED
@@ -3,6 +3,7 @@ import { BasaltError, isProductionEnvironment, parseDuration, tryCtx } from '@ba
3
3
  import { ScryptPasswordHasher } from './hashing.js';
4
4
  import { LoginThrottle } from './throttle.js';
5
5
  import { signJwt, verifyJwt } from './jwt.js';
6
+ import { checkCustomClaims } from './token-claims.js';
6
7
  import { generateTotpSecret, matchTotpStep, otpauthUri } from './totp.js';
7
8
  import { SecretBox, SecretBoxKeyError } from './secret-box.js';
8
9
  import { MemoryAccountLinkStore, MemoryAuthTokenStore, MemoryMfaStore, MemoryRefreshTokenStore, MemorySessionStore, } from './stores.js';
@@ -326,6 +327,7 @@ export class Auth {
326
327
  tokenVersions;
327
328
  enumerationSafeRegister;
328
329
  registerPolicy;
330
+ tokenClaims;
329
331
  constructor(options) {
330
332
  this.users = options.users;
331
333
  this.secret = options.secret;
@@ -379,6 +381,7 @@ export class Auth {
379
381
  this.tokenVersions = options.tokenVersions;
380
382
  this.enumerationSafeRegister = options.enumerationSafeRegister ?? true;
381
383
  this.registerPolicy = options.registerPolicy;
384
+ this.tokenClaims = options.tokenClaims;
382
385
  }
383
386
  /**
384
387
  * Trusted, server-side account creation (seeding, a back-office, a flow that
@@ -548,7 +551,8 @@ export class Auth {
548
551
  amr.push('mfa');
549
552
  }
550
553
  async finishSocialLogin(user, created, amr) {
551
- const tokens = await this.issueTokens(user.id, undefined, amr);
554
+ const claims = await this.customClaims(user, 'social', amr);
555
+ const tokens = await this.issueTokens(user.id, undefined, amr, claims);
552
556
  await this.hooks?.emit('auth:login', { user: publicUser(user) });
553
557
  return { user: publicUser(user), tokens, created, amr };
554
558
  }
@@ -694,10 +698,12 @@ export class Auth {
694
698
  }
695
699
  amr.push('mfa');
696
700
  }
701
+ // Before the throttle is reset: a throwing tokenClaims fails the login closed.
702
+ const claims = await this.customClaims(user, 'login', amr);
697
703
  await this.throttle?.reset(key);
698
704
  if (ipKey)
699
705
  await this.ipThrottle?.release(ipKey);
700
- const tokens = await this.issueTokens(user.id, undefined, amr);
706
+ const tokens = await this.issueTokens(user.id, undefined, amr, claims);
701
707
  await this.hooks?.emit('auth:login', { user: publicUser(user) });
702
708
  return { user: publicUser(user), tokens, amr };
703
709
  }
@@ -716,16 +722,21 @@ export class Auth {
716
722
  if (Date.now() >= record.expiresAt)
717
723
  throw new RefreshInvalidError();
718
724
  // A deleted account must not keep minting tokens from a leftover refresh token.
719
- if (!(await this.users.findById(record.userId))) {
725
+ const user = await this.users.findById(record.userId);
726
+ if (!user) {
720
727
  await this.refreshTokens.revokeFamily(record.familyId);
721
728
  throw new RefreshInvalidError();
722
729
  }
730
+ const amr = amrOfFamily(record.familyId);
731
+ // Re-derived before the token is consumed: a throwing tokenClaims leaves
732
+ // the refresh token usable rather than burning the client's session.
733
+ const claims = await this.customClaims(user, 'refresh', amr);
723
734
  // Compare-and-swap: `false` means another caller consumed this exact token
724
735
  // between our read and this write — the very race reuse detection exists for.
725
736
  if ((await this.refreshTokens.markUsed(hashed)) === false) {
726
737
  return this.reuseDetected(record.userId, record.familyId);
727
738
  }
728
- const pair = await this.issueTokens(record.userId, record.familyId, amrOfFamily(record.familyId));
739
+ const pair = await this.issueTokens(record.userId, record.familyId, amr, claims);
729
740
  // The consumed token is the witness that the family is still alive:
730
741
  // revokeFamily/revokeAllForUser delete every row of it. If a concurrent
731
742
  // revocation (a reuse loser, a logout, a logout-everywhere) ran between our
@@ -1131,7 +1142,19 @@ export class Auth {
1131
1142
  throw new AuthTokenInvalidError(); // user vanished between issue and consume
1132
1143
  return user;
1133
1144
  }
1134
- async issueTokens(userId, family, amr) {
1145
+ /** The app's {@link AuthOptions.tokenClaims} for this sign-in, validated. */
1146
+ async customClaims(user, reason, amr) {
1147
+ if (!this.tokenClaims)
1148
+ return {};
1149
+ const request = tryCtx();
1150
+ const claims = await this.tokenClaims(publicUser(user), {
1151
+ reason,
1152
+ ...(amr && isAmr(amr) ? { amr: [...amr] } : {}),
1153
+ ...(request !== undefined ? { request } : {}),
1154
+ });
1155
+ return checkCustomClaims(claims);
1156
+ }
1157
+ async issueTokens(userId, family, amr, claims = {}) {
1135
1158
  // A new family records the login's authentication methods in its id, so
1136
1159
  // every rotation carries them forward without a store schema change.
1137
1160
  const familyId = family ?? (amr && isAmr(amr) ? `${randomUUID()}.${amr.join('+')}` : randomUUID());
@@ -1145,7 +1168,7 @@ export class Auth {
1145
1168
  });
1146
1169
  const tv = this.tokenVersions ? await this.tokenVersions.get(userId) : undefined;
1147
1170
  return {
1148
- accessToken: signJwt({ sub: userId, ...(tv !== undefined ? { tv } : {}), ...(amr && isAmr(amr) ? { amr } : {}) }, { secret: this.secret, expiresIn: this.accessTtl }),
1171
+ accessToken: signJwt({ ...claims, sub: userId, ...(tv !== undefined ? { tv } : {}), ...(amr && isAmr(amr) ? { amr } : {}) }, { secret: this.secret, expiresIn: this.accessTtl }),
1149
1172
  refreshToken,
1150
1173
  };
1151
1174
  }
package/dist/index.d.ts CHANGED
@@ -22,6 +22,7 @@ export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecr
22
22
  export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, type TotpOptions, type VerifyTotpOptions, type OtpauthUriInput, } from './totp.js';
23
23
  export { SecretBox, SecretBoxKeyError, SecretUnreadableError, type SecretBoxKey, type SecretBoxOptions, type SecretBoxLegacyOptions, type SecretContext, } from './secret-box.js';
24
24
  export { authPlugin, AUTH, CsrfRejectedError, type AuthPluginOptions, type CsrfOptions } from './plugin.js';
25
+ export { tenantBoundTokens, RESERVED_TOKEN_CLAIMS, ReservedTokenClaimError, TokenClaimsRejectedError, type TenantBoundTokensOptions, type TokenClaimsContext, type TokenClaimsFn, type TokenClaimsReason, type VerifyClaimsFn, } from './token-claims.js';
25
26
  export { ApiKeys, ApiKeyExpirationError, ApiKeyOptionsError, ApiKeyNotFoundError, ApiKeyInputError, ApiKeyConflictError, ApiKeyStoreUnsupportedError, ApiKeyIpNotAllowedError, DEFAULT_API_KEY_TOUCH_EVERY_MS, MAX_API_KEY_ROTATION_GRACE_MS, API_KEY_ALLOWED_IPS_MAX, API_KEY_META_LIMITS, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type UpdateApiKeyInput, type RotateApiKeyOptions, type ListApiKeysOptions, type AuthenticateApiKeyOptions, type ApiKeyAuthResult, type ApiKeyUpdatedField, type ApiKeyContext, } from './apikeys.js';
26
27
  export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, ApiKeyAmbiguousError, ApiKeyInvalidError, type ApiKeysPluginOptions, } from './apikeys-plugin.js';
27
28
  export { authRoutes, apiKeyRoutes, mfaRoutes, DEFAULT_AUTH_RATE_LIMIT, ACCOUNT_META, MAX_EMAIL_LENGTH, MAX_PASSWORD_LENGTH, type AuthRoutesOptions, type PasswordPolicy, type RegisterOption, } from './routes.js';
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecr
5
5
  export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, } from './totp.js';
6
6
  export { SecretBox, SecretBoxKeyError, SecretUnreadableError, } from './secret-box.js';
7
7
  export { authPlugin, AUTH, CsrfRejectedError } from './plugin.js';
8
+ export { tenantBoundTokens, RESERVED_TOKEN_CLAIMS, ReservedTokenClaimError, TokenClaimsRejectedError, } from './token-claims.js';
8
9
  export { ApiKeys, ApiKeyExpirationError, ApiKeyOptionsError, ApiKeyNotFoundError, ApiKeyInputError, ApiKeyConflictError, ApiKeyStoreUnsupportedError, ApiKeyIpNotAllowedError, DEFAULT_API_KEY_TOUCH_EVERY_MS, MAX_API_KEY_ROTATION_GRACE_MS, API_KEY_ALLOWED_IPS_MAX, API_KEY_META_LIMITS, ScopeRequiredError, scopesSatisfy, } from './apikeys.js';
9
10
  export { apiKeysPlugin, API_KEYS, ApiKeyTenantMismatchError, ApiKeyNotAllowedError, ApiKeyAmbiguousError, ApiKeyInvalidError, } from './apikeys-plugin.js';
10
11
  export { authRoutes, apiKeyRoutes, mfaRoutes, DEFAULT_AUTH_RATE_LIMIT, ACCOUNT_META, MAX_EMAIL_LENGTH, MAX_PASSWORD_LENGTH, } from './routes.js';
package/dist/plugin.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { BasaltError, type RequestContext } from '@basaltkit/core';
2
2
  import { Auth, type AuthOptions } from './auth.js';
3
3
  import type { PublicUser } from './stores.js';
4
+ import { type VerifyClaimsFn } from './token-claims.js';
4
5
  declare module '@basaltkit/core' {
5
6
  interface RequestContext {
6
7
  /** The authenticated user of the current request, set by auth. */
@@ -138,6 +139,15 @@ export interface AuthPluginOptions extends Omit<AuthOptions, 'hooks'> {
138
139
  * requires MFA on a single route (step-up). Default: off.
139
140
  */
140
141
  requireMfa?: boolean | ((user: PublicUser, context: RequestContext) => boolean | Promise<boolean>);
142
+ /**
143
+ * Checks the claims of every bearer access token on the request it
144
+ * authenticates, after the signature, expiry and token version passed and
145
+ * before the user is looked up. `false` refuses the request (a throw fails it):
146
+ * 401 `AUTH_TOKEN_CLAIMS_REJECTED`. Pair it with `tokenClaims`;
147
+ * `tenantBoundTokens()` gives both for a tenant binding. Sessions and API
148
+ * keys are not tokens and are not passed here. Default: none.
149
+ */
150
+ verifyClaims?: VerifyClaimsFn;
141
151
  }
142
152
  /**
143
153
  * Whether the request's session cookie failed the CSRF check (so it must not
package/dist/plugin.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { BasaltError, createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
2
2
  import { Auth, AuthRequiredError, isAmr, MfaEnrollmentRequiredError, MfaStepUpRequiredError, } from './auth.js';
3
3
  import { assertSessionOptions, publicUser } from './auth.js';
4
+ import { TokenClaimsRejectedError } from './token-claims.js';
4
5
  export const AUTH = createToken('auth');
5
6
  /** A cookie-authenticated, state-changing request came from another origin. */
6
7
  export class CsrfRejectedError extends BasaltError {
@@ -56,7 +57,7 @@ const csrfRejected = new WeakSet();
56
57
  */
57
58
  export const isCsrfRejected = (context) => csrfRejected.has(context);
58
59
  export function authPlugin(pluginOptions) {
59
- const { csrf, requireMfa, ...options } = pluginOptions;
60
+ const { csrf, requireMfa, verifyClaims, ...options } = pluginOptions;
60
61
  const trustedOrigins = new Set((csrf ? (csrf.trustedOrigins ?? []) : []).map((o) => originOf(o)).filter((o) => o !== null));
61
62
  return definePlugin({
62
63
  name: 'basalt:auth',
@@ -86,6 +87,10 @@ export function authPlugin(pluginOptions) {
86
87
  // `mk_`-prefixed bearers are API keys — left to apiKeysPlugin.
87
88
  if (bearer && !bearer.startsWith('mk_')) {
88
89
  const claims = await auth.verifyAccessToken(bearer);
90
+ // Before the lookup: a token from another plane must not resolve
91
+ // whatever user happens to share its `sub` there.
92
+ if (verifyClaims && (await verifyClaims(claims, context)) !== true)
93
+ throw new TokenClaimsRejectedError();
89
94
  const user = await auth.users.findById(claims.sub);
90
95
  if (user) {
91
96
  context.user = publicUser(user);
@@ -0,0 +1,75 @@
1
+ import { BasaltError, type RequestContext } from '@basaltkit/core';
2
+ import type { JwtClaims } from './jwt.js';
3
+ import type { PublicUser } from './stores.js';
4
+ /**
5
+ * Claim names Basalt owns in an access token. A {@link TokenClaimsFn} that
6
+ * returns one of them fails the sign-in with {@link ReservedTokenClaimError}:
7
+ * a custom claim must never overwrite the subject, the expiry, the token
8
+ * version or the authentication methods.
9
+ */
10
+ export declare const RESERVED_TOKEN_CLAIMS: readonly string[];
11
+ /** Why an access token is being signed. */
12
+ export type TokenClaimsReason = 'login' | 'social' | 'refresh';
13
+ export interface TokenClaimsContext {
14
+ /** `login` (password, with or without MFA), `social` (OAuth / SSO) or `refresh` (rotation). */
15
+ reason: TokenClaimsReason;
16
+ /** Authentication methods of the credential (`pwd`, `fed`, `mfa`), when known. */
17
+ amr?: string[];
18
+ /** The ambient context (`ctx()`), absent outside a request / `runWithContext`. */
19
+ request?: RequestContext;
20
+ }
21
+ /**
22
+ * Extra claims for every access token Auth signs — login, social login, MFA
23
+ * completion and every refresh. Called again on each refresh (the claims are
24
+ * re-derived, not copied), so a refreshed token carries the same claims as
25
+ * long as the inputs (the user, the context) are the same. Throwing fails the
26
+ * sign-in (fail closed). Returned values must be JSON-serialisable.
27
+ */
28
+ export type TokenClaimsFn = (user: PublicUser, context: TokenClaimsContext) => Record<string, unknown> | Promise<Record<string, unknown>>;
29
+ /**
30
+ * Checks a verified access token's claims on the request it authenticates.
31
+ * `false` refuses the token with 401 {@link TokenClaimsRejectedError}.
32
+ * Runs before the user lookup, so a refused token never reads its `sub`.
33
+ */
34
+ export type VerifyClaimsFn = (claims: JwtClaims, context: RequestContext) => boolean | Promise<boolean>;
35
+ /** A {@link TokenClaimsFn} returned a claim Basalt reserves (a bug in the app, 500). */
36
+ export declare class ReservedTokenClaimError extends BasaltError {
37
+ readonly status = 500;
38
+ constructor(claim: string);
39
+ }
40
+ /** A signed, unexpired access token whose claims `verifyClaims` refused. */
41
+ export declare class TokenClaimsRejectedError extends BasaltError {
42
+ readonly status = 401;
43
+ constructor();
44
+ }
45
+ /** Validates what a {@link TokenClaimsFn} returned. Internal to the package. */
46
+ export declare function checkCustomClaims(claims: unknown): Record<string, unknown>;
47
+ export interface TenantBoundTokensOptions {
48
+ /** The claim that carries the tenant id. Default `tid`. Must not be reserved. */
49
+ claim?: string;
50
+ /** More claims of the app's own, merged with the tenant claim. */
51
+ tokenClaims?: TokenClaimsFn;
52
+ /** A further check of the app's own, run after the tenant check passed. */
53
+ verifyClaims?: VerifyClaimsFn;
54
+ }
55
+ /**
56
+ * Binds access tokens to the plane they were issued on. Spread the result into
57
+ * `authPlugin({ ...tenantBoundTokens() })`:
58
+ *
59
+ * - every access token carries `tid` — the tenant of the context it was
60
+ * issued in (`ctx().tenant.id`, set by `@basaltkit/tenancy`), or `null` on
61
+ * the central plane;
62
+ * - a bearer token is accepted only where `tid` equals the tenant resolved for
63
+ * the request (`null` = no tenant). Anywhere else — another tenant, the apex,
64
+ * a token issued before the binding (no `tid`) — it is a 401
65
+ * `AUTH_TOKEN_CLAIMS_REJECTED`, whatever user ids the target plane holds.
66
+ *
67
+ * Works with any tenancy that puts `{ id }` on `ctx().tenant`; auth does not
68
+ * depend on `@basaltkit/tenancy`. Register `tenancyPlugin` before `authPlugin`
69
+ * so the tenant is resolved when the token is checked. Sessions and API keys
70
+ * are unaffected (they are looked up in the plane's own store).
71
+ */
72
+ export declare function tenantBoundTokens(options?: TenantBoundTokensOptions): {
73
+ tokenClaims: TokenClaimsFn;
74
+ verifyClaims: VerifyClaimsFn;
75
+ };
@@ -0,0 +1,83 @@
1
+ import { BasaltError } from '@basaltkit/core';
2
+ /**
3
+ * Claim names Basalt owns in an access token. A {@link TokenClaimsFn} that
4
+ * returns one of them fails the sign-in with {@link ReservedTokenClaimError}:
5
+ * a custom claim must never overwrite the subject, the expiry, the token
6
+ * version or the authentication methods.
7
+ */
8
+ export const RESERVED_TOKEN_CLAIMS = Object.freeze([
9
+ 'sub',
10
+ 'tv',
11
+ 'amr',
12
+ 'iat',
13
+ 'exp',
14
+ 'nbf',
15
+ 'iss',
16
+ 'aud',
17
+ 'jti',
18
+ ]);
19
+ /** A {@link TokenClaimsFn} returned a claim Basalt reserves (a bug in the app, 500). */
20
+ export class ReservedTokenClaimError extends BasaltError {
21
+ status = 500;
22
+ constructor(claim) {
23
+ super('AUTH_TOKEN_CLAIM_RESERVED', `The access-token claim "${claim}" is reserved and cannot be set by tokenClaims.`);
24
+ }
25
+ }
26
+ /** A signed, unexpired access token whose claims `verifyClaims` refused. */
27
+ export class TokenClaimsRejectedError extends BasaltError {
28
+ status = 401;
29
+ constructor() {
30
+ super('AUTH_TOKEN_CLAIMS_REJECTED', 'The token is not valid here.');
31
+ }
32
+ }
33
+ /** Validates what a {@link TokenClaimsFn} returned. Internal to the package. */
34
+ export function checkCustomClaims(claims) {
35
+ if (claims === null || typeof claims !== 'object' || Array.isArray(claims)) {
36
+ throw new TypeError('tokenClaims must return a plain object of claims.');
37
+ }
38
+ for (const name of Object.keys(claims)) {
39
+ if (RESERVED_TOKEN_CLAIMS.includes(name))
40
+ throw new ReservedTokenClaimError(name);
41
+ }
42
+ return claims;
43
+ }
44
+ /** The tenant id of a context, read structurally (auth never imports tenancy). */
45
+ const tenantIdOf = (context) => {
46
+ const id = context?.tenant?.id;
47
+ return typeof id === 'string' && id !== '' ? id : null;
48
+ };
49
+ /**
50
+ * Binds access tokens to the plane they were issued on. Spread the result into
51
+ * `authPlugin({ ...tenantBoundTokens() })`:
52
+ *
53
+ * - every access token carries `tid` — the tenant of the context it was
54
+ * issued in (`ctx().tenant.id`, set by `@basaltkit/tenancy`), or `null` on
55
+ * the central plane;
56
+ * - a bearer token is accepted only where `tid` equals the tenant resolved for
57
+ * the request (`null` = no tenant). Anywhere else — another tenant, the apex,
58
+ * a token issued before the binding (no `tid`) — it is a 401
59
+ * `AUTH_TOKEN_CLAIMS_REJECTED`, whatever user ids the target plane holds.
60
+ *
61
+ * Works with any tenancy that puts `{ id }` on `ctx().tenant`; auth does not
62
+ * depend on `@basaltkit/tenancy`. Register `tenancyPlugin` before `authPlugin`
63
+ * so the tenant is resolved when the token is checked. Sessions and API keys
64
+ * are unaffected (they are looked up in the plane's own store).
65
+ */
66
+ export function tenantBoundTokens(options = {}) {
67
+ const claim = options.claim ?? 'tid';
68
+ if (claim === '' || RESERVED_TOKEN_CLAIMS.includes(claim))
69
+ throw new ReservedTokenClaimError(claim);
70
+ const extra = options.tokenClaims;
71
+ const verify = options.verifyClaims;
72
+ return {
73
+ async tokenClaims(user, context) {
74
+ const own = extra ? checkCustomClaims(await extra(user, context)) : {};
75
+ return { ...own, [claim]: tenantIdOf(context.request) };
76
+ },
77
+ async verifyClaims(claims, context) {
78
+ if (claims[claim] !== tenantIdOf(context))
79
+ return false;
80
+ return verify ? (await verify(claims, context)) === true : true;
81
+ },
82
+ };
83
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/auth",
3
- "version": "5.0.0",
3
+ "version": "5.1.0",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },
@@ -18,17 +18,17 @@
18
18
  "dist"
19
19
  ],
20
20
  "dependencies": {
21
- "@basaltkit/http": "^3.0.0",
22
- "@basaltkit/core": "^1.6.0"
21
+ "@basaltkit/core": "^1.6.0",
22
+ "@basaltkit/http": "^3.0.1"
23
23
  },
24
24
  "peerDependencies": {
25
25
  "zod": "^4.0.0"
26
26
  },
27
27
  "devDependencies": {
28
- "@types/node": "^26.6.1",
28
+ "@types/node": "^26.6.5",
29
29
  "typescript": "^7.0.2",
30
- "vitest": "^5.0.1",
31
- "zod": "^4.6.5",
30
+ "vitest": "^5.0.5",
31
+ "zod": "^4.6.7",
32
32
  "@basaltkit/fastify": "^3.0.0",
33
33
  "@basaltkit/tsconfig": "^0.24.0"
34
34
  },