@dunx/auth 0.2.14 → 0.3.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/LICENSE CHANGED
@@ -1,201 +1,21 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright [yyyy] [name of copyright owner]
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Petar Zarkov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -198,7 +198,7 @@ Written bare, `Auth` carries better-auth's core endpoints only.
198
198
  better-auth's default hasher is **pure-JavaScript scrypt**. `AuthModule` replaces it
199
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
- Rule 1's first half: if Bun ships it, use Bun.
201
+ The rule is simple: if Bun ships it, use Bun.
202
202
 
203
203
  Bun pre-hashes the input, so bcrypt's 72-byte cap is a non-issue even for a
204
204
  maximum-length multibyte password, and `verify` reads a hash from another algorithm as
package/dist/index.js.map CHANGED
@@ -7,7 +7,7 @@
7
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
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
9
  "import { inject, type Ctor } from '@dunx/core';\nimport {\n ApiHidden,\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 *\n * `@ApiHidden()` because the mount is a wildcard. The route is real and has to be\n * served, but `*` is not an OpenAPI path template, so documenting it produced an\n * invalid entry tagged with this class's internal name - alongside the paths\n * `betterAuthDocument` describes properly, which is where the auth surface should\n * be read from.\n */\nexport const mountHandler = (mountAt: string): Ctor<AuthHandler> =>\n ApiHidden()(\n Controller(mountAt)(class MountedAuthHandler extends AuthHandler {}),\n );\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",
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, and the rule is simple - 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
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
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
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",
@@ -3,7 +3,7 @@
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, and the rule is simple - 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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dunx/auth",
3
- "version": "0.2.14",
3
+ "version": "0.3.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": "Apache-2.0",
16
+ "license": "MIT",
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.2.14",
62
- "@dunx/http": "^0.2.14",
61
+ "@dunx/core": "^0.3.1",
62
+ "@dunx/http": "^0.3.1",
63
63
  "@types/bun": ">=1.3.0",
64
64
  "better-auth": "^1.6.25",
65
65
  "drizzle-orm": "^0.45.2"