@lunora/auth 1.0.0-alpha.257 → 1.0.0-alpha.259

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.
Files changed (31) hide show
  1. package/LICENSE.md +201 -104
  2. package/README.md +3 -3
  3. package/dist/index.d.mts +14 -2
  4. package/dist/index.d.ts +14 -2
  5. package/dist/index.mjs +1 -1
  6. package/dist/migrate.mjs +1 -1
  7. package/dist/packem_shared/AUTH_DO_AUDIT_PATH-CE5w9qqD.mjs +1 -0
  8. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs +1 -0
  9. package/dist/packem_shared/LunoraAuthAdminError-Be0xQHfn.mjs +1 -0
  10. package/dist/packem_shared/auth-do-BdD-ChAx.mjs +1 -0
  11. package/dist/packem_shared/authDiscoveryPaths-BtKCs_3V.mjs +1 -0
  12. package/dist/packem_shared/{createAuth-CLeBjzDR.mjs → createAuth-Dioo_-mD.mjs} +1 -1
  13. package/dist/packem_shared/createDoAuthWiring-fkSnTL5M.mjs +1 -0
  14. package/dist/packem_shared/handleAuthRequest-Id9Vv_Tk.mjs +1 -0
  15. package/dist/packem_shared/{mcp-CgX1hTOv.mjs → mcp-CK5XkDFp.mjs} +1 -1
  16. package/dist/packem_shared/resolveSessionIdentity-Bk63iwnv.mjs +1 -0
  17. package/dist/packem_shared/sensitive-fields-DqtvDy_d.mjs +1 -0
  18. package/dist/packem_shared/{worker.d-Dnw0s0_j.d.mts → worker.d-CJoVlNo2.d.mts} +8 -7
  19. package/dist/packem_shared/{worker.d-BfQTtOho.d.ts → worker.d-z1x-8MNm.d.ts} +8 -7
  20. package/dist/plugins.mjs +1 -1
  21. package/dist/worker.d.mts +1 -1
  22. package/dist/worker.d.ts +1 -1
  23. package/dist/worker.mjs +1 -1
  24. package/package.json +2 -2
  25. package/dist/packem_shared/AUTH_DO_AUDIT_PATH-CRtEqPlF.mjs +0 -1
  26. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs +0 -1
  27. package/dist/packem_shared/LunoraAuthAdminError-uhKG1MgQ.mjs +0 -1
  28. package/dist/packem_shared/auth-do-Dkk1jOb6.mjs +0 -1
  29. package/dist/packem_shared/authDiscoveryPaths-B14lM14u.mjs +0 -1
  30. package/dist/packem_shared/createDoAuthWiring-DIxLcjKQ.mjs +0 -1
  31. package/dist/packem_shared/resolveSessionIdentity-ChaUVZSy.mjs +0 -1
package/LICENSE.md CHANGED
@@ -1,108 +1,205 @@
1
- # Functional Source License, Version 1.1, Apache 2.0 Future License
2
1
 
3
- ## Abbreviation
4
-
5
- FSL-1.1-Apache-2.0
6
-
7
- ## Notice
8
-
9
- Copyright 2026 anolilab and contributors
10
-
11
- ## Terms and Conditions
12
-
13
- ### Licensor ("We")
14
-
15
- The party offering the Software under these Terms and Conditions.
16
-
17
- ### The Software
18
-
19
- The "Software" is each version of the software that we make available under
20
- these Terms and Conditions, as indicated by our inclusion of these Terms and
21
- Conditions with the Software.
22
-
23
- ### License Grant
24
-
25
- Subject to your compliance with this License Grant and the Patents,
26
- Redistribution and Trademark clauses below, we hereby grant you the right to
27
- use, copy, modify, create derivative works, publicly perform, publicly display
28
- and redistribute the Software for any Permitted Purpose identified below.
29
-
30
- ### Permitted Purpose
31
-
32
- A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
- means making the Software available to others in a commercial product or service
34
- that:
35
-
36
- 1. substitutes for the Software;
37
-
38
- 2. substitutes for any other product or service we offer using the Software that
39
- exists as of the date we make the Software available; or
40
-
41
- 3. offers the same or substantially similar functionality as the Software.
42
-
43
- Permitted Purposes specifically include using the Software:
44
-
45
- 1. for your internal use and access;
46
-
47
- 2. for non-commercial education;
48
-
49
- 3. for non-commercial research; and
50
-
51
- 4. in connection with professional services that you provide to a licensee using
52
- the Software in accordance with these Terms and Conditions.
53
-
54
- ### Patents
55
-
56
- To the extent your use for a Permitted Purpose would necessarily infringe our
57
- patents, the license grant above includes a license under our patents. If you
58
- make a claim against any party that the Software infringes or contributes to the
59
- infringement of any patent, then your patent license to the Software ends
60
- immediately.
61
-
62
- ### Redistribution
63
-
64
- The Terms and Conditions apply to all copies, modifications and derivatives of
65
- the Software.
66
-
67
- If you redistribute any copies, modifications or derivatives of the Software,
68
- you must include a copy of or a link to these Terms and Conditions and not
69
- remove any copyright notices provided in or with the Software.
70
-
71
- ### Disclaimer
72
-
73
- THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
- IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
- PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
-
77
- IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
- SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, EVEN
79
- IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
-
81
- ### Trademarks
82
-
83
- Except for displaying the License Details and identifying us as the origin of
84
- the Software, you have no right under these Terms and Conditions to use our
85
- trademarks, trade names, service marks or product names.
86
-
87
- ## Grant of Future License
88
-
89
- We hereby irrevocably grant you an additional license to use the Software under
90
- the Apache License, Version 2.0 that is effective on the second anniversary of
91
- the date we make the Software available. On or after that date, you may use the
92
- Software under the Apache License, Version 2.0, in which case the following will
93
- apply:
94
-
95
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
- this file except in compliance with the License.
97
-
98
- You may obtain a copy of the License at
99
-
100
- http://www.apache.org/licenses/LICENSE-2.0
101
-
102
- Unless required by applicable law or agreed to in writing, software distributed
103
- under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
- CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
- specific language governing permissions and limitations under the License.
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
106
203
 
107
204
  <!-- DEPENDENCIES -->
108
205
  <!-- /DEPENDENCIES -->
package/README.md CHANGED
@@ -15,7 +15,7 @@
15
15
  <div align="center">
16
16
 
17
17
  [![typescript-image][typescript-badge]][typescript-url]
18
- [![FSL-1.1-Apache-2.0 licence][license-badge]][license]
18
+ [![Apache-2.0 licence][license-badge]][license]
19
19
  [![npm version][npm-version-badge]][npm-version]
20
20
  [![npm downloads][npm-downloads-badge]][npm-downloads]
21
21
  [![PRs Welcome][prs-welcome-badge]][prs-welcome]
@@ -208,11 +208,11 @@ This is an open source project and will always remain free to use. If you think
208
208
 
209
209
  ## License
210
210
 
211
- The Lunora auth package is open-sourced software licensed under the [FSL-1.1-Apache-2.0][license].
211
+ The Lunora auth package is open-sourced software licensed under the [Apache-2.0][license].
212
212
 
213
213
  <!-- badges -->
214
214
 
215
- [license-badge]: https://img.shields.io/badge/license-FSL--1.1--Apache--2.0-blue.svg?style=for-the-badge
215
+ [license-badge]: https://img.shields.io/badge/license-Apache--2.0-blue.svg?style=for-the-badge
216
216
  [license]: https://github.com/anolilab/lunora/blob/alpha/LICENSE.md
217
217
  [npm-version-badge]: https://img.shields.io/npm/v/@lunora/auth?style=for-the-badge
218
218
  [npm-version]: https://www.npmjs.com/package/@lunora/auth
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { D as DoStorageLike } from "./packem_shared/adapter.d-CaPwF2v3.mjs";
2
2
  export { l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-CaPwF2v3.mjs";
3
- export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthCapabilities, type e as AuthConfigInfo, type f as AuthInvitation, type g as AuthJurisdiction, type h as AuthJurisdictionMove, type i as AuthMember, type j as AuthMoveResult, type k as AuthMoveTableReport, type l as AuthNamespaceLike, type m as AuthOrgRole, type n as AuthOrganization, type o as AuthPage, type p as AuthPasskey, type q as AuthSignUpInvitation, type r as AuthTeam, type s as AuthTeamMember, type t as AuthTimestamp, type u as AuthUserFieldSpec, type C as CreateAuthAdminOptions, D as DEFAULT_AUTH_BASE_PATH, type v as DoAuthWiring, type w as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, x as LunoraAuthAdminError, type S as SessionIdentity, y as authDiscoveryPaths, z as authDiscoveryPathsFor, B as createAuthAdmin, E as createDoAuthWiring, F as handleAuthDiscoveryRequest, G as handleAuthRequest, H as resolveSessionIdentity } from "./packem_shared/worker.d-Dnw0s0_j.mjs";
3
+ export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthCapabilities, type e as AuthConfigInfo, type f as AuthInvitation, type g as AuthJurisdiction, type h as AuthJurisdictionMove, type i as AuthMember, type j as AuthMoveResult, type k as AuthMoveTableReport, type l as AuthNamespaceLike, type m as AuthOrgRole, type n as AuthOrganization, type o as AuthPage, type p as AuthPasskey, type q as AuthSignUpInvitation, type r as AuthTeam, type s as AuthTeamMember, type t as AuthTimestamp, type u as AuthUserFieldSpec, type C as CreateAuthAdminOptions, type D as DoAuthWiring, type v as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, w as LunoraAuthAdminError, type S as SessionIdentity, x as authDiscoveryPaths, y as authDiscoveryPathsFor, z as createAuthAdmin, B as createDoAuthWiring, E as handleAuthDiscoveryRequest, F as handleAuthRequest, G as resolveSessionIdentity } from "./packem_shared/worker.d-CJoVlNo2.mjs";
4
4
  import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.mjs";
5
5
  export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, ensureAuthAuditTable, readAuthAuditLog } from "./audit.mjs";
6
6
  import { createAuthMiddleware } from 'better-auth/api';
@@ -376,6 +376,18 @@ declare const withEmailGate: (options: BetterAuthOptions, config?: EmailGateHook
376
376
  * vars is production too — fail closed either way.
377
377
  */
378
378
  declare const isDevEnvironment: (env: Record<string, unknown>) => boolean;
379
+ /**
380
+ * Where `@lunora/auth` serves its routes, for the packages that must know without
381
+ * importing it. `@lunora/config` routes these paths to the Worker ahead of the
382
+ * static assets (`assets.run_worker_first`) but cannot import `@lunora/auth`,
383
+ * which depends on it, so both read them here.
384
+ */
385
+ /**
386
+ * Default basePath used by better-auth's client + handler. Override via the
387
+ * second argument of `handleAuthRequest` if you mount the auth routes somewhere
388
+ * else.
389
+ */
390
+ declare const DEFAULT_AUTH_BASE_PATH: string;
379
391
  /**
380
392
  * The cleanup statements, in execution order: every blocking index, then the column.
381
393
  *
@@ -445,4 +457,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
445
457
  * with the same 60s cookie cache as `rolling`.
446
458
  */
447
459
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
448
- export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
460
+ export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { D as DoStorageLike } from "./packem_shared/adapter.d-CElAPJ1U.js";
2
2
  export { l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-CElAPJ1U.js";
3
- export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthCapabilities, type e as AuthConfigInfo, type f as AuthInvitation, type g as AuthJurisdiction, type h as AuthJurisdictionMove, type i as AuthMember, type j as AuthMoveResult, type k as AuthMoveTableReport, type l as AuthNamespaceLike, type m as AuthOrgRole, type n as AuthOrganization, type o as AuthPage, type p as AuthPasskey, type q as AuthSignUpInvitation, type r as AuthTeam, type s as AuthTeamMember, type t as AuthTimestamp, type u as AuthUserFieldSpec, type C as CreateAuthAdminOptions, D as DEFAULT_AUTH_BASE_PATH, type v as DoAuthWiring, type w as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, x as LunoraAuthAdminError, type S as SessionIdentity, y as authDiscoveryPaths, z as authDiscoveryPathsFor, B as createAuthAdmin, E as createDoAuthWiring, F as handleAuthDiscoveryRequest, G as handleAuthRequest, H as resolveSessionIdentity } from "./packem_shared/worker.d-BfQTtOho.js";
3
+ export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthCapabilities, type e as AuthConfigInfo, type f as AuthInvitation, type g as AuthJurisdiction, type h as AuthJurisdictionMove, type i as AuthMember, type j as AuthMoveResult, type k as AuthMoveTableReport, type l as AuthNamespaceLike, type m as AuthOrgRole, type n as AuthOrganization, type o as AuthPage, type p as AuthPasskey, type q as AuthSignUpInvitation, type r as AuthTeam, type s as AuthTeamMember, type t as AuthTimestamp, type u as AuthUserFieldSpec, type C as CreateAuthAdminOptions, type D as DoAuthWiring, type v as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, w as LunoraAuthAdminError, type S as SessionIdentity, x as authDiscoveryPaths, y as authDiscoveryPathsFor, z as createAuthAdmin, B as createDoAuthWiring, E as handleAuthDiscoveryRequest, F as handleAuthRequest, G as resolveSessionIdentity } from "./packem_shared/worker.d-z1x-8MNm.js";
4
4
  import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.js";
5
5
  export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, ensureAuthAuditTable, readAuthAuditLog } from "./audit.js";
6
6
  import { createAuthMiddleware } from 'better-auth/api';
@@ -376,6 +376,18 @@ declare const withEmailGate: (options: BetterAuthOptions, config?: EmailGateHook
376
376
  * vars is production too — fail closed either way.
377
377
  */
378
378
  declare const isDevEnvironment: (env: Record<string, unknown>) => boolean;
379
+ /**
380
+ * Where `@lunora/auth` serves its routes, for the packages that must know without
381
+ * importing it. `@lunora/config` routes these paths to the Worker ahead of the
382
+ * static assets (`assets.run_worker_first`) but cannot import `@lunora/auth`,
383
+ * which depends on it, so both read them here.
384
+ */
385
+ /**
386
+ * Default basePath used by better-auth's client + handler. Override via the
387
+ * second argument of `handleAuthRequest` if you mount the auth routes somewhere
388
+ * else.
389
+ */
390
+ declare const DEFAULT_AUTH_BASE_PATH: string;
379
391
  /**
380
392
  * The cleanup statements, in execution order: every blocking index, then the column.
381
393
  *
@@ -445,4 +457,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
445
457
  * with the same 60s cookie cache as `rolling`.
446
458
  */
447
459
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
448
- export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
460
+ export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{l as r,a as o,b as a}from"./packem_shared/adapter-CBZ17jKi.mjs";import{LunoraAuthAdminError as s,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-uhKG1MgQ.mjs";import{AUTH_AUDIT_TABLE as A,appendAuthAuditEntry as m,createAuthAuditReader as h,ensureAuthAuditTable as l,readAuthAuditLog as p}from"./audit.mjs";import{authAuditHook as f,buildAuditEntry as x,eventForPath as E,withAuthAudit as D}from"./packem_shared/authAuditHook-DPTKdjBe.mjs";import{R as S,I as c,a as v,L as _}from"./packem_shared/auth-do-Dkk1jOb6.mjs";import{createAuth as U,resolveAuthOptions as y}from"./packem_shared/createAuth-CLeBjzDR.mjs";import{authDiscoveryPaths as P,authDiscoveryPathsFor as L,handleAuthDiscoveryRequest as g}from"./packem_shared/authDiscoveryPaths-B14lM14u.mjs";import{authDoColumnAdditions as O,authDoSchemaStatements as w}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as F}from"./packem_shared/createDoAuthWiring-DIxLcjKQ.mjs";import{emailGateDatabaseHooks as k,withEmailGate as q}from"./packem_shared/emailGateDatabaseHooks-BYLUpiN_.mjs";import{assertEmailAllowed as G,classifyEmail as M,emailGateMiddleware as B,loadEmailDomainLists as W}from"./email-guard.mjs";import{default as Y}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{DEFAULT_AUTH_BASE_PATH as z,handleAuthRequest as J}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";import{createSignUpInvitation as Q,listSignUpInvitations as X,pruneSignUpInvitations as Z,revokeSignUpInvitation as $}from"./packem_shared/createSignUpInvitation-DHZL9fNl.mjs";import{legacyIssuerCleanupStatements as et}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as ot,withAuthPlugins as at}from"./middleware.mjs";import{default as st}from"./schema.mjs";import{sessionPresets as nt,validateSessionPolicy as At}from"./packem_shared/sessionPresets-C867Mlo4.mjs";import{resolveSessionIdentity as ht}from"./packem_shared/resolveSessionIdentity-ChaUVZSy.mjs";import{c as pt,d as dt}from"./packem_shared/sql-store-uMubPYI9.mjs";import{createMemoryAuthStore as xt,matchesWhere as Et}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as Tt,verifyTurnstile as St}from"./turnstile.mjs";import{verifyTurnstileMiddleware as vt}from"./turnstile-middleware.mjs";export{A as AUTH_AUDIT_TABLE,S as AUTH_DO_AUDIT_PATH,c as AUTH_DO_SECRET_HEADER,v as AUTH_DO_SESSION_PATH,z as DEFAULT_AUTH_BASE_PATH,s as LunoraAuthAdminError,_ as LunoraAuthDO,ot as LunoraAuthHeadersError,Tt as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,G as assertEmailAllowed,f as authAuditHook,P as authDiscoveryPaths,L as authDiscoveryPathsFor,O as authDoColumnAdditions,w as authDoSchemaStatements,st as authTables,x as buildAuditEntry,M as classifyEmail,U as createAuth,u as createAuthAdmin,h as createAuthAuditReader,F as createDoAuthWiring,xt as createMemoryAuthStore,Q as createSignUpInvitation,pt as createSqlAuthStore,dt as d1Executor,k as emailGateDatabaseHooks,B as emailGateMiddleware,l as ensureAuthAuditTable,E as eventForPath,g as handleAuthDiscoveryRequest,J as handleAuthRequest,Y as isDevEnvironment,et as legacyIssuerCleanupStatements,X as listSignUpInvitations,W as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,Et as matchesWhere,Z as pruneSignUpInvitations,p as readAuthAuditLog,y as resolveAuthOptions,ht as resolveSessionIdentity,$ as revokeSignUpInvitation,nt as sessionPresets,At as validateSessionPolicy,St as verifyTurnstile,vt as verifyTurnstileMiddleware,D as withAuthAudit,at as withAuthPlugins,q as withEmailGate};
1
+ import{l as r,a as o,b as a}from"./packem_shared/adapter-CBZ17jKi.mjs";import{LunoraAuthAdminError as s,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-Be0xQHfn.mjs";import{AUTH_AUDIT_TABLE as A,appendAuthAuditEntry as m,createAuthAuditReader as p,ensureAuthAuditTable as h,readAuthAuditLog as l}from"./audit.mjs";import{authAuditHook as f,buildAuditEntry as x,eventForPath as E,withAuthAudit as D}from"./packem_shared/authAuditHook-DPTKdjBe.mjs";import{R as S,I as c,a as v,L as _}from"./packem_shared/auth-do-BdD-ChAx.mjs";import{createAuth as U,resolveAuthOptions as y}from"./packem_shared/createAuth-Dioo_-mD.mjs";import{authDiscoveryPaths as P,authDiscoveryPathsFor as L,handleAuthDiscoveryRequest as g}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as O,authDoSchemaStatements as w}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as F}from"./packem_shared/createDoAuthWiring-fkSnTL5M.mjs";import{emailGateDatabaseHooks as k,withEmailGate as q}from"./packem_shared/emailGateDatabaseHooks-BYLUpiN_.mjs";import{assertEmailAllowed as G,classifyEmail as M,emailGateMiddleware as B,loadEmailDomainLists as W}from"./email-guard.mjs";import{default as Y}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{handleAuthRequest as z}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{createSignUpInvitation as K,listSignUpInvitations as Q,pruneSignUpInvitations as X,revokeSignUpInvitation as Z}from"./packem_shared/createSignUpInvitation-DHZL9fNl.mjs";import{legacyIssuerCleanupStatements as tt}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as rt,withAuthPlugins as ot}from"./middleware.mjs";import{default as it}from"./schema.mjs";import{sessionPresets as ut,validateSessionPolicy as nt}from"./packem_shared/sessionPresets-C867Mlo4.mjs";import{resolveSessionIdentity as mt}from"./packem_shared/resolveSessionIdentity-Bk63iwnv.mjs";import{c as ht,d as lt}from"./packem_shared/sql-store-uMubPYI9.mjs";import{createMemoryAuthStore as ft,matchesWhere as xt}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as Dt,verifyTurnstile as Tt}from"./turnstile.mjs";import{verifyTurnstileMiddleware as ct}from"./turnstile-middleware.mjs";import{DEFAULT_AUTH_BASE_PATH as _t}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";export{A as AUTH_AUDIT_TABLE,S as AUTH_DO_AUDIT_PATH,c as AUTH_DO_SECRET_HEADER,v as AUTH_DO_SESSION_PATH,_t as DEFAULT_AUTH_BASE_PATH,s as LunoraAuthAdminError,_ as LunoraAuthDO,rt as LunoraAuthHeadersError,Dt as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,G as assertEmailAllowed,f as authAuditHook,P as authDiscoveryPaths,L as authDiscoveryPathsFor,O as authDoColumnAdditions,w as authDoSchemaStatements,it as authTables,x as buildAuditEntry,M as classifyEmail,U as createAuth,u as createAuthAdmin,p as createAuthAuditReader,F as createDoAuthWiring,ft as createMemoryAuthStore,K as createSignUpInvitation,ht as createSqlAuthStore,lt as d1Executor,k as emailGateDatabaseHooks,B as emailGateMiddleware,h as ensureAuthAuditTable,E as eventForPath,g as handleAuthDiscoveryRequest,z as handleAuthRequest,Y as isDevEnvironment,tt as legacyIssuerCleanupStatements,Q as listSignUpInvitations,W as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,xt as matchesWhere,X as pruneSignUpInvitations,l as readAuthAuditLog,y as resolveAuthOptions,mt as resolveSessionIdentity,Z as revokeSignUpInvitation,ut as sessionPresets,nt as validateSessionPolicy,Tt as verifyTurnstile,ct as verifyTurnstileMiddleware,D as withAuthAudit,ot as withAuthPlugins,q as withEmailGate};
package/dist/migrate.mjs CHANGED
@@ -1 +1 @@
1
- import{getAuthTablesWithResolvedIndexes as w,invalidateSchemaChecks as y}from"@better-auth/core/db/internal";import{LunoraError as R}from"@lunora/errors";import{betterAuth as _}from"better-auth";import{getMigrations as l}from"better-auth/db/migration";import{q as c}from"./packem_shared/quote-identifier-CGiYFBvY.mjs";import{resolveAuthOptions as A,prepareAuthOptions as M}from"./packem_shared/createAuth-CLeBjzDR.mjs";import{schemaDeclaresIssuer as x,legacyIssuerCleanupStatements as T,indexesReferencingIssuer as N}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";const C=/pragma_index_list\s*\(/iu,D=/sqlite_master/iu,S=/^["`[]|["\]`]$/gu,O=/\s+/u,P=/create\s+unique\s+index/iu,L=/\bwhere\b/iu,U=t=>C.test(t)&&D.test(t),q=t=>(t.trim().split(O)[0]??"").replaceAll(S,"").trim(),v=t=>{const e=t.indexOf("(");if(e===-1)return{columns:[],tail:""};let s=0;for(let n=e;n<t.length;n+=1){const a=t[n];if(a==="(")s+=1;else if(a===")"&&(s-=1,s===0))return{columns:t.slice(e+1,n).split(",").map(o=>q(o)).filter(o=>o!==""),tail:t.slice(n+1)}}return{columns:[],tail:""}},W=async t=>{const e=t.prepare("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index'"),{results:s}=await e.all(),n=[];for(const a of s??[]){const o=a.name,r=a.tbl_name,i=a.sql;if(typeof o!="string"||typeof r!="string")continue;if(typeof i!="string"){n.push({columnPosition:0,indexName:o,isPartial:0,isUnique:1,tableName:r});continue}const d=P.test(i)?1:0,{columns:h,tail:b}=v(i),E=L.test(b)?1:0;for(const[g,I]of h.entries())n.push({columnName:I,columnPosition:g,indexName:o,isPartial:E,isUnique:d,tableName:r})}return n},F=t=>{const e=async()=>{const n=await W(t);return{meta:{},results:n,success:!0}},s={all:e,bind:()=>s,run:e};return s},H=t=>new Proxy(t,{get(e,s,n){if(s==="prepare")return o=>U(o)?F(e):e.prepare(o);const a=Reflect.get(e,s,n);return typeof a=="function"?a.bind(e):a}}),m=t=>typeof t=="object"&&t!==null&&typeof t.prepare=="function"&&typeof t.batch=="function",p=t=>{const{database:e}=t;if(!(e&&typeof e!="function"))throw new R("AUTH_MIGRATOR_UNSUPPORTED",e?"@lunora/auth: this auth instance's `database` is a custom adapter, which better-auth's migrator cannot drive.":"@lunora/auth: this auth instance has no `database`, so better-auth's migrator has nothing to introspect.")},f=t=>m(t.database)?{...t,database:H(t.database)}:t,$=async(t,e)=>{const s=c("t");try{return await t.prepare(`SELECT ${s}.${c("issuer")} FROM ${c(e)} AS ${s} LIMIT 0`).run(),!0}catch{return!1}},Q=async t=>{const{database:e}=t,{tables:s}=w(t),{account:n}=s;if(n!==void 0&&!x(Object.entries(n.fields).map(([a,o])=>o.fieldName??a))&&m(e)&&await $(e,n.modelName))try{const{results:a}=await e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?").bind(n.modelName).all();await e.batch(T(n.modelName,N(a)).map(o=>e.prepare(o)))}catch(a){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",a)}},j=t=>{const{database:e}=t;typeof e=="object"&&e!==null&&y(e)},u=new WeakMap,J=async t=>{const{options:e}=t;p(e);const s=u.get(e);if(s){await s;return}const n=(async()=>{const{runMigrations:a}=await l(f(e));await a(),await Q(e),j(e)})();u.set(e,n);try{await n}catch(a){throw u.delete(e),a}},V=async t=>{const e=A(t);p(e);const{compileMigrations:s}=await l(f(e));return s()},Z=t=>_(M(t));export{V as compileMigrationsSql,Z as createMigrationAuth,J as ensureMigrated};
1
+ import{getAuthTablesWithResolvedIndexes as w,invalidateSchemaChecks as y}from"@better-auth/core/db/internal";import{LunoraError as R}from"@lunora/errors";import{betterAuth as _}from"better-auth";import{getMigrations as l}from"better-auth/db/migration";import{q as c}from"./packem_shared/quote-identifier-CGiYFBvY.mjs";import{resolveAuthOptions as A,prepareAuthOptions as M}from"./packem_shared/createAuth-Dioo_-mD.mjs";import{schemaDeclaresIssuer as x,legacyIssuerCleanupStatements as T,indexesReferencingIssuer as N}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";const C=/pragma_index_list\s*\(/iu,D=/sqlite_master/iu,S=/^["`[]|["\]`]$/gu,O=/\s+/u,P=/create\s+unique\s+index/iu,L=/\bwhere\b/iu,U=t=>C.test(t)&&D.test(t),q=t=>(t.trim().split(O)[0]??"").replaceAll(S,"").trim(),v=t=>{const e=t.indexOf("(");if(e===-1)return{columns:[],tail:""};let s=0;for(let n=e;n<t.length;n+=1){const a=t[n];if(a==="(")s+=1;else if(a===")"&&(s-=1,s===0))return{columns:t.slice(e+1,n).split(",").map(o=>q(o)).filter(o=>o!==""),tail:t.slice(n+1)}}return{columns:[],tail:""}},W=async t=>{const e=t.prepare("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index'"),{results:s}=await e.all(),n=[];for(const a of s??[]){const o=a.name,r=a.tbl_name,i=a.sql;if(typeof o!="string"||typeof r!="string")continue;if(typeof i!="string"){n.push({columnPosition:0,indexName:o,isPartial:0,isUnique:1,tableName:r});continue}const d=P.test(i)?1:0,{columns:h,tail:b}=v(i),E=L.test(b)?1:0;for(const[g,I]of h.entries())n.push({columnName:I,columnPosition:g,indexName:o,isPartial:E,isUnique:d,tableName:r})}return n},F=t=>{const e=async()=>{const n=await W(t);return{meta:{},results:n,success:!0}},s={all:e,bind:()=>s,run:e};return s},H=t=>new Proxy(t,{get(e,s,n){if(s==="prepare")return o=>U(o)?F(e):e.prepare(o);const a=Reflect.get(e,s,n);return typeof a=="function"?a.bind(e):a}}),m=t=>typeof t=="object"&&t!==null&&typeof t.prepare=="function"&&typeof t.batch=="function",p=t=>{const{database:e}=t;if(!(e&&typeof e!="function"))throw new R("AUTH_MIGRATOR_UNSUPPORTED",e?"@lunora/auth: this auth instance's `database` is a custom adapter, which better-auth's migrator cannot drive.":"@lunora/auth: this auth instance has no `database`, so better-auth's migrator has nothing to introspect.")},f=t=>m(t.database)?{...t,database:H(t.database)}:t,$=async(t,e)=>{const s=c("t");try{return await t.prepare(`SELECT ${s}.${c("issuer")} FROM ${c(e)} AS ${s} LIMIT 0`).run(),!0}catch{return!1}},Q=async t=>{const{database:e}=t,{tables:s}=w(t),{account:n}=s;if(n!==void 0&&!x(Object.entries(n.fields).map(([a,o])=>o.fieldName??a))&&m(e)&&await $(e,n.modelName))try{const{results:a}=await e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?").bind(n.modelName).all();await e.batch(T(n.modelName,N(a)).map(o=>e.prepare(o)))}catch(a){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",a)}},j=t=>{const{database:e}=t;typeof e=="object"&&e!==null&&y(e)},u=new WeakMap,J=async t=>{const{options:e}=t;p(e);const s=u.get(e);if(s){await s;return}const n=(async()=>{const{runMigrations:a}=await l(f(e));await a(),await Q(e),j(e)})();u.set(e,n);try{await n}catch(a){throw u.delete(e),a}},V=async t=>{const e=A(t);p(e);const{compileMigrations:s}=await l(f(e));return s()},Z=t=>_(M(t));export{V as compileMigrationsSql,Z as createMigrationAuth,J as ensureMigrated};
@@ -0,0 +1 @@
1
+ import{I as _,L as S,R as T,a as s}from"./auth-do-BdD-ChAx.mjs";import"./adapter-CBZ17jKi.mjs";import"../audit.mjs";import"./createAuth-Dioo_-mD.mjs";import"./authDiscoveryPaths-BtKCs_3V.mjs";import"./authDoColumnAdditions-UwF3Rl41.mjs";import"./handleAuthRequest-Id9Vv_Tk.mjs";import"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import"./resolveSessionIdentity-Bk63iwnv.mjs";export{_ as INTERNAL_SECRET_HEADER,S as LunoraAuthDO,T as READ_AUDIT_PATH,s as RESOLVE_SESSION_PATH};
@@ -0,0 +1 @@
1
+ const o="/api/auth",t="/.well-known/oauth-protected-resource",E="/.well-known/oauth-authorization-server";export{E as AUTHORIZATION_SERVER_PREFIX,o as DEFAULT_AUTH_BASE_PATH,t as PROTECTED_RESOURCE_PREFIX};
@@ -0,0 +1 @@
1
+ import{LunoraError as M}from"@lunora/errors";import{getAuthTables as b}from"better-auth/db";import{revokeSignUpInvitation as U,createSignUpInvitation as R}from"./createSignUpInvitation-DHZL9fNl.mjs";import{S as N}from"./sensitive-fields-DqtvDy_d.mjs";class f extends M{constructor(c,h){super(h,c,{name:"LunoraAuthAdminError"})}}const D=50,E=500,O=3600,z=O*24,T=100*365*24*60*60,L=2880*60*1e3,k=[{field:"userId",model:"member"},{field:"userId",model:"teamMember"},{field:"userId",model:"passkey"},{field:"userId",model:"twoFactor"},{field:"userId",model:"oauthAccessToken"},{field:"userId",model:"oauthRefreshToken"},{field:"userId",model:"oauthConsent"},{field:"userId",model:"deviceCode"},{field:"userId",model:"walletAddress"},{field:"inviterId",model:"invitation"}],P=o=>Math.min(Math.max(Math.trunc(o??D),1),E),C=o=>Math.max(0,Math.trunc(o??0)),u=o=>{const c={};for(const[h,l]of Object.entries(o))N.has(h)||(c[h]=l instanceof Date?l.getTime():l);return c},g=o=>Array.isArray(o)?o.join(","):o,S=o=>o.toLowerCase().replaceAll(/[^\da-z]+/g,"-").replaceAll(/^-|-$/g,""),B=new Set(["banExpires","banned","banReason","createdAt","email","emailVerified","id","name","role","updatedAt"]),F={displayUsername:"username",phoneNumber:"phone-number",phoneNumberVerified:"phone-number",username:"username"},G=o=>o==="boolean"||o==="date"||o==="number"?o:"string",V=o=>{const c=[];for(const[h,l]of Object.entries(o))l.input===!1||l.references!==void 0||B.has(h)||c.push({name:h,plugin:F[h],required:l.required===!0,type:G(l.type),unique:l.unique===!0});return c},I=o=>typeof o=="string"&&o.includes("owner"),_=async(o,c)=>{const l=(await o.adapter.findMany({model:"member",where:[{field:"userId",value:c}]})).filter(p=>I(p.role)&&typeof p.organizationId=="string").map(p=>p.organizationId);if(l.length===0)return;const A=await Promise.all(l.map(async p=>o.adapter.findMany({model:"member",where:[{field:"organizationId",value:p}]}))),n=l.find((p,v)=>!A[v]?.some(e=>e.userId!==c&&I(e.role)));if(n!==void 0)throw new f(`user is the last owner of organization ${n} — transfer ownership or delete the organization first`,"LAST_ORGANIZATION_OWNER")},j=o=>{if(o instanceof f)return o;const c=o,h=c?.body?.code??c?.code??"AUTH_ADMIN_ERROR",l=c?.body?.message??c?.message??"auth admin operation failed";return new f(l,h)},X=(o,c={})=>{const h=o.$context,l=c.features??{},A=e=>{const a=new Set((e.plugins??[]).map(i=>i.id)),t=i=>a.has(i);return{accounts:l.accounts??!0,admin:l.admin??t("admin"),inviteOnly:l.inviteOnly??t("lunora-invite-only"),organization:l.organization??t("organization"),passkey:l.passkey??t("passkey"),twoFactor:l.twoFactor??t("two-factor")}},n=async e=>{try{return await e(await h)}catch(a){throw j(a)}},p=e=>u(e),v=async(e,a,t)=>{const i=t.where&&t.where.length>0?t.where:void 0,[r,s]=await Promise.all([e.adapter.findMany({limit:P(t.limit),model:a,offset:C(t.offset),sortBy:t.sortBy,where:i}),e.adapter.count({model:a,where:i})]);return{rows:r.map(d=>u(d)),total:s}};return{banUser:({expiresInSeconds:e,reason:a,userId:t})=>n(async i=>{let r=null;if(e!==void 0){if(!Number.isInteger(e)||e<=0)throw new f("expiresInSeconds must be a positive finite integer","INVALID_BAN_SECONDS");const d=Math.min(e,T);r=new Date(Date.now()+d*1e3)}const s=await i.internalAdapter.updateUser(t,{banExpires:r,banned:!0,banReason:a??"No reason"});return await i.internalAdapter.deleteUserSessions(t),p(s)}),cancelInvitation:({invitationId:e})=>n(async a=>{await a.adapter.delete({model:"invitation",where:[{field:"id",value:e}]})}),capabilities:()=>n(e=>Promise.resolve(A(e.options))),addMember:({organizationId:e,role:a,userId:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:e,role:a===void 0||a===""?"member":a,userId:t},model:"member"});return u(r)}),addTeamMember:({teamId:e,userId:a})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,teamId:e,userId:a},model:"teamMember"});return u(i)}),config:()=>n(e=>{const a=e.options,t=A(a),i=new Set((a.plugins??[]).map(m=>m.id)),r=b(a),s=a.session??{},d=a.rateLimit??{};return Promise.resolve({capabilities:t,emailAndPassword:a.emailAndPassword?.enabled??!1,organization:{enabled:t.organization,roles:!!r.organizationRole,teams:!!r.team},plugins:[...i].toSorted((m,w)=>m.localeCompare(w)),rateLimit:{enabled:d.enabled??!1,max:d.max,window:d.window},session:{cookieCache:s.cookieCache?.enabled,expiresIn:s.expiresIn,freshAge:s.freshAge,updateAge:s.updateAge},socialProviders:Object.keys(a.socialProviders??{}).toSorted((m,w)=>m.localeCompare(w)),userFields:V(r.user?.fields??{})})}),createOrganization:({logo:e,metadata:a,name:t,ownerId:i,slug:r})=>n(async s=>{const d=S(r!==void 0&&r!==""?r:t);if(d==="")throw new f("could not derive a slug from the organization name","ORG_SLUG_INVALID");if(await s.adapter.findOne({model:"organization",where:[{field:"slug",value:d}]}))throw new f("an organization with this slug already exists","ORG_SLUG_TAKEN");const w=await s.adapter.create({data:{createdAt:new Date,logo:e===void 0||e===""?void 0:e,metadata:a===void 0?void 0:JSON.stringify(a),name:t,slug:d},model:"organization"});return i!==void 0&&i!==""&&await s.adapter.create({data:{createdAt:new Date,organizationId:w.id,role:"owner",userId:i},model:"member"}),u(w)}),createOrgRole:({organizationId:e,permission:a,role:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:e,permission:JSON.stringify(a),role:t},model:"organizationRole"});return u(r)}),createTeam:({name:e,organizationId:a})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,name:e,organizationId:a},model:"team"});return u(i)}),deleteOrganization:({organizationId:e})=>n(async a=>{const t=b(a.options);if(await a.adapter.deleteMany({model:"member",where:[{field:"organizationId",value:e}]}),await a.adapter.deleteMany({model:"invitation",where:[{field:"organizationId",value:e}]}),t.team){const i=await a.adapter.findMany({model:"team",where:[{field:"organizationId",value:e}]});for(const r of i)await a.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:r.id}]});await a.adapter.deleteMany({model:"team",where:[{field:"organizationId",value:e}]})}t.organizationRole&&await a.adapter.deleteMany({model:"organizationRole",where:[{field:"organizationId",value:e}]}),await a.adapter.delete({model:"organization",where:[{field:"id",value:e}]})}),deleteOrgRole:({roleId:e})=>n(async a=>{await a.adapter.delete({model:"organizationRole",where:[{field:"id",value:e}]})}),inviteMember:({email:e,inviterId:a,organizationId:t,role:i})=>n(async r=>{let s=a;if(s===void 0||s===""){const m=await r.adapter.findMany({model:"member",where:[{field:"organizationId",value:t}]});s=(m.find(y=>typeof y.role=="string"&&y.role.includes("owner"))??m[0])?.userId}if(s===void 0||s==="")throw new f("provide an inviter — the organization has no members to attribute the invitation to","INVITER_REQUIRED");const d=await r.adapter.create({data:{createdAt:new Date,email:e.toLowerCase(),expiresAt:new Date(Date.now()+L),inviterId:s,organizationId:t,role:i===void 0||i===""?"member":i,status:"pending"},model:"invitation"});return u(d)}),listOrgRoles:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"organizationRole",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listTeamMembers:({limit:e,offset:a,teamId:t})=>n(i=>v(i,"teamMember",{limit:e,offset:a,where:[{field:"teamId",value:t}]})),listTeams:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"team",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),removeTeam:({teamId:e})=>n(async a=>{await a.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:e}]}),await a.adapter.delete({model:"team",where:[{field:"id",value:e}]})}),removeTeamMember:({teamMemberId:e})=>n(async a=>{await a.adapter.delete({model:"teamMember",where:[{field:"id",value:e}]})}),updateMemberRole:({memberId:e,role:a})=>n(async t=>{const i=await t.adapter.update({model:"member",update:{role:g(a)},where:[{field:"id",value:e}]});return u(i??{id:e,role:g(a)})}),updateOrganization:({logo:e,metadata:a,name:t,organizationId:i,slug:r})=>n(async s=>{const d={};if(t!==void 0&&(d.name=t),r!==void 0&&r!==""&&(d.slug=S(r)),e!==void 0&&(d.logo=e===""?void 0:e),a!==void 0&&(d.metadata=JSON.stringify(a)),Object.keys(d).length===0)return u({id:i});const m=await s.adapter.update({model:"organization",update:d,where:[{field:"id",value:i}]});return u(m??{id:i})}),updateOrgRole:({permission:e,roleId:a})=>n(async t=>{const i=await t.adapter.update({model:"organizationRole",update:{permission:JSON.stringify(e),updatedAt:new Date},where:[{field:"id",value:a}]});return u(i??{id:a,permission:JSON.stringify(e)})}),updateTeam:({name:e,teamId:a})=>n(async t=>{const i=await t.adapter.update({model:"team",update:{name:e,updatedAt:new Date},where:[{field:"id",value:a}]});return u(i??{id:a,name:e})}),createUser:({data:e,email:a,name:t,password:i,role:r})=>n(async s=>{const d=a.toLowerCase();if(await s.internalAdapter.findUserByEmail(d))throw new f("a user with this email already exists","USER_ALREADY_EXISTS");const m={...e};delete m.isAnonymous;const w=await s.internalAdapter.createUser({email:d,name:t,role:r===void 0?void 0:g(r),...m},{method:"admin"});if(i!==void 0&&i!==""){const y=await s.password.hash(i);await s.internalAdapter.linkAccount({accountId:w.id,password:y,providerId:"credential",userId:w.id})}return p(w)}),deletePasskey:({passkeyId:e})=>n(async a=>{await a.adapter.delete({model:"passkey",where:[{field:"id",value:e}]})}),disableTwoFactor:({userId:e})=>n(async a=>{await a.adapter.deleteMany({model:"twoFactor",where:[{field:"userId",value:e}]}),await a.internalAdapter.updateUser(e,{twoFactorEnabled:!1})}),impersonateUser:({userId:e})=>n(async a=>{const t=await a.internalAdapter.findUserById(e);if(!t)throw new f("user not found","USER_NOT_FOUND");const i=c.impersonationSeconds;let r=O;if(i!==void 0){if(!Number.isInteger(i)||!Number.isFinite(i)||i<=0)throw new f("impersonationSeconds must be a positive finite integer","INVALID_IMPERSONATION_SECONDS");r=Math.min(i,z)}const s=new Date(Date.now()+r*1e3),d=await a.internalAdapter.createSession(e,!0,{expiresAt:s,impersonatedBy:c.impersonatedBy??e},!0);return{expiresAt:d.expiresAt instanceof Date?d.expiresAt.getTime():s.getTime(),token:d.token,user:p(t)}}),listAccounts:({userId:e})=>n(async a=>(await a.adapter.findMany({model:"account",where:[{field:"userId",value:e}]})).map(i=>u(i))),listInvitations:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"invitation",{limit:e,offset:a,where:[{field:"organizationId",value:t}]})),createSignUpInvitation:({email:e,expiresInSeconds:a,invitedBy:t})=>n(async()=>{const i=await R(o,{email:e,expiresInSeconds:a,invitedBy:t});return{...u({...i}),token:i.token}}),listSignUpInvitations:({limit:e,offset:a})=>n(t=>v(t,"signUpInvitation",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"}})),revokeSignUpInvitation:({email:e})=>n(async()=>U(o,{email:e})),listMembers:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"member",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listOrganizations:({limit:e,offset:a})=>n(t=>v(t,"organization",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"}})),listPasskeys:({userId:e})=>n(async a=>(await a.adapter.findMany({model:"passkey",where:[{field:"userId",value:e}]})).map(i=>u(i))),listSessions:({limit:e,offset:a,userId:t})=>n(i=>v(i,"session",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:t===void 0||t===""?void 0:[{field:"userId",value:t}]})),listUsers:({filterField:e,filterValue:a,limit:t,offset:i,search:r,searchField:s,sortBy:d,sortDirection:m})=>n(w=>{const y=[];return r!==void 0&&r!==""&&y.push({field:s??"email",operator:"contains",value:r}),a!==void 0&&y.push({field:e??"email",operator:"eq",value:a}),v(w,"user",{limit:t,offset:i,sortBy:{direction:m??"desc",field:d??"createdAt"},where:y})}),removeMember:({memberId:e})=>n(async a=>{await a.adapter.delete({model:"member",where:[{field:"id",value:e}]})}),removeUser:({userId:e})=>n(async a=>{const t=b(a.options);t.member&&await _(a,e),await Promise.all(k.filter(({model:i})=>t[i]).map(({field:i,model:r})=>a.adapter.deleteMany({model:r,where:[{field:i,value:e}]}))),await a.internalAdapter.deleteUserSessions(e),await a.internalAdapter.deleteUser(e)}),revokeUserSession:({sessionId:e})=>n(async a=>{const t=await a.adapter.findOne({model:"session",where:[{field:"id",value:e}]});t?.token&&await a.internalAdapter.deleteSession(t.token)}),revokeUserSessions:({userId:e})=>n(async a=>{await a.internalAdapter.deleteUserSessions(e)}),setRole:({role:e,userId:a})=>n(async t=>{const i=await t.internalAdapter.updateUser(a,{role:g(e)});return p(i)}),setUserPassword:({newPassword:e,userId:a})=>n(async t=>{const i=t.password.config.minPasswordLength,r=t.password.config.maxPasswordLength;if(e.length<i)throw new f(`password must be at least ${i.toString()} characters`,"PASSWORD_TOO_SHORT");if(e.length>r)throw new f(`password must be at most ${r.toString()} characters`,"PASSWORD_TOO_LONG");if(!await t.internalAdapter.findUserById(a))throw new f("user not found","USER_NOT_FOUND");const d=(await t.internalAdapter.findAccounts(a)).some(w=>w.providerId==="credential");if(!d&&t.options.emailAndPassword?.enabled!==!0)throw new f("email/password sign-in is disabled for this deployment","EMAIL_PASSWORD_DISABLED");const m=await t.password.hash(e);d?await t.internalAdapter.updatePassword(a,m):await t.internalAdapter.linkAccount({accountId:a,password:m,providerId:"credential",userId:a})}),unbanUser:({userId:e})=>n(async a=>{const t=await a.internalAdapter.updateUser(e,{banExpires:null,banned:!1,banReason:null});return p(t)}),unlinkAccount:({accountId:e,userId:a})=>n(async t=>{await t.adapter.delete({model:"account",where:[{field:"id",value:e},{connector:"AND",field:"userId",value:a}]})}),updateUser:({data:e,userId:a})=>n(async t=>{const i=await t.internalAdapter.updateUser(a,e);return p(i)})}};export{f as LunoraAuthAdminError,X as createAuthAdmin};
@@ -0,0 +1 @@
1
+ import{getAuthTablesWithResolvedIndexes as U}from"@better-auth/core/db/internal";import{LunoraError as w,toErrorBody as Y}from"@lunora/errors";import{d as C,b as K}from"./adapter-CBZ17jKi.mjs";import{AUTH_AUDIT_TABLE as Q,ensureAuthAuditTable as z,createAuthAuditReader as Z}from"../audit.mjs";import{resolveAuthOptions as ee,createAuth as te}from"./createAuth-Dioo_-mD.mjs";import{handleAuthDiscoveryRequest as ne}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{authDoSchemaStatements as re,authDoColumnAdditions as se}from"./authDoColumnAdditions-UwF3Rl41.mjs";import{handleAuthRequest as oe}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{decodeWire as I,encodeWire as v}from"@lunora/wire";import{q as a}from"./quote-identifier-CGiYFBvY.mjs";import{schemaDeclaresIssuer as ie,legacyIssuerCleanupStatements as ae,indexesReferencingIssuer as ce}from"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{parseClaimNames as ue,resolveSessionIdentity as le}from"./resolveSessionIdentity-Bk63iwnv.mjs";const fe=(t,e)=>{const n=Math.max(t.length,e.length);let r=t.length^e.length;for(let s=0;s<n;s+=1){const o=s<t.length?t.charCodeAt(s):0,i=s<e.length?e.charCodeAt(s):0;r|=o^i}return r===0},j=2166136261,F=16777619,k=(t,e=j)=>{let n=e;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,F);return(n>>>0).toString(16).padStart(8,"0")},me=t=>`${k(t,j)}${k(t,F)}`,Ee="/__lunora/auth/move",T="__lunora_auth_move__",R="__lunora_auth_move_rows__",y="__lunora_auth_purged__",x=100,de=16,pe=100,he=2n**64n,H=t=>t.startsWith("sqlite_")||t.startsWith("_cf_")||t===T||t===R||t===y,P=async(t,e)=>t.transaction(async()=>Promise.resolve().then(e)),m=(t,e,...n)=>[...t.sql.exec(e,...n)],u=(t,e,...n)=>{[...t.sql.exec(e,...n)]},_=t=>m(t,"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map(e=>String(e.name)).filter(e=>!H(e)),q=(t,e)=>m(t,"SELECT name, pk FROM pragma_table_info(?)",e).map(n=>({name:String(n.name),pk:Number(n.pk)})),g=(t,e)=>q(t,e).map(({name:n})=>n),W=(t,e)=>{const n=q(t,e),r=n.filter(({pk:s})=>s>0).toSorted((s,o)=>s.pk-o.pk).map(({name:s})=>s);return r.length>0?r:n.map(({name:s})=>s)},B=(t,e)=>Number(m(t,`SELECT count(*) AS n FROM ${a(e)}`)[0]?.n??0),V=t=>JSON.stringify(v(t)),b=(t,e)=>BigInt(`0x${me(V(e.map(n=>t[n]??null)))}`),G=(t,e)=>{let n=0,r=0n;for(const s of t)n+=1,r=(r+e(s))%he;return`${String(n)}:${r.toString(16)}`},X=(t,e)=>{const n=g(t,e).toSorted((r,s)=>r.localeCompare(s));return G(t.sql.exec(`SELECT * FROM ${a(e)}`),r=>b(r,n))},Te=t=>_(t).map(e=>{const n=m(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,r=m(t,"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL",e).map(s=>({name:String(s.name),sql:String(s.sql)}));return{columns:g(t,e),indexes:r,name:e,rows:B(t,e),sql:typeof n=="string"?n:""}}),M=(t,e)=>{if(typeof e!="string"||!_(t).includes(e))throw new TypeError(`unknown table ${JSON.stringify(e)}`);return e},Se=(t,e,n)=>{const r=m(t,`SELECT rowid AS "__lunora_rowid__", * FROM ${a(e)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,n,x),s=r.at(-1)?.__lunora_rowid__;return{last:typeof s=="number"?s:void 0,rows:r.map(({__lunora_rowid__:o,...i})=>i)}},we=t=>g(t,T).length>0,O=t=>we(t)?Object.fromEntries(m(t,`SELECT tbl, after, done, pass, cols, watermark FROM ${a(T)}`).map(e=>[String(e.tbl),{after:Number(e.after),columns:JSON.parse(String(e.cols)),done:e.done===1,pass:Number(e.pass),watermark:Number(e.watermark)}])):{},Re=(t,e,n)=>G(t.sql.exec(`SELECT h FROM ${a(R)} WHERE tbl = ? AND pass = ?`,e,n),r=>BigInt(`0x${String(r.h)}`)),Ne=t=>{u(t,`CREATE TABLE IF NOT EXISTS ${a(T)} (tbl TEXT NOT NULL PRIMARY KEY, after INTEGER NOT NULL, done INTEGER NOT NULL, pass INTEGER NOT NULL, cols TEXT NOT NULL, watermark INTEGER NOT NULL DEFAULT 0)`),u(t,`CREATE TABLE IF NOT EXISTS ${a(R)} (tbl TEXT NOT NULL, k TEXT NOT NULL, h TEXT NOT NULL, pass INTEGER NOT NULL, PRIMARY KEY (tbl, k))`)},Ae=(t,e,n)=>{if(!_(t).includes(e))return 0;const r=W(t,e).map(s=>`u.${a(s)}`).join(", ");return Number(m(t,`SELECT count(*) AS n FROM ${a(e)} u WHERE u.rowid > ? AND NOT EXISTS (SELECT 1 FROM ${a(R)} c WHERE c.tbl = ? AND c.k = json_array(${r}))`,n,e)[0]?.n??0)},_e=/^CREATE TABLE /iu,Oe=/^CREATE (?:UNIQUE )?INDEX /iu,ge=(t,e,n)=>{if(H(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!_e.test(e.sql)||e.indexes.some(({sql:s})=>!Oe.test(s)))throw new TypeError(`refusing unexpected DDL for ${JSON.stringify(e.name)}`);if(n.has(e.name)){const s=new Set(g(t,e.name));for(const o of e.columns.filter(i=>!s.has(i)))u(t,`ALTER TABLE ${a(e.name)} ADD COLUMN ${a(o)}`)}else u(t,e.sql);const r=new Set(m(t,"SELECT name FROM sqlite_master WHERE type = 'index'").map(s=>String(s.name)));for(const s of e.indexes.filter(({name:o})=>!r.has(o)))u(t,s.sql)},Le=(t,e,n)=>{Ne(t);const r=Ae(t,n.userTable,O(t)[n.userTable]?.watermark??0);if(r>0&&!n.force)throw new w("AUTH_MOVE_TARGET_NOT_EMPTY",`the pinned auth object has ${String(r)} user(s) the copy did not write; copying into it would merge two user bases — pass force to copy anyway`,{data:{users:r}});const s=new Set(_(t)),o=O(t);for(const c of e){ge(t,c,s);const f=o[c.name],E=JSON.stringify(c.columns.toSorted((d,p)=>d.localeCompare(p)));f===void 0?u(t,`INSERT INTO ${a(T)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,c.name,E):u(t,`UPDATE ${a(T)} SET cols = ? WHERE tbl = ?`,E,c.name)}u(t,`UPDATE ${a(T)} SET watermark = (SELECT coalesce(max(rowid), 0) FROM ${a(n.userTable)}) WHERE tbl = ?`,n.userTable);const i=O(t);return{cursors:Object.fromEntries(e.map(({name:c})=>[c,i[c]?.after??0])),done:Object.fromEntries(e.map(({name:c})=>[c,i[c]?.done??!1])),targetRows:Object.fromEntries(e.map(({name:c})=>[c,B(t,c)]))}},J=(t,e,n,r,s)=>m(t,`SELECT ${s.map(o=>a(o)).join(", ")} FROM ${a(e)} WHERE ${n.map(o=>`${a(o)} IS ?`).join(" AND ")} LIMIT 1`,...r)[0],$=(t,e)=>{if(!e)throw new w("AUTH_MOVE_CONFLICT",`a row copied into ${t} collides with a row the pinned auth object holds on its own — nothing from this page was written; pass force to keep the pinned object's rows`,{data:{table:t}});return"conflicts"},ye=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),$e=(t,e)=>{if(e.prior!==void 0)return $(e.table,e.force);try{u(t,`INSERT INTO ${a(e.table)} (${e.columns.map(n=>a(n)).join(", ")}) VALUES (${e.columns.map(()=>"?").join(", ")})`,...e.columns.map(n=>e.row[n]))}catch(n){if(!ye(n))throw n;return $(e.table,e.force)}return"copied"},be=(t,e,n)=>{const r=b(n,e.columns).toString(16);return r===e.h?"unchanged":e.prior===void 0||r!==e.prior?$(e.table,e.force):(u(t,`UPDATE ${a(e.table)} SET ${e.columns.map(s=>`${a(s)} = ?`).join(", ")} WHERE ${e.keys.map(s=>`${a(s)} IS ?`).join(" AND ")}`,...e.columns.map(s=>e.row[s]),...e.key),"updated")},Ie=(t,e,n,r)=>{const{force:s,keys:o,pass:i}=r,c=Object.keys(n).toSorted((S,L)=>S.localeCompare(L));if(c.length+o.length>pe)throw new TypeError(`${e} has too many columns to copy`);const f=o.map(S=>n[S]??null),E=V(f),d=b(n,c).toString(16),p=m(t,`SELECT h FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,E)[0]?.h,l={columns:c,force:s,h:d,key:f,keys:o,prior:typeof p=="string"?p:void 0,row:n,table:e},h=l.prior===d?void 0:J(t,e,o,f,c);let N="unchanged";return l.prior!==d&&(N=h===void 0?$e(t,l):be(t,l,h)),u(t,`INSERT INTO ${a(R)} (tbl, k, h, pass) VALUES (?, ?, ?, ?) ON CONFLICT (tbl, k) DO UPDATE SET h = excluded.h, pass = excluded.pass`,e,E,d,i),N},De=(t,e,n)=>{const{counts:r,force:s,keys:o,marker:i}=n,c=m(t,`SELECT k, h FROM ${a(R)} WHERE tbl = ? AND pass < ?`,e,i.pass);for(const f of c){const E=I(JSON.parse(String(f.k))),d=J(t,e,o,E,i.columns);d!==void 0&&(b(d,i.columns).toString(16)===String(f.h)?(u(t,`DELETE FROM ${a(e)} WHERE ${o.map(p=>`${a(p)} IS ?`).join(" AND ")}`,...E),r.deleted+=1):r[$(e,s)]+=1),u(t,`DELETE FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,String(f.k))}},Ue=async(t,e,n)=>{const r=O(t)[e];if(r===void 0)throw new TypeError(`table ${JSON.stringify(e)} was not part of this move`);return P(t,()=>{const s={conflicts:0,copied:0,deleted:0,unchanged:0,updated:0},o=W(t,e);for(const i of n.rows)s[Ie(t,e,i,{force:n.force,keys:o,pass:r.pass})]+=1;return n.final&&De(t,e,{counts:s,force:n.force,keys:o,marker:r}),u(t,`UPDATE ${a(T)} SET after = ?, done = ? WHERE tbl = ?`,n.last,n.final?1:0,e),s})},Ce=async(t,e)=>{const n=_(t);return await P(t,()=>{const r=n.filter(o=>e[o]===void 0);if(r.length>0)throw new w("AUTH_MOVE_INCOMPLETE",`refusing to purge the un-pinned auth object: ${r.join(", ")} not fully copied — run the copy to done: true first`,{data:{unfinished:r}});const s=n.filter(o=>X(t,o)!==e[o]);if(s.length>0)throw new w("AUTH_MOVE_SOURCE_CHANGED",`refusing to purge the un-pinned auth object: ${s.join(", ")} changed since it was copied — run the copy again to carry the changes, then purge`,{data:{changed:s}});for(const o of n)u(t,`DROP TABLE ${a(o)}`);u(t,`CREATE TABLE IF NOT EXISTS ${a(y)} (at INTEGER NOT NULL)`),u(t,`INSERT INTO ${a(y)} (at) VALUES (?)`,Date.now())}),{dropped:n}},ke=t=>{if(g(t,y).length>0)throw new w("AUTH_MOVE_SOURCE_PURGED","the un-pinned auth object was purged after its tables were copied; anything in it now is new, and copying it would delete the pinned object's users")},Me=new Set(["fingerprints","manifest","page","purge"]),ve=(t,e,n)=>{e.prepare();const r=O(t);return{copied:n?Object.fromEntries(Object.entries(r).map(([s,o])=>[s,Re(t,s,o.pass)])):{},markers:r,order:e.order()}},je=(t,e)=>{for(const n of e)u(t,`UPDATE ${a(T)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},Fe=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],xe=t=>{const e=t instanceof Error?t.message:String(t);for(const n of Fe){const r=n.exec(e);if(r)return r[0]}return t instanceof Error?t.name:"unknown"},He=async(t,e,n)=>{switch(Me.has(String(e.op))&&ke(t),e.op){case"begin":return n.prepare(),Le(t,e.tables,{force:e.force===!0,userTable:n.userTable()});case"fingerprints":return{fingerprints:Object.fromEntries(_(t).map(r=>[r,X(t,r)]))};case"manifest":return{tables:Te(t)};case"page":{const r=Se(t,M(t,e.table),Number(e.after??0));return{last:r.last,rows:v(r.rows)}}case"purge":{const r=await Ce(t,e.expected??{});return n.onPurge(),r}case"rescan":return je(t,e.tables??[]);case"status":return ve(t,n,e.fingerprints===!0);case"write":return Ue(t,M(t,e.table),{final:e.final===!0,force:e.force===!0,last:Number(e.last),rows:I(e.rows)});default:throw new TypeError(`unknown move op ${JSON.stringify(e.op)}`)}},Pe=async(t,e,n)=>{try{return await He(t,e,n)}catch(r){if(r instanceof w)throw r;console.error("@lunora/auth: auth move step failed",r);const s=String(e.op),o=typeof e.table=="string"?e.table:void 0,i=xe(r);throw new w("AUTH_MOVE_FAILED",`auth move ${s}${o===void 0?"":` on ${o}`} failed: ${i}`,{data:{cause:i,op:s,...o===void 0?{}:{table:o}}})}},qe=(t,e)=>{const n=r=>{const s=e.first.indexOf(r);if(s!==-1)return s;const o=e.last.indexOf(r);return o===-1?e.first.length:e.first.length+1+o};return t.toSorted((r,s)=>n(r.name)-n(s.name)||r.name.localeCompare(s.name))},We=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),it=t=>{const e=async(n,r)=>{const s=await t(n,r);if(!s.ok){let o={};try{const i=await s.json();typeof i.error=="object"&&i.error!==null&&(o=i.error)}catch{}throw new w(o.code??"AUTH_MOVE_FAILED",o.message??`auth move ${String(r.op)} on the ${n} object failed (${String(s.status)})`,{data:o.data,status:s.status})}return s.json()};return{copy:async(n={})=>{const r=n.force===!0,s=await e("target",{op:"status"}),{tables:o}=await e("source",{op:"manifest"}),i=await e("target",{force:r,op:"begin",tables:o}),c=[];let f=0;for(const l of qe(o,s.order)){const h=We(l,i.targetRows[l.name]??0);let N=i.cursors[l.name]??0;for(c.push(h);;){if(f>=de)return{done:!1,tables:c};f+=1;const S=await e("source",{after:N,op:"page",table:l.name}),L=I(S.rows),D=L.length<x;if(L.length===0&&i.done[l.name]===!0)break;const A=await e("target",{final:D,force:r,last:S.last??N,op:"write",rows:S.rows,table:l.name});if(h.conflicts+=A.conflicts,h.copied+=A.copied,h.deleted+=A.deleted,h.unchanged+=A.unchanged,h.updated+=A.updated,h.targetRows+=A.copied-A.deleted,N=S.last??N,D)break}}const{fingerprints:E}=await e("source",{op:"fingerprints"}),d=await e("target",{fingerprints:!0,op:"status"}),p=Object.keys(E).filter(l=>d.copied[l]!==E[l]);return p.length>0&&await e("target",{op:"rescan",tables:p}),{done:p.length===0,tables:c}},purge:async()=>{const{copied:n,markers:r}=await e("target",{fingerprints:!0,op:"status"}),s=Object.fromEntries(Object.entries(r).filter(([,o])=>o.done).map(([o])=>[o,n[o]]));return e("source",{expected:s,op:"purge"})}}},Be="/__lunora/auth/session",Ve="/__lunora/auth/audit",Ge="x-lunora-auth-do-secret",Xe=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return{error:"body must be a JSON object"};const e={};for(const[n,r]of Object.entries(t))if(n==="limit"||n==="sinceSeq"){if(typeof r!="number"||!Number.isFinite(r))return{error:`"${n}" must be a finite number`};e[n]=r}else if(n==="actorId"||n==="event"){if(typeof r!="string")return{error:`"${n}" must be a string`};e[n]=r}else return{error:`unknown audit read option "${n}"`};return{options:e}};class at{#n;#a;#c;#e;#t;#r=!1;#s={first:["user"],last:[]};constructor(e,n,r={}){this.#e=e.storage,this.#n=C(e.storage),this.#c=n,this.#a=r}#o(){if(this.#t!==void 0)return this.#t;const e=this.#c(),n=ee(e),{tables:r}=U(n);if(this.#s={first:[r.user?.modelName??"user",r.account?.modelName??"account",r.session?.modelName??"session"],last:[Q,r.rateLimit?.modelName??"rateLimit"]},!this.#r){for(const s of re(n))[...this.#e.sql.exec(s)];for(const s of se(n,o=>this.#u(o)))[...this.#e.sql.exec(s)];this.#l(n),this.#r=!0}return this.#t=te({...e,database:K(this.#e)}),this.#t}#u(e){return[...this.#e.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(r=>String(r.name))}#l(e){const{tables:n}=U(e),{account:r}=n;if(r===void 0)return;const s=Object.entries(r.fields).map(([o,i])=>i.fieldName??o);if(!(ie(s)||!this.#u(r.modelName).includes("issuer")))try{const o=[...this.#e.sql.exec("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",r.modelName)].map(i=>({name:String(i.name),sql:typeof i.sql=="string"?i.sql:void 0}));for(const i of ae(r.modelName,ce(o)))[...this.#e.sql.exec(i)]}catch(o){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",o)}}async#f(e){if(!this.#i(e))return Response.json({error:"unauthorized"},{status:401});let n;try{n=await e.json()}catch{return Response.json({error:"invalid body"},{status:400})}const r=Xe(n??{});if("error"in r)return Response.json({error:r.error},{status:400});await z(this.#n);const s=await Z(this.#n).read(r.options);return Response.json({entries:s})}async#m(e){if(e.method!=="POST"||!this.#i(e))return Response.json({error:"unauthorized"},{status:401});try{const n=await e.json(),r=await Pe(this.#e,n,{onPurge:()=>{this.#r=!1,this.#t=void 0,this.#n=C(this.#e)},order:()=>this.#s,prepare:()=>{this.#o()},userTable:()=>this.#s.first[0]??"user"});return Response.json(r)}catch(n){const{body:r,redacted:s,status:o}=Y(n,{encodeData:i=>i,fallbackCode:"AUTH_MOVE_FAILED",redactedMessage:"auth move failed"});return s&&console.error("@lunora/auth: auth move failed",n),Response.json({error:r},{status:o})}}#i(e){const{internalSecret:n}=this.#a;if(n===void 0||n==="")return!1;const r=e.headers.get(Ge);return r!==null&&fe(r,n)}async#E(e){if(!this.#i(e))return Response.json({error:"unauthorized"},{status:401});const n=ue(new URL(e.url).searchParams.get("claims"));return Response.json(await le(this.#o(),e.headers,n)??{})}async fetch(e){const n=new URL(e.url);if(n.pathname===Be)return this.#E(e);if(n.pathname===Ve)return this.#f(e);if(n.pathname===Ee)return this.#m(e);const r=this.#o();return await oe(r,e)??await ne(r,e)??Response.json({error:"not an auth route"},{status:404})}}export{Ge as I,at as L,Ee as M,Ve as R,Be as a,it as c};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";import{AUTHORIZATION_SERVER_PREFIX as p,PROTECTED_RESOURCE_PREFIX as l,DEFAULT_AUTH_BASE_PATH as f}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const d=Symbol.for("lunora.auth.mcpResource"),i=/\/$/u,R=t=>`${l}${new URL(t).pathname.replace(i,"")}`,m=t=>`${p}${t.replace(i,"")}`,v=t=>{if(typeof t=="string")try{const e=new URL(t).pathname.replace(i,"");return e===""?void 0:e}catch{return}},y=(t,e,r)=>{const s=e.find(o=>o.id==="jwt")?.options,n=r?.disableJwtPlugin===!0?void 0:s?.jwt?.issuer;if(typeof n=="string")try{return new URL(n).pathname}catch{}return v(t.baseURL)??t.basePath??f},w=t=>(Array.isArray(t)?t:[]).map(e=>typeof e=="object"&&e!==null?e.identifier:e).filter(e=>typeof e=="string"),E=t=>{const e=t[d];if(typeof e=="string")return e;const r=t.options,s=[...new Set(w(r?.resources))];if(s.length===1)return s[0];if(s.length>1&&Array.isArray(r?.clientRegistrationDefaultResources))throw new h("AUTH_MCP_RESOURCE_AMBIGUOUS",`@lunora/auth cannot tell which of the provider's resources (${s.join(", ")}) is the MCP resource. Use \`mcp\` from "@lunora/auth/plugins", which records it, and pass the plugin object as is.`)},u=t=>{const e=t.plugins??[],r=e.filter(o=>o.id==="oauth-provider");if(r.length===0)return[];const s=r.map(o=>E(o)).filter(o=>o!==void 0).map(o=>R(o)),n=y(t,e,r[0]?.options);return[...new Set([...s,m(n)])]},a=new WeakMap,S=(t,e)=>{let r=a.get(t);return r===void 0&&(r=u(t.options(e)),a.set(t,r)),r},A=t=>t?.status===404?void 0:t,c=new WeakMap,P=(t,e)=>(t.method==="GET"||t.method==="HEAD")&&e.has(new URL(t.url).pathname),_=async(t,e)=>{let r=c.get(t);if(r===void 0&&(r=new Set(u(t.options)),c.set(t,r)),!!P(e,r))return A(await t.handler(e))};export{d as MCP_RESOURCE_KEY,u as authDiscoveryPaths,S as authDiscoveryPathsFor,m as authorizationServerPath,_ as handleAuthDiscoveryRequest,P as isDiscoveryRequest,R as protectedResourcePath,A as unlessNotFound};
@@ -1 +1 @@
1
- import{LunoraError as a}from"@lunora/errors";import{isAPIError as u,createAuthMiddleware as h,getIP as f}from"better-auth/api";import{betterAuth as m}from"better-auth/minimal";import{o as g}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{authDiscoveryPaths as p}from"./authDiscoveryPaths-B14lM14u.mjs";import{setCookieCache as A}from"better-auth/cookies";import{validateSessionPolicy as E}from"./sessionPresets-C867Mlo4.mjs";const d="lunora-org-session-refresh",w=new Set(["/organization/accept-invitation","/organization/create","/organization/delete","/organization/leave","/organization/remove-member"]),S=new Set(["/organization/get-full-organization","/organization/get-organization"]),v=()=>({hooks:{after:[{handler:h(async e=>{const t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!(typeof t!="string"||t===""))try{const r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt.getTime()<=Date.now())return;const o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);await A(e,r,!!o)}catch(r){console.error("@lunora/auth: organization session cache refresh failed",r)}}),matcher:e=>{if(e.context.options.session?.cookieCache?.enabled!==!0||e.path===void 0)return!1;const t=u(e.context.returned);return w.has(e.path)&&!t||S.has(e.path)&&t}}]},id:d}),C=e=>{const t=e.plugins??[];return!t.some(r=>r.id==="organization")||t.some(r=>r.id===d)?e:{...e,plugins:[...t,v()]}},i="cf-connecting-ip",L=e=>{const t=e!==void 0&&e.length>0;return g()?t?[i,"x-forwarded-for"]:[i]:t?["x-forwarded-for"]:[]},s="/**",T=100,_=e=>{const t=e.rateLimit?.customRules??{};return t[s]!==void 0?t:{...t,[s]:(r,o)=>f(r,e)===null?{max:o.max*T,window:o.window}:o}},l=32,R=e=>{const t=typeof e=="string"?e.trim().length:0;return t>0&&t<l},c=e=>typeof e=="string"?e.toLowerCase().startsWith("http://"):e&&typeof e=="object"?e.protocol==="http"?!0:e.protocol==="https"?!1:typeof e.fallback=="string"&&e.fallback.toLowerCase().startsWith("http://"):!1,k=new Set(["127.0.0.1","localhost"]),b=e=>{if(typeof e!="string")return;let t;try{t=new URL(e)}catch{return}if(!(t.protocol!=="http:"||!k.has(t.hostname)))return{allowedHosts:[t.hostname,`${t.hostname}:*`],fallback:e,protocol:"http"}},O=e=>{const t=b(e.baseURL)??e.baseURL;if(R(e.secret)){const n=`@lunora/auth: AUTH_SECRET is only ${String(e.secret?.trim().length)} characters. Use at least ${String(l)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;if(!c(t))throw new a("INTERNAL",n);console.warn(n)}const r=e.advanced??{},o=r.ipAddress??{};return{...e,advanced:{...r,defaultCookieAttributes:r.defaultCookieAttributes??{httpOnly:!0,path:"/",sameSite:"lax"},ipAddress:{...o,...o.ipAddressHeaders===void 0?{ipAddressHeaders:L(o.trustedProxies)}:{}},...r.useSecureCookies===void 0?{useSecureCookies:!c(t)}:{}},baseURL:t}},y=e=>{const t=O(e),r=t.rateLimit?.enabled===void 0,o=t.rateLimit?.storage===void 0&&t.rateLimit?.enabled!==!1,n=t.rateLimit?.enabled===!1?{}:{rateLimit:{...t.rateLimit,...r?{enabled:!0}:{},...o?{storage:"database"}:{},customRules:_(t)}};return C({...t,...n,...t.session?.cookieCache===void 0?{session:{...t.session,cookieCache:{enabled:!0,maxAge:60}}}:{}})},I=e=>{if(!e.secret||e.secret.trim()==="")throw new a("INTERNAL",'@lunora/auth: `secret` is required. Set AUTH_SECRET locally in .dev.vars (`lunora env set AUTH_SECRET "$(openssl rand -hex 32)"`), and in production with `wrangler secret put AUTH_SECRET`.');return e.session&&E(e.session),p(e),y(e)},B=e=>{const t=I(e);if(typeof t.database!="function")throw new a("INTERNAL","@lunora/auth: `createAuth` needs an adapter factory as `database` (`lunoraD1Adapter(env.DB)` or the Durable Object wiring). A raw D1 binding is for the migration-only instance: build it with `createMigrationAuth` from `@lunora/auth/migrate`.");return m(t)};export{B as createAuth,I as prepareAuthOptions,y as resolveAuthOptions};
1
+ import{LunoraError as a}from"@lunora/errors";import{isAPIError as u,createAuthMiddleware as h,getIP as f}from"better-auth/api";import{betterAuth as m}from"better-auth/minimal";import{o as g}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{authDiscoveryPaths as p}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{setCookieCache as A}from"better-auth/cookies";import{validateSessionPolicy as E}from"./sessionPresets-C867Mlo4.mjs";const d="lunora-org-session-refresh",w=new Set(["/organization/accept-invitation","/organization/create","/organization/delete","/organization/leave","/organization/remove-member"]),S=new Set(["/organization/get-full-organization","/organization/get-organization"]),v=()=>({hooks:{after:[{handler:h(async e=>{const t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!(typeof t!="string"||t===""))try{const r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt.getTime()<=Date.now())return;const o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);await A(e,r,!!o)}catch(r){console.error("@lunora/auth: organization session cache refresh failed",r)}}),matcher:e=>{if(e.context.options.session?.cookieCache?.enabled!==!0||e.path===void 0)return!1;const t=u(e.context.returned);return w.has(e.path)&&!t||S.has(e.path)&&t}}]},id:d}),C=e=>{const t=e.plugins??[];return!t.some(r=>r.id==="organization")||t.some(r=>r.id===d)?e:{...e,plugins:[...t,v()]}},i="cf-connecting-ip",L=e=>{const t=e!==void 0&&e.length>0;return g()?t?[i,"x-forwarded-for"]:[i]:t?["x-forwarded-for"]:[]},s="/**",T=100,_=e=>{const t=e.rateLimit?.customRules??{};return t[s]!==void 0?t:{...t,[s]:(r,o)=>f(r,e)===null?{max:o.max*T,window:o.window}:o}},l=32,R=e=>{const t=typeof e=="string"?e.trim().length:0;return t>0&&t<l},c=e=>typeof e=="string"?e.toLowerCase().startsWith("http://"):e&&typeof e=="object"?e.protocol==="http"?!0:e.protocol==="https"?!1:typeof e.fallback=="string"&&e.fallback.toLowerCase().startsWith("http://"):!1,k=new Set(["127.0.0.1","localhost"]),b=e=>{if(typeof e!="string")return;let t;try{t=new URL(e)}catch{return}if(!(t.protocol!=="http:"||!k.has(t.hostname)))return{allowedHosts:[t.hostname,`${t.hostname}:*`],fallback:e,protocol:"http"}},O=e=>{const t=b(e.baseURL)??e.baseURL;if(R(e.secret)){const n=`@lunora/auth: AUTH_SECRET is only ${String(e.secret?.trim().length)} characters. Use at least ${String(l)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;if(!c(t))throw new a("INTERNAL",n);console.warn(n)}const r=e.advanced??{},o=r.ipAddress??{};return{...e,advanced:{...r,defaultCookieAttributes:r.defaultCookieAttributes??{httpOnly:!0,path:"/",sameSite:"lax"},ipAddress:{...o,...o.ipAddressHeaders===void 0?{ipAddressHeaders:L(o.trustedProxies)}:{}},...r.useSecureCookies===void 0?{useSecureCookies:!c(t)}:{}},baseURL:t}},y=e=>{const t=O(e),r=t.rateLimit?.enabled===void 0,o=t.rateLimit?.storage===void 0&&t.rateLimit?.enabled!==!1,n=t.rateLimit?.enabled===!1?{}:{rateLimit:{...t.rateLimit,...r?{enabled:!0}:{},...o?{storage:"database"}:{},customRules:_(t)}};return C({...t,...n,...t.session?.cookieCache===void 0?{session:{...t.session,cookieCache:{enabled:!0,maxAge:60}}}:{}})},I=e=>{if(!e.secret||e.secret.trim()==="")throw new a("INTERNAL",'@lunora/auth: `secret` is required. Set AUTH_SECRET locally in .dev.vars (`lunora env set AUTH_SECRET "$(openssl rand -hex 32)"`), and in production with `wrangler secret put AUTH_SECRET`.');return e.session&&E(e.session),p(e),y(e)},B=e=>{const t=I(e);if(typeof t.database!="function")throw new a("INTERNAL","@lunora/auth: `createAuth` needs an adapter factory as `database` (`lunoraD1Adapter(env.DB)` or the Durable Object wiring). A raw D1 binding is for the migration-only instance: build it with `createMigrationAuth` from `@lunora/auth/migrate`.");return m(t)};export{B as createAuth,I as prepareAuthOptions,y as resolveAuthOptions};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{I as v,a as E,c as N,R as O,M as T}from"./auth-do-BdD-ChAx.mjs";import{isDiscoveryRequest as S,unlessNotFound as _}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{isAuthRoutePath as I}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{validClaimNames as H}from"./resolveSessionIdentity-Bk63iwnv.mjs";import{DEFAULT_AUTH_BASE_PATH as P}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const U=(n,r,u)=>{const d={};for(const s of u){const a=r[s];Object.hasOwn(n,s)||(typeof a=="boolean"||typeof a=="string"||typeof a=="number"&&Number.isFinite(a))&&(d[s]=a)}return Object.assign(n,d)},k=n=>{const{internalSecret:r,jurisdiction:u,objectName:d="auth"}=n,s=H(n.claims),a=new Set(n.discoveryPaths),w=n.namespace;let{namespace:o}=n;if(o&&u!==void 0){if(typeof o.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${u}") — update @cloudflare/workers-types or remove the jurisdiction option`);o=o.jurisdiction(u)}const m=()=>{if(o)return o.get(o.idFromName(d))},R=async(e,t,i)=>{if(!r)return;const l=m();if(!l)return;const f=await l.fetch(new Request(new URL(e,t),{body:JSON.stringify(i),headers:{"content-type":"application/json",[v]:r},method:"POST"}));return f.ok?f:void 0},A=o,b=w&&A&&u!==void 0?N(async(e,t)=>{if(!r)throw new g("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const i=e==="source"?w:A;return i.get(i.idFromName(d)).fetch(new Request(new URL(T,"https://auth-do.invalid"),{body:JSON.stringify(t),headers:{"content-type":"application/json",[v]:r},method:"POST"}))}):void 0;return{...b===void 0?{}:{jurisdictionMove:b},auditReader:{read:async e=>{const t=await R(O,"https://auth-do.invalid",e);return t?(await t.json())?.entries??[]:[]}},authHandler:async e=>{if(I(new URL(e.url).pathname,P))return m()?.fetch(e)},discoveryHandler:async e=>{if(S(e,a))return _(await m()?.fetch(e))},resolveIdentity:async e=>{if(!r)return null;const t=m();if(!t)return null;const i=new Headers(e.headers);i.set(v,r);const l=new URL(E,e.url);s.length>0&&l.searchParams.set("claims",s.join(","));const f=await t.fetch(new Request(l,{headers:i}));if(!f.ok)return null;const c=await f.json(),p=c?.userId;if(!c||typeof p!="string"||p.length===0)return null;const h={userId:p};for(const j of["email","name","orgId","role","teamId"]){const y=c[j];typeof y=="string"&&y.length>0&&(h[j]=y)}return typeof c.expiresAtMs=="number"&&Number.isFinite(c.expiresAtMs)&&(h.expiresAtMs=c.expiresAtMs),U(h,c,s)}}};export{k as createDoAuthWiring};
@@ -0,0 +1 @@
1
+ import{DEFAULT_AUTH_BASE_PATH as o}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const s=(n,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;return n===r||n.startsWith(`${r}/`)},i=async(n,t,r=o)=>{const e=new URL(t.url);if(s(e.pathname,r))return n.handler(t)};export{o as DEFAULT_AUTH_BASE_PATH,i as handleAuthRequest,s as isAuthRoutePath};
@@ -1 +1 @@
1
- import{mcp as o,requireMcpAuth as s}from"@better-auth/mcp";import{LunoraError as c}from"@lunora/errors";import{MCP_RESOURCE_KEY as u,protectedResourcePath as i,authorizationServerPath as n}from"./authDiscoveryPaths-B14lM14u.mjs";import{DEFAULT_AUTH_BASE_PATH as p}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";const a=e=>{if(!(typeof e=="string"&&URL.canParse(e)))throw new c("AUTH_MCP_RESOURCE_INVALID",`requireMcpAuth needs \`resource\` set to the absolute URL passed to mcp({ resource }), got ${JSON.stringify(e)}. Without it no issued token's audience matches and every request is refused.`)},d=e=>{const r=o(e);return Object.defineProperty(r,u,{value:e.resource}),r},E=(e,r,t)=>(a(t.resource),s(e,r,t)),P=(e,r=p)=>[i(e),n(r)];export{d as mcp,P as mcpDiscoveryPaths,E as requireMcpAuth};
1
+ import{mcp as o,requireMcpAuth as s}from"@better-auth/mcp";import{LunoraError as c}from"@lunora/errors";import{MCP_RESOURCE_KEY as u,protectedResourcePath as i,authorizationServerPath as n}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{DEFAULT_AUTH_BASE_PATH as p}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const a=e=>{if(!(typeof e=="string"&&URL.canParse(e)))throw new c("AUTH_MCP_RESOURCE_INVALID",`requireMcpAuth needs \`resource\` set to the absolute URL passed to mcp({ resource }), got ${JSON.stringify(e)}. Without it no issued token's audience matches and every request is refused.`)},d=e=>{const r=o(e);return Object.defineProperty(r,u,{value:e.resource}),r},E=(e,r,t)=>(a(t.resource),s(e,r,t)),P=(e,r=p)=>[i(e),n(r)];export{d as mcp,P as mcpDiscoveryPaths,E as requireMcpAuth};
@@ -0,0 +1 @@
1
+ import{S as c}from"./sensitive-fields-DqtvDy_d.mjs";const a=e=>typeof e=="string"&&e.length>0?e:void 0,u=new Set(["__proto__","email","exp","expiresAtMs","iat","name","nbf","orgId","role","roles","sub","teamId","userId"]),v=(e,t)=>{if(!(u.has(e)||c.has(e))){if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(t instanceof Date)return Number.isNaN(t.getTime())?void 0:t.toISOString()}},p=32,g=/^[A-Z_]\w{0,63}$/i,S=e=>(e??[]).filter(t=>g.test(t)&&!u.has(t)&&!c.has(t)).slice(0,p),_=e=>e==null||e===""?[]:S(e.split(",").map(t=>t.trim())),b=(e,t)=>{const n={};for(const i of t){const o=v(i,e[i]);o!==void 0&&(n[i]=o)}return n},A=(e,t=[])=>{const n=a(e?.user.id);if(e==null||n===void 0)return null;const{activeOrganizationId:i,activeTeamId:o,expiresAt:r}=e.session,d=a(e.user.email),s=a(e.user.name),m=a(i),l=a(e.user.role),f=a(o);return{...b(e.user,t),...d===void 0?{}:{email:d},...r instanceof Date?{expiresAtMs:r.getTime()}:{},...s===void 0?{}:{name:s},...m===void 0?{}:{orgId:m},...l===void 0?{}:{role:l},...f===void 0?{}:{teamId:f},userId:n}},y=async(e,t,n=[])=>{const i=A(await e.api.getSession({headers:t}),n);if(i===null||i.orgId===void 0&&i.teamId===void 0)return i;const{orgId:o,teamId:r,...d}=i;if(o===void 0)return d;const{adapter:s}=await e.$context,{userId:m}=i,[l,f,I]=await Promise.all([s.findOne({model:"member",where:[{field:"organizationId",value:o},{field:"userId",value:m}]}),r===void 0?void 0:s.findOne({model:"team",where:[{field:"id",value:r},{field:"organizationId",value:o}]}),r===void 0?void 0:s.findOne({model:"teamMember",where:[{field:"teamId",value:r},{field:"userId",value:m}]})]);return l?{...d,orgId:o,...f&&I?{teamId:r}:{}}:d};export{A as identityFromSession,_ as parseClaimNames,y as resolveSessionIdentity,S as validClaimNames};
@@ -0,0 +1 @@
1
+ const e=new Set(["accessToken","backupCodes","idToken","password","publicKey","refreshToken","secret","token","tokenHash"]);export{e as S};
@@ -647,7 +647,7 @@ type SessionIdentity = {
647
647
  * @param headers The request headers carrying the session.
648
648
  * @returns The identity, or `null` for an anonymous request.
649
649
  */
650
- declare const resolveSessionIdentity: (auth: LunoraAuth, headers: Headers) => Promise<SessionIdentity | null>;
650
+ declare const resolveSessionIdentity: (auth: LunoraAuth, headers: Headers, claims?: ReadonlyArray<string>) => Promise<SessionIdentity | null>;
651
651
  /** The slice of a Durable Object namespace this needs — structural, so tests need no runtime. */
652
652
  interface AuthNamespaceLike {
653
653
  get(this: void, id: unknown): {
@@ -664,6 +664,12 @@ interface AuthNamespaceLike {
664
664
  type AuthJurisdiction = "eu" | "fedramp" | "us";
665
665
  /** What {@link createDoAuthWiring} needs, already resolved against `env`. */
666
666
  interface DoAuthWiringOptions {
667
+ /**
668
+ * App-declared user columns to forward onto the identity, the same names the D1
669
+ * wiring passes to `resolveSessionIdentity`. Sent to the object as the `claims`
670
+ * query parameter on the internal session route. Empty or absent: none forwarded.
671
+ */
672
+ claims?: ReadonlyArray<string>;
667
673
  /**
668
674
  * The OAuth discovery paths the object serves outside `/api/auth` —
669
675
  * `authDiscoveryPaths(options)` over the same auth options the object builds.
@@ -745,11 +751,6 @@ interface DoAuthWiring {
745
751
  * @returns The `authHandler` / `resolveIdentity` pair.
746
752
  */
747
753
  declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring;
748
- /**
749
- * Default basePath used by better-auth's client + handler. Override via the
750
- * second argument if you mount the auth routes somewhere else.
751
- */
752
- declare const DEFAULT_AUTH_BASE_PATH: string;
753
754
  /**
754
755
  * Route an inbound `Request` to better-auth if the path falls under
755
756
  * `basePath`; otherwise return `undefined` so the caller can continue dispatching.
@@ -759,4 +760,4 @@ declare const DEFAULT_AUTH_BASE_PATH: string;
759
760
  * exact-path map `createWorker` consumes for top-level routes.
760
761
  */
761
762
  declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
762
- export { AuthAccount as A, createAuthAdmin as B, CreateAuthAdminOptions as C, DEFAULT_AUTH_BASE_PATH as D, createDoAuthWiring as E, handleAuthDiscoveryRequest as F, handleAuthRequest as G, resolveSessionIdentity as H, ImpersonationResult as I, ListUsersOptions as L, SessionIdentity as S, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthCapabilities as d, AuthConfigInfo as e, AuthInvitation as f, AuthJurisdiction as g, AuthJurisdictionMove as h, AuthMember as i, AuthMoveResult as j, AuthMoveTableReport as k, AuthNamespaceLike as l, AuthOrgRole as m, AuthOrganization as n, AuthPage as o, AuthPasskey as p, AuthSignUpInvitation as q, AuthTeam as r, AuthTeamMember as s, AuthTimestamp as t, AuthUserFieldSpec as u, DoAuthWiring as v, DoAuthWiringOptions as w, LunoraAuthAdminError as x, authDiscoveryPaths as y, authDiscoveryPathsFor as z };
763
+ export { AuthAccount as A, createDoAuthWiring as B, CreateAuthAdminOptions as C, DoAuthWiring as D, handleAuthDiscoveryRequest as E, handleAuthRequest as F, resolveSessionIdentity as G, ImpersonationResult as I, ListUsersOptions as L, SessionIdentity as S, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthCapabilities as d, AuthConfigInfo as e, AuthInvitation as f, AuthJurisdiction as g, AuthJurisdictionMove as h, AuthMember as i, AuthMoveResult as j, AuthMoveTableReport as k, AuthNamespaceLike as l, AuthOrgRole as m, AuthOrganization as n, AuthPage as o, AuthPasskey as p, AuthSignUpInvitation as q, AuthTeam as r, AuthTeamMember as s, AuthTimestamp as t, AuthUserFieldSpec as u, DoAuthWiringOptions as v, LunoraAuthAdminError as w, authDiscoveryPaths as x, authDiscoveryPathsFor as y, createAuthAdmin as z };
@@ -647,7 +647,7 @@ type SessionIdentity = {
647
647
  * @param headers The request headers carrying the session.
648
648
  * @returns The identity, or `null` for an anonymous request.
649
649
  */
650
- declare const resolveSessionIdentity: (auth: LunoraAuth, headers: Headers) => Promise<SessionIdentity | null>;
650
+ declare const resolveSessionIdentity: (auth: LunoraAuth, headers: Headers, claims?: ReadonlyArray<string>) => Promise<SessionIdentity | null>;
651
651
  /** The slice of a Durable Object namespace this needs — structural, so tests need no runtime. */
652
652
  interface AuthNamespaceLike {
653
653
  get(this: void, id: unknown): {
@@ -664,6 +664,12 @@ interface AuthNamespaceLike {
664
664
  type AuthJurisdiction = "eu" | "fedramp" | "us";
665
665
  /** What {@link createDoAuthWiring} needs, already resolved against `env`. */
666
666
  interface DoAuthWiringOptions {
667
+ /**
668
+ * App-declared user columns to forward onto the identity, the same names the D1
669
+ * wiring passes to `resolveSessionIdentity`. Sent to the object as the `claims`
670
+ * query parameter on the internal session route. Empty or absent: none forwarded.
671
+ */
672
+ claims?: ReadonlyArray<string>;
667
673
  /**
668
674
  * The OAuth discovery paths the object serves outside `/api/auth` —
669
675
  * `authDiscoveryPaths(options)` over the same auth options the object builds.
@@ -745,11 +751,6 @@ interface DoAuthWiring {
745
751
  * @returns The `authHandler` / `resolveIdentity` pair.
746
752
  */
747
753
  declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring;
748
- /**
749
- * Default basePath used by better-auth's client + handler. Override via the
750
- * second argument if you mount the auth routes somewhere else.
751
- */
752
- declare const DEFAULT_AUTH_BASE_PATH: string;
753
754
  /**
754
755
  * Route an inbound `Request` to better-auth if the path falls under
755
756
  * `basePath`; otherwise return `undefined` so the caller can continue dispatching.
@@ -759,4 +760,4 @@ declare const DEFAULT_AUTH_BASE_PATH: string;
759
760
  * exact-path map `createWorker` consumes for top-level routes.
760
761
  */
761
762
  declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
762
- export { AuthAccount as A, createAuthAdmin as B, CreateAuthAdminOptions as C, DEFAULT_AUTH_BASE_PATH as D, createDoAuthWiring as E, handleAuthDiscoveryRequest as F, handleAuthRequest as G, resolveSessionIdentity as H, ImpersonationResult as I, ListUsersOptions as L, SessionIdentity as S, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthCapabilities as d, AuthConfigInfo as e, AuthInvitation as f, AuthJurisdiction as g, AuthJurisdictionMove as h, AuthMember as i, AuthMoveResult as j, AuthMoveTableReport as k, AuthNamespaceLike as l, AuthOrgRole as m, AuthOrganization as n, AuthPage as o, AuthPasskey as p, AuthSignUpInvitation as q, AuthTeam as r, AuthTeamMember as s, AuthTimestamp as t, AuthUserFieldSpec as u, DoAuthWiring as v, DoAuthWiringOptions as w, LunoraAuthAdminError as x, authDiscoveryPaths as y, authDiscoveryPathsFor as z };
763
+ export { AuthAccount as A, createDoAuthWiring as B, CreateAuthAdminOptions as C, DoAuthWiring as D, handleAuthDiscoveryRequest as E, handleAuthRequest as F, resolveSessionIdentity as G, ImpersonationResult as I, ListUsersOptions as L, SessionIdentity as S, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthCapabilities as d, AuthConfigInfo as e, AuthInvitation as f, AuthJurisdiction as g, AuthJurisdictionMove as h, AuthMember as i, AuthMoveResult as j, AuthMoveTableReport as k, AuthNamespaceLike as l, AuthOrgRole as m, AuthOrganization as n, AuthPage as o, AuthPasskey as p, AuthSignUpInvitation as q, AuthTeam as r, AuthTeamMember as s, AuthTimestamp as t, AuthUserFieldSpec as u, DoAuthWiringOptions as v, LunoraAuthAdminError as w, authDiscoveryPaths as x, authDiscoveryPathsFor as y, createAuthAdmin as z };
package/dist/plugins.mjs CHANGED
@@ -1 +1 @@
1
- import{inviteOnly as e}from"./packem_shared/createSignUpInvitation-DHZL9fNl.mjs";import{mcp as m,mcpDiscoveryPaths as p,requireMcpAuth as f}from"./packem_shared/mcp-CgX1hTOv.mjs";import{uiConfig as x}from"./packem_shared/uiConfig-B8pN6pks.mjs";import{apiKey as a}from"@better-auth/api-key";import{cimd as s}from"@better-auth/cimd";import{createMcpProtectedRequestHandler as h}from"@better-auth/mcp";import{oauthDeviceAuthorization as l,oauthProvider as v}from"@better-auth/oauth-provider";import{passkey as A}from"@better-auth/passkey";import{scim as g}from"@better-auth/scim";import{createInsufficientScopeError as T}from"better-auth/oauth2";import{captcha as z,lastLoginMethod as M,oneTap as O}from"better-auth/plugins";import{createAccessControl as b}from"better-auth/plugins/access";import{admin as C}from"better-auth/plugins/admin";import{anonymous as I}from"better-auth/plugins/anonymous";import{bearer as j}from"better-auth/plugins/bearer";import{customSession as E}from"better-auth/plugins/custom-session";import{deviceAuthorization as H}from"better-auth/plugins/device-authorization";import{emailOTP as N}from"better-auth/plugins/email-otp";import{genericOAuth as G}from"better-auth/plugins/generic-oauth";import{haveIBeenPwned as Q}from"better-auth/plugins/haveibeenpwned";import{jwt as V}from"better-auth/plugins/jwt";import{magicLink as X}from"better-auth/plugins/magic-link";import{multiSession as Z}from"better-auth/plugins/multi-session";import{oAuthProxy as $}from"better-auth/plugins/oauth-proxy";import{oneTimeToken as ro}from"better-auth/plugins/one-time-token";import{organization as to}from"better-auth/plugins/organization";import{phoneNumber as po}from"better-auth/plugins/phone-number";import{siwe as io}from"better-auth/plugins/siwe";import{twoFactor as no}from"better-auth/plugins/two-factor";import{username as co}from"better-auth/plugins/username";export{C as admin,I as anonymous,a as apiKey,j as bearer,z as captcha,s as cimd,b as createAccessControl,T as createInsufficientScopeError,h as createMcpProtectedRequestHandler,E as customSession,H as deviceAuthorization,N as emailOTP,G as genericOAuth,Q as haveIBeenPwned,e as inviteOnly,V as jwt,M as lastLoginMethod,X as magicLink,m as mcp,p as mcpDiscoveryPaths,Z as multiSession,$ as oAuthProxy,l as oauthDeviceAuthorization,v as oauthProvider,O as oneTap,ro as oneTimeToken,to as organization,A as passkey,po as phoneNumber,f as requireMcpAuth,g as scim,io as siwe,no as twoFactor,x as uiConfig,co as username};
1
+ import{inviteOnly as e}from"./packem_shared/createSignUpInvitation-DHZL9fNl.mjs";import{mcp as m,mcpDiscoveryPaths as p,requireMcpAuth as f}from"./packem_shared/mcp-CK5XkDFp.mjs";import{uiConfig as x}from"./packem_shared/uiConfig-B8pN6pks.mjs";import{apiKey as a}from"@better-auth/api-key";import{cimd as s}from"@better-auth/cimd";import{createMcpProtectedRequestHandler as h}from"@better-auth/mcp";import{oauthDeviceAuthorization as l,oauthProvider as v}from"@better-auth/oauth-provider";import{passkey as A}from"@better-auth/passkey";import{scim as g}from"@better-auth/scim";import{createInsufficientScopeError as T}from"better-auth/oauth2";import{captcha as z,lastLoginMethod as M,oneTap as O}from"better-auth/plugins";import{createAccessControl as b}from"better-auth/plugins/access";import{admin as C}from"better-auth/plugins/admin";import{anonymous as I}from"better-auth/plugins/anonymous";import{bearer as j}from"better-auth/plugins/bearer";import{customSession as E}from"better-auth/plugins/custom-session";import{deviceAuthorization as H}from"better-auth/plugins/device-authorization";import{emailOTP as N}from"better-auth/plugins/email-otp";import{genericOAuth as G}from"better-auth/plugins/generic-oauth";import{haveIBeenPwned as Q}from"better-auth/plugins/haveibeenpwned";import{jwt as V}from"better-auth/plugins/jwt";import{magicLink as X}from"better-auth/plugins/magic-link";import{multiSession as Z}from"better-auth/plugins/multi-session";import{oAuthProxy as $}from"better-auth/plugins/oauth-proxy";import{oneTimeToken as ro}from"better-auth/plugins/one-time-token";import{organization as to}from"better-auth/plugins/organization";import{phoneNumber as po}from"better-auth/plugins/phone-number";import{siwe as io}from"better-auth/plugins/siwe";import{twoFactor as no}from"better-auth/plugins/two-factor";import{username as co}from"better-auth/plugins/username";export{C as admin,I as anonymous,a as apiKey,j as bearer,z as captcha,s as cimd,b as createAccessControl,T as createInsufficientScopeError,h as createMcpProtectedRequestHandler,E as customSession,H as deviceAuthorization,N as emailOTP,G as genericOAuth,Q as haveIBeenPwned,e as inviteOnly,V as jwt,M as lastLoginMethod,X as magicLink,m as mcp,p as mcpDiscoveryPaths,Z as multiSession,$ as oAuthProxy,l as oauthDeviceAuthorization,v as oauthProvider,O as oneTap,ro as oneTimeToken,to as organization,A as passkey,po as phoneNumber,f as requireMcpAuth,g as scim,io as siwe,no as twoFactor,x as uiConfig,co as username};
package/dist/worker.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { a as lunoraD1Adapter } from "./packem_shared/adapter.d-CaPwF2v3.mjs";
2
- export { z as authDiscoveryPathsFor, B as createAuthAdmin, E as createDoAuthWiring, F as handleAuthDiscoveryRequest, G as handleAuthRequest, H as resolveSessionIdentity } from "./packem_shared/worker.d-Dnw0s0_j.mjs";
2
+ export { y as authDiscoveryPathsFor, z as createAuthAdmin, B as createDoAuthWiring, E as handleAuthDiscoveryRequest, F as handleAuthRequest, G as resolveSessionIdentity } from "./packem_shared/worker.d-CJoVlNo2.mjs";
3
3
  export { createAuthAuditReader } from "./audit.mjs";
4
4
  export { c as createAuth } from "./packem_shared/create-auth.d-DNGo48je.mjs";
5
5
  export { d1Executor } from "./sql-store.mjs";
package/dist/worker.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { a as lunoraD1Adapter } from "./packem_shared/adapter.d-CElAPJ1U.js";
2
- export { z as authDiscoveryPathsFor, B as createAuthAdmin, E as createDoAuthWiring, F as handleAuthDiscoveryRequest, G as handleAuthRequest, H as resolveSessionIdentity } from "./packem_shared/worker.d-BfQTtOho.js";
2
+ export { y as authDiscoveryPathsFor, z as createAuthAdmin, B as createDoAuthWiring, E as handleAuthDiscoveryRequest, F as handleAuthRequest, G as resolveSessionIdentity } from "./packem_shared/worker.d-z1x-8MNm.js";
3
3
  export { createAuthAuditReader } from "./audit.js";
4
4
  export { c as createAuth } from "./packem_shared/create-auth.d-DNGo48je.js";
5
5
  export { d1Executor } from "./sql-store.js";
package/dist/worker.mjs CHANGED
@@ -1 +1 @@
1
- import{a as t}from"./packem_shared/adapter-CBZ17jKi.mjs";import{createAuthAdmin as a}from"./packem_shared/LunoraAuthAdminError-uhKG1MgQ.mjs";import{createAuthAuditReader as h}from"./audit.mjs";import{createAuth as p}from"./packem_shared/createAuth-CLeBjzDR.mjs";import{authDiscoveryPathsFor as x,handleAuthDiscoveryRequest as d}from"./packem_shared/authDiscoveryPaths-B14lM14u.mjs";import{createDoAuthWiring as A}from"./packem_shared/createDoAuthWiring-DIxLcjKQ.mjs";import{handleAuthRequest as c}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";import{resolveSessionIdentity as l}from"./packem_shared/resolveSessionIdentity-ChaUVZSy.mjs";import{d as v}from"./packem_shared/sql-store-uMubPYI9.mjs";export{x as authDiscoveryPathsFor,p as createAuth,a as createAuthAdmin,h as createAuthAuditReader,A as createDoAuthWiring,v as d1Executor,d as handleAuthDiscoveryRequest,c as handleAuthRequest,t as lunoraD1Adapter,l as resolveSessionIdentity};
1
+ import{a as t}from"./packem_shared/adapter-CBZ17jKi.mjs";import{createAuthAdmin as a}from"./packem_shared/LunoraAuthAdminError-Be0xQHfn.mjs";import{createAuthAuditReader as h}from"./audit.mjs";import{createAuth as p}from"./packem_shared/createAuth-Dioo_-mD.mjs";import{authDiscoveryPathsFor as x,handleAuthDiscoveryRequest as d}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{createDoAuthWiring as A}from"./packem_shared/createDoAuthWiring-fkSnTL5M.mjs";import{handleAuthRequest as c}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{resolveSessionIdentity as l}from"./packem_shared/resolveSessionIdentity-Bk63iwnv.mjs";import{d as v}from"./packem_shared/sql-store-uMubPYI9.mjs";export{x as authDiscoveryPathsFor,p as createAuth,a as createAuthAdmin,h as createAuthAuditReader,A as createDoAuthWiring,v as d1Executor,d as handleAuthDiscoveryRequest,c as handleAuthRequest,t as lunoraD1Adapter,l as resolveSessionIdentity};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/auth",
3
- "version": "1.0.0-alpha.257",
3
+ "version": "1.0.0-alpha.259",
4
4
  "description": "Auth for Lunora — a thin better-auth wrapper: email/password, OAuth, plugins, D1-backed",
5
5
  "keywords": [
6
6
  "auth",
@@ -14,7 +14,7 @@
14
14
  ],
15
15
  "homepage": "https://lunora.sh",
16
16
  "bugs": "https://github.com/anolilab/lunora/issues",
17
- "license": "FSL-1.1-Apache-2.0",
17
+ "license": "Apache-2.0",
18
18
  "author": {
19
19
  "name": "Daniel Bannert",
20
20
  "email": "d.bannert@anolilab.de"
@@ -1 +0,0 @@
1
- import{I as _,L as S,R as T,a as s}from"./auth-do-Dkk1jOb6.mjs";import"./adapter-CBZ17jKi.mjs";import"../audit.mjs";import"./createAuth-CLeBjzDR.mjs";import"./authDiscoveryPaths-B14lM14u.mjs";import"./authDoColumnAdditions-UwF3Rl41.mjs";import"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";import"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import"./resolveSessionIdentity-ChaUVZSy.mjs";export{_ as INTERNAL_SECRET_HEADER,S as LunoraAuthDO,T as READ_AUDIT_PATH,s as RESOLVE_SESSION_PATH};
@@ -1 +0,0 @@
1
- const e="/api/auth",u=(n,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;return n===r||n.startsWith(`${r}/`)},o=async(n,t,r=e)=>{const s=new URL(t.url);if(u(s.pathname,r))return n.handler(t)};export{e as DEFAULT_AUTH_BASE_PATH,o as handleAuthRequest,u as isAuthRoutePath};
@@ -1 +0,0 @@
1
- import{LunoraError as M}from"@lunora/errors";import{getAuthTables as b}from"better-auth/db";import{revokeSignUpInvitation as U,createSignUpInvitation as R}from"./createSignUpInvitation-DHZL9fNl.mjs";class f extends M{constructor(c,h){super(h,c,{name:"LunoraAuthAdminError"})}}const N=50,D=500,O=3600,E=O*24,T=100*365*24*60*60,z=2880*60*1e3,k=[{field:"userId",model:"member"},{field:"userId",model:"teamMember"},{field:"userId",model:"passkey"},{field:"userId",model:"twoFactor"},{field:"userId",model:"oauthAccessToken"},{field:"userId",model:"oauthRefreshToken"},{field:"userId",model:"oauthConsent"},{field:"userId",model:"deviceCode"},{field:"userId",model:"walletAddress"},{field:"inviterId",model:"invitation"}],L=new Set(["accessToken","backupCodes","idToken","password","publicKey","refreshToken","secret","token","tokenHash"]),C=o=>Math.min(Math.max(Math.trunc(o??N),1),D),P=o=>Math.max(0,Math.trunc(o??0)),u=o=>{const c={};for(const[h,l]of Object.entries(o))L.has(h)||(c[h]=l instanceof Date?l.getTime():l);return c},g=o=>Array.isArray(o)?o.join(","):o,S=o=>o.toLowerCase().replaceAll(/[^\da-z]+/g,"-").replaceAll(/^-|-$/g,""),B=new Set(["banExpires","banned","banReason","createdAt","email","emailVerified","id","name","role","updatedAt"]),F={displayUsername:"username",phoneNumber:"phone-number",phoneNumberVerified:"phone-number",username:"username"},G=o=>o==="boolean"||o==="date"||o==="number"?o:"string",V=o=>{const c=[];for(const[h,l]of Object.entries(o))l.input===!1||l.references!==void 0||B.has(h)||c.push({name:h,plugin:F[h],required:l.required===!0,type:G(l.type),unique:l.unique===!0});return c},I=o=>typeof o=="string"&&o.includes("owner"),_=async(o,c)=>{const l=(await o.adapter.findMany({model:"member",where:[{field:"userId",value:c}]})).filter(p=>I(p.role)&&typeof p.organizationId=="string").map(p=>p.organizationId);if(l.length===0)return;const A=await Promise.all(l.map(async p=>o.adapter.findMany({model:"member",where:[{field:"organizationId",value:p}]}))),n=l.find((p,v)=>!A[v]?.some(e=>e.userId!==c&&I(e.role)));if(n!==void 0)throw new f(`user is the last owner of organization ${n} — transfer ownership or delete the organization first`,"LAST_ORGANIZATION_OWNER")},j=o=>{if(o instanceof f)return o;const c=o,h=c?.body?.code??c?.code??"AUTH_ADMIN_ERROR",l=c?.body?.message??c?.message??"auth admin operation failed";return new f(l,h)},W=(o,c={})=>{const h=o.$context,l=c.features??{},A=e=>{const a=new Set((e.plugins??[]).map(i=>i.id)),t=i=>a.has(i);return{accounts:l.accounts??!0,admin:l.admin??t("admin"),inviteOnly:l.inviteOnly??t("lunora-invite-only"),organization:l.organization??t("organization"),passkey:l.passkey??t("passkey"),twoFactor:l.twoFactor??t("two-factor")}},n=async e=>{try{return await e(await h)}catch(a){throw j(a)}},p=e=>u(e),v=async(e,a,t)=>{const i=t.where&&t.where.length>0?t.where:void 0,[r,s]=await Promise.all([e.adapter.findMany({limit:C(t.limit),model:a,offset:P(t.offset),sortBy:t.sortBy,where:i}),e.adapter.count({model:a,where:i})]);return{rows:r.map(d=>u(d)),total:s}};return{banUser:({expiresInSeconds:e,reason:a,userId:t})=>n(async i=>{let r=null;if(e!==void 0){if(!Number.isInteger(e)||e<=0)throw new f("expiresInSeconds must be a positive finite integer","INVALID_BAN_SECONDS");const d=Math.min(e,T);r=new Date(Date.now()+d*1e3)}const s=await i.internalAdapter.updateUser(t,{banExpires:r,banned:!0,banReason:a??"No reason"});return await i.internalAdapter.deleteUserSessions(t),p(s)}),cancelInvitation:({invitationId:e})=>n(async a=>{await a.adapter.delete({model:"invitation",where:[{field:"id",value:e}]})}),capabilities:()=>n(e=>Promise.resolve(A(e.options))),addMember:({organizationId:e,role:a,userId:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:e,role:a===void 0||a===""?"member":a,userId:t},model:"member"});return u(r)}),addTeamMember:({teamId:e,userId:a})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,teamId:e,userId:a},model:"teamMember"});return u(i)}),config:()=>n(e=>{const a=e.options,t=A(a),i=new Set((a.plugins??[]).map(m=>m.id)),r=b(a),s=a.session??{},d=a.rateLimit??{};return Promise.resolve({capabilities:t,emailAndPassword:a.emailAndPassword?.enabled??!1,organization:{enabled:t.organization,roles:!!r.organizationRole,teams:!!r.team},plugins:[...i].toSorted((m,w)=>m.localeCompare(w)),rateLimit:{enabled:d.enabled??!1,max:d.max,window:d.window},session:{cookieCache:s.cookieCache?.enabled,expiresIn:s.expiresIn,freshAge:s.freshAge,updateAge:s.updateAge},socialProviders:Object.keys(a.socialProviders??{}).toSorted((m,w)=>m.localeCompare(w)),userFields:V(r.user?.fields??{})})}),createOrganization:({logo:e,metadata:a,name:t,ownerId:i,slug:r})=>n(async s=>{const d=S(r!==void 0&&r!==""?r:t);if(d==="")throw new f("could not derive a slug from the organization name","ORG_SLUG_INVALID");if(await s.adapter.findOne({model:"organization",where:[{field:"slug",value:d}]}))throw new f("an organization with this slug already exists","ORG_SLUG_TAKEN");const w=await s.adapter.create({data:{createdAt:new Date,logo:e===void 0||e===""?void 0:e,metadata:a===void 0?void 0:JSON.stringify(a),name:t,slug:d},model:"organization"});return i!==void 0&&i!==""&&await s.adapter.create({data:{createdAt:new Date,organizationId:w.id,role:"owner",userId:i},model:"member"}),u(w)}),createOrgRole:({organizationId:e,permission:a,role:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:e,permission:JSON.stringify(a),role:t},model:"organizationRole"});return u(r)}),createTeam:({name:e,organizationId:a})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,name:e,organizationId:a},model:"team"});return u(i)}),deleteOrganization:({organizationId:e})=>n(async a=>{const t=b(a.options);if(await a.adapter.deleteMany({model:"member",where:[{field:"organizationId",value:e}]}),await a.adapter.deleteMany({model:"invitation",where:[{field:"organizationId",value:e}]}),t.team){const i=await a.adapter.findMany({model:"team",where:[{field:"organizationId",value:e}]});for(const r of i)await a.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:r.id}]});await a.adapter.deleteMany({model:"team",where:[{field:"organizationId",value:e}]})}t.organizationRole&&await a.adapter.deleteMany({model:"organizationRole",where:[{field:"organizationId",value:e}]}),await a.adapter.delete({model:"organization",where:[{field:"id",value:e}]})}),deleteOrgRole:({roleId:e})=>n(async a=>{await a.adapter.delete({model:"organizationRole",where:[{field:"id",value:e}]})}),inviteMember:({email:e,inviterId:a,organizationId:t,role:i})=>n(async r=>{let s=a;if(s===void 0||s===""){const m=await r.adapter.findMany({model:"member",where:[{field:"organizationId",value:t}]});s=(m.find(y=>typeof y.role=="string"&&y.role.includes("owner"))??m[0])?.userId}if(s===void 0||s==="")throw new f("provide an inviter — the organization has no members to attribute the invitation to","INVITER_REQUIRED");const d=await r.adapter.create({data:{createdAt:new Date,email:e.toLowerCase(),expiresAt:new Date(Date.now()+z),inviterId:s,organizationId:t,role:i===void 0||i===""?"member":i,status:"pending"},model:"invitation"});return u(d)}),listOrgRoles:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"organizationRole",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listTeamMembers:({limit:e,offset:a,teamId:t})=>n(i=>v(i,"teamMember",{limit:e,offset:a,where:[{field:"teamId",value:t}]})),listTeams:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"team",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),removeTeam:({teamId:e})=>n(async a=>{await a.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:e}]}),await a.adapter.delete({model:"team",where:[{field:"id",value:e}]})}),removeTeamMember:({teamMemberId:e})=>n(async a=>{await a.adapter.delete({model:"teamMember",where:[{field:"id",value:e}]})}),updateMemberRole:({memberId:e,role:a})=>n(async t=>{const i=await t.adapter.update({model:"member",update:{role:g(a)},where:[{field:"id",value:e}]});return u(i??{id:e,role:g(a)})}),updateOrganization:({logo:e,metadata:a,name:t,organizationId:i,slug:r})=>n(async s=>{const d={};if(t!==void 0&&(d.name=t),r!==void 0&&r!==""&&(d.slug=S(r)),e!==void 0&&(d.logo=e===""?void 0:e),a!==void 0&&(d.metadata=JSON.stringify(a)),Object.keys(d).length===0)return u({id:i});const m=await s.adapter.update({model:"organization",update:d,where:[{field:"id",value:i}]});return u(m??{id:i})}),updateOrgRole:({permission:e,roleId:a})=>n(async t=>{const i=await t.adapter.update({model:"organizationRole",update:{permission:JSON.stringify(e),updatedAt:new Date},where:[{field:"id",value:a}]});return u(i??{id:a,permission:JSON.stringify(e)})}),updateTeam:({name:e,teamId:a})=>n(async t=>{const i=await t.adapter.update({model:"team",update:{name:e,updatedAt:new Date},where:[{field:"id",value:a}]});return u(i??{id:a,name:e})}),createUser:({data:e,email:a,name:t,password:i,role:r})=>n(async s=>{const d=a.toLowerCase();if(await s.internalAdapter.findUserByEmail(d))throw new f("a user with this email already exists","USER_ALREADY_EXISTS");const m={...e};delete m.isAnonymous;const w=await s.internalAdapter.createUser({email:d,name:t,role:r===void 0?void 0:g(r),...m},{method:"admin"});if(i!==void 0&&i!==""){const y=await s.password.hash(i);await s.internalAdapter.linkAccount({accountId:w.id,password:y,providerId:"credential",userId:w.id})}return p(w)}),deletePasskey:({passkeyId:e})=>n(async a=>{await a.adapter.delete({model:"passkey",where:[{field:"id",value:e}]})}),disableTwoFactor:({userId:e})=>n(async a=>{await a.adapter.deleteMany({model:"twoFactor",where:[{field:"userId",value:e}]}),await a.internalAdapter.updateUser(e,{twoFactorEnabled:!1})}),impersonateUser:({userId:e})=>n(async a=>{const t=await a.internalAdapter.findUserById(e);if(!t)throw new f("user not found","USER_NOT_FOUND");const i=c.impersonationSeconds;let r=O;if(i!==void 0){if(!Number.isInteger(i)||!Number.isFinite(i)||i<=0)throw new f("impersonationSeconds must be a positive finite integer","INVALID_IMPERSONATION_SECONDS");r=Math.min(i,E)}const s=new Date(Date.now()+r*1e3),d=await a.internalAdapter.createSession(e,!0,{expiresAt:s,impersonatedBy:c.impersonatedBy??e},!0);return{expiresAt:d.expiresAt instanceof Date?d.expiresAt.getTime():s.getTime(),token:d.token,user:p(t)}}),listAccounts:({userId:e})=>n(async a=>(await a.adapter.findMany({model:"account",where:[{field:"userId",value:e}]})).map(i=>u(i))),listInvitations:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"invitation",{limit:e,offset:a,where:[{field:"organizationId",value:t}]})),createSignUpInvitation:({email:e,expiresInSeconds:a,invitedBy:t})=>n(async()=>{const i=await R(o,{email:e,expiresInSeconds:a,invitedBy:t});return{...u({...i}),token:i.token}}),listSignUpInvitations:({limit:e,offset:a})=>n(t=>v(t,"signUpInvitation",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"}})),revokeSignUpInvitation:({email:e})=>n(async()=>U(o,{email:e})),listMembers:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"member",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listOrganizations:({limit:e,offset:a})=>n(t=>v(t,"organization",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"}})),listPasskeys:({userId:e})=>n(async a=>(await a.adapter.findMany({model:"passkey",where:[{field:"userId",value:e}]})).map(i=>u(i))),listSessions:({limit:e,offset:a,userId:t})=>n(i=>v(i,"session",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:t===void 0||t===""?void 0:[{field:"userId",value:t}]})),listUsers:({filterField:e,filterValue:a,limit:t,offset:i,search:r,searchField:s,sortBy:d,sortDirection:m})=>n(w=>{const y=[];return r!==void 0&&r!==""&&y.push({field:s??"email",operator:"contains",value:r}),a!==void 0&&y.push({field:e??"email",operator:"eq",value:a}),v(w,"user",{limit:t,offset:i,sortBy:{direction:m??"desc",field:d??"createdAt"},where:y})}),removeMember:({memberId:e})=>n(async a=>{await a.adapter.delete({model:"member",where:[{field:"id",value:e}]})}),removeUser:({userId:e})=>n(async a=>{const t=b(a.options);t.member&&await _(a,e),await Promise.all(k.filter(({model:i})=>t[i]).map(({field:i,model:r})=>a.adapter.deleteMany({model:r,where:[{field:i,value:e}]}))),await a.internalAdapter.deleteUserSessions(e),await a.internalAdapter.deleteUser(e)}),revokeUserSession:({sessionId:e})=>n(async a=>{const t=await a.adapter.findOne({model:"session",where:[{field:"id",value:e}]});t?.token&&await a.internalAdapter.deleteSession(t.token)}),revokeUserSessions:({userId:e})=>n(async a=>{await a.internalAdapter.deleteUserSessions(e)}),setRole:({role:e,userId:a})=>n(async t=>{const i=await t.internalAdapter.updateUser(a,{role:g(e)});return p(i)}),setUserPassword:({newPassword:e,userId:a})=>n(async t=>{const i=t.password.config.minPasswordLength,r=t.password.config.maxPasswordLength;if(e.length<i)throw new f(`password must be at least ${i.toString()} characters`,"PASSWORD_TOO_SHORT");if(e.length>r)throw new f(`password must be at most ${r.toString()} characters`,"PASSWORD_TOO_LONG");if(!await t.internalAdapter.findUserById(a))throw new f("user not found","USER_NOT_FOUND");const d=(await t.internalAdapter.findAccounts(a)).some(w=>w.providerId==="credential");if(!d&&t.options.emailAndPassword?.enabled!==!0)throw new f("email/password sign-in is disabled for this deployment","EMAIL_PASSWORD_DISABLED");const m=await t.password.hash(e);d?await t.internalAdapter.updatePassword(a,m):await t.internalAdapter.linkAccount({accountId:a,password:m,providerId:"credential",userId:a})}),unbanUser:({userId:e})=>n(async a=>{const t=await a.internalAdapter.updateUser(e,{banExpires:null,banned:!1,banReason:null});return p(t)}),unlinkAccount:({accountId:e,userId:a})=>n(async t=>{await t.adapter.delete({model:"account",where:[{field:"id",value:e},{connector:"AND",field:"userId",value:a}]})}),updateUser:({data:e,userId:a})=>n(async t=>{const i=await t.internalAdapter.updateUser(a,e);return p(i)})}};export{f as LunoraAuthAdminError,W as createAuthAdmin};
@@ -1 +0,0 @@
1
- import{getAuthTablesWithResolvedIndexes as U}from"@better-auth/core/db/internal";import{LunoraError as w,toErrorBody as Y}from"@lunora/errors";import{d as k,b as K}from"./adapter-CBZ17jKi.mjs";import{AUTH_AUDIT_TABLE as Q,ensureAuthAuditTable as z,createAuthAuditReader as Z}from"../audit.mjs";import{resolveAuthOptions as ee,createAuth as te}from"./createAuth-CLeBjzDR.mjs";import{handleAuthDiscoveryRequest as ne}from"./authDiscoveryPaths-B14lM14u.mjs";import{authDoSchemaStatements as re,authDoColumnAdditions as se}from"./authDoColumnAdditions-UwF3Rl41.mjs";import{handleAuthRequest as oe}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";import{decodeWire as I,encodeWire as v}from"@lunora/wire";import{q as a}from"./quote-identifier-CGiYFBvY.mjs";import{schemaDeclaresIssuer as ie,legacyIssuerCleanupStatements as ae,indexesReferencingIssuer as ce}from"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{resolveSessionIdentity as ue}from"./resolveSessionIdentity-ChaUVZSy.mjs";const le=(t,e)=>{const n=Math.max(t.length,e.length);let r=t.length^e.length;for(let s=0;s<n;s+=1){const o=s<t.length?t.charCodeAt(s):0,i=s<e.length?e.charCodeAt(s):0;r|=o^i}return r===0},j=2166136261,F=16777619,C=(t,e=j)=>{let n=e;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,F);return(n>>>0).toString(16).padStart(8,"0")},fe=t=>`${C(t,j)}${C(t,F)}`,Ee="/__lunora/auth/move",T="__lunora_auth_move__",R="__lunora_auth_move_rows__",y="__lunora_auth_purged__",x=100,de=16,me=100,pe=2n**64n,H=t=>t.startsWith("sqlite_")||t.startsWith("_cf_")||t===T||t===R||t===y,P=async(t,e)=>t.transaction(async()=>Promise.resolve().then(e)),E=(t,e,...n)=>[...t.sql.exec(e,...n)],u=(t,e,...n)=>{[...t.sql.exec(e,...n)]},_=t=>E(t,"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map(e=>String(e.name)).filter(e=>!H(e)),q=(t,e)=>E(t,"SELECT name, pk FROM pragma_table_info(?)",e).map(n=>({name:String(n.name),pk:Number(n.pk)})),g=(t,e)=>q(t,e).map(({name:n})=>n),W=(t,e)=>{const n=q(t,e),r=n.filter(({pk:s})=>s>0).toSorted((s,o)=>s.pk-o.pk).map(({name:s})=>s);return r.length>0?r:n.map(({name:s})=>s)},B=(t,e)=>Number(E(t,`SELECT count(*) AS n FROM ${a(e)}`)[0]?.n??0),V=t=>JSON.stringify(v(t)),b=(t,e)=>BigInt(`0x${fe(V(e.map(n=>t[n]??null)))}`),G=(t,e)=>{let n=0,r=0n;for(const s of t)n+=1,r=(r+e(s))%pe;return`${String(n)}:${r.toString(16)}`},X=(t,e)=>{const n=g(t,e).toSorted((r,s)=>r.localeCompare(s));return G(t.sql.exec(`SELECT * FROM ${a(e)}`),r=>b(r,n))},he=t=>_(t).map(e=>{const n=E(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,r=E(t,"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL",e).map(s=>({name:String(s.name),sql:String(s.sql)}));return{columns:g(t,e),indexes:r,name:e,rows:B(t,e),sql:typeof n=="string"?n:""}}),M=(t,e)=>{if(typeof e!="string"||!_(t).includes(e))throw new TypeError(`unknown table ${JSON.stringify(e)}`);return e},Te=(t,e,n)=>{const r=E(t,`SELECT rowid AS "__lunora_rowid__", * FROM ${a(e)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,n,x),s=r.at(-1)?.__lunora_rowid__;return{last:typeof s=="number"?s:void 0,rows:r.map(({__lunora_rowid__:o,...i})=>i)}},Se=t=>g(t,T).length>0,O=t=>Se(t)?Object.fromEntries(E(t,`SELECT tbl, after, done, pass, cols, watermark FROM ${a(T)}`).map(e=>[String(e.tbl),{after:Number(e.after),columns:JSON.parse(String(e.cols)),done:e.done===1,pass:Number(e.pass),watermark:Number(e.watermark)}])):{},we=(t,e,n)=>G(t.sql.exec(`SELECT h FROM ${a(R)} WHERE tbl = ? AND pass = ?`,e,n),r=>BigInt(`0x${String(r.h)}`)),Re=t=>{u(t,`CREATE TABLE IF NOT EXISTS ${a(T)} (tbl TEXT NOT NULL PRIMARY KEY, after INTEGER NOT NULL, done INTEGER NOT NULL, pass INTEGER NOT NULL, cols TEXT NOT NULL, watermark INTEGER NOT NULL DEFAULT 0)`),u(t,`CREATE TABLE IF NOT EXISTS ${a(R)} (tbl TEXT NOT NULL, k TEXT NOT NULL, h TEXT NOT NULL, pass INTEGER NOT NULL, PRIMARY KEY (tbl, k))`)},Ae=(t,e,n)=>{if(!_(t).includes(e))return 0;const r=W(t,e).map(s=>`u.${a(s)}`).join(", ");return Number(E(t,`SELECT count(*) AS n FROM ${a(e)} u WHERE u.rowid > ? AND NOT EXISTS (SELECT 1 FROM ${a(R)} c WHERE c.tbl = ? AND c.k = json_array(${r}))`,n,e)[0]?.n??0)},Ne=/^CREATE TABLE /iu,_e=/^CREATE (?:UNIQUE )?INDEX /iu,Oe=(t,e,n)=>{if(H(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!Ne.test(e.sql)||e.indexes.some(({sql:s})=>!_e.test(s)))throw new TypeError(`refusing unexpected DDL for ${JSON.stringify(e.name)}`);if(n.has(e.name)){const s=new Set(g(t,e.name));for(const o of e.columns.filter(i=>!s.has(i)))u(t,`ALTER TABLE ${a(e.name)} ADD COLUMN ${a(o)}`)}else u(t,e.sql);const r=new Set(E(t,"SELECT name FROM sqlite_master WHERE type = 'index'").map(s=>String(s.name)));for(const s of e.indexes.filter(({name:o})=>!r.has(o)))u(t,s.sql)},ge=(t,e,n)=>{Re(t);const r=Ae(t,n.userTable,O(t)[n.userTable]?.watermark??0);if(r>0&&!n.force)throw new w("AUTH_MOVE_TARGET_NOT_EMPTY",`the pinned auth object has ${String(r)} user(s) the copy did not write; copying into it would merge two user bases — pass force to copy anyway`,{data:{users:r}});const s=new Set(_(t)),o=O(t);for(const c of e){Oe(t,c,s);const f=o[c.name],d=JSON.stringify(c.columns.toSorted((m,p)=>m.localeCompare(p)));f===void 0?u(t,`INSERT INTO ${a(T)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,c.name,d):u(t,`UPDATE ${a(T)} SET cols = ? WHERE tbl = ?`,d,c.name)}u(t,`UPDATE ${a(T)} SET watermark = (SELECT coalesce(max(rowid), 0) FROM ${a(n.userTable)}) WHERE tbl = ?`,n.userTable);const i=O(t);return{cursors:Object.fromEntries(e.map(({name:c})=>[c,i[c]?.after??0])),done:Object.fromEntries(e.map(({name:c})=>[c,i[c]?.done??!1])),targetRows:Object.fromEntries(e.map(({name:c})=>[c,B(t,c)]))}},J=(t,e,n,r,s)=>E(t,`SELECT ${s.map(o=>a(o)).join(", ")} FROM ${a(e)} WHERE ${n.map(o=>`${a(o)} IS ?`).join(" AND ")} LIMIT 1`,...r)[0],$=(t,e)=>{if(!e)throw new w("AUTH_MOVE_CONFLICT",`a row copied into ${t} collides with a row the pinned auth object holds on its own — nothing from this page was written; pass force to keep the pinned object's rows`,{data:{table:t}});return"conflicts"},Le=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),ye=(t,e)=>{if(e.prior!==void 0)return $(e.table,e.force);try{u(t,`INSERT INTO ${a(e.table)} (${e.columns.map(n=>a(n)).join(", ")}) VALUES (${e.columns.map(()=>"?").join(", ")})`,...e.columns.map(n=>e.row[n]))}catch(n){if(!Le(n))throw n;return $(e.table,e.force)}return"copied"},$e=(t,e,n)=>{const r=b(n,e.columns).toString(16);return r===e.h?"unchanged":e.prior===void 0||r!==e.prior?$(e.table,e.force):(u(t,`UPDATE ${a(e.table)} SET ${e.columns.map(s=>`${a(s)} = ?`).join(", ")} WHERE ${e.keys.map(s=>`${a(s)} IS ?`).join(" AND ")}`,...e.columns.map(s=>e.row[s]),...e.key),"updated")},be=(t,e,n,r)=>{const{force:s,keys:o,pass:i}=r,c=Object.keys(n).toSorted((S,L)=>S.localeCompare(L));if(c.length+o.length>me)throw new TypeError(`${e} has too many columns to copy`);const f=o.map(S=>n[S]??null),d=V(f),m=b(n,c).toString(16),p=E(t,`SELECT h FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,d)[0]?.h,l={columns:c,force:s,h:m,key:f,keys:o,prior:typeof p=="string"?p:void 0,row:n,table:e},h=l.prior===m?void 0:J(t,e,o,f,c);let A="unchanged";return l.prior!==m&&(A=h===void 0?ye(t,l):$e(t,l,h)),u(t,`INSERT INTO ${a(R)} (tbl, k, h, pass) VALUES (?, ?, ?, ?) ON CONFLICT (tbl, k) DO UPDATE SET h = excluded.h, pass = excluded.pass`,e,d,m,i),A},Ie=(t,e,n)=>{const{counts:r,force:s,keys:o,marker:i}=n,c=E(t,`SELECT k, h FROM ${a(R)} WHERE tbl = ? AND pass < ?`,e,i.pass);for(const f of c){const d=I(JSON.parse(String(f.k))),m=J(t,e,o,d,i.columns);m!==void 0&&(b(m,i.columns).toString(16)===String(f.h)?(u(t,`DELETE FROM ${a(e)} WHERE ${o.map(p=>`${a(p)} IS ?`).join(" AND ")}`,...d),r.deleted+=1):r[$(e,s)]+=1),u(t,`DELETE FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,String(f.k))}},De=async(t,e,n)=>{const r=O(t)[e];if(r===void 0)throw new TypeError(`table ${JSON.stringify(e)} was not part of this move`);return P(t,()=>{const s={conflicts:0,copied:0,deleted:0,unchanged:0,updated:0},o=W(t,e);for(const i of n.rows)s[be(t,e,i,{force:n.force,keys:o,pass:r.pass})]+=1;return n.final&&Ie(t,e,{counts:s,force:n.force,keys:o,marker:r}),u(t,`UPDATE ${a(T)} SET after = ?, done = ? WHERE tbl = ?`,n.last,n.final?1:0,e),s})},Ue=async(t,e)=>{const n=_(t);return await P(t,()=>{const r=n.filter(o=>e[o]===void 0);if(r.length>0)throw new w("AUTH_MOVE_INCOMPLETE",`refusing to purge the un-pinned auth object: ${r.join(", ")} not fully copied — run the copy to done: true first`,{data:{unfinished:r}});const s=n.filter(o=>X(t,o)!==e[o]);if(s.length>0)throw new w("AUTH_MOVE_SOURCE_CHANGED",`refusing to purge the un-pinned auth object: ${s.join(", ")} changed since it was copied — run the copy again to carry the changes, then purge`,{data:{changed:s}});for(const o of n)u(t,`DROP TABLE ${a(o)}`);u(t,`CREATE TABLE IF NOT EXISTS ${a(y)} (at INTEGER NOT NULL)`),u(t,`INSERT INTO ${a(y)} (at) VALUES (?)`,Date.now())}),{dropped:n}},ke=t=>{if(g(t,y).length>0)throw new w("AUTH_MOVE_SOURCE_PURGED","the un-pinned auth object was purged after its tables were copied; anything in it now is new, and copying it would delete the pinned object's users")},Ce=new Set(["fingerprints","manifest","page","purge"]),Me=(t,e,n)=>{e.prepare();const r=O(t);return{copied:n?Object.fromEntries(Object.entries(r).map(([s,o])=>[s,we(t,s,o.pass)])):{},markers:r,order:e.order()}},ve=(t,e)=>{for(const n of e)u(t,`UPDATE ${a(T)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},je=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],Fe=t=>{const e=t instanceof Error?t.message:String(t);for(const n of je){const r=n.exec(e);if(r)return r[0]}return t instanceof Error?t.name:"unknown"},xe=async(t,e,n)=>{switch(Ce.has(String(e.op))&&ke(t),e.op){case"begin":return n.prepare(),ge(t,e.tables,{force:e.force===!0,userTable:n.userTable()});case"fingerprints":return{fingerprints:Object.fromEntries(_(t).map(r=>[r,X(t,r)]))};case"manifest":return{tables:he(t)};case"page":{const r=Te(t,M(t,e.table),Number(e.after??0));return{last:r.last,rows:v(r.rows)}}case"purge":{const r=await Ue(t,e.expected??{});return n.onPurge(),r}case"rescan":return ve(t,e.tables??[]);case"status":return Me(t,n,e.fingerprints===!0);case"write":return De(t,M(t,e.table),{final:e.final===!0,force:e.force===!0,last:Number(e.last),rows:I(e.rows)});default:throw new TypeError(`unknown move op ${JSON.stringify(e.op)}`)}},He=async(t,e,n)=>{try{return await xe(t,e,n)}catch(r){if(r instanceof w)throw r;console.error("@lunora/auth: auth move step failed",r);const s=String(e.op),o=typeof e.table=="string"?e.table:void 0,i=Fe(r);throw new w("AUTH_MOVE_FAILED",`auth move ${s}${o===void 0?"":` on ${o}`} failed: ${i}`,{data:{cause:i,op:s,...o===void 0?{}:{table:o}}})}},Pe=(t,e)=>{const n=r=>{const s=e.first.indexOf(r);if(s!==-1)return s;const o=e.last.indexOf(r);return o===-1?e.first.length:e.first.length+1+o};return t.toSorted((r,s)=>n(r.name)-n(s.name)||r.name.localeCompare(s.name))},qe=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),ot=t=>{const e=async(n,r)=>{const s=await t(n,r);if(!s.ok){let o={};try{const i=await s.json();typeof i.error=="object"&&i.error!==null&&(o=i.error)}catch{}throw new w(o.code??"AUTH_MOVE_FAILED",o.message??`auth move ${String(r.op)} on the ${n} object failed (${String(s.status)})`,{data:o.data,status:s.status})}return s.json()};return{copy:async(n={})=>{const r=n.force===!0,s=await e("target",{op:"status"}),{tables:o}=await e("source",{op:"manifest"}),i=await e("target",{force:r,op:"begin",tables:o}),c=[];let f=0;for(const l of Pe(o,s.order)){const h=qe(l,i.targetRows[l.name]??0);let A=i.cursors[l.name]??0;for(c.push(h);;){if(f>=de)return{done:!1,tables:c};f+=1;const S=await e("source",{after:A,op:"page",table:l.name}),L=I(S.rows),D=L.length<x;if(L.length===0&&i.done[l.name]===!0)break;const N=await e("target",{final:D,force:r,last:S.last??A,op:"write",rows:S.rows,table:l.name});if(h.conflicts+=N.conflicts,h.copied+=N.copied,h.deleted+=N.deleted,h.unchanged+=N.unchanged,h.updated+=N.updated,h.targetRows+=N.copied-N.deleted,A=S.last??A,D)break}}const{fingerprints:d}=await e("source",{op:"fingerprints"}),m=await e("target",{fingerprints:!0,op:"status"}),p=Object.keys(d).filter(l=>m.copied[l]!==d[l]);return p.length>0&&await e("target",{op:"rescan",tables:p}),{done:p.length===0,tables:c}},purge:async()=>{const{copied:n,markers:r}=await e("target",{fingerprints:!0,op:"status"}),s=Object.fromEntries(Object.entries(r).filter(([,o])=>o.done).map(([o])=>[o,n[o]]));return e("source",{expected:s,op:"purge"})}}},We="/__lunora/auth/session",Be="/__lunora/auth/audit",Ve="x-lunora-auth-do-secret",Ge=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return{error:"body must be a JSON object"};const e={};for(const[n,r]of Object.entries(t))if(n==="limit"||n==="sinceSeq"){if(typeof r!="number"||!Number.isFinite(r))return{error:`"${n}" must be a finite number`};e[n]=r}else if(n==="actorId"||n==="event"){if(typeof r!="string")return{error:`"${n}" must be a string`};e[n]=r}else return{error:`unknown audit read option "${n}"`};return{options:e}};class it{#n;#a;#c;#e;#t;#r=!1;#s={first:["user"],last:[]};constructor(e,n,r={}){this.#e=e.storage,this.#n=k(e.storage),this.#c=n,this.#a=r}#o(){if(this.#t!==void 0)return this.#t;const e=this.#c(),n=ee(e),{tables:r}=U(n);if(this.#s={first:[r.user?.modelName??"user",r.account?.modelName??"account",r.session?.modelName??"session"],last:[Q,r.rateLimit?.modelName??"rateLimit"]},!this.#r){for(const s of re(n))[...this.#e.sql.exec(s)];for(const s of se(n,o=>this.#u(o)))[...this.#e.sql.exec(s)];this.#l(n),this.#r=!0}return this.#t=te({...e,database:K(this.#e)}),this.#t}#u(e){return[...this.#e.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(r=>String(r.name))}#l(e){const{tables:n}=U(e),{account:r}=n;if(r===void 0)return;const s=Object.entries(r.fields).map(([o,i])=>i.fieldName??o);if(!(ie(s)||!this.#u(r.modelName).includes("issuer")))try{const o=[...this.#e.sql.exec("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",r.modelName)].map(i=>({name:String(i.name),sql:typeof i.sql=="string"?i.sql:void 0}));for(const i of ae(r.modelName,ce(o)))[...this.#e.sql.exec(i)]}catch(o){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",o)}}async#f(e){if(!this.#i(e))return Response.json({error:"unauthorized"},{status:401});let n;try{n=await e.json()}catch{return Response.json({error:"invalid body"},{status:400})}const r=Ge(n??{});if("error"in r)return Response.json({error:r.error},{status:400});await z(this.#n);const s=await Z(this.#n).read(r.options);return Response.json({entries:s})}async#E(e){if(e.method!=="POST"||!this.#i(e))return Response.json({error:"unauthorized"},{status:401});try{const n=await e.json(),r=await He(this.#e,n,{onPurge:()=>{this.#r=!1,this.#t=void 0,this.#n=k(this.#e)},order:()=>this.#s,prepare:()=>{this.#o()},userTable:()=>this.#s.first[0]??"user"});return Response.json(r)}catch(n){const{body:r,redacted:s,status:o}=Y(n,{encodeData:i=>i,fallbackCode:"AUTH_MOVE_FAILED",redactedMessage:"auth move failed"});return s&&console.error("@lunora/auth: auth move failed",n),Response.json({error:r},{status:o})}}#i(e){const{internalSecret:n}=this.#a;if(n===void 0||n==="")return!1;const r=e.headers.get(Ve);return r!==null&&le(r,n)}async#d(e){return this.#i(e)?Response.json(await ue(this.#o(),e.headers)??{}):Response.json({error:"unauthorized"},{status:401})}async fetch(e){const n=new URL(e.url);if(n.pathname===We)return this.#d(e);if(n.pathname===Be)return this.#f(e);if(n.pathname===Ee)return this.#E(e);const r=this.#o();return await oe(r,e)??await ne(r,e)??Response.json({error:"not an auth route"},{status:404})}}export{Ve as I,it as L,Ee as M,Be as R,We as a,ot as c};
@@ -1 +0,0 @@
1
- import{LunoraError as h}from"@lunora/errors";import{DEFAULT_AUTH_BASE_PATH as p}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";const l=Symbol.for("lunora.auth.mcpResource"),i=/\/$/u,d="/.well-known/oauth-protected-resource",f="/.well-known/oauth-authorization-server",R=t=>`${d}${new URL(t).pathname.replace(i,"")}`,w=t=>`${f}${t.replace(i,"")}`,v=t=>{if(typeof t=="string")try{const e=new URL(t).pathname.replace(i,"");return e===""?void 0:e}catch{return}},m=(t,e,r)=>{const n=e.find(o=>o.id==="jwt")?.options,s=r?.disableJwtPlugin===!0?void 0:n?.jwt?.issuer;if(typeof s=="string")try{return new URL(s).pathname}catch{}return v(t.baseURL)??t.basePath??p},y=t=>(Array.isArray(t)?t:[]).map(e=>typeof e=="object"&&e!==null?e.identifier:e).filter(e=>typeof e=="string"),E=t=>{const e=t[l];if(typeof e=="string")return e;const r=t.options,n=[...new Set(y(r?.resources))];if(n.length===1)return n[0];if(n.length>1&&Array.isArray(r?.clientRegistrationDefaultResources))throw new h("AUTH_MCP_RESOURCE_AMBIGUOUS",`@lunora/auth cannot tell which of the provider's resources (${n.join(", ")}) is the MCP resource. Use \`mcp\` from "@lunora/auth/plugins", which records it, and pass the plugin object as is.`)},u=t=>{const e=t.plugins??[],r=e.filter(o=>o.id==="oauth-provider");if(r.length===0)return[];const n=r.map(o=>E(o)).filter(o=>o!==void 0).map(o=>R(o)),s=m(t,e,r[0]?.options);return[...new Set([...n,w(s)])]},a=new WeakMap,S=(t,e)=>{let r=a.get(t);return r===void 0&&(r=u(t.options(e)),a.set(t,r)),r},A=t=>t?.status===404?void 0:t,c=new WeakMap,P=(t,e)=>(t.method==="GET"||t.method==="HEAD")&&e.has(new URL(t.url).pathname),_=async(t,e)=>{let r=c.get(t);if(r===void 0&&(r=new Set(u(t.options)),c.set(t,r)),!!P(e,r))return A(await t.handler(e))};export{l as MCP_RESOURCE_KEY,u as authDiscoveryPaths,S as authDiscoveryPathsFor,w as authorizationServerPath,_ as handleAuthDiscoveryRequest,P as isDiscoveryRequest,R as protectedResourcePath,A as unlessNotFound};
@@ -1 +0,0 @@
1
- import{LunoraError as E}from"@lunora/errors";import{I as h,a as j,c as T,R as b,M as g}from"./auth-do-Dkk1jOb6.mjs";import{isDiscoveryRequest as S,unlessNotFound as _}from"./authDiscoveryPaths-B14lM14u.mjs";import{isAuthRoutePath as N,DEFAULT_AUTH_BASE_PATH as I}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";const U=a=>{const{internalSecret:i,jurisdiction:c,objectName:p="auth"}=a,A=new Set(a.discoveryPaths),y=a.namespace;let{namespace:r}=a;if(r&&c!==void 0){if(typeof r.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${c}") — update @cloudflare/workers-types or remove the jurisdiction option`);r=r.jurisdiction(c)}const u=()=>{if(r)return r.get(r.idFromName(p))},R=async(e,t,o)=>{if(!i)return;const s=u();if(!s)return;const n=await s.fetch(new Request(new URL(e,t),{body:JSON.stringify(o),headers:{"content-type":"application/json",[h]:i},method:"POST"}));return n.ok?n:void 0},m=r,v=y&&m&&c!==void 0?T(async(e,t)=>{if(!i)throw new E("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const o=e==="source"?y:m;return o.get(o.idFromName(p)).fetch(new Request(new URL(g,"https://auth-do.invalid"),{body:JSON.stringify(t),headers:{"content-type":"application/json",[h]:i},method:"POST"}))}):void 0;return{...v===void 0?{}:{jurisdictionMove:v},auditReader:{read:async e=>{const t=await R(b,"https://auth-do.invalid",e);return t?(await t.json())?.entries??[]:[]}},authHandler:async e=>{if(N(new URL(e.url).pathname,I))return u()?.fetch(e)},discoveryHandler:async e=>{if(S(e,A))return _(await u()?.fetch(e))},resolveIdentity:async e=>{if(!i)return null;const t=u();if(!t)return null;const o=new Headers(e.headers);o.set(h,i);const s=await t.fetch(new Request(new URL(j,e.url),{headers:o}));if(!s.ok)return null;const n=await s.json(),d=n?.userId;if(!n||typeof d!="string"||d.length===0)return null;const f={userId:d};for(const w of["email","name","orgId","role","teamId"]){const l=n[w];typeof l=="string"&&l.length>0&&(f[w]=l)}return typeof n.expiresAtMs=="number"&&Number.isFinite(n.expiresAtMs)&&(f.expiresAtMs=n.expiresAtMs),f}}};export{U as createDoAuthWiring};
@@ -1 +0,0 @@
1
- const r=e=>typeof e=="string"&&e.length>0?e:void 0,c=e=>{const l=r(e?.user.id);if(e==null||l===void 0)return null;const{activeOrganizationId:t,activeTeamId:d,expiresAt:i}=e.session,o=r(e.user.email),n=r(e.user.name),a=r(t),m=r(e.user.role),v=r(d);return{...o===void 0?{}:{email:o},...i instanceof Date?{expiresAtMs:i.getTime()}:{},...n===void 0?{}:{name:n},...a===void 0?{}:{orgId:a},...m===void 0?{}:{role:m},...v===void 0?{}:{teamId:v},userId:l}},u=async(e,l)=>{const t=c(await e.api.getSession({headers:l}));if(t===null||t.orgId===void 0&&t.teamId===void 0)return t;const{orgId:d,teamId:i,...o}=t;if(d===void 0)return o;const{adapter:n}=await e.$context,{userId:a}=t,[m,v,s]=await Promise.all([n.findOne({model:"member",where:[{field:"organizationId",value:d},{field:"userId",value:a}]}),i===void 0?void 0:n.findOne({model:"team",where:[{field:"id",value:i},{field:"organizationId",value:d}]}),i===void 0?void 0:n.findOne({model:"teamMember",where:[{field:"teamId",value:i},{field:"userId",value:a}]})]);return m?{...o,orgId:d,...v&&s?{teamId:i}:{}}:o};export{c as identityFromSession,u as resolveSessionIdentity};