@dunx/auth 0.1.0 → 0.1.1

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
@@ -1,13 +1,13 @@
1
1
  # @dunx/auth
2
2
 
3
3
  [Better Auth](https://better-auth.com) for dunx. **This package is not an
4
- authentication system** better-auth is, and it is very good at it. This is the
4
+ authentication system** - better-auth is, and it is very good at it. This is the
5
5
  wiring: a module that builds the instance from your `ConfigService`, five routes that
6
6
  mount its handler, a guard that composes with the `@Public()` and `@Roles()` metadata
7
7
  `@dunx/http` already carries, and two adapters that let it drive Bun's own APIs.
8
8
 
9
9
  `better-auth` is a **required peer dependency**. Install it yourself and own its
10
- version dunx does not bundle it but it is not optional, because this package
10
+ version - dunx does not bundle it - but it is not optional, because this package
11
11
  imports `betterAuth` as a value and cannot load without it. Marking it optional would
12
12
  trade an install-time warning for a module-resolution crash.
13
13
 
@@ -15,7 +15,7 @@ trade an install-time warning for a module-resolution crash.
15
15
  bun add @dunx/auth better-auth
16
16
  ```
17
17
 
18
- `drizzle-orm` **is** an optional peer, needed only by `@dunx/auth/drizzle` which is
18
+ `drizzle-orm` **is** an optional peer, needed only by `@dunx/auth/drizzle` - which is
19
19
  its own subpath precisely so that a Prisma, Kysely or MongoDB app never loads it.
20
20
  `dist/index.js` contains no reference to drizzle, which is the test a peer has to
21
21
  pass to be called optional.
@@ -33,7 +33,7 @@ documentation is the documentation.
33
33
  | `Auth` | The injection token for the better-auth instance |
34
34
  | `SessionGuard` | Middleware: authenticates, then reads `@Public()` and `@Roles()` |
35
35
  | `AuthContext` | The authenticated caller, reachable from any service in the request |
36
- | `Principal` | `{ session, user }` better-auth's own inferred session type |
36
+ | `Principal` | `{ session, user }` - better-auth's own inferred session type |
37
37
  | `bunPassword` | `Bun.password` bcrypt in place of better-auth's JavaScript scrypt |
38
38
  | `redisStorage` | `secondaryStorage` over `Bun.RedisClient` |
39
39
  | `drizzleDatabase` | `database` over the drizzle handle `@dunx/infra/db` already opened |
@@ -71,7 +71,7 @@ for when the secret is not behind config.
71
71
 
72
72
  `forRootAsync` exists for the one reason it exists on `LoggerModule`, `DbModule` and
73
73
  the rest: a zero-argument function cannot read `ConfigService`. It is not a second
74
- mechanism dunx settles every async factory before the first constructor runs, so
74
+ mechanism - dunx settles every async factory before the first constructor runs, so
75
75
  the instance is built and the connection handshaked before anything can ask for
76
76
  either.
77
77
 
@@ -85,7 +85,7 @@ bunx @better-auth/cli generate
85
85
  ```
86
86
 
87
87
  Put the result in the schema object you already hand `@dunx/infra/db`, and
88
- `drizzleDatabase(connection)` needs no schema argument `@dunx/infra/db` builds its
88
+ `drizzleDatabase(connection)` needs no schema argument - `@dunx/infra/db` builds its
89
89
  handle with `drizzle({ client, schema })`, and better-auth's adapter reads
90
90
  `db._.fullSchema` off it. `examples/full/src/database/auth.schema.ts` is a
91
91
  generated schema in place.
@@ -96,7 +96,7 @@ the library that reads them.
96
96
  ## Mounting
97
97
 
98
98
  `AuthHandler` puts better-auth's `(request: Request) => Promise<Response>` behind five
99
- wildcard routes `GET`, `POST`, `PUT`, `PATCH` and `DELETE` at `<basePath>/*`.
99
+ wildcard routes - `GET`, `POST`, `PUT`, `PATCH` and `DELETE` at `<basePath>/*`.
100
100
  `Bun.serve` matches a wildcard natively, so **Bun is still the router**: dunx does not
101
101
  restate, wrap or re-dispatch a single better-auth endpoint, and the `Response` comes
102
102
  back untouched, `Set-Cookie` headers and redirects included.
@@ -121,10 +121,10 @@ paths, rather than better-auth quietly answering 404 to everything.
121
121
  ## The guard
122
122
 
123
123
  ```ts
124
- // Global every route needs a session unless it says otherwise.
124
+ // Global - every route needs a session unless it says otherwise.
125
125
  HttpFactory.create(root, { middleware: [SessionGuard] });
126
126
 
127
- // or scoped this controller needs one, nothing else does.
127
+ // or scoped - this controller needs one, nothing else does.
128
128
  @UseGuards(SessionGuard)
129
129
  @Controller('profile')
130
130
  class ProfileController {}
@@ -135,10 +135,10 @@ session through better-auth's own `api.getSession`, so a cookie and the `bearer`
135
135
  plugin's `Authorization: Bearer <token>` both work, and then reads the metadata
136
136
  `@dunx/http` already had:
137
137
 
138
- - **`@Public()`** skipped outright. No session lookup, no rejection, no role check.
138
+ - **`@Public()`** - skipped outright. No session lookup, no rejection, no role check.
139
139
  That is what makes the guard safe to install globally: `AuthHandler` is `@Public()`,
140
140
  and a sign-in endpoint that required a session could never be reached.
141
- - **`@Roles('admin', 'editor')`** a 403 unless the caller holds one of them.
141
+ - **`@Roles('admin', 'editor')`** - a 403 unless the caller holds one of them.
142
142
  `@dunx/openapi` already reads the same key for its security schemes.
143
143
 
144
144
  A public route that wants to *adapt* to an optional caller asks better-auth itself:
@@ -173,7 +173,7 @@ but nothing a route handler calls. `AsyncLocalStorage` is a Node built-in Bun
173
173
  implements natively, and it is already how `@dunx/core` carries request state.
174
174
 
175
175
  It is a **second** store rather than a key in `RequestContext`, because that one is
176
- the log record every field in it is serialized into every line the request writes,
176
+ the log record - every field in it is serialized into every line the request writes,
177
177
  so a session object there would be noise on each entry and a redaction hazard in the
178
178
  ones that matter. What does go there is `userId`, which is why every log line inside a
179
179
  guarded request is already correlated to the user.
@@ -196,7 +196,7 @@ Written bare, `Auth` carries better-auth's core endpoints only.
196
196
  ## Password hashing
197
197
 
198
198
  better-auth's default hasher is **pure-JavaScript scrypt**. `AuthModule` replaces it
199
- with `bunPassword` native bcrypt through `Bun.password` whenever
199
+ with `bunPassword` - native bcrypt through `Bun.password` - whenever
200
200
  `emailAndPassword` is enabled and you did not supply a `password` of your own. That is
201
201
  Rule 1's first half: if Bun ships it, use Bun.
202
202
 
@@ -227,12 +227,12 @@ costing a database round trip per request.
227
227
 
228
228
  All five methods are implemented, not the three that are mandatory. `getAndDelete` and
229
229
  `increment` are optional in better-auth's interface because most clients cannot do
230
- them atomically `Bun.RedisClient` can, through `GETDEL` and `INCR`. Without them
230
+ them atomically - `Bun.RedisClient` can, through `GETDEL` and `INCR`. Without them
231
231
  better-auth falls back to read-then-delete for single-use credentials, which is a
232
232
  race, and to a non-atomic rate-limit counter.
233
233
 
234
234
  `redisStorage` takes a `RedisStore`, which is six methods restated rather than
235
- imported an `@dunx/infra/redis` `RedisConnection` satisfies it structurally, and so
235
+ imported - an `@dunx/infra/redis` `RedisConnection` satisfies it structurally, and so
236
236
  does anything else shaped like `Bun.RedisClient`.
237
237
 
238
238
  ## What is bound
@@ -247,5 +247,5 @@ does anything else shaped like `Bun.RedisClient`.
247
247
  | `SessionGuard`| The guard, ready for `middleware: [...]` or `@UseGuards` |
248
248
 
249
249
  Every one of them declares its own `inject` list, so none of it needs
250
- `@dunx/transform`'s transform to have run `@dunx/auth` works in an app with no
250
+ `@dunx/transform`'s transform to have run - `@dunx/auth` works in an app with no
251
251
  preload.
package/dist/auth.d.ts CHANGED
@@ -5,28 +5,28 @@ import type { Auth as Instance, BetterAuthOptions } from 'better-auth';
5
5
  *
6
6
  * `betterAuth()` returns a plain object, so there is no class to use as a token.
7
7
  * This is the same trick `Logger` and `RequestContext` use in `@dunx/core`: an
8
- * abstract class whose members are **aliases of better-auth's own** not
9
- * restatements which a real instance satisfies structurally. That is what makes
8
+ * abstract class whose members are **aliases of better-auth's own** - not
9
+ * restatements - which a real instance satisfies structurally. That is what makes
10
10
  * `constructor(private readonly auth: Auth)` work, since `@dunx/transform` records
11
11
  * the bare type name and the container resolves it.
12
12
  *
13
13
  * The type argument is the `DbModule` trick from `@dunx/infra/db`: the token is the
14
14
  * erased class, so `Auth<typeof authOptions>` at an injection site keeps the
15
15
  * plugin-widened `api` while still resolving the one binding. Written bare, `Auth`
16
- * carries better-auth's core endpoints only a plugin's endpoints are on the
16
+ * carries better-auth's core endpoints only - a plugin's endpoints are on the
17
17
  * annotation, not on the token.
18
18
  */
19
19
  export declare abstract class Auth<O extends BetterAuthOptions = BetterAuthOptions> {
20
20
  /**
21
21
  * `abstract` stops TypeScript constructing this, but the container works on
22
- * runtime values and every class self-binds so `get(Auth)` with nothing bound
22
+ * runtime values and every class self-binds - so `get(Auth)` with nothing bound
23
23
  * would hand back a bare instance whose every member is `undefined`, and the
24
24
  * first symptom would be `auth.handler is not a function` deep in a request.
25
25
  */
26
26
  constructor();
27
27
  /** better-auth's framework-agnostic handler. `AuthHandler` mounts it. */
28
28
  abstract readonly handler: Instance<O>['handler'];
29
- /** Every endpoint as a callable `api.getSession`, `api.signUpEmail`, ... */
29
+ /** Every endpoint as a callable - `api.getSession`, `api.signUpEmail`, ... */
30
30
  abstract readonly api: Instance<O>['api'];
31
31
  /** The options `betterAuth()` was called with, dunx's defaults already applied. */
32
32
  abstract readonly options: Instance<O>['options'];
@@ -35,7 +35,7 @@ export declare abstract class Auth<O extends BetterAuthOptions = BetterAuthOptio
35
35
  abstract readonly $Infer: Instance<O>['$Infer'];
36
36
  }
37
37
  /**
38
- * `{ session, user }` for an authenticated caller better-auth's own inferred
38
+ * `{ session, user }` for an authenticated caller - better-auth's own inferred
39
39
  * session type, so a plugin's extra user fields (the `admin` plugin's `role` and
40
40
  * `banned`, say) are typed without dunx naming a single one of them.
41
41
  */
package/dist/context.d.ts CHANGED
@@ -2,21 +2,21 @@ import { RequestContext } from '@dunx/core';
2
2
  import type { BetterAuthOptions } from 'better-auth';
3
3
  import type { Principal } from './auth.js';
4
4
  /**
5
- * How the authenticated caller reaches a handler and anything the handler calls,
5
+ * How the authenticated caller reaches a handler - and anything the handler calls,
6
6
  * however deep.
7
7
  *
8
8
  * `AsyncLocalStorage`, for the same reason `@dunx/core`'s `RequestContext` is: it is
9
9
  * a Node built-in Bun implements natively, and it is the only mechanism that gets a
10
10
  * value from middleware to a service three constructor hops away without passing
11
- * it. The alternatives were both worse request-scoped DI was measured and rejected
11
+ * it. The alternatives were both worse - request-scoped DI was measured and rejected
12
12
  * (docs/ARCHITECTURE.md), and hanging the principal off `req` reaches a route
13
13
  * handler but nothing a route handler calls.
14
14
  *
15
15
  * It is a **second** store rather than a key in `RequestContext`. That store is the
16
16
  * log record: every field in it is serialized into every line the request writes, so
17
17
  * a session object there would be noise on each entry and a redaction hazard in the
18
- * ones that matter. What does go there is `userId` a well-known `RequestFields`
19
- * key so the log lines are correlated without carrying the principal.
18
+ * ones that matter. What does go there is `userId` - a well-known `RequestFields`
19
+ * key - so the log lines are correlated without carrying the principal.
20
20
  */
21
21
  export declare class AuthContext {
22
22
  #private;
package/dist/drizzle.d.ts CHANGED
@@ -5,12 +5,12 @@ import { drizzleAdapter, type DrizzleAdapterConfig } from 'better-auth/adapters/
5
5
  * Restated structurally rather than imported, for the same reason `@dunx/http`
6
6
  * restates Standard Schema: it keeps `@dunx/auth`'s dependency list at `@dunx/core`
7
7
  * and `@dunx/http`, and it means a bare `drizzle({ client, schema })` handle works
8
- * here too. An `@dunx/infra/db` connection satisfies it with no adapter in between
8
+ * here too. An `@dunx/infra/db` connection satisfies it with no adapter in between -
9
9
  * `dialect` is exactly that union and `db` is exactly `unknown`.
10
10
  */
11
11
  export interface DrizzleSource {
12
12
  readonly dialect: 'postgres' | 'mysql' | 'mariadb' | 'sqlite';
13
- /** The drizzle handle `BunSQLiteDatabase` or `BunSQLDatabase`. */
13
+ /** The drizzle handle - `BunSQLiteDatabase` or `BunSQLDatabase`. */
14
14
  readonly db: unknown;
15
15
  }
16
16
  /**
@@ -29,7 +29,7 @@ export interface DrizzleSource {
29
29
  *
30
30
  * The `provider` comes from the connection's own dialect, so swapping `bun:sqlite`
31
31
  * for `Bun.SQL` needs no edit at the call site. The schema does not have to be passed
32
- * either `@dunx/infra/db` builds its handle with `drizzle({ client, schema })` and
32
+ * either - `@dunx/infra/db` builds its handle with `drizzle({ client, schema })` and
33
33
  * the adapter reads `db._.fullSchema`, so the better-auth tables being in the app's
34
34
  * schema object is the whole requirement.
35
35
  *
@@ -2,7 +2,7 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/drizzle.ts"],
4
4
  "sourcesContent": [
5
- "import {\n drizzleAdapter,\n type DB,\n type DrizzleAdapterConfig,\n} from 'better-auth/adapters/drizzle';\n\n/**\n * The two members of `@dunx/infra/db`'s `DbConnection` this reads.\n *\n * Restated structurally rather than imported, for the same reason `@dunx/http`\n * restates Standard Schema: it keeps `@dunx/auth`'s dependency list at `@dunx/core`\n * and `@dunx/http`, and it means a bare `drizzle({ client, schema })` handle works\n * here too. An `@dunx/infra/db` connection satisfies it with no adapter in between —\n * `dialect` is exactly that union and `db` is exactly `unknown`.\n */\nexport interface DrizzleSource {\n readonly dialect: 'postgres' | 'mysql' | 'mariadb' | 'sqlite';\n /** The drizzle handle `BunSQLiteDatabase` or `BunSQLDatabase`. */\n readonly db: unknown;\n}\n\n/** What better-auth's drizzle adapter calls each of the dialects `@dunx/infra/db` reports. */\nconst PROVIDERS: Readonly<\n Record<DrizzleSource['dialect'], DrizzleAdapterConfig['provider']>\n> = Object.freeze({\n postgres: 'pg',\n mysql: 'mysql',\n mariadb: 'mysql',\n sqlite: 'sqlite',\n});\n\n/**\n * better-auth's `database` option over a connection the app already opened. Nothing\n * here connects: the point is that the app keeps **one** pool, one SQLite handle and\n * one shutdown path, instead of better-auth opening a second.\n *\n * ```ts\n * AuthModule.forRootAsync({\n * useFactory: (connection: DbConnection) => ({\n * database: drizzleDatabase(connection),\n * }),\n * inject: [DbConnection],\n * });\n * ```\n *\n * The `provider` comes from the connection's own dialect, so swapping `bun:sqlite`\n * for `Bun.SQL` needs no edit at the call site. The schema does not have to be passed\n * either `@dunx/infra/db` builds its handle with `drizzle({ client, schema })` and\n * the adapter reads `db._.fullSchema`, so the better-auth tables being in the app's\n * schema object is the whole requirement.\n *\n * dunx ships **no** schema for those tables. They are better-auth's, they change with\n * its plugins, and its own CLI generates them: `bunx @better-auth/cli generate`. A\n * copy of them inside a framework is a copy that silently rots against the library\n * that reads it.\n */\nexport const drizzleDatabase = (\n connection: DrizzleSource,\n config: Omit<DrizzleAdapterConfig, 'provider'> = {},\n): ReturnType<typeof drizzleAdapter> =>\n // `db` is `unknown` on the contract because it cannot promise either backend's\n // handle. Narrowing it is what that contract documents.\n drizzleAdapter(connection.db as DB, {\n ...config,\n provider: PROVIDERS[connection.dialect],\n });\n"
5
+ "import {\n drizzleAdapter,\n type DB,\n type DrizzleAdapterConfig,\n} from 'better-auth/adapters/drizzle';\n\n/**\n * The two members of `@dunx/infra/db`'s `DbConnection` this reads.\n *\n * Restated structurally rather than imported, for the same reason `@dunx/http`\n * restates Standard Schema: it keeps `@dunx/auth`'s dependency list at `@dunx/core`\n * and `@dunx/http`, and it means a bare `drizzle({ client, schema })` handle works\n * here too. An `@dunx/infra/db` connection satisfies it with no adapter in between -\n * `dialect` is exactly that union and `db` is exactly `unknown`.\n */\nexport interface DrizzleSource {\n readonly dialect: 'postgres' | 'mysql' | 'mariadb' | 'sqlite';\n /** The drizzle handle - `BunSQLiteDatabase` or `BunSQLDatabase`. */\n readonly db: unknown;\n}\n\n/** What better-auth's drizzle adapter calls each of the dialects `@dunx/infra/db` reports. */\nconst PROVIDERS: Readonly<\n Record<DrizzleSource['dialect'], DrizzleAdapterConfig['provider']>\n> = Object.freeze({\n postgres: 'pg',\n mysql: 'mysql',\n mariadb: 'mysql',\n sqlite: 'sqlite',\n});\n\n/**\n * better-auth's `database` option over a connection the app already opened. Nothing\n * here connects: the point is that the app keeps **one** pool, one SQLite handle and\n * one shutdown path, instead of better-auth opening a second.\n *\n * ```ts\n * AuthModule.forRootAsync({\n * useFactory: (connection: DbConnection) => ({\n * database: drizzleDatabase(connection),\n * }),\n * inject: [DbConnection],\n * });\n * ```\n *\n * The `provider` comes from the connection's own dialect, so swapping `bun:sqlite`\n * for `Bun.SQL` needs no edit at the call site. The schema does not have to be passed\n * either - `@dunx/infra/db` builds its handle with `drizzle({ client, schema })` and\n * the adapter reads `db._.fullSchema`, so the better-auth tables being in the app's\n * schema object is the whole requirement.\n *\n * dunx ships **no** schema for those tables. They are better-auth's, they change with\n * its plugins, and its own CLI generates them: `bunx @better-auth/cli generate`. A\n * copy of them inside a framework is a copy that silently rots against the library\n * that reads it.\n */\nexport const drizzleDatabase = (\n connection: DrizzleSource,\n config: Omit<DrizzleAdapterConfig, 'provider'> = {},\n): ReturnType<typeof drizzleAdapter> =>\n // `db` is `unknown` on the contract because it cannot promise either backend's\n // handle. Narrowing it is what that contract documents.\n drizzleAdapter(connection.db as DB, {\n ...config,\n provider: PROVIDERS[connection.dialect],\n });\n"
6
6
  ],
7
7
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAsBA,IAAM,YAEF,OAAO,OAAO;AAAA,EAChB,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;AAAA,EACT,QAAQ;AACV,CAAC;AA2BM,IAAM,kBAAkB,CAC7B,YACA,SAAiD,CAAC,MAIlD,eAAe,WAAW,IAAU;AAAA,KAC/B;AAAA,EACH,UAAU,UAAU,WAAW;AACjC,CAAC;",
8
8
  "debugId": "FE2DA2CE89A5EE9A64756E2164756E21",
package/dist/guard.d.ts CHANGED
@@ -6,20 +6,20 @@ import { AuthContext } from './context.js';
6
6
  * What roles a user holds. better-auth's `admin` plugin stores them in a single
7
7
  * `role` column, comma-separated for more than one; a custom plugin may use an
8
8
  * array. Both read the same here, and a user with none reads as `[]` rather than
9
- * throwing an app may well not use roles at all.
9
+ * throwing - an app may well not use roles at all.
10
10
  */
11
11
  export declare const rolesOf: (user: object) => readonly string[];
12
12
  /**
13
13
  * Authenticates every request it sees through better-auth's own session lookup, and
14
14
  * composes with the metadata `@dunx/http` already carries:
15
15
  *
16
- * - `@Public()` skipped outright. No session lookup, no rejection, no role check.
16
+ * - `@Public()` - skipped outright. No session lookup, no rejection, no role check.
17
17
  * That is what makes it safe to install globally: better-auth's own endpoints are
18
18
  * `@Public()`, and a sign-in route that needed a session could never be reached.
19
19
  * A public route that wants to *adapt* to an optional caller injects `Auth` and
20
- * calls `auth.api.getSession({ headers: req.headers })` itself one line, and it
20
+ * calls `auth.api.getSession({ headers: req.headers })` itself - one line, and it
21
21
  * does not put a lookup on every public request in the app.
22
- * - `@Roles('admin')` a 403 unless the caller holds one of them.
22
+ * - `@Roles('admin')` - a 403 unless the caller holds one of them.
23
23
  *
24
24
  * Install it globally with `HttpFactory.create(root, { middleware: [SessionGuard] })`
25
25
  * and opt routes out with `@Public()`, or scope it with `@UseGuards(SessionGuard)`
package/dist/handler.d.ts CHANGED
@@ -3,17 +3,17 @@ import { type Input, type RouteSchemas } from '@dunx/http';
3
3
  /**
4
4
  * better-auth's handler is a plain `(request: Request) => Promise<Response>`, so
5
5
  * mounting it is five one-line routes and nothing else. Every endpoint the library
6
- * and its plugins declare lives under one wildcard dunx does not restate, wrap or
6
+ * and its plugins declare lives under one wildcard - dunx does not restate, wrap or
7
7
  * re-dispatch a single one of them.
8
8
  *
9
9
  * `Bun.serve` matches `<basePath>/*` natively (verified on Bun 1.3.14), so Bun is
10
10
  * still the router. All five verbs are mounted because a plugin may declare any of
11
11
  * them; better-auth's own endpoints are `GET` and `POST`.
12
12
  *
13
- * The `Response` is returned untouched `buildRoutes` passes one straight through,
13
+ * The `Response` is returned untouched - `buildRoutes` passes one straight through,
14
14
  * which is what keeps better-auth's `Set-Cookie` headers and redirects intact.
15
15
  *
16
- * `@Public()` at class scope, so all five inherit it `mergeMeta` reads the class's
16
+ * `@Public()` at class scope, so all five inherit it - `mergeMeta` reads the class's
17
17
  * record under the handler's. Without it a globally installed `SessionGuard` would
18
18
  * demand a session from the sign-in endpoint, and no session could ever be created.
19
19
  *
@@ -36,7 +36,7 @@ export declare class AuthHandler {
36
36
  * A subclass rather than `@Controller(...)` on {@link AuthHandler} itself: the prefix
37
37
  * is only known once the module is configured, and mutating the shared class from a
38
38
  * factory would make two configurations fight over one prefix. The subclass declares
39
- * nothing of its own and inherits everything `discoverRoutes` walks the prototype
39
+ * nothing of its own and inherits everything - `discoverRoutes` walks the prototype
40
40
  * chain for the routes, and `metaOf` and `prefixOf` are plain lookups, so `@Public()`
41
41
  * comes down from the base while the prefix stays own to the subclass.
42
42
  */
package/dist/index.js CHANGED
@@ -249,7 +249,7 @@ _dispatch_fn = function(req) {
249
249
  const basePath = __privateGet(this, _auth).options.basePath ?? DEFAULT_BASE_PATH;
250
250
  const { pathname } = new URL(req.url);
251
251
  if (!pathname.startsWith(`${basePath}/`)) {
252
- throw new AuthError(`${pathname} reached the auth handler, but better-auth is configured with ` + `basePath ${basePath} and would answer 404 to everything under it. A ` + "global prefix is the usual cause: mount the handler at the path without " + "the prefix and give better-auth the full one \u2014 see AuthOptions.mountAt.");
252
+ throw new AuthError(`${pathname} reached the auth handler, but better-auth is configured with ` + `basePath ${basePath} and would answer 404 to everything under it. A ` + "global prefix is the usual cause: mount the handler at the path without " + "the prefix and give better-auth the full one - see AuthOptions.mountAt.");
253
253
  }
254
254
  }
255
255
  return __privateGet(this, _auth).handler(req);
@@ -330,7 +330,7 @@ class AuthModule {
330
330
  useFactory: async (...deps) => {
331
331
  const resolved = new AuthOptions(await provider.useFactory(...deps), mounted);
332
332
  if (mountAt === undefined && resolved.basePath !== mounted) {
333
- throw new AuthError(`The factory returned basePath ${resolved.basePath}, but the handler ` + `is mounted at ${mounted} \u2014 the table was built before the factory ` + "ran, so it could not follow. Pass the route path as " + "forRootAsync's second argument.");
333
+ throw new AuthError(`The factory returned basePath ${resolved.basePath}, but the handler ` + `is mounted at ${mounted} - the table was built before the factory ` + "ran, so it could not follow. Pass the route path as " + "forRootAsync's second argument.");
334
334
  }
335
335
  return resolved;
336
336
  },
@@ -369,5 +369,5 @@ export {
369
369
  Auth
370
370
  };
371
371
 
372
- //# debugId=0D5B2BADC3F2673664756E2164756E21
372
+ //# debugId=0637629E506E689864756E2164756E21
373
373
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -3,16 +3,16 @@
3
3
  "sources": ["../src/errors.ts", "../src/auth.ts", "../src/context.ts", "../src/guard.ts", "../src/handler.ts", "../src/password.ts", "../src/options.ts", "../src/module.ts", "../src/redis.ts"],
4
4
  "sourcesContent": [
5
5
  "import { AppError } from '@dunx/core';\n\n/**\n * Raised by `@dunx/auth`'s own wiring. better-auth's failures propagate as its\n * `APIError`, and a rejected request is an `HttpError` from `@dunx/http`.\n */\nexport class AuthError extends AppError {\n override name = 'AuthError';\n}\n",
6
- "import type { Auth as Instance, BetterAuthOptions } from 'better-auth';\nimport { AuthError } from './errors.js';\n\n/**\n * The injection token for the better-auth instance, and the whole of dunx's\n * contract with the library.\n *\n * `betterAuth()` returns a plain object, so there is no class to use as a token.\n * This is the same trick `Logger` and `RequestContext` use in `@dunx/core`: an\n * abstract class whose members are **aliases of better-auth's own** not\n * restatements which a real instance satisfies structurally. That is what makes\n * `constructor(private readonly auth: Auth)` work, since `@dunx/transform` records\n * the bare type name and the container resolves it.\n *\n * The type argument is the `DbModule` trick from `@dunx/infra/db`: the token is the\n * erased class, so `Auth<typeof authOptions>` at an injection site keeps the\n * plugin-widened `api` while still resolving the one binding. Written bare, `Auth`\n * carries better-auth's core endpoints only a plugin's endpoints are on the\n * annotation, not on the token.\n */\nexport abstract class Auth<O extends BetterAuthOptions = BetterAuthOptions> {\n /**\n * `abstract` stops TypeScript constructing this, but the container works on\n * runtime values and every class self-binds so `get(Auth)` with nothing bound\n * would hand back a bare instance whose every member is `undefined`, and the\n * first symptom would be `auth.handler is not a function` deep in a request.\n */\n constructor() {\n if (new.target === Auth) {\n throw new AuthError(\n 'Auth is a contract, not an implementation. Bind one with ' +\n 'AuthModule.forRoot({ ... }) or AuthModule.forRootAsync({ useFactory }).',\n );\n }\n }\n\n /** better-auth's framework-agnostic handler. `AuthHandler` mounts it. */\n abstract readonly handler: Instance<O>['handler'];\n /** Every endpoint as a callable `api.getSession`, `api.signUpEmail`, ... */\n abstract readonly api: Instance<O>['api'];\n /** The options `betterAuth()` was called with, dunx's defaults already applied. */\n abstract readonly options: Instance<O>['options'];\n abstract readonly $ERROR_CODES: Instance<O>['$ERROR_CODES'];\n abstract readonly $context: Instance<O>['$context'];\n abstract readonly $Infer: Instance<O>['$Infer'];\n}\n\n/**\n * `{ session, user }` for an authenticated caller better-auth's own inferred\n * session type, so a plugin's extra user fields (the `admin` plugin's `role` and\n * `banned`, say) are typed without dunx naming a single one of them.\n */\nexport type Principal<O extends BetterAuthOptions = BetterAuthOptions> =\n Instance<O>['$Infer']['Session'];\n",
7
- "import { AsyncLocalStorage } from 'node:async_hooks';\nimport { RequestContext } from '@dunx/core';\nimport { HttpError, HttpStatusCode } from '@dunx/http';\nimport type { BetterAuthOptions } from 'better-auth';\nimport type { Principal } from './auth.js';\n\n/**\n * How the authenticated caller reaches a handler and anything the handler calls,\n * however deep.\n *\n * `AsyncLocalStorage`, for the same reason `@dunx/core`'s `RequestContext` is: it is\n * a Node built-in Bun implements natively, and it is the only mechanism that gets a\n * value from middleware to a service three constructor hops away without passing\n * it. The alternatives were both worse request-scoped DI was measured and rejected\n * (docs/ARCHITECTURE.md), and hanging the principal off `req` reaches a route\n * handler but nothing a route handler calls.\n *\n * It is a **second** store rather than a key in `RequestContext`. That store is the\n * log record: every field in it is serialized into every line the request writes, so\n * a session object there would be noise on each entry and a redaction hazard in the\n * ones that matter. What does go there is `userId` a well-known `RequestFields`\n * key so the log lines are correlated without carrying the principal.\n */\nexport class AuthContext {\n readonly #storage = new AsyncLocalStorage<Principal>();\n\n constructor(private readonly context: RequestContext) {}\n\n /**\n * The caller, or `undefined` on an anonymous request. The type argument is the\n * options object `AuthModule` was configured with, and is how a plugin's extra\n * user fields become visible:\n *\n * ```ts\n * const principal = this.auth.current<typeof authOptions>();\n * ```\n */\n current<O extends BetterAuthOptions = BetterAuthOptions>():\n | Principal<O>\n | undefined {\n return this.#storage.getStore() as Principal<O> | undefined;\n }\n\n /** The caller, or a 401. For a handler behind `SessionGuard` that is not `@Public()`. */\n require<O extends BetterAuthOptions = BetterAuthOptions>(): Principal<O> {\n const principal = this.current<O>();\n if (!principal) {\n throw new HttpError(HttpStatusCode.UNAUTHORIZED, 'UNAUTHENTICATED');\n }\n return principal;\n }\n\n /**\n * Runs `callback` with `principal` as the caller. `SessionGuard` is what calls\n * this; a job or a socket handler that resolved a session itself can too.\n *\n * `userId` is written to `RequestContext` as well, which is what puts it on every\n * log line the callback produces.\n */\n run<T>(principal: Principal, callback: () => T): T {\n this.context.updateContext({ userId: principal.user.id });\n return this.#storage.run(principal, callback);\n }\n}\nObject.defineProperty(AuthContext, Symbol.for('dunx.deps'), {\n value: () => [RequestContext],\n});\n",
8
- "import {\n HttpError,\n HttpStatusCode,\n PUBLIC,\n ROLES,\n type Middleware,\n type Next,\n type RouteContext,\n} from '@dunx/http';\nimport type { BunRequest } from 'bun';\nimport { Auth, type Principal } from './auth.js';\nimport { AuthContext } from './context.js';\n\ninterface Roled {\n readonly role?: unknown;\n}\n\n/**\n * What roles a user holds. better-auth's `admin` plugin stores them in a single\n * `role` column, comma-separated for more than one; a custom plugin may use an\n * array. Both read the same here, and a user with none reads as `[]` rather than\n * throwing an app may well not use roles at all.\n */\nexport const rolesOf = (user: object): readonly string[] => {\n const role = (user as Roled).role;\n\n if (typeof role === 'string') {\n return role\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n }\n if (Array.isArray(role)) {\n return role.filter((entry): entry is string => typeof entry === 'string');\n }\n return [];\n};\n\n/**\n * Authenticates every request it sees through better-auth's own session lookup, and\n * composes with the metadata `@dunx/http` already carries:\n *\n * - `@Public()` skipped outright. No session lookup, no rejection, no role check.\n * That is what makes it safe to install globally: better-auth's own endpoints are\n * `@Public()`, and a sign-in route that needed a session could never be reached.\n * A public route that wants to *adapt* to an optional caller injects `Auth` and\n * calls `auth.api.getSession({ headers: req.headers })` itself one line, and it\n * does not put a lookup on every public request in the app.\n * - `@Roles('admin')` a 403 unless the caller holds one of them.\n *\n * Install it globally with `HttpFactory.create(root, { middleware: [SessionGuard] })`\n * and opt routes out with `@Public()`, or scope it with `@UseGuards(SessionGuard)`\n * and leave the rest of the app open. `AuthModule` registers it either way.\n */\nexport class SessionGuard implements Middleware {\n constructor(\n private readonly auth: Auth,\n private readonly context: AuthContext,\n ) {}\n\n async handle(\n req: BunRequest,\n ctx: RouteContext,\n next: Next,\n ): Promise<Response> {\n if (ctx.get(PUBLIC)) return next();\n\n const principal: Principal | null = await this.auth.api.getSession({\n headers: req.headers,\n });\n if (!principal) {\n throw new HttpError(HttpStatusCode.UNAUTHORIZED, 'UNAUTHENTICATED');\n }\n\n const required = ctx.get(ROLES);\n if (required !== undefined && required.length > 0) {\n const held = rolesOf(principal.user);\n if (!required.some((role) => held.includes(role))) {\n throw new HttpError(\n HttpStatusCode.FORBIDDEN,\n `Requires one of: ${required.join(', ')}`,\n );\n }\n }\n\n return this.context.run(principal, next);\n }\n}\nObject.defineProperty(SessionGuard, Symbol.for('dunx.deps'), {\n value: () => [Auth, AuthContext],\n});\n",
9
- "import { inject, type Ctor } from '@dunx/core';\nimport {\n Controller,\n Delete,\n Get,\n Patch,\n Post,\n Public,\n Put,\n type Input,\n type RouteSchemas,\n} from '@dunx/http';\nimport type { BunRequest } from 'bun';\nimport { Auth } from './auth.js';\nimport { AuthError } from './errors.js';\nimport { DEFAULT_BASE_PATH } from './options.js';\n\n/**\n * better-auth's handler is a plain `(request: Request) => Promise<Response>`, so\n * mounting it is five one-line routes and nothing else. Every endpoint the library\n * and its plugins declare lives under one wildcard dunx does not restate, wrap or\n * re-dispatch a single one of them.\n *\n * `Bun.serve` matches `<basePath>/*` natively (verified on Bun 1.3.14), so Bun is\n * still the router. All five verbs are mounted because a plugin may declare any of\n * them; better-auth's own endpoints are `GET` and `POST`.\n *\n * The `Response` is returned untouched `buildRoutes` passes one straight through,\n * which is what keeps better-auth's `Set-Cookie` headers and redirects intact.\n *\n * `@Public()` at class scope, so all five inherit it `mergeMeta` reads the class's\n * record under the handler's. Without it a globally installed `SessionGuard` would\n * demand a session from the sign-in endpoint, and no session could ever be created.\n *\n * `inject(Auth)` in a field rather than a constructor parameter, because a bare\n * class in `controllers` is bound as a class provider and would then need\n * `@dunx/transform`'s transform to have run. This way mounting works in an app that\n * never added the preload.\n */\n@Public()\nexport class AuthHandler {\n readonly #auth = inject(Auth);\n #verified = false;\n\n @Get('/*') get({ req }: Input<RouteSchemas>): Promise<Response> {\n return this.#dispatch(req);\n }\n\n @Post('/*') post({ req }: Input<RouteSchemas>): Promise<Response> {\n return this.#dispatch(req);\n }\n\n @Put('/*') put({ req }: Input<RouteSchemas>): Promise<Response> {\n return this.#dispatch(req);\n }\n\n @Patch('/*') patch({ req }: Input<RouteSchemas>): Promise<Response> {\n return this.#dispatch(req);\n }\n\n @Delete('/*') delete({ req }: Input<RouteSchemas>): Promise<Response> {\n return this.#dispatch(req);\n }\n\n /**\n * better-auth resolves an endpoint by comparing the whole pathname to its own\n * `basePath`, so a handler mounted somewhere else answers 404 to everything with no\n * hint as to why. The final path is only knowable once `listen()` has applied the\n * global prefix, which is after this module was configured so it is checked on\n * the **first** request and never again.\n */\n #dispatch(req: BunRequest): Promise<Response> {\n if (!this.#verified) {\n this.#verified = true;\n const basePath = this.#auth.options.basePath ?? DEFAULT_BASE_PATH;\n const { pathname } = new URL(req.url);\n if (!pathname.startsWith(`${basePath}/`)) {\n throw new AuthError(\n `${pathname} reached the auth handler, but better-auth is configured with ` +\n `basePath ${basePath} and would answer 404 to everything under it. A ` +\n 'global prefix is the usual cause: mount the handler at the path without ' +\n 'the prefix and give better-auth the full one see AuthOptions.mountAt.',\n );\n }\n }\n return this.#auth.handler(req);\n }\n}\n\n/**\n * The controller `AuthModule` registers, prefixed with `AuthOptions.mountAt`.\n *\n * A subclass rather than `@Controller(...)` on {@link AuthHandler} itself: the prefix\n * is only known once the module is configured, and mutating the shared class from a\n * factory would make two configurations fight over one prefix. The subclass declares\n * nothing of its own and inherits everything `discoverRoutes` walks the prototype\n * chain for the routes, and `metaOf` and `prefixOf` are plain lookups, so `@Public()`\n * comes down from the base while the prefix stays own to the subclass.\n */\nexport const mountHandler = (mountAt: string): Ctor<AuthHandler> =>\n Controller(mountAt)(class MountedAuthHandler extends AuthHandler {});\n",
10
- "/**\n * better-auth's `emailAndPassword.password`, backed by `Bun.password`.\n *\n * Applied by `AuthModule` whenever `emailAndPassword` is enabled and no `password`\n * of your own is given. better-auth's default is a **pure-JavaScript scrypt**;\n * `Bun.password` is native bcrypt, which is Rule 1's first half if Bun ships it,\n * use Bun.\n *\n * Bun pre-hashes the input, so bcrypt's 72-byte cap is a non-issue even for a\n * maximum-length multibyte password.\n *\n * `verify` swallows Bun's `UnsupportedAlgorithm` throw, so a hash produced by a\n * *different* algorithm a scrypt hash written before this was in place is a\n * clean authentication failure rather than a 500. Those users must reset their\n * password to get a bcrypt hash; pass your own `password` implementation instead\n * if you are migrating an existing user table and cannot.\n */\nexport const bunPassword = {\n hash: (password: string): Promise<string> =>\n Bun.password.hash(password, { algorithm: 'bcrypt', cost: 10 }),\n verify: async ({\n hash,\n password,\n }: {\n hash: string;\n password: string;\n }): Promise<boolean> => {\n try {\n return await Bun.password.verify(password, hash);\n } catch {\n return false;\n }\n },\n};\n",
11
- "import type { BetterAuthOptions } from 'better-auth';\nimport { AuthError } from './errors.js';\nimport { bunPassword } from './password.js';\n\n/** better-auth's own default, and where `AuthHandler` mounts unless told otherwise. */\nexport const DEFAULT_BASE_PATH = '/api/auth';\n\n/**\n * One leading slash, no trailing one the shape `@dunx/http`'s route paths take,\n * so the mount and better-auth's own URL building agree character for character.\n *\n * The root is rejected: the mount is `<basePath>/*`, and at `/` that wildcard would\n * claim every path in the app.\n */\nexport const normalizeBasePath = (basePath: string): string => {\n const normalized = `/${basePath}`.replace(/\\/{2,}/g, '/').replace(/\\/$/, '');\n\n if (normalized.length < 2) {\n throw new AuthError(\n `\"${basePath}\" is not a usable basePath. The handler mounts at ` +\n '<basePath>/*, so at the root it would claim every route in the app. ' +\n `Use something like ${DEFAULT_BASE_PATH}.`,\n );\n }\n return normalized;\n};\n\n/**\n * Bun's native bcrypt in place of better-auth's pure-JavaScript scrypt, unless a\n * `password` of your own is already there. See {@link bunPassword} for the\n * migration caveat.\n */\nconst withBunPassword = <O extends BetterAuthOptions>(options: O): O => {\n const email = options.emailAndPassword;\n if (!email?.enabled || email.password) return options;\n\n // The one cast in the package: TypeScript cannot prove a spread of a generic with\n // one key replaced is still that generic, and widening the return to\n // `BetterAuthOptions` would lose the plugin types `betterAuth()` infers from it.\n return {\n ...options,\n emailAndPassword: { ...email, password: bunPassword },\n } as O;\n};\n\n/**\n * What `betterAuth()` gets called with, where the handler mounts, and the difference\n * between the two. Bound in the container so all of it is readable, and constructed\n * by `AuthModule` rather than by the app.\n */\nexport class AuthOptions<O extends BetterAuthOptions = BetterAuthOptions> {\n readonly options: O;\n\n /**\n * What better-auth matches an incoming pathname against, and builds its URLs from.\n * Normalized here and written back into `options`, so the two cannot drift.\n */\n readonly basePath: string;\n\n /**\n * The **route** path `AuthHandler` is mounted at, which is `basePath` unless the\n * app calls `setGlobalPrefix`. better-auth compares the whole pathname to\n * `basePath`, so with `setGlobalPrefix('api')` the two are different strings for\n * the same URL: mount at `/auth`, and tell better-auth `basePath: '/api/auth'`.\n */\n readonly mountAt: string;\n\n constructor(init: O, mountAt?: string) {\n this.basePath = normalizeBasePath(init.basePath ?? DEFAULT_BASE_PATH);\n this.mountAt =\n mountAt === undefined ? this.basePath : normalizeBasePath(mountAt);\n this.options = withBunPassword({ ...init, basePath: this.basePath });\n }\n}\nObject.defineProperty(AuthOptions, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"init: O\" }, { unresolved: \"mountAt?: string\" }],\n});\n",
12
- "import {\n provide,\n type AbstractCtor,\n type Deps,\n type DynamicModule,\n type FactoryProvider,\n type Registration,\n RequestContext,\n} from '@dunx/core';\nimport { betterAuth, type BetterAuthOptions } from 'better-auth';\nimport { Auth } from './auth.js';\nimport { AuthContext } from './context.js';\nimport { AuthError } from './errors.js';\nimport { SessionGuard } from './guard.js';\nimport { mountHandler } from './handler.js';\nimport {\n AuthOptions,\n DEFAULT_BASE_PATH,\n normalizeBasePath,\n} from './options.js';\n\nconst build = (options: Registration, mountAt: string): DynamicModule => {\n // Instantiated to the token type rather than left as `typeof Auth`, which is what\n // lets the factory below hand back a plain better-auth instance with no cast.\n const auth: AbstractCtor<Auth> = Auth;\n\n return {\n module: AuthModule,\n controllers: [mountHandler(mountAt)],\n // Every binding declares its own `inject`, so nothing here needs\n // `@dunx/transform`'s transform to have run the same reason\n // `RequestLoggingMiddleware` and `@dunx/infra/redis`'s `Redis` are bound this way.\n providers: [\n options,\n provide(auth, {\n useFactory: (resolved: AuthOptions) => betterAuth(resolved.options),\n inject: [AuthOptions] as const,\n }),\n provide(AuthContext, {\n useFactory: (context: RequestContext) => new AuthContext(context),\n inject: [RequestContext] as const,\n }),\n provide(SessionGuard, {\n useFactory: (instance: Auth, context: AuthContext) =>\n new SessionGuard(instance, context),\n inject: [auth, AuthContext] as const,\n }),\n ],\n };\n};\n\n/**\n * Binds three tokens and one controller:\n *\n * - `AuthOptions` what `betterAuth()` was called with, and where it is mounted.\n * - `Auth` the better-auth instance itself.\n * - `AuthContext` the authenticated caller, per request.\n * - a prefixed `AuthHandler`, serving every better-auth endpoint under `basePath`.\n *\n * `SessionGuard` is registered as a provider rather than installed as global\n * middleware, because whether it guards the whole app or one controller is the app's\n * decision pass it to `HttpFactory.create(root, { middleware: [SessionGuard] })`\n * or to `@UseGuards(SessionGuard)`.\n */\nexport class AuthModule {\n /**\n * ```ts\n * AuthModule.forRoot({\n * secret: process.env.BETTER_AUTH_SECRET,\n * baseURL: 'http://localhost:3000',\n * database: drizzleDatabase(connection),\n * emailAndPassword: { enabled: true },\n * plugins: [admin(), bearer()],\n * });\n * ```\n *\n * `const O` is load-bearing: it keeps the literal `plugins` tuple, which is what\n * `betterAuth()` infers the plugin endpoints from and therefore what\n * `Auth<typeof options>` resolves to at an injection site.\n *\n * `mountAt` only matters under a global prefix see {@link AuthOptions.mountAt}.\n */\n static forRoot<const O extends BetterAuthOptions>(\n options: O,\n mountAt?: string,\n ): DynamicModule {\n const resolved = new AuthOptions(options, mountAt);\n return build(\n provide(AuthOptions, { useValue: resolved }),\n resolved.mountAt,\n );\n }\n\n /**\n * `forRoot` with the options behind a factory that may await and may inject —\n * which is the only way the secret, the base URL and the database can come from\n * `ConfigService` rather than from module scope:\n *\n * ```ts\n * AuthModule.forRootAsync({\n * useFactory: (config: AppConfigService, connection: DbConnection) => ({\n * secret: config.get('authSecret'),\n * baseURL: config.get('appUrl'),\n * database: drizzleDatabase(connection),\n * emailAndPassword: { enabled: true },\n * }),\n * inject: [AppConfigService, DbConnection],\n * });\n * ```\n *\n * `mountAt` is a second, **synchronous** argument for the same reason\n * `DbModule.forRootAsync` takes its token positionally: the mount is a route in\n * Bun's table, and that table is built before any factory has run. It is only\n * needed under a global prefix see {@link AuthOptions.mountAt}. Omitting it while\n * the factory returns a non-default `basePath` is a boot error, because that\n * combination could only ever have mounted the handler where better-auth is not\n * looking.\n */\n static forRootAsync<const D extends Deps>(\n provider: FactoryProvider<BetterAuthOptions, D>,\n mountAt?: string,\n ): DynamicModule;\n static forRootAsync(\n provider: FactoryProvider<BetterAuthOptions, Deps>,\n mountAt?: string,\n ): DynamicModule {\n const mounted = normalizeBasePath(mountAt ?? DEFAULT_BASE_PATH);\n\n return build(\n provide(AuthOptions, {\n useFactory: async (\n ...deps: readonly unknown[]\n ): Promise<AuthOptions> => {\n const resolved = new AuthOptions(\n await provider.useFactory(...deps),\n mounted,\n );\n if (mountAt === undefined && resolved.basePath !== mounted) {\n throw new AuthError(\n `The factory returned basePath ${resolved.basePath}, but the handler ` +\n `is mounted at ${mounted} the table was built before the factory ` +\n 'ran, so it could not follow. Pass the route path as ' +\n \"forRootAsync's second argument.\",\n );\n }\n return resolved;\n },\n inject: provider.inject ?? [],\n }),\n mounted,\n );\n }\n}\n",
13
- "import type { BetterAuthOptions } from 'better-auth';\n\ntype SecondaryStorage = NonNullable<BetterAuthOptions['secondaryStorage']>;\n\n/**\n * The six commands this needs, restated rather than imported from\n * `@dunx/infra/redis` same reasoning as {@link DrizzleSource}. A `RedisConnection`\n * satisfies it structurally (its parameters are wider, which is the assignable\n * direction), and a test double is six methods instead of the whole surface.\n */\nexport interface RedisStore {\n get(key: string): Promise<string | null>;\n getdel(key: string): Promise<string | null>;\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<boolean>;\n set(\n key: string,\n value: string,\n options?: { readonly ex?: number },\n ): Promise<string | null>;\n del(key: string): Promise<number>;\n}\n\n/**\n * better-auth's `secondaryStorage` over `Bun.RedisClient`, so sessions, verification\n * values and rate-limit counters live in Redis instead of costing a database round\n * trip on every request.\n *\n * All five methods are implemented, not the three that are mandatory.\n * `getAndDelete` and `increment` are optional in better-auth's interface because most\n * clients cannot do them atomically `Bun.RedisClient` can, through `GETDEL` and\n * `INCR`, both already on `@dunx/infra/redis`'s contract. Without them better-auth\n * falls back to read-then-delete for single-use credentials, which is a race, and to\n * a non-atomic rate-limit counter.\n *\n * `increment`'s TTL applies on creation only, which is what makes the counter expire\n * a fixed window after the first hit rather than sliding forever: `INCR` returning\n * `1` is the signal that this call created the key.\n *\n * Redis being unreachable is deliberately **not** softened here. Bun's client\n * connects lazily and queues, so a command against a down server rejects and\n * better-auth's own error path is what should see it a swallowed `null` from `get`\n * would read as \"no session\" and sign every user out.\n */\nexport const redisStorage = (connection: RedisStore): SecondaryStorage => ({\n get: (key) => connection.get(key),\n getAndDelete: (key) => connection.getdel(key),\n increment: async (key, ttl) => {\n const value = await connection.incr(key);\n if (value === 1) await connection.expire(key, ttl);\n return value;\n },\n set: (key, value, ttl) =>\n connection.set(key, value, ttl === undefined ? {} : { ex: ttl }),\n delete: async (key) => {\n await connection.del(key);\n },\n});\n"
6
+ "import type { Auth as Instance, BetterAuthOptions } from 'better-auth';\nimport { AuthError } from './errors.js';\n\n/**\n * The injection token for the better-auth instance, and the whole of dunx's\n * contract with the library.\n *\n * `betterAuth()` returns a plain object, so there is no class to use as a token.\n * This is the same trick `Logger` and `RequestContext` use in `@dunx/core`: an\n * abstract class whose members are **aliases of better-auth's own** - not\n * restatements - which a real instance satisfies structurally. That is what makes\n * `constructor(private readonly auth: Auth)` work, since `@dunx/transform` records\n * the bare type name and the container resolves it.\n *\n * The type argument is the `DbModule` trick from `@dunx/infra/db`: the token is the\n * erased class, so `Auth<typeof authOptions>` at an injection site keeps the\n * plugin-widened `api` while still resolving the one binding. Written bare, `Auth`\n * carries better-auth's core endpoints only - a plugin's endpoints are on the\n * annotation, not on the token.\n */\nexport abstract class Auth<O extends BetterAuthOptions = BetterAuthOptions> {\n /**\n * `abstract` stops TypeScript constructing this, but the container works on\n * runtime values and every class self-binds - so `get(Auth)` with nothing bound\n * would hand back a bare instance whose every member is `undefined`, and the\n * first symptom would be `auth.handler is not a function` deep in a request.\n */\n constructor() {\n if (new.target === Auth) {\n throw new AuthError(\n 'Auth is a contract, not an implementation. Bind one with ' +\n 'AuthModule.forRoot({ ... }) or AuthModule.forRootAsync({ useFactory }).',\n );\n }\n }\n\n /** better-auth's framework-agnostic handler. `AuthHandler` mounts it. */\n abstract readonly handler: Instance<O>['handler'];\n /** Every endpoint as a callable - `api.getSession`, `api.signUpEmail`, ... */\n abstract readonly api: Instance<O>['api'];\n /** The options `betterAuth()` was called with, dunx's defaults already applied. */\n abstract readonly options: Instance<O>['options'];\n abstract readonly $ERROR_CODES: Instance<O>['$ERROR_CODES'];\n abstract readonly $context: Instance<O>['$context'];\n abstract readonly $Infer: Instance<O>['$Infer'];\n}\n\n/**\n * `{ session, user }` for an authenticated caller - better-auth's own inferred\n * session type, so a plugin's extra user fields (the `admin` plugin's `role` and\n * `banned`, say) are typed without dunx naming a single one of them.\n */\nexport type Principal<O extends BetterAuthOptions = BetterAuthOptions> =\n Instance<O>['$Infer']['Session'];\n",
7
+ "import { AsyncLocalStorage } from 'node:async_hooks';\nimport { RequestContext } from '@dunx/core';\nimport { HttpError, HttpStatusCode } from '@dunx/http';\nimport type { BetterAuthOptions } from 'better-auth';\nimport type { Principal } from './auth.js';\n\n/**\n * How the authenticated caller reaches a handler - and anything the handler calls,\n * however deep.\n *\n * `AsyncLocalStorage`, for the same reason `@dunx/core`'s `RequestContext` is: it is\n * a Node built-in Bun implements natively, and it is the only mechanism that gets a\n * value from middleware to a service three constructor hops away without passing\n * it. The alternatives were both worse - request-scoped DI was measured and rejected\n * (docs/ARCHITECTURE.md), and hanging the principal off `req` reaches a route\n * handler but nothing a route handler calls.\n *\n * It is a **second** store rather than a key in `RequestContext`. That store is the\n * log record: every field in it is serialized into every line the request writes, so\n * a session object there would be noise on each entry and a redaction hazard in the\n * ones that matter. What does go there is `userId` - a well-known `RequestFields`\n * key - so the log lines are correlated without carrying the principal.\n */\nexport class AuthContext {\n readonly #storage = new AsyncLocalStorage<Principal>();\n\n constructor(private readonly context: RequestContext) {}\n\n /**\n * The caller, or `undefined` on an anonymous request. The type argument is the\n * options object `AuthModule` was configured with, and is how a plugin's extra\n * user fields become visible:\n *\n * ```ts\n * const principal = this.auth.current<typeof authOptions>();\n * ```\n */\n current<O extends BetterAuthOptions = BetterAuthOptions>():\n | Principal<O>\n | undefined {\n return this.#storage.getStore() as Principal<O> | undefined;\n }\n\n /** The caller, or a 401. For a handler behind `SessionGuard` that is not `@Public()`. */\n require<O extends BetterAuthOptions = BetterAuthOptions>(): Principal<O> {\n const principal = this.current<O>();\n if (!principal) {\n throw new HttpError(HttpStatusCode.UNAUTHORIZED, 'UNAUTHENTICATED');\n }\n return principal;\n }\n\n /**\n * Runs `callback` with `principal` as the caller. `SessionGuard` is what calls\n * this; a job or a socket handler that resolved a session itself can too.\n *\n * `userId` is written to `RequestContext` as well, which is what puts it on every\n * log line the callback produces.\n */\n run<T>(principal: Principal, callback: () => T): T {\n this.context.updateContext({ userId: principal.user.id });\n return this.#storage.run(principal, callback);\n }\n}\nObject.defineProperty(AuthContext, Symbol.for('dunx.deps'), {\n value: () => [RequestContext],\n});\n",
8
+ "import {\n HttpError,\n HttpStatusCode,\n PUBLIC,\n ROLES,\n type Middleware,\n type Next,\n type RouteContext,\n} from '@dunx/http';\nimport type { BunRequest } from 'bun';\nimport { Auth, type Principal } from './auth.js';\nimport { AuthContext } from './context.js';\n\ninterface Roled {\n readonly role?: unknown;\n}\n\n/**\n * What roles a user holds. better-auth's `admin` plugin stores them in a single\n * `role` column, comma-separated for more than one; a custom plugin may use an\n * array. Both read the same here, and a user with none reads as `[]` rather than\n * throwing - an app may well not use roles at all.\n */\nexport const rolesOf = (user: object): readonly string[] => {\n const role = (user as Roled).role;\n\n if (typeof role === 'string') {\n return role\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n }\n if (Array.isArray(role)) {\n return role.filter((entry): entry is string => typeof entry === 'string');\n }\n return [];\n};\n\n/**\n * Authenticates every request it sees through better-auth's own session lookup, and\n * composes with the metadata `@dunx/http` already carries:\n *\n * - `@Public()` - skipped outright. No session lookup, no rejection, no role check.\n * That is what makes it safe to install globally: better-auth's own endpoints are\n * `@Public()`, and a sign-in route that needed a session could never be reached.\n * A public route that wants to *adapt* to an optional caller injects `Auth` and\n * calls `auth.api.getSession({ headers: req.headers })` itself - one line, and it\n * does not put a lookup on every public request in the app.\n * - `@Roles('admin')` - a 403 unless the caller holds one of them.\n *\n * Install it globally with `HttpFactory.create(root, { middleware: [SessionGuard] })`\n * and opt routes out with `@Public()`, or scope it with `@UseGuards(SessionGuard)`\n * and leave the rest of the app open. `AuthModule` registers it either way.\n */\nexport class SessionGuard implements Middleware {\n constructor(\n private readonly auth: Auth,\n private readonly context: AuthContext,\n ) {}\n\n async handle(\n req: BunRequest,\n ctx: RouteContext,\n next: Next,\n ): Promise<Response> {\n if (ctx.get(PUBLIC)) return next();\n\n const principal: Principal | null = await this.auth.api.getSession({\n headers: req.headers,\n });\n if (!principal) {\n throw new HttpError(HttpStatusCode.UNAUTHORIZED, 'UNAUTHENTICATED');\n }\n\n const required = ctx.get(ROLES);\n if (required !== undefined && required.length > 0) {\n const held = rolesOf(principal.user);\n if (!required.some((role) => held.includes(role))) {\n throw new HttpError(\n HttpStatusCode.FORBIDDEN,\n `Requires one of: ${required.join(', ')}`,\n );\n }\n }\n\n return this.context.run(principal, next);\n }\n}\nObject.defineProperty(SessionGuard, Symbol.for('dunx.deps'), {\n value: () => [Auth, AuthContext],\n});\n",
9
+ "import { inject, type Ctor } from '@dunx/core';\nimport {\n Controller,\n Delete,\n Get,\n Patch,\n Post,\n Public,\n Put,\n type Input,\n type RouteSchemas,\n} from '@dunx/http';\nimport type { BunRequest } from 'bun';\nimport { Auth } from './auth.js';\nimport { AuthError } from './errors.js';\nimport { DEFAULT_BASE_PATH } from './options.js';\n\n/**\n * better-auth's handler is a plain `(request: Request) => Promise<Response>`, so\n * mounting it is five one-line routes and nothing else. Every endpoint the library\n * and its plugins declare lives under one wildcard - dunx does not restate, wrap or\n * re-dispatch a single one of them.\n *\n * `Bun.serve` matches `<basePath>/*` natively (verified on Bun 1.3.14), so Bun is\n * still the router. All five verbs are mounted because a plugin may declare any of\n * them; better-auth's own endpoints are `GET` and `POST`.\n *\n * The `Response` is returned untouched - `buildRoutes` passes one straight through,\n * which is what keeps better-auth's `Set-Cookie` headers and redirects intact.\n *\n * `@Public()` at class scope, so all five inherit it - `mergeMeta` reads the class's\n * record under the handler's. Without it a globally installed `SessionGuard` would\n * demand a session from the sign-in endpoint, and no session could ever be created.\n *\n * `inject(Auth)` in a field rather than a constructor parameter, because a bare\n * class in `controllers` is bound as a class provider and would then need\n * `@dunx/transform`'s transform to have run. This way mounting works in an app that\n * never added the preload.\n */\n@Public()\nexport class AuthHandler {\n readonly #auth = inject(Auth);\n #verified = false;\n\n @Get('/*') get({ req }: Input<RouteSchemas>): Promise<Response> {\n return this.#dispatch(req);\n }\n\n @Post('/*') post({ req }: Input<RouteSchemas>): Promise<Response> {\n return this.#dispatch(req);\n }\n\n @Put('/*') put({ req }: Input<RouteSchemas>): Promise<Response> {\n return this.#dispatch(req);\n }\n\n @Patch('/*') patch({ req }: Input<RouteSchemas>): Promise<Response> {\n return this.#dispatch(req);\n }\n\n @Delete('/*') delete({ req }: Input<RouteSchemas>): Promise<Response> {\n return this.#dispatch(req);\n }\n\n /**\n * better-auth resolves an endpoint by comparing the whole pathname to its own\n * `basePath`, so a handler mounted somewhere else answers 404 to everything with no\n * hint as to why. The final path is only knowable once `listen()` has applied the\n * global prefix, which is after this module was configured - so it is checked on\n * the **first** request and never again.\n */\n #dispatch(req: BunRequest): Promise<Response> {\n if (!this.#verified) {\n this.#verified = true;\n const basePath = this.#auth.options.basePath ?? DEFAULT_BASE_PATH;\n const { pathname } = new URL(req.url);\n if (!pathname.startsWith(`${basePath}/`)) {\n throw new AuthError(\n `${pathname} reached the auth handler, but better-auth is configured with ` +\n `basePath ${basePath} and would answer 404 to everything under it. A ` +\n 'global prefix is the usual cause: mount the handler at the path without ' +\n 'the prefix and give better-auth the full one - see AuthOptions.mountAt.',\n );\n }\n }\n return this.#auth.handler(req);\n }\n}\n\n/**\n * The controller `AuthModule` registers, prefixed with `AuthOptions.mountAt`.\n *\n * A subclass rather than `@Controller(...)` on {@link AuthHandler} itself: the prefix\n * is only known once the module is configured, and mutating the shared class from a\n * factory would make two configurations fight over one prefix. The subclass declares\n * nothing of its own and inherits everything - `discoverRoutes` walks the prototype\n * chain for the routes, and `metaOf` and `prefixOf` are plain lookups, so `@Public()`\n * comes down from the base while the prefix stays own to the subclass.\n */\nexport const mountHandler = (mountAt: string): Ctor<AuthHandler> =>\n Controller(mountAt)(class MountedAuthHandler extends AuthHandler {});\n",
10
+ "/**\n * better-auth's `emailAndPassword.password`, backed by `Bun.password`.\n *\n * Applied by `AuthModule` whenever `emailAndPassword` is enabled and no `password`\n * of your own is given. better-auth's default is a **pure-JavaScript scrypt**;\n * `Bun.password` is native bcrypt, which is Rule 1's first half - if Bun ships it,\n * use Bun.\n *\n * Bun pre-hashes the input, so bcrypt's 72-byte cap is a non-issue even for a\n * maximum-length multibyte password.\n *\n * `verify` swallows Bun's `UnsupportedAlgorithm` throw, so a hash produced by a\n * *different* algorithm - a scrypt hash written before this was in place - is a\n * clean authentication failure rather than a 500. Those users must reset their\n * password to get a bcrypt hash; pass your own `password` implementation instead\n * if you are migrating an existing user table and cannot.\n */\nexport const bunPassword = {\n hash: (password: string): Promise<string> =>\n Bun.password.hash(password, { algorithm: 'bcrypt', cost: 10 }),\n verify: async ({\n hash,\n password,\n }: {\n hash: string;\n password: string;\n }): Promise<boolean> => {\n try {\n return await Bun.password.verify(password, hash);\n } catch {\n return false;\n }\n },\n};\n",
11
+ "import type { BetterAuthOptions } from 'better-auth';\nimport { AuthError } from './errors.js';\nimport { bunPassword } from './password.js';\n\n/** better-auth's own default, and where `AuthHandler` mounts unless told otherwise. */\nexport const DEFAULT_BASE_PATH = '/api/auth';\n\n/**\n * One leading slash, no trailing one - the shape `@dunx/http`'s route paths take,\n * so the mount and better-auth's own URL building agree character for character.\n *\n * The root is rejected: the mount is `<basePath>/*`, and at `/` that wildcard would\n * claim every path in the app.\n */\nexport const normalizeBasePath = (basePath: string): string => {\n const normalized = `/${basePath}`.replace(/\\/{2,}/g, '/').replace(/\\/$/, '');\n\n if (normalized.length < 2) {\n throw new AuthError(\n `\"${basePath}\" is not a usable basePath. The handler mounts at ` +\n '<basePath>/*, so at the root it would claim every route in the app. ' +\n `Use something like ${DEFAULT_BASE_PATH}.`,\n );\n }\n return normalized;\n};\n\n/**\n * Bun's native bcrypt in place of better-auth's pure-JavaScript scrypt, unless a\n * `password` of your own is already there. See {@link bunPassword} for the\n * migration caveat.\n */\nconst withBunPassword = <O extends BetterAuthOptions>(options: O): O => {\n const email = options.emailAndPassword;\n if (!email?.enabled || email.password) return options;\n\n // The one cast in the package: TypeScript cannot prove a spread of a generic with\n // one key replaced is still that generic, and widening the return to\n // `BetterAuthOptions` would lose the plugin types `betterAuth()` infers from it.\n return {\n ...options,\n emailAndPassword: { ...email, password: bunPassword },\n } as O;\n};\n\n/**\n * What `betterAuth()` gets called with, where the handler mounts, and the difference\n * between the two. Bound in the container so all of it is readable, and constructed\n * by `AuthModule` rather than by the app.\n */\nexport class AuthOptions<O extends BetterAuthOptions = BetterAuthOptions> {\n readonly options: O;\n\n /**\n * What better-auth matches an incoming pathname against, and builds its URLs from.\n * Normalized here and written back into `options`, so the two cannot drift.\n */\n readonly basePath: string;\n\n /**\n * The **route** path `AuthHandler` is mounted at, which is `basePath` unless the\n * app calls `setGlobalPrefix`. better-auth compares the whole pathname to\n * `basePath`, so with `setGlobalPrefix('api')` the two are different strings for\n * the same URL: mount at `/auth`, and tell better-auth `basePath: '/api/auth'`.\n */\n readonly mountAt: string;\n\n constructor(init: O, mountAt?: string) {\n this.basePath = normalizeBasePath(init.basePath ?? DEFAULT_BASE_PATH);\n this.mountAt =\n mountAt === undefined ? this.basePath : normalizeBasePath(mountAt);\n this.options = withBunPassword({ ...init, basePath: this.basePath });\n }\n}\nObject.defineProperty(AuthOptions, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"init: O\" }, { unresolved: \"mountAt?: string\" }],\n});\n",
12
+ "import {\n provide,\n type AbstractCtor,\n type Deps,\n type DynamicModule,\n type FactoryProvider,\n type Registration,\n RequestContext,\n} from '@dunx/core';\nimport { betterAuth, type BetterAuthOptions } from 'better-auth';\nimport { Auth } from './auth.js';\nimport { AuthContext } from './context.js';\nimport { AuthError } from './errors.js';\nimport { SessionGuard } from './guard.js';\nimport { mountHandler } from './handler.js';\nimport {\n AuthOptions,\n DEFAULT_BASE_PATH,\n normalizeBasePath,\n} from './options.js';\n\nconst build = (options: Registration, mountAt: string): DynamicModule => {\n // Instantiated to the token type rather than left as `typeof Auth`, which is what\n // lets the factory below hand back a plain better-auth instance with no cast.\n const auth: AbstractCtor<Auth> = Auth;\n\n return {\n module: AuthModule,\n controllers: [mountHandler(mountAt)],\n // Every binding declares its own `inject`, so nothing here needs\n // `@dunx/transform`'s transform to have run - the same reason\n // `RequestLoggingMiddleware` and `@dunx/infra/redis`'s `Redis` are bound this way.\n providers: [\n options,\n provide(auth, {\n useFactory: (resolved: AuthOptions) => betterAuth(resolved.options),\n inject: [AuthOptions] as const,\n }),\n provide(AuthContext, {\n useFactory: (context: RequestContext) => new AuthContext(context),\n inject: [RequestContext] as const,\n }),\n provide(SessionGuard, {\n useFactory: (instance: Auth, context: AuthContext) =>\n new SessionGuard(instance, context),\n inject: [auth, AuthContext] as const,\n }),\n ],\n };\n};\n\n/**\n * Binds three tokens and one controller:\n *\n * - `AuthOptions` - what `betterAuth()` was called with, and where it is mounted.\n * - `Auth` - the better-auth instance itself.\n * - `AuthContext` - the authenticated caller, per request.\n * - a prefixed `AuthHandler`, serving every better-auth endpoint under `basePath`.\n *\n * `SessionGuard` is registered as a provider rather than installed as global\n * middleware, because whether it guards the whole app or one controller is the app's\n * decision - pass it to `HttpFactory.create(root, { middleware: [SessionGuard] })`\n * or to `@UseGuards(SessionGuard)`.\n */\nexport class AuthModule {\n /**\n * ```ts\n * AuthModule.forRoot({\n * secret: process.env.BETTER_AUTH_SECRET,\n * baseURL: 'http://localhost:3000',\n * database: drizzleDatabase(connection),\n * emailAndPassword: { enabled: true },\n * plugins: [admin(), bearer()],\n * });\n * ```\n *\n * `const O` is load-bearing: it keeps the literal `plugins` tuple, which is what\n * `betterAuth()` infers the plugin endpoints from - and therefore what\n * `Auth<typeof options>` resolves to at an injection site.\n *\n * `mountAt` only matters under a global prefix - see {@link AuthOptions.mountAt}.\n */\n static forRoot<const O extends BetterAuthOptions>(\n options: O,\n mountAt?: string,\n ): DynamicModule {\n const resolved = new AuthOptions(options, mountAt);\n return build(\n provide(AuthOptions, { useValue: resolved }),\n resolved.mountAt,\n );\n }\n\n /**\n * `forRoot` with the options behind a factory that may await and may inject -\n * which is the only way the secret, the base URL and the database can come from\n * `ConfigService` rather than from module scope:\n *\n * ```ts\n * AuthModule.forRootAsync({\n * useFactory: (config: AppConfigService, connection: DbConnection) => ({\n * secret: config.get('authSecret'),\n * baseURL: config.get('appUrl'),\n * database: drizzleDatabase(connection),\n * emailAndPassword: { enabled: true },\n * }),\n * inject: [AppConfigService, DbConnection],\n * });\n * ```\n *\n * `mountAt` is a second, **synchronous** argument for the same reason\n * `DbModule.forRootAsync` takes its token positionally: the mount is a route in\n * Bun's table, and that table is built before any factory has run. It is only\n * needed under a global prefix - see {@link AuthOptions.mountAt}. Omitting it while\n * the factory returns a non-default `basePath` is a boot error, because that\n * combination could only ever have mounted the handler where better-auth is not\n * looking.\n */\n static forRootAsync<const D extends Deps>(\n provider: FactoryProvider<BetterAuthOptions, D>,\n mountAt?: string,\n ): DynamicModule;\n static forRootAsync(\n provider: FactoryProvider<BetterAuthOptions, Deps>,\n mountAt?: string,\n ): DynamicModule {\n const mounted = normalizeBasePath(mountAt ?? DEFAULT_BASE_PATH);\n\n return build(\n provide(AuthOptions, {\n useFactory: async (\n ...deps: readonly unknown[]\n ): Promise<AuthOptions> => {\n const resolved = new AuthOptions(\n await provider.useFactory(...deps),\n mounted,\n );\n if (mountAt === undefined && resolved.basePath !== mounted) {\n throw new AuthError(\n `The factory returned basePath ${resolved.basePath}, but the handler ` +\n `is mounted at ${mounted} - the table was built before the factory ` +\n 'ran, so it could not follow. Pass the route path as ' +\n \"forRootAsync's second argument.\",\n );\n }\n return resolved;\n },\n inject: provider.inject ?? [],\n }),\n mounted,\n );\n }\n}\n",
13
+ "import type { BetterAuthOptions } from 'better-auth';\n\ntype SecondaryStorage = NonNullable<BetterAuthOptions['secondaryStorage']>;\n\n/**\n * The six commands this needs, restated rather than imported from\n * `@dunx/infra/redis` - same reasoning as {@link DrizzleSource}. A `RedisConnection`\n * satisfies it structurally (its parameters are wider, which is the assignable\n * direction), and a test double is six methods instead of the whole surface.\n */\nexport interface RedisStore {\n get(key: string): Promise<string | null>;\n getdel(key: string): Promise<string | null>;\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<boolean>;\n set(\n key: string,\n value: string,\n options?: { readonly ex?: number },\n ): Promise<string | null>;\n del(key: string): Promise<number>;\n}\n\n/**\n * better-auth's `secondaryStorage` over `Bun.RedisClient`, so sessions, verification\n * values and rate-limit counters live in Redis instead of costing a database round\n * trip on every request.\n *\n * All five methods are implemented, not the three that are mandatory.\n * `getAndDelete` and `increment` are optional in better-auth's interface because most\n * clients cannot do them atomically - `Bun.RedisClient` can, through `GETDEL` and\n * `INCR`, both already on `@dunx/infra/redis`'s contract. Without them better-auth\n * falls back to read-then-delete for single-use credentials, which is a race, and to\n * a non-atomic rate-limit counter.\n *\n * `increment`'s TTL applies on creation only, which is what makes the counter expire\n * a fixed window after the first hit rather than sliding forever: `INCR` returning\n * `1` is the signal that this call created the key.\n *\n * Redis being unreachable is deliberately **not** softened here. Bun's client\n * connects lazily and queues, so a command against a down server rejects and\n * better-auth's own error path is what should see it - a swallowed `null` from `get`\n * would read as \"no session\" and sign every user out.\n */\nexport const redisStorage = (connection: RedisStore): SecondaryStorage => ({\n get: (key) => connection.get(key),\n getAndDelete: (key) => connection.getdel(key),\n increment: async (key, ttl) => {\n const value = await connection.incr(key);\n if (value === 1) await connection.expire(key, ttl);\n return value;\n },\n set: (key, value, ttl) =>\n connection.set(key, value, ttl === undefined ? {} : { ex: ttl }),\n delete: async (key) => {\n await connection.del(key);\n },\n});\n"
14
14
  ],
15
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAMO,MAAM,kBAAkB,SAAS;AAAA,EAC7B,OAAO;AAClB;;;ACYO,MAAe,KAAsD;AAAA,EAO1E,WAAW,GAAG;AAAA,IACZ,IAAI,eAAe,MAAM;AAAA,MACvB,MAAM,IAAI,UACR,8DACE,yEACJ;AAAA,IACF;AAAA;AAYJ;;AC7CA;AACA;AACA;AAAA;AAqBO,MAAM,YAAY;AAAA,EAGM;AAAA,EAFpB,WAAW,IAAI;AAAA,EAExB,WAAW,CAAkB,SAAyB;AAAA,IAAzB;AAAA;AAAA,EAW7B,OAAwD,GAE1C;AAAA,IACZ,OAAO,KAAK,SAAS,SAAS;AAAA;AAAA,EAIhC,OAAwD,GAA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C;AAAA,IAC9B,CAAC,GACD,OACF;AAAA;AAEJ;;AC5GO,IAAM,eAAe,CAAC,gBAA8C;AAAA,EACzE,KAAK,CAAC,QAAQ,WAAW,IAAI,GAAG;AAAA,EAChC,cAAc,CAAC,QAAQ,WAAW,OAAO,GAAG;AAAA,EAC5C,WAAW,OAAO,KAAK,QAAQ;AAAA,IAC7B,MAAM,QAAQ,MAAM,WAAW,KAAK,GAAG;AAAA,IACvC,IAAI,UAAU;AAAA,MAAG,MAAM,WAAW,OAAO,KAAK,GAAG;AAAA,IACjD,OAAO;AAAA;AAAA,EAET,KAAK,CAAC,KAAK,OAAO,QAChB,WAAW,IAAI,KAAK,OAAO,QAAQ,YAAY,CAAC,IAAI,EAAE,IAAI,IAAI,CAAC;AAAA,EACjE,QAAQ,OAAO,QAAQ;AAAA,IACrB,MAAM,WAAW,IAAI,GAAG;AAAA;AAE5B;",
16
+ "debugId": "0637629E506E689864756E2164756E21",
17
17
  "names": []
18
18
  }
package/dist/module.d.ts CHANGED
@@ -3,14 +3,14 @@ import { type BetterAuthOptions } from 'better-auth';
3
3
  /**
4
4
  * Binds three tokens and one controller:
5
5
  *
6
- * - `AuthOptions` what `betterAuth()` was called with, and where it is mounted.
7
- * - `Auth` the better-auth instance itself.
8
- * - `AuthContext` the authenticated caller, per request.
6
+ * - `AuthOptions` - what `betterAuth()` was called with, and where it is mounted.
7
+ * - `Auth` - the better-auth instance itself.
8
+ * - `AuthContext` - the authenticated caller, per request.
9
9
  * - a prefixed `AuthHandler`, serving every better-auth endpoint under `basePath`.
10
10
  *
11
11
  * `SessionGuard` is registered as a provider rather than installed as global
12
12
  * middleware, because whether it guards the whole app or one controller is the app's
13
- * decision pass it to `HttpFactory.create(root, { middleware: [SessionGuard] })`
13
+ * decision - pass it to `HttpFactory.create(root, { middleware: [SessionGuard] })`
14
14
  * or to `@UseGuards(SessionGuard)`.
15
15
  */
16
16
  export declare class AuthModule {
@@ -26,14 +26,14 @@ export declare class AuthModule {
26
26
  * ```
27
27
  *
28
28
  * `const O` is load-bearing: it keeps the literal `plugins` tuple, which is what
29
- * `betterAuth()` infers the plugin endpoints from and therefore what
29
+ * `betterAuth()` infers the plugin endpoints from - and therefore what
30
30
  * `Auth<typeof options>` resolves to at an injection site.
31
31
  *
32
- * `mountAt` only matters under a global prefix see {@link AuthOptions.mountAt}.
32
+ * `mountAt` only matters under a global prefix - see {@link AuthOptions.mountAt}.
33
33
  */
34
34
  static forRoot<const O extends BetterAuthOptions>(options: O, mountAt?: string): DynamicModule;
35
35
  /**
36
- * `forRoot` with the options behind a factory that may await and may inject
36
+ * `forRoot` with the options behind a factory that may await and may inject -
37
37
  * which is the only way the secret, the base URL and the database can come from
38
38
  * `ConfigService` rather than from module scope:
39
39
  *
@@ -52,7 +52,7 @@ export declare class AuthModule {
52
52
  * `mountAt` is a second, **synchronous** argument for the same reason
53
53
  * `DbModule.forRootAsync` takes its token positionally: the mount is a route in
54
54
  * Bun's table, and that table is built before any factory has run. It is only
55
- * needed under a global prefix see {@link AuthOptions.mountAt}. Omitting it while
55
+ * needed under a global prefix - see {@link AuthOptions.mountAt}. Omitting it while
56
56
  * the factory returns a non-default `basePath` is a boot error, because that
57
57
  * combination could only ever have mounted the handler where better-auth is not
58
58
  * looking.
package/dist/options.d.ts CHANGED
@@ -2,7 +2,7 @@ import type { BetterAuthOptions } from 'better-auth';
2
2
  /** better-auth's own default, and where `AuthHandler` mounts unless told otherwise. */
3
3
  export declare const DEFAULT_BASE_PATH = "/api/auth";
4
4
  /**
5
- * One leading slash, no trailing one the shape `@dunx/http`'s route paths take,
5
+ * One leading slash, no trailing one - the shape `@dunx/http`'s route paths take,
6
6
  * so the mount and better-auth's own URL building agree character for character.
7
7
  *
8
8
  * The root is rejected: the mount is `<basePath>/*`, and at `/` that wildcard would
@@ -3,14 +3,14 @@
3
3
  *
4
4
  * Applied by `AuthModule` whenever `emailAndPassword` is enabled and no `password`
5
5
  * of your own is given. better-auth's default is a **pure-JavaScript scrypt**;
6
- * `Bun.password` is native bcrypt, which is Rule 1's first half if Bun ships it,
6
+ * `Bun.password` is native bcrypt, which is Rule 1's first half - if Bun ships it,
7
7
  * use Bun.
8
8
  *
9
9
  * Bun pre-hashes the input, so bcrypt's 72-byte cap is a non-issue even for a
10
10
  * maximum-length multibyte password.
11
11
  *
12
12
  * `verify` swallows Bun's `UnsupportedAlgorithm` throw, so a hash produced by a
13
- * *different* algorithm a scrypt hash written before this was in place is a
13
+ * *different* algorithm - a scrypt hash written before this was in place - is a
14
14
  * clean authentication failure rather than a 500. Those users must reset their
15
15
  * password to get a bcrypt hash; pass your own `password` implementation instead
16
16
  * if you are migrating an existing user table and cannot.
package/dist/redis.d.ts CHANGED
@@ -2,7 +2,7 @@ import type { BetterAuthOptions } from 'better-auth';
2
2
  type SecondaryStorage = NonNullable<BetterAuthOptions['secondaryStorage']>;
3
3
  /**
4
4
  * The six commands this needs, restated rather than imported from
5
- * `@dunx/infra/redis` same reasoning as {@link DrizzleSource}. A `RedisConnection`
5
+ * `@dunx/infra/redis` - same reasoning as {@link DrizzleSource}. A `RedisConnection`
6
6
  * satisfies it structurally (its parameters are wider, which is the assignable
7
7
  * direction), and a test double is six methods instead of the whole surface.
8
8
  */
@@ -23,7 +23,7 @@ export interface RedisStore {
23
23
  *
24
24
  * All five methods are implemented, not the three that are mandatory.
25
25
  * `getAndDelete` and `increment` are optional in better-auth's interface because most
26
- * clients cannot do them atomically `Bun.RedisClient` can, through `GETDEL` and
26
+ * clients cannot do them atomically - `Bun.RedisClient` can, through `GETDEL` and
27
27
  * `INCR`, both already on `@dunx/infra/redis`'s contract. Without them better-auth
28
28
  * falls back to read-then-delete for single-use credentials, which is a race, and to
29
29
  * a non-atomic rate-limit counter.
@@ -34,7 +34,7 @@ export interface RedisStore {
34
34
  *
35
35
  * Redis being unreachable is deliberately **not** softened here. Bun's client
36
36
  * connects lazily and queues, so a command against a down server rejects and
37
- * better-auth's own error path is what should see it a swallowed `null` from `get`
37
+ * better-auth's own error path is what should see it - a swallowed `null` from `get`
38
38
  * would read as "no session" and sign every user out.
39
39
  */
40
40
  export declare const redisStorage: (connection: RedisStore) => SecondaryStorage;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dunx/auth",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Better Auth for dunx: its handler mounted on Bun.serve, a session guard reading @Public() and @Roles(), the caller in async context, and Bun.password hashing",
5
5
  "keywords": [
6
6
  "auth",
@@ -13,7 +13,7 @@
13
13
  "session"
14
14
  ],
15
15
  "homepage": "https://github.com/petarzarkov/dunx/tree/main/packages/auth#readme",
16
- "license": "MIT",
16
+ "license": "Apache-2.0",
17
17
  "author": {
18
18
  "name": "Petar Zarkov",
19
19
  "email": "pzarko1@gmail.com",
@@ -58,8 +58,8 @@
58
58
  "drizzle-orm": "^0.45.2"
59
59
  },
60
60
  "peerDependencies": {
61
- "@dunx/core": "0.1.0",
62
- "@dunx/http": "0.1.0",
61
+ "@dunx/core": "0.1.1",
62
+ "@dunx/http": "0.1.1",
63
63
  "@types/bun": ">=1.3.0",
64
64
  "better-auth": "^1.6.25",
65
65
  "drizzle-orm": "^0.45.2"