@auth/qwik 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6GG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AAE5C,OAAO,EAAc,OAAO,EAAE,MAAM,kBAAkB,CAAA;AAEtD,OAAO,EAGL,CAAC,EAED,KAAK,kBAAkB,EACxB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,SAAS,EAAE,MAAM,kDAAkD,CAAA;AAI5E,8CAA8C;AAC9C,MAAM,WAAW,cAAe,SAAQ,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC;CAAG;AAElE,MAAM,MAAM,gBAAgB,GAAG,OAAO,CAAC;IAAE,IAAI,EAAE,OAAO,GAAG,IAAI,CAAC;IAAC,MAAM,EAAE,GAAG,CAAA;CAAE,CAAC,CAAA;AA2G7E;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,SAAS,eArHE,kBAAkB,KAAK,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAuE7B,kBAAkB;CA8CmB,CAAA;AAmFrE,eAAO,MAAM,cAAc,QAAS,SAAS,UAAU,UAAU,SAwChE,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6GG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AAE5C,OAAO,EAAc,OAAO,EAAE,MAAM,kBAAkB,CAAA;AAEtD,OAAO,EAGL,CAAC,EAED,KAAK,kBAAkB,EACxB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,SAAS,EAAE,MAAM,kDAAkD,CAAA;AAI5E,8CAA8C;AAC9C,MAAM,WAAW,cAAe,SAAQ,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC;CAAG;AAElE,MAAM,MAAM,gBAAgB,GAAG,OAAO,CAAC;IAAE,IAAI,EAAE,OAAO,GAAG,IAAI,CAAC;IAAC,MAAM,EAAE,GAAG,CAAA;CAAE,CAAC,CAAA;AA4G7E;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,SAAS,eArHE,kBAAkB,KAAK,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAuE7B,kBAAkB;CA8CmB,CAAA;AAmFrE,eAAO,MAAM,cAAc,QAAS,SAAS,UAAU,UAAU,SAwChE,CAAA"}
package/index.qwik.js ADDED
@@ -0,0 +1,353 @@
1
+ import { globalActionQrl, zodQrl, z, routeLoaderQrl } from "@builder.io/qwik-city";
2
+ import { inlinedQrl, useLexicalScope, implicit$FirstArg } from "@builder.io/qwik";
3
+ import { Auth, skipCSRFCheck, isAuthAction } from "@auth/core";
4
+ import { isServer } from "@builder.io/qwik/build";
5
+ var setCookie = { exports: {} };
6
+ var defaultParseOptions = {
7
+ decodeValues: true,
8
+ map: false,
9
+ silent: false
10
+ };
11
+ function isNonEmptyString(str) {
12
+ return typeof str === "string" && !!str.trim();
13
+ }
14
+ function parseString(setCookieValue, options) {
15
+ var parts = setCookieValue.split(";").filter(isNonEmptyString);
16
+ var nameValuePairStr = parts.shift();
17
+ var parsed = parseNameValuePair(nameValuePairStr);
18
+ var name = parsed.name;
19
+ var value = parsed.value;
20
+ options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;
21
+ try {
22
+ value = options.decodeValues ? decodeURIComponent(value) : value;
23
+ } catch (e) {
24
+ console.error(
25
+ "set-cookie-parser encountered an error while decoding a cookie with value '" + value + "'. Set options.decodeValues to false to disable this feature.",
26
+ e
27
+ );
28
+ }
29
+ var cookie = {
30
+ name,
31
+ value
32
+ };
33
+ parts.forEach(function(part) {
34
+ var sides = part.split("=");
35
+ var key = sides.shift().trimLeft().toLowerCase();
36
+ var value2 = sides.join("=");
37
+ if (key === "expires") {
38
+ cookie.expires = new Date(value2);
39
+ } else if (key === "max-age") {
40
+ cookie.maxAge = parseInt(value2, 10);
41
+ } else if (key === "secure") {
42
+ cookie.secure = true;
43
+ } else if (key === "httponly") {
44
+ cookie.httpOnly = true;
45
+ } else if (key === "samesite") {
46
+ cookie.sameSite = value2;
47
+ } else {
48
+ cookie[key] = value2;
49
+ }
50
+ });
51
+ return cookie;
52
+ }
53
+ function parseNameValuePair(nameValuePairStr) {
54
+ var name = "";
55
+ var value = "";
56
+ var nameValueArr = nameValuePairStr.split("=");
57
+ if (nameValueArr.length > 1) {
58
+ name = nameValueArr.shift();
59
+ value = nameValueArr.join("=");
60
+ } else {
61
+ value = nameValuePairStr;
62
+ }
63
+ return { name, value };
64
+ }
65
+ function parse(input, options) {
66
+ options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;
67
+ if (!input) {
68
+ if (!options.map) {
69
+ return [];
70
+ } else {
71
+ return {};
72
+ }
73
+ }
74
+ if (input.headers) {
75
+ if (typeof input.headers.getSetCookie === "function") {
76
+ input = input.headers.getSetCookie();
77
+ } else if (input.headers["set-cookie"]) {
78
+ input = input.headers["set-cookie"];
79
+ } else {
80
+ var sch = input.headers[Object.keys(input.headers).find(function(key) {
81
+ return key.toLowerCase() === "set-cookie";
82
+ })];
83
+ if (!sch && input.headers.cookie && !options.silent) {
84
+ console.warn(
85
+ "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
86
+ );
87
+ }
88
+ input = sch;
89
+ }
90
+ }
91
+ if (!Array.isArray(input)) {
92
+ input = [input];
93
+ }
94
+ options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions;
95
+ if (!options.map) {
96
+ return input.filter(isNonEmptyString).map(function(str) {
97
+ return parseString(str, options);
98
+ });
99
+ } else {
100
+ var cookies = {};
101
+ return input.filter(isNonEmptyString).reduce(function(cookies2, str) {
102
+ var cookie = parseString(str, options);
103
+ cookies2[cookie.name] = cookie;
104
+ return cookies2;
105
+ }, cookies);
106
+ }
107
+ }
108
+ function splitCookiesString(cookiesString) {
109
+ if (Array.isArray(cookiesString)) {
110
+ return cookiesString;
111
+ }
112
+ if (typeof cookiesString !== "string") {
113
+ return [];
114
+ }
115
+ var cookiesStrings = [];
116
+ var pos = 0;
117
+ var start;
118
+ var ch;
119
+ var lastComma;
120
+ var nextStart;
121
+ var cookiesSeparatorFound;
122
+ function skipWhitespace() {
123
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
124
+ pos += 1;
125
+ }
126
+ return pos < cookiesString.length;
127
+ }
128
+ function notSpecialChar() {
129
+ ch = cookiesString.charAt(pos);
130
+ return ch !== "=" && ch !== ";" && ch !== ",";
131
+ }
132
+ while (pos < cookiesString.length) {
133
+ start = pos;
134
+ cookiesSeparatorFound = false;
135
+ while (skipWhitespace()) {
136
+ ch = cookiesString.charAt(pos);
137
+ if (ch === ",") {
138
+ lastComma = pos;
139
+ pos += 1;
140
+ skipWhitespace();
141
+ nextStart = pos;
142
+ while (pos < cookiesString.length && notSpecialChar()) {
143
+ pos += 1;
144
+ }
145
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
146
+ cookiesSeparatorFound = true;
147
+ pos = nextStart;
148
+ cookiesStrings.push(cookiesString.substring(start, lastComma));
149
+ start = pos;
150
+ } else {
151
+ pos = lastComma + 1;
152
+ }
153
+ } else {
154
+ pos += 1;
155
+ }
156
+ }
157
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) {
158
+ cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
159
+ }
160
+ }
161
+ return cookiesStrings;
162
+ }
163
+ setCookie.exports = parse;
164
+ setCookie.exports.parse = parse;
165
+ var parseString_1 = setCookie.exports.parseString = parseString;
166
+ var splitCookiesString_1 = setCookie.exports.splitCookiesString = splitCookiesString;
167
+ function QwikAuthQrl(authOptions) {
168
+ const useSignIn = globalActionQrl(/* @__PURE__ */ inlinedQrl(async ({ providerId, redirectTo: _redirectTo, options, authorizationParams }, req) => {
169
+ const [authOptions2] = useLexicalScope();
170
+ const { redirectTo = _redirectTo ?? defaultRedirectTo(req), ...rest } = options ?? {};
171
+ const isCredentials = providerId === "credentials";
172
+ const authOpts = await authOptions2(req);
173
+ setEnvDefaults(req.env, authOpts);
174
+ const body = new URLSearchParams({
175
+ redirectTo
176
+ });
177
+ Object.entries(rest).forEach(([key, value]) => {
178
+ body.set(key, String(value));
179
+ });
180
+ const baseSignInUrl = `/auth/${isCredentials ? "callback" : "signin"}${providerId ? `/${providerId}` : ""}`;
181
+ const signInUrl = `${baseSignInUrl}?${new URLSearchParams(authorizationParams)}`;
182
+ const data = await authAction(body, req, signInUrl, authOpts);
183
+ req.cookie.set("authjs.callback-url", redirectTo, {
184
+ path: "/"
185
+ });
186
+ if (data.url)
187
+ throw req.redirect(301, data.url);
188
+ }, "QwikAuthQrl_useSignIn_globalAction_xjVnyrcqS90", [
189
+ authOptions
190
+ ]), zodQrl(/* @__PURE__ */ inlinedQrl({
191
+ providerId: z.string().optional(),
192
+ /** Yoooo */
193
+ redirectTo: z.string().optional(),
194
+ options: z.object({
195
+ redirectTo: z.string()
196
+ }).passthrough().partial().optional(),
197
+ authorizationParams: z.union([
198
+ z.string(),
199
+ z.custom(),
200
+ z.record(z.string())
201
+ ]).optional()
202
+ }, "QwikAuthQrl_useSignIn_globalAction_zod_X0EcrMISJRM")));
203
+ const useSignOut = globalActionQrl(/* @__PURE__ */ inlinedQrl(async ({ redirectTo }, req) => {
204
+ const [authOptions2] = useLexicalScope();
205
+ redirectTo ?? (redirectTo = defaultRedirectTo(req));
206
+ const authOpts = await authOptions2(req);
207
+ setEnvDefaults(req.env, authOpts);
208
+ const body = new URLSearchParams({
209
+ redirectTo
210
+ });
211
+ await authAction(body, req, `/auth/signout`, authOpts);
212
+ }, "QwikAuthQrl_useSignOut_globalAction_ah1IDwV91Ag", [
213
+ authOptions
214
+ ]), zodQrl(/* @__PURE__ */ inlinedQrl({
215
+ redirectTo: z.string().optional()
216
+ }, "QwikAuthQrl_useSignOut_globalAction_zod_R188QAWPJFs")));
217
+ const useSession = routeLoaderQrl(/* @__PURE__ */ inlinedQrl((req) => {
218
+ return req.sharedMap.get("session");
219
+ }, "QwikAuthQrl_useSession_routeLoader_4AFWl3chA98"));
220
+ const onRequest = async (req) => {
221
+ if (isServer) {
222
+ const prefix = "/auth";
223
+ const action = req.url.pathname.slice(prefix.length + 1).split("/")[0];
224
+ const authOpts = await authOptions(req);
225
+ setEnvDefaults(req.env, authOpts);
226
+ if (isAuthAction(action) && req.url.pathname.startsWith(prefix + "/")) {
227
+ const res = await Auth(req.request, authOpts);
228
+ const cookie = res.headers.get("set-cookie");
229
+ if (cookie) {
230
+ req.headers.set("set-cookie", cookie);
231
+ res.headers.delete("set-cookie");
232
+ fixCookies(req);
233
+ }
234
+ throw req.send(res);
235
+ } else {
236
+ const { data, cookie } = await getSessionData(req.request, authOpts);
237
+ req.sharedMap.set("session", data);
238
+ if (cookie) {
239
+ req.headers.set("set-cookie", cookie);
240
+ fixCookies(req);
241
+ }
242
+ }
243
+ }
244
+ };
245
+ return {
246
+ useSignIn,
247
+ useSignOut,
248
+ useSession,
249
+ onRequest
250
+ };
251
+ }
252
+ const QwikAuth$ = /* @__PURE__ */ implicit$FirstArg(QwikAuthQrl);
253
+ async function authAction(body, req, path, authOptions) {
254
+ const request = new Request(new URL(path, req.request.url), {
255
+ method: req.request.method,
256
+ headers: req.request.headers,
257
+ body
258
+ });
259
+ request.headers.set("content-type", "application/x-www-form-urlencoded");
260
+ const res = await Auth(request, authOptions);
261
+ const cookies = [];
262
+ res.headers.forEach((value, key) => {
263
+ if (key === "set-cookie")
264
+ cookies.push(value);
265
+ else if (!req.headers.has(key))
266
+ req.headers.set(key, value);
267
+ });
268
+ if (cookies.length > 0)
269
+ req.headers.set("set-cookie", cookies.join(", "));
270
+ fixCookies(req);
271
+ try {
272
+ return await res.json();
273
+ } catch (error) {
274
+ return await res.text();
275
+ }
276
+ }
277
+ const fixCookies = (req) => {
278
+ req.headers.set("set-cookie", req.headers.get("set-cookie") || "");
279
+ const cookie = req.headers.get("set-cookie");
280
+ if (cookie) {
281
+ req.headers.delete("set-cookie");
282
+ splitCookiesString_1(cookie).forEach((cookie2) => {
283
+ const { name, value, ...rest } = parseString_1(cookie2);
284
+ req.cookie.set(name, value, rest);
285
+ });
286
+ }
287
+ };
288
+ const defaultRedirectTo = (req) => {
289
+ req.url.searchParams.delete("qaction");
290
+ return req.url.href;
291
+ };
292
+ async function getSessionData(req, options) {
293
+ options.secret ?? (options.secret = process.env.AUTH_SECRET);
294
+ options.trustHost ?? (options.trustHost = true);
295
+ const url = new URL("/auth/session", req.url);
296
+ const response = await Auth(new Request(url, {
297
+ headers: req.headers
298
+ }), options);
299
+ const { status = 200 } = response;
300
+ const data = await response.json();
301
+ const cookie = response.headers.get("set-cookie");
302
+ if (!data || !Object.keys(data).length)
303
+ return {
304
+ data: null,
305
+ cookie
306
+ };
307
+ if (status === 200)
308
+ return {
309
+ data,
310
+ cookie
311
+ };
312
+ throw new Error(data.message);
313
+ }
314
+ const setEnvDefaults = (env, config) => {
315
+ config.basePath = "/auth";
316
+ if (!config.secret?.length) {
317
+ config.secret = [];
318
+ const secret = env.get("AUTH_SECRET");
319
+ if (secret)
320
+ config.secret.push(secret);
321
+ for (const i of [
322
+ 1,
323
+ 2,
324
+ 3
325
+ ]) {
326
+ const secret2 = env.get(`AUTH_SECRET_${i}`);
327
+ if (secret2)
328
+ config.secret.unshift(secret2);
329
+ }
330
+ }
331
+ config.redirectProxyUrl ?? (config.redirectProxyUrl = env.get("AUTH_REDIRECT_PROXY_URL"));
332
+ config.trustHost ?? (config.trustHost = !!(env.get("AUTH_URL") ?? env.get("AUTH_TRUST_HOST") ?? env.get("VERCEL") ?? env.get("CF_PAGES") ?? env.get("NODE_ENV") !== "production"));
333
+ config.skipCSRFCheck = skipCSRFCheck;
334
+ config.providers = config.providers.map((p) => {
335
+ const finalProvider = typeof p === "function" ? p({}) : p;
336
+ const ID = finalProvider.id.toUpperCase().replace(/-/g, "_");
337
+ if (finalProvider.type === "oauth" || finalProvider.type === "oidc") {
338
+ finalProvider.clientId ?? (finalProvider.clientId = env.get(`AUTH_${ID}_ID`));
339
+ finalProvider.clientSecret ?? (finalProvider.clientSecret = env.get(`AUTH_${ID}_SECRET`));
340
+ if (finalProvider.type === "oidc")
341
+ finalProvider.issuer ?? (finalProvider.issuer = env.get(`AUTH_${ID}_ISSUER`));
342
+ } else if (finalProvider.type === "email")
343
+ finalProvider.apiKey ?? (finalProvider.apiKey = env.get(`AUTH_${ID}_KEY`));
344
+ return finalProvider;
345
+ });
346
+ };
347
+ export {
348
+ QwikAuth$,
349
+ QwikAuthQrl,
350
+ authAction as _auto_authAction,
351
+ defaultRedirectTo as _auto_defaultRedirectTo,
352
+ setEnvDefaults
353
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@auth/qwik",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Authentication for Qwik.",
5
5
  "license": "ISC",
6
6
  "author": "gioboa <giorgiob.boa@gmail.com>",
@@ -36,12 +36,11 @@
36
36
  "import": "./providers/*.js"
37
37
  }
38
38
  },
39
- "qwik": "./index.qwik.mjs",
39
+ "qwik": "./index.qwik.js",
40
40
  "files": [
41
41
  "*.d.ts*",
42
42
  "*.js",
43
- "*.mjs",
44
- "*.qwik.mjs",
43
+ "*.qwik.js",
45
44
  "providers",
46
45
  "src"
47
46
  ],
package/src/index.ts CHANGED
@@ -129,7 +129,8 @@ export interface QwikAuthConfig extends Omit<AuthConfig, "raw"> {}
129
129
 
130
130
  export type GetSessionResult = Promise<{ data: Session | null; cookie: any }>
131
131
 
132
- function qwikAuthQrl(
132
+ /** @internal */
133
+ export function QwikAuthQrl(
133
134
  authOptions: QRL<(ev: RequestEventCommon) => QwikAuthConfig>
134
135
  ) {
135
136
  const useSignIn = globalAction$(
@@ -247,7 +248,7 @@ function qwikAuthQrl(
247
248
  * } = QwikAuth$(() => ({ providers: [GitHub] }))
248
249
  * ```
249
250
  */
250
- export const QwikAuth$ = /*#__PURE__*/ implicit$FirstArg(qwikAuthQrl)
251
+ export const QwikAuth$ = /*#__PURE__*/ implicit$FirstArg(QwikAuthQrl)
251
252
 
252
253
  async function authAction(
253
254
  body: URLSearchParams | undefined,