@zitadel/astro-auth 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +254 -0
- package/dist/api/[...auth].js +41 -0
- package/dist/api/[...auth].js.map +1 -0
- package/dist/client.d.ts +91 -0
- package/dist/client.js +157 -0
- package/dist/client.js.map +1 -0
- package/dist/components/Auth.astro +38 -0
- package/dist/components/SignIn.astro +133 -0
- package/dist/components/SignOut.astro +99 -0
- package/dist/components/index.d.ts +9 -0
- package/dist/components/index.js +10 -0
- package/dist/components/index.js.map +1 -0
- package/dist/config-lAdfi49m.d.ts +104 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +152 -0
- package/dist/index.js.map +1 -0
- package/dist/server.d.ts +50 -0
- package/dist/server.js +84 -0
- package/dist/server.js.map +1 -0
- package/dist/types-Bvas30QH.d.ts +66 -0
- package/package.json +107 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
# Astro Auth.js
|
|
2
|
+
|
|
3
|
+
An [Astro](https://astro.build/) integration for [Auth.js](https://authjs.dev/)
|
|
4
|
+
that provides seamless authentication with multiple providers, session
|
|
5
|
+
management, and UI primitives that feel natural in Astro.
|
|
6
|
+
|
|
7
|
+
This integration brings the power and flexibility of Auth.js to Astro
|
|
8
|
+
applications with full TypeScript support, SSR-friendly HTTP handling,
|
|
9
|
+
and Astro-native patterns including integrations, endpoints, and components.
|
|
10
|
+
|
|
11
|
+
### Why?
|
|
12
|
+
|
|
13
|
+
Modern web applications require robust, secure, and flexible authentication
|
|
14
|
+
systems. While Auth.js provides excellent authentication capabilities,
|
|
15
|
+
integrating it with Astro applications requires careful consideration of
|
|
16
|
+
framework patterns, server-side rendering, and TypeScript integration.
|
|
17
|
+
|
|
18
|
+
However, a direct integration isn't always straightforward. Different types
|
|
19
|
+
of applications or deployment scenarios might warrant different approaches:
|
|
20
|
+
|
|
21
|
+
- **Framework Integration:** Auth.js operates at the HTTP level, while Astro
|
|
22
|
+
uses integrations, endpoints, and components. A proper integration should bridge this
|
|
23
|
+
gap by providing Astro-native primitives for authentication and authorization
|
|
24
|
+
while maintaining the full Auth.js ecosystem compatibility.
|
|
25
|
+
- **HTTP Request Handling:** Astro’s server output and adapters (Node, Vercel, etc.)
|
|
26
|
+
require clean request handling and route injection. Teams need a unified approach that
|
|
27
|
+
maintains performance while providing seamless Auth.js integration.
|
|
28
|
+
- **Session and Request Lifecycle:** Proper session handling in Astro requires
|
|
29
|
+
SSR-friendly utilities and components that work across server-rendered pages
|
|
30
|
+
and client interactions.
|
|
31
|
+
- **Route Protection & UI:** Many applications need fine-grained authorization
|
|
32
|
+
beyond simple authentication. This calls for cohesive building blocks: server utilities,
|
|
33
|
+
client helpers, and drop-in UI components.
|
|
34
|
+
|
|
35
|
+
This integration, `@zitadel/astro-auth`, aims to provide the flexibility to
|
|
36
|
+
handle such scenarios. It allows you to leverage the full Auth.js ecosystem
|
|
37
|
+
while maintaining Astro best practices, ultimately leading to a more
|
|
38
|
+
effective and less burdensome authentication implementation.
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
Install using NPM by using the following command:
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
npm install @zitadel/astro-auth @auth/core
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Usage
|
|
49
|
+
|
|
50
|
+
To use this integration, add the `@zitadel/astro-auth` integration to your Astro application.
|
|
51
|
+
The integration provides authentication infrastructure with configurable
|
|
52
|
+
endpoints, SSR utilities, and components.
|
|
53
|
+
|
|
54
|
+
You'll need to configure it with your Auth.js providers and options. The
|
|
55
|
+
integration will then be available throughout your application via Astro’s
|
|
56
|
+
integration system.
|
|
57
|
+
|
|
58
|
+
First, add the integration to your Astro config:
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
// astro.config.mjs
|
|
62
|
+
import { defineConfig } from 'astro/config';
|
|
63
|
+
import authAstro from '@zitadel/astro-auth';
|
|
64
|
+
|
|
65
|
+
export default defineConfig({
|
|
66
|
+
output: 'server',
|
|
67
|
+
integrations: [
|
|
68
|
+
authAstro({
|
|
69
|
+
// Optional:
|
|
70
|
+
// prefix: '/api/auth',
|
|
71
|
+
// configFile: './auth.config.ts'
|
|
72
|
+
}),
|
|
73
|
+
],
|
|
74
|
+
});
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
// auth.config.ts
|
|
79
|
+
import { defineConfig } from '@zitadel/astro-auth';
|
|
80
|
+
import Google from '@auth/core/providers/google';
|
|
81
|
+
|
|
82
|
+
export default defineConfig({
|
|
83
|
+
providers: [
|
|
84
|
+
Google({
|
|
85
|
+
clientId: process.env.GOOGLE_CLIENT_ID,
|
|
86
|
+
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
|
|
87
|
+
}),
|
|
88
|
+
],
|
|
89
|
+
secret: process.env.AUTH_SECRET,
|
|
90
|
+
trustHost: true,
|
|
91
|
+
});
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
#### Using the Authentication System
|
|
95
|
+
|
|
96
|
+
The integration provides several functions and hooks for handling
|
|
97
|
+
authentication:
|
|
98
|
+
|
|
99
|
+
**Functions and Hooks:**
|
|
100
|
+
|
|
101
|
+
- `getSession(request, config?)`: Retrieves the current Auth.js session (SSR)
|
|
102
|
+
- `<Auth>`: Render-prop component that provides the current session to children
|
|
103
|
+
- `<SignIn provider="...">`: Drop-in button component for starting sign-in
|
|
104
|
+
- `<SignOut>`: Drop-in button component for signing out
|
|
105
|
+
- `signIn(provider, options?, authParams?)`: Client helper for programmatic sign-in
|
|
106
|
+
- `signOut(options?)`: Client helper for programmatic sign-out
|
|
107
|
+
|
|
108
|
+
**Basic Usage:**
|
|
109
|
+
|
|
110
|
+
```astro
|
|
111
|
+
---
|
|
112
|
+
// src/pages/index.astro
|
|
113
|
+
import { getSession } from '@zitadel/astro-auth/server';
|
|
114
|
+
import type { Session } from '@auth/core/types';
|
|
115
|
+
|
|
116
|
+
const session = await getSession(Astro.request);
|
|
117
|
+
---
|
|
118
|
+
|
|
119
|
+
<html>
|
|
120
|
+
<body>
|
|
121
|
+
{session ? (
|
|
122
|
+
<>
|
|
123
|
+
<p>Welcome {session.user?.name}</p>
|
|
124
|
+
<a href="/api/auth/signout">Sign out</a>
|
|
125
|
+
</>
|
|
126
|
+
) : (
|
|
127
|
+
<a href="/api/auth/signin">Sign in</a>
|
|
128
|
+
)}
|
|
129
|
+
</body>
|
|
130
|
+
</html>
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Prefer using components? Use the built-ins for a richer experience:
|
|
134
|
+
|
|
135
|
+
```astro
|
|
136
|
+
---
|
|
137
|
+
// src/pages/index.astro
|
|
138
|
+
import type { Session } from '@auth/core/types';
|
|
139
|
+
import { Auth, SignIn, SignOut } from '@zitadel/astro-auth/components';
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
<Auth>
|
|
143
|
+
{(session: Session | null) => (
|
|
144
|
+
<>
|
|
145
|
+
{session ? (
|
|
146
|
+
<>
|
|
147
|
+
<SignOut>Sign out</SignOut>
|
|
148
|
+
<p>Logged in as {session.user?.name}</p>
|
|
149
|
+
</>
|
|
150
|
+
) : (
|
|
151
|
+
<SignIn provider="github">Sign in with GitHub</SignIn>
|
|
152
|
+
)}
|
|
153
|
+
</>
|
|
154
|
+
)}
|
|
155
|
+
</Auth>
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Prefer client helpers? Use inline script tags:
|
|
159
|
+
|
|
160
|
+
```html
|
|
161
|
+
---
|
|
162
|
+
---
|
|
163
|
+
|
|
164
|
+
<html>
|
|
165
|
+
<body>
|
|
166
|
+
<button id="login">Login</button>
|
|
167
|
+
<button id="logout">Logout</button>
|
|
168
|
+
|
|
169
|
+
<script>
|
|
170
|
+
const { signIn, signOut } = await import("@zitadel/astro-auth/client");
|
|
171
|
+
document.querySelector("#login").onclick = () => signIn("github");
|
|
172
|
+
document.querySelector("#logout").onclick = () => signOut();
|
|
173
|
+
</script>
|
|
174
|
+
</body>
|
|
175
|
+
</html>
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
##### Example: Advanced Configuration with Multiple Providers
|
|
179
|
+
|
|
180
|
+
This example shows how to use the integration with multiple Auth.js
|
|
181
|
+
providers and custom session configuration:
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
// auth.config.ts
|
|
185
|
+
import { defineConfig } from '@zitadel/astro-auth';
|
|
186
|
+
import Google from '@auth/core/providers/google';
|
|
187
|
+
import GitHub from '@auth/core/providers/github';
|
|
188
|
+
|
|
189
|
+
export default defineConfig({
|
|
190
|
+
providers: [
|
|
191
|
+
Google({
|
|
192
|
+
clientId: process.env.GOOGLE_CLIENT_ID,
|
|
193
|
+
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
|
|
194
|
+
}),
|
|
195
|
+
GitHub({
|
|
196
|
+
clientId: process.env.GITHUB_CLIENT_ID,
|
|
197
|
+
clientSecret: process.env.GITHUB_CLIENT_SECRET,
|
|
198
|
+
}),
|
|
199
|
+
],
|
|
200
|
+
secret: process.env.AUTH_SECRET,
|
|
201
|
+
trustHost: true,
|
|
202
|
+
session: {
|
|
203
|
+
strategy: 'jwt',
|
|
204
|
+
maxAge: 30 * 24 * 60 * 60, // 30 days
|
|
205
|
+
},
|
|
206
|
+
callbacks: {
|
|
207
|
+
async jwt({ token, user }) {
|
|
208
|
+
if (user) (token as any).roles = (user as any).roles;
|
|
209
|
+
return token;
|
|
210
|
+
},
|
|
211
|
+
async session({ session, token }) {
|
|
212
|
+
(session.user as any).roles = (token as any).roles as
|
|
213
|
+
| string[]
|
|
214
|
+
| undefined;
|
|
215
|
+
return session;
|
|
216
|
+
},
|
|
217
|
+
},
|
|
218
|
+
});
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
## Known Issues
|
|
222
|
+
|
|
223
|
+
- **SSR & Adapter Required:** The integration requires Astro’s server output
|
|
224
|
+
with an adapter (e.g., `@astrojs/node`, Vercel, etc.). Ensure `output: 'server'`
|
|
225
|
+
is set and an adapter is configured in `astro.config.mjs`.
|
|
226
|
+
- **Environment Configuration:** The integration relies on `AUTH_SECRET` and,
|
|
227
|
+
in many hosting scenarios, `AUTH_TRUST_HOST`. Ensure these are correctly set
|
|
228
|
+
in your environment for production.
|
|
229
|
+
- **Callback URLs:** OAuth providers must be configured with the correct
|
|
230
|
+
callback URL: `[origin]/api/auth/callback/[provider]` (or your custom `prefix`).
|
|
231
|
+
- **Type Augmentation:** If you attach additional properties (e.g., roles) to
|
|
232
|
+
the Auth.js user object, extend your app’s types accordingly so consumers of
|
|
233
|
+
`session.user` remain type-safe.
|
|
234
|
+
- **Redirect Semantics:** OAuth providers expect real browser navigations during
|
|
235
|
+
sign-in. The client helpers handle this for you—avoid manual `fetch()` calls
|
|
236
|
+
to provider endpoints unless you know you need credential/email flows.
|
|
237
|
+
|
|
238
|
+
## Useful links
|
|
239
|
+
|
|
240
|
+
- **[Auth.js](https://authjs.dev/):** The authentication library that this
|
|
241
|
+
integration is built upon.
|
|
242
|
+
- **[Astro](https://astro.build/):** The framework this integration targets.
|
|
243
|
+
- **[Auth.js Providers](https://authjs.dev/getting-started/providers):**
|
|
244
|
+
Complete list of supported authentication providers.
|
|
245
|
+
|
|
246
|
+
## Contributing
|
|
247
|
+
|
|
248
|
+
If you have suggestions for how this integration could be improved, or
|
|
249
|
+
want to report a bug, open an issue - we'd love all and any
|
|
250
|
+
contributions.
|
|
251
|
+
|
|
252
|
+
## License
|
|
253
|
+
|
|
254
|
+
Apache-2.0
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// src/server.ts
|
|
2
|
+
import { Auth, createActionURL, setEnvDefaults } from "@auth/core";
|
|
3
|
+
import authConfig from "auth:config";
|
|
4
|
+
function AstroAuthHandler(prefix, options = authConfig) {
|
|
5
|
+
const normalizedPrefix = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
|
|
6
|
+
return async ({ request }) => {
|
|
7
|
+
const url = new URL(request.url);
|
|
8
|
+
if (!url.pathname.startsWith(normalizedPrefix + "/")) {
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
return await Auth(request, options);
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
function AstroAuth(options = authConfig) {
|
|
15
|
+
const config = options ?? authConfig;
|
|
16
|
+
if (!config) {
|
|
17
|
+
throw new Error(
|
|
18
|
+
"Auth configuration not found. Please ensure auth.config is properly configured."
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
const { prefix = "/api/auth", ...authOptions } = config;
|
|
22
|
+
const handler = AstroAuthHandler(prefix, authOptions);
|
|
23
|
+
return {
|
|
24
|
+
async GET(context) {
|
|
25
|
+
return await handler(context);
|
|
26
|
+
},
|
|
27
|
+
async POST(context) {
|
|
28
|
+
return await handler(context);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// src/api/[...auth].ts
|
|
34
|
+
var prerender = false;
|
|
35
|
+
var { GET, POST } = AstroAuth();
|
|
36
|
+
export {
|
|
37
|
+
GET,
|
|
38
|
+
POST,
|
|
39
|
+
prerender
|
|
40
|
+
};
|
|
41
|
+
//# sourceMappingURL=[...auth].js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/server.ts","../../src/api/%5B...auth%5D.ts"],"sourcesContent":["/**\n * > **caution**\n * > `astro-auth` is currently experimental. Be aware of breaking changes between versions.\n *\n *\n * Astro Auth is the unofficial Astro integration for Auth.js.\n * It provides a simple way to add authentication to your Astro site in a few lines of code.\n *\n * ## Installation\n *\n * `astro-auth` requires building your site in `server` mode with a platform adaper like `@astrojs/node`.\n * ```js\n * // astro.config.mjs\n * export default defineConfig({\n * output: \"server\",\n * adapter: node({\n * mode: 'standalone'\n * })\n * });\n * ```\n *\n * ```bash npm2yarn2pnpm\n * npm install @auth/core @zitadel/astro-auth\n * ```\n */\nimport { Auth, createActionURL, setEnvDefaults } from '@auth/core';\nimport type { APIContext } from 'astro';\nimport authConfig from 'auth:config';\nimport type { AstroAuthConfig } from './types.js';\nimport type { Session } from '@auth/core/types';\n\nfunction AstroAuthHandler(prefix: string, options = authConfig) {\n const normalizedPrefix = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;\n return async ({ request }: APIContext) => {\n const url = new URL(request.url);\n // Only handle requests that match our prefix path\n // Non-matching paths return undefined because this handler is mounted as [...auth]\n if (!url.pathname.startsWith(normalizedPrefix + '/')) {\n return;\n }\n\n return await Auth(request, options);\n };\n}\n\n/**\n * Creates a set of Astro endpoints for authentication.\n *\n * @param options - The configuration for authentication providers and other options.\n * @returns An object with `GET` and `POST` methods that can be exported in an Astro endpoint.\n * @throws {Error} When auth configuration is not found or not properly configured.\n *\n * @example\n * ```ts\n * export const { GET, POST } = AstroAuth({\n * providers: [\n * GitHub({\n * clientId: process.env.GITHUB_ID!,\n * clientSecret: process.env.GITHUB_SECRET!,\n * }),\n * ],\n * debug: false,\n * })\n * ```\n */\nexport function AstroAuth(options = authConfig) {\n const config = options ?? authConfig;\n if (!config) {\n throw new Error(\n 'Auth configuration not found. Please ensure auth.config is properly configured.',\n );\n }\n const { prefix = '/api/auth', ...authOptions } = config;\n\n const handler = AstroAuthHandler(prefix, authOptions);\n return {\n async GET(context: APIContext) {\n return await handler(context);\n },\n async POST(context: APIContext) {\n return await handler(context);\n },\n };\n}\n\n/**\n * Retrieves the current session for a Request.\n *\n * This function extracts session information from the request cookies and\n * validates it against the Auth.js configuration. It returns the session\n * object if valid or null if no valid session exists.\n *\n * @param req - The Request object\n * @param config - The authentication configuration\n * @returns Promise resolving to session data or null\n * @throws {Error} When session validation fails or Auth.js returns an error\n *\n * @example\n * ```ts\n * const session = await getSession(request, authConfig)\n * if (!session) throw new Error (\"Not authenticated\")\n * ```\n */\nexport async function getSession(\n req: Request,\n config: AstroAuthConfig,\n): Promise<Session | null> {\n setEnvDefaults(process.env, config);\n const url = createActionURL(\n 'session',\n new URL(req.url).protocol.replace(':', ''),\n new Headers(req.headers),\n process.env,\n config,\n );\n const headers = new Headers(req.headers);\n const response = await Auth(\n new Request(url, {\n headers,\n }),\n config,\n );\n const status = response.status ?? 200;\n const data = await response.json();\n if (!data || !Object.keys(data).length) {\n return null;\n } else {\n const astroGlobal = globalThis as unknown as {\n Astro?: { response?: { headers?: Headers } };\n };\n const target =\n astroGlobal.Astro && astroGlobal.Astro.response\n ? astroGlobal.Astro.response.headers\n : undefined;\n if (target) {\n const h = response.headers as unknown as {\n getSetCookie?: () => string[];\n };\n if (h && typeof h.getSetCookie === 'function') {\n const cookies = h.getSetCookie();\n if (Array.isArray(cookies)) {\n for (const c of cookies) {\n target.append('Set-Cookie', c);\n }\n }\n } else {\n const single = response.headers.get('set-cookie');\n if (single) {\n target.append('Set-Cookie', single);\n }\n }\n }\n if (status === 200) {\n return data as Session;\n } else {\n throw new Error(\n `[astro-auth] getSession failed: ${status} ${JSON.stringify(data)}`,\n );\n }\n }\n}\n","/* istanbul ignore file */\nimport { AstroAuth } from '../server.js';\n\n// noinspection JSUnusedGlobalSymbols\nexport const prerender = false;\n\nexport const { GET, POST } = AstroAuth();\n"],"mappings":";AAyBA,SAAS,MAAM,iBAAiB,sBAAsB;AAEtD,OAAO,gBAAgB;AAIvB,SAAS,iBAAiB,QAAgB,UAAU,YAAY;AAC9D,QAAM,mBAAmB,OAAO,SAAS,GAAG,IAAI,OAAO,MAAM,GAAG,EAAE,IAAI;AACtE,SAAO,OAAO,EAAE,QAAQ,MAAkB;AACxC,UAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;AAG/B,QAAI,CAAC,IAAI,SAAS,WAAW,mBAAmB,GAAG,GAAG;AACpD;AAAA,IACF;AAEA,WAAO,MAAM,KAAK,SAAS,OAAO;AAAA,EACpC;AACF;AAsBO,SAAS,UAAU,UAAU,YAAY;AAC9C,QAAM,SAAS,WAAW;AAC1B,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,QAAM,EAAE,SAAS,aAAa,GAAG,YAAY,IAAI;AAEjD,QAAM,UAAU,iBAAiB,QAAQ,WAAW;AACpD,SAAO;AAAA,IACL,MAAM,IAAI,SAAqB;AAC7B,aAAO,MAAM,QAAQ,OAAO;AAAA,IAC9B;AAAA,IACA,MAAM,KAAK,SAAqB;AAC9B,aAAO,MAAM,QAAQ,OAAO;AAAA,IAC9B;AAAA,EACF;AACF;;;AC/EO,IAAM,YAAY;AAElB,IAAM,EAAE,KAAK,KAAK,IAAI,UAAU;","names":[]}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { L as LiteralUnion, A as AstroSignInOptions, S as SignInAuthorizationParams, a as AstroSignOutParams } from './types-Bvas30QH.js';
|
|
2
|
+
import '@auth/core/types';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Initiates a sign-in flow with the specified authentication provider.
|
|
6
|
+
*
|
|
7
|
+
* This function handles authentication for different provider types using
|
|
8
|
+
* the appropriate mechanism for each. OAuth providers require browser form
|
|
9
|
+
* submission to properly handle redirect chains, while credential-based
|
|
10
|
+
* providers can use fetch for JSON responses.
|
|
11
|
+
*
|
|
12
|
+
* @typeParam P - The provider identifier type for type-safe provider names
|
|
13
|
+
* @param providerId - The authentication provider identifier (e.g., 'github',
|
|
14
|
+
* 'google', 'credentials')
|
|
15
|
+
* @param options - Configuration options for the sign-in flow
|
|
16
|
+
* @param authorizationParams - Additional OAuth authorization parameters to
|
|
17
|
+
* pass to the provider
|
|
18
|
+
* @returns Promise that resolves to Response for credential providers when
|
|
19
|
+
* redirect is false and an error occurs, otherwise void
|
|
20
|
+
*
|
|
21
|
+
* @remarks
|
|
22
|
+
* **Why Different Mechanisms for Different Providers:**
|
|
23
|
+
*
|
|
24
|
+
* OAuth Providers (github, google, etc.):
|
|
25
|
+
* - Auth.js responds with a 302 redirect to the OAuth provider's login page
|
|
26
|
+
* - Using `fetch()` causes the browser to follow redirects in JS context
|
|
27
|
+
* - The OAuth provider expects a real browser navigation, not XHR
|
|
28
|
+
* - Result: fetch completes but no visible navigation occurs
|
|
29
|
+
* - Solution: Use real form submission to let browser handle redirects
|
|
30
|
+
*
|
|
31
|
+
* Credential/Email Providers:
|
|
32
|
+
* - Auth.js responds with JSON containing success/error information
|
|
33
|
+
* - These providers need to return Response objects for error handling
|
|
34
|
+
* - Using `fetch()` allows access to response data and conditional redirects
|
|
35
|
+
* - Result: Can detect errors and optionally suppress redirect
|
|
36
|
+
* - Solution: Use fetch with JSON response handling
|
|
37
|
+
*
|
|
38
|
+
* **Security Considerations:**
|
|
39
|
+
* - All requests include CSRF token protection
|
|
40
|
+
* - Callback URLs are normalized to prevent open redirect attacks
|
|
41
|
+
* - Only same-origin URLs are allowed for redirects
|
|
42
|
+
*
|
|
43
|
+
* **Browser Compatibility:**
|
|
44
|
+
* - Form submission approach works in all browsers including those that
|
|
45
|
+
* restrict fetch() behavior for cross-origin redirects
|
|
46
|
+
* - Hash-based navigation triggers explicit reload for proper routing
|
|
47
|
+
*
|
|
48
|
+
* @example OAuth Provider Sign-In
|
|
49
|
+
* ```ts
|
|
50
|
+
* // Triggers form submission and browser navigation to GitHub
|
|
51
|
+
* await signIn('github')
|
|
52
|
+
* ```
|
|
53
|
+
*
|
|
54
|
+
* @example OAuth with Custom Callback
|
|
55
|
+
* ```ts
|
|
56
|
+
* await signIn('google', {
|
|
57
|
+
* callbackUrl: '/dashboard'
|
|
58
|
+
* })
|
|
59
|
+
* ```
|
|
60
|
+
*
|
|
61
|
+
* @example OAuth with Authorization Parameters
|
|
62
|
+
* ```ts
|
|
63
|
+
* await signIn('google', undefined, {
|
|
64
|
+
* prompt: 'consent',
|
|
65
|
+
* login_hint: 'user@example.com'
|
|
66
|
+
* })
|
|
67
|
+
* ```
|
|
68
|
+
*
|
|
69
|
+
* @example Credential Provider with Error Handling
|
|
70
|
+
* ```ts
|
|
71
|
+
* const response = await signIn('credentials', {
|
|
72
|
+
* redirect: false
|
|
73
|
+
* }, {
|
|
74
|
+
* username: 'user',
|
|
75
|
+
* password: 'pass'
|
|
76
|
+
* })
|
|
77
|
+
*
|
|
78
|
+
* if (response) {
|
|
79
|
+
* const data = await response.json()
|
|
80
|
+
* if (data.error) {
|
|
81
|
+
* console.error('Sign in failed:', data.error)
|
|
82
|
+
* }
|
|
83
|
+
* }
|
|
84
|
+
* ```
|
|
85
|
+
*
|
|
86
|
+
* @public
|
|
87
|
+
*/
|
|
88
|
+
declare function signIn<P extends string | undefined = undefined>(providerId?: LiteralUnion<P extends string ? P | string : string>, options?: AstroSignInOptions, authorizationParams?: SignInAuthorizationParams): Promise<Response | void>;
|
|
89
|
+
declare function signOut(options?: AstroSignOutParams): Promise<void>;
|
|
90
|
+
|
|
91
|
+
export { signIn, signOut };
|